diff --git a/.classpath b/.classpath index 6aed2ebfb..d57ec0251 100644 --- a/.classpath +++ b/.classpath @@ -1,8 +1,9 @@ - - + + + diff --git a/.gitignore b/.gitignore index 193211df4..04b103fc1 100644 --- a/.gitignore +++ b/.gitignore @@ -1,13 +1,33 @@ +# System: +Thumbs.db +.DS_Store +*.swp +*~ +Desktop.ini + +# Version Control Systems: +.svn +CVS +.hg +.bzr + +# Android: +local.properties +proguard/** target/** bin/** +obj/** doc/** gen/** -.DS_Store -Thumbs.db gdb.setup gdbserver -.svn -.hg -local.properties + +# Eclipse: .settings -AndEngine.iml \ No newline at end of file + +# IntelliJ / Android Studio: +idea/workspace.xml +idea/tasks.xml + +# Crashlytics +res/values/com_crashlytics_export_strings.xml \ No newline at end of file diff --git a/AUTHORS.md b/AUTHORS.md index 04786c3a5..391264692 100644 --- a/AUTHORS.md +++ b/AUTHORS.md @@ -45,6 +45,8 @@ * Daniel Epstein * Added possibility to define scaleX/scaleY instead of just scale. * Fixed horizontal/vertical flipping of BaseTextureRegionBuffer. +* Arturo GutiƩrrez + * Added TextureMemoryLogger. ## Suggestions / Issue-Reports: * Leandro De Brasi diff --git a/AndroidManifest.xml b/AndroidManifest.xml index f206a68bf..c6cad6ff4 100644 --- a/AndroidManifest.xml +++ b/AndroidManifest.xml @@ -4,7 +4,7 @@ android:versionCode="1" android:versionName="1.0"> - + - + \ No newline at end of file diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 000000000..35cfa48aa --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,176 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS \ No newline at end of file diff --git a/README.md b/README.md index 128c9ef57..f886e7e46 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,29 @@ # AndEngine +## Donations +While developing AndEngine was a lot of fun, it also also consumed many(!) months of my life. It actually continues to cost me a significant amount of money to host the AndEngine forums. + +If you made profit using your game and can afford to spare a fraction of it to the developer of the game engine you used, I would be very grateful! =) + +### Bitcoin +The easiest way of donating is via Bitcoin to the AndEngine funds wallet address: + +![Bitcoin](http://www.andengine.org/donate/bitcoin_16x16.png "Donate via Bitcoin") +Bitcoin Wallet Address: ``1run6zViD16j2rP9evpayu8FqQ6mcRDqi`` ![Bitcoin Wallet](http://www.andengine.org/donate/bitcoin_wallet.png "Bitcoin Wallet") + +### Tip4Commit (Bitcoin) +Tip the author (not the project itself) of the next commit to AndEngine: + +[![Bitcoin top for next commit](http://tip4commit.com/projects/192.svg)](http://tip4commit.com/projects/192) + +### PayPal +Donation Email: donate@andengine.org + + +Thank you! + +/Nicolas Gramlich + ## Building ### Eclipse @@ -47,7 +71,7 @@ public final class BuildConfig { * [`AndEngineScriptingExtension`][URI_AndEngineScriptingExtension] * [`AndEngineScriptingExtensionGenerator`][URI_AndEngineScriptingExtensionGenerator] * [`AndEngineSVGTextureRegionExtension`][URI_AndEngineSVGTextureRegionExtension] - * [`AndEngineTexturePackerExtension`][URI_AndEngineTexturePackerExtension] + * [`AndEngineTexturePackerExtension`][URI_AndEngineTexturePackerExtension] (Merged into the 'GLES2-AnchorCenter' branch.) * [`AndEngineTMXTiledMapExtension`][URI_AndEngineTMXTiledMapExtension] (Merged into the 'GLES1' branch.) @@ -66,4 +90,4 @@ public final class BuildConfig { [URI_AndEngineScriptingExtensionGenerator]: https://github.com/nicolasgramlich/AndEngineScriptingExtensionGenerator [URI_AndEngineSVGTextureRegionExtension]: https://github.com/nicolasgramlich/AndEngineSVGTextureRegionExtension [URI_AndEngineTexturePackerExtension]: https://github.com/nicolasgramlich/AndEngineTexturePackerExtension -[URI_AndEngineTMXTiledMapExtension]: https://github.com/nicolasgramlich/AndEngineTMXTiledMapExtension \ No newline at end of file +[URI_AndEngineTMXTiledMapExtension]: https://github.com/nicolasgramlich/AndEngineTMXTiledMapExtension diff --git a/build.xml b/build.xml index e30400456..d5f276687 100644 --- a/build.xml +++ b/build.xml @@ -1,85 +1,76 @@ - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - /* 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} */ - + + + + + ---> - - - + + + + + diff --git a/checkstyle.xml b/checkstyle.xml new file mode 100644 index 000000000..11f50a92b --- /dev/null +++ b/checkstyle.xml @@ -0,0 +1,70 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ext/img/badge_xlarge.png b/ext/img/badge_xlarge.png new file mode 100644 index 000000000..733dd573a Binary files /dev/null and b/ext/img/badge_xlarge.png differ diff --git a/ext/libs/ant-contrib-1.0b3.jar b/ext/libs/ant-contrib-1.0b3.jar new file mode 100644 index 000000000..062537661 Binary files /dev/null and b/ext/libs/ant-contrib-1.0b3.jar differ diff --git a/git-rank-contributors.rb b/git-rank-contributors.rb new file mode 100755 index 000000000..de1b612e6 --- /dev/null +++ b/git-rank-contributors.rb @@ -0,0 +1,60 @@ +#!/usr/bin/env ruby + +## git-rank-contributors: a simple script to trace through the logs and +## rank contributors by the total size of the diffs they're responsible for. +## A change counts twice as much as a plain addition or deletion. +## +## Output may or may not be suitable for inclusion in a CREDITS file. +## Probably not without some editing, because people often commit from more +## than one address. +## +## git-rank-contributors Copyright 2008 William Morgan . +## This program is free software: you can redistribute it and/or modify +## it under the terms of the GNU General Public License as published by +## the Free Software Foundation, either version 3 of the License, or (at +## your option) any later version. +## +## This program is distributed in the hope that it will be useful, +## but WITHOUT ANY WARRANTY; without even the implied warranty of +## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +## GNU General Public License for more details. +## +## You can find the GNU General Public License at: +## http://www.gnu.org/licenses/ + +class String + def obfuscate; gsub(/@/, " at the ").gsub(/\.(\w+)(>|$)/, ' dot \1s\2') end + def htmlize; gsub("&", "&").gsub("<", "<").gsub(">", ">") end +end + +lines = {} +verbose = ARGV.delete("-v") +obfuscate = ARGV.delete("-o") +htmlize = ARGV.delete("-h") + +author = nil +state = :pre_author +`git log -M -C -C -p --no-color`.each do |l| + case + when (state == :pre_author || state == :post_author) && l =~ /Author: (.*)$/ + author = $1 + state = :post_author + lines[author] ||= 0 + when state == :post_author && l =~ /^\+\+\+/ + state = :in_diff + when state == :in_diff && l =~ /^[\+\-]/ + lines[author] += 1 + when state == :in_diff && l =~ /^commit / + state = :pre_author + end +end + +lines.sort_by { |a, c| -c }.each do |a, c| + a = a.obfuscate if obfuscate + a = a.htmlize if htmlize + if verbose + puts "#{a}: #{c} lines of diff" + else + puts a + end +end \ No newline at end of file diff --git a/jni/Application.mk b/jni/Application.mk index f47b6ee8a..1716886f7 100644 --- a/jni/Application.mk +++ b/jni/Application.mk @@ -1,3 +1,3 @@ -# Build both ARMv5TE and ARMv7-A and x86 machine code. -APP_ABI := armeabi armeabi-v7a x86 -APP_STL := gnustl_shared \ No newline at end of file +# Build ARMv5TE, ARMv7-A, x86 and MIPS machine code. +APP_ABI := armeabi armeabi-v7a x86 mips +# APP_STL := gnustl_shared \ No newline at end of file diff --git a/jni/build.sh b/jni/build.sh index 91790b1ba..f371ec5f2 100755 --- a/jni/build.sh +++ b/jni/build.sh @@ -1,15 +1,18 @@ #!/bin/bash -NDK_DIRECTORY="/Users/ngramlich/SDKs/Android/ndk/r7b/" -PROJECT_DIRECTORY="/Users/ngramlich/Workspace/gdk/graphic_engines/AndEngine/AndEngine/" +NDK_DIRECTORY="/Users/ngramlich/Applications/android/ndk/r8e/" + +SCRIPT_DIR="$( cd "$( dirname "${0}" )" && pwd )" + +PROJECT_DIRECTORY=${SCRIPT_DIR}/../ # Run build: -pushd ${PROJECT_DIRECTORY} -${NDK_DIRECTORY}ndk-build +pushd ${PROJECT_DIRECTORY} > /dev/null +${NDK_DIRECTORY}ndk-build -j8 # Clean temporary files: -# rm -rf ${PROJECT_DIRECTORY}obj -# find . -name gdbserver -print0 | xargs -0 rm -rf -# find . -name gdb.setup -print0 | xargs -0 rm -rf +rm -rf ${PROJECT_DIRECTORY}obj +find . -name gdbserver -print0 | xargs -0 rm -rf +find . -name gdb.setup -print0 | xargs -0 rm -rf -popd \ No newline at end of file +popd > /dev/null \ No newline at end of file diff --git a/libs/armeabi-v7a/libandengine.so b/libs/armeabi-v7a/libandengine.so index 558d8aa29..a49438c17 100755 Binary files a/libs/armeabi-v7a/libandengine.so and b/libs/armeabi-v7a/libandengine.so differ diff --git a/libs/armeabi/libandengine.so b/libs/armeabi/libandengine.so index 983f54970..0892d3bfb 100755 Binary files a/libs/armeabi/libandengine.so and b/libs/armeabi/libandengine.so differ diff --git a/libs/mips/libandengine.so b/libs/mips/libandengine.so new file mode 100755 index 000000000..958b2c826 Binary files /dev/null and b/libs/mips/libandengine.so differ diff --git a/libs/x86/libandengine.so b/libs/x86/libandengine.so index fc23d6226..ae62dc351 100755 Binary files a/libs/x86/libandengine.so and b/libs/x86/libandengine.so differ diff --git a/proguard-project.txt b/proguard-project.txt new file mode 100644 index 000000000..f2fe1559a --- /dev/null +++ b/proguard-project.txt @@ -0,0 +1,20 @@ +# To enable ProGuard in your project, edit project.properties +# to define the proguard.config property as described in that file. +# +# Add project specific ProGuard rules here. +# By default, the flags in this file are appended to flags specified +# in ${sdk.dir}/tools/proguard/proguard-android.txt +# You can edit the include path and order by changing the ProGuard +# include property in project.properties. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# Add any project specific keep options here: + +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#} diff --git a/proguard.cfg b/proguard.cfg deleted file mode 100644 index b1cdf17b5..000000000 --- a/proguard.cfg +++ /dev/null @@ -1,40 +0,0 @@ --optimizationpasses 5 --dontusemixedcaseclassnames --dontskipnonpubliclibraryclasses --dontpreverify --verbose --optimizations !code/simplification/arithmetic,!field/*,!class/merging/* - --keep public class * extends android.app.Activity --keep public class * extends android.app.Application --keep public class * extends android.app.Service --keep public class * extends android.content.BroadcastReceiver --keep public class * extends android.content.ContentProvider --keep public class * extends android.app.backup.BackupAgentHelper --keep public class * extends android.preference.Preference --keep public class com.android.vending.licensing.ILicensingService - --keepclasseswithmembernames class * { - native ; -} - --keepclasseswithmembers class * { - public (android.content.Context, android.util.AttributeSet); -} - --keepclasseswithmembers class * { - public (android.content.Context, android.util.AttributeSet, int); -} - --keepclassmembers class * extends android.app.Activity { - public void *(android.view.View); -} - --keepclassmembers enum * { - public static **[] values(); - public static ** valueOf(java.lang.String); -} - --keep class * implements android.os.Parcelable { - public static final android.os.Parcelable$Creator *; -} diff --git a/project.properties b/project.properties index b3dbf357e..8624e6ba8 100644 --- a/project.properties +++ b/project.properties @@ -11,4 +11,4 @@ android.library=true # Indicates whether an apk should be generated for each density. split.density=false # Project target. -target=android-15 +target=android-17 diff --git a/src/org/andengine/AndEngine.java b/src/org/andengine/AndEngine.java index ca986a39f..487a28dea 100644 --- a/src/org/andengine/AndEngine.java +++ b/src/org/andengine/AndEngine.java @@ -4,20 +4,24 @@ import javax.microedition.khronos.egl.EGLContext; import javax.microedition.khronos.egl.EGLDisplay; +import org.andengine.engine.options.ConfigChooserOptions; import org.andengine.opengl.view.ConfigChooser; import org.andengine.util.exception.DeviceNotSupportedException; import org.andengine.util.exception.DeviceNotSupportedException.DeviceNotSupportedCause; import org.andengine.util.system.SystemUtils; +import android.app.ActivityManager; +import android.content.Context; +import android.content.pm.ConfigurationInfo; import android.os.Build; /** - * (c) Zynga 2012 + * (c) 2012 Zynga Inc. * * @author Nicolas Gramlich * @since 14:03:59 - 19.03.2012 */ -public class AndEngine { +public final class AndEngine { // =========================================================== // Constants // =========================================================== @@ -30,6 +34,10 @@ public class AndEngine { // Constructors // =========================================================== + private AndEngine() { + + } + // =========================================================== // Getter & Setter // =========================================================== @@ -42,23 +50,23 @@ public class AndEngine { // Methods // =========================================================== - public static boolean isDeviceSupported() { + public static boolean isDeviceSupported(final Context pContext) { try { - AndEngine.checkDeviceSupported(); + AndEngine.checkDeviceSupported(pContext); return true; } catch (final DeviceNotSupportedException e) { return false; } } - public static void checkDeviceSupported() throws DeviceNotSupportedException { + public static void checkDeviceSupported(final Context pContext) throws DeviceNotSupportedException { AndEngine.checkCodePathSupport(); - AndEngine.checkOpenGLSupport(); + AndEngine.checkOpenGLSupport(pContext); } private static void checkCodePathSupport() throws DeviceNotSupportedException { - if(SystemUtils.isAndroidVersionOrLower(Build.VERSION_CODES.FROYO)) { + if (SystemUtils.isAndroidVersionOrLower(Build.VERSION_CODES.FROYO)) { try { System.loadLibrary("andengine"); } catch (final UnsatisfiedLinkError e) { @@ -67,10 +75,21 @@ private static void checkCodePathSupport() throws DeviceNotSupportedException { } } - private static void checkOpenGLSupport() throws DeviceNotSupportedException { + private static void checkOpenGLSupport(final Context pContext) throws DeviceNotSupportedException { + AndEngine.checkGLES20Support(pContext); AndEngine.checkEGLConfigChooserSupport(); } + private static void checkGLES20Support(final Context pContext) throws DeviceNotSupportedException { + final ActivityManager activityManager = (ActivityManager) pContext.getSystemService(Context.ACTIVITY_SERVICE); + + final ConfigurationInfo configurationInfo = activityManager.getDeviceConfigurationInfo(); + + if (configurationInfo.reqGlEsVersion < 0x20000) { + throw new DeviceNotSupportedException(DeviceNotSupportedCause.GLES2_UNSUPPORTED); + } + } + private static void checkEGLConfigChooserSupport() throws DeviceNotSupportedException { /* Get an EGL instance. */ final EGL10 egl = (EGL10) EGLContext.getEGL(); @@ -82,7 +101,7 @@ private static void checkEGLConfigChooserSupport() throws DeviceNotSupportedExce final int[] version = new int[2]; egl.eglInitialize(eglDisplay, version); - final ConfigChooser configChooser = new ConfigChooser(false); // TODO Doesn't correlate to possible multisampling request in EngineOptions... + final ConfigChooser configChooser = new ConfigChooser(new ConfigChooserOptions()); try { configChooser.chooseConfig(egl, eglDisplay); diff --git a/src/org/andengine/audio/BaseAudioEntity.java b/src/org/andengine/audio/BaseAudioEntity.java index 7fad4f864..894973b00 100644 --- a/src/org/andengine/audio/BaseAudioEntity.java +++ b/src/org/andengine/audio/BaseAudioEntity.java @@ -5,7 +5,7 @@ /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 16:35:37 - 13.06.2010 */ @@ -69,7 +69,7 @@ protected float getMasterVolume() throws AudioException { // Methods for/from SuperClass/Interfaces // =========================================================== - protected abstract void throwOnReleased() throws AudioException ; + protected abstract void throwOnReleased() throws AudioException; @Override public float getVolume() throws AudioException { @@ -149,7 +149,7 @@ public void release() throws AudioException { // =========================================================== protected void assertNotReleased() throws AudioException { - if(this.mReleased) { + if (this.mReleased) { this.throwOnReleased(); } } diff --git a/src/org/andengine/audio/BaseAudioManager.java b/src/org/andengine/audio/BaseAudioManager.java index 40d3d52bf..64bc0c6e3 100644 --- a/src/org/andengine/audio/BaseAudioManager.java +++ b/src/org/andengine/audio/BaseAudioManager.java @@ -3,9 +3,9 @@ import java.util.ArrayList; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 18:07:02 - 13.06.2010 */ @@ -44,7 +44,7 @@ public void setMasterVolume(final float pMasterVolume) { this.mMasterVolume = pMasterVolume; final ArrayList audioEntities = this.mAudioEntities; - for(int i = audioEntities.size() - 1; i >= 0; i--) { + for (int i = audioEntities.size() - 1; i >= 0; i--) { final T audioEntity = audioEntities.get(i); audioEntity.onMasterVolumeChanged(pMasterVolume); @@ -64,7 +64,7 @@ public boolean remove(final T pAudioEntity) { @Override public void releaseAll() { final ArrayList audioEntities = this.mAudioEntities; - for(int i = audioEntities.size() - 1; i >= 0; i--) { + for (int i = audioEntities.size() - 1; i >= 0; i--) { final T audioEntity = audioEntities.get(i); audioEntity.stop(); diff --git a/src/org/andengine/audio/IAudioEntity.java b/src/org/andengine/audio/IAudioEntity.java index c235465df..d029522ac 100644 --- a/src/org/andengine/audio/IAudioEntity.java +++ b/src/org/andengine/audio/IAudioEntity.java @@ -1,9 +1,9 @@ package org.andengine.audio; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 14:53:29 - 13.06.2010 */ diff --git a/src/org/andengine/audio/IAudioManager.java b/src/org/andengine/audio/IAudioManager.java index c290bdc3a..0183ae0db 100644 --- a/src/org/andengine/audio/IAudioManager.java +++ b/src/org/andengine/audio/IAudioManager.java @@ -1,9 +1,9 @@ package org.andengine.audio; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 15:02:06 - 13.06.2010 */ diff --git a/src/org/andengine/audio/exception/AudioException.java b/src/org/andengine/audio/exception/AudioException.java index 563295d8f..d7b6b0697 100644 --- a/src/org/andengine/audio/exception/AudioException.java +++ b/src/org/andengine/audio/exception/AudioException.java @@ -3,7 +3,7 @@ import org.andengine.util.exception.AndEngineRuntimeException; /** - * (c) Zynga 2011 + * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 20:44:53 - 09.11.2011 diff --git a/src/org/andengine/audio/music/Music.java b/src/org/andengine/audio/music/Music.java index 921dd5d26..fe52892a6 100644 --- a/src/org/andengine/audio/music/Music.java +++ b/src/org/andengine/audio/music/Music.java @@ -9,7 +9,7 @@ /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 14:53:12 - 13.06.2010 */ @@ -56,7 +56,7 @@ public MediaPlayer getMediaPlayer() throws MusicReleasedException { @Override protected MusicManager getAudioManager() throws MusicReleasedException { - return (MusicManager)super.getAudioManager(); + return (MusicManager) super.getAudioManager(); } @Override diff --git a/src/org/andengine/audio/music/MusicFactory.java b/src/org/andengine/audio/music/MusicFactory.java index e8feb3f15..19d419d94 100644 --- a/src/org/andengine/audio/music/MusicFactory.java +++ b/src/org/andengine/audio/music/MusicFactory.java @@ -1,21 +1,24 @@ package org.andengine.audio.music; import java.io.File; +import java.io.FileDescriptor; import java.io.FileInputStream; import java.io.IOException; +import org.andengine.util.StreamUtils; + import android.content.Context; import android.content.res.AssetFileDescriptor; import android.media.MediaPlayer; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 15:05:49 - 13.06.2010 */ -public class MusicFactory { +public final class MusicFactory { // =========================================================== // Constants // =========================================================== @@ -30,6 +33,10 @@ public class MusicFactory { // Constructors // =========================================================== + private MusicFactory() { + + } + // =========================================================== // Getter & Setter // =========================================================== @@ -38,13 +45,17 @@ public class MusicFactory { * @param pAssetBasePath must end with '/' or have .length() == 0. */ public static void setAssetBasePath(final String pAssetBasePath) { - if(pAssetBasePath.endsWith("/") || pAssetBasePath.length() == 0) { + if (pAssetBasePath.endsWith("/") || pAssetBasePath.length() == 0) { MusicFactory.sAssetBasePath = pAssetBasePath; } else { - throw new IllegalStateException("pAssetBasePath must end with '/' or be lenght zero."); + throw new IllegalStateException("pAssetBasePath must end with '/' or be length zero."); } } + public static String getAssetBasePath() { + return MusicFactory.sAssetBasePath; + } + public static void onCreate() { MusicFactory.setAssetBasePath(""); } @@ -60,7 +71,10 @@ public static void onCreate() { public static Music createMusicFromFile(final MusicManager pMusicManager, final File pFile) throws IOException { final MediaPlayer mediaPlayer = new MediaPlayer(); - mediaPlayer.setDataSource(new FileInputStream(pFile).getFD()); + final FileInputStream fileInputStream = new FileInputStream(pFile); + final FileDescriptor fileDescriptor = fileInputStream.getFD(); + StreamUtils.close(fileInputStream); + mediaPlayer.setDataSource(fileDescriptor); mediaPlayer.prepare(); final Music music = new Music(pMusicManager, mediaPlayer); diff --git a/src/org/andengine/audio/music/MusicLibrary.java b/src/org/andengine/audio/music/MusicLibrary.java index 1fa730dd9..b4cb17ee4 100644 --- a/src/org/andengine/audio/music/MusicLibrary.java +++ b/src/org/andengine/audio/music/MusicLibrary.java @@ -3,7 +3,7 @@ import org.andengine.util.adt.map.Library; /** - * (c) Zynga 2011 + * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 20:30:34 - 09.11.2011 diff --git a/src/org/andengine/audio/music/MusicManager.java b/src/org/andengine/audio/music/MusicManager.java index 639b5338a..9d23d32fc 100644 --- a/src/org/andengine/audio/music/MusicManager.java +++ b/src/org/andengine/audio/music/MusicManager.java @@ -3,9 +3,9 @@ import org.andengine.audio.BaseAudioManager; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 15:01:23 - 13.06.2010 */ diff --git a/src/org/andengine/audio/music/exception/MusicException.java b/src/org/andengine/audio/music/exception/MusicException.java index ffe2617c7..751bb8fd6 100644 --- a/src/org/andengine/audio/music/exception/MusicException.java +++ b/src/org/andengine/audio/music/exception/MusicException.java @@ -3,7 +3,7 @@ import org.andengine.util.exception.AndEngineRuntimeException; /** - * (c) Zynga 2011 + * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 20:37:53 - 09.11.2011 diff --git a/src/org/andengine/audio/music/exception/MusicReleasedException.java b/src/org/andengine/audio/music/exception/MusicReleasedException.java index 5ab6b2443..9ddb3f773 100644 --- a/src/org/andengine/audio/music/exception/MusicReleasedException.java +++ b/src/org/andengine/audio/music/exception/MusicReleasedException.java @@ -1,7 +1,7 @@ package org.andengine.audio.music.exception; /** - * (c) Zynga 2011 + * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 20:44:27 - 09.11.2011 diff --git a/src/org/andengine/audio/sound/Sound.java b/src/org/andengine/audio/sound/Sound.java index a38cce903..1abeedbcd 100644 --- a/src/org/andengine/audio/sound/Sound.java +++ b/src/org/andengine/audio/sound/Sound.java @@ -8,7 +8,7 @@ /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 13:22:15 - 11.03.2010 */ @@ -28,6 +28,7 @@ public class Sound extends BaseAudioEntity { private int mLoopCount; private float mRate = 1.0f; + private int mPriority = 1; // =========================================================== // Constructors @@ -63,7 +64,7 @@ public void setLoopCount(final int pLoopCount) throws SoundReleasedException { this.assertNotReleased(); this.mLoopCount = pLoopCount; - if(this.mStreamID != 0) { + if (this.mStreamID != 0) { this.getSoundPool().setLoop(this.mStreamID, pLoopCount); } } @@ -76,11 +77,24 @@ public void setRate(final float pRate) throws SoundReleasedException { this.assertNotReleased(); this.mRate = pRate; - if(this.mStreamID != 0) { + if (this.mStreamID != 0) { this.getSoundPool().setRate(this.mStreamID, pRate); } } + public int getPriority() { + return this.mPriority; + } + + public void setPriority(final int pPriority) throws SoundReleasedException { + this.assertNotReleased(); + + this.mPriority = pPriority; + if(this.mStreamID != 0) { + this.getSoundPool().setPriority(this.mStreamID, pPriority); + } + } + private SoundPool getSoundPool() throws SoundReleasedException { return this.getAudioManager().getSoundPool(); } @@ -91,7 +105,7 @@ private SoundPool getSoundPool() throws SoundReleasedException { @Override protected SoundManager getAudioManager() throws SoundReleasedException { - return (SoundManager)super.getAudioManager(); + return (SoundManager) super.getAudioManager(); } @Override @@ -107,14 +121,14 @@ public void play() throws SoundReleasedException { final float leftVolume = this.mLeftVolume * masterVolume; final float rightVolume = this.mRightVolume * masterVolume; - this.mStreamID = this.getSoundPool().play(this.mSoundID, leftVolume, rightVolume, 1, this.mLoopCount, this.mRate); + this.mStreamID = this.getSoundPool().play(this.mSoundID, leftVolume, rightVolume, this.mPriority, this.mLoopCount, this.mRate); } @Override public void stop() throws SoundReleasedException { super.stop(); - if(this.mStreamID != 0) { + if (this.mStreamID != 0) { this.getSoundPool().stop(this.mStreamID); } } @@ -123,7 +137,7 @@ public void stop() throws SoundReleasedException { public void resume() throws SoundReleasedException { super.resume(); - if(this.mStreamID != 0) { + if (this.mStreamID != 0) { this.getSoundPool().resume(this.mStreamID); } } @@ -132,7 +146,7 @@ public void resume() throws SoundReleasedException { public void pause() throws SoundReleasedException { super.pause(); - if(this.mStreamID != 0) { + if (this.mStreamID != 0) { this.getSoundPool().pause(this.mStreamID); } } @@ -161,7 +175,7 @@ public void setLooping(final boolean pLooping) throws SoundReleasedException { public void setVolume(final float pLeftVolume, final float pRightVolume) throws SoundReleasedException { super.setVolume(pLeftVolume, pRightVolume); - if(this.mStreamID != 0){ + if (this.mStreamID != 0) { final float masterVolume = this.getMasterVolume(); final float leftVolume = this.mLeftVolume * masterVolume; final float rightVolume = this.mRightVolume * masterVolume; diff --git a/src/org/andengine/audio/sound/SoundFactory.java b/src/org/andengine/audio/sound/SoundFactory.java index 0c61df51d..2943813e2 100644 --- a/src/org/andengine/audio/sound/SoundFactory.java +++ b/src/org/andengine/audio/sound/SoundFactory.java @@ -8,13 +8,13 @@ import android.content.res.AssetFileDescriptor; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 14:23:03 - 11.03.2010 */ -public class SoundFactory { +public final class SoundFactory { // =========================================================== // Constants // =========================================================== @@ -29,6 +29,10 @@ public class SoundFactory { // Constructors // =========================================================== + private SoundFactory() { + + } + // =========================================================== // Getter & Setter // =========================================================== @@ -37,13 +41,17 @@ public class SoundFactory { * @param pAssetBasePath must end with '/' or have .length() == 0. */ public static void setAssetBasePath(final String pAssetBasePath) { - if(pAssetBasePath.endsWith("/") || pAssetBasePath.length() == 0) { + if (pAssetBasePath.endsWith("/") || pAssetBasePath.length() == 0) { SoundFactory.sAssetBasePath = pAssetBasePath; } else { - throw new IllegalStateException("pAssetBasePath must end with '/' or be lenght zero."); + throw new IllegalStateException("pAssetBasePath must end with '/' or be length zero."); } } + public static String getAssetBasePath() { + return SoundFactory.sAssetBasePath; + } + public static void onCreate() { SoundFactory.setAssetBasePath(""); } @@ -57,7 +65,7 @@ public static void onCreate() { // =========================================================== public static Sound createSoundFromPath(final SoundManager pSoundManager, final String pPath) throws IOException { - synchronized(pSoundManager) { + synchronized (pSoundManager) { final int soundID = pSoundManager.getSoundPool().load(pPath, 1); final Sound sound = new Sound(pSoundManager, soundID); pSoundManager.add(sound); @@ -66,7 +74,7 @@ public static Sound createSoundFromPath(final SoundManager pSoundManager, final } public static Sound createSoundFromAsset(final SoundManager pSoundManager, final Context pContext, final String pAssetPath) throws IOException { - synchronized(pSoundManager) { + synchronized (pSoundManager) { final int soundID = pSoundManager.getSoundPool().load(pContext.getAssets().openFd(SoundFactory.sAssetBasePath + pAssetPath), 1); final Sound sound = new Sound(pSoundManager, soundID); pSoundManager.add(sound); @@ -75,7 +83,7 @@ public static Sound createSoundFromAsset(final SoundManager pSoundManager, final } public static Sound createSoundFromResource(final SoundManager pSoundManager, final Context pContext, final int pSoundResID) { - synchronized(pSoundManager) { + synchronized (pSoundManager) { final int soundID = pSoundManager.getSoundPool().load(pContext, pSoundResID, 1); final Sound sound = new Sound(pSoundManager, soundID); pSoundManager.add(sound); @@ -88,7 +96,7 @@ public static Sound createSoundFromFile(final SoundManager pSoundManager, final } public static Sound createSoundFromAssetFileDescriptor(final SoundManager pSoundManager, final AssetFileDescriptor pAssetFileDescriptor) { - synchronized(pSoundManager) { + synchronized (pSoundManager) { final int soundID = pSoundManager.getSoundPool().load(pAssetFileDescriptor, 1); final Sound sound = new Sound(pSoundManager, soundID); pSoundManager.add(sound); @@ -97,7 +105,7 @@ public static Sound createSoundFromAssetFileDescriptor(final SoundManager pSound } public static Sound createSoundFromFileDescriptor(final SoundManager pSoundManager, final FileDescriptor pFileDescriptor, final long pOffset, final long pLength) throws IOException { - synchronized(pSoundManager) { + synchronized (pSoundManager) { final int soundID = pSoundManager.getSoundPool().load(pFileDescriptor, pOffset, pLength, 1); final Sound sound = new Sound(pSoundManager, soundID); pSoundManager.add(sound); diff --git a/src/org/andengine/audio/sound/SoundLibrary.java b/src/org/andengine/audio/sound/SoundLibrary.java index c617891bb..8c92e9e93 100644 --- a/src/org/andengine/audio/sound/SoundLibrary.java +++ b/src/org/andengine/audio/sound/SoundLibrary.java @@ -3,9 +3,9 @@ import org.andengine.util.adt.map.Library; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 20:41:56 - 20.08.2010 */ diff --git a/src/org/andengine/audio/sound/SoundManager.java b/src/org/andengine/audio/sound/SoundManager.java index 98028f710..357084447 100644 --- a/src/org/andengine/audio/sound/SoundManager.java +++ b/src/org/andengine/audio/sound/SoundManager.java @@ -9,9 +9,9 @@ import android.util.SparseArray; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 13:22:59 - 11.03.2010 */ @@ -66,25 +66,25 @@ public void add(final Sound pSound) { @Override public boolean remove(final Sound pSound) { final boolean removed = super.remove(pSound); - if(removed) { + if (removed) { this.mSoundMap.remove(pSound.getSoundID()); } return removed; } - + @Override public void releaseAll() { super.releaseAll(); this.mSoundPool.release(); } - + @Override public synchronized void onLoadComplete(final SoundPool pSoundPool, final int pSoundID, final int pStatus) { - if(pStatus == SoundManager.SOUND_STATUS_OK) { + if (pStatus == SoundManager.SOUND_STATUS_OK) { final Sound sound = this.mSoundMap.get(pSoundID); - if(sound == null) { + if (sound == null) { throw new SoundException("Unexpected soundID: '" + pSoundID + "'."); } else { sound.setLoaded(true); @@ -96,6 +96,14 @@ public synchronized void onLoadComplete(final SoundPool pSoundPool, final int pS // Methods // =========================================================== + public void onPause() { + this.mSoundPool.autoPause(); + } + + public void onResume() { + this.mSoundPool.autoResume(); + } + // =========================================================== // Inner and Anonymous Classes // =========================================================== diff --git a/src/org/andengine/audio/sound/exception/SoundException.java b/src/org/andengine/audio/sound/exception/SoundException.java index a2c7c5f29..e1158ba7a 100644 --- a/src/org/andengine/audio/sound/exception/SoundException.java +++ b/src/org/andengine/audio/sound/exception/SoundException.java @@ -3,7 +3,7 @@ import org.andengine.util.exception.AndEngineRuntimeException; /** - * (c) Zynga 2011 + * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 20:37:53 - 09.11.2011 diff --git a/src/org/andengine/audio/sound/exception/SoundReleasedException.java b/src/org/andengine/audio/sound/exception/SoundReleasedException.java index 4e35dc579..26fb7be9f 100644 --- a/src/org/andengine/audio/sound/exception/SoundReleasedException.java +++ b/src/org/andengine/audio/sound/exception/SoundReleasedException.java @@ -1,7 +1,7 @@ package org.andengine.audio.sound.exception; /** - * (c) Zynga 2011 + * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 20:44:27 - 09.11.2011 diff --git a/src/org/andengine/engine/Engine.java b/src/org/andengine/engine/Engine.java index 3aafa8df5..6b3f385bf 100644 --- a/src/org/andengine/engine/Engine.java +++ b/src/org/andengine/engine/Engine.java @@ -9,6 +9,7 @@ import org.andengine.audio.music.MusicManager; import org.andengine.audio.sound.SoundFactory; import org.andengine.audio.sound.SoundManager; +import org.andengine.audio.sound.exception.SoundException; import org.andengine.engine.camera.Camera; import org.andengine.engine.handler.DrawHandlerList; import org.andengine.engine.handler.IDrawHandler; @@ -62,7 +63,7 @@ /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 12:21:31 - 08.03.2010 */ @@ -107,6 +108,8 @@ public class Engine implements SensorEventListener, OnTouchListener, ITouchEvent private Vibrator mVibrator; + private Display mDefaultDisplay; + private ILocationListener mLocationListener; private Location mLocation; @@ -139,7 +142,7 @@ public Engine(final EngineOptions pEngineOptions) { /* Apply EngineOptions. */ this.mEngineOptions = pEngineOptions; - if(this.mEngineOptions.hasEngineLock()) { + if (this.mEngineOptions.hasEngineLock()) { this.mEngineLock = pEngineOptions.getEngineLock(); } else { this.mEngineLock = new EngineLock(false); @@ -147,31 +150,34 @@ public Engine(final EngineOptions pEngineOptions) { this.mCamera = pEngineOptions.getCamera(); /* Touch. */ - if(this.mEngineOptions.getTouchOptions().needsMultiTouch()) { + if (this.mEngineOptions.getTouchOptions().needsMultiTouch()) { this.setTouchController(new MultiTouchController()); } else { this.setTouchController(new SingleTouchController()); } /* Audio. */ - if(this.mEngineOptions.getAudioOptions().needsSound()) { + if (this.mEngineOptions.getAudioOptions().needsSound()) { this.mSoundManager = new SoundManager(this.mEngineOptions.getAudioOptions().getSoundOptions().getMaxSimultaneousStreams()); } else { this.mSoundManager = null; } - if(this.mEngineOptions.getAudioOptions().needsMusic()) { + if (this.mEngineOptions.getAudioOptions().needsMusic()) { this.mMusicManager = new MusicManager(); } else { this.mMusicManager = null; } /* Start the UpdateThread. */ - if(this.mEngineOptions.hasUpdateThread()) { + if (this.mEngineOptions.hasUpdateThread()) { this.mUpdateThread = this.mEngineOptions.getUpdateThread(); } else { this.mUpdateThread = new UpdateThread(); } this.mUpdateThread.setEngine(this); + } + + public void startUpdateThread() throws IllegalThreadStateException { this.mUpdateThread.start(); } @@ -184,14 +190,20 @@ public synchronized boolean isRunning() { } public synchronized void start() { - if(!this.mRunning) { + if (!this.mRunning) { this.mLastTick = System.nanoTime(); + if (this.mSoundManager != null) { + this.mSoundManager.onResume(); + } this.mRunning = true; } } public synchronized void stop() { - if(this.mRunning) { + if (this.mRunning) { + if (this.mSoundManager != null) { + this.mSoundManager.onPause(); + } this.mRunning = false; } } @@ -277,7 +289,7 @@ public ShaderProgramManager getShaderProgramManager() { } public SoundManager getSoundManager() throws IllegalStateException { - if(this.mSoundManager != null) { + if (this.mSoundManager != null) { return this.mSoundManager; } else { throw new IllegalStateException("To enable the SoundManager, check the EngineOptions!"); @@ -285,7 +297,7 @@ public SoundManager getSoundManager() throws IllegalStateException { } public MusicManager getMusicManager() throws IllegalStateException { - if(this.mMusicManager != null) { + if (this.mMusicManager != null) { return this.mMusicManager; } else { throw new IllegalStateException("To enable the MusicManager, check the EngineOptions!"); @@ -322,13 +334,14 @@ public void clearDrawHandlers() { @Override public void onAccuracyChanged(final Sensor pSensor, final int pAccuracy) { - if(this.mRunning) { - switch(pSensor.getType()) { + if (this.mRunning) { + final int sensorType = pSensor.getType(); + switch (sensorType) { case Sensor.TYPE_ACCELEROMETER: - if(this.mAccelerationData != null) { + if (this.mAccelerationData != null) { this.mAccelerationData.setAccuracy(pAccuracy); this.mAccelerationListener.onAccelerationAccuracyChanged(this.mAccelerationData); - } else if(this.mOrientationData != null) { + } else if (this.mOrientationData != null) { this.mOrientationData.setAccelerationAccuracy(pAccuracy); this.mOrientationListener.onOrientationAccuracyChanged(this.mOrientationData); } @@ -337,37 +350,46 @@ public void onAccuracyChanged(final Sensor pSensor, final int pAccuracy) { this.mOrientationData.setMagneticFieldAccuracy(pAccuracy); this.mOrientationListener.onOrientationAccuracyChanged(this.mOrientationData); break; + default: + throw new IllegalArgumentException("Unexpected " + Sensor.class.getSimpleName() + " of Type: '" + sensorType + "'."); } } } @Override public void onSensorChanged(final SensorEvent pEvent) { - if(this.mRunning) { - switch(pEvent.sensor.getType()) { + if (this.mRunning) { + final Sensor sensor = pEvent.sensor; + final int sensorType = sensor.getType(); + switch (sensorType) { case Sensor.TYPE_ACCELEROMETER: - if(this.mAccelerationData != null) { + if (this.mAccelerationData != null) { + this.mAccelerationData.setDisplayRotation(this.getDisplayOrientation()); this.mAccelerationData.setValues(pEvent.values); this.mAccelerationListener.onAccelerationChanged(this.mAccelerationData); - } else if(this.mOrientationData != null) { + } else if (this.mOrientationData != null) { + this.mOrientationData.setDisplayRotation(this.getDisplayOrientation()); this.mOrientationData.setAccelerationValues(pEvent.values); this.mOrientationListener.onOrientationChanged(this.mOrientationData); } break; case Sensor.TYPE_MAGNETIC_FIELD: + this.mOrientationData.setDisplayRotation(this.getDisplayOrientation()); this.mOrientationData.setMagneticFieldValues(pEvent.values); this.mOrientationListener.onOrientationChanged(this.mOrientationData); break; + default: + throw new IllegalArgumentException("Unexpected " + Sensor.class.getSimpleName() + " of Type: '" + sensorType + "'."); } } } @Override public void onLocationChanged(final Location pLocation) { - if(this.mLocation == null) { + if (this.mLocation == null) { this.mLocation = pLocation; } else { - if(pLocation == null) { + if (pLocation == null) { this.mLocationListener.onLocationLost(); } else { this.mLocation = pLocation; @@ -388,7 +410,7 @@ public void onProviderEnabled(final String pProvider) { @Override public void onStatusChanged(final String pProvider, final int pStatus, final Bundle pExtras) { - switch(pStatus) { + switch (pStatus) { case LocationProvider.AVAILABLE: this.mLocationListener.onLocationProviderStatusChanged(LocationProviderStatus.AVAILABLE, pExtras); break; @@ -398,12 +420,14 @@ public void onStatusChanged(final String pProvider, final int pStatus, final Bun case LocationProvider.TEMPORARILY_UNAVAILABLE: this.mLocationListener.onLocationProviderStatusChanged(LocationProviderStatus.TEMPORARILY_UNAVAILABLE, pExtras); break; + default: + throw new IllegalArgumentException("Unexpected " + LocationProvider.class.getSimpleName() + ": '" + pStatus + "'."); } } @Override public boolean onTouch(final View pView, final MotionEvent pSurfaceMotionEvent) { - if(this.mRunning) { + if (this.mRunning) { this.mTouchController.onHandleMotionEvent(pSurfaceMotionEvent); try { /* Because a human cannot interact 1000x per second, we pause the UI-Thread for a little. */ @@ -419,16 +443,13 @@ public boolean onTouch(final View pView, final MotionEvent pSurfaceMotionEvent) @Override public boolean onTouchEvent(final TouchEvent pSurfaceTouchEvent) { - /* - * Let the engine determine which scene and camera this event should be - * handled by. - */ + /* Let the engine determine which scene and camera this event should be handled by. */ final Scene scene = this.getSceneFromSurfaceTouchEvent(pSurfaceTouchEvent); final Camera camera = this.getCameraFromSurfaceTouchEvent(pSurfaceTouchEvent); - this.convertSurfaceToSceneTouchEvent(camera, pSurfaceTouchEvent); + this.convertSurfaceTouchEventToSceneTouchEvent(camera, pSurfaceTouchEvent); - if(this.onTouchHUD(camera, pSurfaceTouchEvent)) { + if (this.onTouchHUD(camera, pSurfaceTouchEvent)) { return true; } else { /* If HUD didn't handle it, Scene may handle it. */ @@ -437,7 +458,7 @@ public boolean onTouchEvent(final TouchEvent pSurfaceTouchEvent) { } protected boolean onTouchHUD(final Camera pCamera, final TouchEvent pSceneTouchEvent) { - if(pCamera.hasHUD()) { + if (pCamera.hasHUD()) { return pCamera.getHUD().onSceneTouchEvent(pSceneTouchEvent); } else { return false; @@ -445,7 +466,7 @@ protected boolean onTouchHUD(final Camera pCamera, final TouchEvent pSceneTouchE } protected boolean onTouchScene(final Scene pScene, final TouchEvent pSceneTouchEvent) { - if(pScene != null) { + if (pScene != null) { return pScene.onSceneTouchEvent(pSceneTouchEvent); } else { return false; @@ -464,11 +485,11 @@ public void runOnUpdateThread(final Runnable pRunnable) { * This method is useful when you want to execute code on the {@link UpdateThread}, even though the Engine is paused. * * @param pRunnable the {@link Runnable} to be run on the {@link UpdateThread}. - * @param pOnlyWhenEngineRunning if true, the execution of the {@link Runnable} will be delayed until the next time {@link Engine#onUpdateUpdateHandlers(float)} is picked up, which is when {@link Engine#isRunning()} is true. - * if false, the execution of the {@link Runnable} will happen as soon as possible on the {@link UpdateThread}, no matter what {@link Engine#isRunning()} is. + * @param pOnlyWhenEngineRunning if true, the execution of the {@link Runnable} will be delayed until the next time {@link #onUpdateUpdateHandlers(float)} is picked up, which is when {@link Engine#isRunning()} is true. + * if false, the execution of the {@link Runnable} will happen as soon as possible on the {@link UpdateThread}, no matter what {@link #isRunning()} is. */ public void runOnUpdateThread(final Runnable pRunnable, final boolean pOnlyWhenEngineRunning) { - if(pOnlyWhenEngineRunning) { + if (pOnlyWhenEngineRunning) { this.mUpdateThreadRunnableHandler.postRunnable(pRunnable); } else { this.mUpdateThread.postRunnable(pRunnable); @@ -478,7 +499,7 @@ public void runOnUpdateThread(final Runnable pRunnable, final boolean pOnlyWhenE /** * @param pRunnable the {@link Runnable} to run mutually exclusive to the {@link UpdateThread} and the GL-{@link Thread}. * When the caller already is on the {@link UpdateThread} or the GL-{@link Thread}, the {@link Runnable} is executed immediately. - * @see {@link Engine#getEngineLock()} to manually {@link EngineLock#lock()}/{@link EngineLock#unlock()} on, while avoiding creating a {@link Runnable}. + * @see {@link #getEngineLock()} to manually {@link EngineLock#lock()}/{@link EngineLock#unlock()} on, while avoiding creating a {@link Runnable}. */ public void runSafely(final Runnable pRunnable) { this.mEngineLock.lock(); @@ -505,6 +526,8 @@ public void onDestroy() { this.mUpdateThread.interrupt(); } + this.releaseDefaultDisplay(); + this.mVertexBufferObjectManager.onDestroy(); this.mTextureManager.onDestroy(); this.mFontManager.onDestroy(); @@ -526,16 +549,16 @@ protected Scene getSceneFromSurfaceTouchEvent(final TouchEvent pTouchEvent) { return this.mScene; } - protected void convertSurfaceToSceneTouchEvent(final Camera pCamera, final TouchEvent pSurfaceTouchEvent) { - pCamera.convertSurfaceToSceneTouchEvent(pSurfaceTouchEvent, this.mSurfaceWidth, this.mSurfaceHeight); + protected void convertSurfaceTouchEventToSceneTouchEvent(final Camera pCamera, final TouchEvent pSurfaceTouchEvent) { + pCamera.convertSurfaceTouchEventToSceneTouchEvent(pSurfaceTouchEvent, this.mSurfaceWidth, this.mSurfaceHeight); } - protected void convertSceneToSurfaceTouchEvent(final Camera pCamera, final TouchEvent pSurfaceTouchEvent) { - pCamera.convertSceneToSurfaceTouchEvent(pSurfaceTouchEvent, this.mSurfaceWidth, this.mSurfaceHeight); + protected void convertSceneTouchEventToSurfaceTouchEvent(final Camera pCamera, final TouchEvent pSurfaceTouchEvent) { + pCamera.convertSceneTouchEventToSurfaceTouchEvent(pSurfaceTouchEvent, this.mSurfaceWidth, this.mSurfaceHeight); } void onTickUpdate() throws InterruptedException { - if(this.mRunning) { + if (this.mRunning) { final long secondsElapsed = this.getNanosecondsElapsed(); this.mEngineLock.lock(); @@ -567,7 +590,7 @@ void onTickUpdate() throws InterruptedException { } private void throwOnDestroyed() throws EngineDestroyedException { - if(this.mDestroyed) { + if (this.mDestroyed) { throw new EngineDestroyedException(); } } @@ -584,15 +607,15 @@ public void onUpdate(final long pNanosecondsElapsed) throws InterruptedException } protected void onUpdateScene(final float pSecondsElapsed) { - if(this.mScene != null) { + if (this.mScene != null) { this.mScene.onUpdate(pSecondsElapsed); } + this.getCamera().onUpdate(pSecondsElapsed); } protected void onUpdateUpdateHandlers(final float pSecondsElapsed) { this.mUpdateThreadRunnableHandler.onUpdate(pSecondsElapsed); this.mUpdateHandlers.onUpdate(pSecondsElapsed); - this.getCamera().onUpdate(pSecondsElapsed); } protected void onUpdateDrawHandlers(final GLState pGLState, final Camera pCamera) { @@ -620,7 +643,7 @@ public void onDrawFrame(final GLState pGLState) throws InterruptedException { } protected void onDrawScene(final GLState pGLState, final Camera pCamera) { - if(this.mScene != null) { + if (this.mScene != null) { this.mScene.onDraw(pGLState, pCamera); } @@ -639,7 +662,7 @@ public boolean enableVibrator(final Context pContext) { } public void vibrate(final long pMilliseconds) throws IllegalStateException { - if(this.mVibrator != null) { + if (this.mVibrator != null) { this.mVibrator.vibrate(pMilliseconds); } else { throw new IllegalStateException("You need to enable the Vibrator before you can use it!"); @@ -647,7 +670,7 @@ public void vibrate(final long pMilliseconds) throws IllegalStateException { } public void vibrate(final long[] pPattern, final int pRepeat) throws IllegalStateException { - if(this.mVibrator != null) { + if (this.mVibrator != null) { this.mVibrator.vibrate(pPattern, pRepeat); } else { throw new IllegalStateException("You need to enable the Vibrator before you can use it!"); @@ -671,7 +694,7 @@ public void disableLocationSensor(final Context pContext) { } /** - * @see {@link Engine#enableAccelerationSensor(Context, IAccelerationListener, AccelerationSensorOptions)} + * @see {@link #enableAccelerationSensor(Context, IAccelerationListener, AccelerationSensorOptions)} */ public boolean enableAccelerationSensor(final Context pContext, final IAccelerationListener pAccelerationListener) { return this.enableAccelerationSensor(pContext, pAccelerationListener, new AccelerationSensorOptions(Engine.SENSORDELAY_DEFAULT)); @@ -682,13 +705,13 @@ public boolean enableAccelerationSensor(final Context pContext, final IAccelerat */ public boolean enableAccelerationSensor(final Context pContext, final IAccelerationListener pAccelerationListener, final AccelerationSensorOptions pAccelerationSensorOptions) { final SensorManager sensorManager = (SensorManager) pContext.getSystemService(Context.SENSOR_SERVICE); - if(this.isSensorSupported(sensorManager, Sensor.TYPE_ACCELEROMETER)) { + if (this.isSensorSupported(sensorManager, Sensor.TYPE_ACCELEROMETER)) { this.mAccelerationListener = pAccelerationListener; - if(this.mAccelerationData == null) { - final Display display = ((WindowManager) pContext.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); - final int displayRotation = display.getOrientation(); - this.mAccelerationData = new AccelerationData(displayRotation); + this.initDefaultDisplay(pContext); + + if (this.mAccelerationData == null) { + this.mAccelerationData = new AccelerationData(); } this.registerSelfAsSensorListener(sensorManager, Sensor.TYPE_ACCELEROMETER, pAccelerationSensorOptions.getSensorDelay()); @@ -699,13 +722,12 @@ public boolean enableAccelerationSensor(final Context pContext, final IAccelerat } } - /** * @return true when the sensor was successfully disabled, false otherwise. */ public boolean disableAccelerationSensor(final Context pContext) { final SensorManager sensorManager = (SensorManager) pContext.getSystemService(Context.SENSOR_SERVICE); - if(this.isSensorSupported(sensorManager, Sensor.TYPE_ACCELEROMETER)) { + if (this.isSensorSupported(sensorManager, Sensor.TYPE_ACCELEROMETER)) { this.unregisterSelfAsSensorListener(sensorManager, Sensor.TYPE_ACCELEROMETER); return true; } else { @@ -714,7 +736,7 @@ public boolean disableAccelerationSensor(final Context pContext) { } /** - * @see {@link Engine#enableOrientationSensor(Context, IOrientationListener, OrientationSensorOptions)} + * @see {@link #enableOrientationSensor(Context, IOrientationListener, OrientationSensorOptions)} */ public boolean enableOrientationSensor(final Context pContext, final IOrientationListener pOrientationListener) { return this.enableOrientationSensor(pContext, pOrientationListener, new OrientationSensorOptions(Engine.SENSORDELAY_DEFAULT)); @@ -725,13 +747,13 @@ public boolean enableOrientationSensor(final Context pContext, final IOrientatio */ public boolean enableOrientationSensor(final Context pContext, final IOrientationListener pOrientationListener, final OrientationSensorOptions pOrientationSensorOptions) { final SensorManager sensorManager = (SensorManager) pContext.getSystemService(Context.SENSOR_SERVICE); - if(this.isSensorSupported(sensorManager, Sensor.TYPE_ACCELEROMETER) && this.isSensorSupported(sensorManager, Sensor.TYPE_MAGNETIC_FIELD)) { + if (this.isSensorSupported(sensorManager, Sensor.TYPE_ACCELEROMETER) && this.isSensorSupported(sensorManager, Sensor.TYPE_MAGNETIC_FIELD)) { this.mOrientationListener = pOrientationListener; - if(this.mOrientationData == null) { - final Display display = ((WindowManager) pContext.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); - final int displayRotation = display.getOrientation(); - this.mOrientationData = new OrientationData(displayRotation); + this.initDefaultDisplay(pContext); + + if (this.mOrientationData == null) { + this.mOrientationData = new OrientationData(); } this.registerSelfAsSensorListener(sensorManager, Sensor.TYPE_ACCELEROMETER, pOrientationSensorOptions.getSensorDelay()); @@ -749,7 +771,7 @@ public boolean enableOrientationSensor(final Context pContext, final IOrientatio */ public boolean disableOrientationSensor(final Context pContext) { final SensorManager sensorManager = (SensorManager) pContext.getSystemService(Context.SENSOR_SERVICE); - if(this.isSensorSupported(sensorManager, Sensor.TYPE_ACCELEROMETER) && this.isSensorSupported(sensorManager, Sensor.TYPE_MAGNETIC_FIELD)) { + if (this.isSensorSupported(sensorManager, Sensor.TYPE_ACCELEROMETER) && this.isSensorSupported(sensorManager, Sensor.TYPE_MAGNETIC_FIELD)) { this.unregisterSelfAsSensorListener(sensorManager, Sensor.TYPE_ACCELEROMETER); this.unregisterSelfAsSensorListener(sensorManager, Sensor.TYPE_MAGNETIC_FIELD); return true; @@ -772,6 +794,25 @@ private void unregisterSelfAsSensorListener(final SensorManager pSensorManager, pSensorManager.unregisterListener(this, sensor); } + private void initDefaultDisplay(final Context pContext) { + if (this.mDefaultDisplay == null) { + final WindowManager windowManager = (WindowManager) pContext.getSystemService(Context.WINDOW_SERVICE); + this.mDefaultDisplay = windowManager.getDefaultDisplay(); + } + } + + private void releaseDefaultDisplay() { + this.mDefaultDisplay = null; + } + + private int getDisplayOrientation() { + if (this.mDefaultDisplay == null) { + throw new IllegalStateException(); + } else { + return this.mDefaultDisplay.getOrientation(); + } + } + // =========================================================== // Inner and Anonymous Classes // =========================================================== @@ -812,12 +853,12 @@ public void setEngine(final Engine pEngine) { public void run() { android.os.Process.setThreadPriority(this.mEngine.getEngineOptions().getUpdateThreadPriority()); try { - while(true) { + while (true) { this.mRunnableHandler.onUpdate(0); this.mEngine.onTickUpdate(); } } catch (final InterruptedException e) { - if(BuildConfig.DEBUG) { + if (BuildConfig.DEBUG) { Debug.d(this.getClass().getSimpleName() + " interrupted. Don't worry - this " + e.getClass().getSimpleName() + " is most likely expected!", e); } this.interrupt(); @@ -914,13 +955,13 @@ void notifyCanUpdate() { } void waitUntilCanDraw() throws InterruptedException { - while(!this.mDrawing.get()) { + while (!this.mDrawing.get()) { this.mDrawingCondition.await(); } } void waitUntilCanUpdate() throws InterruptedException { - while(this.mDrawing.get()) { + while (this.mDrawing.get()) { this.mDrawingCondition.await(); } } diff --git a/src/org/andengine/engine/FixedStepEngine.java b/src/org/andengine/engine/FixedStepEngine.java index 924add30b..1c1b04919 100644 --- a/src/org/andengine/engine/FixedStepEngine.java +++ b/src/org/andengine/engine/FixedStepEngine.java @@ -7,10 +7,10 @@ /** * A subclass of {@link Engine} that tries to achieve a specific amount of updates per second. * When the time since the last update is bigger long the steplength, additional updates are executed. - * - * (c) 2010 Nicolas Gramlich + * + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 10:17:47 - 02.08.2010 */ @@ -32,6 +32,7 @@ public class FixedStepEngine extends Engine { public FixedStepEngine(final EngineOptions pEngineOptions, final int pStepsPerSecond) { super(pEngineOptions); + this.mStepLength = TimeConstants.NANOSECONDS_PER_SECOND / pStepsPerSecond; } @@ -48,7 +49,7 @@ public void onUpdate(final long pNanosecondsElapsed) throws InterruptedException this.mSecondsElapsedAccumulator += pNanosecondsElapsed; final long stepLength = this.mStepLength; - while(this.mSecondsElapsedAccumulator >= stepLength) { + while (this.mSecondsElapsedAccumulator >= stepLength) { super.onUpdate(stepLength); this.mSecondsElapsedAccumulator -= stepLength; } diff --git a/src/org/andengine/engine/LimitedFPSEngine.java b/src/org/andengine/engine/LimitedFPSEngine.java index 6b9b302d7..ee7b77aa7 100644 --- a/src/org/andengine/engine/LimitedFPSEngine.java +++ b/src/org/andengine/engine/LimitedFPSEngine.java @@ -7,10 +7,10 @@ * A subclass of {@link Engine} that tries to achieve a specific amount of * updates per second. When the time since the last update is bigger long the * steplength, additional updates are executed. - * - * (c) 2010 Nicolas Gramlich + * + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 10:17:47 - 02.08.2010 */ @@ -31,6 +31,7 @@ public class LimitedFPSEngine extends Engine { public LimitedFPSEngine(final EngineOptions pEngineOptions, final int pFramesPerSecond) { super(pEngineOptions); + this.mPreferredFrameLengthNanoseconds = TimeConstants.NANOSECONDS_PER_SECOND / pFramesPerSecond; } @@ -47,7 +48,7 @@ public void onUpdate(final long pNanosecondsElapsed) throws InterruptedException final long preferredFrameLengthNanoseconds = this.mPreferredFrameLengthNanoseconds; final long deltaFrameLengthNanoseconds = preferredFrameLengthNanoseconds - pNanosecondsElapsed; - if(deltaFrameLengthNanoseconds <= 0) { + if (deltaFrameLengthNanoseconds <= 0) { super.onUpdate(pNanosecondsElapsed); } else { final int sleepTimeMilliseconds = (int) (deltaFrameLengthNanoseconds / TimeConstants.NANOSECONDS_PER_MILLISECOND); diff --git a/src/org/andengine/engine/camera/BoundCamera.java b/src/org/andengine/engine/camera/BoundCamera.java index d7842369d..9faeea074 100644 --- a/src/org/andengine/engine/camera/BoundCamera.java +++ b/src/org/andengine/engine/camera/BoundCamera.java @@ -1,9 +1,9 @@ package org.andengine.engine.camera; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 15:55:54 - 27.07.2010 */ @@ -95,12 +95,12 @@ public float getBoundsHeight() { // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== - + @Override public void setCenter(final float pCenterX, final float pCenterY) { super.setCenter(pCenterX, pCenterY); - - if(this.mBoundsEnabled) { + + if (this.mBoundsEnabled) { this.ensureInBounds(); } } @@ -111,16 +111,16 @@ public void setCenter(final float pCenterX, final float pCenterY) { protected void ensureInBounds() { final float centerX; - if(this.mBoundsWidth < this.getWidth()) { + if (this.mBoundsWidth < this.getWidth()) { centerX = this.mBoundsCenterX; } else { - centerX = getBoundedX(this.getCenterX()); + centerX = getBoundedX(this.getCenterX()); } final float centerY; - if(this.mBoundsHeight < this.getHeight()) { + if (this.mBoundsHeight < this.getHeight()) { centerY = this.mBoundsCenterY; } else { - centerY = getBoundedY(this.getCenterY()); + centerY = getBoundedY(this.getCenterY()); } super.setCenter(centerX, centerY); } @@ -132,8 +132,8 @@ protected float getBoundedX(final float pX) { final float maxXBoundExceededAmount = this.getXMax() - this.mBoundsXMax; final boolean maxXBoundExceeded = maxXBoundExceededAmount > 0; - if(minXBoundExceeded) { - if(maxXBoundExceeded) { + if (minXBoundExceeded) { + if (maxXBoundExceeded) { /* Min and max X exceeded. */ return pX - maxXBoundExceededAmount + minXBoundExceededAmount; } else { @@ -141,7 +141,7 @@ protected float getBoundedX(final float pX) { return pX + minXBoundExceededAmount; } } else { - if(maxXBoundExceeded) { + if (maxXBoundExceeded) { /* Only max X exceeded. */ return pX - maxXBoundExceededAmount; } else { @@ -158,8 +158,8 @@ protected float getBoundedY(final float pY) { final float maxYBoundExceededAmount = this.getYMax() - this.mBoundsYMax; final boolean maxYBoundExceeded = maxYBoundExceededAmount > 0; - if(minYBoundExceeded) { - if(maxYBoundExceeded) { + if (minYBoundExceeded) { + if (maxYBoundExceeded) { /* Min and max Y exceeded. */ return pY - maxYBoundExceededAmount + minYBoundExceededAmount; } else { @@ -167,7 +167,7 @@ protected float getBoundedY(final float pY) { return pY + minYBoundExceededAmount; } } else { - if(maxYBoundExceeded) { + if (maxYBoundExceeded) { /* Only max Y exceeded. */ return pY - maxYBoundExceededAmount; } else { diff --git a/src/org/andengine/engine/camera/Camera.java b/src/org/andengine/engine/camera/Camera.java index f4719398a..169a6fd49 100644 --- a/src/org/andengine/engine/camera/Camera.java +++ b/src/org/andengine/engine/camera/Camera.java @@ -5,18 +5,17 @@ import org.andengine.engine.handler.UpdateHandlerList; import org.andengine.entity.IEntity; import org.andengine.entity.primitive.Line; -import org.andengine.entity.shape.RectangularShape; import org.andengine.input.touch.TouchEvent; import org.andengine.opengl.util.GLState; import org.andengine.util.Constants; import org.andengine.util.adt.transformation.Transformation; -import org.andengine.util.algorithm.collision.RectangularShapeCollisionChecker; +import org.andengine.util.algorithm.collision.EntityCollisionChecker; import org.andengine.util.math.MathUtils; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 10:24:18 - 25.03.2010 */ @@ -136,11 +135,11 @@ public float getHeight() { return this.mYMax - this.mYMin; } - public float getWidthRaw() { + public final float getCameraSceneWidth() { return this.mXMax - this.mXMin; } - public float getHeightRaw() { + public final float getCameraSceneHeight() { return this.mYMax - this.mYMin; } @@ -172,7 +171,7 @@ public HUD getHUD() { public void setHUD(final HUD pHUD) { this.mHUD = pHUD; - if(pHUD != null) { + if (pHUD != null) { pHUD.setCamera(this); } } @@ -222,9 +221,9 @@ public int getSurfaceHeight() { } public void setSurfaceSize(final int pSurfaceX, final int pSurfaceY, final int pSurfaceWidth, final int pSurfaceHeight) { - if(this.mSurfaceHeight == 0 && this.mSurfaceWidth == 0) { + if (this.mSurfaceHeight == 0 && this.mSurfaceWidth == 0) { this.onSurfaceSizeInitialized(pSurfaceX, pSurfaceY, pSurfaceWidth, pSurfaceHeight); - } else if(this.mSurfaceWidth != pSurfaceWidth || this.mSurfaceHeight != pSurfaceHeight) { + } else if (this.mSurfaceWidth != pSurfaceWidth || this.mSurfaceHeight != pSurfaceHeight) { this.onSurfaceSizeChanged(this.mSurfaceX, this.mSurfaceY, this.mSurfaceWidth, this.mSurfaceHeight, pSurfaceX, pSurfaceY, pSurfaceWidth, pSurfaceHeight); } } @@ -243,11 +242,11 @@ public void setResizeOnSurfaceSizeChanged(final boolean pResizeOnSurfaceSizeChan @Override public void onUpdate(final float pSecondsElapsed) { - if(this.mUpdateHandlers != null) { + if (this.mUpdateHandlers != null) { this.mUpdateHandlers.onUpdate(pSecondsElapsed); } - if(this.mHUD != null) { + if (this.mHUD != null) { this.mHUD.onUpdate(pSecondsElapsed); } @@ -264,59 +263,59 @@ public void reset() { // =========================================================== public void onDrawHUD(final GLState pGLState) { - if(this.mHUD != null) { + if (this.mHUD != null) { this.mHUD.onDraw(pGLState, this); } } public void updateChaseEntity() { - if(this.mChaseEntity != null) { + if (this.mChaseEntity != null) { final float[] centerCoordinates = this.mChaseEntity.getSceneCenterCoordinates(); this.setCenter(centerCoordinates[Constants.VERTEX_INDEX_X], centerCoordinates[Constants.VERTEX_INDEX_Y]); } } public boolean isLineVisible(final Line pLine) { - return RectangularShapeCollisionChecker.isVisible(this, pLine); + return EntityCollisionChecker.isVisible(this, pLine); } - public boolean isRectangularShapeVisible(final RectangularShape pRectangularShape) { - return RectangularShapeCollisionChecker.isVisible(this, pRectangularShape); + public boolean isEntityVisible(final IEntity pEntity) { + return EntityCollisionChecker.isVisible(this, pEntity); } - public boolean isRectangularShapeVisible(final float pX, final float pY, final float pWidth, final float pHeight, final Transformation pLocalToSceneTransformation) { - return RectangularShapeCollisionChecker.isVisible(this, pX, pY, pWidth, pHeight, pLocalToSceneTransformation); + public boolean isEntityVisible(final float pX, final float pY, final float pWidth, final float pHeight, final Transformation pLocalToSceneTransformation) { + return EntityCollisionChecker.isVisible(this, pX, pY, pWidth, pHeight, pLocalToSceneTransformation); } public void onApplySceneMatrix(final GLState pGLState) { - pGLState.orthoProjectionGLMatrixf(this.getXMin(), this.getXMax(), this.getYMax(), this.getYMin(), this.mZNear, this.mZFar); + pGLState.orthoProjectionGLMatrixf(this.getXMin(), this.getXMax(), this.getYMin(), this.getYMax(), this.mZNear, this.mZFar); final float rotation = this.mRotation; - if(rotation != 0) { + if (rotation != 0) { this.applyRotation(pGLState, this.getCenterX(), this.getCenterY(), rotation); } } public void onApplySceneBackgroundMatrix(final GLState pGLState) { - final float widthRaw = this.getWidthRaw(); - final float heightRaw = this.getHeightRaw(); + final float cameraSceneWidth = this.getCameraSceneWidth(); + final float cameraSceneHeight = this.getCameraSceneHeight(); - pGLState.orthoProjectionGLMatrixf(0, widthRaw, heightRaw, 0, this.mZNear, this.mZFar); + pGLState.orthoProjectionGLMatrixf(0, cameraSceneWidth, 0, cameraSceneHeight, this.mZNear, this.mZFar); final float rotation = this.mRotation; - if(rotation != 0) { - this.applyRotation(pGLState, widthRaw * 0.5f, heightRaw * 0.5f, rotation); + if (rotation != 0) { + this.applyRotation(pGLState, cameraSceneWidth * 0.5f, cameraSceneHeight * 0.5f, rotation); } } public void onApplyCameraSceneMatrix(final GLState pGLState) { - final float widthRaw = this.getWidthRaw(); - final float heightRaw = this.getHeightRaw(); - pGLState.orthoProjectionGLMatrixf(0, widthRaw, heightRaw, 0, this.mZNear, this.mZFar); + final float cameraSceneWidth = this.getCameraSceneWidth(); + final float cameraSceneHeight = this.getCameraSceneHeight(); + pGLState.orthoProjectionGLMatrixf(0, cameraSceneWidth, 0, cameraSceneHeight, this.mZNear, this.mZFar); final float cameraSceneRotation = this.mCameraSceneRotation; - if(cameraSceneRotation != 0) { - this.applyRotation(pGLState, widthRaw * 0.5f, heightRaw * 0.5f, cameraSceneRotation); + if (cameraSceneRotation != 0) { + this.applyRotation(pGLState, cameraSceneWidth * 0.5f, cameraSceneHeight * 0.5f, cameraSceneRotation); } } @@ -326,7 +325,7 @@ private void applyRotation(final GLState pGLState, final float pRotationCenterX, pGLState.translateProjectionGLMatrixf(-pRotationCenterX, -pRotationCenterY, 0); } - public void convertSceneToCameraSceneTouchEvent(final TouchEvent pSceneTouchEvent) { + public void convertSceneTouchEventToCameraSceneTouchEvent(final TouchEvent pSceneTouchEvent) { this.unapplySceneRotation(pSceneTouchEvent); this.applySceneToCameraSceneOffset(pSceneTouchEvent); @@ -351,7 +350,7 @@ public float[] getCameraSceneCoordinatesFromSceneCoordinates(final float[] pScen return pSceneCoordinates; } - public void convertCameraSceneToSceneTouchEvent(final TouchEvent pCameraSceneTouchEvent) { + public void convertCameraSceneTouchEventToSceneTouchEvent(final TouchEvent pCameraSceneTouchEvent) { this.unapplyCameraSceneRotation(pCameraSceneTouchEvent); this.unapplySceneToCameraSceneOffset(pCameraSceneTouchEvent); @@ -396,18 +395,19 @@ protected void unapplySceneToCameraSceneOffset(final float[] pCameraSceneCoordin private void applySceneRotation(final float[] pCameraSceneCoordinates) { final float rotation = this.mRotation; - if(rotation != 0) { - MathUtils.rotateAroundCenter(pCameraSceneCoordinates, -rotation, this.getCenterX(), this.getCenterY()); + if (rotation != 0) { + MathUtils.rotateAroundCenter(pCameraSceneCoordinates, rotation, this.getCenterX(), this.getCenterY()); // TODO Use a Transformation object instead!?! } } private void applySceneRotation(final TouchEvent pCameraSceneTouchEvent) { final float rotation = this.mRotation; - if(rotation != 0) { + + if (rotation != 0) { Camera.VERTICES_TMP[Constants.VERTEX_INDEX_X] = pCameraSceneTouchEvent.getX(); Camera.VERTICES_TMP[Constants.VERTEX_INDEX_Y] = pCameraSceneTouchEvent.getY(); - MathUtils.rotateAroundCenter(Camera.VERTICES_TMP, -rotation, this.getCenterX(), this.getCenterY()); + MathUtils.rotateAroundCenter(Camera.VERTICES_TMP, rotation, this.getCenterX(), this.getCenterY()); // TODO Use a Transformation object instead!?! pCameraSceneTouchEvent.set(Camera.VERTICES_TMP[Constants.VERTEX_INDEX_X], Camera.VERTICES_TMP[Constants.VERTEX_INDEX_Y]); } @@ -416,68 +416,72 @@ private void applySceneRotation(final TouchEvent pCameraSceneTouchEvent) { private void unapplySceneRotation(final float[] pSceneCoordinates) { final float rotation = this.mRotation; - if(rotation != 0) { - MathUtils.revertRotateAroundCenter(pSceneCoordinates, rotation, this.getCenterX(), this.getCenterY()); + if (rotation != 0) { + MathUtils.revertRotateAroundCenter(pSceneCoordinates, rotation, this.getCenterX(), this.getCenterY()); // TODO Use a Transformation object instead!?! } } private void unapplySceneRotation(final TouchEvent pSceneTouchEvent) { final float rotation = this.mRotation; - if(rotation != 0) { + if (rotation != 0) { Camera.VERTICES_TMP[Constants.VERTEX_INDEX_X] = pSceneTouchEvent.getX(); Camera.VERTICES_TMP[Constants.VERTEX_INDEX_Y] = pSceneTouchEvent.getY(); - MathUtils.revertRotateAroundCenter(Camera.VERTICES_TMP, rotation, this.getCenterX(), this.getCenterY()); + MathUtils.revertRotateAroundCenter(Camera.VERTICES_TMP, rotation, this.getCenterX(), this.getCenterY()); // TODO Use a Transformation object instead!?! pSceneTouchEvent.set(Camera.VERTICES_TMP[Constants.VERTEX_INDEX_X], Camera.VERTICES_TMP[Constants.VERTEX_INDEX_Y]); } } private void applyCameraSceneRotation(final float[] pSceneCoordinates) { - final float cameraSceneRotation = -this.mCameraSceneRotation; + final float cameraSceneRotation = this.mCameraSceneRotation; - if(cameraSceneRotation != 0) { - MathUtils.rotateAroundCenter(pSceneCoordinates, cameraSceneRotation, (this.mXMax - this.mXMin) * 0.5f, (this.mYMax - this.mYMin) * 0.5f); + if (cameraSceneRotation != 0) { + MathUtils.rotateAroundCenter(pSceneCoordinates, cameraSceneRotation, this.getCameraSceneWidth() * 0.5f, this.getCameraSceneHeight() * 0.5f); // TODO Use a Transformation object instead!?! } } private void applyCameraSceneRotation(final TouchEvent pSceneTouchEvent) { - final float cameraSceneRotation = -this.mCameraSceneRotation; + final float cameraSceneRotation = this.mCameraSceneRotation; - if(cameraSceneRotation != 0) { + if (cameraSceneRotation != 0) { Camera.VERTICES_TMP[Constants.VERTEX_INDEX_X] = pSceneTouchEvent.getX(); Camera.VERTICES_TMP[Constants.VERTEX_INDEX_Y] = pSceneTouchEvent.getY(); - MathUtils.rotateAroundCenter(Camera.VERTICES_TMP, cameraSceneRotation, (this.mXMax - this.mXMin) * 0.5f, (this.mYMax - this.mYMin) * 0.5f); + MathUtils.rotateAroundCenter(Camera.VERTICES_TMP, cameraSceneRotation, this.getCameraSceneWidth() * 0.5f, this.getCameraSceneHeight() * 0.5f); // TODO Use a Transformation object instead!?! pSceneTouchEvent.set(Camera.VERTICES_TMP[Constants.VERTEX_INDEX_X], Camera.VERTICES_TMP[Constants.VERTEX_INDEX_Y]); } } private void unapplyCameraSceneRotation(final float[] pCameraSceneCoordinates) { - final float cameraSceneRotation = -this.mCameraSceneRotation; + final float cameraSceneRotation = this.mCameraSceneRotation; - if(cameraSceneRotation != 0) { - MathUtils.revertRotateAroundCenter(pCameraSceneCoordinates, cameraSceneRotation, (this.mXMax - this.mXMin) * 0.5f, (this.mYMax - this.mYMin) * 0.5f); + if (cameraSceneRotation != 0) { + MathUtils.revertRotateAroundCenter(pCameraSceneCoordinates, cameraSceneRotation, this.getCameraSceneWidth() * 0.5f, this.getCameraSceneHeight() * 0.5f); // TODO Use a Transformation object instead!?! } } private void unapplyCameraSceneRotation(final TouchEvent pCameraSceneTouchEvent) { - final float cameraSceneRotation = -this.mCameraSceneRotation; + final float cameraSceneRotation = this.mCameraSceneRotation; - if(cameraSceneRotation != 0) { + if (cameraSceneRotation != 0) { Camera.VERTICES_TMP[Constants.VERTEX_INDEX_X] = pCameraSceneTouchEvent.getX(); Camera.VERTICES_TMP[Constants.VERTEX_INDEX_Y] = pCameraSceneTouchEvent.getY(); - MathUtils.revertRotateAroundCenter(Camera.VERTICES_TMP, cameraSceneRotation, (this.mXMax - this.mXMin) * 0.5f, (this.mYMax - this.mYMin) * 0.5f); + MathUtils.revertRotateAroundCenter(Camera.VERTICES_TMP, cameraSceneRotation, this.getCameraSceneWidth() * 0.5f, this.getCameraSceneHeight() * 0.5f); // TODO Use a Transformation object instead!?! pCameraSceneTouchEvent.set(Camera.VERTICES_TMP[Constants.VERTEX_INDEX_X], Camera.VERTICES_TMP[Constants.VERTEX_INDEX_Y]); } } - // TODO Camera already knows about its surfaceWidth, is there a need to pass it in here again? - public void convertSurfaceToSceneTouchEvent(final TouchEvent pSurfaceTouchEvent, final int pSurfaceWidth, final int pSurfaceHeight) { + + public void convertSurfaceTouchEventToSceneTouchEvent(final TouchEvent pSurfaceTouchEvent) { + this.convertSurfaceTouchEventToSceneTouchEvent(pSurfaceTouchEvent, this.mSurfaceWidth, this.mSurfaceHeight); + } + + public void convertSurfaceTouchEventToSceneTouchEvent(final TouchEvent pSurfaceTouchEvent, final int pSurfaceWidth, final int pSurfaceHeight) { final float relativeX; final float relativeY; @@ -485,26 +489,60 @@ public void convertSurfaceToSceneTouchEvent(final TouchEvent pSurfaceTouchEvent, final float surfaceTouchEventY = pSurfaceTouchEvent.getY(); final float rotation = this.mRotation; - if(rotation == 0) { + if (rotation == 0) { relativeX = surfaceTouchEventX / pSurfaceWidth; - relativeY = surfaceTouchEventY / pSurfaceHeight; - } else if(rotation == 180) { - relativeX = 1 - (surfaceTouchEventX / pSurfaceWidth); relativeY = 1 - (surfaceTouchEventY / pSurfaceHeight); + } else if (rotation == 180) { + relativeX = 1 - (surfaceTouchEventX / pSurfaceWidth); + relativeY = surfaceTouchEventY / pSurfaceHeight; } else { Camera.VERTICES_TMP[Constants.VERTEX_INDEX_X] = surfaceTouchEventX; Camera.VERTICES_TMP[Constants.VERTEX_INDEX_Y] = surfaceTouchEventY; - MathUtils.rotateAroundCenter(Camera.VERTICES_TMP, rotation, pSurfaceWidth >> 1, pSurfaceHeight >> 1); + MathUtils.rotateAroundCenter(Camera.VERTICES_TMP, rotation, pSurfaceWidth >> 1, pSurfaceHeight >> 1); // TODO Use a Transformation object instead!?! relativeX = Camera.VERTICES_TMP[Constants.VERTEX_INDEX_X] / pSurfaceWidth; - relativeY = Camera.VERTICES_TMP[Constants.VERTEX_INDEX_Y] / pSurfaceHeight; + relativeY = 1 - (Camera.VERTICES_TMP[Constants.VERTEX_INDEX_Y] / pSurfaceHeight); + } + + this.convertAxisAlignedSurfaceTouchEventToSceneTouchEvent(pSurfaceTouchEvent, relativeX, relativeY); + } + + public float[] getSceneCoordinatesFromSurfaceCoordinates(final float pSurfaceX, final float pSurfaceY) { + Camera.VERTICES_TMP[Constants.VERTEX_INDEX_X] = pSurfaceX; + Camera.VERTICES_TMP[Constants.VERTEX_INDEX_Y] = pSurfaceY; + + return this.getSceneCoordinatesFromSurfaceCoordinates(Camera.VERTICES_TMP); + } + + public float[] getSceneCoordinatesFromSurfaceCoordinates(final float[] pSurfaceCoordinates) { + return this.getSceneCoordinatesFromSurfaceCoordinates(pSurfaceCoordinates, this.mSurfaceWidth, this.mSurfaceHeight); + } + + public float[] getSceneCoordinatesFromSurfaceCoordinates(final float[] pSurfaceCoordinates, final int pSurfaceWidth, final int pSurfaceHeight) { + final float relativeX; + final float relativeY; + + final float rotation = this.mRotation; + if (rotation == 0) { + relativeX = pSurfaceCoordinates[Constants.VERTEX_INDEX_X] / pSurfaceWidth; + relativeY = 1 - (pSurfaceCoordinates[Constants.VERTEX_INDEX_Y] / pSurfaceHeight); + } else if (rotation == 180) { + relativeX = 1 - (pSurfaceCoordinates[Constants.VERTEX_INDEX_X] / pSurfaceWidth); + relativeY = pSurfaceCoordinates[Constants.VERTEX_INDEX_Y] / pSurfaceHeight; + } else { + MathUtils.rotateAroundCenter(pSurfaceCoordinates, rotation, pSurfaceWidth >> 1, pSurfaceHeight >> 1); // TODO Use a Transformation object instead!?! + + relativeX = pSurfaceCoordinates[Constants.VERTEX_INDEX_X] / pSurfaceWidth; + relativeY = 1 - (pSurfaceCoordinates[Constants.VERTEX_INDEX_Y] / pSurfaceHeight); } - this.convertAxisAlignedSurfaceToSceneTouchEvent(pSurfaceTouchEvent, relativeX, relativeY); + this.convertAxisAlignedSurfaceCoordinatesToSceneCoordinates(pSurfaceCoordinates, relativeX, relativeY); + + return pSurfaceCoordinates; } - private void convertAxisAlignedSurfaceToSceneTouchEvent(final TouchEvent pSurfaceTouchEvent, final float pRelativeX, final float pRelativeY) { + private void convertAxisAlignedSurfaceTouchEventToSceneTouchEvent(final TouchEvent pSurfaceTouchEvent, final float pRelativeX, final float pRelativeY) { final float xMin = this.getXMin(); final float xMax = this.getXMax(); final float yMin = this.getYMin(); @@ -516,24 +554,74 @@ private void convertAxisAlignedSurfaceToSceneTouchEvent(final TouchEvent pSurfac pSurfaceTouchEvent.set(x, y); } - public void convertSceneToSurfaceTouchEvent(final TouchEvent pSceneTouchEvent, final int pSurfaceWidth, final int pSurfaceHeight) { + private void convertAxisAlignedSurfaceCoordinatesToSceneCoordinates(final float[] pSurfaceCoordinates, final float pRelativeX, final float pRelativeY) { + final float xMin = this.getXMin(); + final float xMax = this.getXMax(); + final float yMin = this.getYMin(); + final float yMax = this.getYMax(); + + final float x = xMin + pRelativeX * (xMax - xMin); + final float y = yMin + pRelativeY * (yMax - yMin); + + pSurfaceCoordinates[Constants.VERTEX_INDEX_X] = x; + pSurfaceCoordinates[Constants.VERTEX_INDEX_Y] = y; + } + + + public void convertSceneTouchEventToSurfaceTouchEvent(final TouchEvent pSceneTouchEvent) { + this.convertSceneTouchEventToSurfaceTouchEvent(pSceneTouchEvent, this.mSurfaceWidth, this.mSurfaceHeight); + } + + public void convertSceneTouchEventToSurfaceTouchEvent(final TouchEvent pSceneTouchEvent, final int pSurfaceWidth, final int pSurfaceHeight) { this.convertAxisAlignedSceneToSurfaceTouchEvent(pSceneTouchEvent, pSurfaceWidth, pSurfaceHeight); final float rotation = this.mRotation; - if(rotation == 0) { - /* Nothing to do. */ - } else if(rotation == 180) { - pSceneTouchEvent.set(pSurfaceWidth - pSceneTouchEvent.getX(), pSurfaceHeight - pSceneTouchEvent.getY()); + if (rotation == 0) { + /* Nothing. */ + } else if (rotation == 180) { + pSceneTouchEvent.setY(pSurfaceHeight - pSceneTouchEvent.getY()); + pSceneTouchEvent.setX(pSurfaceWidth - pSceneTouchEvent.getX()); } else { Camera.VERTICES_TMP[Constants.VERTEX_INDEX_X] = pSceneTouchEvent.getX(); Camera.VERTICES_TMP[Constants.VERTEX_INDEX_Y] = pSceneTouchEvent.getY(); - MathUtils.revertRotateAroundCenter(Camera.VERTICES_TMP, rotation, pSurfaceWidth >> 1, pSurfaceHeight >> 1); + MathUtils.revertRotateAroundCenter(Camera.VERTICES_TMP, -rotation, pSurfaceWidth >> 1, pSurfaceHeight >> 1); // TODO Use a Transformation object instead!?! pSceneTouchEvent.set(Camera.VERTICES_TMP[Constants.VERTEX_INDEX_X], Camera.VERTICES_TMP[Constants.VERTEX_INDEX_Y]); } } + public float[] getSurfaceCoordinatesFromSceneCoordinates(final float pSceneX, final float pSceneY) { + return this.getSurfaceCoordinatesFromSceneCoordinates(pSceneX, pSceneY, mSurfaceWidth, mSurfaceHeight); + } + + public float[] getSurfaceCoordinatesFromSceneCoordinates(final float pSceneX, final float pSceneY, final int pSurfaceWidth, final int pSurfaceHeight) { + Camera.VERTICES_TMP[Constants.VERTEX_INDEX_X] = pSceneX; + Camera.VERTICES_TMP[Constants.VERTEX_INDEX_Y] = pSceneY; + + return this.getSurfaceCoordinatesFromSceneCoordinates(Camera.VERTICES_TMP, pSurfaceWidth, pSurfaceHeight); + } + + public float[] getSurfaceCoordinatesFromSceneCoordinates(final float[] pSceneCoordinates) { + return this.getSurfaceCoordinatesFromSceneCoordinates(pSceneCoordinates, this.mSurfaceWidth, this.mSurfaceHeight); + } + + public float[] getSurfaceCoordinatesFromSceneCoordinates(final float[] pSceneCoordinates, final int pSurfaceWidth, final int pSurfaceHeight) { + this.convertAxisAlignedSceneCoordinatesToSurfaceCoordinates(pSceneCoordinates, pSurfaceWidth, pSurfaceHeight); + + final float rotation = this.mRotation; + if (rotation == 0) { + /* Nothing. */ + } else if (rotation == 180) { + pSceneCoordinates[Constants.VERTEX_INDEX_Y] = pSurfaceHeight - pSceneCoordinates[Constants.VERTEX_INDEX_Y]; + pSceneCoordinates[Constants.VERTEX_INDEX_X] = pSurfaceWidth - pSceneCoordinates[Constants.VERTEX_INDEX_X]; + } else { + MathUtils.revertRotateAroundCenter(pSceneCoordinates, -rotation, pSurfaceWidth >> 1, pSurfaceHeight >> 1); // TODO Use a Transformation object instead!?! + } + + return pSceneCoordinates; + } + private void convertAxisAlignedSceneToSurfaceTouchEvent(final TouchEvent pSceneTouchEvent, final int pSurfaceWidth, final int pSurfaceHeight) { final float xMin = this.getXMin(); final float xMax = this.getXMax(); @@ -541,34 +629,51 @@ private void convertAxisAlignedSceneToSurfaceTouchEvent(final TouchEvent pSceneT final float yMax = this.getYMax(); final float relativeX = (pSceneTouchEvent.getX() - xMin) / (xMax - xMin); - final float relativeY = (pSceneTouchEvent.getY() - yMin) / (yMax - yMin); + final float relativeY = 1 - (pSceneTouchEvent.getY() - yMin) / (yMax - yMin); - pSceneTouchEvent.set(relativeX * pSurfaceWidth, relativeY * pSurfaceHeight); + final float x = relativeX * pSurfaceWidth; + final float y = relativeY * pSurfaceHeight; + + pSceneTouchEvent.set(x, y); } + private void convertAxisAlignedSceneCoordinatesToSurfaceCoordinates(final float[] pSceneCoordinates, final int pSurfaceWidth, final int pSurfaceHeight) { + final float xMin = this.getXMin(); + final float xMax = this.getXMax(); + final float yMin = this.getYMin(); + final float yMax = this.getYMax(); + + final float relativeX = (pSceneCoordinates[Constants.VERTEX_INDEX_X] - xMin) / (xMax - xMin); + final float relativeY = 1 - (pSceneCoordinates[Constants.VERTEX_INDEX_Y] - yMin) / (yMax - yMin); + + pSceneCoordinates[Constants.VERTEX_INDEX_X] = relativeX * pSurfaceWidth; + pSceneCoordinates[Constants.VERTEX_INDEX_Y] = relativeY * pSurfaceHeight; + } + + public void registerUpdateHandler(final IUpdateHandler pUpdateHandler) { - if(this.mUpdateHandlers == null) { + if (this.mUpdateHandlers == null) { this.allocateUpdateHandlers(); } this.mUpdateHandlers.add(pUpdateHandler); } public boolean unregisterUpdateHandler(final IUpdateHandler pUpdateHandler) { - if(this.mUpdateHandlers == null) { + if (this.mUpdateHandlers == null) { return false; } return this.mUpdateHandlers.remove(pUpdateHandler); } public boolean unregisterUpdateHandlers(final IUpdateHandlerMatcher pUpdateHandlerMatcher) { - if(this.mUpdateHandlers == null) { + if (this.mUpdateHandlers == null) { return false; } return this.mUpdateHandlers.removeAll(pUpdateHandlerMatcher); } public void clearUpdateHandlers() { - if(this.mUpdateHandlers == null) { + if (this.mUpdateHandlers == null) { return; } this.mUpdateHandlers.clear(); @@ -586,23 +691,23 @@ protected void onSurfaceSizeInitialized(final int pSurfaceX, final int pSurfaceY } protected void onSurfaceSizeChanged(final int pOldSurfaceX, final int pOldSurfaceY, final int pOldSurfaceWidth, final int pOldSurfaceHeight, final int pNewSurfaceX, final int pNewSurfaceY, final int pNewSurfaceWidth, final int pNewSurfaceHeight) { - if(this.mResizeOnSurfaceSizeChanged) { + if (this.mResizeOnSurfaceSizeChanged) { final float surfaceWidthRatio = (float)pNewSurfaceWidth / pOldSurfaceWidth; final float surfaceHeightRatio = (float)pNewSurfaceHeight / pOldSurfaceHeight; final float centerX = this.getCenterX(); final float centerY = this.getCenterY(); - final float newWidthRaw = this.getWidthRaw() * surfaceWidthRatio; - final float newHeightRaw = this.getHeightRaw() * surfaceHeightRatio; + final float newWidth = (this.mXMax - this.mXMin) * surfaceWidthRatio; + final float newHeight = (this.mYMax - this.mYMin) * surfaceHeightRatio; - final float newWidthRawHalf = newWidthRaw * 0.5f; - final float newHeightRawHalf = newHeightRaw * 0.5f; + final float newWidthHalf = newWidth * 0.5f; + final float newHeightHalf = newHeight * 0.5f; - final float xMin = centerX - newWidthRawHalf; - final float yMin = centerY - newHeightRawHalf; - final float xMax = centerX + newWidthRawHalf; - final float yMax = centerY + newHeightRawHalf; + final float xMin = centerX - newWidthHalf; + final float yMin = centerY - newHeightHalf; + final float xMax = centerX + newWidthHalf; + final float yMax = centerY + newHeightHalf; this.set(xMin, yMin, xMax, yMax); } diff --git a/src/org/andengine/engine/camera/CameraFactory.java b/src/org/andengine/engine/camera/CameraFactory.java index ad64d1312..e7dbadce9 100644 --- a/src/org/andengine/engine/camera/CameraFactory.java +++ b/src/org/andengine/engine/camera/CameraFactory.java @@ -4,13 +4,13 @@ import android.util.DisplayMetrics; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 13:50:42 - 03.07.2010 */ -public class CameraFactory { +public final class CameraFactory { // =========================================================== // Constants // =========================================================== @@ -23,6 +23,10 @@ public class CameraFactory { // Constructors // =========================================================== + private CameraFactory() { + + } + // =========================================================== // Getter & Setter // =========================================================== diff --git a/src/org/andengine/engine/camera/SmoothCamera.java b/src/org/andengine/engine/camera/SmoothCamera.java index 46ebb688c..0f0823500 100644 --- a/src/org/andengine/engine/camera/SmoothCamera.java +++ b/src/org/andengine/engine/camera/SmoothCamera.java @@ -2,9 +2,9 @@ /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 22:11:17 - 25.03.2010 */ @@ -72,8 +72,8 @@ public void setCenterDirect(final float pCenterX, final float pCenterY) { @Override public void setZoomFactor(final float pZoomFactor) { - if(this.mTargetZoomFactor != pZoomFactor) { - if(this.mTargetZoomFactor == this.mZoomFactor) { + if (this.mTargetZoomFactor != pZoomFactor) { + if (this.mTargetZoomFactor == this.mZoomFactor) { this.mTargetZoomFactor = pZoomFactor; this.onSmoothZoomStarted(); @@ -84,7 +84,7 @@ public void setZoomFactor(final float pZoomFactor) { } public void setZoomFactorDirect(final float pZoomFactor) { - if(this.mTargetZoomFactor != this.mZoomFactor) { + if (this.mTargetZoomFactor != this.mZoomFactor) { this.mTargetZoomFactor = pZoomFactor; super.setZoomFactor(pZoomFactor); @@ -146,7 +146,7 @@ public void onUpdate(final float pSecondsElapsed) { final float targetCenterX = this.mTargetCenterX; final float targetCenterY = this.mTargetCenterY; - if(currentCenterX != targetCenterX || currentCenterY != targetCenterY) { + if (currentCenterX != targetCenterX || currentCenterY != targetCenterY) { final float diffX = targetCenterX - currentCenterX; final float dX = this.limitToMaxVelocityX(diffX, pSecondsElapsed); @@ -161,19 +161,19 @@ public void onUpdate(final float pSecondsElapsed) { final float targetZoomFactor = this.mTargetZoomFactor; - if(currentZoom != targetZoomFactor) { + if (currentZoom != targetZoomFactor) { final float absoluteZoomDifference = targetZoomFactor - currentZoom; final float zoomChange = this.limitToMaxZoomFactorChange(absoluteZoomDifference, pSecondsElapsed); super.setZoomFactor(currentZoom + zoomChange); - if(this.mZoomFactor == this.mTargetZoomFactor) { + if (this.mZoomFactor == this.mTargetZoomFactor) { this.onSmoothZoomFinished(); } } } private float limitToMaxVelocityX(final float pValue, final float pSecondsElapsed) { - if(pValue > 0) { + if (pValue > 0) { return Math.min(pValue, this.mMaxVelocityX * pSecondsElapsed); } else { return Math.max(pValue, -this.mMaxVelocityX * pSecondsElapsed); @@ -181,7 +181,7 @@ private float limitToMaxVelocityX(final float pValue, final float pSecondsElapse } private float limitToMaxVelocityY(final float pValue, final float pSecondsElapsed) { - if(pValue > 0) { + if (pValue > 0) { return Math.min(pValue, this.mMaxVelocityY * pSecondsElapsed); } else { return Math.max(pValue, -this.mMaxVelocityY * pSecondsElapsed); @@ -189,7 +189,7 @@ private float limitToMaxVelocityY(final float pValue, final float pSecondsElapse } private float limitToMaxZoomFactorChange(final float pValue, final float pSecondsElapsed) { - if(pValue > 0) { + if (pValue > 0) { return Math.min(pValue, this.mMaxZoomFactorChange * pSecondsElapsed); } else { return Math.max(pValue, -this.mMaxZoomFactorChange * pSecondsElapsed); diff --git a/src/org/andengine/engine/camera/ZoomCamera.java b/src/org/andengine/engine/camera/ZoomCamera.java index f94186aff..d40c6958f 100644 --- a/src/org/andengine/engine/camera/ZoomCamera.java +++ b/src/org/andengine/engine/camera/ZoomCamera.java @@ -9,7 +9,7 @@ /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 15:48:11 - 24.06.2010 * TODO min/max(X/Y) values could be cached and only updated once the zoomfactor/center changed. @@ -44,7 +44,7 @@ public float getZoomFactor() { public void setZoomFactor(final float pZoomFactor) { this.mZoomFactor = pZoomFactor; - if(this.mBoundsEnabled) { + if (this.mBoundsEnabled) { this.ensureInBounds(); } } @@ -55,7 +55,7 @@ public void setZoomFactor(final float pZoomFactor) { @Override public float getXMin() { - if(this.mZoomFactor == 1.0f) { + if (this.mZoomFactor == 1.0f) { return super.getXMin(); } else { final float centerX = this.getCenterX(); @@ -65,7 +65,7 @@ public float getXMin() { @Override public float getXMax() { - if(this.mZoomFactor == 1.0f) { + if (this.mZoomFactor == 1.0f) { return super.getXMax(); } else { final float centerX = this.getCenterX(); @@ -75,7 +75,7 @@ public float getXMax() { @Override public float getYMin() { - if(this.mZoomFactor == 1.0f) { + if (this.mZoomFactor == 1.0f) { return super.getYMin(); } else { final float centerY = this.getCenterY(); @@ -85,7 +85,7 @@ public float getYMin() { @Override public float getYMax() { - if(this.mZoomFactor == 1.0f) { + if (this.mZoomFactor == 1.0f) { return super.getYMax(); } else { final float centerY = this.getCenterY(); @@ -106,7 +106,7 @@ public float getHeight() { @Override protected void applySceneToCameraSceneOffset(final TouchEvent pSceneTouchEvent) { final float zoomFactor = this.mZoomFactor; - if(zoomFactor != 1) { + if (zoomFactor != 1) { Camera.VERTICES_TMP[Constants.VERTEX_INDEX_X] = pSceneTouchEvent.getX(); Camera.VERTICES_TMP[Constants.VERTEX_INDEX_Y] = pSceneTouchEvent.getY(); @@ -121,7 +121,7 @@ protected void applySceneToCameraSceneOffset(final TouchEvent pSceneTouchEvent) @Override protected void applySceneToCameraSceneOffset(final float[] pSceneCoordinates) { final float zoomFactor = this.mZoomFactor; - if(zoomFactor != 1) { + if (zoomFactor != 1) { MathUtils.scaleAroundCenter(pSceneCoordinates, zoomFactor, zoomFactor, this.getCenterX(), this.getCenterY()); // TODO Use a Transformation object instead!?! } @@ -133,7 +133,7 @@ protected void unapplySceneToCameraSceneOffset(final TouchEvent pCameraSceneTouc super.unapplySceneToCameraSceneOffset(pCameraSceneTouchEvent); final float zoomFactor = this.mZoomFactor; - if(zoomFactor != 1) { + if (zoomFactor != 1) { Camera.VERTICES_TMP[Constants.VERTEX_INDEX_X] = pCameraSceneTouchEvent.getX(); Camera.VERTICES_TMP[Constants.VERTEX_INDEX_Y] = pCameraSceneTouchEvent.getY(); @@ -148,7 +148,7 @@ protected void unapplySceneToCameraSceneOffset(final float[] pCameraSceneCoordin super.unapplySceneToCameraSceneOffset(pCameraSceneCoordinates); final float zoomFactor = this.mZoomFactor; - if(zoomFactor != 1) { + if (zoomFactor != 1) { MathUtils.revertScaleAroundCenter(pCameraSceneCoordinates, zoomFactor, zoomFactor, this.getCenterX(), this.getCenterY()); // TODO Use a Transformation object instead!?! } } diff --git a/src/org/andengine/engine/camera/hud/HUD.java b/src/org/andengine/engine/camera/hud/HUD.java index 052805d3b..4fa0bebe2 100644 --- a/src/org/andengine/engine/camera/hud/HUD.java +++ b/src/org/andengine/engine/camera/hud/HUD.java @@ -7,10 +7,10 @@ /** * While you can add a {@link HUD} to {@link Scene}, you should not do so. * {@link HUD}s are meant to be added to {@link Camera}s via {@link Camera#setHUD(HUD)}. - * - * (c) 2010 Nicolas Gramlich + * + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 14:13:13 - 01.04.2010 */ diff --git a/src/org/andengine/engine/camera/hud/controls/AnalogOnScreenControl.java b/src/org/andengine/engine/camera/hud/controls/AnalogOnScreenControl.java index 27bfb836b..8feff2a61 100644 --- a/src/org/andengine/engine/camera/hud/controls/AnalogOnScreenControl.java +++ b/src/org/andengine/engine/camera/hud/controls/AnalogOnScreenControl.java @@ -8,12 +8,10 @@ import org.andengine.opengl.vbo.VertexBufferObjectManager; import org.andengine.util.math.MathUtils; -import android.util.FloatMath; - /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 00:21:55 - 11.07.2010 */ @@ -78,11 +76,11 @@ protected boolean onHandleControlBaseTouched(final TouchEvent pSceneTouchEvent, @Override protected void onUpdateControlKnob(final float pRelativeX, final float pRelativeY) { - if(pRelativeX * pRelativeX + pRelativeY * pRelativeY <= 0.25f) { + if (pRelativeX * pRelativeX + pRelativeY * pRelativeY <= 0.25f) { super.onUpdateControlKnob(pRelativeX, pRelativeY); } else { final float angleRad = MathUtils.atan2(pRelativeY, pRelativeX); - super.onUpdateControlKnob(FloatMath.cos(angleRad) * 0.5f, FloatMath.sin(angleRad) * 0.5f); + super.onUpdateControlKnob((float) Math.cos(angleRad) * 0.5f, (float) Math.sin(angleRad) * 0.5f); } } diff --git a/src/org/andengine/engine/camera/hud/controls/BaseOnScreenControl.java b/src/org/andengine/engine/camera/hud/controls/BaseOnScreenControl.java index 43df2f888..715242edf 100644 --- a/src/org/andengine/engine/camera/hud/controls/BaseOnScreenControl.java +++ b/src/org/andengine/engine/camera/hud/controls/BaseOnScreenControl.java @@ -1,8 +1,5 @@ package org.andengine.engine.camera.hud.controls; -import static org.andengine.util.Constants.VERTEX_INDEX_X; -import static org.andengine.util.Constants.VERTEX_INDEX_Y; - import org.andengine.engine.camera.Camera; import org.andengine.engine.camera.hud.HUD; import org.andengine.engine.handler.timer.ITimerCallback; @@ -18,9 +15,9 @@ import android.view.MotionEvent; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 10:43:09 - 11.07.2010 */ @@ -43,7 +40,7 @@ public abstract class BaseOnScreenControl extends HUD implements IOnSceneTouchLi private final IOnScreenControlListener mOnScreenControlListener; - private int mActivePointerID = INVALID_POINTER_ID; + private int mActivePointerID = BaseOnScreenControl.INVALID_POINTER_ID; // =========================================================== // Constructors @@ -76,7 +73,7 @@ public void onTimePassed(final TimerHandler pTimerHandler) { })); this.attachChild(this.mControlBase); - this.attachChild(this.mControlKnob); + this.mControlBase.attachChild(this.mControlKnob); this.setTouchAreaBindingOnActionDownEnabled(true); } @@ -104,13 +101,13 @@ public IOnScreenControlListener getOnScreenControlListener() { @Override public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) { final int pointerID = pSceneTouchEvent.getPointerID(); - if(pointerID == this.mActivePointerID) { + if (pointerID == this.mActivePointerID) { this.onHandleControlBaseLeft(); - switch(pSceneTouchEvent.getAction()) { + switch (pSceneTouchEvent.getAction()) { case MotionEvent.ACTION_UP: case MotionEvent.ACTION_CANCEL: - this.mActivePointerID = INVALID_POINTER_ID; + this.mActivePointerID = BaseOnScreenControl.INVALID_POINTER_ID; } } return false; @@ -125,8 +122,8 @@ public void refreshControlKnobPosition() { } /** - * When the touch happened outside of the bounds of this OnScreenControl. - * */ + * When the touch happened outside of the bounds of this OnScreenControl. + */ protected void onHandleControlBaseLeft() { this.onUpdateControlKnob(0, 0); } @@ -141,9 +138,9 @@ protected void onHandleControlKnobReleased() { protected boolean onHandleControlBaseTouched(final TouchEvent pSceneTouchEvent, final float pTouchAreaLocalX, final float pTouchAreaLocalY) { final int pointerID = pSceneTouchEvent.getPointerID(); - switch(pSceneTouchEvent.getAction()) { + switch (pSceneTouchEvent.getAction()) { case MotionEvent.ACTION_DOWN: - if(this.mActivePointerID == INVALID_POINTER_ID) { + if (this.mActivePointerID == BaseOnScreenControl.INVALID_POINTER_ID) { this.mActivePointerID = pointerID; this.updateControlKnob(pTouchAreaLocalX, pTouchAreaLocalY); return true; @@ -151,14 +148,14 @@ protected boolean onHandleControlBaseTouched(final TouchEvent pSceneTouchEvent, break; case MotionEvent.ACTION_UP: case MotionEvent.ACTION_CANCEL: - if(this.mActivePointerID == pointerID) { - this.mActivePointerID = INVALID_POINTER_ID; + if (this.mActivePointerID == pointerID) { + this.mActivePointerID = BaseOnScreenControl.INVALID_POINTER_ID; this.onHandleControlKnobReleased(); return true; } break; default: - if(this.mActivePointerID == pointerID) { + if (this.mActivePointerID == pointerID) { this.updateControlKnob(pTouchAreaLocalX, pTouchAreaLocalY); return true; } @@ -170,15 +167,15 @@ protected boolean onHandleControlBaseTouched(final TouchEvent pSceneTouchEvent, private void updateControlKnob(final float pTouchAreaLocalX, final float pTouchAreaLocalY) { final Sprite controlBase = this.mControlBase; - final float relativeX = MathUtils.bringToBounds(0, controlBase.getWidth(), pTouchAreaLocalX) / controlBase.getWidth() - 0.5f; - final float relativeY = MathUtils.bringToBounds(0, controlBase.getHeight(), pTouchAreaLocalY) / controlBase.getHeight() - 0.5f; + final float relativeX = (MathUtils.bringToBounds(0, controlBase.getWidth(), pTouchAreaLocalX) / controlBase.getWidth()) - 0.5f; + final float relativeY = (MathUtils.bringToBounds(0, controlBase.getHeight(), pTouchAreaLocalY) / controlBase.getHeight()) - 0.5f; this.onUpdateControlKnob(relativeX, relativeY); } /** - * @param pRelativeX from -0.5 (left) to 0.5 (right). - * @param pRelativeY from -0.5 (top) to 0.5 (bottom). + * @param pRelativeX from -0.5f (left) to 0.5 (right). + * @param pRelativeY from -0.5f (bottom) to 0.5f (top). */ protected void onUpdateControlKnob(final float pRelativeX, final float pRelativeY) { final Sprite controlBase = this.mControlBase; @@ -187,9 +184,8 @@ protected void onUpdateControlKnob(final float pRelativeX, final float pRelative this.mControlValueX = 2 * pRelativeX; this.mControlValueY = 2 * pRelativeY; - final float[] controlBaseSceneCenterCoordinates = controlBase.getSceneCenterCoordinates(); - final float x = controlBaseSceneCenterCoordinates[VERTEX_INDEX_X] - controlKnob.getWidth() * 0.5f + pRelativeX * controlBase.getWidthScaled(); - final float y = controlBaseSceneCenterCoordinates[VERTEX_INDEX_Y] - controlKnob.getHeight() * 0.5f + pRelativeY * controlBase.getHeightScaled(); + final float x = controlBase.getWidth() * (0.5f + pRelativeX); + final float y = controlBase.getHeight() * (0.5f + pRelativeY); controlKnob.setPosition(x, y); } diff --git a/src/org/andengine/engine/camera/hud/controls/DigitalOnScreenControl.java b/src/org/andengine/engine/camera/hud/controls/DigitalOnScreenControl.java index a4bf87c5d..818fe7010 100644 --- a/src/org/andengine/engine/camera/hud/controls/DigitalOnScreenControl.java +++ b/src/org/andengine/engine/camera/hud/controls/DigitalOnScreenControl.java @@ -6,9 +6,9 @@ import org.andengine.util.math.MathUtils; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 00:21:55 - 11.07.2010 */ @@ -61,47 +61,47 @@ public void setAllowDiagonal(final boolean pAllowDiagonal) { @Override protected void onUpdateControlKnob(final float pRelativeX, final float pRelativeY) { - if(pRelativeX == 0 && pRelativeY == 0) { + if (pRelativeX == 0 && pRelativeY == 0) { super.onUpdateControlKnob(0, 0); return; } - if(this.mAllowDiagonal) { + if (this.mAllowDiagonal) { final float angle = MathUtils.radToDeg(MathUtils.atan2(pRelativeY, pRelativeX)) + 180; - if(this.testDiagonalAngle(0, angle) || this.testDiagonalAngle(360, angle)) { + if (this.testDiagonalAngle(0, angle) || this.testDiagonalAngle(360, angle)) { super.onUpdateControlKnob(-EXTENT_SIDE, 0); - } else if(this.testDiagonalAngle(45, angle)) { + } else if (this.testDiagonalAngle(45, angle)) { super.onUpdateControlKnob(-EXTENT_DIAGONAL, -EXTENT_DIAGONAL); - } else if(this.testDiagonalAngle(90, angle)) { + } else if (this.testDiagonalAngle(90, angle)) { super.onUpdateControlKnob(0, -EXTENT_SIDE); - } else if(this.testDiagonalAngle(135, angle)) { + } else if (this.testDiagonalAngle(135, angle)) { super.onUpdateControlKnob(EXTENT_DIAGONAL, -EXTENT_DIAGONAL); - } else if(this.testDiagonalAngle(180, angle)) { + } else if (this.testDiagonalAngle(180, angle)) { super.onUpdateControlKnob(EXTENT_SIDE, 0); - } else if(this.testDiagonalAngle(225, angle)) { + } else if (this.testDiagonalAngle(225, angle)) { super.onUpdateControlKnob(EXTENT_DIAGONAL, EXTENT_DIAGONAL); - } else if(this.testDiagonalAngle(270, angle)) { + } else if (this.testDiagonalAngle(270, angle)) { super.onUpdateControlKnob(0, EXTENT_SIDE); - } else if(this.testDiagonalAngle(315, angle)) { + } else if (this.testDiagonalAngle(315, angle)) { super.onUpdateControlKnob(-EXTENT_DIAGONAL, EXTENT_DIAGONAL); } else { super.onUpdateControlKnob(0, 0); } } else { - if(Math.abs(pRelativeX) > Math.abs(pRelativeY)) { - if(pRelativeX > 0) { + if (Math.abs(pRelativeX) > Math.abs(pRelativeY)) { + if (pRelativeX > 0) { super.onUpdateControlKnob(EXTENT_SIDE, 0); - } else if(pRelativeX < 0) { + } else if (pRelativeX < 0) { super.onUpdateControlKnob(-EXTENT_SIDE, 0); - } else if(pRelativeX == 0) { + } else if (pRelativeX == 0) { super.onUpdateControlKnob(0, 0); } } else { - if(pRelativeY > 0) { + if (pRelativeY > 0) { super.onUpdateControlKnob(0, EXTENT_SIDE); - } else if(pRelativeY < 0) { + } else if (pRelativeY < 0) { super.onUpdateControlKnob(0, -EXTENT_SIDE); - } else if(pRelativeY == 0) { + } else if (pRelativeY == 0) { super.onUpdateControlKnob(0, 0); } } diff --git a/src/org/andengine/engine/handler/BaseEntityUpdateHandler.java b/src/org/andengine/engine/handler/BaseEntityUpdateHandler.java index 33c49e2ba..26883ea76 100644 --- a/src/org/andengine/engine/handler/BaseEntityUpdateHandler.java +++ b/src/org/andengine/engine/handler/BaseEntityUpdateHandler.java @@ -5,7 +5,7 @@ /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 14:00:25 - 24.12.2010 */ diff --git a/src/org/andengine/engine/handler/DrawHandlerList.java b/src/org/andengine/engine/handler/DrawHandlerList.java index 8d844a67e..cd1161376 100644 --- a/src/org/andengine/engine/handler/DrawHandlerList.java +++ b/src/org/andengine/engine/handler/DrawHandlerList.java @@ -5,7 +5,7 @@ import org.andengine.util.adt.list.SmartList; /** - * (c) Zynga 2011 + * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 17:42:49 - 22.11.2011 @@ -44,7 +44,7 @@ public DrawHandlerList(final int pCapacity) { @Override public void onDraw(final GLState pGLState, final Camera pCamera) { final int handlerCount = this.size(); - for(int i = handlerCount - 1; i >= 0; i--) { + for (int i = handlerCount - 1; i >= 0; i--) { this.get(i).onDraw(pGLState, pCamera); } } diff --git a/src/org/andengine/engine/handler/IDrawHandler.java b/src/org/andengine/engine/handler/IDrawHandler.java index d7d0ccfa5..c3d1fc5e9 100644 --- a/src/org/andengine/engine/handler/IDrawHandler.java +++ b/src/org/andengine/engine/handler/IDrawHandler.java @@ -5,9 +5,9 @@ /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 10:50:58 - 08.08.2010 */ diff --git a/src/org/andengine/engine/handler/IUpdateHandler.java b/src/org/andengine/engine/handler/IUpdateHandler.java index a5378b11d..f9ac4927d 100644 --- a/src/org/andengine/engine/handler/IUpdateHandler.java +++ b/src/org/andengine/engine/handler/IUpdateHandler.java @@ -3,9 +3,9 @@ import org.andengine.util.IMatcher; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 12:24:09 - 11.03.2010 */ @@ -20,13 +20,13 @@ public interface IUpdateHandler { public void onUpdate(final float pSecondsElapsed); public void reset(); - + // TODO Maybe add onRegister and onUnregister. (Maybe add SimpleUpdateHandler that implements all methods, but onUpdate) // =========================================================== // Inner and Anonymous Classes // =========================================================== - + public interface IUpdateHandlerMatcher extends IMatcher { // =========================================================== // Constants diff --git a/src/org/andengine/engine/handler/UpdateHandlerList.java b/src/org/andengine/engine/handler/UpdateHandlerList.java index e7676e36b..cad9a696d 100644 --- a/src/org/andengine/engine/handler/UpdateHandlerList.java +++ b/src/org/andengine/engine/handler/UpdateHandlerList.java @@ -3,9 +3,9 @@ import org.andengine.util.adt.list.SmartList; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 09:45:22 - 31.03.2010 */ @@ -43,7 +43,7 @@ public UpdateHandlerList(final int pCapacity) { @Override public void onUpdate(final float pSecondsElapsed) { final int handlerCount = this.size(); - for(int i = handlerCount - 1; i >= 0; i--) { + for (int i = handlerCount - 1; i >= 0; i--) { this.get(i).onUpdate(pSecondsElapsed); } } @@ -51,7 +51,7 @@ public void onUpdate(final float pSecondsElapsed) { @Override public void reset() { final int handlerCount = this.size(); - for(int i = handlerCount - 1; i >= 0; i--) { + for (int i = handlerCount - 1; i >= 0; i--) { this.get(i).reset(); } } diff --git a/src/org/andengine/engine/handler/collision/CollisionHandler.java b/src/org/andengine/engine/handler/collision/CollisionHandler.java index dc8f5d84b..085c77a71 100644 --- a/src/org/andengine/engine/handler/collision/CollisionHandler.java +++ b/src/org/andengine/engine/handler/collision/CollisionHandler.java @@ -7,9 +7,9 @@ import org.andengine.util.adt.list.ListUtils; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 12:19:35 - 11.03.2010 */ @@ -64,10 +64,10 @@ public void onUpdate(final float pSecondsElapsed) { final ArrayList staticEntities = this.mTargetStaticEntities; final int staticEntityCount = staticEntities.size(); - for(int i = 0; i < staticEntityCount; i++){ - if(checkShape.collidesWith(staticEntities.get(i))){ + for (int i = 0; i < staticEntityCount; i++) { + if (checkShape.collidesWith(staticEntities.get(i))) { final boolean proceed = this.mCollisionCallback.onCollision(checkShape, staticEntities.get(i)); - if(!proceed) { + if (!proceed) { return; } } diff --git a/src/org/andengine/engine/handler/collision/ICollisionCallback.java b/src/org/andengine/engine/handler/collision/ICollisionCallback.java index ece85fcb2..c944609f2 100644 --- a/src/org/andengine/engine/handler/collision/ICollisionCallback.java +++ b/src/org/andengine/engine/handler/collision/ICollisionCallback.java @@ -3,9 +3,9 @@ import org.andengine.entity.shape.IShape; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 12:05:39 - 11.03.2010 */ diff --git a/src/org/andengine/engine/handler/physics/PhysicsHandler.java b/src/org/andengine/engine/handler/physics/PhysicsHandler.java index f1629060f..c95ddf1a3 100644 --- a/src/org/andengine/engine/handler/physics/PhysicsHandler.java +++ b/src/org/andengine/engine/handler/physics/PhysicsHandler.java @@ -4,9 +4,9 @@ import org.andengine.entity.IEntity; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 13:53:07 - 24.12.2010 */ @@ -120,25 +120,25 @@ public void setAngularVelocity(final float pAngularVelocity) { @Override protected void onUpdate(final float pSecondsElapsed, final IEntity pEntity) { - if(this.mEnabled) { + if (this.mEnabled) { /* Apply linear acceleration. */ final float accelerationX = this.mAccelerationX; final float accelerationY = this.mAccelerationY; - if(accelerationX != 0 || accelerationY != 0) { + if (accelerationX != 0 || accelerationY != 0) { this.mVelocityX += accelerationX * pSecondsElapsed; this.mVelocityY += accelerationY * pSecondsElapsed; } /* Apply angular velocity. */ final float angularVelocity = this.mAngularVelocity; - if(angularVelocity != 0) { + if (angularVelocity != 0) { pEntity.setRotation(pEntity.getRotation() + angularVelocity * pSecondsElapsed); } /* Apply linear velocity. */ final float velocityX = this.mVelocityX; final float velocityY = this.mVelocityY; - if(velocityX != 0 || velocityY != 0) { + if (velocityX != 0 || velocityY != 0) { pEntity.setPosition(pEntity.getX() + velocityX * pSecondsElapsed, pEntity.getY() + velocityY * pSecondsElapsed); } } diff --git a/src/org/andengine/engine/handler/runnable/RunnableHandler.java b/src/org/andengine/engine/handler/runnable/RunnableHandler.java index e82e4e05b..db7d3301d 100644 --- a/src/org/andengine/engine/handler/runnable/RunnableHandler.java +++ b/src/org/andengine/engine/handler/runnable/RunnableHandler.java @@ -5,9 +5,9 @@ import org.andengine.engine.handler.IUpdateHandler; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 10:24:39 - 18.06.2010 */ @@ -38,7 +38,7 @@ public class RunnableHandler implements IUpdateHandler { public synchronized void onUpdate(final float pSecondsElapsed) { final ArrayList runnables = this.mRunnables; final int runnableCount = runnables.size(); - for(int i = runnableCount - 1; i >= 0; i--) { + for (int i = runnableCount - 1; i >= 0; i--) { runnables.get(i).run(); } runnables.clear(); diff --git a/src/org/andengine/engine/handler/timer/ITimerCallback.java b/src/org/andengine/engine/handler/timer/ITimerCallback.java index 14c45fd8d..2139ec622 100644 --- a/src/org/andengine/engine/handler/timer/ITimerCallback.java +++ b/src/org/andengine/engine/handler/timer/ITimerCallback.java @@ -1,9 +1,9 @@ package org.andengine.engine.handler.timer; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 16:23:25 - 12.03.2010 */ diff --git a/src/org/andengine/engine/handler/timer/TimerHandler.java b/src/org/andengine/engine/handler/timer/TimerHandler.java index bb7b16990..9b278632c 100644 --- a/src/org/andengine/engine/handler/timer/TimerHandler.java +++ b/src/org/andengine/engine/handler/timer/TimerHandler.java @@ -3,9 +3,9 @@ import org.andengine.engine.handler.IUpdateHandler; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 16:23:58 - 12.03.2010 */ @@ -33,7 +33,7 @@ public TimerHandler(final float pTimerSeconds, final ITimerCallback pTimerCallba } public TimerHandler(final float pTimerSeconds, final boolean pAutoReset, final ITimerCallback pTimerCallback) { - if(pTimerSeconds <= 0){ + if (pTimerSeconds <= 0) { throw new IllegalStateException("pTimerSeconds must be >= 0!"); } @@ -65,7 +65,7 @@ public float getTimerSeconds() { public float getTimerSecondsElapsed() { return this.mTimerSecondsElapsed; } - + public boolean isTimerCallbackTriggered() { return this.mTimerCallbackTriggered; } @@ -80,16 +80,16 @@ public void setTimerCallbackTriggered(boolean pTimerCallbackTriggered) { @Override public void onUpdate(final float pSecondsElapsed) { - if(this.mAutoReset) { + if (this.mAutoReset) { this.mTimerSecondsElapsed += pSecondsElapsed; - while(this.mTimerSecondsElapsed >= this.mTimerSeconds) { + while (this.mTimerSecondsElapsed >= this.mTimerSeconds) { this.mTimerSecondsElapsed -= this.mTimerSeconds; this.mTimerCallback.onTimePassed(this); } } else { - if(!this.mTimerCallbackTriggered) { + if (!this.mTimerCallbackTriggered) { this.mTimerSecondsElapsed += pSecondsElapsed; - if(this.mTimerSecondsElapsed >= this.mTimerSeconds) { + if (this.mTimerSecondsElapsed >= this.mTimerSeconds) { this.mTimerCallbackTriggered = true; this.mTimerCallback.onTimePassed(this); } diff --git a/src/org/andengine/engine/options/AudioOptions.java b/src/org/andengine/engine/options/AudioOptions.java index 3dbfe3a73..53338c808 100644 --- a/src/org/andengine/engine/options/AudioOptions.java +++ b/src/org/andengine/engine/options/AudioOptions.java @@ -1,7 +1,7 @@ package org.andengine.engine.options; -/** - * (c) Zynga 2011 +/** + * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 23:13:07 - 22.11.2011 diff --git a/src/org/andengine/engine/options/ConfigChooserOptions.java b/src/org/andengine/engine/options/ConfigChooserOptions.java new file mode 100644 index 000000000..289c63c86 --- /dev/null +++ b/src/org/andengine/engine/options/ConfigChooserOptions.java @@ -0,0 +1,117 @@ +package org.andengine.engine.options; + +/** + * (c) 2012 Zynga Inc. + * + * @author Nicolas Gramlich + * @since 16:01:53 - 12.05.2012 + */ +public class ConfigChooserOptions { + // =========================================================== + // Constants + // =========================================================== + + private static final int RED_SIZE_DEFAULT = 5; + private static final int GREEN_SIZE_DEFAULT = 6; + private static final int BLUE_SIZE_DEFAULT = 5; + private static final int DEPTH_SIZE_DEFAULT = 0; + private static final int ALPHA_SIZE_DEFAULT = 0; + private static final int STENCIL_SIZE_DEFAULT = 0; + + // =========================================================== + // Fields + // =========================================================== + + private boolean mRequestedMultiSampling; + + private int mRequestedRedSize = ConfigChooserOptions.RED_SIZE_DEFAULT; + private int mRequestedGreenSize = ConfigChooserOptions.GREEN_SIZE_DEFAULT; + private int mRequestedBlueSize = ConfigChooserOptions.BLUE_SIZE_DEFAULT; + private int mRequestedAlphaSize = ConfigChooserOptions.ALPHA_SIZE_DEFAULT; + private int mRequestedDepthSize = ConfigChooserOptions.DEPTH_SIZE_DEFAULT; + private int mRequestedStencilSize = ConfigChooserOptions.STENCIL_SIZE_DEFAULT; + + // =========================================================== + // Constructors + // =========================================================== + + // =========================================================== + // Getter & Setter + // =========================================================== + + public boolean isRequestedMultiSampling() { + return this.mRequestedMultiSampling; + } + + public void setRequestedMultiSampling(final boolean pRequestedMultiSampling) { + this.mRequestedMultiSampling = pRequestedMultiSampling; + } + + public int getRequestedRedSize() { + return this.mRequestedRedSize; + } + + public void setRequestedRedSize(final int pRequestedRedSize) { + this.mRequestedRedSize = pRequestedRedSize; + } + + public int getRequestedGreenSize() { + return this.mRequestedGreenSize; + } + + public void setRequestedGreenSize(final int pRequestedGreenSize) { + this.mRequestedGreenSize = pRequestedGreenSize; + } + + public int getRequestedBlueSize() { + return this.mRequestedBlueSize; + } + + public void setRequestedBlueSize(final int pRequestedBlueSize) { + this.mRequestedBlueSize = pRequestedBlueSize; + } + + public int getRequestedAlphaSize() { + return this.mRequestedAlphaSize; + } + + public void setRequestedAlphaSize(final int pRequestedAlphaSize) { + this.mRequestedAlphaSize = pRequestedAlphaSize; + } + + public int getRequestedDepthSize() { + return this.mRequestedDepthSize; + } + + public void setRequestedDepthSize(final int pRequestedDepthSize) { + this.mRequestedDepthSize = pRequestedDepthSize; + } + + public int getRequestedStencilSize() { + return this.mRequestedStencilSize; + } + + public void setRequestedStencilSize(final int pRequestedStencilSize) { + this.mRequestedStencilSize = pRequestedStencilSize; + } + + public boolean isRequestedRGBA8888() { + return (this.mRequestedRedSize == 8) && (this.mRequestedGreenSize == 8) && (this.mRequestedBlueSize == 8) && (this.mRequestedAlphaSize == 8); + } + + public boolean isRequestedRGB565() { + return (this.mRequestedRedSize == 5) && (this.mRequestedGreenSize == 6) && (this.mRequestedBlueSize == 5) && (this.mRequestedAlphaSize == 0); + } + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== +} diff --git a/src/org/andengine/engine/options/EngineOptions.java b/src/org/andengine/engine/options/EngineOptions.java index 2eae1c417..e3a55cfc8 100644 --- a/src/org/andengine/engine/options/EngineOptions.java +++ b/src/org/andengine/engine/options/EngineOptions.java @@ -8,7 +8,7 @@ /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 15:59:52 - 09.03.2010 */ diff --git a/src/org/andengine/engine/options/MusicOptions.java b/src/org/andengine/engine/options/MusicOptions.java index bf12cfbf1..a2faf2eb1 100644 --- a/src/org/andengine/engine/options/MusicOptions.java +++ b/src/org/andengine/engine/options/MusicOptions.java @@ -2,7 +2,7 @@ /** - * (c) Zynga 2011 + * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 23:13:07 - 22.11.2011 diff --git a/src/org/andengine/engine/options/RenderOptions.java b/src/org/andengine/engine/options/RenderOptions.java index c8738f4f2..fadd067c4 100644 --- a/src/org/andengine/engine/options/RenderOptions.java +++ b/src/org/andengine/engine/options/RenderOptions.java @@ -3,7 +3,7 @@ /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 13:01:40 - 02.07.2010 */ @@ -16,8 +16,9 @@ public class RenderOptions { // Fields // =========================================================== - private boolean mMultiSampling = false; - private boolean mDithering = false; + private boolean mDithering; + + private ConfigChooserOptions mConfigChooserOptions = new ConfigChooserOptions(); // =========================================================== // Constructors @@ -27,14 +28,6 @@ public class RenderOptions { // Getter & Setter // =========================================================== - public boolean isMultiSampling() { - return this.mMultiSampling; - } - - public void setMultiSampling(final boolean pMultiSampling) { - this.mMultiSampling = pMultiSampling; - } - public boolean isDithering() { return this.mDithering; } @@ -43,6 +36,10 @@ public void setDithering(final boolean pDithering) { this.mDithering = pDithering; } + public ConfigChooserOptions getConfigChooserOptions() { + return this.mConfigChooserOptions; + } + // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== diff --git a/src/org/andengine/engine/options/ScreenOrientation.java b/src/org/andengine/engine/options/ScreenOrientation.java index 6a6d218bf..2521e0311 100644 --- a/src/org/andengine/engine/options/ScreenOrientation.java +++ b/src/org/andengine/engine/options/ScreenOrientation.java @@ -1,7 +1,7 @@ package org.andengine.engine.options; /** - * (c) Zynga 2012 + * (c) 2012 Zynga Inc. * * @author Nicolas Gramlich * @since 16:48:03 - 04.04.2012 diff --git a/src/org/andengine/engine/options/SoundOptions.java b/src/org/andengine/engine/options/SoundOptions.java index a58ac3b0e..397fdb128 100644 --- a/src/org/andengine/engine/options/SoundOptions.java +++ b/src/org/andengine/engine/options/SoundOptions.java @@ -3,7 +3,7 @@ import org.andengine.audio.sound.SoundManager; /** - * (c) Zynga 2011 + * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 23:13:07 - 22.11.2011 diff --git a/src/org/andengine/engine/options/TouchOptions.java b/src/org/andengine/engine/options/TouchOptions.java index 4b031e547..4c26eac42 100644 --- a/src/org/andengine/engine/options/TouchOptions.java +++ b/src/org/andengine/engine/options/TouchOptions.java @@ -1,7 +1,7 @@ package org.andengine.engine.options; /** - * (c) Zynga 2011 + * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 23:18:06 - 22.11.2011 diff --git a/src/org/andengine/engine/options/WakeLockOptions.java b/src/org/andengine/engine/options/WakeLockOptions.java index 8d007ac83..efd295bdf 100644 --- a/src/org/andengine/engine/options/WakeLockOptions.java +++ b/src/org/andengine/engine/options/WakeLockOptions.java @@ -3,9 +3,9 @@ import android.os.PowerManager; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 19:45:23 - 10.07.2010 */ diff --git a/src/org/andengine/engine/options/resolutionpolicy/BaseResolutionPolicy.java b/src/org/andengine/engine/options/resolutionpolicy/BaseResolutionPolicy.java index 40abb95c9..6cfad8583 100644 --- a/src/org/andengine/engine/options/resolutionpolicy/BaseResolutionPolicy.java +++ b/src/org/andengine/engine/options/resolutionpolicy/BaseResolutionPolicy.java @@ -3,9 +3,9 @@ import android.view.View.MeasureSpec; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 22:46:43 - 06.10.2010 */ diff --git a/src/org/andengine/engine/options/resolutionpolicy/FillResolutionPolicy.java b/src/org/andengine/engine/options/resolutionpolicy/FillResolutionPolicy.java index b9b062306..874b714e8 100644 --- a/src/org/andengine/engine/options/resolutionpolicy/FillResolutionPolicy.java +++ b/src/org/andengine/engine/options/resolutionpolicy/FillResolutionPolicy.java @@ -1,13 +1,11 @@ package org.andengine.engine.options.resolutionpolicy; -import org.andengine.opengl.view.RenderSurfaceView; - import android.view.View.MeasureSpec; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 11:22:48 - 29.03.2010 */ @@ -33,13 +31,13 @@ public class FillResolutionPolicy extends BaseResolutionPolicy { // =========================================================== @Override - public void onMeasure(final RenderSurfaceView pRenderSurfaceView, final int pWidthMeasureSpec, final int pHeightMeasureSpec) { + public void onMeasure(final IResolutionPolicy.Callback pResolutionPolicyCallback, final int pWidthMeasureSpec, final int pHeightMeasureSpec) { BaseResolutionPolicy.throwOnNotMeasureSpecEXACTLY(pWidthMeasureSpec, pHeightMeasureSpec); final int measuredWidth = MeasureSpec.getSize(pWidthMeasureSpec); final int measuredHeight = MeasureSpec.getSize(pHeightMeasureSpec); - pRenderSurfaceView.setMeasuredDimensionProxy(measuredWidth, measuredHeight); + pResolutionPolicyCallback.onResolutionChanged(measuredWidth, measuredHeight); } // =========================================================== diff --git a/src/org/andengine/engine/options/resolutionpolicy/FixedResolutionPolicy.java b/src/org/andengine/engine/options/resolutionpolicy/FixedResolutionPolicy.java index 4d823ffd2..f64ca3dfe 100644 --- a/src/org/andengine/engine/options/resolutionpolicy/FixedResolutionPolicy.java +++ b/src/org/andengine/engine/options/resolutionpolicy/FixedResolutionPolicy.java @@ -1,11 +1,10 @@ package org.andengine.engine.options.resolutionpolicy; -import org.andengine.opengl.view.RenderSurfaceView; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 11:23:00 - 29.03.2010 */ @@ -39,8 +38,8 @@ public FixedResolutionPolicy(final int pWidth, final int pHeight) { // =========================================================== @Override - public void onMeasure(final RenderSurfaceView pRenderSurfaceView, final int pWidthMeasureSpec, final int pHeightMeasureSpec) { - pRenderSurfaceView.setMeasuredDimensionProxy(this.mWidth, this.mHeight); + public void onMeasure(final IResolutionPolicy.Callback pResolutionPolicyCallback, final int pWidthMeasureSpec, final int pHeightMeasureSpec) { + pResolutionPolicyCallback.onResolutionChanged(this.mWidth, this.mHeight); } // =========================================================== diff --git a/src/org/andengine/engine/options/resolutionpolicy/IResolutionPolicy.java b/src/org/andengine/engine/options/resolutionpolicy/IResolutionPolicy.java index 4e8884f70..6d0ded3da 100644 --- a/src/org/andengine/engine/options/resolutionpolicy/IResolutionPolicy.java +++ b/src/org/andengine/engine/options/resolutionpolicy/IResolutionPolicy.java @@ -1,11 +1,10 @@ package org.andengine.engine.options.resolutionpolicy; -import org.andengine.opengl.view.RenderSurfaceView; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 11:02:35 - 29.03.2010 */ @@ -18,5 +17,21 @@ public interface IResolutionPolicy { // Methods // =========================================================== - public void onMeasure(final RenderSurfaceView pRenderSurfaceView, final int pWidthMeasureSpec, final int pHeightMeasureSpec); + public void onMeasure(final IResolutionPolicy.Callback pResolutionPolicyCallback, final int pWidthMeasureSpec, final int pHeightMeasureSpec); + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== + + public static interface Callback { + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + public void onResolutionChanged(final int pWidth, final int pHeight); + } } diff --git a/src/org/andengine/engine/options/resolutionpolicy/RatioResolutionPolicy.java b/src/org/andengine/engine/options/resolutionpolicy/RatioResolutionPolicy.java index 46ffa5b95..57f86e7ac 100644 --- a/src/org/andengine/engine/options/resolutionpolicy/RatioResolutionPolicy.java +++ b/src/org/andengine/engine/options/resolutionpolicy/RatioResolutionPolicy.java @@ -1,13 +1,11 @@ package org.andengine.engine.options.resolutionpolicy; -import org.andengine.opengl.view.RenderSurfaceView; - import android.view.View.MeasureSpec; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 11:23:00 - 29.03.2010 */ @@ -43,18 +41,18 @@ public RatioResolutionPolicy(final float pWidthRatio, final float pHeightRatio) // =========================================================== @Override - public void onMeasure(final RenderSurfaceView pRenderSurfaceView, final int pWidthMeasureSpec, final int pHeightMeasureSpec) { + public void onMeasure(final IResolutionPolicy.Callback pResolutionPolicyCallback, final int pWidthMeasureSpec, final int pHeightMeasureSpec) { BaseResolutionPolicy.throwOnNotMeasureSpecEXACTLY(pWidthMeasureSpec, pHeightMeasureSpec); final int specWidth = MeasureSpec.getSize(pWidthMeasureSpec); final int specHeight = MeasureSpec.getSize(pHeightMeasureSpec); final float desiredRatio = this.mRatio; - final float realRatio = (float)specWidth / specHeight; + final float realRatio = ((float) specWidth) / specHeight; int measuredWidth; int measuredHeight; - if(realRatio < desiredRatio) { + if (realRatio < desiredRatio) { measuredWidth = specWidth; measuredHeight = Math.round(measuredWidth / desiredRatio); } else { @@ -62,7 +60,7 @@ public void onMeasure(final RenderSurfaceView pRenderSurfaceView, final int pWid measuredWidth = Math.round(measuredHeight * desiredRatio); } - pRenderSurfaceView.setMeasuredDimensionProxy(measuredWidth, measuredHeight); + pResolutionPolicyCallback.onResolutionChanged(measuredWidth, measuredHeight); } // =========================================================== diff --git a/src/org/andengine/engine/options/resolutionpolicy/RelativeResolutionPolicy.java b/src/org/andengine/engine/options/resolutionpolicy/RelativeResolutionPolicy.java index 6ed0ec232..c84f24c0b 100644 --- a/src/org/andengine/engine/options/resolutionpolicy/RelativeResolutionPolicy.java +++ b/src/org/andengine/engine/options/resolutionpolicy/RelativeResolutionPolicy.java @@ -1,13 +1,11 @@ package org.andengine.engine.options.resolutionpolicy; -import org.andengine.opengl.view.RenderSurfaceView; - import android.view.View.MeasureSpec; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 11:23:00 - 29.03.2010 */ @@ -45,13 +43,13 @@ public RelativeResolutionPolicy(final float pWidthScale, final float pHeightScal // =========================================================== @Override - public void onMeasure(final RenderSurfaceView pRenderSurfaceView, final int pWidthMeasureSpec, final int pHeightMeasureSpec) { + public void onMeasure(final IResolutionPolicy.Callback pResolutionPolicyCallback, final int pWidthMeasureSpec, final int pHeightMeasureSpec) { BaseResolutionPolicy.throwOnNotMeasureSpecEXACTLY(pWidthMeasureSpec, pHeightMeasureSpec); - final int measuredWidth = (int)(MeasureSpec.getSize(pWidthMeasureSpec) * this.mWidthScale); - final int measuredHeight = (int)(MeasureSpec.getSize(pHeightMeasureSpec) * this.mHeightScale); + final int measuredWidth = (int) (MeasureSpec.getSize(pWidthMeasureSpec) * this.mWidthScale); + final int measuredHeight = (int) (MeasureSpec.getSize(pHeightMeasureSpec) * this.mHeightScale); - pRenderSurfaceView.setMeasuredDimensionProxy(measuredWidth, measuredHeight); + pResolutionPolicyCallback.onResolutionChanged(measuredWidth, measuredHeight); } // =========================================================== diff --git a/src/org/andengine/engine/splitscreen/DoubleSceneSplitScreenEngine.java b/src/org/andengine/engine/splitscreen/DoubleSceneSplitScreenEngine.java index c52fefc79..151bf6808 100644 --- a/src/org/andengine/engine/splitscreen/DoubleSceneSplitScreenEngine.java +++ b/src/org/andengine/engine/splitscreen/DoubleSceneSplitScreenEngine.java @@ -10,9 +10,9 @@ import android.opengl.GLES20; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 22:28:34 - 27.03.2010 */ @@ -41,6 +41,9 @@ public DoubleSceneSplitScreenEngine(final EngineOptions pEngineOptions, final Ca // Getter & Setter // =========================================================== + /** + * @deprecated Instead use {@link #getFirstCamera()} or {@link #getSecondCamera()}. + */ @Deprecated @Override public Camera getCamera() { @@ -55,6 +58,9 @@ public Camera getSecondCamera() { return this.mSecondCamera; } + /** + * @deprecated Instead use {@link #getFirstCamera()} or {@link #getSecondScene()}. + */ @Deprecated @Override public Scene getScene() { @@ -69,6 +75,9 @@ public Scene getSecondScene() { return this.mSecondScene; } + /** + * @deprecated Instead use {@link #setFirstScene(Scene)} or {@link #setSecondScene(Scene)}. + */ @Deprecated @Override public void setScene(final Scene pScene) { @@ -87,6 +96,17 @@ public void setSecondScene(final Scene pScene) { // Methods for/from SuperClass/Interfaces // =========================================================== + @Override + protected void onUpdateScene(final float pSecondsElapsed) { + super.onUpdateScene(pSecondsElapsed); + + if (this.mSecondScene != null) { + this.mSecondScene.onUpdate(pSecondsElapsed); + } + + this.getSecondCamera().onUpdate(pSecondsElapsed); + } + @Override protected void onDrawScene(final GLState pGLState, final Camera pFirstCamera) { final Camera secondCamera = this.getSecondCamera(); @@ -99,7 +119,7 @@ protected void onDrawScene(final GLState pGLState, final Camera pFirstCamera) { pGLState.enableScissorTest(); /* First Screen. With first camera, on the left half of the screens width. */ - if(super.mScene != null) { + if (super.mScene != null) { GLES20.glScissor(0, 0, surfaceWidthHalf, surfaceHeight); GLES20.glViewport(0, 0, surfaceWidthHalf, surfaceHeight); @@ -108,7 +128,7 @@ protected void onDrawScene(final GLState pGLState, final Camera pFirstCamera) { } /* Second Screen. With second camera, on the right half of the screens width. */ - if(this.mSecondScene != null) { + if (this.mSecondScene != null) { GLES20.glScissor(surfaceWidthHalf, 0, surfaceWidthHalf, surfaceHeight); GLES20.glViewport(surfaceWidthHalf, 0, surfaceWidthHalf, surfaceHeight); @@ -121,7 +141,7 @@ protected void onDrawScene(final GLState pGLState, final Camera pFirstCamera) { @Override protected Camera getCameraFromSurfaceTouchEvent(final TouchEvent pTouchEvent) { - if(pTouchEvent.getX() <= this.mSurfaceWidth >> 1) { + if (pTouchEvent.getX() <= this.mSurfaceWidth >> 1) { return this.getFirstCamera(); } else { return this.getSecondCamera(); @@ -130,7 +150,7 @@ protected Camera getCameraFromSurfaceTouchEvent(final TouchEvent pTouchEvent) { @Override protected Scene getSceneFromSurfaceTouchEvent(final TouchEvent pTouchEvent) { - if(pTouchEvent.getX() <= this.mSurfaceWidth >> 1) { + if (pTouchEvent.getX() <= this.mSurfaceWidth >> 1) { return this.getFirstScene(); } else { return this.getSecondScene(); @@ -138,31 +158,17 @@ protected Scene getSceneFromSurfaceTouchEvent(final TouchEvent pTouchEvent) { } @Override - protected void onUpdateScene(final float pSecondsElapsed) { - super.onUpdateScene(pSecondsElapsed); - if(this.mSecondScene != null) { - this.mSecondScene.onUpdate(pSecondsElapsed); - } - } - - @Override - protected void convertSurfaceToSceneTouchEvent(final Camera pCamera, final TouchEvent pSurfaceTouchEvent) { + protected void convertSurfaceTouchEventToSceneTouchEvent(final Camera pCamera, final TouchEvent pSurfaceTouchEvent) { final int surfaceWidthHalf = this.mSurfaceWidth >> 1; - if(pCamera == this.getFirstCamera()) { - pCamera.convertSurfaceToSceneTouchEvent(pSurfaceTouchEvent, surfaceWidthHalf, this.mSurfaceHeight); + if (pCamera == this.getFirstCamera()) { + pCamera.convertSurfaceTouchEventToSceneTouchEvent(pSurfaceTouchEvent, surfaceWidthHalf, this.mSurfaceHeight); } else { pSurfaceTouchEvent.offset(-surfaceWidthHalf, 0); - pCamera.convertSurfaceToSceneTouchEvent(pSurfaceTouchEvent, surfaceWidthHalf, this.mSurfaceHeight); + pCamera.convertSurfaceTouchEventToSceneTouchEvent(pSurfaceTouchEvent, surfaceWidthHalf, this.mSurfaceHeight); } } - @Override - protected void onUpdateUpdateHandlers(final float pSecondsElapsed) { - super.onUpdateUpdateHandlers(pSecondsElapsed); - this.getSecondCamera().onUpdate(pSecondsElapsed); - } - @Override protected void onUpdateCameraSurface() { final int surfaceWidth = this.mSurfaceWidth; diff --git a/src/org/andengine/engine/splitscreen/SingleSceneSplitScreenEngine.java b/src/org/andengine/engine/splitscreen/SingleSceneSplitScreenEngine.java index c8df8605a..c10e2da83 100644 --- a/src/org/andengine/engine/splitscreen/SingleSceneSplitScreenEngine.java +++ b/src/org/andengine/engine/splitscreen/SingleSceneSplitScreenEngine.java @@ -9,9 +9,9 @@ import android.opengl.GLES20; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 22:28:34 - 27.03.2010 */ @@ -39,6 +39,9 @@ public SingleSceneSplitScreenEngine(final EngineOptions pEngineOptions, final Ca // Getter & Setter // =========================================================== + /** + * @deprecated Instead use {@link #getFirstCamera()} or {@link #getSecondCamera()}. + */ @Deprecated @Override public Camera getCamera() { @@ -57,43 +60,50 @@ public Camera getSecondCamera() { // Methods for/from SuperClass/Interfaces // =========================================================== + @Override + protected void onUpdateScene(final float pSecondsElapsed) { + super.onUpdateScene(pSecondsElapsed); + + this.getSecondCamera().onUpdate(pSecondsElapsed); + } + @Override protected void onDrawScene(final GLState pGLState, final Camera pFirstCamera) { - if(super.mScene != null) { + if (super.mScene != null) { final Camera secondCamera = this.getSecondCamera(); - + final int surfaceWidth = this.mSurfaceWidth; final int surfaceWidthHalf = surfaceWidth >> 1; - + final int surfaceHeight = this.mSurfaceHeight; - + pGLState.enableScissorTest(); - + /* First Screen. With first camera, on the left half of the screens width. */ { GLES20.glScissor(0, 0, surfaceWidthHalf, surfaceHeight); GLES20.glViewport(0, 0, surfaceWidthHalf, surfaceHeight); - + super.mScene.onDraw(pGLState, pFirstCamera); pFirstCamera.onDrawHUD(pGLState); } - + /* Second Screen. With second camera, on the right half of the screens width. */ { GLES20.glScissor(surfaceWidthHalf, 0, surfaceWidthHalf, surfaceHeight); GLES20.glViewport(surfaceWidthHalf, 0, surfaceWidthHalf, surfaceHeight); - + super.mScene.onDraw(pGLState, secondCamera); secondCamera.onDrawHUD(pGLState); } - + pGLState.disableScissorTest(); } } @Override protected Camera getCameraFromSurfaceTouchEvent(final TouchEvent pTouchEvent) { - if(pTouchEvent.getX() <= this.mSurfaceWidth >> 1) { + if (pTouchEvent.getX() <= this.mSurfaceWidth >> 1) { return this.getFirstCamera(); } else { return this.getSecondCamera(); @@ -101,23 +111,17 @@ protected Camera getCameraFromSurfaceTouchEvent(final TouchEvent pTouchEvent) { } @Override - protected void convertSurfaceToSceneTouchEvent(final Camera pCamera, final TouchEvent pSurfaceTouchEvent) { + protected void convertSurfaceTouchEventToSceneTouchEvent(final Camera pCamera, final TouchEvent pSurfaceTouchEvent) { final int surfaceWidthHalf = this.mSurfaceWidth >> 1; - if(pCamera == this.getFirstCamera()) { - pCamera.convertSurfaceToSceneTouchEvent(pSurfaceTouchEvent, surfaceWidthHalf, this.mSurfaceHeight); + if (pCamera == this.getFirstCamera()) { + pCamera.convertSurfaceTouchEventToSceneTouchEvent(pSurfaceTouchEvent, surfaceWidthHalf, this.mSurfaceHeight); } else { pSurfaceTouchEvent.offset(-surfaceWidthHalf, 0); - pCamera.convertSurfaceToSceneTouchEvent(pSurfaceTouchEvent, surfaceWidthHalf, this.mSurfaceHeight); + pCamera.convertSurfaceTouchEventToSceneTouchEvent(pSurfaceTouchEvent, surfaceWidthHalf, this.mSurfaceHeight); } } - @Override - protected void onUpdateUpdateHandlers(final float pSecondsElapsed) { - super.onUpdateUpdateHandlers(pSecondsElapsed); - this.getSecondCamera().onUpdate(pSecondsElapsed); - } - @Override protected void onUpdateCameraSurface() { final int surfaceWidth = this.mSurfaceWidth; diff --git a/src/org/andengine/entity/Entity.java b/src/org/andengine/entity/Entity.java index 8716fa98a..dbfc92b69 100644 --- a/src/org/andengine/entity/Entity.java +++ b/src/org/andengine/entity/Entity.java @@ -9,18 +9,22 @@ import org.andengine.entity.modifier.EntityModifierList; import org.andengine.entity.modifier.IEntityModifier; import org.andengine.entity.modifier.IEntityModifier.IEntityModifierMatcher; +import org.andengine.entity.primitive.Line; +import org.andengine.input.touch.TouchEvent; import org.andengine.opengl.util.GLState; import org.andengine.util.Constants; +import org.andengine.util.adt.color.Color; +import org.andengine.util.adt.color.ColorUtils; import org.andengine.util.adt.list.SmartList; import org.andengine.util.adt.transformation.Transformation; +import org.andengine.util.algorithm.collision.EntityCollisionChecker; import org.andengine.util.call.ParameterCallable; -import org.andengine.util.color.Color; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 12:00:48 - 08.03.2010 */ @@ -35,6 +39,8 @@ public class Entity implements IEntity { private static final float[] VERTICES_SCENE_TO_LOCAL_TMP = new float[2]; private static final float[] VERTICES_LOCAL_TO_SCENE_TMP = new float[2]; + private static final float[] VERTICES_PARENT_TO_LOCAL_TMP = new float[2]; + private static final float[] VERTICES_LOCAL_TO_PARENT_TMP = new float[2]; private static final ParameterCallable PARAMETERCALLABLE_DETACHCHILD = new ParameterCallable() { @Override @@ -56,9 +62,9 @@ public void call(final IEntity pEntity) { protected boolean mChildrenIgnoreUpdate; protected boolean mChildrenSortPending; - protected int mTag = IEntity.TAG_INVALID; + protected int mTag = IEntity.TAG_DEFAULT; - protected int mZIndex = 0; + protected int mZIndex = IEntity.ZINDEX_DEFAULT; private IEntity mParent; @@ -66,27 +72,41 @@ public void call(final IEntity pEntity) { private EntityModifierList mEntityModifiers; private UpdateHandlerList mUpdateHandlers; - protected Color mColor = new Color(1, 1, 1, 1); + protected Color mColor = new Color(Color.WHITE); protected float mX; protected float mY; - protected float mRotation = 0; + protected float mOffsetCenterX = IEntity.OFFSET_CENTER_X_DEFAULT; + protected float mOffsetCenterY = IEntity.OFFSET_CENTER_Y_DEFAULT; + protected float mLocalOffsetCenterX; + protected float mLocalOffsetCenterY; - protected float mRotationCenterX = 0; - protected float mRotationCenterY = 0; + protected float mWidth; + protected float mHeight; - protected float mScaleX = 1; - protected float mScaleY = 1; + protected float mRotation = IEntity.ROTATION_DEFAULT; - protected float mScaleCenterX = 0; - protected float mScaleCenterY = 0; + protected float mRotationCenterX = IEntity.ROTATION_CENTER_X_DEFAULT; + protected float mRotationCenterY = IEntity.ROTATION_CENTER_Y_DEFAULT; + protected float mLocalRotationCenterX; + protected float mLocalRotationCenterY; - protected float mSkewX = 0; - protected float mSkewY = 0; + protected float mScaleX = IEntity.SCALE_X_DEFAULT; + protected float mScaleY = IEntity.SCALE_Y_DEFAULT; - protected float mSkewCenterX = 0; - protected float mSkewCenterY = 0; + protected float mScaleCenterX = IEntity.SCALE_CENTER_X_DEFAULT; + protected float mScaleCenterY = IEntity.SCALE_CENTER_Y_DEFAULT; + protected float mLocalScaleCenterX; + protected float mLocalScaleCenterY; + + protected float mSkewX = IEntity.SKEW_X_DEFAULT; + protected float mSkewY = IEntity.SKEW_Y_DEFAULT; + + protected float mSkewCenterX = IEntity.SKEW_CENTER_X_DEFAULT; + protected float mSkewCenterY = IEntity.SKEW_CENTER_Y_DEFAULT; + protected float mLocalSkewCenterX; + protected float mLocalSkewCenterY; private boolean mLocalToParentTransformationDirty = true; private boolean mParentToLocalTransformationDirty = true; @@ -108,8 +128,17 @@ public Entity() { } public Entity(final float pX, final float pY) { + this(pX, pY, 0, 0); + } + + public Entity(final float pX, final float pY, final float pWidth, final float pHeight) { this.mX = pX; this.mY = pY; + + this.mWidth = pWidth; + this.mHeight = pHeight; + + this.updateLocalCenters(); } // =========================================================== @@ -151,6 +180,25 @@ public void setCullingEnabled(final boolean pCullingEnabled) { @Override public boolean isCulled(final Camera pCamera) { + return !EntityCollisionChecker.isVisible(pCamera, this); + } + + @Override + public boolean collidesWith(final IEntity pOtherEntity) { + if (pOtherEntity instanceof Line) { + return EntityCollisionChecker.checkCollision(this, (Line) pOtherEntity); + } else { + return EntityCollisionChecker.checkCollision(this, pOtherEntity); + } + } + + @Override + public boolean contains(final float pX, final float pY) { + return EntityCollisionChecker.checkContains(this, pX, pY); + } + + @Override + public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final float pTouchAreaLocalX, final float pTouchAreaLocalY) { return false; } @@ -199,6 +247,17 @@ public void setParent(final IEntity pEntity) { this.mParent = pEntity; } + @Override + public IEntity getRootEntity() { + IEntity rootEntity = this; + + while (rootEntity.hasParent()) { + rootEntity = rootEntity.getParent(); + } + + return rootEntity; + } + @Override public int getTag() { return this.mTag; @@ -259,6 +318,91 @@ public void setPosition(final float pX, final float pY) { this.mParentToLocalTransformationDirty = true; } + @Override + public float getWidth() { + return this.mWidth; + } + + @Deprecated + @Override + public float getWidthScaled() { + return this.mWidth * this.mScaleX; + } + + @Override + public void setWidth(final float pWidth) { + this.mWidth = pWidth; + + this.updateLocalCenterXs(); + } + + @Override + public float getHeight() { + return this.mHeight; + } + + @Deprecated + @Override + public float getHeightScaled() { + return this.mHeight * this.mScaleY; + } + + @Override + public void setHeight(final float pHeight) { + this.mHeight = pHeight; + + this.updateLocalCenterYs(); + } + + @Override + public void setSize(final float pWidth, final float pHeight) { + this.mWidth = pWidth; + this.mHeight = pHeight; + + this.updateLocalCenters(); + } + + @Override + public float getOffsetCenterX() { + return this.mOffsetCenterX; + } + + @Override + public float getOffsetCenterY() { + return this.mOffsetCenterY; + } + + @Override + public void setOffsetCenterX(final float pOffsetCenterX) { + this.mOffsetCenterX = pOffsetCenterX; + + this.updateLocalOffsetCenterX(); + + this.mLocalToParentTransformationDirty = true; + this.mParentToLocalTransformationDirty = true; + } + + @Override + public void setOffsetCenterY(final float pOffsetCenterY) { + this.mOffsetCenterY = pOffsetCenterY; + + this.updateLocalOffsetCenterY(); + + this.mLocalToParentTransformationDirty = true; + this.mParentToLocalTransformationDirty = true; + } + + @Override + public void setOffsetCenter(final float pOffsetCenterX, final float pOffsetCenterY) { + this.mOffsetCenterX = pOffsetCenterX; + this.mOffsetCenterY = pOffsetCenterY; + + this.updateLocalOffsetCenter(); + + this.mLocalToParentTransformationDirty = true; + this.mParentToLocalTransformationDirty = true; + } + @Override public float getRotation() { return this.mRotation; @@ -291,6 +435,8 @@ public float getRotationCenterY() { public void setRotationCenterX(final float pRotationCenterX) { this.mRotationCenterX = pRotationCenterX; + this.updateLocalRotationCenterX(); + this.mLocalToParentTransformationDirty = true; this.mParentToLocalTransformationDirty = true; } @@ -299,6 +445,8 @@ public void setRotationCenterX(final float pRotationCenterX) { public void setRotationCenterY(final float pRotationCenterY) { this.mRotationCenterY = pRotationCenterY; + this.updateLocalRotationCenterY(); + this.mLocalToParentTransformationDirty = true; this.mParentToLocalTransformationDirty = true; } @@ -308,6 +456,8 @@ public void setRotationCenter(final float pRotationCenterX, final float pRotatio this.mRotationCenterX = pRotationCenterX; this.mRotationCenterY = pRotationCenterY; + this.updateLocalRotationCenter(); + this.mLocalToParentTransformationDirty = true; this.mParentToLocalTransformationDirty = true; } @@ -345,11 +495,7 @@ public void setScaleY(final float pScaleY) { @Override public void setScale(final float pScale) { - this.mScaleX = pScale; - this.mScaleY = pScale; - - this.mLocalToParentTransformationDirty = true; - this.mParentToLocalTransformationDirty = true; + this.setScale(pScale, pScale); } @Override @@ -375,6 +521,8 @@ public float getScaleCenterY() { public void setScaleCenterX(final float pScaleCenterX) { this.mScaleCenterX = pScaleCenterX; + this.updateLocalScaleCenterX(); + this.mLocalToParentTransformationDirty = true; this.mParentToLocalTransformationDirty = true; } @@ -383,6 +531,8 @@ public void setScaleCenterX(final float pScaleCenterX) { public void setScaleCenterY(final float pScaleCenterY) { this.mScaleCenterY = pScaleCenterY; + this.updateLocalScaleCenterY(); + this.mLocalToParentTransformationDirty = true; this.mParentToLocalTransformationDirty = true; } @@ -392,6 +542,8 @@ public void setScaleCenter(final float pScaleCenterX, final float pScaleCenterY) this.mScaleCenterX = pScaleCenterX; this.mScaleCenterY = pScaleCenterY; + this.updateLocalScaleCenter(); + this.mLocalToParentTransformationDirty = true; this.mParentToLocalTransformationDirty = true; } @@ -429,11 +581,7 @@ public void setSkewY(final float pSkewY) { @Override public void setSkew(final float pSkew) { - this.mSkewX = pSkew; - this.mSkewY = pSkew; - - this.mLocalToParentTransformationDirty = true; - this.mParentToLocalTransformationDirty = true; + this.setSkew(pSkew, pSkew); } @Override @@ -459,6 +607,8 @@ public float getSkewCenterY() { public void setSkewCenterX(final float pSkewCenterX) { this.mSkewCenterX = pSkewCenterX; + this.updateLocalSkewCenterX(); + this.mLocalToParentTransformationDirty = true; this.mParentToLocalTransformationDirty = true; } @@ -467,6 +617,8 @@ public void setSkewCenterX(final float pSkewCenterX) { public void setSkewCenterY(final float pSkewCenterY) { this.mSkewCenterY = pSkewCenterY; + this.updateLocalSkewCenterY(); + this.mLocalToParentTransformationDirty = true; this.mParentToLocalTransformationDirty = true; } @@ -476,6 +628,8 @@ public void setSkewCenter(final float pSkewCenterX, final float pSkewCenterY) { this.mSkewCenterX = pSkewCenterX; this.mSkewCenterY = pSkewCenterY; + this.updateLocalSkewCenter(); + this.mLocalToParentTransformationDirty = true; this.mParentToLocalTransformationDirty = true; } @@ -485,6 +639,30 @@ public boolean isRotatedOrScaledOrSkewed() { return (this.mRotation != 0) || (this.mScaleX != 1) || (this.mScaleY != 1) || (this.mSkewX != 0) || (this.mSkewY != 0); } + @Override + public void setAnchorCenterX(final float pAnchorCenterX) { + this.setOffsetCenterX(pAnchorCenterX); + this.setRotationCenterX(pAnchorCenterX); + this.setScaleCenterX(pAnchorCenterX); + this.setSkewCenterX(pAnchorCenterX); + } + + @Override + public void setAnchorCenterY(final float pAnchorCenterY) { + this.setOffsetCenterY(pAnchorCenterY); + this.setRotationCenterY(pAnchorCenterY); + this.setScaleCenterY(pAnchorCenterY); + this.setSkewCenterY(pAnchorCenterY); + } + + @Override + public void setAnchorCenter(final float pAnchorCenterX, final float pAnchorCenterY) { + this.setOffsetCenter(pAnchorCenterX, pAnchorCenterY); + this.setRotationCenter(pAnchorCenterX, pAnchorCenterY); + this.setScaleCenter(pAnchorCenterX, pAnchorCenterY); + this.setSkewCenter(pAnchorCenterX, pAnchorCenterY); + } + @Override public float getRed() { return this.mColor.getRed(); @@ -517,12 +695,19 @@ public void setColor(final Color pColor) { this.onUpdateColor(); } + @Override + public void setColor(final int pARGBPackedInt) { + ColorUtils.convertARGBPackedIntToColor(pARGBPackedInt, this.mColor); + + this.onUpdateColor(); + } + /** * @param pRed from 0.0f to 1.0f */ @Override public void setRed(final float pRed) { - if(this.mColor.setRedChecking(pRed)) { + if (this.mColor.setRedChecking(pRed)) { // TODO Is this check worth it? this.onUpdateColor(); } } @@ -532,7 +717,7 @@ public void setRed(final float pRed) { */ @Override public void setGreen(final float pGreen) { - if(this.mColor.setGreenChecking(pGreen)) { + if (this.mColor.setGreenChecking(pGreen)) { // TODO Is this check worth it? this.onUpdateColor(); } } @@ -542,7 +727,7 @@ public void setGreen(final float pGreen) { */ @Override public void setBlue(final float pBlue) { - if(this.mColor.setBlueChecking(pBlue)) { + if (this.mColor.setBlueChecking(pBlue)) { // TODO Is this check worth it? this.onUpdateColor(); } } @@ -552,7 +737,7 @@ public void setBlue(final float pBlue) { */ @Override public void setAlpha(final float pAlpha) { - if(this.mColor.setAlphaChecking(pAlpha)) { + if (this.mColor.setAlphaChecking(pAlpha)) { // TODO Is this check worth it? this.onUpdateColor(); } } @@ -564,7 +749,7 @@ public void setAlpha(final float pAlpha) { */ @Override public void setColor(final float pRed, final float pGreen, final float pBlue) { - if(this.mColor.setChecking(pRed, pGreen, pBlue)) { // TODO Is this check worth it? + if (this.mColor.setChecking(pRed, pGreen, pBlue)) { // TODO Is this check worth it? this.onUpdateColor(); } } @@ -577,14 +762,14 @@ public void setColor(final float pRed, final float pGreen, final float pBlue) { */ @Override public void setColor(final float pRed, final float pGreen, final float pBlue, final float pAlpha) { - if(this.mColor.setChecking(pRed, pGreen, pBlue, pAlpha)) { // TODO Is this check worth it? + if (this.mColor.setChecking(pRed, pGreen, pBlue, pAlpha)) { // TODO Is this check worth it? this.onUpdateColor(); } } @Override public int getChildCount() { - if(this.mChildren == null) { + if (this.mChildren == null) { return 0; } return this.mChildren.size(); @@ -592,12 +777,12 @@ public int getChildCount() { @Override public IEntity getChildByTag(final int pTag) { - if(this.mChildren == null) { + if (this.mChildren == null) { return null; } - for(int i = this.mChildren.size() - 1; i >= 0; i--) { + for (int i = this.mChildren.size() - 1; i >= 0; i--) { final IEntity child = this.mChildren.get(i); - if(child.getTag() == pTag) { + if (child.getTag() == pTag) { return child; } } @@ -606,15 +791,15 @@ public IEntity getChildByTag(final int pTag) { @Override public IEntity getChildByIndex(final int pIndex) { - if(this.mChildren == null) { - return null; - } - return this.mChildren.get(pIndex); + if (this.mChildren == null) { + return null; + } + return this.mChildren.get(pIndex); } @Override public IEntity getChildByMatcher(final IEntityMatcher pEntityMatcher) { - if(this.mChildren == null) { + if (this.mChildren == null) { return null; } return this.mChildren.get(pEntityMatcher); @@ -622,7 +807,7 @@ public IEntity getChildByMatcher(final IEntityMatcher pEntityMatcher) { @Override public IEntity getFirstChild() { - if(this.mChildren == null) { + if (this.mChildren == null) { return null; } return this.mChildren.get(0); @@ -630,7 +815,7 @@ public IEntity getFirstChild() { @Override public IEntity getLastChild() { - if(this.mChildren == null) { + if (this.mChildren == null) { return null; } return this.mChildren.get(this.mChildren.size() - 1); @@ -650,14 +835,14 @@ public IEntity queryFirst(final IEntityMatcher pEntityMatcher) { @Override public S queryFirstForSubclass(final IEntityMatcher pEntityMatcher) { final int childCount = this.getChildCount(); - for(int i = 0; i < childCount; i++) { + for (int i = 0; i < childCount; i++) { final IEntity child = this.mChildren.get(i); - if(pEntityMatcher.matches(child)) { + if (pEntityMatcher.matches(child)) { return (S)child; } final S childQueryFirst = child.queryFirstForSubclass(pEntityMatcher); - if(childQueryFirst != null) { + if (childQueryFirst != null) { return childQueryFirst; } } @@ -668,9 +853,9 @@ public S queryFirstForSubclass(final IEntityMatcher pEntityM @Override public > L query(final IEntityMatcher pEntityMatcher, final L pResult) { final int childCount = this.getChildCount(); - for(int i = 0; i < childCount; i++) { + for (int i = 0; i < childCount; i++) { final IEntity child = this.mChildren.get(i); - if(pEntityMatcher.matches(child)) { + if (pEntityMatcher.matches(child)) { pResult.add(child); } @@ -689,10 +874,10 @@ public ArrayList queryForSubclass(final IEntityMatcher pE @Override public , S extends IEntity> L queryForSubclass(final IEntityMatcher pEntityMatcher, final L pResult) throws ClassCastException { final int childCount = this.getChildCount(); - for(int i = 0; i < childCount; i++) { + for (int i = 0; i < childCount; i++) { final IEntity child = this.mChildren.get(i); - if(pEntityMatcher.matches(child)) { - pResult.add((S)child); + if (pEntityMatcher.matches(child)) { + pResult.add((S) child); } child.queryForSubclass(pEntityMatcher, pResult); @@ -704,7 +889,7 @@ public , S extends IEntity> L queryForSubclass(final IEntityMa @Override public boolean detachSelf() { final IEntity parent = this.mParent; - if(parent != null) { + if (parent != null) { return parent.detachChild(this); } else { return false; @@ -713,7 +898,7 @@ public boolean detachSelf() { @Override public void detachChildren() { - if(this.mChildren == null) { + if (this.mChildren == null) { return; } this.mChildren.clear(Entity.PARAMETERCALLABLE_DETACHCHILD); @@ -723,7 +908,7 @@ public void detachChildren() { public void attachChild(final IEntity pEntity) throws IllegalStateException { this.assertEntityHasNoParent(pEntity); - if(this.mChildren == null) { + if (this.mChildren == null) { this.allocateChildren(); } this.mChildren.add(pEntity); @@ -738,10 +923,10 @@ public void sortChildren() { @Override public void sortChildren(final boolean pImmediate) { - if(this.mChildren == null) { + if (this.mChildren == null) { return; } - if(pImmediate) { + if (pImmediate) { ZIndexSorter.getInstance().sort(this.mChildren); } else { this.mChildrenSortPending = true; @@ -750,7 +935,7 @@ public void sortChildren(final boolean pImmediate) { @Override public void sortChildren(final IEntityComparator pEntityComparator) { - if(this.mChildren == null) { + if (this.mChildren == null) { return; } ZIndexSorter.getInstance().sort(this.mChildren, pEntityComparator); @@ -758,7 +943,7 @@ public void sortChildren(final IEntityComparator pEntityComparator) { @Override public boolean detachChild(final IEntity pEntity) { - if(this.mChildren == null) { + if (this.mChildren == null) { return false; } return this.mChildren.remove(pEntity, Entity.PARAMETERCALLABLE_DETACHCHILD); @@ -766,11 +951,11 @@ public boolean detachChild(final IEntity pEntity) { @Override public IEntity detachChild(final int pTag) { - if(this.mChildren == null) { + if (this.mChildren == null) { return null; } - for(int i = this.mChildren.size() - 1; i >= 0; i--) { - if(this.mChildren.get(i).getTag() == pTag) { + for (int i = this.mChildren.size() - 1; i >= 0; i--) { + if (this.mChildren.get(i).getTag() == pTag) { final IEntity removed = this.mChildren.remove(i); Entity.PARAMETERCALLABLE_DETACHCHILD.call(removed); return removed; @@ -781,7 +966,7 @@ public IEntity detachChild(final int pTag) { @Override public IEntity detachChild(final IEntityMatcher pEntityMatcher) { - if(this.mChildren == null) { + if (this.mChildren == null) { return null; } return this.mChildren.remove(pEntityMatcher, Entity.PARAMETERCALLABLE_DETACHCHILD); @@ -789,7 +974,7 @@ public IEntity detachChild(final IEntityMatcher pEntityMatcher) { @Override public boolean detachChildren(final IEntityMatcher pEntityMatcher) { - if(this.mChildren == null) { + if (this.mChildren == null) { return false; } return this.mChildren.removeAll(pEntityMatcher, Entity.PARAMETERCALLABLE_DETACHCHILD); @@ -797,7 +982,7 @@ public boolean detachChildren(final IEntityMatcher pEntityMatcher) { @Override public void callOnChildren(final IEntityParameterCallable pEntityParameterCallable) { - if(this.mChildren == null) { + if (this.mChildren == null) { return; } this.mChildren.call(pEntityParameterCallable); @@ -805,7 +990,7 @@ public void callOnChildren(final IEntityParameterCallable pEntityParameterCallab @Override public void callOnChildren(final IEntityParameterCallable pEntityParameterCallable, final IEntityMatcher pEntityMatcher) { - if(this.mChildren == null) { + if (this.mChildren == null) { return; } this.mChildren.call(pEntityMatcher, pEntityParameterCallable); @@ -813,7 +998,7 @@ public void callOnChildren(final IEntityParameterCallable pEntityParameterCallab @Override public void registerUpdateHandler(final IUpdateHandler pUpdateHandler) { - if(this.mUpdateHandlers == null) { + if (this.mUpdateHandlers == null) { this.allocateUpdateHandlers(); } this.mUpdateHandlers.add(pUpdateHandler); @@ -821,7 +1006,7 @@ public void registerUpdateHandler(final IUpdateHandler pUpdateHandler) { @Override public boolean unregisterUpdateHandler(final IUpdateHandler pUpdateHandler) { - if(this.mUpdateHandlers == null) { + if (this.mUpdateHandlers == null) { return false; } return this.mUpdateHandlers.remove(pUpdateHandler); @@ -829,15 +1014,23 @@ public boolean unregisterUpdateHandler(final IUpdateHandler pUpdateHandler) { @Override public boolean unregisterUpdateHandlers(final IUpdateHandlerMatcher pUpdateHandlerMatcher) { - if(this.mUpdateHandlers == null) { + if (this.mUpdateHandlers == null) { return false; } return this.mUpdateHandlers.removeAll(pUpdateHandlerMatcher); } + @Override + public int getUpdateHandlerCount() { + if (this.mUpdateHandlers == null) { + return 0; + } + return this.mUpdateHandlers.size(); + } + @Override public void clearUpdateHandlers() { - if(this.mUpdateHandlers == null) { + if (this.mUpdateHandlers == null) { return; } this.mUpdateHandlers.clear(); @@ -845,7 +1038,7 @@ public void clearUpdateHandlers() { @Override public void registerEntityModifier(final IEntityModifier pEntityModifier) { - if(this.mEntityModifiers == null) { + if (this.mEntityModifiers == null) { this.allocateEntityModifiers(); } this.mEntityModifiers.add(pEntityModifier); @@ -853,7 +1046,7 @@ public void registerEntityModifier(final IEntityModifier pEntityModifier) { @Override public boolean unregisterEntityModifier(final IEntityModifier pEntityModifier) { - if(this.mEntityModifiers == null) { + if (this.mEntityModifiers == null) { return false; } return this.mEntityModifiers.remove(pEntityModifier); @@ -861,15 +1054,30 @@ public boolean unregisterEntityModifier(final IEntityModifier pEntityModifier) { @Override public boolean unregisterEntityModifiers(final IEntityModifierMatcher pEntityModifierMatcher) { - if(this.mEntityModifiers == null) { + if (this.mEntityModifiers == null) { return false; } return this.mEntityModifiers.removeAll(pEntityModifierMatcher); } + @Override + public int getEntityModifierCount() { + if (this.mEntityModifiers == null) { + return 0; + } + return this.mEntityModifiers.size(); + } + + @Override + public void resetEntityModifiers() { + if (this.mEntityModifiers != null) { + this.mEntityModifiers.reset(); + } + } + @Override public void clearEntityModifiers() { - if(this.mEntityModifiers == null) { + if (this.mEntityModifiers == null) { return; } this.mEntityModifiers.clear(); @@ -877,30 +1085,30 @@ public void clearEntityModifiers() { @Override public float[] getSceneCenterCoordinates() { - return this.convertLocalToSceneCoordinates(0, 0); + return this.convertLocalCoordinatesToSceneCoordinates(this.mWidth * 0.5f, this.mHeight * 0.5f); } @Override public float[] getSceneCenterCoordinates(final float[] pReuse) { - return this.convertLocalToSceneCoordinates(0, 0, pReuse); + return this.convertLocalCoordinatesToSceneCoordinates(this.mWidth * 0.5f, this.mHeight * 0.5f, pReuse); } @Override public Transformation getLocalToParentTransformation() { - if(this.mLocalToParentTransformation == null) { + if (this.mLocalToParentTransformation == null) { this.mLocalToParentTransformation = new Transformation(); } final Transformation localToParentTransformation = this.mLocalToParentTransformation; - if(this.mLocalToParentTransformationDirty) { + if (this.mLocalToParentTransformationDirty) { localToParentTransformation.setToIdentity(); /* Scale. */ final float scaleX = this.mScaleX; final float scaleY = this.mScaleY; - if((scaleX != 1) || (scaleY != 1)) { - final float scaleCenterX = this.mScaleCenterX; - final float scaleCenterY = this.mScaleCenterY; + if ((scaleX != 1) || (scaleY != 1)) { + final float scaleCenterX = this.mLocalScaleCenterX; + final float scaleCenterY = this.mLocalScaleCenterY; /* TODO Check if it is worth to check for scaleCenterX == 0 && scaleCenterY == 0 as the two postTranslate can be saved. * The same obviously applies for all similar occurrences of this pattern in this class. */ @@ -913,9 +1121,9 @@ public Transformation getLocalToParentTransformation() { /* Skew. */ final float skewX = this.mSkewX; final float skewY = this.mSkewY; - if((skewX != 0) || (skewY != 0)) { - final float skewCenterX = this.mSkewCenterX; - final float skewCenterY = this.mSkewCenterY; + if ((skewX != 0) || (skewY != 0)) { + final float skewCenterX = this.mLocalSkewCenterX; + final float skewCenterY = this.mLocalSkewCenterY; localToParentTransformation.postTranslate(-skewCenterX, -skewCenterY); localToParentTransformation.postSkew(skewX, skewY); @@ -924,18 +1132,21 @@ public Transformation getLocalToParentTransformation() { /* Rotation. */ final float rotation = this.mRotation; - if(rotation != 0) { - final float rotationCenterX = this.mRotationCenterX; - final float rotationCenterY = this.mRotationCenterY; + if (rotation != 0) { + final float rotationCenterX = this.mLocalRotationCenterX; + final float rotationCenterY = this.mLocalRotationCenterY; localToParentTransformation.postTranslate(-rotationCenterX, -rotationCenterY); - localToParentTransformation.postRotate(rotation); + localToParentTransformation.postRotate(-rotation); localToParentTransformation.postTranslate(rotationCenterX, rotationCenterY); } /* Translation. */ localToParentTransformation.postTranslate(this.mX, this.mY); + /* Offset. */ + localToParentTransformation.postTranslate(-this.mLocalOffsetCenterX, -this.mLocalOffsetCenterY); + this.mLocalToParentTransformationDirty = false; } return localToParentTransformation; @@ -943,50 +1154,53 @@ public Transformation getLocalToParentTransformation() { @Override public Transformation getParentToLocalTransformation() { - if(this.mParentToLocalTransformation == null) { + if (this.mParentToLocalTransformation == null) { this.mParentToLocalTransformation = new Transformation(); } final Transformation parentToLocalTransformation = this.mParentToLocalTransformation; - if(this.mParentToLocalTransformationDirty) { + if (this.mParentToLocalTransformationDirty) { parentToLocalTransformation.setToIdentity(); + /* Offset. */ + parentToLocalTransformation.postTranslate(this.mLocalOffsetCenterX, this.mLocalOffsetCenterY); + /* Translation. */ parentToLocalTransformation.postTranslate(-this.mX, -this.mY); /* Rotation. */ final float rotation = this.mRotation; - if(rotation != 0) { - final float rotationCenterX = this.mRotationCenterX; - final float rotationCenterY = this.mRotationCenterY; + if (rotation != 0) { + final float localRotationCenterX = this.mLocalRotationCenterX; + final float localRotationCenterY = this.mLocalRotationCenterY; - parentToLocalTransformation.postTranslate(-rotationCenterX, -rotationCenterY); - parentToLocalTransformation.postRotate(-rotation); - parentToLocalTransformation.postTranslate(rotationCenterX, rotationCenterY); + parentToLocalTransformation.postTranslate(-localRotationCenterX, -localRotationCenterY); + parentToLocalTransformation.postRotate(rotation); + parentToLocalTransformation.postTranslate(localRotationCenterX, localRotationCenterY); } /* Skew. */ final float skewX = this.mSkewX; final float skewY = this.mSkewY; - if((skewX != 0) || (skewY != 0)) { - final float skewCenterX = this.mSkewCenterX; - final float skewCenterY = this.mSkewCenterY; + if ((skewX != 0) || (skewY != 0)) { + final float localSkewCenterX = this.mLocalSkewCenterX; + final float localSkewCenterY = this.mLocalSkewCenterY; - parentToLocalTransformation.postTranslate(-skewCenterX, -skewCenterY); + parentToLocalTransformation.postTranslate(-localSkewCenterX, -localSkewCenterY); parentToLocalTransformation.postSkew(-skewX, -skewY); - parentToLocalTransformation.postTranslate(skewCenterX, skewCenterY); + parentToLocalTransformation.postTranslate(localSkewCenterX, localSkewCenterY); } /* Scale. */ final float scaleX = this.mScaleX; final float scaleY = this.mScaleY; - if((scaleX != 1) || (scaleY != 1)) { - final float scaleCenterX = this.mScaleCenterX; - final float scaleCenterY = this.mScaleCenterY; + if ((scaleX != 1) || (scaleY != 1)) { + final float localScaleCenterX = this.mLocalScaleCenterX; + final float localScaleCenterY = this.mLocalScaleCenterY; - parentToLocalTransformation.postTranslate(-scaleCenterX, -scaleCenterY); + parentToLocalTransformation.postTranslate(-localScaleCenterX, -localScaleCenterY); parentToLocalTransformation.postScale(1 / scaleX, 1 / scaleY); // TODO Division could be replaced by a multiplication of 'scale(X/Y)Inverse'... - parentToLocalTransformation.postTranslate(scaleCenterX, scaleCenterY); + parentToLocalTransformation.postTranslate(localScaleCenterX, localScaleCenterY); } this.mParentToLocalTransformationDirty = false; @@ -996,7 +1210,7 @@ public Transformation getParentToLocalTransformation() { @Override public Transformation getLocalToSceneTransformation() { - if(this.mLocalToSceneTransformation == null) { + if (this.mLocalToSceneTransformation == null) { this.mLocalToSceneTransformation = new Transformation(); } @@ -1005,7 +1219,7 @@ public Transformation getLocalToSceneTransformation() { localToSceneTransformation.setTo(this.getLocalToParentTransformation()); final IEntity parent = this.mParent; - if(parent != null) { + if (parent != null) { localToSceneTransformation.postConcat(parent.getLocalToSceneTransformation()); } @@ -1014,7 +1228,7 @@ public Transformation getLocalToSceneTransformation() { @Override public Transformation getSceneToLocalTransformation() { - if(this.mSceneToLocalTransformation == null) { + if (this.mSceneToLocalTransformation == null) { this.mSceneToLocalTransformation = new Transformation(); } @@ -1023,26 +1237,84 @@ public Transformation getSceneToLocalTransformation() { sceneToLocalTransformation.setTo(this.getParentToLocalTransformation()); final IEntity parent = this.mParent; - if(parent != null) { + if (parent != null) { sceneToLocalTransformation.preConcat(parent.getSceneToLocalTransformation()); } return sceneToLocalTransformation; } - /* (non-Javadoc) - * @see org.andengine.entity.IEntity#convertLocalToSceneCoordinates(float, float) - */ @Override - public float[] convertLocalToSceneCoordinates(final float pX, final float pY) { - return this.convertLocalToSceneCoordinates(pX, pY, Entity.VERTICES_LOCAL_TO_SCENE_TMP); + public float[] convertLocalCoordinatesToParentCoordinates(final float pX, final float pY) { + return this.convertLocalCoordinatesToParentCoordinates(pX, pY, Entity.VERTICES_LOCAL_TO_PARENT_TMP); + } + + @Override + public float[] convertLocalCoordinatesToParentCoordinates(final float pX, final float pY, final float[] pReuse) { + final Transformation localToParentTransformation = this.getLocalToParentTransformation(); + + pReuse[Constants.VERTEX_INDEX_X] = pX; + pReuse[Constants.VERTEX_INDEX_Y] = pY; + + localToParentTransformation.transform(pReuse); + + return pReuse; + } + + @Override + public float[] convertLocalCoordinatesToParentCoordinates(final float[] pCoordinates) { + return this.convertLocalCoordinatesToParentCoordinates(pCoordinates, Entity.VERTICES_LOCAL_TO_PARENT_TMP); + } + + @Override + public float[] convertLocalCoordinatesToParentCoordinates(final float[] pCoordinates, final float[] pReuse) { + final Transformation localToParentTransformation = this.getLocalToParentTransformation(); + + pReuse[Constants.VERTEX_INDEX_X] = pCoordinates[Constants.VERTEX_INDEX_X]; + pReuse[Constants.VERTEX_INDEX_Y] = pCoordinates[Constants.VERTEX_INDEX_Y]; + + localToParentTransformation.transform(pReuse); + + return pReuse; + } + + @Override + public float[] convertParentCoordinatesToLocalCoordinates(final float pX, final float pY) { + return this.convertParentCoordinatesToLocalCoordinates(pX, pY, Entity.VERTICES_PARENT_TO_LOCAL_TMP); + } + + @Override + public float[] convertParentCoordinatesToLocalCoordinates(final float pX, final float pY, final float[] pReuse) { + pReuse[Constants.VERTEX_INDEX_X] = pX; + pReuse[Constants.VERTEX_INDEX_Y] = pY; + + this.getParentToLocalTransformation().transform(pReuse); + + return pReuse; + } + + @Override + public float[] convertParentCoordinatesToLocalCoordinates(final float[] pCoordinates) { + return this.convertParentCoordinatesToLocalCoordinates(pCoordinates, Entity.VERTICES_PARENT_TO_LOCAL_TMP); + } + + @Override + public float[] convertParentCoordinatesToLocalCoordinates(final float[] pCoordinates, final float[] pReuse) { + pReuse[Constants.VERTEX_INDEX_X] = pCoordinates[Constants.VERTEX_INDEX_X]; + pReuse[Constants.VERTEX_INDEX_Y] = pCoordinates[Constants.VERTEX_INDEX_Y]; + + this.getParentToLocalTransformation().transform(pReuse); + + return pReuse; + } + + @Override + public float[] convertLocalCoordinatesToSceneCoordinates(final float pX, final float pY) { + return this.convertLocalCoordinatesToSceneCoordinates(pX, pY, Entity.VERTICES_LOCAL_TO_SCENE_TMP); } - /* (non-Javadoc) - * @see org.andengine.entity.IEntity#convertLocalToSceneCoordinates(float, float, float[]) - */ @Override - public float[] convertLocalToSceneCoordinates(final float pX, final float pY, final float[] pReuse) { + public float[] convertLocalCoordinatesToSceneCoordinates(final float pX, final float pY, final float[] pReuse) { final Transformation localToSceneTransformation = this.getLocalToSceneTransformation(); pReuse[Constants.VERTEX_INDEX_X] = pX; @@ -1053,19 +1325,13 @@ public float[] convertLocalToSceneCoordinates(final float pX, final float pY, fi return pReuse; } - /* (non-Javadoc) - * @see org.andengine.entity.IEntity#convertLocalToSceneCoordinates(float[]) - */ @Override - public float[] convertLocalToSceneCoordinates(final float[] pCoordinates) { - return this.convertSceneToLocalCoordinates(pCoordinates, Entity.VERTICES_LOCAL_TO_SCENE_TMP); + public float[] convertLocalCoordinatesToSceneCoordinates(final float[] pCoordinates) { + return this.convertLocalCoordinatesToSceneCoordinates(pCoordinates, Entity.VERTICES_LOCAL_TO_SCENE_TMP); } - /* (non-Javadoc) - * @see org.andengine.entity.IEntity#convertLocalToSceneCoordinates(float[], float[]) - */ @Override - public float[] convertLocalToSceneCoordinates(final float[] pCoordinates, final float[] pReuse) { + public float[] convertLocalCoordinatesToSceneCoordinates(final float[] pCoordinates, final float[] pReuse) { final Transformation localToSceneTransformation = this.getLocalToSceneTransformation(); pReuse[Constants.VERTEX_INDEX_X] = pCoordinates[Constants.VERTEX_INDEX_X]; @@ -1076,19 +1342,13 @@ public float[] convertLocalToSceneCoordinates(final float[] pCoordinates, final return pReuse; } - /* (non-Javadoc) - * @see org.andengine.entity.IEntity#convertSceneToLocalCoordinates(float, float) - */ @Override - public float[] convertSceneToLocalCoordinates(final float pX, final float pY) { - return this.convertSceneToLocalCoordinates(pX, pY, Entity.VERTICES_SCENE_TO_LOCAL_TMP); + public float[] convertSceneCoordinatesToLocalCoordinates(final float pX, final float pY) { + return this.convertSceneCoordinatesToLocalCoordinates(pX, pY, Entity.VERTICES_SCENE_TO_LOCAL_TMP); } - /* (non-Javadoc) - * @see org.andengine.entity.IEntity#convertSceneToLocalCoordinates(float, float, float[]) - */ @Override - public float[] convertSceneToLocalCoordinates(final float pX, final float pY, final float[] pReuse) { + public float[] convertSceneCoordinatesToLocalCoordinates(final float pX, final float pY, final float[] pReuse) { pReuse[Constants.VERTEX_INDEX_X] = pX; pReuse[Constants.VERTEX_INDEX_Y] = pY; @@ -1097,19 +1357,13 @@ public float[] convertSceneToLocalCoordinates(final float pX, final float pY, fi return pReuse; } - /* (non-Javadoc) - * @see org.andengine.entity.IEntity#convertSceneToLocalCoordinates(float[]) - */ @Override - public float[] convertSceneToLocalCoordinates(final float[] pCoordinates) { - return this.convertSceneToLocalCoordinates(pCoordinates, Entity.VERTICES_SCENE_TO_LOCAL_TMP); + public float[] convertSceneCoordinatesToLocalCoordinates(final float[] pCoordinates) { + return this.convertSceneCoordinatesToLocalCoordinates(pCoordinates, Entity.VERTICES_SCENE_TO_LOCAL_TMP); } - /* (non-Javadoc) - * @see org.andengine.entity.IEntity#convertSceneToLocalCoordinates(float[], float[]) - */ @Override - public float[] convertSceneToLocalCoordinates(final float[] pCoordinates, final float[] pReuse) { + public float[] convertSceneCoordinatesToLocalCoordinates(final float[] pCoordinates, final float[] pReuse) { pReuse[Constants.VERTEX_INDEX_X] = pCoordinates[Constants.VERTEX_INDEX_X]; pReuse[Constants.VERTEX_INDEX_Y] = pCoordinates[Constants.VERTEX_INDEX_Y]; @@ -1140,14 +1394,14 @@ public void setUserData(final Object pUserData) { @Override public final void onDraw(final GLState pGLState, final Camera pCamera) { - if(this.mVisible && !(this.mCullingEnabled && this.isCulled(pCamera))) { + if (this.mVisible && !(this.mCullingEnabled && this.isCulled(pCamera))) { this.onManagedDraw(pGLState, pCamera); } } @Override public final void onUpdate(final float pSecondsElapsed) { - if(!this.mIgnoreUpdate) { + if (!this.mIgnoreUpdate) { this.onManagedUpdate(pSecondsElapsed); } } @@ -1166,23 +1420,26 @@ public void reset() { this.mSkewX = 0; this.mSkewY = 0; + this.resetRotationCenter(); + this.resetSkewCenter(); + this.resetScaleCenter(); + this.mColor.reset(); - if(this.mEntityModifiers != null) { - this.mEntityModifiers.reset(); - } + this.resetEntityModifiers(); - if(this.mChildren != null) { - final SmartList entities = this.mChildren; - for(int i = entities.size() - 1; i >= 0; i--) { - entities.get(i).reset(); + if (this.mChildren != null) { + final SmartList children = this.mChildren; + for (int i = children.size() - 1; i >= 0; i--) { + final IEntity child = children.get(i); + child.reset(); } } } @Override public void dispose() { - if(!this.mDisposed) { + if (!this.mDisposed) { this.mDisposed = true; } else { throw new AlreadyDisposedException(); @@ -1193,7 +1450,7 @@ public void dispose() { protected void finalize() throws Throwable { super.finalize(); - if(!this.mDisposed) { + if (!this.mDisposed) { this.dispose(); } } @@ -1209,16 +1466,21 @@ public String toString() { public void toString(final StringBuilder pStringBuilder) { pStringBuilder.append(this.getClass().getSimpleName()); - if((this.mChildren != null) && (this.mChildren.size() > 0)) { + if ((this.mChildren != null) && (this.mChildren.size() > 0)) { + final SmartList children = this.mChildren; + pStringBuilder.append(" ["); - final SmartList entities = this.mChildren; - for(int i = 0; i < entities.size(); i++) { - entities.get(i).toString(pStringBuilder); - if(i < (entities.size() - 1)) { + + final int childCount = children.size(); + for (int i = 0; i < childCount; i++) { + final IEntity child = children.get(i); + child.toString(pStringBuilder); + + if (i < (childCount - 1)) { pStringBuilder.append(", "); } } - pStringBuilder.append("]"); + pStringBuilder.append(']'); } } @@ -1263,6 +1525,9 @@ private void allocateUpdateHandlers() { } protected void onApplyTransformations(final GLState pGLState) { + /* Offset. */ + this.applyOffset(pGLState); + /* Translation. */ this.applyTranslation(pGLState); @@ -1276,6 +1541,10 @@ protected void onApplyTransformations(final GLState pGLState) { this.applyScale(pGLState); } + protected void applyOffset(final GLState pGLState) { + pGLState.translateModelViewGLMatrixf(-this.mLocalOffsetCenterX, -this.mLocalOffsetCenterY, 0); + } + protected void applyTranslation(final GLState pGLState) { pGLState.translateModelViewGLMatrixf(this.mX, this.mY, 0); } @@ -1283,13 +1552,13 @@ protected void applyTranslation(final GLState pGLState) { protected void applyRotation(final GLState pGLState) { final float rotation = this.mRotation; - if(rotation != 0) { - final float rotationCenterX = this.mRotationCenterX; - final float rotationCenterY = this.mRotationCenterY; + if (rotation != 0) { + final float localRotationCenterX = this.mLocalRotationCenterX; + final float localRotationCenterY = this.mLocalRotationCenterY; - pGLState.translateModelViewGLMatrixf(rotationCenterX, rotationCenterY, 0); - pGLState.rotateModelViewGLMatrixf(rotation, 0, 0, 1); - pGLState.translateModelViewGLMatrixf(-rotationCenterX, -rotationCenterY, 0); + pGLState.translateModelViewGLMatrixf(localRotationCenterX, localRotationCenterY, 0); + pGLState.rotateModelViewGLMatrixf(-rotation, 0, 0, 1); + pGLState.translateModelViewGLMatrixf(-localRotationCenterX, -localRotationCenterY, 0); /* TODO There is a special, but very likely case when mRotationCenter and mScaleCenter are the same. * In that case the last glTranslatef of the rotation and the first glTranslatef of the scale is superfluous. @@ -1301,13 +1570,13 @@ protected void applySkew(final GLState pGLState) { final float skewX = this.mSkewX; final float skewY = this.mSkewY; - if((skewX != 0) || (skewY != 0)) { - final float skewCenterX = this.mSkewCenterX; - final float skewCenterY = this.mSkewCenterY; + if ((skewX != 0) || (skewY != 0)) { + final float localSkewCenterX = this.mLocalSkewCenterX; + final float localSkewCenterY = this.mLocalSkewCenterY; - pGLState.translateModelViewGLMatrixf(skewCenterX, skewCenterY, 0); + pGLState.translateModelViewGLMatrixf(localSkewCenterX, localSkewCenterY, 0); pGLState.skewModelViewGLMatrixf(skewX, skewY); - pGLState.translateModelViewGLMatrixf(-skewCenterX, -skewCenterY, 0); + pGLState.translateModelViewGLMatrixf(-localSkewCenterX, -localSkewCenterY, 0); } } @@ -1315,13 +1584,13 @@ protected void applyScale(final GLState pGLState) { final float scaleX = this.mScaleX; final float scaleY = this.mScaleY; - if((scaleX != 1) || (scaleY != 1)) { - final float scaleCenterX = this.mScaleCenterX; - final float scaleCenterY = this.mScaleCenterY; + if ((scaleX != 1) || (scaleY != 1)) { + final float localScaleCenterX = this.mLocalScaleCenterX; + final float localScaleCenterY = this.mLocalScaleCenterY; - pGLState.translateModelViewGLMatrixf(scaleCenterX, scaleCenterY, 0); + pGLState.translateModelViewGLMatrixf(localScaleCenterX, localScaleCenterY, 0); pGLState.scaleModelViewGLMatrixf(scaleX, scaleY, 1); - pGLState.translateModelViewGLMatrixf(-scaleCenterX, -scaleCenterY, 0); + pGLState.translateModelViewGLMatrixf(-localScaleCenterX, -localScaleCenterY, 0); } } @@ -1331,13 +1600,13 @@ protected void onManagedDraw(final GLState pGLState, final Camera pCamera) { this.onApplyTransformations(pGLState); final SmartList children = this.mChildren; - if((children == null) || !this.mChildrenVisible) { + if ((children == null) || !this.mChildrenVisible) { /* Draw only self. */ this.preDraw(pGLState, pCamera); this.draw(pGLState, pCamera); this.postDraw(pGLState, pCamera); } else { - if(this.mChildrenSortPending) { + if (this.mChildrenSortPending) { ZIndexSorter.getInstance().sort(this.mChildren); this.mChildrenSortPending = false; } @@ -1346,9 +1615,9 @@ protected void onManagedDraw(final GLState pGLState, final Camera pCamera) { int i = 0; { /* Draw children behind this Entity. */ - for(; i < childCount; i++) { + for (; i < childCount; i++) { final IEntity child = children.get(i); - if(child.getZIndex() < 0) { + if (child.getZIndex() < 0) { child.onDraw(pGLState, pCamera); } else { break; @@ -1362,7 +1631,7 @@ protected void onManagedDraw(final GLState pGLState, final Camera pCamera) { this.postDraw(pGLState, pCamera); { /* Draw children in front of this Entity. */ - for(; i < childCount; i++) { + for (; i < childCount; i++) { children.get(i).onDraw(pGLState, pCamera); } } @@ -1372,28 +1641,112 @@ protected void onManagedDraw(final GLState pGLState, final Camera pCamera) { } protected void onManagedUpdate(final float pSecondsElapsed) { - if(this.mEntityModifiers != null) { + if (this.mEntityModifiers != null) { this.mEntityModifiers.onUpdate(pSecondsElapsed); } - if(this.mUpdateHandlers != null) { + if (this.mUpdateHandlers != null) { this.mUpdateHandlers.onUpdate(pSecondsElapsed); } - if((this.mChildren != null) && !this.mChildrenIgnoreUpdate) { - final SmartList entities = this.mChildren; - final int entityCount = entities.size(); - for(int i = 0; i < entityCount; i++) { - entities.get(i).onUpdate(pSecondsElapsed); + if ((this.mChildren != null) && !this.mChildrenIgnoreUpdate) { + final SmartList children = this.mChildren; + final int entityCount = children.size(); + for (int i = 0; i < entityCount; i++) { + final IEntity child = children.get(i); + child.onUpdate(pSecondsElapsed); } } } + protected void updateLocalCenters() { + this.updateLocalCenterXs(); + this.updateLocalCenterYs(); + } + + protected void updateLocalCenterXs() { + this.updateLocalOffsetCenterX(); + this.updateLocalRotationCenterX(); + this.updateLocalScaleCenterX(); + this.updateLocalSkewCenterX(); + } + + protected void updateLocalCenterYs() { + this.updateLocalOffsetCenterY(); + this.updateLocalRotationCenterY(); + this.updateLocalScaleCenterY(); + this.updateLocalSkewCenterY(); + } + + protected void updateLocalOffsetCenter() { + this.updateLocalOffsetCenterX(); + this.updateLocalOffsetCenterY(); + } + + protected void updateLocalOffsetCenterX() { + this.mLocalOffsetCenterX = this.mOffsetCenterX * this.mWidth; + } + + protected void updateLocalOffsetCenterY() { + this.mLocalOffsetCenterY = this.mOffsetCenterY * this.mHeight; + } + + protected void updateLocalRotationCenter() { + this.updateLocalRotationCenterX(); + this.updateLocalRotationCenterY(); + } + + protected void updateLocalRotationCenterX() { + this.mLocalRotationCenterX = this.mRotationCenterX * this.mWidth; + } + + protected void updateLocalRotationCenterY() { + this.mLocalRotationCenterY = this.mRotationCenterY * this.mHeight; + } + + protected void updateLocalScaleCenter() { + this.updateLocalScaleCenterX(); + this.updateLocalScaleCenterY(); + } + + protected void updateLocalScaleCenterX() { + this.mLocalScaleCenterX = this.mScaleCenterX * this.mWidth; + } + + protected void updateLocalScaleCenterY() { + this.mLocalScaleCenterY = this.mScaleCenterY * this.mHeight; + } + + protected void updateLocalSkewCenter() { + this.updateLocalSkewCenterX(); + this.updateLocalSkewCenterY(); + } + + protected void updateLocalSkewCenterX() { + this.mLocalSkewCenterX = this.mSkewCenterX * this.mWidth; + } + + protected void updateLocalSkewCenterY() { + this.mLocalSkewCenterY = this.mSkewCenterY * this.mHeight; + } + + public void resetRotationCenter() { + this.setRotationCenter(IEntity.ROTATION_CENTER_X_DEFAULT, IEntity.ROTATION_CENTER_Y_DEFAULT); + } + + public void resetScaleCenter() { + this.setScaleCenter(IEntity.SCALE_CENTER_X_DEFAULT, IEntity.SCALE_CENTER_Y_DEFAULT); + } + + public void resetSkewCenter() { + this.setSkewCenter(IEntity.SKEW_CENTER_X_DEFAULT, IEntity.SKEW_CENTER_Y_DEFAULT); + } + private void assertEntityHasNoParent(final IEntity pEntity) throws IllegalStateException { - if(pEntity.hasParent()) { + if (pEntity.hasParent()) { final String entityClassName = pEntity.getClass().getSimpleName(); final String currentParentClassName = pEntity.getParent().getClass().getSimpleName(); final String newParentClassName = this.getClass().getSimpleName(); - throw new IllegalStateException("pEntity '" + entityClassName +"' already has a parent: '" + currentParentClassName + "'. New parent: '" + newParentClassName + "'!"); + throw new IllegalStateException("pEntity '" + entityClassName + "' already has a parent: '" + currentParentClassName + "'. New parent: '" + newParentClassName + "'!"); } } diff --git a/src/org/andengine/entity/IEntity.java b/src/org/andengine/entity/IEntity.java index 1e3fa1919..ab8b2779c 100644 --- a/src/org/andengine/entity/IEntity.java +++ b/src/org/andengine/entity/IEntity.java @@ -11,25 +11,44 @@ import org.andengine.engine.handler.runnable.RunnableHandler; import org.andengine.entity.modifier.IEntityModifier; import org.andengine.entity.modifier.IEntityModifier.IEntityModifierMatcher; +import org.andengine.entity.scene.ITouchArea; import org.andengine.entity.scene.Scene; import org.andengine.util.IDisposable; +import org.andengine.util.adt.color.Color; import org.andengine.util.adt.transformation.Transformation; -import org.andengine.util.color.Color; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 11:20:25 - 08.03.2010 */ -public interface IEntity extends IDrawHandler, IUpdateHandler, IDisposable { +public interface IEntity extends IDrawHandler, IUpdateHandler, IDisposable, ITouchArea { // =========================================================== // Constants // =========================================================== - public static final int TAG_INVALID = Integer.MIN_VALUE; + public static final int TAG_DEFAULT = 0; + public static final int ZINDEX_DEFAULT = 0; + + public static final float OFFSET_CENTER_X_DEFAULT = 0.5f; + public static final float OFFSET_CENTER_Y_DEFAULT = 0.5f; + + public static final float ROTATION_DEFAULT = 0; + public static final float ROTATION_CENTER_X_DEFAULT = 0.5f; + public static final float ROTATION_CENTER_Y_DEFAULT = 0.5f; + + public static final float SCALE_X_DEFAULT = 1; + public static final float SCALE_Y_DEFAULT = 1; + public static final float SCALE_CENTER_X_DEFAULT = 0.5f; + public static final float SCALE_CENTER_Y_DEFAULT = 0.5f; + + public static final float SKEW_X_DEFAULT = 0; + public static final float SKEW_Y_DEFAULT = 0; + public static final float SKEW_CENTER_X_DEFAULT = 0.5f; + public static final float SKEW_CENTER_Y_DEFAULT = 0.5f; // =========================================================== // Methods @@ -57,6 +76,8 @@ public interface IEntity extends IDrawHandler, IUpdateHandler, IDisposable { public IEntity getParent(); public void setParent(final IEntity pEntity); + public IEntity getRootEntity(); + public float getX(); public float getY(); public void setX(final float pX); @@ -65,6 +86,32 @@ public interface IEntity extends IDrawHandler, IUpdateHandler, IDisposable { public void setPosition(final IEntity pOtherEntity); public void setPosition(final float pX, final float pY); + public float getWidth(); + public float getHeight(); + + /** + * It is very likely you do NOT want to use this method! + * @return + */ + @Deprecated + public float getWidthScaled(); + /** + * It is very likely you do NOT want to use this method! + * @return + */ + @Deprecated + public float getHeightScaled(); + + public void setHeight(final float pHeight); + public void setWidth(final float pWidth); + public void setSize(final float pWidth, final float pHeight); + + public float getOffsetCenterX(); + public float getOffsetCenterY(); + public void setOffsetCenterX(final float pOffsetCenterX); + public void setOffsetCenterY(final float pOffsetCenterY); + public void setOffsetCenter(final float pOffsetCenterX, final float pOffsetCenterY); + public boolean isRotated(); public float getRotation(); public void setRotation(final float pRotation); @@ -103,7 +150,11 @@ public interface IEntity extends IDrawHandler, IUpdateHandler, IDisposable { public void setSkewCenterY(final float pSkewCenterY); public void setSkewCenter(final float pSkewCenterX, final float pSkewCenterY); - public boolean isRotatedOrScaledOrSkewed(); + public boolean isRotatedOrScaledOrSkewed(); // TODO What about the new offset? + + public void setAnchorCenterX(final float pAnchorCenterX); + public void setAnchorCenterY(final float pAnchorCenterY); + public void setAnchorCenter(final float pAnchorCenterX, final float pAnchorCenterY); public float getRed(); public float getGreen(); @@ -116,6 +167,7 @@ public interface IEntity extends IDrawHandler, IUpdateHandler, IDisposable { public void setBlue(final float pBlue); public void setAlpha(final float pAlpha); public void setColor(final Color pColor); + public void setColor(final int pARGBPackedInt); public void setColor(final float pRed, final float pGreen, final float pBlue); public void setColor(final float pRed, final float pGreen, final float pBlue, final float pAlpha); @@ -135,50 +187,100 @@ public interface IEntity extends IDrawHandler, IUpdateHandler, IDisposable { * @param pY * @return a shared(!) float[] of length 2. */ - public float[] convertLocalToSceneCoordinates(final float pX, final float pY); + public float[] convertLocalCoordinatesToParentCoordinates(final float pX, final float pY); /** * @param pX * @param pY * @param pReuse must be of length 2. * @return pReuse as a convenience. */ - public float[] convertLocalToSceneCoordinates(final float pX, final float pY, final float[] pReuse); + public float[] convertLocalCoordinatesToParentCoordinates(final float pX, final float pY, final float[] pReuse); /** * @param pCoordinates must be of length 2. * @return a shared(!) float[] of length 2. */ - public float[] convertLocalToSceneCoordinates(final float[] pCoordinates); + public float[] convertLocalCoordinatesToParentCoordinates(final float[] pCoordinates); /** * @param pCoordinates must be of length 2. * @param pReuse must be of length 2. * @return pReuse as a convenience. */ - public float[] convertLocalToSceneCoordinates(final float[] pCoordinates, final float[] pReuse); + public float[] convertLocalCoordinatesToParentCoordinates(final float[] pCoordinates, final float[] pReuse); /** * @param pX * @param pY * @return a shared(!) float[] of length 2. */ - public float[] convertSceneToLocalCoordinates(final float pX, final float pY); + public float[] convertParentCoordinatesToLocalCoordinates(final float pX, final float pY); /** * @param pX * @param pY * @param pReuse must be of length 2. * @return pReuse as a convenience. */ - public float[] convertSceneToLocalCoordinates(final float pX, final float pY, final float[] pReuse); + public float[] convertParentCoordinatesToLocalCoordinates(final float pX, final float pY, final float[] pReuse); /** * @param pCoordinates must be of length 2. * @return a shared(!) float[] of length 2. */ - public float[] convertSceneToLocalCoordinates(final float[] pCoordinates); + public float[] convertParentCoordinatesToLocalCoordinates(final float[] pCoordinates); /** * @param pCoordinates must be of length 2. * @param pReuse must be of length 2. * @return pReuse as a convenience. */ - public float[] convertSceneToLocalCoordinates(final float[] pCoordinates, final float[] pReuse); + public float[] convertParentCoordinatesToLocalCoordinates(final float[] pCoordinates, final float[] pReuse); + + /** + * @param pX + * @param pY + * @return a shared(!) float[] of length 2. + */ + public float[] convertLocalCoordinatesToSceneCoordinates(final float pX, final float pY); + /** + * @param pX + * @param pY + * @param pReuse must be of length 2. + * @return pReuse as a convenience. + */ + public float[] convertLocalCoordinatesToSceneCoordinates(final float pX, final float pY, final float[] pReuse); + /** + * @param pCoordinates must be of length 2. + * @return a shared(!) float[] of length 2. + */ + public float[] convertLocalCoordinatesToSceneCoordinates(final float[] pCoordinates); + /** + * @param pCoordinates must be of length 2. + * @param pReuse must be of length 2. + * @return pReuse as a convenience. + */ + public float[] convertLocalCoordinatesToSceneCoordinates(final float[] pCoordinates, final float[] pReuse); + + /** + * @param pX + * @param pY + * @return a shared(!) float[] of length 2. + */ + public float[] convertSceneCoordinatesToLocalCoordinates(final float pX, final float pY); + /** + * @param pX + * @param pY + * @param pReuse must be of length 2. + * @return pReuse as a convenience. + */ + public float[] convertSceneCoordinatesToLocalCoordinates(final float pX, final float pY, final float[] pReuse); + /** + * @param pCoordinates must be of length 2. + * @return a shared(!) float[] of length 2. + */ + public float[] convertSceneCoordinatesToLocalCoordinates(final float[] pCoordinates); + /** + * @param pCoordinates must be of length 2. + * @param pReuse must be of length 2. + * @return pReuse as a convenience. + */ + public float[] convertSceneCoordinatesToLocalCoordinates(final float[] pCoordinates, final float[] pReuse); public Transformation getLocalToSceneTransformation(); public Transformation getSceneToLocalTransformation(); @@ -241,9 +343,9 @@ public interface IEntity extends IDrawHandler, IUpdateHandler, IDisposable { public void sortChildren(); /** * Sorts the {@link IEntity}s based on their ZIndex. Sort is stable. - * In contrast to {@link IEntity#sortChildren()} this method is particularly useful to avoid multiple sorts per frame. + * In contrast to {@link #sortChildren()} this method is particularly useful to avoid multiple sorts per frame. * @param pImmediate if true, the sorting is executed immediately. - * If false the sorting is executed before the next (visible) drawing of the children of this {@link IEntity}. + * If false the sorting is executed before the next (visible) drawing of the children of this {@link IEntity}. */ public void sortChildren(final boolean pImmediate); /** @@ -295,23 +397,28 @@ public interface IEntity extends IDrawHandler, IUpdateHandler, IDisposable { public void registerUpdateHandler(final IUpdateHandler pUpdateHandler); public boolean unregisterUpdateHandler(final IUpdateHandler pUpdateHandler); public boolean unregisterUpdateHandlers(final IUpdateHandlerMatcher pUpdateHandlerMatcher); + public int getUpdateHandlerCount(); public void clearUpdateHandlers(); public void registerEntityModifier(final IEntityModifier pEntityModifier); public boolean unregisterEntityModifier(final IEntityModifier pEntityModifier); public boolean unregisterEntityModifiers(final IEntityModifierMatcher pEntityModifierMatcher); + public int getEntityModifierCount(); + public void resetEntityModifiers(); public void clearEntityModifiers(); public boolean isCullingEnabled(); public void setCullingEnabled(final boolean pCullingEnabled); /** - * Will only be performed if {@link IEntity#isCullingEnabled()} is true. + * Will only be performed if {@link #isCullingEnabled()} is true. * * @param pCamera the currently active camera to perform culling checks against. * @return true when this object is visible by the {@link Camera}, false otherwise. */ public boolean isCulled(final Camera pCamera); + public boolean collidesWith(final IEntity pOtherEntity); + public void setUserData(final Object pUserData); public Object getUserData(); diff --git a/src/org/andengine/entity/IEntityComparator.java b/src/org/andengine/entity/IEntityComparator.java index ee8b5b444..6982da43b 100644 --- a/src/org/andengine/entity/IEntityComparator.java +++ b/src/org/andengine/entity/IEntityComparator.java @@ -3,7 +3,7 @@ import java.util.Comparator; /** - * (c) Zynga 2012 + * (c) 2012 Zynga Inc. * * @author Nicolas Gramlich * @since 14:02:56 - 10.04.2012 diff --git a/src/org/andengine/entity/IEntityFactory.java b/src/org/andengine/entity/IEntityFactory.java index 02072e318..538081715 100644 --- a/src/org/andengine/entity/IEntityFactory.java +++ b/src/org/andengine/entity/IEntityFactory.java @@ -2,12 +2,12 @@ /** - * (c) Zynga 2011 + * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 20:04:41 - 19.11.2011 */ -public interface IEntityFactory { +public interface IEntityFactory { // =========================================================== // Constants // =========================================================== diff --git a/src/org/andengine/entity/IEntityMatcher.java b/src/org/andengine/entity/IEntityMatcher.java index 11cf25865..41477c68e 100644 --- a/src/org/andengine/entity/IEntityMatcher.java +++ b/src/org/andengine/entity/IEntityMatcher.java @@ -3,7 +3,7 @@ import org.andengine.util.IMatcher; /** - * (c) Zynga 2012 + * (c) 2012 Zynga Inc. * * @author Nicolas Gramlich * @since 20:06:28 - 26.03.2012 diff --git a/src/org/andengine/entity/IEntityParameterCallable.java b/src/org/andengine/entity/IEntityParameterCallable.java index 7a5d08808..325fe32dc 100644 --- a/src/org/andengine/entity/IEntityParameterCallable.java +++ b/src/org/andengine/entity/IEntityParameterCallable.java @@ -3,7 +3,7 @@ import org.andengine.util.call.ParameterCallable; /** - * (c) Zynga 2012 + * (c) 2012 Zynga Inc. * * @author Nicolas Gramlich * @since 20:06:53 - 26.03.2012 diff --git a/src/org/andengine/entity/TagEntityMatcher.java b/src/org/andengine/entity/TagEntityMatcher.java index 7d516a5ef..c18ad601a 100644 --- a/src/org/andengine/entity/TagEntityMatcher.java +++ b/src/org/andengine/entity/TagEntityMatcher.java @@ -1,7 +1,7 @@ package org.andengine.entity; /** - * (c) Zynga 2012 + * (c) 2012 Zynga Inc. * * @author Nicolas Gramlich * @since 15:49:11 - 01.05.2012 diff --git a/src/org/andengine/entity/ZIndexSorter.java b/src/org/andengine/entity/ZIndexSorter.java index 33d5e8972..031ac78f9 100644 --- a/src/org/andengine/entity/ZIndexSorter.java +++ b/src/org/andengine/entity/ZIndexSorter.java @@ -7,8 +7,8 @@ import org.andengine.util.algorithm.sort.InsertionSorter; /** - * (c) Nicolas Gramlich 2010 - * (c) Zynga 2011 + * (c) 2010 Nicolas Gramlich + * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 12:08:56 - 06.08.2010 @@ -40,7 +40,7 @@ private ZIndexSorter() { } public static ZIndexSorter getInstance() { - if(INSTANCE == null) { + if (INSTANCE == null) { INSTANCE = new ZIndexSorter(); } return INSTANCE; diff --git a/src/org/andengine/entity/clip/ClipEntity.java b/src/org/andengine/entity/clip/ClipEntity.java new file mode 100644 index 000000000..d8aa4d50f --- /dev/null +++ b/src/org/andengine/entity/clip/ClipEntity.java @@ -0,0 +1,121 @@ +package org.andengine.entity.clip; + +import org.andengine.engine.camera.Camera; +import org.andengine.entity.Entity; +import org.andengine.opengl.util.GLState; +import org.andengine.util.Constants; +import org.andengine.util.math.MathUtils; + +/** + * A {@link ClipEntity} clips drawing of all its children in a rectangle, which is defined as the axis aligned bounding box around itself. + * It can be attached anywhere in the scene graph, which means that it inherits transformations from its parents, which have a direct effect on the clipping area. + * + * (c) 2012 Zynga Inc. + * + * @author Nicolas Gramlich + * @since 13:53:29 - 10.05.2012 + */ +public class ClipEntity extends Entity { + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + private boolean mClippingEnabled = true; + + // =========================================================== + // Constructors + // =========================================================== + + public ClipEntity() { + super(); + } + + public ClipEntity(final float pX, final float pY) { + super(pX, pY); + } + + public ClipEntity(final float pX, final float pY, final float pWidth, final float pHeight) { + super(pX, pY, pWidth, pHeight); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + public boolean isClippingEnabled() { + return this.mClippingEnabled; + } + + public void setClippingEnabled(final boolean pClippingEnabled) { + this.mClippingEnabled = pClippingEnabled; + } + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + protected void onManagedDraw(final GLState pGLState, final Camera pCamera) { + if (this.mClippingEnabled) { + /* Enable scissor test, while remembering previous state. */ + final boolean wasScissorTestEnabled = pGLState.enableScissorTest(); + + final int surfaceHeight = pCamera.getSurfaceHeight(); + + /* In order to apply clipping, we need to determine the the axis aligned bounds in OpenGL coordinates. */ + + /* Determine clipping coordinates of each corner in surface coordinates. */ + final float[] lowerLeftSurfaceCoordinates = pCamera.getSurfaceCoordinatesFromSceneCoordinates(this.convertLocalCoordinatesToSceneCoordinates(0, 0)); + final int lowerLeftX = (int) Math.round(lowerLeftSurfaceCoordinates[Constants.VERTEX_INDEX_X]); + final int lowerLeftY = surfaceHeight - (int) Math.round(lowerLeftSurfaceCoordinates[Constants.VERTEX_INDEX_Y]); + + final float[] upperLeftSurfaceCoordinates = pCamera.getSurfaceCoordinatesFromSceneCoordinates(this.convertLocalCoordinatesToSceneCoordinates(0, this.mHeight)); + final int upperLeftX = (int) Math.round(upperLeftSurfaceCoordinates[Constants.VERTEX_INDEX_X]); + final int upperLeftY = surfaceHeight - (int) Math.round(upperLeftSurfaceCoordinates[Constants.VERTEX_INDEX_Y]); + + final float[] upperRightSurfaceCoordinates = pCamera.getSurfaceCoordinatesFromSceneCoordinates(this.convertLocalCoordinatesToSceneCoordinates(this.mWidth, this.mHeight)); + final int upperRightX = (int) Math.round(upperRightSurfaceCoordinates[Constants.VERTEX_INDEX_X]); + final int upperRightY = surfaceHeight - (int) Math.round(upperRightSurfaceCoordinates[Constants.VERTEX_INDEX_Y]); + + final float[] lowerRightSurfaceCoordinates = pCamera.getSurfaceCoordinatesFromSceneCoordinates(this.convertLocalCoordinatesToSceneCoordinates(this.mWidth, 0)); + final int lowerRightX = (int) Math.round(lowerRightSurfaceCoordinates[Constants.VERTEX_INDEX_X]); + final int lowerRightY = surfaceHeight - (int) Math.round(lowerRightSurfaceCoordinates[Constants.VERTEX_INDEX_Y]); + + /* Determine minimum and maximum x clipping coordinates. */ + final int minClippingX = MathUtils.min(lowerLeftX, upperLeftX, upperRightX, lowerRightX); + final int maxClippingX = MathUtils.max(lowerLeftX, upperLeftX, upperRightX, lowerRightX); + + /* Determine minimum and maximum y clipping coordinates. */ + final int minClippingY = MathUtils.min(lowerLeftY, upperLeftY, upperRightY, lowerRightY); + final int maxClippingY = MathUtils.max(lowerLeftY, upperLeftY, upperRightY, lowerRightY); + + /* Determine clipping width and height. */ + final int clippingWidth = maxClippingX - minClippingX; + final int clippingHeight = maxClippingY - minClippingY; + + /* Finally apply the clipping. */ + pGLState.glPushScissor(minClippingX, minClippingY, clippingWidth, clippingHeight); + + /* Draw children, etc... */ + super.onManagedDraw(pGLState, pCamera); + + /* Revert scissor test to previous state. */ + pGLState.glPopScissor(); + pGLState.setScissorTestEnabled(wasScissorTestEnabled); + } else { + super.onManagedDraw(pGLState, pCamera); + } + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== +} diff --git a/src/org/andengine/entity/modifier/AlphaModifier.java b/src/org/andengine/entity/modifier/AlphaModifier.java index ce905b317..f25a37c22 100644 --- a/src/org/andengine/entity/modifier/AlphaModifier.java +++ b/src/org/andengine/entity/modifier/AlphaModifier.java @@ -5,9 +5,9 @@ import org.andengine.util.modifier.ease.IEaseFunction; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 23:13:01 - 19.03.2010 */ @@ -45,7 +45,7 @@ protected AlphaModifier(final AlphaModifier pAlphaModifier) { } @Override - public AlphaModifier deepCopy(){ + public AlphaModifier deepCopy() { return new AlphaModifier(this); } diff --git a/src/org/andengine/entity/modifier/CardinalSplineMoveModifier.java b/src/org/andengine/entity/modifier/CardinalSplineMoveModifier.java index c0c6e977d..09fd5f2f5 100644 --- a/src/org/andengine/entity/modifier/CardinalSplineMoveModifier.java +++ b/src/org/andengine/entity/modifier/CardinalSplineMoveModifier.java @@ -7,12 +7,13 @@ import org.andengine.util.modifier.ease.IEaseFunction; /** - * (c) Zynga 2012 + * (c) 2012 Zynga Inc. * * @author Nicolas Gramlich * @since 11:47:24 - 20.03.2012 - * @see {@link http://en.wikipedia.org/wiki/Cubic_Hermite_spline#Cardinal_spline} - * @see {@link http://algorithmist.wordpress.com/2009/10/06/cardinal-splines-part-4/} + * + * @see en.wikipedia.org/wiki/Cubic_Hermite_spline#Cardinal_spline + * @see algorithmist.wordpress.com/2009/10/06/cardinal-splines-part-4/ */ public class CardinalSplineMoveModifier extends DurationEntityModifier { // =========================================================== @@ -84,7 +85,7 @@ protected void onManagedUpdate(final float pSecondsElapsed, final IEntity pEntit /* Calculate active control point. */ final int p; - if(percentageDone == 1) { + if (percentageDone == 1) { p = this.mControlSegmentCount; } else { p = (int) (percentageDone / this.mControlSegmentCountInverse); @@ -192,7 +193,7 @@ public static class CardinalSplineMoveModifierConfig { * @param pTension [-1, 1] */ public CardinalSplineMoveModifierConfig(final int pControlPointCount, final float pTension) { - if(pControlPointCount < CardinalSplineMoveModifierConfig.CONTROLPOINT_COUNT_MINIMUM) { + if (pControlPointCount < CardinalSplineMoveModifierConfig.CONTROLPOINT_COUNT_MINIMUM) { throw new IllegalArgumentException("A " + CardinalSplineMoveModifierConfig.class.getSimpleName() + " needs at least " + CardinalSplineMoveModifierConfig.CONTROLPOINT_COUNT_MINIMUM + " control points."); } diff --git a/src/org/andengine/entity/modifier/CatmullRomSplineMoveModifier.java b/src/org/andengine/entity/modifier/CatmullRomSplineMoveModifier.java index afc63f38b..f7c4da57c 100644 --- a/src/org/andengine/entity/modifier/CatmullRomSplineMoveModifier.java +++ b/src/org/andengine/entity/modifier/CatmullRomSplineMoveModifier.java @@ -3,7 +3,7 @@ import org.andengine.util.modifier.ease.IEaseFunction; /** - * (c) Zynga 2012 + * (c) 2012 Zynga Inc. * * @author Nicolas Gramlich * @since 11:51:22 - 21.03.2012 @@ -53,7 +53,7 @@ public CatmullRomSplineMoveModifier(final float pDuration, final CatmullRomMoveM // Inner and Anonymous Classes // =========================================================== - public class CatmullRomMoveModifierConfig extends CardinalSplineMoveModifierConfig { + public static class CatmullRomMoveModifierConfig extends CardinalSplineMoveModifierConfig { // =========================================================== // Constants // =========================================================== diff --git a/src/org/andengine/entity/modifier/ColorModifier.java b/src/org/andengine/entity/modifier/ColorModifier.java index e230dcf76..e482502e3 100644 --- a/src/org/andengine/entity/modifier/ColorModifier.java +++ b/src/org/andengine/entity/modifier/ColorModifier.java @@ -1,14 +1,14 @@ package org.andengine.entity.modifier; import org.andengine.entity.IEntity; -import org.andengine.util.color.Color; +import org.andengine.util.adt.color.Color; import org.andengine.util.modifier.ease.EaseLinear; import org.andengine.util.modifier.ease.IEaseFunction; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 15:39:50 - 29.06.2010 */ @@ -62,7 +62,7 @@ protected ColorModifier(final ColorModifier pColorModifier) { } @Override - public ColorModifier deepCopy(){ + public ColorModifier deepCopy() { return new ColorModifier(this); } diff --git a/src/org/andengine/entity/modifier/CubicBezierCurveMoveModifier.java b/src/org/andengine/entity/modifier/CubicBezierCurveMoveModifier.java index 343b74458..4a6542d4c 100644 --- a/src/org/andengine/entity/modifier/CubicBezierCurveMoveModifier.java +++ b/src/org/andengine/entity/modifier/CubicBezierCurveMoveModifier.java @@ -7,7 +7,7 @@ /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Pawel Plewa * @author Nicolas Gramlich * @since 23:24:26 - 16.07.2011 @@ -126,7 +126,7 @@ public CubicBezierCurveMoveModifier deepCopy() { @Override protected void onManagedInitialize(final IEntity pEntity) { - + } @Override diff --git a/src/org/andengine/entity/modifier/DelayModifier.java b/src/org/andengine/entity/modifier/DelayModifier.java index 8366fed65..f66c61138 100644 --- a/src/org/andengine/entity/modifier/DelayModifier.java +++ b/src/org/andengine/entity/modifier/DelayModifier.java @@ -3,9 +3,9 @@ import org.andengine.entity.IEntity; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 22:55:13 - 19.03.2010 */ @@ -35,7 +35,7 @@ protected DelayModifier(final DelayModifier pDelayModifier) { } @Override - public DelayModifier deepCopy(){ + public DelayModifier deepCopy() { return new DelayModifier(this); } diff --git a/src/org/andengine/entity/modifier/DoubleValueChangeEntityModifier.java b/src/org/andengine/entity/modifier/DoubleValueChangeEntityModifier.java index 45225ce83..b17ff5656 100644 --- a/src/org/andengine/entity/modifier/DoubleValueChangeEntityModifier.java +++ b/src/org/andengine/entity/modifier/DoubleValueChangeEntityModifier.java @@ -4,7 +4,7 @@ import org.andengine.util.modifier.BaseDoubleValueChangeModifier; /** - * (c) Zynga 2011 + * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 14:27:48 - 10.08.2011 diff --git a/src/org/andengine/entity/modifier/DoubleValueSpanEntityModifier.java b/src/org/andengine/entity/modifier/DoubleValueSpanEntityModifier.java index 6158e9fdd..a5b87712d 100644 --- a/src/org/andengine/entity/modifier/DoubleValueSpanEntityModifier.java +++ b/src/org/andengine/entity/modifier/DoubleValueSpanEntityModifier.java @@ -5,9 +5,9 @@ import org.andengine.util.modifier.ease.IEaseFunction; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 23:29:22 - 19.03.2010 */ diff --git a/src/org/andengine/entity/modifier/DurationEntityModifier.java b/src/org/andengine/entity/modifier/DurationEntityModifier.java index bf751878a..01f3ef530 100644 --- a/src/org/andengine/entity/modifier/DurationEntityModifier.java +++ b/src/org/andengine/entity/modifier/DurationEntityModifier.java @@ -4,9 +4,9 @@ import org.andengine.util.modifier.BaseDurationModifier; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 16:10:42 - 19.03.2010 */ diff --git a/src/org/andengine/entity/modifier/EntityModifier.java b/src/org/andengine/entity/modifier/EntityModifier.java index 1953a6722..fc8d7c80a 100644 --- a/src/org/andengine/entity/modifier/EntityModifier.java +++ b/src/org/andengine/entity/modifier/EntityModifier.java @@ -4,9 +4,9 @@ import org.andengine.util.modifier.BaseModifier; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 10:53:16 - 03.09.2010 */ diff --git a/src/org/andengine/entity/modifier/EntityModifierList.java b/src/org/andengine/entity/modifier/EntityModifierList.java index 1af8dcd9a..70bafd2eb 100644 --- a/src/org/andengine/entity/modifier/EntityModifierList.java +++ b/src/org/andengine/entity/modifier/EntityModifierList.java @@ -4,9 +4,9 @@ import org.andengine.util.modifier.ModifierList; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 14:19:18 - 24.12.2010 */ diff --git a/src/org/andengine/entity/modifier/FadeInModifier.java b/src/org/andengine/entity/modifier/FadeInModifier.java index 40c98e579..6c40b4e22 100644 --- a/src/org/andengine/entity/modifier/FadeInModifier.java +++ b/src/org/andengine/entity/modifier/FadeInModifier.java @@ -5,9 +5,9 @@ /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 19:03:12 - 08.06.2010 */ diff --git a/src/org/andengine/entity/modifier/FadeOutModifier.java b/src/org/andengine/entity/modifier/FadeOutModifier.java index e89a9fb14..e325875ae 100644 --- a/src/org/andengine/entity/modifier/FadeOutModifier.java +++ b/src/org/andengine/entity/modifier/FadeOutModifier.java @@ -5,9 +5,9 @@ /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 19:03:12 - 08.06.2010 */ diff --git a/src/org/andengine/entity/modifier/IEntityModifier.java b/src/org/andengine/entity/modifier/IEntityModifier.java index d7167d180..3ac327a21 100644 --- a/src/org/andengine/entity/modifier/IEntityModifier.java +++ b/src/org/andengine/entity/modifier/IEntityModifier.java @@ -5,9 +5,9 @@ import org.andengine.util.modifier.IModifier; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 11:17:50 - 19.03.2010 */ @@ -19,7 +19,7 @@ public interface IEntityModifier extends IModifier { // =========================================================== // Methods // =========================================================== - + @Override public IEntityModifier deepCopy() throws DeepCopyNotSupportedException; @@ -27,7 +27,7 @@ public interface IEntityModifier extends IModifier { // Inner and Anonymous Classes // =========================================================== - public static interface IEntityModifierListener extends IModifierListener{ + public static interface IEntityModifierListener extends IModifierListener { // =========================================================== // Constants // =========================================================== @@ -36,7 +36,7 @@ public static interface IEntityModifierListener extends IModifierListener> { // =========================================================== // Constants diff --git a/src/org/andengine/entity/modifier/JumpModifier.java b/src/org/andengine/entity/modifier/JumpModifier.java index a98f444dd..96d732bd7 100644 --- a/src/org/andengine/entity/modifier/JumpModifier.java +++ b/src/org/andengine/entity/modifier/JumpModifier.java @@ -5,7 +5,7 @@ import org.andengine.util.modifier.ease.IEaseFunction; /** - * (c) Zynga 2012 + * (c) 2012 Zynga Inc. * * @author Nicolas Gramlich * @since 12:12:55 - 11.01.2012 @@ -57,7 +57,7 @@ public JumpModifier(final float pDuration, final float pFromX, final float pToX, } public JumpModifier(final float pDuration, final float pFromX, final float pToX, final float pFromY, final float pToY, final float pJumpHeight, final int pJumpCount, final IEntityModifierListener pEntityModifierListener, final IEaseFunction pEaseFunction) { - super(pDuration, pFromX, pToX, pFromY, pToY, pEntityModifierListener, pEaseFunction); + super(pDuration, pFromX, pFromY, pToX, pToY, pEntityModifierListener, pEaseFunction); this.mJumpHeight = pJumpHeight; this.mJumpCount = pJumpCount; diff --git a/src/org/andengine/entity/modifier/LoopEntityModifier.java b/src/org/andengine/entity/modifier/LoopEntityModifier.java index 1f5fde527..6eb8638e4 100644 --- a/src/org/andengine/entity/modifier/LoopEntityModifier.java +++ b/src/org/andengine/entity/modifier/LoopEntityModifier.java @@ -4,9 +4,9 @@ import org.andengine.util.modifier.LoopModifier; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 12:42:13 - 03.09.2010 */ diff --git a/src/org/andengine/entity/modifier/MoveByModifier.java b/src/org/andengine/entity/modifier/MoveByModifier.java index 571d8a7b5..535fd1ee3 100644 --- a/src/org/andengine/entity/modifier/MoveByModifier.java +++ b/src/org/andengine/entity/modifier/MoveByModifier.java @@ -4,7 +4,7 @@ /** * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 14:15:52 - 10.08.2011 */ @@ -34,7 +34,7 @@ protected MoveByModifier(final DoubleValueChangeEntityModifier pDoubleValueChang } @Override - public MoveByModifier deepCopy(){ + public MoveByModifier deepCopy() { return new MoveByModifier(this); } diff --git a/src/org/andengine/entity/modifier/MoveModifier.java b/src/org/andengine/entity/modifier/MoveModifier.java index 6cd19afc0..f4abbb4e9 100644 --- a/src/org/andengine/entity/modifier/MoveModifier.java +++ b/src/org/andengine/entity/modifier/MoveModifier.java @@ -5,9 +5,9 @@ import org.andengine.util.modifier.ease.IEaseFunction; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 16:12:52 - 19.03.2010 */ @@ -24,19 +24,19 @@ public class MoveModifier extends DoubleValueSpanEntityModifier { // Constructors // =========================================================== - public MoveModifier(final float pDuration, final float pFromX, final float pToX, final float pFromY, final float pToY) { - this(pDuration, pFromX, pToX, pFromY, pToY, null, EaseLinear.getInstance()); + public MoveModifier(final float pDuration, final float pFromX, final float pFromY, final float pToX, final float pToY) { + this(pDuration, pFromX, pFromY, pToX, pToY, null, EaseLinear.getInstance()); } - public MoveModifier(final float pDuration, final float pFromX, final float pToX, final float pFromY, final float pToY, final IEaseFunction pEaseFunction) { - this(pDuration, pFromX, pToX, pFromY, pToY, null, pEaseFunction); + public MoveModifier(final float pDuration, final float pFromX, final float pFromY, final float pToX, final float pToY, final IEaseFunction pEaseFunction) { + this(pDuration, pFromX, pFromY, pToX, pToY, null, pEaseFunction); } - public MoveModifier(final float pDuration, final float pFromX, final float pToX, final float pFromY, final float pToY, final IEntityModifierListener pEntityModifierListener) { + public MoveModifier(final float pDuration, final float pFromX, final float pFromY, final float pToX, final float pToY, final IEntityModifierListener pEntityModifierListener) { super(pDuration, pFromX, pToX, pFromY, pToY, pEntityModifierListener, EaseLinear.getInstance()); } - public MoveModifier(final float pDuration, final float pFromX, final float pToX, final float pFromY, final float pToY, final IEntityModifierListener pEntityModifierListener, final IEaseFunction pEaseFunction) { + public MoveModifier(final float pDuration, final float pFromX, final float pFromY, final float pToX, final float pToY, final IEntityModifierListener pEntityModifierListener, final IEaseFunction pEaseFunction) { super(pDuration, pFromX, pToX, pFromY, pToY, pEntityModifierListener, pEaseFunction); } @@ -45,7 +45,7 @@ protected MoveModifier(final MoveModifier pMoveModifier) { } @Override - public MoveModifier deepCopy(){ + public MoveModifier deepCopy() { return new MoveModifier(this); } diff --git a/src/org/andengine/entity/modifier/MoveXModifier.java b/src/org/andengine/entity/modifier/MoveXModifier.java index ac56db7cb..ba0390b56 100644 --- a/src/org/andengine/entity/modifier/MoveXModifier.java +++ b/src/org/andengine/entity/modifier/MoveXModifier.java @@ -5,9 +5,9 @@ import org.andengine.util.modifier.ease.IEaseFunction; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 12:03:22 - 30.08.2010 */ @@ -45,7 +45,7 @@ protected MoveXModifier(final MoveXModifier pMoveXModifier) { } @Override - public MoveXModifier deepCopy(){ + public MoveXModifier deepCopy() { return new MoveXModifier(this); } diff --git a/src/org/andengine/entity/modifier/MoveYModifier.java b/src/org/andengine/entity/modifier/MoveYModifier.java index 11ad53887..06ba983eb 100644 --- a/src/org/andengine/entity/modifier/MoveYModifier.java +++ b/src/org/andengine/entity/modifier/MoveYModifier.java @@ -5,9 +5,9 @@ import org.andengine.util.modifier.ease.IEaseFunction; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 12:04:21 - 30.08.2010 */ @@ -45,7 +45,7 @@ protected MoveYModifier(final MoveYModifier pMoveYModifier) { } @Override - public MoveYModifier deepCopy(){ + public MoveYModifier deepCopy() { return new MoveYModifier(this); } diff --git a/src/org/andengine/entity/modifier/ParallelEntityModifier.java b/src/org/andengine/entity/modifier/ParallelEntityModifier.java index 5b9a25521..d0dc539dd 100644 --- a/src/org/andengine/entity/modifier/ParallelEntityModifier.java +++ b/src/org/andengine/entity/modifier/ParallelEntityModifier.java @@ -4,9 +4,9 @@ import org.andengine.util.modifier.ParallelModifier; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 12:40:31 - 03.09.2010 */ diff --git a/src/org/andengine/entity/modifier/PathModifier.java b/src/org/andengine/entity/modifier/PathModifier.java index 453f7e0b1..6845a0220 100644 --- a/src/org/andengine/entity/modifier/PathModifier.java +++ b/src/org/andengine/entity/modifier/PathModifier.java @@ -7,12 +7,10 @@ import org.andengine.util.modifier.ease.EaseLinear; import org.andengine.util.modifier.ease.IEaseFunction; -import android.util.FloatMath; - /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 16:50:02 - 16.06.2010 */ @@ -82,9 +80,9 @@ public PathModifier(final float pDuration, final Path pPath, final IEntityModifi final float velocity = pPath.getLength() / pDuration; final int modifierCount = moveModifiers.length; - for(int i = 0; i < modifierCount; i++) { + for (int i = 0; i < modifierCount; i++) { final float duration = pPath.getSegmentLength(i) / velocity; - moveModifiers[i] = new MoveModifier(duration, coordinatesX[i], coordinatesX[i + 1], coordinatesY[i], coordinatesY[i + 1], null, pEaseFunction); + moveModifiers[i] = new MoveModifier(duration, coordinatesX[i], coordinatesY[i], coordinatesX[i + 1], coordinatesY[i + 1], null, pEaseFunction); } /* Create a new SequenceModifier and register the listeners that @@ -93,14 +91,14 @@ public PathModifier(final float pDuration, final Path pPath, final IEntityModifi new ISubSequenceModifierListener() { @Override public void onSubSequenceStarted(final IModifier pModifier, final IEntity pEntity, final int pIndex) { - if(PathModifier.this.mPathModifierListener != null) { + if (PathModifier.this.mPathModifierListener != null) { PathModifier.this.mPathModifierListener.onPathWaypointStarted(PathModifier.this, pEntity, pIndex); } } @Override public void onSubSequenceFinished(final IModifier pEntityModifier, final IEntity pEntity, final int pIndex) { - if(PathModifier.this.mPathModifierListener != null) { + if (PathModifier.this.mPathModifierListener != null) { PathModifier.this.mPathModifierListener.onPathWaypointFinished(PathModifier.this, pEntity, pIndex); } } @@ -109,7 +107,7 @@ public void onSubSequenceFinished(final IModifier pEntityModifier, fina @Override public void onModifierStarted(final IModifier pModifier, final IEntity pEntity) { PathModifier.this.onModifierStarted(pEntity); - if(PathModifier.this.mPathModifierListener != null) { + if (PathModifier.this.mPathModifierListener != null) { PathModifier.this.mPathModifierListener.onPathStarted(PathModifier.this, pEntity); } } @@ -117,7 +115,7 @@ public void onModifierStarted(final IModifier pModifier, final IEntity @Override public void onModifierFinished(final IModifier pEntityModifier, final IEntity pEntity) { PathModifier.this.onModifierFinished(pEntity); - if(PathModifier.this.mPathModifierListener != null) { + if (PathModifier.this.mPathModifierListener != null) { PathModifier.this.mPathModifierListener.onPathFinished(PathModifier.this, pEntity); } } @@ -217,7 +215,7 @@ public static class Path { private final float[] mYs; private int mIndex; - private boolean mLengthChanged = false; + private boolean mLengthChanged; private float mLength; // =========================================================== @@ -276,6 +274,18 @@ public Path to(final float pX, final float pY) { return this; } + public Path to(final int pIndex) { + return this.to(this.getX(pIndex), this.getY(pIndex)); + } + + private float getX(final int pIndex) { + return this.mXs[pIndex]; + } + + private float getY(final int pIndex) { + return this.mYs[pIndex]; + } + public float[] getCoordinatesX() { return this.mXs; } @@ -289,7 +299,7 @@ public int getSize() { } public float getLength() { - if(this.mLengthChanged) { + if (this.mLengthChanged) { this.updateLength(); } return this.mLength; @@ -304,7 +314,7 @@ public float getSegmentLength(final int pSegmentIndex) { final float dx = coordinatesX[pSegmentIndex] - coordinatesX[nextSegmentIndex]; final float dy = coordinatesY[pSegmentIndex] - coordinatesY[nextSegmentIndex]; - return FloatMath.sqrt(dx * dx + dy * dy); + return (float) Math.sqrt(dx * dx + dy * dy); } // =========================================================== @@ -318,7 +328,7 @@ public float getSegmentLength(final int pSegmentIndex) { private void updateLength() { float length = 0.0f; - for(int i = this.mIndex - 2; i >= 0; i--) { + for (int i = this.mIndex - 2; i >= 0; i--) { length += this.getSegmentLength(i); } this.mLength = length; diff --git a/src/org/andengine/entity/modifier/QuadraticBezierCurveMoveModifier.java b/src/org/andengine/entity/modifier/QuadraticBezierCurveMoveModifier.java index be9f6fa69..d3a236a3f 100644 --- a/src/org/andengine/entity/modifier/QuadraticBezierCurveMoveModifier.java +++ b/src/org/andengine/entity/modifier/QuadraticBezierCurveMoveModifier.java @@ -7,7 +7,7 @@ /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 23:24:26 - 16.07.2011 */ @@ -121,8 +121,8 @@ protected void onManagedUpdate(final float pSecondsElapsed, final IEntity pEntit final float percentageDone = this.mEaseFunction.getPercentage(this.getSecondsElapsed(), this.mDuration); final float u = 1 - percentageDone; - final float tt = percentageDone*percentageDone; - final float uu = u*u; + final float tt = percentageDone * percentageDone; + final float uu = u * u; final float ut2 = 2 * u * percentageDone; diff --git a/src/org/andengine/entity/modifier/RotationAtModifier.java b/src/org/andengine/entity/modifier/RotationAtModifier.java index 6d3c960aa..5c3d12a31 100644 --- a/src/org/andengine/entity/modifier/RotationAtModifier.java +++ b/src/org/andengine/entity/modifier/RotationAtModifier.java @@ -6,9 +6,9 @@ /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 21:59:38 - 06.07.2010 */ @@ -55,7 +55,7 @@ protected RotationAtModifier(final RotationAtModifier pRotationAtModifier) { } @Override - public RotationAtModifier deepCopy(){ + public RotationAtModifier deepCopy() { return new RotationAtModifier(this); } diff --git a/src/org/andengine/entity/modifier/RotationByModifier.java b/src/org/andengine/entity/modifier/RotationByModifier.java index 663c3eaca..c07446081 100644 --- a/src/org/andengine/entity/modifier/RotationByModifier.java +++ b/src/org/andengine/entity/modifier/RotationByModifier.java @@ -3,9 +3,9 @@ import org.andengine.entity.IEntity; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 16:12:52 - 19.03.2010 */ @@ -35,7 +35,7 @@ protected RotationByModifier(final RotationByModifier pRotationByModifier) { } @Override - public RotationByModifier deepCopy(){ + public RotationByModifier deepCopy() { return new RotationByModifier(this); } diff --git a/src/org/andengine/entity/modifier/RotationModifier.java b/src/org/andengine/entity/modifier/RotationModifier.java index 27201a59d..59a89c1ac 100644 --- a/src/org/andengine/entity/modifier/RotationModifier.java +++ b/src/org/andengine/entity/modifier/RotationModifier.java @@ -5,9 +5,9 @@ import org.andengine.util.modifier.ease.IEaseFunction; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 16:12:52 - 19.03.2010 */ @@ -45,7 +45,7 @@ protected RotationModifier(final RotationModifier pRotationModifier) { } @Override - public RotationModifier deepCopy(){ + public RotationModifier deepCopy() { return new RotationModifier(this); } diff --git a/src/org/andengine/entity/modifier/ScaleAtModifier.java b/src/org/andengine/entity/modifier/ScaleAtModifier.java index 1620a4e90..4bc3953ae 100644 --- a/src/org/andengine/entity/modifier/ScaleAtModifier.java +++ b/src/org/andengine/entity/modifier/ScaleAtModifier.java @@ -6,9 +6,9 @@ /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 21:53:30 - 06.07.2010 */ @@ -71,7 +71,7 @@ protected ScaleAtModifier(final ScaleAtModifier pScaleAtModifier) { } @Override - public ScaleAtModifier deepCopy(){ + public ScaleAtModifier deepCopy() { return new ScaleAtModifier(this); } diff --git a/src/org/andengine/entity/modifier/ScaleModifier.java b/src/org/andengine/entity/modifier/ScaleModifier.java index acd2c3cf1..bb52d3ce8 100644 --- a/src/org/andengine/entity/modifier/ScaleModifier.java +++ b/src/org/andengine/entity/modifier/ScaleModifier.java @@ -5,9 +5,9 @@ import org.andengine.util.modifier.ease.IEaseFunction; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 23:37:53 - 19.03.2010 */ @@ -61,7 +61,7 @@ protected ScaleModifier(final ScaleModifier pScaleModifier) { } @Override - public ScaleModifier deepCopy(){ + public ScaleModifier deepCopy() { return new ScaleModifier(this); } diff --git a/src/org/andengine/entity/modifier/SequenceEntityModifier.java b/src/org/andengine/entity/modifier/SequenceEntityModifier.java index 416fd7be5..4ed06c5fe 100644 --- a/src/org/andengine/entity/modifier/SequenceEntityModifier.java +++ b/src/org/andengine/entity/modifier/SequenceEntityModifier.java @@ -4,9 +4,9 @@ import org.andengine.util.modifier.SequenceModifier; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 12:41:15 - 03.09.2010 */ diff --git a/src/org/andengine/entity/modifier/SingleValueChangeEntityModifier.java b/src/org/andengine/entity/modifier/SingleValueChangeEntityModifier.java index dc9dd8023..cdcc35d2a 100644 --- a/src/org/andengine/entity/modifier/SingleValueChangeEntityModifier.java +++ b/src/org/andengine/entity/modifier/SingleValueChangeEntityModifier.java @@ -4,9 +4,9 @@ import org.andengine.util.modifier.BaseSingleValueChangeModifier; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 15:34:35 - 17.06.2010 */ diff --git a/src/org/andengine/entity/modifier/SingleValueSpanEntityModifier.java b/src/org/andengine/entity/modifier/SingleValueSpanEntityModifier.java index d18d79d26..bea60d136 100644 --- a/src/org/andengine/entity/modifier/SingleValueSpanEntityModifier.java +++ b/src/org/andengine/entity/modifier/SingleValueSpanEntityModifier.java @@ -5,9 +5,9 @@ import org.andengine.util.modifier.ease.IEaseFunction; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 23:29:22 - 19.03.2010 */ diff --git a/src/org/andengine/entity/modifier/SkewModifier.java b/src/org/andengine/entity/modifier/SkewModifier.java index f724bcab1..e26603530 100644 --- a/src/org/andengine/entity/modifier/SkewModifier.java +++ b/src/org/andengine/entity/modifier/SkewModifier.java @@ -5,7 +5,7 @@ import org.andengine.util.modifier.ease.IEaseFunction; /** - * (c) Zynga 2011 + * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 10:46:10 - 05.10.2011 @@ -44,7 +44,7 @@ protected SkewModifier(final SkewModifier pSkewXModifier) { } @Override - public SkewModifier deepCopy(){ + public SkewModifier deepCopy() { return new SkewModifier(this); } diff --git a/src/org/andengine/entity/modifier/SkewXModifier.java b/src/org/andengine/entity/modifier/SkewXModifier.java index e4269c31e..9011f6f51 100644 --- a/src/org/andengine/entity/modifier/SkewXModifier.java +++ b/src/org/andengine/entity/modifier/SkewXModifier.java @@ -5,7 +5,7 @@ import org.andengine.util.modifier.ease.IEaseFunction; /** - * (c) Zynga 2011 + * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 10:46:10 - 05.10.2011 @@ -44,7 +44,7 @@ protected SkewXModifier(final SkewXModifier pSkewXModifier) { } @Override - public SkewXModifier deepCopy(){ + public SkewXModifier deepCopy() { return new SkewXModifier(this); } diff --git a/src/org/andengine/entity/modifier/SkewYModifier.java b/src/org/andengine/entity/modifier/SkewYModifier.java index 85a012964..716cc9869 100644 --- a/src/org/andengine/entity/modifier/SkewYModifier.java +++ b/src/org/andengine/entity/modifier/SkewYModifier.java @@ -5,7 +5,7 @@ import org.andengine.util.modifier.ease.IEaseFunction; /** - * (c) Zynga 2011 + * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 10:48:45 - 05.10.2011 @@ -44,7 +44,7 @@ protected SkewYModifier(final SkewYModifier pSkewYModifier) { } @Override - public SkewYModifier deepCopy(){ + public SkewYModifier deepCopy() { return new SkewYModifier(this); } diff --git a/src/org/andengine/entity/modifier/TripleValueSpanEntityModifier.java b/src/org/andengine/entity/modifier/TripleValueSpanEntityModifier.java index 5a72e145e..591777edf 100644 --- a/src/org/andengine/entity/modifier/TripleValueSpanEntityModifier.java +++ b/src/org/andengine/entity/modifier/TripleValueSpanEntityModifier.java @@ -5,9 +5,9 @@ import org.andengine.util.modifier.ease.IEaseFunction; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 15:35:18 - 29.06.2010 */ diff --git a/src/org/andengine/entity/particle/BatchedPseudoSpriteParticleSystem.java b/src/org/andengine/entity/particle/BatchedPseudoSpriteParticleSystem.java new file mode 100644 index 000000000..97acf9245 --- /dev/null +++ b/src/org/andengine/entity/particle/BatchedPseudoSpriteParticleSystem.java @@ -0,0 +1,87 @@ +package org.andengine.entity.particle; + +import org.andengine.engine.camera.Camera; +import org.andengine.entity.Entity; +import org.andengine.entity.IEntityFactory; +import org.andengine.entity.particle.emitter.IParticleEmitter; +import org.andengine.entity.sprite.batch.SpriteBatch; +import org.andengine.opengl.texture.region.ITextureRegion; +import org.andengine.opengl.util.GLState; +import org.andengine.opengl.vbo.VertexBufferObjectManager; +import org.andengine.util.adt.color.ColorUtils; + +/** + * (c) 2012 Zynga Inc. + * + * @author Nicolas Gramlich + * @since 11:39:46 - 10.05.2012 + */ +public class BatchedPseudoSpriteParticleSystem extends BlendFunctionParticleSystem { + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + protected final SpriteBatch mSpriteBatch; + private final ITextureRegion mTextureRegion; + + // =========================================================== + // Constructors + // =========================================================== + + public BatchedPseudoSpriteParticleSystem(final IParticleEmitter pParticleEmitter, final float pRateMinimum, final float pRateMaximum, final int pParticlesMaximum, final ITextureRegion pTextureRegion, final VertexBufferObjectManager pVertexBufferObjectManager) { + this(0, 0, pParticleEmitter, pRateMinimum, pRateMaximum, pParticlesMaximum, pTextureRegion, pVertexBufferObjectManager); + } + + public BatchedPseudoSpriteParticleSystem(final float pX, final float pY, final IParticleEmitter pParticleEmitter, final float pRateMinimum, final float pRateMaximum, final int pParticlesMaximum, final ITextureRegion pTextureRegion, final VertexBufferObjectManager pVertexBufferObjectManager) { + super(pX, pY, new IEntityFactory() { + @Override + public Entity create(final float pX, final float pY) { + return new Entity(pX, pY, pTextureRegion.getWidth(), pTextureRegion.getHeight()); + } + }, pParticleEmitter, pRateMinimum, pRateMaximum, pParticlesMaximum); + + this.mTextureRegion = pTextureRegion; + + this.mSpriteBatch = new SpriteBatch(pTextureRegion.getTexture(), pParticlesMaximum, pVertexBufferObjectManager); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + protected void onManagedDraw(final GLState pGLState, final Camera pCamera) { + this.mSpriteBatch.setIndex(0); + + final Particle[] particles = this.mParticles; + for (int i = this.mParticlesAlive - 1; i >= 0; i--) { + final Entity entity = particles[i].getEntity(); + + /* In order to support alpha changes of the sprites inside the spritebatch, + * we have to 'premultiply' the RGB channels of the sprite with its alpha channel. */ + final float alpha = entity.getAlpha(); + final float colorABGRPackedInt = ColorUtils.convertRGBAToABGRPackedFloat(entity.getRed() * alpha, entity.getGreen() * alpha, entity.getBlue() * alpha, alpha); + + this.mSpriteBatch.drawWithoutChecks(this.mTextureRegion, entity, colorABGRPackedInt); + } + this.mSpriteBatch.submit(); + + this.mSpriteBatch.onDraw(pGLState, pCamera); + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== +} diff --git a/src/org/andengine/entity/particle/BatchedSpriteParticleSystem.java b/src/org/andengine/entity/particle/BatchedSpriteParticleSystem.java new file mode 100644 index 000000000..33c60749b --- /dev/null +++ b/src/org/andengine/entity/particle/BatchedSpriteParticleSystem.java @@ -0,0 +1,86 @@ +package org.andengine.entity.particle; + +import org.andengine.engine.camera.Camera; +import org.andengine.entity.IEntityFactory; +import org.andengine.entity.particle.emitter.IParticleEmitter; +import org.andengine.entity.sprite.Sprite; +import org.andengine.entity.sprite.UncoloredSprite; +import org.andengine.entity.sprite.batch.SpriteBatch; +import org.andengine.opengl.texture.region.ITextureRegion; +import org.andengine.opengl.util.GLState; +import org.andengine.opengl.vbo.VertexBufferObjectManager; +import org.andengine.util.adt.color.ColorUtils; + +/** + * (c) 2012 Zynga Inc. + * + * @author Nicolas Gramlich + * @since 18:32:29 - 09.05.2012 + */ +public class BatchedSpriteParticleSystem extends BlendFunctionParticleSystem { + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + protected final SpriteBatch mSpriteBatch; + + // =========================================================== + // Constructors + // =========================================================== + + public BatchedSpriteParticleSystem(final IParticleEmitter pParticleEmitter, final float pRateMinimum, final float pRateMaximum, final int pParticlesMaximum, final ITextureRegion pTextureRegion, final VertexBufferObjectManager pVertexBufferObjectManager) { + this(0, 0, pParticleEmitter, pRateMinimum, pRateMaximum, pParticlesMaximum, pTextureRegion, pVertexBufferObjectManager); + } + + public BatchedSpriteParticleSystem(final float pX, final float pY, final IParticleEmitter pParticleEmitter, final float pRateMinimum, final float pRateMaximum, final int pParticlesMaximum, final ITextureRegion pTextureRegion, final VertexBufferObjectManager pVertexBufferObjectManager) { + super(pX, pY, new IEntityFactory() { + @Override + public UncoloredSprite create(final float pX, final float pY) { + /* We can create an uncolored sprite, since */ + return new UncoloredSprite(pX, pY, pTextureRegion, pVertexBufferObjectManager); + } + }, pParticleEmitter, pRateMinimum, pRateMaximum, pParticlesMaximum); + + this.mSpriteBatch = new SpriteBatch(pTextureRegion.getTexture(), pParticlesMaximum, pVertexBufferObjectManager); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + protected void onManagedDraw(final GLState pGLState, final Camera pCamera) { + this.mSpriteBatch.setIndex(0); + + final Particle[] particles = this.mParticles; + for (int i = this.mParticlesAlive - 1; i >= 0; i--) { + final Sprite sprite = particles[i].getEntity(); + + /* In order to support alpha changes of the sprites inside the spritebatch, + * we have to 'premultiply' the RGB channels of the sprite with its alpha channel. */ + final float alpha = sprite.getAlpha(); + final float colorABGRPackedInt = ColorUtils.convertRGBAToABGRPackedFloat(sprite.getRed() * alpha, sprite.getGreen() * alpha, sprite.getBlue() * alpha, alpha); + + this.mSpriteBatch.drawWithoutChecks(sprite, colorABGRPackedInt); + } + this.mSpriteBatch.submit(); + + this.mSpriteBatch.onDraw(pGLState, pCamera); + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== +} diff --git a/src/org/andengine/entity/particle/BlendFunctionParticleSystem.java b/src/org/andengine/entity/particle/BlendFunctionParticleSystem.java new file mode 100644 index 000000000..4fe4c4278 --- /dev/null +++ b/src/org/andengine/entity/particle/BlendFunctionParticleSystem.java @@ -0,0 +1,100 @@ +package org.andengine.entity.particle; + +import org.andengine.engine.camera.Camera; +import org.andengine.entity.IEntity; +import org.andengine.entity.IEntityFactory; +import org.andengine.entity.particle.emitter.IParticleEmitter; +import org.andengine.entity.shape.IShape; +import org.andengine.opengl.util.GLState; + +/** + * (c) 2012 Zynga Inc. + * + * @author Nicolas Gramlich + * @since 11:34:32 - 10.05.2012 + */ +public class BlendFunctionParticleSystem extends ParticleSystem { + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + protected boolean mBlendingEnabled = true; + protected int mBlendFunctionSource = IShape.BLENDFUNCTION_SOURCE_DEFAULT; + protected int mBlendFunctionDestination = IShape.BLENDFUNCTION_DESTINATION_DEFAULT; + + // =========================================================== + // Constructors + // =========================================================== + + public BlendFunctionParticleSystem(final IEntityFactory pEntityFactory, final IParticleEmitter pParticleEmitter, final float pRateMinimum, final float pRateMaximum, final int pParticlesMaximum) { + super(pEntityFactory, pParticleEmitter, pRateMinimum, pRateMaximum, pParticlesMaximum); + } + + public BlendFunctionParticleSystem(final float pX, final float pY, final IEntityFactory pEntityFactory, final IParticleEmitter pParticleEmitter, final float pRateMinimum, final float pRateMaximum, final int pParticlesMaximum) { + super(pX, pY, pEntityFactory, pParticleEmitter, pRateMinimum, pRateMaximum, pParticlesMaximum); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + public boolean isBlendingEnabled() { + return this.mBlendingEnabled; + } + + public void setBlendingEnabled(final boolean pBlendingEnabled) { + this.mBlendingEnabled = pBlendingEnabled; + } + + public int getBlendFunctionSource() { + return this.mBlendFunctionSource; + } + + public void setBlendFunctionSource(final int pBlendFunctionSource) { + this.mBlendFunctionSource = pBlendFunctionSource; + } + + public int getBlendFunctionDestination() { + return this.mBlendFunctionDestination; + } + + public void setBlendFunctionDestination(final int pBlendFunctionDestination) { + this.mBlendFunctionDestination = pBlendFunctionDestination; + } + + public void setBlendFunction(final int pBlendFunctionSource, final int pBlendFunctionDestination) { + this.mBlendFunctionSource = pBlendFunctionSource; + this.mBlendFunctionDestination = pBlendFunctionDestination; + } + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + protected void preDraw(final GLState pGLState, final Camera pCamera) { + if (this.mBlendingEnabled) { + pGLState.enableBlend(); + pGLState.blendFunction(this.mBlendFunctionSource, this.mBlendFunctionDestination); + } + } + + @Override + protected void postDraw(final GLState pGLState, final Camera pCamera) { + if (this.mBlendingEnabled) { + pGLState.disableBlend(); + } + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== +} diff --git a/src/org/andengine/entity/particle/Particle.java b/src/org/andengine/entity/particle/Particle.java index 66bda0532..51318d900 100644 --- a/src/org/andengine/entity/particle/Particle.java +++ b/src/org/andengine/entity/particle/Particle.java @@ -8,7 +8,7 @@ /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 19:37:13 - 14.03.2010 */ @@ -61,7 +61,7 @@ public void setExpireTime(final float pExpireTime) { } public boolean isExpired() { - return this.mExpired ; + return this.mExpired; } public void setExpired(final boolean pExpired) { @@ -77,8 +77,8 @@ public PhysicsHandler getPhysicsHandler() { // =========================================================== protected void onUpdate(final float pSecondsElapsed) { - if(!this.mExpired){ - if(this.mExpireTime == Particle.EXPIRETIME_NEVER || this.mLifeTime + pSecondsElapsed < this.mExpireTime) { + if (!this.mExpired) { + if (this.mExpireTime == Particle.EXPIRETIME_NEVER || this.mLifeTime + pSecondsElapsed < this.mExpireTime) { /* Particle doesn't expire or didn't expire yet. */ this.mLifeTime += pSecondsElapsed; this.mEntity.onUpdate(pSecondsElapsed); @@ -94,7 +94,7 @@ protected void onUpdate(final float pSecondsElapsed) { } public void onDraw(final GLState pGLState, final Camera pCamera) { - if(!this.mExpired) { + if (!this.mExpired) { this.mEntity.onDraw(pGLState, pCamera); } } diff --git a/src/org/andengine/entity/particle/ParticleSystem.java b/src/org/andengine/entity/particle/ParticleSystem.java index a3576c24d..725b0b946 100644 --- a/src/org/andengine/entity/particle/ParticleSystem.java +++ b/src/org/andengine/entity/particle/ParticleSystem.java @@ -4,56 +4,51 @@ import org.andengine.engine.camera.Camera; import org.andengine.entity.Entity; +import org.andengine.entity.IEntity; import org.andengine.entity.IEntityFactory; import org.andengine.entity.particle.emitter.IParticleEmitter; import org.andengine.entity.particle.initializer.IParticleInitializer; import org.andengine.entity.particle.modifier.IParticleModifier; import org.andengine.opengl.util.GLState; import org.andengine.util.Constants; +import org.andengine.util.adt.array.ArrayUtils; import org.andengine.util.math.MathUtils; -import android.util.FloatMath; - /** - * TODO Check if SpriteBatch can be used here to improve performance. - * * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 19:42:27 - 14.03.2010 */ -public class ParticleSystem extends Entity { +public class ParticleSystem extends Entity { // =========================================================== // Constants // =========================================================== - private final float[] POSITION_OFFSET = new float[2]; + private static final float[] POSITION_OFFSET_CONTAINER = new float[2]; // =========================================================== // Fields // =========================================================== - private final IEntityFactory mEntityFactory; - private final IParticleEmitter mParticleEmitter; + protected final IEntityFactory mEntityFactory; + protected final IParticleEmitter mParticleEmitter; - private final Particle[] mParticles; + protected final Particle[] mParticles; - private final ArrayList> mParticleInitializers = new ArrayList>(); - private final ArrayList> mParticleModifiers = new ArrayList>(); + protected final ArrayList> mParticleInitializers = new ArrayList>(); + protected final ArrayList> mParticleModifiers = new ArrayList>(); private final float mRateMinimum; private final float mRateMaximum; private boolean mParticlesSpawnEnabled = true; - private final int mParticlesMaximum; - private int mParticlesAlive; + protected final int mParticlesMaximum; + protected int mParticlesAlive; private float mParticlesDueToSpawn; - private int mParticleModifierCount; - private int mParticleInitializerCount; - // =========================================================== // Constructors // =========================================================== @@ -68,7 +63,7 @@ public ParticleSystem(final float pX, final float pY, final IEntityFactory pE this.mEntityFactory = pEntityFactory; this.mParticleEmitter = pParticleEmitter; - this.mParticles = (Particle[])new Particle[pParticlesMaximum]; + this.mParticles = (Particle[]) new Particle[pParticlesMaximum]; this.mRateMinimum = pRateMinimum; this.mRateMaximum = pRateMaximum; this.mParticlesMaximum = pParticlesMaximum; @@ -110,9 +105,8 @@ public void reset() { @Override protected void onManagedDraw(final GLState pGLState, final Camera pCamera) { - final Particle[] particles = this.mParticles; - for(int i = this.mParticlesAlive - 1; i >= 0; i--) { - particles[i].onDraw(pGLState, pCamera); + for (int i = this.mParticlesAlive - 1; i >= 0; i--) { + this.mParticles[i].onDraw(pGLState, pCamera); } } @@ -120,54 +114,60 @@ protected void onManagedDraw(final GLState pGLState, final Camera pCamera) { protected void onManagedUpdate(final float pSecondsElapsed) { super.onManagedUpdate(pSecondsElapsed); - if(this.isParticlesSpawnEnabled()) { + if (this.isParticlesSpawnEnabled()) { this.spawnParticles(pSecondsElapsed); } - final Particle[] particles = this.mParticles; - - final ArrayList> particleModifiers = this.mParticleModifiers; - final int particleModifierCountMinusOne = this.mParticleModifierCount - 1; - - for(int i = this.mParticlesAlive - 1; i >= 0; i--) { - final Particle particle = particles[i]; + final int particleModifierCountMinusOne = this.mParticleModifiers.size() - 1; + for (int i = this.mParticlesAlive - 1; i >= 0; i--) { + final Particle particle = this.mParticles[i]; /* Apply all particleModifiers */ - for(int j = particleModifierCountMinusOne; j >= 0; j--) { - particleModifiers.get(j).onUpdateParticle(particle); + for (int j = particleModifierCountMinusOne; j >= 0; j--) { + this.mParticleModifiers.get(j).onUpdateParticle(particle); } particle.onUpdate(pSecondsElapsed); - if(particle.mExpired){ + if (particle.mExpired) { this.mParticlesAlive--; - final int particlesAlive = this.mParticlesAlive; - particles[i] = particles[particlesAlive]; - particles[particlesAlive] = particle; + + this.moveParticleToEnd(i); } } } + protected void moveParticleToEnd(final int pIndex) { + final Particle particle = this.mParticles[pIndex]; + + final int particlesToCopy = this.mParticlesAlive - pIndex; + if (particlesToCopy > 0) { + System.arraycopy(this.mParticles, pIndex + 1, this.mParticles, pIndex, particlesToCopy); + } + this.mParticles[this.mParticlesAlive] = particle; + + /* This mode of swapping particles is faster than copying tons of array elements, + * but it doesn't respect the 'lifetime' of the particles. */ +// particles[i] = particles[this.mParticlesAlive]; +// particles[this.mParticlesAlive] = particle; + } + // =========================================================== // Methods // =========================================================== public void addParticleModifier(final IParticleModifier pParticleModifier) { this.mParticleModifiers.add(pParticleModifier); - this.mParticleModifierCount++; } public void removeParticleModifier(final IParticleModifier pParticleModifier) { - this.mParticleModifierCount--; this.mParticleModifiers.remove(pParticleModifier); } public void addParticleInitializer(final IParticleInitializer pParticleInitializer) { this.mParticleInitializers.add(pParticleInitializer); - this.mParticleInitializerCount++; } public void removeParticleInitializer(final IParticleInitializer pParticleInitializer) { - this.mParticleInitializerCount--; this.mParticleInitializers.remove(pParticleInitializer); } @@ -177,30 +177,27 @@ private void spawnParticles(final float pSecondsElapsed) { this.mParticlesDueToSpawn += newParticlesThisFrame; - final int particlesToSpawnThisFrame = Math.min(this.mParticlesMaximum - this.mParticlesAlive, (int)FloatMath.floor(this.mParticlesDueToSpawn)); + final int particlesToSpawnThisFrame = Math.min(this.mParticlesMaximum - this.mParticlesAlive, (int) Math.floor(this.mParticlesDueToSpawn)); this.mParticlesDueToSpawn -= particlesToSpawnThisFrame; - for(int i = 0; i < particlesToSpawnThisFrame; i++){ + for (int i = 0; i < particlesToSpawnThisFrame; i++) { this.spawnParticle(); } } private void spawnParticle() { - final Particle[] particles = this.mParticles; - - final int particlesAlive = this.mParticlesAlive; - if(particlesAlive < this.mParticlesMaximum){ - Particle particle = particles[particlesAlive]; + if (this.mParticlesAlive < this.mParticlesMaximum) { + Particle particle = this.mParticles[this.mParticlesAlive]; /* New particle needs to be created. */ - this.mParticleEmitter.getPositionOffset(this.POSITION_OFFSET); + this.mParticleEmitter.getPositionOffset(ParticleSystem.POSITION_OFFSET_CONTAINER); - final float x = this.POSITION_OFFSET[Constants.VERTEX_INDEX_X]; - final float y = this.POSITION_OFFSET[Constants.VERTEX_INDEX_Y]; + final float x = ParticleSystem.POSITION_OFFSET_CONTAINER[Constants.VERTEX_INDEX_X]; + final float y = ParticleSystem.POSITION_OFFSET_CONTAINER[Constants.VERTEX_INDEX_Y]; - if(particle == null) { + if (particle == null) { particle = new Particle(); - particles[particlesAlive] = particle; + this.mParticles[this.mParticlesAlive] = particle; particle.setEntity(this.mEntityFactory.create(x, y)); } else { particle.reset(); @@ -209,14 +206,12 @@ private void spawnParticle() { /* Apply particle initializers. */ { - final ArrayList> particleInitializers = this.mParticleInitializers; - for(int i = this.mParticleInitializerCount - 1; i >= 0; i--) { - particleInitializers.get(i).onInitializeParticle(particle); + for (int i = this.mParticleInitializers.size() - 1; i >= 0; i--) { + this.mParticleInitializers.get(i).onInitializeParticle(particle); } - final ArrayList> particleModifiers = this.mParticleModifiers; - for(int i = this.mParticleModifierCount - 1; i >= 0; i--) { - particleModifiers.get(i).onInitializeParticle(particle); + for (int i = this.mParticleModifiers.size() - 1; i >= 0; i--) { + this.mParticleModifiers.get(i).onInitializeParticle(particle); } } @@ -225,7 +220,7 @@ private void spawnParticle() { } protected float determineCurrentRate() { - if(this.mRateMinimum == this.mRateMaximum){ + if (this.mRateMinimum == this.mRateMaximum) { return this.mRateMinimum; } else { return MathUtils.random(this.mRateMinimum, this.mRateMaximum); diff --git a/src/org/andengine/entity/particle/SpriteParticleSystem.java b/src/org/andengine/entity/particle/SpriteParticleSystem.java index b7bd64453..aef2b20e2 100644 --- a/src/org/andengine/entity/particle/SpriteParticleSystem.java +++ b/src/org/andengine/entity/particle/SpriteParticleSystem.java @@ -7,7 +7,7 @@ import org.andengine.opengl.vbo.VertexBufferObjectManager; /** - * (c) Zynga 2011 + * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 21:00:23 - 04.12.2011 @@ -38,6 +38,10 @@ public Sprite create(final float pX, final float pY) { }, pParticleEmitter, pRateMinimum, pRateMaximum, pParticlesMaximum); } + protected SpriteParticleSystem(final float pX, final float pY, final IEntityFactory pEntityFactory, final IParticleEmitter pParticleEmitter, final float pRateMinimum, final float pRateMaximum, final int pParticlesMaximum) { + super(pX, pY, pEntityFactory, pParticleEmitter, pRateMinimum, pRateMaximum, pParticlesMaximum); + } + // =========================================================== // Getter & Setter // =========================================================== diff --git a/src/org/andengine/entity/particle/emitter/BaseCircleParticleEmitter.java b/src/org/andengine/entity/particle/emitter/BaseCircleParticleEmitter.java index 6cf5bd3cf..618990acb 100644 --- a/src/org/andengine/entity/particle/emitter/BaseCircleParticleEmitter.java +++ b/src/org/andengine/entity/particle/emitter/BaseCircleParticleEmitter.java @@ -2,9 +2,9 @@ /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 20:14:43 - 01.10.2010 */ diff --git a/src/org/andengine/entity/particle/emitter/BaseParticleEmitter.java b/src/org/andengine/entity/particle/emitter/BaseParticleEmitter.java index 8c29f6ebf..1ec272956 100644 --- a/src/org/andengine/entity/particle/emitter/BaseParticleEmitter.java +++ b/src/org/andengine/entity/particle/emitter/BaseParticleEmitter.java @@ -1,9 +1,9 @@ package org.andengine.entity.particle.emitter; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 15:58:12 - 01.10.2010 */ diff --git a/src/org/andengine/entity/particle/emitter/BaseRectangleParticleEmitter.java b/src/org/andengine/entity/particle/emitter/BaseRectangleParticleEmitter.java index 0dfccd07c..334020209 100644 --- a/src/org/andengine/entity/particle/emitter/BaseRectangleParticleEmitter.java +++ b/src/org/andengine/entity/particle/emitter/BaseRectangleParticleEmitter.java @@ -2,9 +2,9 @@ /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 18:53:18 - 01.10.2010 */ diff --git a/src/org/andengine/entity/particle/emitter/CircleOutlineParticleEmitter.java b/src/org/andengine/entity/particle/emitter/CircleOutlineParticleEmitter.java index 95ad9e4e8..9807c8247 100644 --- a/src/org/andengine/entity/particle/emitter/CircleOutlineParticleEmitter.java +++ b/src/org/andengine/entity/particle/emitter/CircleOutlineParticleEmitter.java @@ -6,12 +6,10 @@ import org.andengine.util.math.MathConstants; import org.andengine.util.math.MathUtils; -import android.util.FloatMath; - /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 20:18:41 - 01.10.2010 */ @@ -47,8 +45,8 @@ public CircleOutlineParticleEmitter(final float pCenterX, final float pCenterY, @Override public void getPositionOffset(final float[] pOffset) { final float random = MathUtils.RANDOM.nextFloat() * MathConstants.PI * 2; - pOffset[VERTEX_INDEX_X] = this.mCenterX + FloatMath.cos(random) * this.mRadiusX; - pOffset[VERTEX_INDEX_Y] = this.mCenterY + FloatMath.sin(random) * this.mRadiusY; + pOffset[VERTEX_INDEX_X] = this.mCenterX + (float) Math.cos(random) * this.mRadiusX; + pOffset[VERTEX_INDEX_Y] = this.mCenterY + (float) Math.sin(random) * this.mRadiusY; } // =========================================================== diff --git a/src/org/andengine/entity/particle/emitter/CircleParticleEmitter.java b/src/org/andengine/entity/particle/emitter/CircleParticleEmitter.java index ba8c69a7b..f492a7609 100644 --- a/src/org/andengine/entity/particle/emitter/CircleParticleEmitter.java +++ b/src/org/andengine/entity/particle/emitter/CircleParticleEmitter.java @@ -6,12 +6,10 @@ import org.andengine.util.math.MathConstants; import org.andengine.util.math.MathUtils; -import android.util.FloatMath; - /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 20:18:41 - 01.10.2010 */ @@ -47,8 +45,8 @@ public CircleParticleEmitter(final float pCenterX, final float pCenterY, final f @Override public void getPositionOffset(final float[] pOffset) { final float random = MathUtils.RANDOM.nextFloat() * MathConstants.PI * 2; - pOffset[VERTEX_INDEX_X] = this.mCenterX + FloatMath.cos(random) * this.mRadiusX * MathUtils.RANDOM.nextFloat(); - pOffset[VERTEX_INDEX_Y] = this.mCenterY + FloatMath.sin(random) * this.mRadiusY * MathUtils.RANDOM.nextFloat(); + pOffset[VERTEX_INDEX_X] = this.mCenterX + (float) Math.cos(random) * this.mRadiusX * MathUtils.RANDOM.nextFloat(); + pOffset[VERTEX_INDEX_Y] = this.mCenterY + (float) Math.sin(random) * this.mRadiusY * MathUtils.RANDOM.nextFloat(); } // =========================================================== diff --git a/src/org/andengine/entity/particle/emitter/IParticleEmitter.java b/src/org/andengine/entity/particle/emitter/IParticleEmitter.java index 80c6d1a19..881fac369 100644 --- a/src/org/andengine/entity/particle/emitter/IParticleEmitter.java +++ b/src/org/andengine/entity/particle/emitter/IParticleEmitter.java @@ -3,9 +3,9 @@ import org.andengine.engine.handler.IUpdateHandler; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 15:48:09 - 01.10.2010 */ diff --git a/src/org/andengine/entity/particle/emitter/PointParticleEmitter.java b/src/org/andengine/entity/particle/emitter/PointParticleEmitter.java index 763371845..ca052fa6b 100644 --- a/src/org/andengine/entity/particle/emitter/PointParticleEmitter.java +++ b/src/org/andengine/entity/particle/emitter/PointParticleEmitter.java @@ -4,9 +4,9 @@ import static org.andengine.util.Constants.VERTEX_INDEX_Y; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 23:14:42 - 01.10.2010 */ diff --git a/src/org/andengine/entity/particle/emitter/RectangleOutlineParticleEmitter.java b/src/org/andengine/entity/particle/emitter/RectangleOutlineParticleEmitter.java index d81def32e..f8967b102 100644 --- a/src/org/andengine/entity/particle/emitter/RectangleOutlineParticleEmitter.java +++ b/src/org/andengine/entity/particle/emitter/RectangleOutlineParticleEmitter.java @@ -6,9 +6,9 @@ import org.andengine.util.math.MathUtils; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 15:48:00 - 01.10.2010 */ diff --git a/src/org/andengine/entity/particle/emitter/RectangleParticleEmitter.java b/src/org/andengine/entity/particle/emitter/RectangleParticleEmitter.java index b4e1da14c..f693564c3 100644 --- a/src/org/andengine/entity/particle/emitter/RectangleParticleEmitter.java +++ b/src/org/andengine/entity/particle/emitter/RectangleParticleEmitter.java @@ -6,9 +6,9 @@ import org.andengine.util.math.MathUtils; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 15:48:00 - 01.10.2010 */ diff --git a/src/org/andengine/entity/particle/initializer/AccelerationParticleInitializer.java b/src/org/andengine/entity/particle/initializer/AccelerationParticleInitializer.java index 47de27615..2fa371037 100644 --- a/src/org/andengine/entity/particle/initializer/AccelerationParticleInitializer.java +++ b/src/org/andengine/entity/particle/initializer/AccelerationParticleInitializer.java @@ -4,9 +4,9 @@ import org.andengine.entity.particle.Particle; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 21:21:10 - 14.03.2010 */ diff --git a/src/org/andengine/entity/particle/initializer/AlphaParticleInitializer.java b/src/org/andengine/entity/particle/initializer/AlphaParticleInitializer.java index a51e8c649..a7ccfdc56 100644 --- a/src/org/andengine/entity/particle/initializer/AlphaParticleInitializer.java +++ b/src/org/andengine/entity/particle/initializer/AlphaParticleInitializer.java @@ -5,9 +5,9 @@ /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 18:53:41 - 02.10.2010 */ diff --git a/src/org/andengine/entity/particle/initializer/BaseDoubleValueParticleInitializer.java b/src/org/andengine/entity/particle/initializer/BaseDoubleValueParticleInitializer.java index 1ceb167ff..15c9586f1 100644 --- a/src/org/andengine/entity/particle/initializer/BaseDoubleValueParticleInitializer.java +++ b/src/org/andengine/entity/particle/initializer/BaseDoubleValueParticleInitializer.java @@ -5,9 +5,9 @@ import org.andengine.util.math.MathUtils; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 15:58:29 - 04.05.2010 */ @@ -53,7 +53,7 @@ protected final void onInitializeParticle(final Particle pParticle, final flo // =========================================================== protected float getRandomValueB() { - if(this.mMinValueB == this.mMaxValueB) { + if (this.mMinValueB == this.mMaxValueB) { return this.mMaxValueB; } else { return MathUtils.random(this.mMinValueB, this.mMaxValueB); diff --git a/src/org/andengine/entity/particle/initializer/BaseSingleValueParticleInitializer.java b/src/org/andengine/entity/particle/initializer/BaseSingleValueParticleInitializer.java index 580d1a9fb..1b62c9cb2 100644 --- a/src/org/andengine/entity/particle/initializer/BaseSingleValueParticleInitializer.java +++ b/src/org/andengine/entity/particle/initializer/BaseSingleValueParticleInitializer.java @@ -5,9 +5,9 @@ import org.andengine.util.math.MathUtils; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 10:18:06 - 29.06.2010 */ @@ -52,7 +52,7 @@ public final void onInitializeParticle(final Particle pParticle) { // =========================================================== protected float getRandomValue() { - if(this.mMinValue == this.mMaxValue) { + if (this.mMinValue == this.mMaxValue) { return this.mMaxValue; } else { return MathUtils.random(this.mMinValue, this.mMaxValue); diff --git a/src/org/andengine/entity/particle/initializer/BaseTripleValueParticleInitializer.java b/src/org/andengine/entity/particle/initializer/BaseTripleValueParticleInitializer.java index 37bce1e1a..101f448e4 100644 --- a/src/org/andengine/entity/particle/initializer/BaseTripleValueParticleInitializer.java +++ b/src/org/andengine/entity/particle/initializer/BaseTripleValueParticleInitializer.java @@ -5,9 +5,9 @@ import org.andengine.util.math.MathUtils; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 15:58:29 - 04.05.2010 */ @@ -53,7 +53,7 @@ protected final void onInitializeParticle(final Particle pParticle, final flo // =========================================================== protected float getRandomValueC() { - if(this.mMinValueC == this.mMaxValueC) { + if (this.mMinValueC == this.mMaxValueC) { return this.mMaxValueC; } else { return MathUtils.random(this.mMinValueC, this.mMaxValueC); diff --git a/src/org/andengine/entity/particle/initializer/BlendFunctionParticleInitializer.java b/src/org/andengine/entity/particle/initializer/BlendFunctionParticleInitializer.java index cec51c15f..9c1909f9b 100644 --- a/src/org/andengine/entity/particle/initializer/BlendFunctionParticleInitializer.java +++ b/src/org/andengine/entity/particle/initializer/BlendFunctionParticleInitializer.java @@ -8,9 +8,9 @@ /** * Sets the blend function used to draw the {@link Particle} during its lifespan. Only applicable to {@link Shape}s. - * - * @author janne.sinivirta - * + * + * @author Janne Sinivirta + * * @since 17:24:32 - 28.12.2011 */ public class BlendFunctionParticleInitializer implements IParticleInitializer { diff --git a/src/org/andengine/entity/particle/initializer/ColorParticleInitializer.java b/src/org/andengine/entity/particle/initializer/ColorParticleInitializer.java index c9d7cae67..f2502cb24 100644 --- a/src/org/andengine/entity/particle/initializer/ColorParticleInitializer.java +++ b/src/org/andengine/entity/particle/initializer/ColorParticleInitializer.java @@ -2,13 +2,13 @@ import org.andengine.entity.IEntity; import org.andengine.entity.particle.Particle; -import org.andengine.util.color.Color; +import org.andengine.util.adt.color.Color; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 10:17:42 - 29.06.2010 */ @@ -28,7 +28,7 @@ public class ColorParticleInitializer extends BaseTripleValue public ColorParticleInitializer(final Color pColor) { super(pColor.getRed(), pColor.getRed(), pColor.getGreen(), pColor.getGreen(), pColor.getBlue(), pColor.getBlue()); } - + public ColorParticleInitializer(final float pRed, final float pGreen, final float pBlue) { super(pRed, pRed, pGreen, pGreen, pBlue, pBlue); } @@ -36,7 +36,7 @@ public ColorParticleInitializer(final float pRed, final float pGreen, final floa public ColorParticleInitializer(final Color pMinColor, final Color pMaxColor) { super(pMinColor.getRed(), pMaxColor.getRed(), pMinColor.getGreen(), pMaxColor.getGreen(), pMinColor.getBlue(), pMaxColor.getBlue()); } - + public ColorParticleInitializer(final float pMinRed, final float pMaxRed, final float pMinGreen, final float pMaxGreen, final float pMinBlue, final float pMaxBlue) { super(pMinRed, pMaxRed, pMinGreen, pMaxGreen, pMinBlue, pMaxBlue); } diff --git a/src/org/andengine/entity/particle/modifier/ExpireParticleInitializer.java b/src/org/andengine/entity/particle/initializer/ExpireParticleInitializer.java similarity index 93% rename from src/org/andengine/entity/particle/modifier/ExpireParticleInitializer.java rename to src/org/andengine/entity/particle/initializer/ExpireParticleInitializer.java index 9bbdf4ac7..c6a482bfb 100644 --- a/src/org/andengine/entity/particle/modifier/ExpireParticleInitializer.java +++ b/src/org/andengine/entity/particle/initializer/ExpireParticleInitializer.java @@ -1,14 +1,13 @@ -package org.andengine.entity.particle.modifier; +package org.andengine.entity.particle.initializer; import org.andengine.entity.IEntity; import org.andengine.entity.particle.Particle; -import org.andengine.entity.particle.initializer.IParticleInitializer; import org.andengine.util.math.MathUtils; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 21:21:10 - 14.03.2010 */ diff --git a/src/org/andengine/entity/particle/initializer/GravityParticleInitializer.java b/src/org/andengine/entity/particle/initializer/GravityParticleInitializer.java index 3dde7d5d7..bf08927e3 100644 --- a/src/org/andengine/entity/particle/initializer/GravityParticleInitializer.java +++ b/src/org/andengine/entity/particle/initializer/GravityParticleInitializer.java @@ -5,9 +5,9 @@ import android.hardware.SensorManager; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 12:04:00 - 15.03.2010 */ diff --git a/src/org/andengine/entity/particle/initializer/IParticleInitializer.java b/src/org/andengine/entity/particle/initializer/IParticleInitializer.java index fd2e4f361..64a01968d 100644 --- a/src/org/andengine/entity/particle/initializer/IParticleInitializer.java +++ b/src/org/andengine/entity/particle/initializer/IParticleInitializer.java @@ -4,9 +4,9 @@ import org.andengine.entity.particle.Particle; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 10:12:09 - 29.06.2010 */ diff --git a/src/org/andengine/entity/particle/initializer/RotationParticleInitializer.java b/src/org/andengine/entity/particle/initializer/RotationParticleInitializer.java index 785eb8388..2a3bd9c2e 100644 --- a/src/org/andengine/entity/particle/initializer/RotationParticleInitializer.java +++ b/src/org/andengine/entity/particle/initializer/RotationParticleInitializer.java @@ -4,9 +4,9 @@ import org.andengine.entity.particle.Particle; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 10:17:42 - 29.06.2010 */ diff --git a/src/org/andengine/entity/particle/initializer/ScaleParticleInitializer.java b/src/org/andengine/entity/particle/initializer/ScaleParticleInitializer.java index 6a94826c7..626318877 100644 --- a/src/org/andengine/entity/particle/initializer/ScaleParticleInitializer.java +++ b/src/org/andengine/entity/particle/initializer/ScaleParticleInitializer.java @@ -5,7 +5,7 @@ /** - * (c) Zynga 2011 + * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 10:03:29 - 19.11.2011 diff --git a/src/org/andengine/entity/particle/initializer/VelocityParticleInitializer.java b/src/org/andengine/entity/particle/initializer/VelocityParticleInitializer.java index dd4c46458..f0c69b20f 100644 --- a/src/org/andengine/entity/particle/initializer/VelocityParticleInitializer.java +++ b/src/org/andengine/entity/particle/initializer/VelocityParticleInitializer.java @@ -4,9 +4,9 @@ import org.andengine.entity.particle.Particle; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 21:21:10 - 14.03.2010 */ diff --git a/src/org/andengine/entity/particle/modifier/AlphaParticleModifier.java b/src/org/andengine/entity/particle/modifier/AlphaParticleModifier.java index 93faec292..e57a9237d 100644 --- a/src/org/andengine/entity/particle/modifier/AlphaParticleModifier.java +++ b/src/org/andengine/entity/particle/modifier/AlphaParticleModifier.java @@ -6,9 +6,9 @@ import org.andengine.util.modifier.ease.IEaseFunction; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 21:21:10 - 14.03.2010 */ diff --git a/src/org/andengine/entity/particle/modifier/BaseDoubleValueSpanParticleModifier.java b/src/org/andengine/entity/particle/modifier/BaseDoubleValueSpanParticleModifier.java index 177fd125d..f78ef2b3f 100644 --- a/src/org/andengine/entity/particle/modifier/BaseDoubleValueSpanParticleModifier.java +++ b/src/org/andengine/entity/particle/modifier/BaseDoubleValueSpanParticleModifier.java @@ -6,9 +6,9 @@ import org.andengine.util.modifier.ease.IEaseFunction; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 15:19:46 - 29.06.2010 */ diff --git a/src/org/andengine/entity/particle/modifier/BaseSingleValueSpanParticleModifier.java b/src/org/andengine/entity/particle/modifier/BaseSingleValueSpanParticleModifier.java index caf014d51..d1342a156 100644 --- a/src/org/andengine/entity/particle/modifier/BaseSingleValueSpanParticleModifier.java +++ b/src/org/andengine/entity/particle/modifier/BaseSingleValueSpanParticleModifier.java @@ -6,9 +6,9 @@ import org.andengine.util.modifier.ease.IEaseFunction; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 16:10:16 - 04.05.2010 */ @@ -68,7 +68,7 @@ public void onInitializeParticle(final Particle pParticle) { @Override public void onUpdateParticle(final Particle pParticle) { final float lifeTime = pParticle.getLifeTime(); - if(lifeTime > this.mFromTime && lifeTime < this.mToTime) { + if (lifeTime > this.mFromTime && lifeTime < this.mToTime) { final float percentageDone = this.mEaseFunction.getPercentage((lifeTime - this.mFromTime), this.mDuration); this.onSetValue(pParticle, percentageDone, this.mFromValue + percentageDone * this.mValueSpan); } diff --git a/src/org/andengine/entity/particle/modifier/BaseTripleValueSpanParticleModifier.java b/src/org/andengine/entity/particle/modifier/BaseTripleValueSpanParticleModifier.java index b46418390..fb6fb90e9 100644 --- a/src/org/andengine/entity/particle/modifier/BaseTripleValueSpanParticleModifier.java +++ b/src/org/andengine/entity/particle/modifier/BaseTripleValueSpanParticleModifier.java @@ -6,9 +6,9 @@ import org.andengine.util.modifier.ease.IEaseFunction; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 15:19:46 - 29.06.2010 */ diff --git a/src/org/andengine/entity/particle/modifier/ColorParticleModifier.java b/src/org/andengine/entity/particle/modifier/ColorParticleModifier.java index 4a6c81852..365809cc5 100644 --- a/src/org/andengine/entity/particle/modifier/ColorParticleModifier.java +++ b/src/org/andengine/entity/particle/modifier/ColorParticleModifier.java @@ -2,13 +2,14 @@ import org.andengine.entity.IEntity; import org.andengine.entity.particle.Particle; +import org.andengine.util.adt.color.Color; import org.andengine.util.modifier.ease.EaseLinear; import org.andengine.util.modifier.ease.IEaseFunction; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 15:22:26 - 29.06.2010 */ @@ -25,6 +26,14 @@ public class ColorParticleModifier extends BaseTripleValueSpa // Constructors // =========================================================== + public ColorParticleModifier(final float pFromTime, final float pToTime, final Color pFromColor, final Color pToColor) { + this(pFromTime, pToTime, pFromColor.getRed(), pToColor.getRed(), pFromColor.getGreen(), pToColor.getGreen(), pFromColor.getBlue(), pToColor.getBlue()); + } + + public ColorParticleModifier(final float pFromTime, final float pToTime, final Color pFromColor, final Color pToColor, final IEaseFunction pEaseFunction) { + super(pFromTime, pToTime, pFromColor.getRed(), pToColor.getRed(), pFromColor.getGreen(), pToColor.getGreen(), pFromColor.getBlue(), pToColor.getBlue(), pEaseFunction); + } + public ColorParticleModifier(final float pFromTime, final float pToTime, final float pFromRed, final float pToRed, final float pFromGreen, final float pToGreen, final float pFromBlue, final float pToBlue) { this(pFromTime, pToTime, pFromRed, pToRed, pFromGreen, pToGreen, pFromBlue, pToBlue, EaseLinear.getInstance()); } diff --git a/src/org/andengine/entity/particle/modifier/IParticleModifier.java b/src/org/andengine/entity/particle/modifier/IParticleModifier.java index 1e9a1360d..e078b583c 100644 --- a/src/org/andengine/entity/particle/modifier/IParticleModifier.java +++ b/src/org/andengine/entity/particle/modifier/IParticleModifier.java @@ -5,9 +5,9 @@ import org.andengine.entity.particle.initializer.IParticleInitializer; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 20:06:05 - 14.03.2010 */ diff --git a/src/org/andengine/entity/particle/modifier/OffCameraExpireParticleModifier.java b/src/org/andengine/entity/particle/modifier/OffCameraExpireParticleModifier.java index 711ec363e..c2d54e29b 100644 --- a/src/org/andengine/entity/particle/modifier/OffCameraExpireParticleModifier.java +++ b/src/org/andengine/entity/particle/modifier/OffCameraExpireParticleModifier.java @@ -2,17 +2,17 @@ import org.andengine.engine.camera.Camera; +import org.andengine.entity.IEntity; import org.andengine.entity.particle.Particle; -import org.andengine.entity.shape.RectangularShape; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 21:21:10 - 14.03.2010 */ -public class OffCameraExpireParticleModifier implements IParticleModifier { +public class OffCameraExpireParticleModifier implements IParticleModifier { // =========================================================== // Constants // =========================================================== @@ -50,7 +50,7 @@ public void onInitializeParticle(final Particle pParticle) { @Override public void onUpdateParticle(final Particle pParticle) { - if(!this.mCamera.isRectangularShapeVisible(pParticle.getEntity())) { + if (!this.mCamera.isEntityVisible(pParticle.getEntity())) { pParticle.setExpired(true); } } diff --git a/src/org/andengine/entity/particle/modifier/RotationParticleModifier.java b/src/org/andengine/entity/particle/modifier/RotationParticleModifier.java index cd9a3de64..de8ec793b 100644 --- a/src/org/andengine/entity/particle/modifier/RotationParticleModifier.java +++ b/src/org/andengine/entity/particle/modifier/RotationParticleModifier.java @@ -6,9 +6,9 @@ import org.andengine.util.modifier.ease.IEaseFunction; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 10:36:18 - 29.06.2010 */ diff --git a/src/org/andengine/entity/particle/modifier/ScaleParticleModifier.java b/src/org/andengine/entity/particle/modifier/ScaleParticleModifier.java index 1243eee51..d94cf2786 100644 --- a/src/org/andengine/entity/particle/modifier/ScaleParticleModifier.java +++ b/src/org/andengine/entity/particle/modifier/ScaleParticleModifier.java @@ -6,9 +6,9 @@ import org.andengine.util.modifier.ease.IEaseFunction; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 20:37:27 - 04.05.2010 */ diff --git a/src/org/andengine/entity/primitive/DrawMode.java b/src/org/andengine/entity/primitive/DrawMode.java index b2ec80c2f..3471c591f 100644 --- a/src/org/andengine/entity/primitive/DrawMode.java +++ b/src/org/andengine/entity/primitive/DrawMode.java @@ -3,7 +3,7 @@ import android.opengl.GLES20; /** - * (c) Zynga 2012 + * (c) 2012 Zynga Inc. * * @author Nicolas Gramlich * @since 18:46:51 - 28.03.2012 diff --git a/src/org/andengine/entity/primitive/Gradient.java b/src/org/andengine/entity/primitive/Gradient.java new file mode 100644 index 000000000..88b996a58 --- /dev/null +++ b/src/org/andengine/entity/primitive/Gradient.java @@ -0,0 +1,484 @@ +package org.andengine.entity.primitive; + +import org.andengine.engine.camera.Camera; +import org.andengine.entity.primitive.vbo.HighPerformanceGradientVertexBufferObject; +import org.andengine.entity.primitive.vbo.IGradientVertexBufferObject; +import org.andengine.entity.shape.Shape; +import org.andengine.opengl.shader.PositionColorShaderProgram; +import org.andengine.opengl.shader.constants.ShaderProgramConstants; +import org.andengine.opengl.util.GLState; +import org.andengine.opengl.vbo.DrawType; +import org.andengine.opengl.vbo.VertexBufferObjectManager; +import org.andengine.opengl.vbo.attribute.VertexBufferObjectAttribute; +import org.andengine.opengl.vbo.attribute.VertexBufferObjectAttributes; +import org.andengine.opengl.vbo.attribute.VertexBufferObjectAttributesBuilder; +import org.andengine.util.adt.color.Color; +import org.andengine.util.math.MathUtils; + +import android.opengl.GLES20; + +/** + * (c) 2012 Zynga Inc. + * + * @author Nicolas Gramlich + * @since 14:23:56 - 23.04.2012 + */ +public class Gradient extends Shape { + // =========================================================== + // Constants + // =========================================================== + + public static final int VERTEX_INDEX_X = 0; + public static final int VERTEX_INDEX_Y = Gradient.VERTEX_INDEX_X + 1; + public static final int COLOR_INDEX = Gradient.VERTEX_INDEX_Y + 1; + + public static final int VERTEX_SIZE = 2 + 1; + public static final int VERTICES_PER_RECTANGLE = 4; + public static final int RECTANGLE_SIZE = Gradient.VERTEX_SIZE * Gradient.VERTICES_PER_RECTANGLE; + + public static final VertexBufferObjectAttributes VERTEXBUFFEROBJECTATTRIBUTES_DEFAULT = new VertexBufferObjectAttributesBuilder(2) + .add(ShaderProgramConstants.ATTRIBUTE_POSITION_LOCATION, ShaderProgramConstants.ATTRIBUTE_POSITION, 2, GLES20.GL_FLOAT, false) + .add(ShaderProgramConstants.ATTRIBUTE_COLOR_LOCATION, ShaderProgramConstants.ATTRIBUTE_COLOR, 4, GLES20.GL_UNSIGNED_BYTE, true) + .build(); + + // =========================================================== + // Fields + // =========================================================== + + protected final IGradientVertexBufferObject mGradientVertexBufferObject; + + private final Color mToColor = new Color(Color.WHITE); + private float mGradientVectorX = 0; + private float mGradientVectorY = -1; + private boolean mGradientFitToBounds; + private boolean mGradientDitherEnabled; + + // =========================================================== + // Constructors + // =========================================================== + + /** + * Uses a default {@link HighPerformanceGradientVertexBufferObject} in {@link DrawType#STATIC} with the {@link VertexBufferObjectAttribute}s: {@link Gradient#VERTEXBUFFEROBJECTATTRIBUTES_DEFAULT}. + */ + public Gradient(final float pX, final float pY, final float pWidth, final float pHeight, final VertexBufferObjectManager pVertexBufferObjectManager) { + this(pX, pY, pWidth, pHeight, pVertexBufferObjectManager, DrawType.STATIC); + } + + /** + * Uses a default {@link HighPerformanceGradientVertexBufferObject} with the {@link VertexBufferObjectAttribute}s: {@link Gradient#VERTEXBUFFEROBJECTATTRIBUTES_DEFAULT}. + */ + public Gradient(final float pX, final float pY, final float pWidth, final float pHeight, final VertexBufferObjectManager pVertexBufferObjectManager, final DrawType pDrawType) { + this(pX, pY, pWidth, pHeight, new HighPerformanceGradientVertexBufferObject(pVertexBufferObjectManager, Gradient.RECTANGLE_SIZE, pDrawType, true, Gradient.VERTEXBUFFEROBJECTATTRIBUTES_DEFAULT)); + } + + public Gradient(final float pX, final float pY, final float pWidth, final float pHeight, final IGradientVertexBufferObject pGradientVertexBufferObject) { + super(pX, pY, pWidth, pHeight, PositionColorShaderProgram.getInstance()); + + this.mGradientVertexBufferObject = pGradientVertexBufferObject; + + this.onUpdateVertices(); + this.onUpdateColor(); + + this.setBlendingEnabled(true); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + public boolean isGradientFitToBounds() { + return this.mGradientFitToBounds; + } + + /** + * @param pGradientFitToBounds If true ensures the from and to color are always on the bounds of the {@link Gradient} entity. + * If false the from and to color might exceed the bounds of the {@link Gradient} entity, depending on the angle/vector supplied. + */ + public void setGradientFitToBounds(final boolean pGradientFitToBounds) { + if (this.mGradientFitToBounds != pGradientFitToBounds) { + this.mGradientFitToBounds = pGradientFitToBounds; + + this.onUpdateColor(); + } + } + + public boolean isGradientDitherEnabled() { + return this.mGradientDitherEnabled; + } + + /** + * @param pGradientDitherEnabled true to enable dither, false to use the currently active dither setting in {@link GLState}. + */ + public void setGradientDitherEnabled(final boolean pGradientDitherEnabled) { + this.mGradientDitherEnabled = pGradientDitherEnabled; + } + + @Deprecated + @Override + public float getRed() { + return super.getRed(); + } + + @Deprecated + @Override + public float getGreen() { + return super.getGreen(); + } + + @Deprecated + @Override + public float getBlue() { + return super.getBlue(); + } + + @Deprecated + @Override + public float getAlpha() { + return super.getAlpha(); + } + + @Deprecated + @Override + public Color getColor() { + return super.getColor(); + } + + @Deprecated + @Override + public void setRed(final float pRed) { + super.setRed(pRed); + } + + @Deprecated + @Override + public void setGreen(final float pGreen) { + super.setGreen(pGreen); + } + + @Deprecated + @Override + public void setBlue(final float pBlue) { + super.setBlue(pBlue); + } + + @Deprecated + @Override + public void setAlpha(final float pAlpha) { + super.setAlpha(pAlpha); + } + + @Deprecated + @Override + public void setColor(final Color pColor) { + super.setColor(pColor); + } + + @Deprecated + @Override + public void setColor(final float pRed, final float pGreen, final float pBlue) { + super.setColor(pRed, pGreen, pBlue); + } + + @Deprecated + @Override + public void setColor(final float pRed, final float pGreen, final float pBlue, final float pAlpha) { + super.setColor(pRed, pGreen, pBlue, pAlpha); + } + + public float getFromRed() { + return super.getRed(); + } + + public float getFromGreen() { + return super.getGreen(); + } + + public float getFromBlue() { + return super.getBlue(); + } + + public float getFromAlpha() { + return super.getAlpha(); + } + + public Color getFromColor() { + return super.getColor(); + } + + /** + * @param pRed from 0.0f to 1.0f + */ + public void setFromRed(final float pRed) { + super.setRed(pRed); + } + + /** + * @param pGreen from 0.0f to 1.0f + */ + public void setFromGreen(final float pGreen) { + super.setGreen(pGreen); + } + + /** + * @param pBlue from 0.0f to 1.0f + */ + public void setFromBlue(final float pBlue) { + super.setBlue(pBlue); + } + + /** + * @param pAlpha from 0.0f (transparent) to 1.0f (opaque) + */ + public void setFromAlpha(final float pAlpha) { + super.setAlpha(pAlpha); + } + + /** + * @param pRed from 0.0f to 1.0f + * @param pGreen from 0.0f to 1.0f + * @param pBlue from 0.0f to 1.0f + */ + public void setFromColor(final float pRed, final float pGreen, final float pBlue) { + super.setColor(pRed, pGreen, pBlue); + } + + /** + * @param pRed from 0.0f to 1.0f + * @param pGreen from 0.0f to 1.0f + * @param pBlue from 0.0f to 1.0f + * @param pAlpha from 0.0f (transparent) to 1.0f (opaque) + */ + public void setFromColor(final float pRed, final float pGreen, final float pBlue, final float pAlpha) { + super.setColor(pRed, pGreen, pBlue, pAlpha); + } + + public void setFromColor(final Color pColor) { + super.setColor(pColor); + } + + public float getToRed() { + return this.mToColor.getRed(); + } + + public float getToGreen() { + return this.mToColor.getGreen(); + } + + public float getToBlue() { + return this.mToColor.getBlue(); + } + + public float getToAlpha() { + return this.mToColor.getAlpha(); + } + + public Color getToColor() { + return this.mToColor; + } + + /** + * @param pRed from 0.0f to 1.0f + */ + public void setToRed(final float pRed) { + if (this.mToColor.setRedChecking(pRed)) { // TODO Is this check worth it? + this.onUpdateColor(); + } + } + + /** + * @param pGreen from 0.0f to 1.0f + */ + public void setToGreen(final float pGreen) { + if (this.mToColor.setGreenChecking(pGreen)) { // TODO Is this check worth it? + this.onUpdateColor(); + } + } + + /** + * @param pBlue from 0.0f to 1.0f + */ + public void setToBlue(final float pBlue) { + if (this.mToColor.setBlueChecking(pBlue)) { // TODO Is this check worth it? + this.onUpdateColor(); + } + } + + /** + * @param pAlpha from 0.0f (transparent) to 1.0f (opaque) + */ + public void setToAlpha(final float pAlpha) { + if (this.mToColor.setAlphaChecking(pAlpha)) { // TODO Is this check worth it? + this.onUpdateColor(); + } + } + + /** + * @param pRed from 0.0f to 1.0f + * @param pGreen from 0.0f to 1.0f + * @param pBlue from 0.0f to 1.0f + */ + public void setToColor(final float pRed, final float pGreen, final float pBlue) { + if (this.mToColor.setChecking(pRed, pGreen, pBlue)) { // TODO Is this check worth it? + this.onUpdateColor(); + } + } + + /** + * @param pRed from 0.0f to 1.0f + * @param pGreen from 0.0f to 1.0f + * @param pBlue from 0.0f to 1.0f + * @param pAlpha from 0.0f (transparent) to 1.0f (opaque) + */ + public void setToColor(final float pRed, final float pGreen, final float pBlue, final float pAlpha) { + if (this.mToColor.setChecking(pRed, pGreen, pBlue, pAlpha)) { // TODO Is this check worth it? + this.onUpdateColor(); + } + } + + public void setToColor(final Color pColor) { + if (this.mToColor.setChecking(pColor)) { // TODO Is this check worth it? + this.onUpdateColor(); + } + } + + public float getGradientVectorX() { + return this.mGradientVectorX; + } + + public float getGradientVectorY() { + return this.mGradientVectorY; + } + + public void setGradientVectorX(final float pGradientVectorX) { + this.mGradientVectorX = pGradientVectorX; + + this.onUpdateColor(); + } + + public void setGradientVectorY(final float pGradientVectorY) { + this.mGradientVectorY = pGradientVectorY; + + this.onUpdateColor(); + } + + public void setGradientVector(final float pGradientVectorX, final float pGradientVectorY) { + this.mGradientVectorX = pGradientVectorX; + this.mGradientVectorY = pGradientVectorY; + + this.onUpdateColor(); + } + + /** + * @param pGradientAngle in degrees. 0 is a 'left-to-right', 90 is 'top-to-bottom', ... + */ + public void setGradientAngle(final float pGradientAngle) { + final float angleInRad = MathUtils.degToRad(pGradientAngle); + + this.setGradientVector((float) Math.cos(angleInRad), (float) Math.sin(angleInRad)); + } + + public void setGradientColor(final float pFromRed, final float pToRed, final float pFromGreen, final float pToGreen, final float pFromBlue, final float pToBlue) { + this.mColor.set(pFromRed, pFromGreen, pFromBlue); + this.mToColor.set(pToRed, pToGreen, pToBlue); + + this.onUpdateColor(); + } + + public void setGradientColor(final float pFromRed, final float pToRed, final float pFromGreen, final float pToGreen, final float pFromBlue, final float pToBlue, final float pFromAlpha, final float pToAlpha) { + this.mColor.set(pFromRed, pFromGreen, pFromBlue, pFromAlpha); + this.mToColor.set(pToRed, pToGreen, pToBlue, pToAlpha); + + this.onUpdateColor(); + } + + public void setGradientColor(final Color pFromColor, final Color pToColor) { + this.mColor.set(pFromColor); + this.mToColor.set(pToColor); + + this.onUpdateColor(); + } + + public void setGradient(final float pFromRed, final float pToRed, final float pFromGreen, final float pToGreen, final float pFromBlue, final float pToBlue, final float pGradientVectorX, final float pGradientVectorY) { + this.mGradientVectorX = pGradientVectorX; + this.mGradientVectorY = pGradientVectorY; + + this.mColor.set(pFromRed, pFromGreen, pFromBlue); + this.mToColor.set(pToRed, pToGreen, pToBlue); + + this.onUpdateColor(); + } + + public void setGradient(final float pFromRed, final float pToRed, final float pFromGreen, final float pToGreen, final float pFromBlue, final float pToBlue, final float pFromAlpha, final float pToAlpha, final float pGradientVectorX, final float pGradientVectorY) { + this.mGradientVectorX = pGradientVectorX; + this.mGradientVectorY = pGradientVectorY; + + this.mColor.set(pFromRed, pFromGreen, pFromBlue, pFromAlpha); + this.mToColor.set(pToRed, pToGreen, pToBlue, pToAlpha); + + this.onUpdateColor(); + } + + public void setGradient(final Color pFromColor, final Color pToColor, final float pGradientVectorX, final float pGradientVectorY) { + this.mGradientVectorX = pGradientVectorX; + this.mGradientVectorY = pGradientVectorY; + + this.mColor.set(pFromColor); + this.mToColor.set(pToColor); + + this.onUpdateColor(); + } + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + public IGradientVertexBufferObject getVertexBufferObject() { + return this.mGradientVertexBufferObject; + } + + @Override + protected void preDraw(final GLState pGLState, final Camera pCamera) { + super.preDraw(pGLState, pCamera); + + this.mGradientVertexBufferObject.bind(pGLState, this.mShaderProgram); + } + + @Override + protected void draw(final GLState pGLState, final Camera pCamera) { + if (this.mGradientDitherEnabled) { + final boolean wasDitherEnabled = pGLState.enableDither(); + + this.mGradientVertexBufferObject.draw(GLES20.GL_TRIANGLE_STRIP, Gradient.VERTICES_PER_RECTANGLE); + + pGLState.setDitherEnabled(wasDitherEnabled); + } else { + this.mGradientVertexBufferObject.draw(GLES20.GL_TRIANGLE_STRIP, Gradient.VERTICES_PER_RECTANGLE); + } + } + + @Override + protected void postDraw(final GLState pGLState, final Camera pCamera) { + this.mGradientVertexBufferObject.unbind(pGLState, this.mShaderProgram); + + super.postDraw(pGLState, pCamera); + } + + @Override + protected void onUpdateColor() { + this.mGradientVertexBufferObject.onUpdateColor(this); + } + + @Override + protected void onUpdateVertices() { + this.mGradientVertexBufferObject.onUpdateVertices(this); + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== +} \ No newline at end of file diff --git a/src/org/andengine/entity/primitive/Line.java b/src/org/andengine/entity/primitive/Line.java index 1bc892c53..57e3b47eb 100644 --- a/src/org/andengine/entity/primitive/Line.java +++ b/src/org/andengine/entity/primitive/Line.java @@ -1,10 +1,9 @@ package org.andengine.entity.primitive; import org.andengine.engine.camera.Camera; +import org.andengine.entity.IEntity; import org.andengine.entity.primitive.vbo.HighPerformanceLineVertexBufferObject; import org.andengine.entity.primitive.vbo.ILineVertexBufferObject; -import org.andengine.entity.shape.IShape; -import org.andengine.entity.shape.RectangularShape; import org.andengine.entity.shape.Shape; import org.andengine.opengl.shader.PositionColorShaderProgram; import org.andengine.opengl.shader.constants.ShaderProgramConstants; @@ -15,7 +14,6 @@ import org.andengine.opengl.vbo.attribute.VertexBufferObjectAttributes; import org.andengine.opengl.vbo.attribute.VertexBufferObjectAttributesBuilder; import org.andengine.util.algorithm.collision.LineCollisionChecker; -import org.andengine.util.algorithm.collision.RectangularShapeCollisionChecker; import org.andengine.util.exception.MethodNotSupportedException; import android.opengl.GLES20; @@ -23,7 +21,7 @@ /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 09:50:36 - 04.04.2010 */ @@ -32,7 +30,7 @@ public class Line extends Shape { // Constants // =========================================================== - public static final float LINE_WIDTH_DEFAULT = 1.0f; + public static final float LINE_WIDTH_DEFAULT = GLState.LINE_WIDTH_DEFAULT; public static final int VERTEX_INDEX_X = 0; public static final int VERTEX_INDEX_Y = Line.VERTEX_INDEX_X + 1; @@ -63,21 +61,21 @@ public class Line extends Shape { // =========================================================== /** - * Uses a default {@link HighPerformanceLineVertexBufferObject} in {@link DrawType#STATIC} with the {@link VertexBufferObjectAttribute}s: {@link Line#VERTEXBUFFEROBJECTATTRIBUTES_DEFAULT}. + * Uses a default {@link HighPerformanceLineVertexBufferObject} in {@link DrawType#STATIC} with the {@link VertexBufferObjectAttribute}s: {@link #VERTEXBUFFEROBJECTATTRIBUTES_DEFAULT}. */ public Line(final float pX1, final float pY1, final float pX2, final float pY2, final VertexBufferObjectManager pVertexBufferObjectManager) { this(pX1, pY1, pX2, pY2, Line.LINE_WIDTH_DEFAULT, pVertexBufferObjectManager, DrawType.STATIC); } /** - * Uses a default {@link HighPerformanceLineVertexBufferObject} with the {@link VertexBufferObjectAttribute}s: {@link Line#VERTEXBUFFEROBJECTATTRIBUTES_DEFAULT}. + * Uses a default {@link HighPerformanceLineVertexBufferObject} with the {@link VertexBufferObjectAttribute}s: {@link #VERTEXBUFFEROBJECTATTRIBUTES_DEFAULT}. */ public Line(final float pX1, final float pY1, final float pX2, final float pY2, final VertexBufferObjectManager pVertexBufferObjectManager, final DrawType pDrawType) { this(pX1, pY1, pX2, pY2, Line.LINE_WIDTH_DEFAULT, pVertexBufferObjectManager, pDrawType); } /** - * Uses a default {@link HighPerformanceLineVertexBufferObject} in {@link DrawType#STATIC} with the {@link VertexBufferObjectAttribute}s: {@link Line#VERTEXBUFFEROBJECTATTRIBUTES_DEFAULT}. + * Uses a default {@link HighPerformanceLineVertexBufferObject} in {@link DrawType#STATIC} with the {@link VertexBufferObjectAttribute}s: {@link #VERTEXBUFFEROBJECTATTRIBUTES_DEFAULT}. */ public Line(final float pX1, final float pY1, final float pX2, final float pY2, final float pLineWidth, final VertexBufferObjectManager pVertexBufferObjectManager) { this(pX1, pY1, pX2, pY2, pLineWidth, pVertexBufferObjectManager, DrawType.STATIC); @@ -88,11 +86,13 @@ public Line(final float pX1, final float pY1, final float pX2, final float pY2, } public Line(final float pX1, final float pY1, final float pX2, final float pY2, final float pLineWidth, final ILineVertexBufferObject pLineVertexBufferObject) { - super(pX1, pY1, PositionColorShaderProgram.getInstance()); + super(pX1, pY1, pX2 - pX1, pY2 - pY1, PositionColorShaderProgram.getInstance()); this.mX2 = pX2; this.mY2 = pY2; + this.setOffsetCenter(0, 0); + this.mLineWidth = pLineWidth; this.mLineVertexBufferObject = pLineVertexBufferObject; @@ -100,15 +100,6 @@ public Line(final float pX1, final float pY1, final float pX2, final float pY2, this.onUpdateVertices(); this.onUpdateColor(); - final float centerX = (this.mX2 - this.mX) * 0.5f; - final float centerY = (this.mY2 - this.mY) * 0.5f; - - this.mRotationCenterX = centerX; - this.mRotationCenterY = centerY; - - this.mScaleCenterX = this.mRotationCenterX; - this.mScaleCenterY = this.mRotationCenterY; - this.setBlendingEnabled(true); } @@ -117,7 +108,7 @@ public Line(final float pX1, final float pY1, final float pX2, final float pY2, // =========================================================== /** - * @deprecated Instead use {@link Line#getX1()} or {@link Line#getX2()}. + * @deprecated Instead use {@link #getX1()} or {@link #getX2()}. */ @Deprecated @Override @@ -126,7 +117,7 @@ public float getX() { } /** - * @deprecatedInstead use {@link Line#getY1()} or {@link Line#getY2()}. + * @deprecated Instead use {@link #getY1()} or {@link #getY2()}. */ @Deprecated @Override @@ -159,33 +150,37 @@ public void setLineWidth(final float pLineWidth) { } /** - * Instead use {@link Line#setPosition(float, float, float, float)}. + * Instead use {@link #setPosition(float, float, float, float)}. */ @Deprecated @Override public void setX(final float pX) { final float dX = this.mX - pX; + this.mX2 += dX; + super.setX(pX); - this.mX2 += dX; + this.onUpdateVertices(); } /** - * Instead use {@link Line#setPosition(float, float, float, float)}. + * Instead use {@link #setPosition(float, float, float, float)}. */ @Deprecated @Override public void setY(final float pY) { final float dY = this.mY - pY; - - super.setY(pY); - + this.mY2 += dY; + + super.setY(pY); + + this.onUpdateVertices(); } /** - * Instead use {@link Line#setPosition(float, float, float, float)}. + * Instead use {@link #setPosition(float, float, float, float)}. */ @Deprecated @Override @@ -193,10 +188,12 @@ public void setPosition(final float pX, final float pY) { final float dX = this.mX - pX; final float dY = this.mY - pY; - super.setPosition(pX, pY); - this.mX2 += dX; this.mY2 += dY; + + super.setPosition(pX, pY); + + this.onUpdateVertices(); } public void setPosition(final float pX1, final float pY1, final float pX2, final float pY2) { @@ -208,6 +205,24 @@ public void setPosition(final float pX1, final float pY1, final float pX2, final this.onUpdateVertices(); } + @Deprecated + @Override + public void setWidth(final float pWidth) { + super.setWidth(pWidth); + } + + @Deprecated + @Override + public void setHeight(final float pHeight) { + super.setHeight(pHeight); + } + + @Deprecated + @Override + public void setSize(final float pWidth, final float pHeight) { + super.setSize(pWidth, pHeight); + } + // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @@ -270,14 +285,12 @@ public boolean contains(final float pX, final float pY) { } @Override - public boolean collidesWith(final IShape pOtherShape) { - if(pOtherShape instanceof Line) { - final Line otherLine = (Line) pOtherShape; + public boolean collidesWith(final IEntity pOtherEntity) { + if (pOtherEntity instanceof Line) { + final Line otherLine = (Line) pOtherEntity; return LineCollisionChecker.checkLineCollision(this.mX, this.mY, this.mX2, this.mY2, otherLine.mX, otherLine.mY, otherLine.mX2, otherLine.mY2); - } else if(pOtherShape instanceof RectangularShape) { - return RectangularShapeCollisionChecker.checkCollision((RectangularShape) pOtherShape, this); } else { - return false; + return super.collidesWith(pOtherEntity); } } diff --git a/src/org/andengine/entity/primitive/LineChain.java b/src/org/andengine/entity/primitive/LineChain.java new file mode 100644 index 000000000..27db8f6c5 --- /dev/null +++ b/src/org/andengine/entity/primitive/LineChain.java @@ -0,0 +1,311 @@ +package org.andengine.entity.primitive; + +import org.andengine.engine.camera.Camera; +import org.andengine.entity.primitive.vbo.HighPerformanceLineChainVertexBufferObject; +import org.andengine.entity.primitive.vbo.ILineChainVertexBufferObject; +import org.andengine.entity.shape.Shape; +import org.andengine.opengl.shader.PositionColorShaderProgram; +import org.andengine.opengl.shader.constants.ShaderProgramConstants; +import org.andengine.opengl.util.GLState; +import org.andengine.opengl.vbo.DrawType; +import org.andengine.opengl.vbo.VertexBufferObjectManager; +import org.andengine.opengl.vbo.attribute.VertexBufferObjectAttribute; +import org.andengine.opengl.vbo.attribute.VertexBufferObjectAttributes; +import org.andengine.opengl.vbo.attribute.VertexBufferObjectAttributesBuilder; +import org.andengine.util.exception.MethodNotSupportedException; + +import android.opengl.GLES20; + +/** + * (c) 2013 Nicolas Gramlich + * + * @author Nicolas Gramlich + * @since 20:26:36 - 30.05.2013 + */ +public abstract class LineChain extends Shape { + // =========================================================== + // Constants + // =========================================================== + + public static final float LINE_WIDTH_DEFAULT = GLState.LINE_WIDTH_DEFAULT; + + public static final int VERTEX_INDEX_X = 0; + public static final int VERTEX_INDEX_Y = LineChain.VERTEX_INDEX_X + 1; + public static final int COLOR_INDEX = LineChain.VERTEX_INDEX_Y + 1; + + public static final int VERTEX_SIZE = 2 + 1; + + public static final VertexBufferObjectAttributes VERTEXBUFFEROBJECTATTRIBUTES_DEFAULT = new VertexBufferObjectAttributesBuilder(2) + .add(ShaderProgramConstants.ATTRIBUTE_POSITION_LOCATION, ShaderProgramConstants.ATTRIBUTE_POSITION, 2, GLES20.GL_FLOAT, false) + .add(ShaderProgramConstants.ATTRIBUTE_COLOR_LOCATION, ShaderProgramConstants.ATTRIBUTE_COLOR, 4, GLES20.GL_UNSIGNED_BYTE, true) + .build(); + + // =========================================================== + // Fields + // =========================================================== + + protected int mCapacity; + protected final ILineChainVertexBufferObject mLineChainVertexBufferObject; + + protected final float[] mXs; + protected final float[] mYs; + + protected float mLineWidth; + + protected int mIndex; + + // =========================================================== + // Constructors + // =========================================================== + + /** + * Uses a default {@link HighPerformanceLineChainVertexBufferObject} in {@link DrawType#STATIC} with the {@link VertexBufferObjectAttribute}s: {@link #VERTEXBUFFEROBJECTATTRIBUTES_DEFAULT}. + */ + public LineChain(final float pX, final float pY, final int pCapacity, final VertexBufferObjectManager pVertexBufferObjectManager) { + this(pX, pY, LineChain.LINE_WIDTH_DEFAULT, pCapacity, pVertexBufferObjectManager, DrawType.STATIC); + } + + /** + * Uses a default {@link HighPerformanceLineChainVertexBufferObject} with the {@link VertexBufferObjectAttribute}s: {@link #VERTEXBUFFEROBJECTATTRIBUTES_DEFAULT}. + */ + public LineChain(final float pX, final float pY, final int pCapacity, final VertexBufferObjectManager pVertexBufferObjectManager, final DrawType pDrawType) { + this(pX, pY, LineChain.LINE_WIDTH_DEFAULT, pCapacity, pVertexBufferObjectManager, pDrawType); + } + + /** + * Uses a default {@link HighPerformanceLineChainVertexBufferObject} in {@link DrawType#STATIC} with the {@link VertexBufferObjectAttribute}s: {@link #VERTEXBUFFEROBJECTATTRIBUTES_DEFAULT}. + */ + public LineChain(final float pX, final float pY, final float pLineWidth, final int pCapacity, final VertexBufferObjectManager pVertexBufferObjectManager) { + this(pX, pY, pLineWidth, pCapacity, pVertexBufferObjectManager, DrawType.STATIC); + } + + public LineChain(final float pX, final float pY, final float pLineWidth, final int pCapacity, final VertexBufferObjectManager pVertexBufferObjectManager, final DrawType pDrawType) { + this(pX, pY, pLineWidth, pCapacity, new HighPerformanceLineChainVertexBufferObject(pVertexBufferObjectManager, pCapacity * LineChain.VERTEX_SIZE, pDrawType, true, LineChain.VERTEXBUFFEROBJECTATTRIBUTES_DEFAULT)); + } + + public LineChain(final float pX, final float pY, final float pLineWidth, final int pCapacity, final ILineChainVertexBufferObject pLineChainVertexBufferObject) { + super(pX, pY, 0, 0, PositionColorShaderProgram.getInstance()); + + this.mXs = new float[pCapacity]; + this.mYs = new float[pCapacity]; + this.mCapacity = pCapacity; + + this.mLineWidth = pLineWidth; + + this.mLineChainVertexBufferObject = pLineChainVertexBufferObject; + + this.onUpdateVertices(); + this.onUpdateColor(); + + this.setBlendingEnabled(true); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + public int getCapacity() { + return this.mCapacity; + } + + public int getIndex() { + return this.mIndex; + } + + public void setIndex(final int pIndex) { + this.assertCapacity(pIndex); + + this.mIndex = pIndex; + } + + public float getLineWidth() { + return this.mLineWidth; + } + + public void setLineWidth(final float pLineWidth) { + this.mLineWidth = pLineWidth; + } + + @Override + public void setX(final float pX) { + final float dX = this.mX - pX; + + for (int i = this.mIndex - 1; i >= 0; i++) { + this.mXs[i] += dX; + } + + super.setX(pX); + + this.onUpdateVertices(); + } + + @Override + public void setY(final float pY) { + final float dY = this.mY - pY; + + for (int i = this.mIndex - 1; i >= 0; i++) { + this.mYs[i] += dY; + } + + super.setY(pY); + + this.onUpdateVertices(); + } + + @Override + public void setPosition(final float pX, final float pY) { + final float dX = this.mX - pX; + final float dY = this.mY - pY; + + for (int i = this.mIndex - 1; i >= 0; i++) { + this.mXs[i] += dX; + this.mYs[i] += dY; + } + + super.setPosition(pX, pY); + + this.onUpdateVertices(); + } + + public float getX(final int pIndex) { + this.assertCapacity(pIndex); + + return this.mX + this.mXs[pIndex]; + } + + public float getY(final int pIndex) { + this.assertCapacity(pIndex); + + return this.mY + this.mYs[pIndex]; + } + + public void setX(final int pIndex, final float pX) { + this.assertCapacity(pIndex); + this.assertIndex(pIndex); + + this.mXs[pIndex] = pX; + + this.onUpdateVertices(); + } + + public void setY(final int pIndex, final float pY) { + this.assertCapacity(pIndex); + this.assertIndex(pIndex); + + this.mYs[pIndex] = pY; + + this.onUpdateVertices(); + } + + public void add(final float pX, final float pY) { + this.assertCapacity(); + + this.mXs[this.mIndex] = pX; + this.mYs[this.mIndex] = pY; + + this.mIndex++; + + this.onUpdateVertices(); + } + + public void shift() { + final int length = this.mCapacity - 1; + System.arraycopy(this.mXs, 0, this.mXs, 1, length); + System.arraycopy(this.mYs, 0, this.mYs, 1, length); + } + + @Deprecated + @Override + public void setWidth(final float pWidth) { + super.setWidth(pWidth); + } + + @Deprecated + @Override + public void setHeight(final float pHeight) { + super.setHeight(pHeight); + } + + @Deprecated + @Override + public void setSize(final float pWidth, final float pHeight) { + super.setSize(pWidth, pHeight); + } + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + public ILineChainVertexBufferObject getVertexBufferObject() { + return this.mLineChainVertexBufferObject; + } + + @Override + protected void preDraw(final GLState pGLState, final Camera pCamera) { + super.preDraw(pGLState, pCamera); + + pGLState.lineWidth(this.mLineWidth); + + this.mLineChainVertexBufferObject.bind(pGLState, this.mShaderProgram); + } + + @Override + protected void postDraw(final GLState pGLState, final Camera pCamera) { + this.mLineChainVertexBufferObject.unbind(pGLState, this.mShaderProgram); + + super.postDraw(pGLState, pCamera); + } + + @Override + protected void onUpdateColor() { + this.mLineChainVertexBufferObject.onUpdateColor(this); + } + + @Override + protected void onUpdateVertices() { + this.mLineChainVertexBufferObject.onUpdateVertices(this); + } + + @Override + public float[] getSceneCenterCoordinates() { + throw new MethodNotSupportedException(); + } + + @Override + public float[] getSceneCenterCoordinates(final float[] pReuse) { + throw new MethodNotSupportedException(); + } + + @Override + @Deprecated + public boolean contains(final float pX, final float pY) { + throw new MethodNotSupportedException(); + } + + // =========================================================== + // Methods + // =========================================================== + + private void assertIndex(final int pIndex) { + if (pIndex >= this.mIndex - 1) { + throw new IllegalStateException("This supplied pIndex: '" + pIndex + "' is exceeding the current index: '" + this.mIndex + "' of this " + this.getClass().getSimpleName() + "!"); + } + } + + private void assertCapacity(final int pIndex) { + if (pIndex >= this.mCapacity) { + throw new IllegalStateException("This supplied pIndex: '" + pIndex + "' is exceeding the capacity: '" + this.mCapacity + "' of this " + this.getClass().getSimpleName() + "!"); + } + } + + private void assertCapacity() { + if (this.mIndex == this.mCapacity) { + throw new IllegalStateException("This " + this.getClass().getSimpleName() + " has already reached its capacity (" + this.mCapacity + ") !"); + } + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== +} \ No newline at end of file diff --git a/src/org/andengine/entity/primitive/LineLoop.java b/src/org/andengine/entity/primitive/LineLoop.java new file mode 100644 index 000000000..b1a8ea454 --- /dev/null +++ b/src/org/andengine/entity/primitive/LineLoop.java @@ -0,0 +1,70 @@ +package org.andengine.entity.primitive; + +import org.andengine.engine.camera.Camera; +import org.andengine.entity.primitive.vbo.ILineChainVertexBufferObject; +import org.andengine.opengl.util.GLState; +import org.andengine.opengl.vbo.DrawType; +import org.andengine.opengl.vbo.VertexBufferObjectManager; + +import android.opengl.GLES20; + +/** + * (c) 2013 Nicolas Gramlich + * + * @author Nicolas Gramlich + * @since 13:51:36 - 01.06.2013 + */ +public class LineLoop extends LineChain { + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + // =========================================================== + // Constructors + // =========================================================== + + public LineLoop(final float pX, final float pY, final int pCapacity, final VertexBufferObjectManager pVertexBufferObjectManager) { + super(pX, pY, pCapacity, pVertexBufferObjectManager); + } + + public LineLoop(final float pX, final float pY, final int pCapacity, final VertexBufferObjectManager pVertexBufferObjectManager, final DrawType pDrawType) { + super(pX, pY, pCapacity, pVertexBufferObjectManager, pDrawType); + } + + public LineLoop(final float pX, final float pY, final float pLineWidth, final int pCapacity, final VertexBufferObjectManager pVertexBufferObjectManager) { + super(pX, pY, pLineWidth, pCapacity, pVertexBufferObjectManager); + } + + public LineLoop(final float pX, final float pY, final float pLineWidth, final int pCapacity, final VertexBufferObjectManager pVertexBufferObjectManager, final DrawType pDrawType) { + super(pX, pY, pLineWidth, pCapacity, pVertexBufferObjectManager, pDrawType); + } + + public LineLoop(final float pX, final float pY, final float pLineWidth, final int pCapacity, final ILineChainVertexBufferObject pLineChainVertexBufferObject) { + super(pX, pY, pLineWidth, pCapacity, pLineChainVertexBufferObject); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + protected void draw(final GLState pGLState, final Camera pCamera) { + this.mLineChainVertexBufferObject.draw(GLES20.GL_LINE_LOOP, this.mIndex); + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== +} diff --git a/src/org/andengine/entity/primitive/LineStrip.java b/src/org/andengine/entity/primitive/LineStrip.java new file mode 100644 index 000000000..c9b5959b1 --- /dev/null +++ b/src/org/andengine/entity/primitive/LineStrip.java @@ -0,0 +1,70 @@ +package org.andengine.entity.primitive; + +import org.andengine.engine.camera.Camera; +import org.andengine.entity.primitive.vbo.ILineChainVertexBufferObject; +import org.andengine.opengl.util.GLState; +import org.andengine.opengl.vbo.DrawType; +import org.andengine.opengl.vbo.VertexBufferObjectManager; + +import android.opengl.GLES20; + +/** + * (c) 2013 Nicolas Gramlich + * + * @author Nicolas Gramlich + * @since 13:51:36 - 01.06.2013 + */ +public class LineStrip extends LineChain { + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + // =========================================================== + // Constructors + // =========================================================== + + public LineStrip(final float pX, final float pY, final int pCapacity, final VertexBufferObjectManager pVertexBufferObjectManager) { + super(pX, pY, pCapacity, pVertexBufferObjectManager); + } + + public LineStrip(final float pX, final float pY, final int pCapacity, final VertexBufferObjectManager pVertexBufferObjectManager, final DrawType pDrawType) { + super(pX, pY, pCapacity, pVertexBufferObjectManager, pDrawType); + } + + public LineStrip(final float pX, final float pY, final float pLineWidth, final int pCapacity, final VertexBufferObjectManager pVertexBufferObjectManager) { + super(pX, pY, pLineWidth, pCapacity, pVertexBufferObjectManager); + } + + public LineStrip(final float pX, final float pY, final float pLineWidth, final int pCapacity, final VertexBufferObjectManager pVertexBufferObjectManager, final DrawType pDrawType) { + super(pX, pY, pLineWidth, pCapacity, pVertexBufferObjectManager, pDrawType); + } + + public LineStrip(final float pX, final float pY, final float pLineWidth, final int pCapacity, final ILineChainVertexBufferObject pLineChainVertexBufferObject) { + super(pX, pY, pLineWidth, pCapacity, pLineChainVertexBufferObject); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + protected void draw(final GLState pGLState, final Camera pCamera) { + this.mLineChainVertexBufferObject.draw(GLES20.GL_LINE_STRIP, this.mIndex); + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== +} diff --git a/src/org/andengine/entity/primitive/Mesh.java b/src/org/andengine/entity/primitive/Mesh.java index 0f083e4e1..840968e91 100644 --- a/src/org/andengine/entity/primitive/Mesh.java +++ b/src/org/andengine/entity/primitive/Mesh.java @@ -1,10 +1,9 @@ package org.andengine.entity.primitive; import org.andengine.engine.camera.Camera; +import org.andengine.entity.IEntity; import org.andengine.entity.primitive.vbo.HighPerformanceMeshVertexBufferObject; import org.andengine.entity.primitive.vbo.IMeshVertexBufferObject; -import org.andengine.entity.shape.IShape; -import org.andengine.entity.shape.RectangularShape; import org.andengine.entity.shape.Shape; import org.andengine.opengl.shader.PositionColorShaderProgram; import org.andengine.opengl.shader.constants.ShaderProgramConstants; @@ -19,7 +18,7 @@ import android.opengl.GLES20; /** - * (c) Zynga 2012 + * (c) 2012 Zynga Inc. * * @author Nicolas Gramlich * @since 16:44:50 - 09.02.2012 @@ -56,18 +55,36 @@ public class Mesh extends Shape { * Uses a default {@link HighPerformanceMeshVertexBufferObject} in {@link DrawType#STATIC} with the {@link VertexBufferObjectAttribute}s: {@link Mesh#VERTEXBUFFEROBJECTATTRIBUTES_DEFAULT}. */ public Mesh(final float pX, final float pY, final float[] pBufferData, final int pVertexCount, final DrawMode pDrawMode, final VertexBufferObjectManager pVertexBufferObjectManager) { - this(pX, pY, pBufferData, pVertexCount, pDrawMode, pVertexBufferObjectManager, DrawType.STATIC); + this(pX, pY, 0, 0, pBufferData, pVertexCount, pDrawMode, pVertexBufferObjectManager); + } + + /** + * Uses a default {@link HighPerformanceMeshVertexBufferObject} in {@link DrawType#STATIC} with the {@link VertexBufferObjectAttribute}s: {@link Mesh#VERTEXBUFFEROBJECTATTRIBUTES_DEFAULT}. + */ + public Mesh(final float pX, final float pY, final float pWidth, final float pHeight, final float[] pBufferData, final int pVertexCount, final DrawMode pDrawMode, final VertexBufferObjectManager pVertexBufferObjectManager) { + this(pX, pY, pWidth, pHeight, pBufferData, pVertexCount, pDrawMode, pVertexBufferObjectManager, DrawType.STATIC); } /** * Uses a default {@link HighPerformanceMeshVertexBufferObject} with the {@link VertexBufferObjectAttribute}s: {@link Mesh#VERTEXBUFFEROBJECTATTRIBUTES_DEFAULT}. */ public Mesh(final float pX, final float pY, final float[] pBufferData, final int pVertexCount, final DrawMode pDrawMode, final VertexBufferObjectManager pVertexBufferObjectManager, final DrawType pDrawType) { - this(pX, pY, pVertexCount, pDrawMode, new HighPerformanceMeshVertexBufferObject(pVertexBufferObjectManager, pBufferData, pVertexCount, pDrawType, true, Mesh.VERTEXBUFFEROBJECTATTRIBUTES_DEFAULT)); + this(pX, pY, 0, 0, pBufferData, pVertexCount, pDrawMode, pVertexBufferObjectManager, pDrawType); + } + + /** + * Uses a default {@link HighPerformanceMeshVertexBufferObject} with the {@link VertexBufferObjectAttribute}s: {@link Mesh#VERTEXBUFFEROBJECTATTRIBUTES_DEFAULT}. + */ + public Mesh(final float pX, final float pY, final float pWidth, final float pHeight, final float[] pBufferData, final int pVertexCount, final DrawMode pDrawMode, final VertexBufferObjectManager pVertexBufferObjectManager, final DrawType pDrawType) { + this(pX, pY, pWidth, pHeight, pVertexCount, pDrawMode, new HighPerformanceMeshVertexBufferObject(pVertexBufferObjectManager, pBufferData, pVertexCount, pDrawType, true, Mesh.VERTEXBUFFEROBJECTATTRIBUTES_DEFAULT)); } public Mesh(final float pX, final float pY, final int pVertexCount, final DrawMode pDrawMode, final IMeshVertexBufferObject pMeshVertexBufferObject) { - super(pX, pY, PositionColorShaderProgram.getInstance()); + this(pX, pY, 0, 0, pVertexCount, pDrawMode, pMeshVertexBufferObject); + } + + public Mesh(final float pX, final float pY, final float pWidth, final float pHeight, final int pVertexCount, final DrawMode pDrawMode, final IMeshVertexBufferObject pMeshVertexBufferObject) { + super(pX, pY, pWidth, pHeight, PositionColorShaderProgram.getInstance()); this.mDrawMode = pDrawMode.getDrawMode(); this.mMeshVertexBufferObject = pMeshVertexBufferObject; @@ -139,15 +156,15 @@ public boolean contains(final float pX, final float pY) { } @Override - public boolean collidesWith(final IShape pOtherShape) { - if(pOtherShape instanceof Line) { + public boolean collidesWith(final IEntity pOtherEntity) { + if (pOtherEntity instanceof Mesh) { // TODO - return false; - } else if(pOtherShape instanceof RectangularShape) { + return super.collidesWith(pOtherEntity); + } else if (pOtherEntity instanceof Line) { // TODO - return false; + return super.collidesWith(pOtherEntity); } else { - return false; + return super.collidesWith(pOtherEntity); } } diff --git a/src/org/andengine/entity/primitive/Rectangle.java b/src/org/andengine/entity/primitive/Rectangle.java index 1eeab4434..c56ec30b6 100644 --- a/src/org/andengine/entity/primitive/Rectangle.java +++ b/src/org/andengine/entity/primitive/Rectangle.java @@ -3,7 +3,7 @@ import org.andengine.engine.camera.Camera; import org.andengine.entity.primitive.vbo.HighPerformanceRectangleVertexBufferObject; import org.andengine.entity.primitive.vbo.IRectangleVertexBufferObject; -import org.andengine.entity.shape.RectangularShape; +import org.andengine.entity.shape.Shape; import org.andengine.opengl.shader.PositionColorShaderProgram; import org.andengine.opengl.shader.constants.ShaderProgramConstants; import org.andengine.opengl.util.GLState; @@ -18,11 +18,11 @@ /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 12:18:49 - 13.03.2010 */ -public class Rectangle extends RectangularShape { +public class Rectangle extends Shape { // =========================================================== // Constants // =========================================================== diff --git a/src/org/andengine/entity/primitive/vbo/HighPerformanceGradientVertexBufferObject.java b/src/org/andengine/entity/primitive/vbo/HighPerformanceGradientVertexBufferObject.java new file mode 100644 index 000000000..0ead93196 --- /dev/null +++ b/src/org/andengine/entity/primitive/vbo/HighPerformanceGradientVertexBufferObject.java @@ -0,0 +1,129 @@ +package org.andengine.entity.primitive.vbo; + +import org.andengine.entity.primitive.Gradient; +import org.andengine.opengl.vbo.DrawType; +import org.andengine.opengl.vbo.HighPerformanceVertexBufferObject; +import org.andengine.opengl.vbo.VertexBufferObjectManager; +import org.andengine.opengl.vbo.attribute.VertexBufferObjectAttributes; +import org.andengine.util.adt.color.ColorUtils; +import org.andengine.util.math.MathConstants; +import org.andengine.util.math.MathUtils; + +/** + * (c) 2012 Zynga Inc. + * + * @author Nicolas Gramlich + * @since 14:27:09 - 23.04.2012 + */ +public class HighPerformanceGradientVertexBufferObject extends HighPerformanceVertexBufferObject implements IGradientVertexBufferObject { + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + // =========================================================== + // Constructors + // =========================================================== + + public HighPerformanceGradientVertexBufferObject(final VertexBufferObjectManager pVertexBufferObjectManager, final int pCapacity, final DrawType pDrawType, final boolean pAutoDispose, final VertexBufferObjectAttributes pVertexBufferObjectAttributes) { + super(pVertexBufferObjectManager, pCapacity, pDrawType, pAutoDispose, pVertexBufferObjectAttributes); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + public void onUpdateColor(final Gradient pGradient) { + final float[] bufferData = this.mBufferData; + + final float gradientVectorX = pGradient.getGradientVectorX(); + final float gradientVectorY = pGradient.getGradientVectorY(); + + final float length = MathUtils.length(gradientVectorX, gradientVectorY); + if (length == 0) { + return; + } + + float dX = gradientVectorX / length; + float dY = gradientVectorY / length; + + final float c = MathConstants.SQRT_2; + final float c2 = 2 * c; + + if (pGradient.isGradientFitToBounds()) { + final float tmp = 1 / (Math.abs(dX) + Math.abs(dY)); + dX *= tmp * c; + dY *= tmp * c; + } + + final float fromRed = pGradient.getFromRed(); + final float fromGreen = pGradient.getFromGreen(); + final float fromBlue = pGradient.getFromBlue(); + final float fromAlpha = pGradient.getFromAlpha(); // TODO * 'this.mOverallOpactity' + + final float toRed = pGradient.getToRed(); + final float toGreen = pGradient.getToGreen(); + final float toBlue = pGradient.getToBlue(); + final float toAlpha = pGradient.getToAlpha(); // TODO * 'this.mOverallOpactity' + + /* Pre-fetch some calculations. */ + final float dRed = fromRed - toRed; + final float dGreen = fromGreen - toGreen; + final float dBlue = fromBlue - toBlue; + final float dAlpha = fromAlpha - toAlpha; + + + final float v0 = (c + dX + dY) / c2; + bufferData[(0 * Gradient.VERTEX_SIZE) + Gradient.COLOR_INDEX] = ColorUtils.convertRGBAToABGRPackedFloat(toRed + (dRed * v0), toGreen + (dGreen * v0), toBlue + (dBlue * v0), toAlpha + (dAlpha * v0)); + + final float v1 = (c + dX - dY) / c2; + bufferData[(1 * Gradient.VERTEX_SIZE) + Gradient.COLOR_INDEX] = ColorUtils.convertRGBAToABGRPackedFloat(toRed + (dRed * v1), toGreen + (dGreen * v1), toBlue + (dBlue * v1), toAlpha + (dAlpha * v1)); + + final float v2 = (c - dX + dY) / c2; + bufferData[(2 * Gradient.VERTEX_SIZE) + Gradient.COLOR_INDEX] = ColorUtils.convertRGBAToABGRPackedFloat(toRed + (dRed * v2), toGreen + (dGreen * v2), toBlue + (dBlue * v2), toAlpha + (dAlpha * v2)); + + final float v3 = (c - dX - dY) / c2; + bufferData[(3 * Gradient.VERTEX_SIZE) + Gradient.COLOR_INDEX] = ColorUtils.convertRGBAToABGRPackedFloat(toRed + (dRed * v3), toGreen + (dGreen * v3), toBlue + (dBlue * v3), toAlpha + (dAlpha * v3)); + + + this.setDirtyOnHardware(); + } + + @Override + public void onUpdateVertices(final Gradient pGradient) { + final float[] bufferData = this.mBufferData; + + final float width = pGradient.getWidth(); // TODO Optimize with field access? + final float height = pGradient.getHeight(); // TODO Optimize with field access? + + bufferData[(0 * Gradient.VERTEX_SIZE) + Gradient.VERTEX_INDEX_X] = 0; + bufferData[(0 * Gradient.VERTEX_SIZE) + Gradient.VERTEX_INDEX_Y] = 0; + + bufferData[(1 * Gradient.VERTEX_SIZE) + Gradient.VERTEX_INDEX_X] = 0; + bufferData[(1 * Gradient.VERTEX_SIZE) + Gradient.VERTEX_INDEX_Y] = height; + + bufferData[(2 * Gradient.VERTEX_SIZE) + Gradient.VERTEX_INDEX_X] = width; + bufferData[(2 * Gradient.VERTEX_SIZE) + Gradient.VERTEX_INDEX_Y] = 0; + + bufferData[(3 * Gradient.VERTEX_SIZE) + Gradient.VERTEX_INDEX_X] = width; + bufferData[(3 * Gradient.VERTEX_SIZE) + Gradient.VERTEX_INDEX_Y] = height; + + this.setDirtyOnHardware(); + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== +} \ No newline at end of file diff --git a/src/org/andengine/entity/primitive/vbo/HighPerformanceLineChainVertexBufferObject.java b/src/org/andengine/entity/primitive/vbo/HighPerformanceLineChainVertexBufferObject.java new file mode 100644 index 000000000..c95700ff8 --- /dev/null +++ b/src/org/andengine/entity/primitive/vbo/HighPerformanceLineChainVertexBufferObject.java @@ -0,0 +1,78 @@ +package org.andengine.entity.primitive.vbo; + +import org.andengine.entity.primitive.LineChain; +import org.andengine.opengl.vbo.DrawType; +import org.andengine.opengl.vbo.HighPerformanceVertexBufferObject; +import org.andengine.opengl.vbo.VertexBufferObjectManager; +import org.andengine.opengl.vbo.attribute.VertexBufferObjectAttributes; + +/** + * (c) 2013 Nicolas Gramlich + * + * @author Nicolas Gramlich + * @since 21:50:00 - 30.05.2013 + */ +public class HighPerformanceLineChainVertexBufferObject extends HighPerformanceVertexBufferObject implements ILineChainVertexBufferObject { + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + // =========================================================== + // Constructors + // =========================================================== + + public HighPerformanceLineChainVertexBufferObject(final VertexBufferObjectManager pVertexBufferObjectManager, final int pCapacity, final DrawType pDrawType, final boolean pAutoDispose, final VertexBufferObjectAttributes pVertexBufferObjectAttributes) { + super(pVertexBufferObjectManager, pCapacity, pDrawType, pAutoDispose, pVertexBufferObjectAttributes); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + public void onUpdateColor(final LineChain pLineChain) { + final float[] bufferData = this.mBufferData; + + final float packedColor = pLineChain.getColor().getABGRPackedFloat(); + + for (int i = pLineChain.getCapacity() - 1; i >= 0; i--) { + bufferData[(i * LineChain.VERTEX_SIZE) + LineChain.COLOR_INDEX] = packedColor; + } + + this.setDirtyOnHardware(); + } + + @Override + public void onUpdateVertices(final LineChain pLineChain) { + final float[] bufferData = this.mBufferData; + + bufferData[(0 * LineChain.VERTEX_SIZE) + LineChain.VERTEX_INDEX_X] = 0; + bufferData[(0 * LineChain.VERTEX_SIZE) + LineChain.VERTEX_INDEX_Y] = 0; + + final float x = pLineChain.getX(); + final float y = pLineChain.getY(); + + for (int i = pLineChain.getCapacity() - 1; i >= 0; i--) { + bufferData[(i * LineChain.VERTEX_SIZE) + LineChain.VERTEX_INDEX_X] = pLineChain.getX(i) - x; + bufferData[(i * LineChain.VERTEX_SIZE) + LineChain.VERTEX_INDEX_Y] = pLineChain.getY(i) - y; + } + + this.setDirtyOnHardware(); + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== +} \ No newline at end of file diff --git a/src/org/andengine/entity/primitive/vbo/HighPerformanceLineVertexBufferObject.java b/src/org/andengine/entity/primitive/vbo/HighPerformanceLineVertexBufferObject.java index 31665570a..7c5282499 100644 --- a/src/org/andengine/entity/primitive/vbo/HighPerformanceLineVertexBufferObject.java +++ b/src/org/andengine/entity/primitive/vbo/HighPerformanceLineVertexBufferObject.java @@ -7,7 +7,7 @@ import org.andengine.opengl.vbo.attribute.VertexBufferObjectAttributes; /** - * (c) Zynga 2012 + * (c) 2012 Zynga Inc. * * @author Nicolas Gramlich * @since 18:45:00 - 28.03.2012 @@ -43,8 +43,8 @@ public void onUpdateColor(final Line pLine) { final float packedColor = pLine.getColor().getABGRPackedFloat(); - bufferData[0 * Line.VERTEX_SIZE + Line.COLOR_INDEX] = packedColor; - bufferData[1 * Line.VERTEX_SIZE + Line.COLOR_INDEX] = packedColor; + bufferData[(0 * Line.VERTEX_SIZE) + Line.COLOR_INDEX] = packedColor; + bufferData[(1 * Line.VERTEX_SIZE) + Line.COLOR_INDEX] = packedColor; this.setDirtyOnHardware(); } @@ -53,11 +53,11 @@ public void onUpdateColor(final Line pLine) { public void onUpdateVertices(final Line pLine) { final float[] bufferData = this.mBufferData; - bufferData[0 * Line.VERTEX_SIZE + Line.VERTEX_INDEX_X] = 0; - bufferData[0 * Line.VERTEX_SIZE + Line.VERTEX_INDEX_Y] = 0; + bufferData[(0 * Line.VERTEX_SIZE) + Line.VERTEX_INDEX_X] = 0; + bufferData[(0 * Line.VERTEX_SIZE) + Line.VERTEX_INDEX_Y] = 0; - bufferData[1 * Line.VERTEX_SIZE + Line.VERTEX_INDEX_X] = pLine.getX2() - pLine.getX1(); - bufferData[1 * Line.VERTEX_SIZE + Line.VERTEX_INDEX_Y] = pLine.getY2() - pLine.getY1(); + bufferData[(1 * Line.VERTEX_SIZE) + Line.VERTEX_INDEX_X] = pLine.getX2() - pLine.getX1(); + bufferData[(1 * Line.VERTEX_SIZE) + Line.VERTEX_INDEX_Y] = pLine.getY2() - pLine.getY1(); this.setDirtyOnHardware(); } diff --git a/src/org/andengine/entity/primitive/vbo/HighPerformanceMeshVertexBufferObject.java b/src/org/andengine/entity/primitive/vbo/HighPerformanceMeshVertexBufferObject.java index ae75f2761..183f88842 100644 --- a/src/org/andengine/entity/primitive/vbo/HighPerformanceMeshVertexBufferObject.java +++ b/src/org/andengine/entity/primitive/vbo/HighPerformanceMeshVertexBufferObject.java @@ -7,7 +7,7 @@ import org.andengine.opengl.vbo.attribute.VertexBufferObjectAttributes; /** - * (c) Zynga 2012 + * (c) 2012 Zynga Inc. * * @author Nicolas Gramlich * @since 18:46:51 - 28.03.2012 @@ -47,7 +47,7 @@ public void onUpdateColor(final Mesh pMesh) { final float packedColor = pMesh.getColor().getABGRPackedFloat(); - for(int i = 0; i < this.mVertexCount; i++) { + for (int i = 0; i < this.mVertexCount; i++) { bufferData[(i * Mesh.VERTEX_SIZE) + Mesh.COLOR_INDEX] = packedColor; } diff --git a/src/org/andengine/entity/primitive/vbo/HighPerformanceRectangleVertexBufferObject.java b/src/org/andengine/entity/primitive/vbo/HighPerformanceRectangleVertexBufferObject.java index e1b79c40a..a8836f492 100644 --- a/src/org/andengine/entity/primitive/vbo/HighPerformanceRectangleVertexBufferObject.java +++ b/src/org/andengine/entity/primitive/vbo/HighPerformanceRectangleVertexBufferObject.java @@ -7,7 +7,7 @@ import org.andengine.opengl.vbo.attribute.VertexBufferObjectAttributes; /** - * (c) Zynga 2012 + * (c) 2012 Zynga Inc. * * @author Nicolas Gramlich * @since 18:48:14 - 28.03.2012 @@ -43,10 +43,10 @@ public void onUpdateColor(final Rectangle pRectangle) { final float packedColor = pRectangle.getColor().getABGRPackedFloat(); - bufferData[0 * Rectangle.VERTEX_SIZE + Rectangle.COLOR_INDEX] = packedColor; - bufferData[1 * Rectangle.VERTEX_SIZE + Rectangle.COLOR_INDEX] = packedColor; - bufferData[2 * Rectangle.VERTEX_SIZE + Rectangle.COLOR_INDEX] = packedColor; - bufferData[3 * Rectangle.VERTEX_SIZE + Rectangle.COLOR_INDEX] = packedColor; + bufferData[(0 * Rectangle.VERTEX_SIZE) + Rectangle.COLOR_INDEX] = packedColor; + bufferData[(1 * Rectangle.VERTEX_SIZE) + Rectangle.COLOR_INDEX] = packedColor; + bufferData[(2 * Rectangle.VERTEX_SIZE) + Rectangle.COLOR_INDEX] = packedColor; + bufferData[(3 * Rectangle.VERTEX_SIZE) + Rectangle.COLOR_INDEX] = packedColor; this.setDirtyOnHardware(); } @@ -55,22 +55,20 @@ public void onUpdateColor(final Rectangle pRectangle) { public void onUpdateVertices(final Rectangle pRectangle) { final float[] bufferData = this.mBufferData; - final float x = 0; - final float y = 0; - final float x2 = pRectangle.getWidth(); // TODO Optimize with field access? - final float y2 = pRectangle.getHeight(); // TODO Optimize with field access? + final float width = pRectangle.getWidth(); // TODO Optimize with field access? + final float height = pRectangle.getHeight(); // TODO Optimize with field access? - bufferData[0 * Rectangle.VERTEX_SIZE + Rectangle.VERTEX_INDEX_X] = x; - bufferData[0 * Rectangle.VERTEX_SIZE + Rectangle.VERTEX_INDEX_Y] = y; + bufferData[(0 * Rectangle.VERTEX_SIZE) + Rectangle.VERTEX_INDEX_X] = 0; + bufferData[(0 * Rectangle.VERTEX_SIZE) + Rectangle.VERTEX_INDEX_Y] = 0; - bufferData[1 * Rectangle.VERTEX_SIZE + Rectangle.VERTEX_INDEX_X] = x; - bufferData[1 * Rectangle.VERTEX_SIZE + Rectangle.VERTEX_INDEX_Y] = y2; + bufferData[(1 * Rectangle.VERTEX_SIZE) + Rectangle.VERTEX_INDEX_X] = 0; + bufferData[(1 * Rectangle.VERTEX_SIZE) + Rectangle.VERTEX_INDEX_Y] = height; - bufferData[2 * Rectangle.VERTEX_SIZE + Rectangle.VERTEX_INDEX_X] = x2; - bufferData[2 * Rectangle.VERTEX_SIZE + Rectangle.VERTEX_INDEX_Y] = y; + bufferData[(2 * Rectangle.VERTEX_SIZE) + Rectangle.VERTEX_INDEX_X] = width; + bufferData[(2 * Rectangle.VERTEX_SIZE) + Rectangle.VERTEX_INDEX_Y] = 0; - bufferData[3 * Rectangle.VERTEX_SIZE + Rectangle.VERTEX_INDEX_X] = x2; - bufferData[3 * Rectangle.VERTEX_SIZE + Rectangle.VERTEX_INDEX_Y] = y2; + bufferData[(3 * Rectangle.VERTEX_SIZE) + Rectangle.VERTEX_INDEX_X] = width; + bufferData[(3 * Rectangle.VERTEX_SIZE) + Rectangle.VERTEX_INDEX_Y] = height; this.setDirtyOnHardware(); } diff --git a/src/org/andengine/entity/primitive/vbo/IGradientVertexBufferObject.java b/src/org/andengine/entity/primitive/vbo/IGradientVertexBufferObject.java new file mode 100644 index 000000000..9af59158d --- /dev/null +++ b/src/org/andengine/entity/primitive/vbo/IGradientVertexBufferObject.java @@ -0,0 +1,23 @@ +package org.andengine.entity.primitive.vbo; + +import org.andengine.entity.primitive.Gradient; +import org.andengine.opengl.vbo.IVertexBufferObject; + +/** + * (c) 2012 Zynga Inc. + * + * @author Nicolas Gramlich + * @since 14:27:22 - 23.04.2012 + */ +public interface IGradientVertexBufferObject extends IVertexBufferObject { + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + public void onUpdateColor(final Gradient pGradient); + public void onUpdateVertices(final Gradient pGradient); +} \ No newline at end of file diff --git a/src/org/andengine/entity/primitive/vbo/ILineChainVertexBufferObject.java b/src/org/andengine/entity/primitive/vbo/ILineChainVertexBufferObject.java new file mode 100644 index 000000000..e517b20e5 --- /dev/null +++ b/src/org/andengine/entity/primitive/vbo/ILineChainVertexBufferObject.java @@ -0,0 +1,23 @@ +package org.andengine.entity.primitive.vbo; + +import org.andengine.entity.primitive.LineChain; +import org.andengine.opengl.vbo.IVertexBufferObject; + +/** + * (c) 2013 Nicolas Gramlich + * + * @author Nicolas Gramlich + * @since 21:49:01 - 30.05.2013 + */ +public interface ILineChainVertexBufferObject extends IVertexBufferObject { + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + public void onUpdateColor(final LineChain pLineChain); + public void onUpdateVertices(final LineChain pLineChain); +} \ No newline at end of file diff --git a/src/org/andengine/entity/primitive/vbo/ILineVertexBufferObject.java b/src/org/andengine/entity/primitive/vbo/ILineVertexBufferObject.java index 07c572285..e179c8ecf 100644 --- a/src/org/andengine/entity/primitive/vbo/ILineVertexBufferObject.java +++ b/src/org/andengine/entity/primitive/vbo/ILineVertexBufferObject.java @@ -4,7 +4,7 @@ import org.andengine.opengl.vbo.IVertexBufferObject; /** - * (c) Zynga 2012 + * (c) 2012 Zynga Inc. * * @author Nicolas Gramlich * @since 18:45:00 - 28.03.2012 diff --git a/src/org/andengine/entity/primitive/vbo/IMeshVertexBufferObject.java b/src/org/andengine/entity/primitive/vbo/IMeshVertexBufferObject.java index 0e0ec2fe9..fa6223316 100644 --- a/src/org/andengine/entity/primitive/vbo/IMeshVertexBufferObject.java +++ b/src/org/andengine/entity/primitive/vbo/IMeshVertexBufferObject.java @@ -4,7 +4,7 @@ import org.andengine.opengl.vbo.IVertexBufferObject; /** - * (c) Zynga 2012 + * (c) 2012 Zynga Inc. * * @author Nicolas Gramlich * @since 18:46:51 - 28.03.2012 diff --git a/src/org/andengine/entity/primitive/vbo/IRectangleVertexBufferObject.java b/src/org/andengine/entity/primitive/vbo/IRectangleVertexBufferObject.java index 017a845ef..dde390ec1 100644 --- a/src/org/andengine/entity/primitive/vbo/IRectangleVertexBufferObject.java +++ b/src/org/andengine/entity/primitive/vbo/IRectangleVertexBufferObject.java @@ -4,7 +4,7 @@ import org.andengine.opengl.vbo.IVertexBufferObject; /** - * (c) Zynga 2012 + * (c) 2012 Zynga Inc. * * @author Nicolas Gramlich * @since 18:48:14 - 28.03.2012 diff --git a/src/org/andengine/entity/primitive/vbo/LowMemoryGradientVertexBufferObject.java b/src/org/andengine/entity/primitive/vbo/LowMemoryGradientVertexBufferObject.java new file mode 100644 index 000000000..4fcd6cc5c --- /dev/null +++ b/src/org/andengine/entity/primitive/vbo/LowMemoryGradientVertexBufferObject.java @@ -0,0 +1,131 @@ +package org.andengine.entity.primitive.vbo; + +import java.nio.FloatBuffer; + +import org.andengine.entity.primitive.Gradient; +import org.andengine.opengl.vbo.DrawType; +import org.andengine.opengl.vbo.LowMemoryVertexBufferObject; +import org.andengine.opengl.vbo.VertexBufferObjectManager; +import org.andengine.opengl.vbo.attribute.VertexBufferObjectAttributes; +import org.andengine.util.adt.color.ColorUtils; +import org.andengine.util.math.MathConstants; +import org.andengine.util.math.MathUtils; + +/** + * (c) 2012 Zynga Inc. + * + * @author Nicolas Gramlich + * @since 14:27:33 - 23.04.2012 + */ +public class LowMemoryGradientVertexBufferObject extends LowMemoryVertexBufferObject implements IGradientVertexBufferObject { + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + // =========================================================== + // Constructors + // =========================================================== + + public LowMemoryGradientVertexBufferObject(final VertexBufferObjectManager pVertexBufferObjectManager, final int pCapacity, final DrawType pDrawType, final boolean pAutoDispose, final VertexBufferObjectAttributes pVertexBufferObjectAttributes) { + super(pVertexBufferObjectManager, pCapacity, pDrawType, pAutoDispose, pVertexBufferObjectAttributes); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + public void onUpdateColor(final Gradient pGradient) { + final FloatBuffer bufferData = this.mFloatBuffer; + + final float gradientVectorX = pGradient.getGradientVectorX(); + final float gradientVectorY = pGradient.getGradientVectorY(); + + final float length = MathUtils.length(gradientVectorX, gradientVectorY); + if (length == 0) { + return; + } + + float dX = gradientVectorX / length; + float dY = gradientVectorY / length; + + final float c = MathConstants.SQRT_2; + final float c2 = 2 * c; + + if (pGradient.isGradientFitToBounds()) { + final float tmp = 1 / (Math.abs(dX) + Math.abs(dY)); + dX *= tmp * c; + dY *= tmp * c; + } + + final float fromRed = pGradient.getFromRed(); + final float fromGreen = pGradient.getFromGreen(); + final float fromBlue = pGradient.getFromBlue(); + final float fromAlpha = pGradient.getFromAlpha(); // TODO * 'this.mOverallOpactity' + + final float toRed = pGradient.getToRed(); + final float toGreen = pGradient.getToGreen(); + final float toBlue = pGradient.getToBlue(); + final float toAlpha = pGradient.getToAlpha(); // TODO * 'this.mOverallOpactity' + + /* Pre-fetch some calculations. */ + final float dRed = fromRed - toRed; + final float dGreen = fromGreen - toGreen; + final float dBlue = fromBlue - toBlue; + final float dAlpha = fromAlpha - toAlpha; + + + final float v0 = (c + dX + dY) / c2; + bufferData.put((0 * Gradient.VERTEX_SIZE) + Gradient.COLOR_INDEX, ColorUtils.convertRGBAToABGRPackedFloat(toRed + (dRed * v0), toGreen + (dGreen * v0), toBlue + (dBlue * v0), toAlpha + (dAlpha * v0))); + + final float v1 = (c + dX - dY) / c2; + bufferData.put((1 * Gradient.VERTEX_SIZE) + Gradient.COLOR_INDEX, ColorUtils.convertRGBAToABGRPackedFloat(toRed + (dRed * v1), toGreen + (dGreen * v1), toBlue + (dBlue * v1), toAlpha + (dAlpha * v1))); + + final float v2 = (c - dX + dY) / c2; + bufferData.put((2 * Gradient.VERTEX_SIZE) + Gradient.COLOR_INDEX, ColorUtils.convertRGBAToABGRPackedFloat(toRed + (dRed * v2), toGreen + (dGreen * v2), toBlue + (dBlue * v2), toAlpha + (dAlpha * v2))); + + final float v3 = (c - dX - dY) / c2; + bufferData.put((3 * Gradient.VERTEX_SIZE) + Gradient.COLOR_INDEX, ColorUtils.convertRGBAToABGRPackedFloat(toRed + (dRed * v3), toGreen + (dGreen * v3), toBlue + (dBlue * v3), toAlpha + (dAlpha * v3))); + + + this.setDirtyOnHardware(); + } + + @Override + public void onUpdateVertices(final Gradient pGradient) { + final FloatBuffer bufferData = this.mFloatBuffer; + + final float width = pGradient.getWidth(); // TODO Optimize with field access? + final float height = pGradient.getHeight(); // TODO Optimize with field access? + + bufferData.put((0 * Gradient.VERTEX_SIZE) + Gradient.VERTEX_INDEX_X, 0); + bufferData.put((0 * Gradient.VERTEX_SIZE) + Gradient.VERTEX_INDEX_Y, 0); + + bufferData.put((1 * Gradient.VERTEX_SIZE) + Gradient.VERTEX_INDEX_X, 0); + bufferData.put((1 * Gradient.VERTEX_SIZE) + Gradient.VERTEX_INDEX_Y, height); + + bufferData.put((2 * Gradient.VERTEX_SIZE) + Gradient.VERTEX_INDEX_X, width); + bufferData.put((2 * Gradient.VERTEX_SIZE) + Gradient.VERTEX_INDEX_Y, 0); + + bufferData.put((3 * Gradient.VERTEX_SIZE) + Gradient.VERTEX_INDEX_X, width); + bufferData.put((3 * Gradient.VERTEX_SIZE) + Gradient.VERTEX_INDEX_Y, height); + + this.setDirtyOnHardware(); + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== +} \ No newline at end of file diff --git a/src/org/andengine/entity/primitive/vbo/LowMemoryLineChainVertexBufferObject.java b/src/org/andengine/entity/primitive/vbo/LowMemoryLineChainVertexBufferObject.java new file mode 100644 index 000000000..0c93882a3 --- /dev/null +++ b/src/org/andengine/entity/primitive/vbo/LowMemoryLineChainVertexBufferObject.java @@ -0,0 +1,80 @@ +package org.andengine.entity.primitive.vbo; + +import java.nio.FloatBuffer; + +import org.andengine.entity.primitive.LineChain; +import org.andengine.opengl.vbo.DrawType; +import org.andengine.opengl.vbo.LowMemoryVertexBufferObject; +import org.andengine.opengl.vbo.VertexBufferObjectManager; +import org.andengine.opengl.vbo.attribute.VertexBufferObjectAttributes; + +/** + * (c) 2013 Nicolas Gramlich + * + * @author Nicolas Gramlich + * @since 21:50:00 - 30.05.2013 + */ +public class LowMemoryLineChainVertexBufferObject extends LowMemoryVertexBufferObject implements ILineChainVertexBufferObject { + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + // =========================================================== + // Constructors + // =========================================================== + + public LowMemoryLineChainVertexBufferObject(final VertexBufferObjectManager pVertexBufferObjectManager, final int pCapacity, final DrawType pDrawType, final boolean pAutoDispose, final VertexBufferObjectAttributes pVertexBufferObjectAttributes) { + super(pVertexBufferObjectManager, pCapacity, pDrawType, pAutoDispose, pVertexBufferObjectAttributes); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + public void onUpdateColor(final LineChain pLineChain) { + final FloatBuffer bufferData = this.mFloatBuffer; + + final float packedColor = pLineChain.getColor().getABGRPackedFloat(); + + for (int i = pLineChain.getCapacity() - 1; i >= 0; i--) { + bufferData.put((i * LineChain.VERTEX_SIZE) + LineChain.COLOR_INDEX, packedColor); + } + + this.setDirtyOnHardware(); + } + + @Override + public void onUpdateVertices(final LineChain pLineChain) { + final FloatBuffer bufferData = this.mFloatBuffer; + + bufferData.put((0 * LineChain.VERTEX_SIZE) + LineChain.VERTEX_INDEX_X, 0); + bufferData.put((0 * LineChain.VERTEX_SIZE) + LineChain.VERTEX_INDEX_Y, 0); + + final float x = pLineChain.getX(); + final float y = pLineChain.getY(); + + for (int i = pLineChain.getCapacity() - 1; i >= 0; i--) { + bufferData.put((i * LineChain.VERTEX_SIZE) + LineChain.VERTEX_INDEX_X, pLineChain.getX(i) - x); + bufferData.put((i * LineChain.VERTEX_SIZE) + LineChain.VERTEX_INDEX_Y, pLineChain.getY(i) - y); + } + + this.setDirtyOnHardware(); + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== +} \ No newline at end of file diff --git a/src/org/andengine/entity/primitive/vbo/LowMemoryLineVertexBufferObject.java b/src/org/andengine/entity/primitive/vbo/LowMemoryLineVertexBufferObject.java index 42da35b4c..8b7c4db36 100644 --- a/src/org/andengine/entity/primitive/vbo/LowMemoryLineVertexBufferObject.java +++ b/src/org/andengine/entity/primitive/vbo/LowMemoryLineVertexBufferObject.java @@ -9,7 +9,7 @@ import org.andengine.opengl.vbo.attribute.VertexBufferObjectAttributes; /** - * (c) Zynga 2012 + * (c) 2012 Zynga Inc. * * @author Nicolas Gramlich * @since 18:45:00 - 28.03.2012 @@ -45,8 +45,8 @@ public void onUpdateColor(final Line pLine) { final float packedColor = pLine.getColor().getABGRPackedFloat(); - bufferData.put(0 * Line.VERTEX_SIZE + Line.COLOR_INDEX, packedColor); - bufferData.put(1 * Line.VERTEX_SIZE + Line.COLOR_INDEX, packedColor); + bufferData.put((0 * Line.VERTEX_SIZE) + Line.COLOR_INDEX, packedColor); + bufferData.put((1 * Line.VERTEX_SIZE) + Line.COLOR_INDEX, packedColor); this.setDirtyOnHardware(); } @@ -55,11 +55,11 @@ public void onUpdateColor(final Line pLine) { public void onUpdateVertices(final Line pLine) { final FloatBuffer bufferData = this.mFloatBuffer; - bufferData.put(0 * Line.VERTEX_SIZE + Line.VERTEX_INDEX_X, 0); - bufferData.put(0 * Line.VERTEX_SIZE + Line.VERTEX_INDEX_Y, 0); + bufferData.put((0 * Line.VERTEX_SIZE) + Line.VERTEX_INDEX_X, 0); + bufferData.put((0 * Line.VERTEX_SIZE) + Line.VERTEX_INDEX_Y, 0); - bufferData.put(1 * Line.VERTEX_SIZE + Line.VERTEX_INDEX_X, pLine.getX2() - pLine.getX1()); // TODO Optimize with field access? - bufferData.put(1 * Line.VERTEX_SIZE + Line.VERTEX_INDEX_Y, pLine.getY2() - pLine.getY1()); // TODO Optimize with field access? + bufferData.put((1 * Line.VERTEX_SIZE) + Line.VERTEX_INDEX_X, pLine.getX2() - pLine.getX1()); // TODO Optimize with field access? + bufferData.put((1 * Line.VERTEX_SIZE) + Line.VERTEX_INDEX_Y, pLine.getY2() - pLine.getY1()); // TODO Optimize with field access? this.setDirtyOnHardware(); } diff --git a/src/org/andengine/entity/primitive/vbo/LowMemoryRectangleVertexBufferObject.java b/src/org/andengine/entity/primitive/vbo/LowMemoryRectangleVertexBufferObject.java index 798d1a774..0226c8a2a 100644 --- a/src/org/andengine/entity/primitive/vbo/LowMemoryRectangleVertexBufferObject.java +++ b/src/org/andengine/entity/primitive/vbo/LowMemoryRectangleVertexBufferObject.java @@ -9,7 +9,7 @@ import org.andengine.opengl.vbo.attribute.VertexBufferObjectAttributes; /** - * (c) Zynga 2012 + * (c) 2012 Zynga Inc. * * @author Nicolas Gramlich * @since 18:48:14 - 28.03.2012 @@ -45,10 +45,10 @@ public void onUpdateColor(final Rectangle pRectangle) { final float packedColor = pRectangle.getColor().getABGRPackedFloat(); - bufferData.put(0 * Rectangle.VERTEX_SIZE + Rectangle.COLOR_INDEX, packedColor); - bufferData.put(1 * Rectangle.VERTEX_SIZE + Rectangle.COLOR_INDEX, packedColor); - bufferData.put(2 * Rectangle.VERTEX_SIZE + Rectangle.COLOR_INDEX, packedColor); - bufferData.put(3 * Rectangle.VERTEX_SIZE + Rectangle.COLOR_INDEX, packedColor); + bufferData.put((0 * Rectangle.VERTEX_SIZE) + Rectangle.COLOR_INDEX, packedColor); + bufferData.put((1 * Rectangle.VERTEX_SIZE) + Rectangle.COLOR_INDEX, packedColor); + bufferData.put((2 * Rectangle.VERTEX_SIZE) + Rectangle.COLOR_INDEX, packedColor); + bufferData.put((3 * Rectangle.VERTEX_SIZE) + Rectangle.COLOR_INDEX, packedColor); this.setDirtyOnHardware(); } @@ -57,22 +57,20 @@ public void onUpdateColor(final Rectangle pRectangle) { public void onUpdateVertices(final Rectangle pRectangle) { final FloatBuffer bufferData = this.mFloatBuffer; - final float x = 0; - final float y = 0; - final float x2 = pRectangle.getWidth(); - final float y2 = pRectangle.getHeight(); + final float width = pRectangle.getWidth(); // TODO Optimize with field access? + final float height = pRectangle.getHeight(); // TODO Optimize with field access? - bufferData.put(0 * Rectangle.VERTEX_SIZE + Rectangle.VERTEX_INDEX_X, x); - bufferData.put(0 * Rectangle.VERTEX_SIZE + Rectangle.VERTEX_INDEX_Y, y); + bufferData.put((0 * Rectangle.VERTEX_SIZE) + Rectangle.VERTEX_INDEX_X, 0); + bufferData.put((0 * Rectangle.VERTEX_SIZE) + Rectangle.VERTEX_INDEX_Y, 0); - bufferData.put(1 * Rectangle.VERTEX_SIZE + Rectangle.VERTEX_INDEX_X, x); - bufferData.put(1 * Rectangle.VERTEX_SIZE + Rectangle.VERTEX_INDEX_Y, y2); + bufferData.put((1 * Rectangle.VERTEX_SIZE) + Rectangle.VERTEX_INDEX_X, 0); + bufferData.put((1 * Rectangle.VERTEX_SIZE) + Rectangle.VERTEX_INDEX_Y, height); - bufferData.put(2 * Rectangle.VERTEX_SIZE + Rectangle.VERTEX_INDEX_X, x2); - bufferData.put(2 * Rectangle.VERTEX_SIZE + Rectangle.VERTEX_INDEX_Y, y); + bufferData.put((2 * Rectangle.VERTEX_SIZE) + Rectangle.VERTEX_INDEX_X, width); + bufferData.put((2 * Rectangle.VERTEX_SIZE) + Rectangle.VERTEX_INDEX_Y, 0); - bufferData.put(3 * Rectangle.VERTEX_SIZE + Rectangle.VERTEX_INDEX_X, x2); - bufferData.put(3 * Rectangle.VERTEX_SIZE + Rectangle.VERTEX_INDEX_Y, y2); + bufferData.put((3 * Rectangle.VERTEX_SIZE) + Rectangle.VERTEX_INDEX_X, width); + bufferData.put((3 * Rectangle.VERTEX_SIZE) + Rectangle.VERTEX_INDEX_Y, height); this.setDirtyOnHardware(); } diff --git a/src/org/andengine/entity/scene/CameraScene.java b/src/org/andengine/entity/scene/CameraScene.java index eef5adc5a..64ff3b38c 100644 --- a/src/org/andengine/entity/scene/CameraScene.java +++ b/src/org/andengine/entity/scene/CameraScene.java @@ -1,14 +1,15 @@ package org.andengine.entity.scene; import org.andengine.engine.camera.Camera; -import org.andengine.entity.shape.IAreaShape; +import org.andengine.entity.IEntity; import org.andengine.input.touch.TouchEvent; import org.andengine.opengl.util.GLState; +import org.andengine.util.exception.MethodNotSupportedException; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 15:35:53 - 29.03.2010 */ @@ -28,7 +29,7 @@ public class CameraScene extends Scene { // =========================================================== /** - * {@link CameraScene#setCamera(Camera)} needs to be called manually. Otherwise nothing will be drawn. + * {@link #setCamera(Camera)} needs to be called manually. Otherwise nothing will be drawn. */ public CameraScene() { this(null); @@ -50,23 +51,48 @@ public void setCamera(final Camera pCamera) { this.mCamera = pCamera; } + @Override + public float getWidth() { + return this.mCamera.getCameraSceneWidth(); + } + + @Override + public float getHeight() { + return this.mCamera.getCameraSceneHeight(); + } + + @Override + public void setWidth(final float pWidth) { + throw new MethodNotSupportedException(); + } + + @Override + public void setHeight(final float pHeight) { + throw new MethodNotSupportedException(); + } + + @Override + public void setSize(final float pWidth, final float pHeight) { + throw new MethodNotSupportedException(); + } + // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public boolean onSceneTouchEvent(final TouchEvent pSceneTouchEvent) { - if(this.mCamera == null) { + if (this.mCamera == null) { return false; } else { - this.mCamera.convertSceneToCameraSceneTouchEvent(pSceneTouchEvent); + this.mCamera.convertSceneTouchEventToCameraSceneTouchEvent(pSceneTouchEvent); final boolean handled = super.onSceneTouchEvent(pSceneTouchEvent); - if(handled) { + if (handled) { return true; } else { - this.mCamera.convertCameraSceneToSceneTouchEvent(pSceneTouchEvent); + this.mCamera.convertCameraSceneTouchEventToSceneTouchEvent(pSceneTouchEvent); return false; } } @@ -75,10 +101,10 @@ public boolean onSceneTouchEvent(final TouchEvent pSceneTouchEvent) { @Override protected boolean onChildSceneTouchEvent(final TouchEvent pSceneTouchEvent) { final boolean childIsCameraScene = this.mChildScene instanceof CameraScene; - if(childIsCameraScene) { - this.mCamera.convertCameraSceneToSceneTouchEvent(pSceneTouchEvent); + if (childIsCameraScene) { + this.mCamera.convertCameraSceneTouchEventToSceneTouchEvent(pSceneTouchEvent); final boolean result = super.onChildSceneTouchEvent(pSceneTouchEvent); - this.mCamera.convertSceneToCameraSceneTouchEvent(pSceneTouchEvent); + this.mCamera.convertSceneTouchEventToCameraSceneTouchEvent(pSceneTouchEvent); return result; } else { return super.onChildSceneTouchEvent(pSceneTouchEvent); @@ -94,17 +120,16 @@ protected void onApplyMatrix(final GLState pGLState, final Camera pCamera) { // Methods // =========================================================== - public void centerShapeInCamera(final IAreaShape pAreaShape) { - final Camera camera = this.mCamera; - pAreaShape.setPosition((camera.getWidth() - pAreaShape.getWidth()) * 0.5f, (camera.getHeight() - pAreaShape.getHeight()) * 0.5f); + public void centerEntityInCamera(final IEntity pEntity) { + pEntity.setPosition(this.mCamera.getCenterX(), this.mCamera.getCenterY()); } - public void centerShapeInCameraHorizontally(final IAreaShape pAreaShape) { - pAreaShape.setPosition((this.mCamera.getWidth() - pAreaShape.getWidth()) * 0.5f, pAreaShape.getY()); + public void centerEntityInCameraHorizontally(final IEntity pEntity) { + pEntity.setX(this.mCamera.getCenterX()); } - public void centerShapeInCameraVertically(final IAreaShape pAreaShape) { - pAreaShape.setPosition(pAreaShape.getX(), (this.mCamera.getHeight() - pAreaShape.getHeight()) * 0.5f); + public void centerEntityInCameraVertically(final IEntity pEntity) { + pEntity.setY(this.mCamera.getCenterY()); } // =========================================================== diff --git a/src/org/andengine/entity/scene/IOnAreaTouchListener.java b/src/org/andengine/entity/scene/IOnAreaTouchListener.java index 58da60934..c9c6e99b8 100644 --- a/src/org/andengine/entity/scene/IOnAreaTouchListener.java +++ b/src/org/andengine/entity/scene/IOnAreaTouchListener.java @@ -7,7 +7,7 @@ * dispatched to an {@link ITouchArea} area. The callback will be invoked * before the {@link TouchEvent} is passed to the {@link ITouchArea}. * - * (c) Zynga 2012 + * (c) 2012 Zynga Inc. * * @author Nicolas Gramlich * @since 15:01:48 PM - 27.03.2012 @@ -24,12 +24,12 @@ public interface IOnAreaTouchListener { /** * Called when a {@link TouchEvent} is dispatched to an {@link ITouchArea}. This allows * listeners to get a chance to respond before the target {@link ITouchArea#onAreaTouched(TouchEvent, float, float)} is called. - * + * * @param pTouchArea The {@link ITouchArea} that the {@link TouchEvent} has been dispatched to. * @param pSceneTouchEvent The {@link TouchEvent} object containing full information about the event. * @param pTouchAreaLocalX the x coordinate within the area touched. * @param pTouchAreaLocalY the y coordinate within the area touched. - * + * * @return true if this {@link IOnAreaTouchListener} has consumed the {@link TouchEvent}, false otherwise. */ public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final ITouchArea pTouchArea, final float pTouchAreaLocalX, final float pTouchAreaLocalY); diff --git a/src/org/andengine/entity/scene/IOnSceneTouchListener.java b/src/org/andengine/entity/scene/IOnSceneTouchListener.java index ed99f5718..8e1a10702 100644 --- a/src/org/andengine/entity/scene/IOnSceneTouchListener.java +++ b/src/org/andengine/entity/scene/IOnSceneTouchListener.java @@ -7,7 +7,7 @@ * dispatched to a {@link Scene}. The callback will be invoked * after all {@link ITouchArea}s have been checked and none consumed the {@link TouchEvent}. * - * (c) Zynga 2012 + * (c) 2012 Zynga Inc. * * @author Nicolas Gramlich * @since 15:02:20 - 27.03.2012 @@ -23,10 +23,10 @@ public interface IOnSceneTouchListener { /** * Called when a {@link TouchEvent} is dispatched to a {@link Scene}. - * + * * @param pScene The {@link Scene} that the {@link TouchEvent} has been dispatched to. * @param pSceneTouchEvent The {@link TouchEvent} object containing full information about the event. - * + * * @return true if this {@link IOnSceneTouchListener} has consumed the {@link TouchEvent}, false otherwise. */ public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent); diff --git a/src/org/andengine/entity/scene/ITouchArea.java b/src/org/andengine/entity/scene/ITouchArea.java index cc577f63b..474b7cb8a 100644 --- a/src/org/andengine/entity/scene/ITouchArea.java +++ b/src/org/andengine/entity/scene/ITouchArea.java @@ -4,7 +4,7 @@ import org.andengine.util.IMatcher; /** - * (c) Zynga 2012 + * (c) 2012 Zynga Inc. * * @author Nicolas Gramlich * @since 15:01:18 - 27.03.2012 @@ -20,8 +20,8 @@ public interface ITouchArea { public boolean contains(final float pX, final float pY); - public float[] convertSceneToLocalCoordinates(final float pX, final float pY); - public float[] convertLocalToSceneCoordinates(final float pX, final float pY); + public float[] convertSceneCoordinatesToLocalCoordinates(final float pX, final float pY); + public float[] convertLocalCoordinatesToSceneCoordinates(final float pX, final float pY); /** * This method only fires if this {@link ITouchArea} is registered to the {@link Scene} via {@link Scene#registerTouchArea(ITouchArea)}. diff --git a/src/org/andengine/entity/scene/Scene.java b/src/org/andengine/entity/scene/Scene.java index f05966ea2..df8594c69 100644 --- a/src/org/andengine/entity/scene/Scene.java +++ b/src/org/andengine/entity/scene/Scene.java @@ -4,7 +4,6 @@ import org.andengine.engine.handler.runnable.RunnableHandler; import org.andengine.entity.Entity; import org.andengine.entity.IEntity; -import org.andengine.entity.scene.ITouchArea.ITouchAreaMatcher; import org.andengine.entity.scene.background.Background; import org.andengine.entity.scene.background.IBackground; import org.andengine.entity.shape.IShape; @@ -12,15 +11,15 @@ import org.andengine.input.touch.TouchEvent; import org.andengine.opengl.util.GLState; import org.andengine.util.Constants; +import org.andengine.util.adt.color.Color; import org.andengine.util.adt.list.SmartList; -import org.andengine.util.color.Color; import android.util.SparseArray; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 12:47:39 - 08.03.2010 */ @@ -72,7 +71,7 @@ public Scene() { @Deprecated public Scene(final int pChildCount) { - for(int i = 0; i < pChildCount; i++) { + for (int i = 0; i < pChildCount; i++) { this.attachChild(new Entity()); } } @@ -98,7 +97,7 @@ public boolean isBackgroundEnabled() { } public void setBackgroundEnabled(final boolean pEnabled) { - this.mBackgroundEnabled = pEnabled; + this.mBackgroundEnabled = pEnabled; } public void setOnSceneTouchListener(final IOnSceneTouchListener pOnSceneTouchListener) { @@ -181,11 +180,11 @@ public boolean isTouchAreaBindingOnActionMoveEnabled() { * with {@link TouchEvent#ACTION_DOWN}, they will receive all subsequent {@link TouchEvent}s * that are made with the same PointerID (finger) * even if the {@link TouchEvent} is outside of the actual {@link ITouchArea}! - * + * * @param pTouchAreaBindingOnActionDownEnabled */ public void setTouchAreaBindingOnActionDownEnabled(final boolean pTouchAreaBindingOnActionDownEnabled) { - if(this.mTouchAreaBindingOnActionDownEnabled && !pTouchAreaBindingOnActionDownEnabled) { + if (this.mTouchAreaBindingOnActionDownEnabled && !pTouchAreaBindingOnActionDownEnabled) { this.mTouchAreaBindings.clear(); } this.mTouchAreaBindingOnActionDownEnabled = pTouchAreaBindingOnActionDownEnabled; @@ -199,11 +198,11 @@ public void setTouchAreaBindingOnActionDownEnabled(final boolean pTouchAreaBindi * with {@link TouchEvent#ACTION_MOVE}, they will receive all subsequent {@link TouchEvent}s * that are made with the same PointerID (finger) * even if the {@link TouchEvent} is outside of the actual {@link ITouchArea}! - * + * * @param pTouchAreaBindingOnActionMoveEnabled */ public void setTouchAreaBindingOnActionMoveEnabled(final boolean pTouchAreaBindingOnActionMoveEnabled) { - if(this.mTouchAreaBindingOnActionMoveEnabled && !pTouchAreaBindingOnActionMoveEnabled) { + if (this.mTouchAreaBindingOnActionMoveEnabled && !pTouchAreaBindingOnActionMoveEnabled) { this.mTouchAreaBindings.clear(); } this.mTouchAreaBindingOnActionMoveEnabled = pTouchAreaBindingOnActionMoveEnabled; @@ -221,11 +220,11 @@ public boolean isOnSceneTouchListenerBindingOnActionDownEnabled() { * with {@link TouchEvent#ACTION_DOWN}, it will receive all subsequent {@link TouchEvent}s * that are made with the same PointerID (finger) * even if the {@link TouchEvent} is would belong to an overlaying {@link ITouchArea}! - * + * * @param pOnSceneTouchListenerBindingOnActionDownEnabled */ public void setOnSceneTouchListenerBindingOnActionDownEnabled(final boolean pOnSceneTouchListenerBindingOnActionDownEnabled) { - if(this.mOnSceneTouchListenerBindingOnActionDownEnabled && !pOnSceneTouchListenerBindingOnActionDownEnabled) { + if (this.mOnSceneTouchListenerBindingOnActionDownEnabled && !pOnSceneTouchListenerBindingOnActionDownEnabled) { this.mOnSceneTouchListenerBindings.clear(); } this.mOnSceneTouchListenerBindingOnActionDownEnabled = pOnSceneTouchListenerBindingOnActionDownEnabled; @@ -239,8 +238,8 @@ public void setOnSceneTouchListenerBindingOnActionDownEnabled(final boolean pOnS protected void onManagedDraw(final GLState pGLState, final Camera pCamera) { final Scene childScene = this.mChildScene; - if(childScene == null || !this.mChildSceneModalDraw) { - if(this.mBackgroundEnabled) { + if (childScene == null || !this.mChildSceneModalDraw) { + if (this.mBackgroundEnabled) { pGLState.pushProjectionGLMatrix(); pCamera.onApplySceneBackgroundMatrix(pGLState); @@ -263,7 +262,7 @@ protected void onManagedDraw(final GLState pGLState, final Camera pCamera) { } } - if(childScene != null) { + if (childScene != null) { childScene.onDraw(pGLState, pCamera); } } @@ -279,12 +278,12 @@ protected void onManagedUpdate(final float pSecondsElapsed) { this.mRunnableHandler.onUpdate(pSecondsElapsed); final Scene childScene = this.mChildScene; - if(childScene == null || !this.mChildSceneModalUpdate) { + if (childScene == null || !this.mChildSceneModalUpdate) { this.mBackground.onUpdate(pSecondsElapsed); super.onManagedUpdate(pSecondsElapsed); } - if(childScene != null) { + if (childScene != null) { childScene.onUpdate(pSecondsElapsed); } } @@ -294,39 +293,39 @@ public boolean onSceneTouchEvent(final TouchEvent pSceneTouchEvent) { final boolean isActionDown = pSceneTouchEvent.isActionDown(); final boolean isActionMove = pSceneTouchEvent.isActionMove(); - if(!isActionDown) { - if(this.mOnSceneTouchListenerBindingOnActionDownEnabled) { + if (!isActionDown) { + if (this.mOnSceneTouchListenerBindingOnActionDownEnabled) { final IOnSceneTouchListener boundOnSceneTouchListener = this.mOnSceneTouchListenerBindings.get(pSceneTouchEvent.getPointerID()); if (boundOnSceneTouchListener != null) { /* Check if boundTouchArea needs to be removed. */ - switch(action) { + switch (action) { case TouchEvent.ACTION_UP: case TouchEvent.ACTION_CANCEL: this.mOnSceneTouchListenerBindings.remove(pSceneTouchEvent.getPointerID()); } final Boolean handled = this.mOnSceneTouchListener.onSceneTouchEvent(this, pSceneTouchEvent); - if(handled != null && handled) { + if (handled != null && handled) { return true; } } } - if(this.mTouchAreaBindingOnActionDownEnabled) { + if (this.mTouchAreaBindingOnActionDownEnabled) { final SparseArray touchAreaBindings = this.mTouchAreaBindings; final ITouchArea boundTouchArea = touchAreaBindings.get(pSceneTouchEvent.getPointerID()); /* In the case a ITouchArea has been bound to this PointerID, * we'll pass this this TouchEvent to the same ITouchArea. */ - if(boundTouchArea != null) { + if (boundTouchArea != null) { final float sceneTouchEventX = pSceneTouchEvent.getX(); final float sceneTouchEventY = pSceneTouchEvent.getY(); /* Check if boundTouchArea needs to be removed. */ - switch(action) { + switch (action) { case TouchEvent.ACTION_UP: case TouchEvent.ACTION_CANCEL: touchAreaBindings.remove(pSceneTouchEvent.getPointerID()); } final Boolean handled = this.onAreaTouchEvent(pSceneTouchEvent, sceneTouchEventX, sceneTouchEventY, boundTouchArea); - if(handled != null && handled) { + if (handled != null && handled) { return true; } } @@ -334,11 +333,11 @@ public boolean onSceneTouchEvent(final TouchEvent pSceneTouchEvent) { } final Scene childScene = this.mChildScene; - if(childScene != null) { + if (childScene != null) { final boolean handledByChild = this.onChildSceneTouchEvent(pSceneTouchEvent); - if(handledByChild) { + if (handledByChild) { return true; - } else if(this.mChildSceneModalTouch) { + } else if (this.mChildSceneModalTouch) { return false; } } @@ -347,18 +346,18 @@ public boolean onSceneTouchEvent(final TouchEvent pSceneTouchEvent) { final float sceneTouchEventY = pSceneTouchEvent.getY(); final SmartList touchAreas = this.mTouchAreas; - if(touchAreas != null) { + if (touchAreas != null) { final int touchAreaCount = touchAreas.size(); - if(touchAreaCount > 0) { - if(this.mOnAreaTouchTraversalBackToFront) { /* Back to Front. */ - for(int i = 0; i < touchAreaCount; i++) { + if (touchAreaCount > 0) { + if (this.mOnAreaTouchTraversalBackToFront) { /* Back to Front. */ + for (int i = 0; i < touchAreaCount; i++) { final ITouchArea touchArea = touchAreas.get(i); - if(touchArea.contains(sceneTouchEventX, sceneTouchEventY)) { + if (touchArea.contains(sceneTouchEventX, sceneTouchEventY)) { final Boolean handled = this.onAreaTouchEvent(pSceneTouchEvent, sceneTouchEventX, sceneTouchEventY, touchArea); - if(handled != null && handled) { + if (handled != null && handled) { /* If binding of ITouchAreas is enabled and this is an ACTION_DOWN event, - * bind this ITouchArea to the PointerID. */ - if((this.mTouchAreaBindingOnActionDownEnabled && isActionDown) || (this.mTouchAreaBindingOnActionMoveEnabled && isActionMove)) { + * bind this ITouchArea to the PointerID. */ + if ((this.mTouchAreaBindingOnActionDownEnabled && isActionDown) || (this.mTouchAreaBindingOnActionMoveEnabled && isActionMove)) { this.mTouchAreaBindings.put(pSceneTouchEvent.getPointerID(), touchArea); } return true; @@ -366,14 +365,14 @@ public boolean onSceneTouchEvent(final TouchEvent pSceneTouchEvent) { } } } else { /* Front to back. */ - for(int i = touchAreaCount - 1; i >= 0; i--) { + for (int i = touchAreaCount - 1; i >= 0; i--) { final ITouchArea touchArea = touchAreas.get(i); - if(touchArea.contains(sceneTouchEventX, sceneTouchEventY)) { + if (touchArea.contains(sceneTouchEventX, sceneTouchEventY)) { final Boolean handled = this.onAreaTouchEvent(pSceneTouchEvent, sceneTouchEventX, sceneTouchEventY, touchArea); - if(handled != null && handled) { + if (handled != null && handled) { /* If binding of ITouchAreas is enabled and this is an ACTION_DOWN event, - * bind this ITouchArea to the PointerID. */ - if((this.mTouchAreaBindingOnActionDownEnabled && isActionDown) || (this.mTouchAreaBindingOnActionMoveEnabled && isActionMove)) { + * bind this ITouchArea to the PointerID. */ + if ((this.mTouchAreaBindingOnActionDownEnabled && isActionDown) || (this.mTouchAreaBindingOnActionMoveEnabled && isActionMove)) { this.mTouchAreaBindings.put(pSceneTouchEvent.getPointerID(), touchArea); } return true; @@ -384,12 +383,12 @@ public boolean onSceneTouchEvent(final TouchEvent pSceneTouchEvent) { } } /* If no area was touched, the Scene itself was touched as a fallback. */ - if(this.mOnSceneTouchListener != null){ + if (this.mOnSceneTouchListener != null) { final Boolean handled = this.mOnSceneTouchListener.onSceneTouchEvent(this, pSceneTouchEvent); - if(handled != null && handled) { + if (handled != null && handled) { /* If binding of ITouchAreas is enabled and this is an ACTION_DOWN event, - * bind the active OnSceneTouchListener to the PointerID. */ - if(this.mOnSceneTouchListenerBindingOnActionDownEnabled && isActionDown) { + * bind the active OnSceneTouchListener to the PointerID. */ + if (this.mOnSceneTouchListenerBindingOnActionDownEnabled && isActionDown) { this.mOnSceneTouchListenerBindings.put(pSceneTouchEvent.getPointerID(), this.mOnSceneTouchListener); } return true; @@ -402,14 +401,14 @@ public boolean onSceneTouchEvent(final TouchEvent pSceneTouchEvent) { } private Boolean onAreaTouchEvent(final TouchEvent pSceneTouchEvent, final float sceneTouchEventX, final float sceneTouchEventY, final ITouchArea touchArea) { - final float[] touchAreaLocalCoordinates = touchArea.convertSceneToLocalCoordinates(sceneTouchEventX, sceneTouchEventY); + final float[] touchAreaLocalCoordinates = touchArea.convertSceneCoordinatesToLocalCoordinates(sceneTouchEventX, sceneTouchEventY); final float touchAreaLocalX = touchAreaLocalCoordinates[Constants.VERTEX_INDEX_X]; final float touchAreaLocalY = touchAreaLocalCoordinates[Constants.VERTEX_INDEX_Y]; final boolean handledSelf = touchArea.onAreaTouched(pSceneTouchEvent, touchAreaLocalX, touchAreaLocalY); - if(handledSelf) { + if (handledSelf) { return Boolean.TRUE; - } else if(this.mOnAreaTouchListener != null) { + } else if (this.mOnAreaTouchListener != null) { return this.mOnAreaTouchListener.onAreaTouched(pSceneTouchEvent, touchArea, touchAreaLocalX, touchAreaLocalY); } else { return null; @@ -463,7 +462,7 @@ public SmartList getTouchAreas() { public void back() { this.clearChildScene(); - if(this.mParentScene != null) { + if (this.mParentScene != null) { this.mParentScene.clearChildScene(); this.mParentScene = null; } diff --git a/src/org/andengine/entity/scene/background/AutoParallaxBackground.java b/src/org/andengine/entity/scene/background/AutoParallaxBackground.java index b1a997864..745c49068 100644 --- a/src/org/andengine/entity/scene/background/AutoParallaxBackground.java +++ b/src/org/andengine/entity/scene/background/AutoParallaxBackground.java @@ -3,9 +3,9 @@ /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 19:44:31 - 19.07.2010 */ @@ -26,6 +26,7 @@ public class AutoParallaxBackground extends ParallaxBackground { public AutoParallaxBackground(final float pRed, final float pGreen, final float pBlue, final float pParallaxChangePerSecond) { super(pRed, pGreen, pBlue); + this.mParallaxChangePerSecond = pParallaxChangePerSecond; } diff --git a/src/org/andengine/entity/scene/background/Background.java b/src/org/andengine/entity/scene/background/Background.java index b023ab919..7dfe93155 100644 --- a/src/org/andengine/entity/scene/background/Background.java +++ b/src/org/andengine/entity/scene/background/Background.java @@ -2,7 +2,7 @@ import org.andengine.engine.camera.Camera; import org.andengine.opengl.util.GLState; -import org.andengine.util.color.Color; +import org.andengine.util.adt.color.Color; import org.andengine.util.modifier.IModifier; import org.andengine.util.modifier.ModifierList; @@ -12,7 +12,7 @@ /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 14:08:17 - 19.07.2010 */ @@ -27,7 +27,7 @@ public class Background implements IBackground { // Fields // =========================================================== - private ModifierList mBackgroundModifiers = null; + private ModifierList mBackgroundModifiers; private final Color mColor = new Color(0, 0, 0, 1); private boolean mColorEnabled = true; @@ -100,7 +100,7 @@ public void setColorEnabled(final boolean pColorEnabled) { @Override public void registerBackgroundModifier(final IModifier pBackgroundModifier) { - if(this.mBackgroundModifiers == null) { + if (this.mBackgroundModifiers == null) { this.allocateBackgroundModifiers(); } this.mBackgroundModifiers.add(pBackgroundModifier); @@ -108,7 +108,7 @@ public void registerBackgroundModifier(final IModifier pBackgroundM @Override public boolean unregisterBackgroundModifier(final IModifier pBackgroundModifier) { - if(this.mBackgroundModifiers != null) { + if (this.mBackgroundModifiers != null) { return this.mBackgroundModifiers.remove(pBackgroundModifier); } else { return false; @@ -117,21 +117,21 @@ public boolean unregisterBackgroundModifier(final IModifier pBackgr @Override public void clearBackgroundModifiers() { - if(this.mBackgroundModifiers != null) { + if (this.mBackgroundModifiers != null) { this.mBackgroundModifiers.clear(); } } @Override public void onUpdate(final float pSecondsElapsed) { - if(this.mBackgroundModifiers != null) { + if (this.mBackgroundModifiers != null) { this.mBackgroundModifiers.onUpdate(pSecondsElapsed); } } @Override public void onDraw(final GLState pGLState, final Camera pCamera) { - if(this.mColorEnabled) { + if (this.mColorEnabled) { GLES20.glClearColor(this.mColor.getRed(), this.mColor.getGreen(), this.mColor.getBlue(), this.mColor.getAlpha()); GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT); // TODO Does this cause problems when multisampling? } diff --git a/src/org/andengine/entity/scene/background/EntityBackground.java b/src/org/andengine/entity/scene/background/EntityBackground.java index 9cba6efa3..dd7c942bb 100644 --- a/src/org/andengine/entity/scene/background/EntityBackground.java +++ b/src/org/andengine/entity/scene/background/EntityBackground.java @@ -5,9 +5,9 @@ import org.andengine.opengl.util.GLState; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 18:25:10 - 21.07.2010 */ diff --git a/src/org/andengine/entity/scene/background/IBackground.java b/src/org/andengine/entity/scene/background/IBackground.java index bce15fd9b..9f7a83137 100644 --- a/src/org/andengine/entity/scene/background/IBackground.java +++ b/src/org/andengine/entity/scene/background/IBackground.java @@ -2,13 +2,13 @@ import org.andengine.engine.handler.IDrawHandler; import org.andengine.engine.handler.IUpdateHandler; -import org.andengine.util.color.Color; +import org.andengine.util.adt.color.Color; import org.andengine.util.modifier.IModifier; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 13:47:41 - 19.07.2010 */ diff --git a/src/org/andengine/entity/scene/background/ParallaxBackground.java b/src/org/andengine/entity/scene/background/ParallaxBackground.java index 22bb53979..c3f0dc14c 100644 --- a/src/org/andengine/entity/scene/background/ParallaxBackground.java +++ b/src/org/andengine/entity/scene/background/ParallaxBackground.java @@ -3,13 +3,14 @@ import java.util.ArrayList; import org.andengine.engine.camera.Camera; -import org.andengine.entity.shape.IAreaShape; +import org.andengine.entity.IEntity; import org.andengine.opengl.util.GLState; +import org.andengine.util.debug.Debug; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 15:36:26 - 19.07.2010 */ @@ -54,7 +55,7 @@ public void onDraw(final GLState pGLState, final Camera pCamera) { final float parallaxValue = this.mParallaxValue; final ArrayList parallaxEntities = this.mParallaxEntities; - for(int i = 0; i < this.mParallaxEntityCount; i++) { + for (int i = 0; i < this.mParallaxEntityCount; i++) { parallaxEntities.get(i).onDraw(pGLState, pCamera, parallaxValue); } } @@ -71,7 +72,7 @@ public void attachParallaxEntity(final ParallaxEntity pParallaxEntity) { public boolean detachParallaxEntity(final ParallaxEntity pParallaxEntity) { this.mParallaxEntityCount--; final boolean success = this.mParallaxEntities.remove(pParallaxEntity); - if(!success) { + if (!success) { this.mParallaxEntityCount++; } return success; @@ -91,15 +92,24 @@ public static class ParallaxEntity { // =========================================================== final float mParallaxFactor; - final IAreaShape mAreaShape; + final IEntity mEntity; // =========================================================== // Constructors // =========================================================== - public ParallaxEntity(final float pParallaxFactor, final IAreaShape pAreaShape) { + public ParallaxEntity(final float pParallaxFactor, final IEntity pEntity) { this.mParallaxFactor = pParallaxFactor; - this.mAreaShape = pAreaShape; + this.mEntity = pEntity; + + // TODO Adjust onDraw calculations, so that these assumptions aren't necessary. + if (this.mEntity.getX() != 0) { + Debug.w("The X position of a " + this.getClass().getSimpleName() + " is expected to be 0."); + } + + if (this.mEntity.getOffsetCenterX() != 0) { + Debug.w("The OffsetCenterXposition of a " + this.getClass().getSimpleName() + " is expected to be 0."); + } } // =========================================================== @@ -118,21 +128,21 @@ public void onDraw(final GLState pGLState, final Camera pCamera, final float pPa pGLState.pushModelViewGLMatrix(); { final float cameraWidth = pCamera.getWidth(); - final float shapeWidthScaled = this.mAreaShape.getWidthScaled(); - float baseOffset = (pParallaxValue * this.mParallaxFactor) % shapeWidthScaled; + final float entityWidthScaled = this.mEntity.getWidth() * this.mEntity.getScaleX(); + float baseOffset = (pParallaxValue * this.mParallaxFactor) % entityWidthScaled; - while(baseOffset > 0) { - baseOffset -= shapeWidthScaled; + while (baseOffset > 0) { + baseOffset -= entityWidthScaled; } pGLState.translateModelViewGLMatrixf(baseOffset, 0, 0); float currentMaxX = baseOffset; - + do { - this.mAreaShape.onDraw(pGLState, pCamera); - pGLState.translateModelViewGLMatrixf(shapeWidthScaled, 0, 0); - currentMaxX += shapeWidthScaled; - } while(currentMaxX < cameraWidth); + this.mEntity.onDraw(pGLState, pCamera); + pGLState.translateModelViewGLMatrixf(entityWidthScaled, 0, 0); + currentMaxX += entityWidthScaled; + } while (currentMaxX < cameraWidth); } pGLState.popModelViewGLMatrix(); } diff --git a/src/org/andengine/entity/scene/background/RepeatingSpriteBackground.java b/src/org/andengine/entity/scene/background/RepeatingSpriteBackground.java index 7aef2106f..319abc4c0 100644 --- a/src/org/andengine/entity/scene/background/RepeatingSpriteBackground.java +++ b/src/org/andengine/entity/scene/background/RepeatingSpriteBackground.java @@ -1,19 +1,13 @@ package org.andengine.entity.scene.background; import org.andengine.entity.sprite.Sprite; -import org.andengine.opengl.texture.TextureManager; -import org.andengine.opengl.texture.TextureOptions; -import org.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; -import org.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; -import org.andengine.opengl.texture.atlas.bitmap.source.IBitmapTextureAtlasSource; -import org.andengine.opengl.texture.bitmap.BitmapTextureFormat; import org.andengine.opengl.texture.region.ITextureRegion; import org.andengine.opengl.vbo.VertexBufferObjectManager; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 15:11:10 - 19.07.2010 */ @@ -22,42 +16,28 @@ public class RepeatingSpriteBackground extends SpriteBackground { // Constants // =========================================================== + private static final float SCALE_DEFAULT = 1; + // =========================================================== // Fields // =========================================================== - private BitmapTextureAtlas mBitmapTextureAtlas; - private final float mScale; - // =========================================================== // Constructors // =========================================================== - /** - * @param pCameraWidth - * @param pCameraHeight - * @param pTextureManager - * @param pBitmapTextureAtlasSource needs to be a power of two as otherwise the repeating feature doesn't work. - */ - public RepeatingSpriteBackground(final float pCameraWidth, final float pCameraHeight, final TextureManager pTextureManager, final IBitmapTextureAtlasSource pBitmapTextureAtlasSource, final VertexBufferObjectManager pVertexBufferObjectManager) throws IllegalArgumentException { - this(pCameraWidth, pCameraHeight, pTextureManager, pBitmapTextureAtlasSource, 1, pVertexBufferObjectManager); + public RepeatingSpriteBackground(final float pCameraWidth, final float pCameraHeight, final ITextureRegion pTextureRegion, final VertexBufferObjectManager pVertexBufferObjectManager) throws IllegalArgumentException { + this(pCameraWidth, pCameraHeight, pTextureRegion, SCALE_DEFAULT, pVertexBufferObjectManager); } - public RepeatingSpriteBackground(final float pCameraWidth, final float pCameraHeight, final TextureManager pTextureManager, final IBitmapTextureAtlasSource pBitmapTextureAtlasSource, final float pScale, final VertexBufferObjectManager pVertexBufferObjectManager) throws IllegalArgumentException { - super(null); - - this.mScale = pScale; - this.mEntity = this.loadSprite(pCameraWidth, pCameraHeight, pTextureManager, pBitmapTextureAtlasSource, pVertexBufferObjectManager); + public RepeatingSpriteBackground(final float pCameraWidth, final float pCameraHeight, final ITextureRegion pTextureRegion, final float pScale, final VertexBufferObjectManager pVertexBufferObjectManager) throws IllegalArgumentException { + super(RepeatingSpriteBackground.createSprite(pCameraWidth, pCameraHeight, pTextureRegion, pScale, pVertexBufferObjectManager)); } // =========================================================== // Getter & Setter // =========================================================== - public BitmapTextureAtlas getBitmapTextureAtlas() { - return this.mBitmapTextureAtlas; - } - // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @@ -66,22 +46,13 @@ public BitmapTextureAtlas getBitmapTextureAtlas() { // Methods // =========================================================== - private Sprite loadSprite(final float pCameraWidth, final float pCameraHeight, final TextureManager pTextureManager, final IBitmapTextureAtlasSource pBitmapTextureAtlasSource, final VertexBufferObjectManager pVertexBufferObjectManager) throws IllegalArgumentException { - this.mBitmapTextureAtlas = new BitmapTextureAtlas(pTextureManager, pBitmapTextureAtlasSource.getTextureWidth(), pBitmapTextureAtlasSource.getTextureHeight(), BitmapTextureFormat.RGBA_8888, TextureOptions.REPEATING_NEAREST); - final ITextureRegion textureRegion = BitmapTextureAtlasTextureRegionFactory.createFromSource(this.mBitmapTextureAtlas, pBitmapTextureAtlasSource, 0, 0); - - final int width = Math.round(pCameraWidth / this.mScale); - final int height = Math.round(pCameraHeight / this.mScale); - - textureRegion.setTextureWidth(width); - textureRegion.setTextureHeight(height); + private static Sprite createSprite(final float pCameraWidth, final float pCameraHeight, final ITextureRegion pTextureRegion, final float pScale, final VertexBufferObjectManager pVertexBufferObjectManager) throws IllegalArgumentException { + final int width = Math.round(pCameraWidth / pScale); + final int height = Math.round(pCameraHeight / pScale); - this.mBitmapTextureAtlas.load(); + pTextureRegion.setTextureSize(width, height); - final Sprite sprite = new Sprite(0, 0, width, height, textureRegion, pVertexBufferObjectManager); - sprite.setScaleCenter(0, 0); - sprite.setScale(this.mScale); - return sprite; + return new Sprite(pCameraWidth * 0.5f, pCameraHeight * 0.5f, width * pScale, height * pScale, pTextureRegion, pVertexBufferObjectManager); } // =========================================================== diff --git a/src/org/andengine/entity/scene/background/SpriteBackground.java b/src/org/andengine/entity/scene/background/SpriteBackground.java index 0661aaa39..9a752e67b 100644 --- a/src/org/andengine/entity/scene/background/SpriteBackground.java +++ b/src/org/andengine/entity/scene/background/SpriteBackground.java @@ -3,9 +3,9 @@ import org.andengine.entity.sprite.Sprite; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 14:01:43 - 19.07.2010 */ @@ -33,11 +33,11 @@ public SpriteBackground(final float pRed, final float pGreen, final float pBlue, // =========================================================== // Getter & Setter // =========================================================== - + public Sprite getSprite() { - return (Sprite)this.mEntity; + return (Sprite) this.mEntity; } - + // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== diff --git a/src/org/andengine/entity/scene/background/modifier/ColorBackgroundModifier.java b/src/org/andengine/entity/scene/background/modifier/ColorBackgroundModifier.java index d59c046ef..5f8106994 100644 --- a/src/org/andengine/entity/scene/background/modifier/ColorBackgroundModifier.java +++ b/src/org/andengine/entity/scene/background/modifier/ColorBackgroundModifier.java @@ -1,7 +1,7 @@ package org.andengine.entity.scene.background.modifier; import org.andengine.entity.scene.background.IBackground; -import org.andengine.util.color.Color; +import org.andengine.util.adt.color.Color; import org.andengine.util.modifier.BaseTripleValueSpanModifier; import org.andengine.util.modifier.ease.EaseLinear; import org.andengine.util.modifier.ease.IEaseFunction; @@ -9,7 +9,7 @@ /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 14:51:03 - 03.09.2010 */ @@ -63,7 +63,7 @@ protected ColorBackgroundModifier(final ColorBackgroundModifier pColorBackground } @Override - public ColorBackgroundModifier deepCopy(){ + public ColorBackgroundModifier deepCopy() { return new ColorBackgroundModifier(this); } diff --git a/src/org/andengine/entity/scene/background/modifier/IBackgroundModifier.java b/src/org/andengine/entity/scene/background/modifier/IBackgroundModifier.java index 35accdb31..eecd46d6a 100644 --- a/src/org/andengine/entity/scene/background/modifier/IBackgroundModifier.java +++ b/src/org/andengine/entity/scene/background/modifier/IBackgroundModifier.java @@ -4,9 +4,9 @@ import org.andengine.util.modifier.IModifier; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 14:55:54 - 03.09.2010 */ @@ -26,7 +26,7 @@ public interface IBackgroundModifier extends IModifier { // Inner and Anonymous Classes // =========================================================== - public static interface IBackgroundModifierListener extends IModifierListener{ + public static interface IBackgroundModifierListener extends IModifierListener { // =========================================================== // Constants // =========================================================== diff --git a/src/org/andengine/entity/scene/background/modifier/LoopBackgroundModifier.java b/src/org/andengine/entity/scene/background/modifier/LoopBackgroundModifier.java index ab080d2b8..0932a868d 100644 --- a/src/org/andengine/entity/scene/background/modifier/LoopBackgroundModifier.java +++ b/src/org/andengine/entity/scene/background/modifier/LoopBackgroundModifier.java @@ -4,9 +4,9 @@ import org.andengine.util.modifier.LoopModifier; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 15:03:53 - 03.09.2010 */ @@ -32,7 +32,7 @@ public LoopBackgroundModifier(final IBackgroundModifier pBackgroundModifier, fin } public LoopBackgroundModifier(final IBackgroundModifier pBackgroundModifier, final int pLoopCount, final ILoopBackgroundModifierListener pLoopModifierListener) { - super(pBackgroundModifier, pLoopCount, pLoopModifierListener, (IBackgroundModifierListener)null); + super(pBackgroundModifier, pLoopCount, pLoopModifierListener, (IBackgroundModifierListener) null); } public LoopBackgroundModifier(final IBackgroundModifier pBackgroundModifier, final int pLoopCount, final IBackgroundModifierListener pBackgroundModifierListener) { diff --git a/src/org/andengine/entity/scene/background/modifier/ParallelBackgroundModifier.java b/src/org/andengine/entity/scene/background/modifier/ParallelBackgroundModifier.java index f5179dc73..c0713c44d 100644 --- a/src/org/andengine/entity/scene/background/modifier/ParallelBackgroundModifier.java +++ b/src/org/andengine/entity/scene/background/modifier/ParallelBackgroundModifier.java @@ -4,9 +4,9 @@ import org.andengine.util.modifier.ParallelModifier; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 15:03:57 - 03.09.2010 */ diff --git a/src/org/andengine/entity/scene/background/modifier/SequenceBackgroundModifier.java b/src/org/andengine/entity/scene/background/modifier/SequenceBackgroundModifier.java index 16b6107ac..f9a6006b4 100644 --- a/src/org/andengine/entity/scene/background/modifier/SequenceBackgroundModifier.java +++ b/src/org/andengine/entity/scene/background/modifier/SequenceBackgroundModifier.java @@ -4,9 +4,9 @@ import org.andengine.util.modifier.SequenceModifier; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 15:04:02 - 03.09.2010 */ @@ -26,7 +26,7 @@ public class SequenceBackgroundModifier extends SequenceModifier im public SequenceBackgroundModifier(final IBackgroundModifier... pBackgroundModifiers) throws IllegalArgumentException { super(pBackgroundModifiers); } - + public SequenceBackgroundModifier(final ISubSequenceBackgroundModifierListener pSubSequenceBackgroundModifierListener, final IBackgroundModifier... pBackgroundModifiers) throws IllegalArgumentException { super(pSubSequenceBackgroundModifierListener, pBackgroundModifiers); } diff --git a/src/org/andengine/entity/scene/menu/MenuScene.java b/src/org/andengine/entity/scene/menu/MenuScene.java index 7de51199a..e13102658 100644 --- a/src/org/andengine/entity/scene/menu/MenuScene.java +++ b/src/org/andengine/entity/scene/menu/MenuScene.java @@ -8,16 +8,17 @@ import org.andengine.entity.scene.IOnSceneTouchListener; import org.andengine.entity.scene.ITouchArea; import org.andengine.entity.scene.Scene; -import org.andengine.entity.scene.menu.animator.IMenuAnimator; +import org.andengine.entity.scene.menu.animator.IMenuSceneAnimator; +import org.andengine.entity.scene.menu.animator.InstantMenuSceneAnimator; import org.andengine.entity.scene.menu.item.IMenuItem; import org.andengine.input.touch.TouchEvent; import android.view.MotionEvent; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 20:06:51 - 01.04.2010 */ @@ -30,11 +31,11 @@ public class MenuScene extends CameraScene implements IOnAreaTouchListener, IOnS // Fields // =========================================================== - private final ArrayList mMenuItems = new ArrayList(); + protected final ArrayList mMenuItems = new ArrayList(); private IOnMenuItemClickListener mOnMenuItemClickListener; - private IMenuAnimator mMenuAnimator = IMenuAnimator.DEFAULT; + private IMenuSceneAnimator mMenuSceneAnimator; private IMenuItem mSelectedMenuItem; @@ -42,20 +43,22 @@ public class MenuScene extends CameraScene implements IOnAreaTouchListener, IOnS // Constructors // =========================================================== - public MenuScene() { - this(null, null); + public MenuScene(final Camera pCamera) { + this(pCamera, new InstantMenuSceneAnimator()); } - public MenuScene(final IOnMenuItemClickListener pOnMenuItemClickListener) { - this(null, pOnMenuItemClickListener); + public MenuScene(final Camera pCamera, final IMenuSceneAnimator pMenuSceneAnimator) { + this(pCamera, pMenuSceneAnimator, null); } - public MenuScene(final Camera pCamera) { - this(pCamera, null); + public MenuScene(final Camera pCamera, final IOnMenuItemClickListener pOnMenuItemClickListener) { + this(pCamera, new InstantMenuSceneAnimator(), pOnMenuItemClickListener); } - public MenuScene(final Camera pCamera, final IOnMenuItemClickListener pOnMenuItemClickListener) { + public MenuScene(final Camera pCamera, final IMenuSceneAnimator pMenuSceneAnimator, final IOnMenuItemClickListener pOnMenuItemClickListener) { super(pCamera); + + this.mMenuSceneAnimator = pMenuSceneAnimator; this.mOnMenuItemClickListener = pOnMenuItemClickListener; this.setOnSceneTouchListener(this); this.setOnAreaTouchListener(this); @@ -73,6 +76,14 @@ public void setOnMenuItemClickListener(final IOnMenuItemClickListener pOnMenuIte this.mOnMenuItemClickListener = pOnMenuItemClickListener; } + public ArrayList getMenuItems() { + return this.mMenuItems; + } + + public IMenuItem getMenuItem(final int pIndex) { + return this.mMenuItems.get(pIndex); + } + public int getMenuItemCount() { return this.mMenuItems.size(); } @@ -83,6 +94,14 @@ public void addMenuItem(final IMenuItem pMenuItem) { this.registerTouchArea(pMenuItem); } + public void clearMenuItems() { + for (int i = this.mMenuItems.size() - 1; i >= 0; i--) { + final IMenuItem menuItem = this.mMenuItems.remove(i); + this.detachChild(menuItem); + this.unregisterTouchArea(menuItem); + } + } + @Override public MenuScene getChildScene() { return (MenuScene)super.getChildScene(); @@ -90,23 +109,27 @@ public MenuScene getChildScene() { @Override public void setChildScene(final Scene pChildScene, final boolean pModalDraw, final boolean pModalUpdate, final boolean pModalTouch) throws IllegalArgumentException { - if(pChildScene instanceof MenuScene) { + if (pChildScene instanceof MenuScene) { super.setChildScene(pChildScene, pModalDraw, pModalUpdate, pModalTouch); } else { - throw new IllegalArgumentException("MenuScene accepts only MenuScenes as a ChildScene."); + throw new IllegalArgumentException("A " + MenuScene.class.getSimpleName() + " accepts only " + MenuScene.class.getSimpleName() + " as a ChildScene."); } } @Override public void clearChildScene() { - if(this.getChildScene() != null) { + if (this.getChildScene() != null) { this.getChildScene().reset(); super.clearChildScene(); } } - public void setMenuAnimator(final IMenuAnimator pMenuAnimator) { - this.mMenuAnimator = pMenuAnimator; + public IMenuSceneAnimator getMenuSceneAnimator() { + return this.mMenuSceneAnimator; + } + + public void setMenuSceneAnimator(final IMenuSceneAnimator pMenuSceneAnimator) { + this.mMenuSceneAnimator = pMenuSceneAnimator; } // =========================================================== @@ -117,17 +140,17 @@ public void setMenuAnimator(final IMenuAnimator pMenuAnimator) { public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final ITouchArea pTouchArea, final float pTouchAreaLocalX, final float pTouchAreaLocalY) { final IMenuItem menuItem = ((IMenuItem)pTouchArea); - switch(pSceneTouchEvent.getAction()) { + switch (pSceneTouchEvent.getAction()) { case MotionEvent.ACTION_DOWN: case MotionEvent.ACTION_MOVE: - if(this.mSelectedMenuItem != null && this.mSelectedMenuItem != menuItem) { + if ((this.mSelectedMenuItem != null) && (this.mSelectedMenuItem != menuItem)) { this.mSelectedMenuItem.onUnselected(); } this.mSelectedMenuItem = menuItem; this.mSelectedMenuItem.onSelected(); break; case MotionEvent.ACTION_UP: - if(this.mOnMenuItemClickListener != null) { + if (this.mOnMenuItemClickListener != null) { final boolean handled = this.mOnMenuItemClickListener.onMenuItemClicked(this, menuItem, pTouchAreaLocalX, pTouchAreaLocalY); menuItem.onUnselected(); this.mSelectedMenuItem = null; @@ -144,7 +167,7 @@ public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final ITouchArea @Override public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) { - if(this.mSelectedMenuItem != null) { + if (this.mSelectedMenuItem != null) { this.mSelectedMenuItem.onUnselected(); this.mSelectedMenuItem = null; } @@ -153,21 +176,25 @@ public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouc @Override public void back() { - super.back(); + this.back(true, true); + } - this.reset(); + public void back(final boolean pResetAnimations) { + this.back(pResetAnimations, true); } - @Override - public void reset() { - super.reset(); + public void back(final boolean pResetAnimations, final boolean pResetParentMenuSceneAnimations) { + super.back(); - final ArrayList menuItems = this.mMenuItems; - for(int i = menuItems.size() - 1; i >= 0; i--) { - menuItems.get(i).reset(); + if (pResetAnimations) { + this.resetAnimations(); } - this.prepareAnimations(); + if (pResetParentMenuSceneAnimations) { + if ((this.mParentScene != null) && (this.mParentScene instanceof MenuScene)) { + ((MenuScene)this.mParentScene).resetAnimations(); + } + } } // =========================================================== @@ -179,17 +206,11 @@ public void closeMenuScene() { } public void buildAnimations() { - this.prepareAnimations(); - - final float cameraWidthRaw = this.mCamera.getWidthRaw(); - final float cameraHeightRaw = this.mCamera.getHeightRaw(); - this.mMenuAnimator.buildAnimations(this.mMenuItems, cameraWidthRaw, cameraHeightRaw); + this.mMenuSceneAnimator.buildMenuSceneAnimations(this); } - public void prepareAnimations() { - final float cameraWidthRaw = this.mCamera.getWidthRaw(); - final float cameraHeightRaw = this.mCamera.getHeightRaw(); - this.mMenuAnimator.prepareAnimations(this.mMenuItems, cameraWidthRaw, cameraHeightRaw); + public void resetAnimations() { + this.mMenuSceneAnimator.resetMenuSceneAnimations(this); } // =========================================================== diff --git a/src/org/andengine/entity/scene/menu/animator/AlphaMenuAnimator.java b/src/org/andengine/entity/scene/menu/animator/AlphaMenuAnimator.java deleted file mode 100644 index 01d1bcc63..000000000 --- a/src/org/andengine/entity/scene/menu/animator/AlphaMenuAnimator.java +++ /dev/null @@ -1,127 +0,0 @@ -package org.andengine.entity.scene.menu.animator; - -import java.util.ArrayList; - -import org.andengine.entity.modifier.AlphaModifier; -import org.andengine.entity.scene.menu.item.IMenuItem; -import org.andengine.util.HorizontalAlign; -import org.andengine.util.modifier.ease.IEaseFunction; - -/** - * (c) 2010 Nicolas Gramlich - * (c) 2011 Zynga Inc. - * - * @author Nicolas Gramlich - * @since 11:04:35 - 02.04.2010 - */ -public class AlphaMenuAnimator extends BaseMenuAnimator { - // =========================================================== - // Constants - // =========================================================== - - private static final float ALPHA_FROM = 0.0f; - private static final float ALPHA_TO = 1.0f; - - // =========================================================== - // Fields - // =========================================================== - - // =========================================================== - // Constructors - // =========================================================== - - public AlphaMenuAnimator(){ - super(); - } - - public AlphaMenuAnimator(final IEaseFunction pEaseFunction) { - super(pEaseFunction); - } - - public AlphaMenuAnimator(final HorizontalAlign pHorizontalAlign) { - super(pHorizontalAlign); - } - - public AlphaMenuAnimator(final HorizontalAlign pHorizontalAlign, final IEaseFunction pEaseFunction) { - super(pHorizontalAlign, pEaseFunction); - } - - public AlphaMenuAnimator(final float pMenuItemSpacing) { - super(pMenuItemSpacing); - } - - public AlphaMenuAnimator(final float pMenuItemSpacing, final IEaseFunction pEaseFunction) { - super(pMenuItemSpacing, pEaseFunction); - } - - public AlphaMenuAnimator(final HorizontalAlign pHorizontalAlign, final float pMenuItemSpacing) { - super(pHorizontalAlign, pMenuItemSpacing); - } - - public AlphaMenuAnimator(final HorizontalAlign pHorizontalAlign, final float pMenuItemSpacing, final IEaseFunction pEaseFunction) { - super(pHorizontalAlign, pMenuItemSpacing, pEaseFunction); - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - public void buildAnimations(final ArrayList pMenuItems, final float pCameraWidth, final float pCameraHeight) { - final IEaseFunction easeFunction = this.mEaseFunction; - final int menuItemCount = pMenuItems.size(); - for(int i = menuItemCount - 1; i >= 0; i--) { - final AlphaModifier alphaModifier = new AlphaModifier(DURATION, ALPHA_FROM, ALPHA_TO, easeFunction); - alphaModifier.setAutoUnregisterWhenFinished(false); - pMenuItems.get(i).registerEntityModifier(alphaModifier); - } - } - - @Override - public void prepareAnimations(final ArrayList pMenuItems, final float pCameraWidth, final float pCameraHeight) { - final float maximumWidth = this.getMaximumWidth(pMenuItems); - final float overallHeight = this.getOverallHeight(pMenuItems); - - final float baseX = (pCameraWidth - maximumWidth) * 0.5f; - final float baseY = (pCameraHeight - overallHeight) * 0.5f; - - final float menuItemSpacing = this.mMenuItemSpacing; - - float offsetY = 0; - final int menuItemCount = pMenuItems.size(); - for(int i = 0; i < menuItemCount; i++) { - final IMenuItem menuItem = pMenuItems.get(i); - - final float offsetX; - switch(this.mHorizontalAlign) { - case LEFT: - offsetX = 0; - break; - case RIGHT: - offsetX = maximumWidth - menuItem.getWidthScaled(); - break; - case CENTER: - default: - offsetX = (maximumWidth - menuItem.getWidthScaled()) * 0.5f; - break; - } - menuItem.setPosition(baseX + offsetX , baseY + offsetY); - - menuItem.setAlpha(ALPHA_FROM); - - offsetY += menuItem.getHeight() + menuItemSpacing; - } - } - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== -} diff --git a/src/org/andengine/entity/scene/menu/animator/AlphaMenuSceneAnimator.java b/src/org/andengine/entity/scene/menu/animator/AlphaMenuSceneAnimator.java new file mode 100644 index 000000000..55e05ce21 --- /dev/null +++ b/src/org/andengine/entity/scene/menu/animator/AlphaMenuSceneAnimator.java @@ -0,0 +1,99 @@ +package org.andengine.entity.scene.menu.animator; + +import org.andengine.entity.modifier.AlphaModifier; +import org.andengine.entity.scene.menu.MenuScene; +import org.andengine.entity.scene.menu.item.IMenuItem; +import org.andengine.util.adt.align.HorizontalAlign; +import org.andengine.util.adt.align.VerticalAlign; +import org.andengine.util.modifier.ease.EaseLinear; +import org.andengine.util.modifier.ease.IEaseFunction; + +/** + * (c) 2010 Nicolas Gramlich + * (c) 2011 Zynga Inc. + * + * @author Nicolas Gramlich + * @since 11:04:35 - 02.04.2010 + */ +public class AlphaMenuSceneAnimator extends MenuSceneAnimator { + // =========================================================== + // Constants + // =========================================================== + + private static final float DURATION = 1.0f; + private static final float ALPHA_FROM = 0.0f; + private static final float ALPHA_TO = 1.0f; + + private static final IEaseFunction EASEFUNCTION_DEFAULT = EaseLinear.getInstance(); + + // =========================================================== + // Fields + // =========================================================== + + private IEaseFunction mEaseFunction; + + // =========================================================== + // Constructors + // =========================================================== + + public AlphaMenuSceneAnimator() { + this(AlphaMenuSceneAnimator.EASEFUNCTION_DEFAULT); + } + + public AlphaMenuSceneAnimator(final IEaseFunction pEaseFunction) { + super(); + + this.mEaseFunction = pEaseFunction; + } + + public AlphaMenuSceneAnimator(final HorizontalAlign pHorizontalAlign, final VerticalAlign pVerticalAlign) { + this(pHorizontalAlign, pVerticalAlign, AlphaMenuSceneAnimator.EASEFUNCTION_DEFAULT); + } + + public AlphaMenuSceneAnimator(final HorizontalAlign pHorizontalAlign, final VerticalAlign pVerticalAlign, final IEaseFunction pEaseFunction) { + super(pHorizontalAlign, pVerticalAlign); + + this.mEaseFunction = pEaseFunction; + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + public IEaseFunction getEaseFunction() { + return this.mEaseFunction; + } + + public void setEaseFunction(final IEaseFunction pEaseFunction) { + this.mEaseFunction = pEaseFunction; + } + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + protected void onMenuItemPositionBuilt(final MenuScene pMenuScene, final int pIndex, final IMenuItem pMenuItem, final float pX, final float pY) { + pMenuItem.setPosition(pX, pY); + + final AlphaModifier alphaModifier = new AlphaModifier(AlphaMenuSceneAnimator.DURATION, AlphaMenuSceneAnimator.ALPHA_FROM, AlphaMenuSceneAnimator.ALPHA_TO, this.mEaseFunction); + alphaModifier.setAutoUnregisterWhenFinished(false); + pMenuItem.registerEntityModifier(alphaModifier); + } + + @Override + protected void onMenuItemPositionReset(final MenuScene pMenuScene, final int pIndex, final IMenuItem pMenuItem, final float pX, final float pY) { + pMenuItem.setPosition(pX, pY); + + pMenuItem.resetEntityModifiers(); + pMenuItem.setAlpha(AlphaMenuSceneAnimator.ALPHA_FROM); + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== +} diff --git a/src/org/andengine/entity/scene/menu/animator/BaseMenuAnimator.java b/src/org/andengine/entity/scene/menu/animator/BaseMenuAnimator.java deleted file mode 100644 index 083a7c120..000000000 --- a/src/org/andengine/entity/scene/menu/animator/BaseMenuAnimator.java +++ /dev/null @@ -1,109 +0,0 @@ -package org.andengine.entity.scene.menu.animator; - -import java.util.ArrayList; - -import org.andengine.entity.scene.menu.item.IMenuItem; -import org.andengine.util.HorizontalAlign; -import org.andengine.util.modifier.ease.EaseLinear; -import org.andengine.util.modifier.ease.IEaseFunction; - -/** - * (c) 2010 Nicolas Gramlich - * (c) 2011 Zynga Inc. - * - * @author Nicolas Gramlich - * @since 11:17:32 - 02.04.2010 - */ -public abstract class BaseMenuAnimator implements IMenuAnimator { - // =========================================================== - // Constants - // =========================================================== - - protected static final float DURATION = 1.0f; - - private static final float MENUITEMSPACING_DEFAULT = 1.0f; - - private static final HorizontalAlign HORIZONTALALIGN_DEFAULT = HorizontalAlign.CENTER; - - // =========================================================== - // Fields - // =========================================================== - - protected final float mMenuItemSpacing; - protected final HorizontalAlign mHorizontalAlign; - protected final IEaseFunction mEaseFunction; - - // =========================================================== - // Constructors - // =========================================================== - - public BaseMenuAnimator() { - this(MENUITEMSPACING_DEFAULT); - } - - public BaseMenuAnimator(final IEaseFunction pEaseFunction) { - this(MENUITEMSPACING_DEFAULT, pEaseFunction); - } - - public BaseMenuAnimator(final float pMenuItemSpacing) { - this(HORIZONTALALIGN_DEFAULT, pMenuItemSpacing); - } - - public BaseMenuAnimator(final float pMenuItemSpacing, final IEaseFunction pEaseFunction) { - this(HORIZONTALALIGN_DEFAULT, pMenuItemSpacing, pEaseFunction); - } - - public BaseMenuAnimator(final HorizontalAlign pHorizontalAlign) { - this(pHorizontalAlign, MENUITEMSPACING_DEFAULT); - } - - public BaseMenuAnimator(final HorizontalAlign pHorizontalAlign, final IEaseFunction pEaseFunction) { - this(pHorizontalAlign, MENUITEMSPACING_DEFAULT, pEaseFunction); - } - - public BaseMenuAnimator(final HorizontalAlign pHorizontalAlign, final float pMenuItemSpacing) { - this(pHorizontalAlign, pMenuItemSpacing, EaseLinear.getInstance()); - } - - public BaseMenuAnimator(final HorizontalAlign pHorizontalAlign, final float pMenuItemSpacing, final IEaseFunction pEaseFunction) { - this.mHorizontalAlign = pHorizontalAlign; - this.mMenuItemSpacing = pMenuItemSpacing; - this.mEaseFunction = pEaseFunction; - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - protected float getMaximumWidth(final ArrayList pMenuItems) { - float maximumWidth = Float.MIN_VALUE; - for(int i = pMenuItems.size() - 1; i >= 0; i--) { - final IMenuItem menuItem = pMenuItems.get(i); - maximumWidth = Math.max(maximumWidth, menuItem.getWidthScaled()); - } - return maximumWidth; - } - - protected float getOverallHeight(final ArrayList pMenuItems) { - float overallHeight = 0; - for(int i = pMenuItems.size() - 1; i >= 0; i--) { - final IMenuItem menuItem = pMenuItems.get(i); - overallHeight += menuItem.getHeight(); - } - - overallHeight += (pMenuItems.size() - 1) * this.mMenuItemSpacing; - return overallHeight; - } - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== -} diff --git a/src/org/andengine/entity/scene/menu/animator/DirectMenuAnimator.java b/src/org/andengine/entity/scene/menu/animator/DirectMenuAnimator.java deleted file mode 100644 index 7d0639292..000000000 --- a/src/org/andengine/entity/scene/menu/animator/DirectMenuAnimator.java +++ /dev/null @@ -1,98 +0,0 @@ -package org.andengine.entity.scene.menu.animator; - -import java.util.ArrayList; - -import org.andengine.entity.scene.menu.item.IMenuItem; -import org.andengine.util.HorizontalAlign; - -/** - * (c) 2010 Nicolas Gramlich - * (c) 2011 Zynga Inc. - * - * @author Nicolas Gramlich - * @since 10:46:34 - 14.05.2010 - */ -public class DirectMenuAnimator extends BaseMenuAnimator { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - // =========================================================== - // Constructors - // =========================================================== - - public DirectMenuAnimator(){ - super(); - } - - public DirectMenuAnimator(final HorizontalAlign pHorizontalAlign) { - super(pHorizontalAlign); - } - - public DirectMenuAnimator(final float pMenuItemSpacing) { - super(pMenuItemSpacing); - } - - public DirectMenuAnimator(final HorizontalAlign pHorizontalAlign, final float pMenuItemSpacing) { - super(pHorizontalAlign, pMenuItemSpacing); - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - public void buildAnimations(final ArrayList pMenuItems, final float pCameraWidth, final float pCameraHeight) { - - } - - @Override - public void prepareAnimations(final ArrayList pMenuItems, final float pCameraWidth, final float pCameraHeight) { - final float maximumWidth = this.getMaximumWidth(pMenuItems); - final float overallHeight = this.getOverallHeight(pMenuItems); - - final float baseX = (pCameraWidth - maximumWidth) * 0.5f; - final float baseY = (pCameraHeight - overallHeight) * 0.5f; - - final float menuItemSpacing = this.mMenuItemSpacing; - - float offsetY = 0; - final int menuItemCount = pMenuItems.size(); - for(int i = 0; i < menuItemCount; i++) { - final IMenuItem menuItem = pMenuItems.get(i); - - final float offsetX; - switch(this.mHorizontalAlign) { - case LEFT: - offsetX = 0; - break; - case RIGHT: - offsetX = maximumWidth - menuItem.getWidthScaled(); - break; - case CENTER: - default: - offsetX = (maximumWidth - menuItem.getWidthScaled()) * 0.5f; - break; - } - menuItem.setPosition(baseX + offsetX , baseY + offsetY); - - offsetY += menuItem.getHeight() + menuItemSpacing; - } - } - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== -} diff --git a/src/org/andengine/entity/scene/menu/animator/IMenuAnimator.java b/src/org/andengine/entity/scene/menu/animator/IMenuAnimator.java deleted file mode 100644 index f9cb8df6e..000000000 --- a/src/org/andengine/entity/scene/menu/animator/IMenuAnimator.java +++ /dev/null @@ -1,27 +0,0 @@ -package org.andengine.entity.scene.menu.animator; - -import java.util.ArrayList; - -import org.andengine.entity.scene.menu.item.IMenuItem; - -/** - * (c) 2010 Nicolas Gramlich - * (c) 2011 Zynga Inc. - * - * @author Nicolas Gramlich - * @since 10:50:36 - 02.04.2010 - */ -public interface IMenuAnimator { - // =========================================================== - // Constants - // =========================================================== - - public static final IMenuAnimator DEFAULT = new AlphaMenuAnimator(); - - // =========================================================== - // Methods - // =========================================================== - - public void prepareAnimations(final ArrayList pMenuItems, final float pCameraWidth, final float pCameraHeight); - public void buildAnimations(final ArrayList pMenuItems, final float pCameraWidth, final float pCameraHeight); -} diff --git a/src/org/andengine/entity/scene/menu/animator/IMenuSceneAnimator.java b/src/org/andengine/entity/scene/menu/animator/IMenuSceneAnimator.java new file mode 100644 index 000000000..57c290a3e --- /dev/null +++ b/src/org/andengine/entity/scene/menu/animator/IMenuSceneAnimator.java @@ -0,0 +1,36 @@ +package org.andengine.entity.scene.menu.animator; + +import org.andengine.entity.scene.menu.MenuScene; +import org.andengine.util.adt.align.HorizontalAlign; +import org.andengine.util.adt.align.VerticalAlign; + +/** + * (c) 2010 Nicolas Gramlich + * (c) 2011 Zynga Inc. + * + * @author Nicolas Gramlich + * @since 10:50:36 - 02.04.2010 + */ +public interface IMenuSceneAnimator { + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + public float getOffsetX(); + public void setOffsetX(final float pOffsetX); + public float getOffsetY(); + public void setOffsetY(final float pOffsetY); + public float getMenuItemSpacing(); + public void setMenuItemSpacing(final float pMenuItemSpacing); + public HorizontalAlign getHorizontalAlign(); + public void setHorizontalAlign(final HorizontalAlign pHorizontalAlign); + public VerticalAlign getVerticalAlign(); + public void setVerticalAlign(final VerticalAlign pVerticalAlign); + + public void buildMenuSceneAnimations(final MenuScene pMenuScene); + public void resetMenuSceneAnimations(final MenuScene pMenuScene); +} diff --git a/src/org/andengine/entity/scene/menu/animator/InstantMenuSceneAnimator.java b/src/org/andengine/entity/scene/menu/animator/InstantMenuSceneAnimator.java new file mode 100644 index 000000000..30728db3d --- /dev/null +++ b/src/org/andengine/entity/scene/menu/animator/InstantMenuSceneAnimator.java @@ -0,0 +1,61 @@ +package org.andengine.entity.scene.menu.animator; + +import org.andengine.entity.scene.menu.MenuScene; +import org.andengine.entity.scene.menu.item.IMenuItem; +import org.andengine.util.adt.align.HorizontalAlign; +import org.andengine.util.adt.align.VerticalAlign; + +/** + * (c) 2010 Nicolas Gramlich + * (c) 2011 Zynga Inc. + * + * @author Nicolas Gramlich + * @since 11:04:35 - 02.04.2010 + */ +public class InstantMenuSceneAnimator extends MenuSceneAnimator { + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + // =========================================================== + // Constructors + // =========================================================== + + public InstantMenuSceneAnimator() { + super(); + } + + public InstantMenuSceneAnimator(final HorizontalAlign pHorizontalAlign, final VerticalAlign pVerticalAlign) { + super(pHorizontalAlign, pVerticalAlign); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + protected void onMenuItemPositionBuilt(final MenuScene pMenuScene, final int pIndex, final IMenuItem pMenuItem, final float pX, final float pY) { + pMenuItem.setPosition(pX, pY); + } + + @Override + protected void onMenuItemPositionReset(final MenuScene pMenuScene, final int pIndex, final IMenuItem pMenuItem, final float pX, final float pY) { + pMenuItem.setPosition(pX, pY); + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== +} diff --git a/src/org/andengine/entity/scene/menu/animator/MenuSceneAnimator.java b/src/org/andengine/entity/scene/menu/animator/MenuSceneAnimator.java new file mode 100644 index 000000000..cafc6bdf8 --- /dev/null +++ b/src/org/andengine/entity/scene/menu/animator/MenuSceneAnimator.java @@ -0,0 +1,214 @@ +package org.andengine.entity.scene.menu.animator; + +import org.andengine.entity.scene.menu.MenuScene; +import org.andengine.entity.scene.menu.item.IMenuItem; +import org.andengine.util.adt.align.HorizontalAlign; +import org.andengine.util.adt.align.VerticalAlign; + +/** + * (c) 2010 Nicolas Gramlich + * (c) 2011 Zynga Inc. + * + * @author Nicolas Gramlich + * @since 11:17:32 - 02.04.2010 + */ +public abstract class MenuSceneAnimator implements IMenuSceneAnimator { + // =========================================================== + // Constants + // =========================================================== + + private static final HorizontalAlign HORIZONTALALIGN_DEFAULT = HorizontalAlign.CENTER; + private static final VerticalAlign VERTICALALIGN_DEFAULT = VerticalAlign.CENTER; + private static final float SPACING_DEFAULT = 1.0f; + private static final float OFFSET_X_DEFAULT = 0.0f; + private static final float OFFSET_Y_DEFAULT = 0.0f; + + // =========================================================== + // Fields + // =========================================================== + + protected HorizontalAlign mHorizontalAlign; + protected VerticalAlign mVerticalAlign; + + protected float mOffsetX = MenuSceneAnimator.OFFSET_X_DEFAULT; + protected float mOffsetY = MenuSceneAnimator.OFFSET_Y_DEFAULT; + + protected float mMenuItemSpacing = MenuSceneAnimator.SPACING_DEFAULT; + protected float mOverallHeight; + + // =========================================================== + // Constructors + // =========================================================== + + public MenuSceneAnimator() { + this(MenuSceneAnimator.HORIZONTALALIGN_DEFAULT, MenuSceneAnimator.VERTICALALIGN_DEFAULT); + } + + public MenuSceneAnimator(final HorizontalAlign pHorizontalAlign, final VerticalAlign pVerticalAlign) { + this.mHorizontalAlign = pHorizontalAlign; + this.mVerticalAlign = pVerticalAlign; + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + @Override + public float getOffsetX() { + return this.mOffsetX; + } + + @Override + public void setOffsetX(final float pOffsetX) { + this.mOffsetX = pOffsetX; + } + + @Override + public float getOffsetY() { + return this.mOffsetY; + } + + @Override + public void setOffsetY(final float pOffsetY) { + this.mOffsetY = pOffsetY; + } + + @Override + public float getMenuItemSpacing() { + return this.mMenuItemSpacing; + } + + @Override + public void setMenuItemSpacing(final float pMenuItemSpacing) { + this.mMenuItemSpacing = pMenuItemSpacing; + } + + @Override + public HorizontalAlign getHorizontalAlign() { + return this.mHorizontalAlign; + } + + @Override + public void setHorizontalAlign(final HorizontalAlign pHorizontalAlign) { + this.mHorizontalAlign = pHorizontalAlign; + } + + @Override + public VerticalAlign getVerticalAlign() { + return this.mVerticalAlign; + } + + @Override + public void setVerticalAlign(final VerticalAlign pVerticalAlign) { + this.mVerticalAlign = pVerticalAlign; + } + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + protected abstract void onMenuItemPositionBuilt(final MenuScene pMenuScene, final int pIndex, final IMenuItem pMenuItem, final float pX, final float pY); + protected abstract void onMenuItemPositionReset(final MenuScene pMenuScene, final int pIndex, final IMenuItem pMenuItem, final float pX, final float pY); + + @Override + public void buildMenuSceneAnimations(final MenuScene pMenuScene) { + this.updateOverallHeight(pMenuScene); + + final int menuItemCount = pMenuScene.getMenuItemCount(); + + for (int i = 0; i < menuItemCount; i++) { + final IMenuItem menuItem = pMenuScene.getMenuItem(i); + + final float x = this.getMenuItemX(pMenuScene, i); + final float y = this.getMenuItemY(pMenuScene, i); + this.onMenuItemPositionBuilt(pMenuScene, i, menuItem, x, y); + } + } + + @Override + public void resetMenuSceneAnimations(final MenuScene pMenuScene) { + final int menuItemCount = pMenuScene.getMenuItemCount(); + + for (int i = 0; i < menuItemCount; i++) { + final IMenuItem menuItem = pMenuScene.getMenuItem(i); + + final float x = this.getMenuItemX(pMenuScene, i); + final float y = this.getMenuItemY(pMenuScene, i); + this.onMenuItemPositionReset(pMenuScene, i, menuItem, x, y); + } + } + + // =========================================================== + // Methods + // =========================================================== + + protected float getMenuItemX(final MenuScene pMenuScene, final int pIndex) { + final float menuSceneWidth = pMenuScene.getWidth(); + + final IMenuItem menuItem = pMenuScene.getMenuItem(pIndex); + final float menuItemWidth = menuItem.getWidth(); + + /* Determine horizontal position. */ + final float x; + switch (this.mHorizontalAlign) { + case LEFT: + x = menuItemWidth * 0.5f; + break; + case CENTER: + x = menuSceneWidth * 0.5f; + break; + case RIGHT: + x = menuSceneWidth - (menuItemWidth * 0.5f); + break; + default: + throw new IllegalArgumentException("Unexpected " + HorizontalAlign.class.getSimpleName() + " with value: '" + this.mHorizontalAlign + "'."); + } + + return x + this.mOffsetX; + } + + protected float getMenuItemY(final MenuScene pMenuScene, final int pIndex) { + final float menuSceneHeight = pMenuScene.getHeight(); + + final IMenuItem menuItem = pMenuScene.getMenuItem(pIndex); + + /* Prepare vertical position. */ + float baseY; + switch (this.mVerticalAlign) { + case TOP: + baseY = menuSceneHeight; + break; + case CENTER: + baseY = (0.5f * menuSceneHeight) + (this.mOverallHeight * 0.5f); + break; + case BOTTOM: + baseY = this.mOverallHeight; + break; + default: + throw new IllegalArgumentException("Unexpected " + VerticalAlign.class.getSimpleName() + " with value: '" + this.mVerticalAlign + "'."); + } + + final float menuItemHeight = menuItem.getHeight(); + + /* Determine vertical position. */ + final float y = baseY - (menuItemHeight * 0.5f) - (pIndex * (menuItemHeight + this.mMenuItemSpacing)); + + return y + this.mOffsetY; + } + + private void updateOverallHeight(final MenuScene pMenuScene) { + final int menuItemCount = pMenuScene.getMenuItemCount(); + + float overallHeight = 0; + for (int i = menuItemCount - 1; i >= 0; i--) { + final IMenuItem menuItem = pMenuScene.getMenuItem(i); + overallHeight += menuItem.getHeight(); + } + + this.mOverallHeight = overallHeight + ((menuItemCount - 1) * this.mMenuItemSpacing); + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== +} diff --git a/src/org/andengine/entity/scene/menu/animator/SlideMenuAnimator.java b/src/org/andengine/entity/scene/menu/animator/SlideMenuAnimator.java deleted file mode 100644 index fe7e72664..000000000 --- a/src/org/andengine/entity/scene/menu/animator/SlideMenuAnimator.java +++ /dev/null @@ -1,133 +0,0 @@ -package org.andengine.entity.scene.menu.animator; - -import java.util.ArrayList; - -import org.andengine.entity.modifier.MoveModifier; -import org.andengine.entity.scene.menu.item.IMenuItem; -import org.andengine.util.HorizontalAlign; -import org.andengine.util.modifier.ease.IEaseFunction; - -/** - * (c) 2010 Nicolas Gramlich - * (c) 2011 Zynga Inc. - * - * @author Nicolas Gramlich - * @since 11:04:35 - 02.04.2010 - */ -public class SlideMenuAnimator extends BaseMenuAnimator { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - // =========================================================== - // Constructors - // =========================================================== - - public SlideMenuAnimator(){ - super(); - } - - public SlideMenuAnimator(final IEaseFunction pEaseFunction) { - super(pEaseFunction); - } - - public SlideMenuAnimator(final HorizontalAlign pHorizontalAlign) { - super(pHorizontalAlign); - } - - public SlideMenuAnimator(final HorizontalAlign pHorizontalAlign, final IEaseFunction pEaseFunction) { - super(pHorizontalAlign, pEaseFunction); - } - - public SlideMenuAnimator(final float pMenuItemSpacing) { - super(pMenuItemSpacing); - } - - public SlideMenuAnimator(final float pMenuItemSpacing, final IEaseFunction pEaseFunction) { - super(pMenuItemSpacing, pEaseFunction); - } - - public SlideMenuAnimator(final HorizontalAlign pHorizontalAlign, final float pMenuItemSpacing) { - super(pHorizontalAlign, pMenuItemSpacing); - } - - public SlideMenuAnimator(final HorizontalAlign pHorizontalAlign, final float pMenuItemSpacing, final IEaseFunction pEaseFunction) { - super(pHorizontalAlign, pMenuItemSpacing, pEaseFunction); - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - public void buildAnimations(final ArrayList pMenuItems, final float pCameraWidth, final float pCameraHeight) { - final IEaseFunction easeFunction = this.mEaseFunction; - final float maximumWidth = this.getMaximumWidth(pMenuItems); - final float overallHeight = this.getOverallHeight(pMenuItems); - - final float baseX = (pCameraWidth - maximumWidth) * 0.5f; - final float baseY = (pCameraHeight - overallHeight) * 0.5f; - - float offsetY = 0; - final int menuItemCount = pMenuItems.size(); - for(int i = 0; i < menuItemCount; i++) { - final IMenuItem menuItem = pMenuItems.get(i); - - final float offsetX; - switch(this.mHorizontalAlign) { - case LEFT: - offsetX = 0; - break; - case RIGHT: - offsetX = maximumWidth - menuItem.getWidthScaled(); - break; - case CENTER: - default: - offsetX = (maximumWidth - menuItem.getWidthScaled()) * 0.5f; - break; - } - - final MoveModifier moveModifier = new MoveModifier(DURATION, -maximumWidth, baseX + offsetX, baseY + offsetY, baseY + offsetY, easeFunction); - moveModifier.setAutoUnregisterWhenFinished(false); - menuItem.registerEntityModifier(moveModifier); - - offsetY += menuItem.getHeight() + this.mMenuItemSpacing; - } - } - - @Override - public void prepareAnimations(final ArrayList pMenuItems, final float pCameraWidth, final float pCameraHeight) { - final float maximumWidth = this.getMaximumWidth(pMenuItems); - final float overallHeight = this.getOverallHeight(pMenuItems); - - final float baseY = (pCameraHeight - overallHeight) * 0.5f; - - final float menuItemSpacing = this.mMenuItemSpacing; - - float offsetY = 0; - final int menuItemCount = pMenuItems.size(); - for(int i = 0; i < menuItemCount; i++) { - final IMenuItem menuItem = pMenuItems.get(i); - - menuItem.setPosition(-maximumWidth, baseY + offsetY); - - offsetY += menuItem.getHeight() + menuItemSpacing; - } - } - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== -} diff --git a/src/org/andengine/entity/scene/menu/animator/SlideMenuSceneAnimator.java b/src/org/andengine/entity/scene/menu/animator/SlideMenuSceneAnimator.java new file mode 100644 index 000000000..5fa2c5f60 --- /dev/null +++ b/src/org/andengine/entity/scene/menu/animator/SlideMenuSceneAnimator.java @@ -0,0 +1,168 @@ +package org.andengine.entity.scene.menu.animator; + +import org.andengine.entity.modifier.MoveModifier; +import org.andengine.entity.scene.menu.MenuScene; +import org.andengine.entity.scene.menu.item.IMenuItem; +import org.andengine.util.adt.align.HorizontalAlign; +import org.andengine.util.adt.align.VerticalAlign; +import org.andengine.util.adt.spatial.Direction; +import org.andengine.util.modifier.ease.EaseLinear; +import org.andengine.util.modifier.ease.IEaseFunction; + +/** + * (c) 2010 Nicolas Gramlich + * (c) 2011 Zynga Inc. + * + * @author Nicolas Gramlich + * @since 11:04:35 - 02.04.2010 + */ +public class SlideMenuSceneAnimator extends MenuSceneAnimator { + // =========================================================== + // Constants + // =========================================================== + + private static final float DURATION = 1.0f; + + private static final IEaseFunction EASEFUNCTION_DEFAULT = EaseLinear.getInstance(); + + private static final Direction DIRECTION_DEFAULT = Direction.RIGHT; + + // =========================================================== + // Fields + // =========================================================== + + private IEaseFunction mEaseFunction; + private Direction mDirection; + + // =========================================================== + // Constructors + // =========================================================== + + public SlideMenuSceneAnimator() { + this(SlideMenuSceneAnimator.DIRECTION_DEFAULT, SlideMenuSceneAnimator.EASEFUNCTION_DEFAULT); + } + + public SlideMenuSceneAnimator(final IEaseFunction pEaseFunction) { + this(SlideMenuSceneAnimator.DIRECTION_DEFAULT, pEaseFunction); + } + + public SlideMenuSceneAnimator(final Direction pDirection) { + this(pDirection, SlideMenuSceneAnimator.EASEFUNCTION_DEFAULT); + } + + public SlideMenuSceneAnimator(final Direction pDirection, final IEaseFunction pEaseFunction) { + super(); + + this.mDirection = pDirection; + this.mEaseFunction = pEaseFunction; + } + + public SlideMenuSceneAnimator(final HorizontalAlign pHorizontalAlign, final VerticalAlign pVerticalAlign) { + this(pHorizontalAlign, pVerticalAlign, SlideMenuSceneAnimator.DIRECTION_DEFAULT, SlideMenuSceneAnimator.EASEFUNCTION_DEFAULT); + } + + public SlideMenuSceneAnimator(final HorizontalAlign pHorizontalAlign, final VerticalAlign pVerticalAlign, final IEaseFunction pEaseFunction) { + this(pHorizontalAlign, pVerticalAlign, SlideMenuSceneAnimator.DIRECTION_DEFAULT, pEaseFunction); + } + + public SlideMenuSceneAnimator(final HorizontalAlign pHorizontalAlign, final VerticalAlign pVerticalAlign, final Direction pDirection) { + this(pHorizontalAlign, pVerticalAlign, pDirection, SlideMenuSceneAnimator.EASEFUNCTION_DEFAULT); + } + + public SlideMenuSceneAnimator(final HorizontalAlign pHorizontalAlign, final VerticalAlign pVerticalAlign, final Direction pDirection, final IEaseFunction pEaseFunction) { + super(pHorizontalAlign, pVerticalAlign); + + this.mDirection = pDirection; + this.mEaseFunction = pEaseFunction; + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + public IEaseFunction getEaseFunction() { + return this.mEaseFunction; + } + + public void setEaseFunction(final IEaseFunction pEaseFunction) { + this.mEaseFunction = pEaseFunction; + } + + public Direction getDirection() { + return this.mDirection; + } + + public void setDirection(final Direction pDirection) { + this.mDirection = pDirection; + } + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + protected void onMenuItemPositionBuilt(final MenuScene pMenuScene, final int pIndex, final IMenuItem pMenuItem, final float pX, final float pY) { + final float fromX = getFromX(pMenuScene, pMenuItem, pX); + final float fromY = getFromY(pMenuScene, pMenuItem, pY); + + pMenuItem.setPosition(fromX, fromY); + + final MoveModifier moveModifier = new MoveModifier(SlideMenuSceneAnimator.DURATION, fromX, fromY, pX, pY, this.mEaseFunction); + moveModifier.setAutoUnregisterWhenFinished(false); + pMenuItem.registerEntityModifier(moveModifier); + } + + @Override + protected void onMenuItemPositionReset(final MenuScene pMenuScene, final int pIndex, final IMenuItem pMenuItem, final float pX, final float pY) { + final float fromX = getFromX(pMenuScene, pMenuItem, pX); + final float fromY = getFromY(pMenuScene, pMenuItem, pY); + + pMenuItem.setPosition(fromX, fromY); + + pMenuItem.resetEntityModifiers(); + } + + // =========================================================== + // Methods + // =========================================================== + + protected float getFromX(final MenuScene pMenuScene, final IMenuItem pMenuItem, final float pX) { + switch (this.mDirection) { + case UP: + case DOWN: + return pX; + case DOWN_LEFT: + case UP_LEFT: + case LEFT: + return pMenuScene.getWidth() + (pMenuItem.getWidth() * 0.5f); + case DOWN_RIGHT: + case UP_RIGHT: + case RIGHT: + return -(pMenuItem.getWidth() * 0.5f); + default: + throw new IllegalArgumentException(); + } + } + + protected float getFromY(final MenuScene pMenuScene, final IMenuItem pMenuItem, final float pY) { + switch (this.mDirection) { + case DOWN_LEFT: + case DOWN: + case DOWN_RIGHT: + return pMenuScene.getHeight() + (pMenuItem.getHeight() * 0.5f); + case LEFT: + case RIGHT: + return pY; + case UP_LEFT: + case UP: + case UP_RIGHT: + return -(pMenuItem.getHeight() * 0.5f); + default: + throw new IllegalArgumentException(); + } + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== +} diff --git a/src/org/andengine/entity/scene/menu/item/AnimatedSpriteMenuItem.java b/src/org/andengine/entity/scene/menu/item/AnimatedSpriteMenuItem.java index 34593a4e2..2ff796544 100644 --- a/src/org/andengine/entity/scene/menu/item/AnimatedSpriteMenuItem.java +++ b/src/org/andengine/entity/scene/menu/item/AnimatedSpriteMenuItem.java @@ -10,7 +10,7 @@ /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 15:44:39 - 07.07.2010 */ diff --git a/src/org/andengine/entity/scene/menu/item/IMenuItem.java b/src/org/andengine/entity/scene/menu/item/IMenuItem.java index 77b340cf5..3e8d5b787 100644 --- a/src/org/andengine/entity/scene/menu/item/IMenuItem.java +++ b/src/org/andengine/entity/scene/menu/item/IMenuItem.java @@ -1,15 +1,15 @@ package org.andengine.entity.scene.menu.item; -import org.andengine.entity.shape.IAreaShape; +import org.andengine.entity.shape.IShape; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 13:27:16 - 07.07.2010 */ -public interface IMenuItem extends IAreaShape { +public interface IMenuItem extends IShape { // =========================================================== // Constants // =========================================================== diff --git a/src/org/andengine/entity/scene/menu/item/SpriteMenuItem.java b/src/org/andengine/entity/scene/menu/item/SpriteMenuItem.java index df733a96b..69968bc85 100644 --- a/src/org/andengine/entity/scene/menu/item/SpriteMenuItem.java +++ b/src/org/andengine/entity/scene/menu/item/SpriteMenuItem.java @@ -10,7 +10,7 @@ /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 20:15:20 - 01.04.2010 */ diff --git a/src/org/andengine/entity/scene/menu/item/TextMenuItem.java b/src/org/andengine/entity/scene/menu/item/TextMenuItem.java index 8ef0ae031..716975b34 100644 --- a/src/org/andengine/entity/scene/menu/item/TextMenuItem.java +++ b/src/org/andengine/entity/scene/menu/item/TextMenuItem.java @@ -11,7 +11,7 @@ /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 20:15:20 - 01.04.2010 */ diff --git a/src/org/andengine/entity/scene/menu/item/decorator/BaseMenuItemDecorator.java b/src/org/andengine/entity/scene/menu/item/decorator/BaseMenuItemDecorator.java index 33a5b26e6..55361136d 100644 --- a/src/org/andengine/entity/scene/menu/item/decorator/BaseMenuItemDecorator.java +++ b/src/org/andengine/entity/scene/menu/item/decorator/BaseMenuItemDecorator.java @@ -12,21 +12,20 @@ import org.andengine.entity.modifier.IEntityModifier; import org.andengine.entity.modifier.IEntityModifier.IEntityModifierMatcher; import org.andengine.entity.scene.menu.item.IMenuItem; -import org.andengine.entity.shape.IShape; import org.andengine.input.touch.TouchEvent; import org.andengine.opengl.shader.ShaderProgram; import org.andengine.opengl.util.GLState; import org.andengine.opengl.vbo.IVertexBufferObject; import org.andengine.opengl.vbo.VertexBufferObjectManager; +import org.andengine.util.adt.color.Color; import org.andengine.util.adt.transformation.Transformation; -import org.andengine.util.color.Color; /** * I HATE THIS CLASS! - * + * * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 15:05:44 - 18.11.2010 */ @@ -122,7 +121,8 @@ public void setPosition(final float pX, final float pY) { public float getWidth() { return this.mMenuItem.getWidth(); } - + + @Deprecated @Override public float getWidthScaled() { return this.mMenuItem.getWidthScaled(); @@ -132,7 +132,8 @@ public float getWidthScaled() { public float getHeight() { return this.mMenuItem.getHeight(); } - + + @Deprecated @Override public float getHeightScaled() { return this.mMenuItem.getHeightScaled(); @@ -203,6 +204,11 @@ public void setColor(final Color pColor) { this.mMenuItem.setColor(pColor); } + @Override + public void setColor(final int pARGBPackedInt) { + this.mMenuItem.setColor(pARGBPackedInt); + } + @Override public void setColor(final float pRed, final float pGreen, final float pBlue) { this.mMenuItem.setColor(pRed, pGreen, pBlue); @@ -213,6 +219,31 @@ public void setColor(final float pRed, final float pGreen, final float pBlue, fi this.mMenuItem.setColor(pRed, pGreen, pBlue, pAlpha); } + @Override + public float getOffsetCenterX() { + return this.mMenuItem.getOffsetCenterX(); + } + + @Override + public float getOffsetCenterY() { + return this.mMenuItem.getOffsetCenterY(); + } + + @Override + public void setOffsetCenterX(final float pOffsetCenterX) { + this.mMenuItem.setOffsetCenterX(pOffsetCenterX); + } + + @Override + public void setOffsetCenterY(final float pOffsetCenterY) { + this.mMenuItem.setOffsetCenterY(pOffsetCenterY); + } + + @Override + public void setOffsetCenter(final float pOffsetCenterX, final float pOffsetCenterY) { + this.mMenuItem.setOffsetCenter(pOffsetCenterX, pOffsetCenterY); + } + @Override public boolean isRotated() { return this.mMenuItem.isRotated(); @@ -312,62 +343,62 @@ public void setScaleCenterY(final float pScaleCenterY) { public void setScaleCenter(final float pScaleCenterX, final float pScaleCenterY) { this.mMenuItem.setScaleCenter(pScaleCenterX, pScaleCenterY); } - + @Override public boolean isSkewed() { return this.mMenuItem.isSkewed(); } - + @Override public float getSkewX() { return this.mMenuItem.getSkewX(); } - + @Override public float getSkewY() { return this.mMenuItem.getSkewY(); } - + @Override public void setSkew(final float pSkew) { this.mMenuItem.setSkew(pSkew); } - + @Override public void setSkew(final float pSkewX, final float pSkewY) { this.mMenuItem.setSkew(pSkewX, pSkewY); } - + @Override public void setSkewX(final float pSkewX) { this.mMenuItem.setSkewX(pSkewX); } - + @Override public void setSkewY(final float pSkewY) { this.mMenuItem.setSkewY(pSkewY); } - + @Override public float getSkewCenterX() { return this.mMenuItem.getSkewCenterX(); } - + @Override public float getSkewCenterY() { return this.mMenuItem.getSkewCenterY(); } - + @Override public void setSkewCenterX(final float pSkewCenterX) { this.mMenuItem.setSkewCenterX(pSkewCenterX); } - + @Override public void setSkewCenterY(final float pSkewCenterY) { this.mMenuItem.setSkewCenterY(pSkewCenterY); } - + @Override public void setSkewCenter(final float pSkewCenterX, final float pSkewCenterY) { this.mMenuItem.setSkewCenter(pSkewCenterX, pSkewCenterY); @@ -377,10 +408,25 @@ public void setSkewCenter(final float pSkewCenterX, final float pSkewCenterY) { public boolean isRotatedOrScaledOrSkewed() { return this.mMenuItem.isRotatedOrScaledOrSkewed(); } - + @Override - public boolean collidesWith(final IShape pOtherShape) { - return this.mMenuItem.collidesWith(pOtherShape); + public void setAnchorCenterX(final float pAnchorCenterX) { + this.setAnchorCenterX(pAnchorCenterX); + } + + @Override + public void setAnchorCenterY(final float pAnchorCenterY) { + this.setAnchorCenterY(pAnchorCenterY); + } + + @Override + public void setAnchorCenter(final float pAnchorCenterX, final float pAnchorCenterY) { + this.mMenuItem.setAnchorCenter(pAnchorCenterX, pAnchorCenterY); + } + + @Override + public boolean collidesWith(final IEntity pOtherEntity) { + return this.mMenuItem.collidesWith(pOtherEntity); } @Override @@ -413,11 +459,21 @@ public boolean unregisterEntityModifiers(final IEntityModifierMatcher pEntityMod return this.mMenuItem.unregisterEntityModifiers(pEntityModifierMatcher); } + @Override + public int getEntityModifierCount() { + return this.mMenuItem.getEntityModifierCount(); + } + @Override public void clearEntityModifiers() { this.mMenuItem.clearEntityModifiers(); } + @Override + public void resetEntityModifiers() { + this.mMenuItem.resetEntityModifiers(); + } + @Override public boolean isBlendingEnabled() { return this.mMenuItem.isBlendingEnabled(); @@ -520,43 +576,83 @@ public boolean contains(final float pX, final float pY) { } @Override - public float[] convertLocalToSceneCoordinates(final float pX, final float pY) { - return this.mMenuItem.convertLocalToSceneCoordinates(pX, pY); + public float[] convertLocalCoordinatesToParentCoordinates(final float pX, final float pY) { + return this.mMenuItem.convertLocalCoordinatesToParentCoordinates(pX, pY); + } + + @Override + public float[] convertLocalCoordinatesToParentCoordinates(final float pX, final float pY, final float[] pReuse) { + return this.mMenuItem.convertLocalCoordinatesToParentCoordinates(pX, pY, pReuse); + } + + @Override + public float[] convertLocalCoordinatesToParentCoordinates(final float[] pCoordinates) { + return this.mMenuItem.convertLocalCoordinatesToParentCoordinates(pCoordinates); + } + + @Override + public float[] convertLocalCoordinatesToParentCoordinates(final float[] pCoordinates, final float[] pReuse) { + return this.mMenuItem.convertLocalCoordinatesToParentCoordinates(pCoordinates, pReuse); + } + + @Override + public float[] convertParentCoordinatesToLocalCoordinates(final float pX, final float pY) { + return this.mMenuItem.convertParentCoordinatesToLocalCoordinates(pX, pY); + } + + @Override + public float[] convertParentCoordinatesToLocalCoordinates(final float pX, final float pY, final float[] pReuse) { + return this.mMenuItem.convertParentCoordinatesToLocalCoordinates(pX, pY, pReuse); + } + + @Override + public float[] convertParentCoordinatesToLocalCoordinates(final float[] pCoordinates) { + return this.mMenuItem.convertParentCoordinatesToLocalCoordinates(pCoordinates); + } + + @Override + public float[] convertParentCoordinatesToLocalCoordinates(final float[] pCoordinates, final float[] pReuse) { + return this.mMenuItem.convertParentCoordinatesToLocalCoordinates(pCoordinates, pReuse); + } + + @Override + public float[] convertLocalCoordinatesToSceneCoordinates(final float pX, final float pY) { + return this.mMenuItem.convertLocalCoordinatesToSceneCoordinates(pX, pY); } @Override - public float[] convertLocalToSceneCoordinates(final float pX, final float pY, final float[] pReuse) { - return this.mMenuItem.convertLocalToSceneCoordinates(pX, pY, pReuse); + public float[] convertLocalCoordinatesToSceneCoordinates(final float pX, final float pY, final float[] pReuse) { + return this.mMenuItem.convertLocalCoordinatesToSceneCoordinates(pX, pY, pReuse); } @Override - public float[] convertLocalToSceneCoordinates(final float[] pCoordinates) { - return this.mMenuItem.convertLocalToSceneCoordinates(pCoordinates); + public float[] convertLocalCoordinatesToSceneCoordinates(final float[] pCoordinates) { + return this.mMenuItem.convertLocalCoordinatesToSceneCoordinates(pCoordinates); } @Override - public float[] convertLocalToSceneCoordinates(final float[] pCoordinates, final float[] pReuse) { - return this.mMenuItem.convertLocalToSceneCoordinates(pCoordinates, pReuse); + public float[] convertLocalCoordinatesToSceneCoordinates(final float[] pCoordinates, final float[] pReuse) { + return this.mMenuItem.convertLocalCoordinatesToSceneCoordinates(pCoordinates, pReuse); } @Override - public float[] convertSceneToLocalCoordinates(final float pX, final float pY) { - return this.mMenuItem.convertSceneToLocalCoordinates(pX, pY); + public float[] convertSceneCoordinatesToLocalCoordinates(final float pX, final float pY) { + return this.mMenuItem.convertSceneCoordinatesToLocalCoordinates(pX, pY); } @Override - public float[] convertSceneToLocalCoordinates(final float pX, final float pY, final float[] pReuse) { - return this.mMenuItem.convertSceneToLocalCoordinates(pX, pY, pReuse); + public float[] convertSceneCoordinatesToLocalCoordinates(final float pX, final float pY, final float[] pReuse) { + return this.mMenuItem.convertSceneCoordinatesToLocalCoordinates(pX, pY, pReuse); } @Override - public float[] convertSceneToLocalCoordinates(final float[] pCoordinates) { - return this.mMenuItem.convertSceneToLocalCoordinates(pCoordinates); + public float[] convertSceneCoordinatesToLocalCoordinates(final float[] pCoordinates) { + return this.mMenuItem.convertSceneCoordinatesToLocalCoordinates(pCoordinates); } @Override - public float[] convertSceneToLocalCoordinates(final float[] pCoordinates, final float[] pReuse) { - return this.mMenuItem.convertSceneToLocalCoordinates(pCoordinates, pReuse); + public float[] convertSceneCoordinatesToLocalCoordinates(final float[] pCoordinates, final float[] pReuse) { + return this.mMenuItem.convertSceneCoordinatesToLocalCoordinates(pCoordinates, pReuse); } @Override @@ -589,13 +685,12 @@ public IEntity getChildByTag(final int pTag) { return this.mMenuItem.getChildByTag(pTag); } - @Override public IEntity getChildByIndex(final int pIndex) { return this.mMenuItem.getChildByIndex(pIndex); } @Override - public IEntity getChildByMatcher(IEntityMatcher pEntityMatcher) { + public IEntity getChildByMatcher(final IEntityMatcher pEntityMatcher) { return this.mMenuItem.getChildByMatcher(pEntityMatcher); } @@ -624,6 +719,7 @@ public ArrayList queryForSubclass(final IEntityMatcher pE return this.mMenuItem.queryForSubclass(pEntityMatcher); } + @Override public , S extends IEntity> L queryForSubclass(final IEntityMatcher pEntityMatcher, final L pResult) throws ClassCastException { return this.mMenuItem.queryForSubclass(pEntityMatcher, pResult); } @@ -632,7 +728,7 @@ public , S extends IEntity> L queryForSubclass(final IEntityMa public void sortChildren() { this.mMenuItem.sortChildren(); } - + @Override public void sortChildren(final boolean pImmediate) { this.mMenuItem.sortChildren(pImmediate); @@ -718,6 +814,11 @@ public void setParent(final IEntity pEntity) { this.mMenuItem.setParent(pEntity); } + @Override + public IEntity getRootEntity() { + return this.mMenuItem.getRootEntity(); + } + @Override public boolean isVisible() { return this.mMenuItem.isVisible(); @@ -793,6 +894,11 @@ public boolean unregisterUpdateHandler(final IUpdateHandler pUpdateHandler) { return this.mMenuItem.unregisterUpdateHandler(pUpdateHandler); } + @Override + public int getUpdateHandlerCount() { + return this.mMenuItem.getUpdateHandlerCount(); + } + @Override public void clearUpdateHandlers() { this.mMenuItem.clearUpdateHandlers(); diff --git a/src/org/andengine/entity/scene/menu/item/decorator/ColorMenuItemDecorator.java b/src/org/andengine/entity/scene/menu/item/decorator/ColorMenuItemDecorator.java index 05b0f7fe1..edfa41201 100644 --- a/src/org/andengine/entity/scene/menu/item/decorator/ColorMenuItemDecorator.java +++ b/src/org/andengine/entity/scene/menu/item/decorator/ColorMenuItemDecorator.java @@ -1,12 +1,12 @@ package org.andengine.entity.scene.menu.item.decorator; import org.andengine.entity.scene.menu.item.IMenuItem; -import org.andengine.util.color.Color; +import org.andengine.util.adt.color.Color; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 14:25:35 - 07.07.2010 */ diff --git a/src/org/andengine/entity/scene/menu/item/decorator/ScaleMenuItemDecorator.java b/src/org/andengine/entity/scene/menu/item/decorator/ScaleMenuItemDecorator.java index a41071df6..80031924a 100644 --- a/src/org/andengine/entity/scene/menu/item/decorator/ScaleMenuItemDecorator.java +++ b/src/org/andengine/entity/scene/menu/item/decorator/ScaleMenuItemDecorator.java @@ -3,9 +3,9 @@ import org.andengine.entity.scene.menu.item.IMenuItem; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 15:04:29 - 18.11.2010 */ diff --git a/src/org/andengine/entity/shape/IAreaShape.java b/src/org/andengine/entity/shape/IAreaShape.java deleted file mode 100644 index 429b829cb..000000000 --- a/src/org/andengine/entity/shape/IAreaShape.java +++ /dev/null @@ -1,28 +0,0 @@ -package org.andengine.entity.shape; - - -/** - * (c) Zynga 2011 - * - * @author Nicolas Gramlich - * @since 19:01:16 - 07.08.2011 - */ -public interface IAreaShape extends IShape { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Methods - // =========================================================== - - public float getWidth(); - public float getHeight(); - - public float getWidthScaled(); - public float getHeightScaled(); - - public void setHeight(final float pHeight); - public void setWidth(final float pWidth); - public void setSize(final float pWidth, final float pHeight); -} diff --git a/src/org/andengine/entity/shape/IShape.java b/src/org/andengine/entity/shape/IShape.java index 04692d2e6..008c3be52 100644 --- a/src/org/andengine/entity/shape/IShape.java +++ b/src/org/andengine/entity/shape/IShape.java @@ -1,7 +1,6 @@ package org.andengine.entity.shape; import org.andengine.entity.IEntity; -import org.andengine.entity.scene.ITouchArea; import org.andengine.opengl.shader.ShaderProgram; import org.andengine.opengl.vbo.IVertexBufferObject; import org.andengine.opengl.vbo.VertexBufferObjectManager; @@ -9,13 +8,13 @@ import android.opengl.GLES20; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 13:32:52 - 07.07.2010 */ -public interface IShape extends IEntity, ITouchArea { +public interface IShape extends IEntity { // =========================================================== // Constants // =========================================================== @@ -30,8 +29,6 @@ public interface IShape extends IEntity, ITouchArea { // Methods // =========================================================== - public boolean collidesWith(final IShape pOtherShape); - public boolean isBlendingEnabled(); public void setBlendingEnabled(final boolean pBlendingEnabled); public int getBlendFunctionSource(); diff --git a/src/org/andengine/entity/shape/RectangularShape.java b/src/org/andengine/entity/shape/RectangularShape.java deleted file mode 100644 index b94d40d05..000000000 --- a/src/org/andengine/entity/shape/RectangularShape.java +++ /dev/null @@ -1,150 +0,0 @@ -package org.andengine.entity.shape; - -import org.andengine.engine.camera.Camera; -import org.andengine.entity.primitive.Line; -import org.andengine.opengl.shader.ShaderProgram; -import org.andengine.util.algorithm.collision.RectangularShapeCollisionChecker; - -/** - * (c) 2010 Nicolas Gramlich - * (c) 2011 Zynga Inc. - * - * @author Nicolas Gramlich - * @since 11:37:50 - 04.04.2010 - */ -public abstract class RectangularShape extends Shape implements IAreaShape { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - protected float mWidth; - protected float mHeight; - - // =========================================================== - // Constructors - // =========================================================== - - public RectangularShape(final float pX, final float pY, final float pWidth, final float pHeight, final ShaderProgram pShaderProgram) { - super(pX, pY, pShaderProgram); - - this.mWidth = pWidth; - this.mHeight = pHeight; - - this.resetRotationCenter(); - this.resetScaleCenter(); - this.resetSkewCenter(); - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - @Override - public float getWidth() { - return this.mWidth; - } - - @Override - public float getHeight() { - return this.mHeight; - } - - @Override - public void setWidth(final float pWidth) { - this.mWidth = pWidth; - this.onUpdateVertices(); - } - - @Override - public void setHeight(final float pHeight) { - this.mHeight = pHeight; - this.onUpdateVertices(); - } - - @Override - public void setSize(final float pWidth, final float pHeight) { - this.mWidth = pWidth; - this.mHeight = pHeight; - this.onUpdateVertices(); - } - - @Override - public float getWidthScaled() { - return this.getWidth() * this.mScaleX; - } - - @Override - public float getHeightScaled() { - return this.getHeight() * this.mScaleY; - } - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - public boolean isCulled(final Camera pCamera) { - return !RectangularShapeCollisionChecker.isVisible(pCamera, this); - } - - @Override - public void reset() { - super.reset(); - - this.resetRotationCenter(); - this.resetSkewCenter(); - this.resetScaleCenter(); - } - - @Override - public boolean contains(final float pX, final float pY) { - return RectangularShapeCollisionChecker.checkContains(this, pX, pY); - } - - @Override - public float[] getSceneCenterCoordinates() { - return this.convertLocalToSceneCoordinates(this.mWidth * 0.5f, this.mHeight * 0.5f); - } - - public float[] getSceneCenterCoordinates(final float[] pReuse) { - return this.convertLocalToSceneCoordinates(this.mWidth * 0.5f, this.mHeight * 0.5f, pReuse); - } - - @Override - public boolean collidesWith(final IShape pOtherShape) { - if(pOtherShape instanceof RectangularShape) { - return RectangularShapeCollisionChecker.checkCollision(this, (RectangularShape) pOtherShape); - } else if(pOtherShape instanceof Line) { - return RectangularShapeCollisionChecker.checkCollision(this, (Line) pOtherShape); - } else { - return false; - } - } - - // =========================================================== - // Methods - // =========================================================== - - public void resetRotationCenter() { - this.mRotationCenterX = this.mWidth * 0.5f; - this.mRotationCenterY = this.mHeight * 0.5f; - } - - public void resetScaleCenter() { - this.mScaleCenterX = this.mWidth * 0.5f; - this.mScaleCenterY = this.mHeight * 0.5f; - } - - public void resetSkewCenter() { - this.mSkewCenterX = this.mWidth * 0.5f; - this.mSkewCenterY = this.mHeight * 0.5f; - } - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== -} diff --git a/src/org/andengine/entity/shape/Shape.java b/src/org/andengine/entity/shape/Shape.java index 850491e2a..2bff0c0b3 100644 --- a/src/org/andengine/entity/shape/Shape.java +++ b/src/org/andengine/entity/shape/Shape.java @@ -2,7 +2,6 @@ import org.andengine.engine.camera.Camera; import org.andengine.entity.Entity; -import org.andengine.input.touch.TouchEvent; import org.andengine.opengl.shader.ShaderProgram; import org.andengine.opengl.texture.ITexture; import org.andengine.opengl.texture.TextureOptions; @@ -14,7 +13,7 @@ /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 11:51:27 - 13.03.2010 */ @@ -30,7 +29,7 @@ public abstract class Shape extends Entity implements IShape { protected int mBlendFunctionSource = IShape.BLENDFUNCTION_SOURCE_DEFAULT; protected int mBlendFunctionDestination = IShape.BLENDFUNCTION_DESTINATION_DEFAULT; - protected boolean mBlendingEnabled = false; + protected boolean mBlendingEnabled; protected ShaderProgram mShaderProgram; @@ -44,6 +43,12 @@ public Shape(final float pX, final float pY, final ShaderProgram pShaderProgram) this.mShaderProgram = pShaderProgram; } + public Shape(final float pX, final float pY, final float pWidth, final float pHeight, final ShaderProgram pShaderProgram) { + super(pX, pY, pWidth, pHeight); + + this.mShaderProgram = pShaderProgram; + } + // =========================================================== // Getter & Setter // =========================================================== @@ -107,7 +112,7 @@ public VertexBufferObjectManager getVertexBufferObjectManager() { @Override protected void preDraw(final GLState pGLState, final Camera pCamera) { - if(this.mBlendingEnabled) { + if (this.mBlendingEnabled) { pGLState.enableBlend(); pGLState.blendFunction(this.mBlendFunctionSource, this.mBlendFunctionDestination); } @@ -115,14 +120,30 @@ protected void preDraw(final GLState pGLState, final Camera pCamera) { @Override protected void postDraw(final GLState pGLState, final Camera pCamera) { - if(this.mBlendingEnabled) { + if (this.mBlendingEnabled) { pGLState.disableBlend(); } } @Override - public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final float pTouchAreaLocalX, final float pTouchAreaLocalY) { - return false; + public void setWidth(final float pWidth) { + super.setWidth(pWidth); + + this.onUpdateVertices(); + } + + @Override + public void setHeight(final float pHeight) { + super.setHeight(pHeight); + + this.onUpdateVertices(); + } + + @Override + public void setSize(final float pWidth, final float pHeight) { + super.setSize(pWidth, pHeight); + + this.onUpdateVertices(); } @Override @@ -138,7 +159,7 @@ public void dispose() { super.dispose(); final IVertexBufferObject vertexBufferObject = this.getVertexBufferObject(); - if((vertexBufferObject != null) && vertexBufferObject.isAutoDispose() && !vertexBufferObject.isDisposed()) { + if ((vertexBufferObject != null) && vertexBufferObject.isAutoDispose() && !vertexBufferObject.isDisposed()) { vertexBufferObject.dispose(); } } @@ -156,7 +177,7 @@ protected void initBlendFunction(final ITexture pTexture) { } protected void initBlendFunction(final TextureOptions pTextureOptions) { - if(pTextureOptions.mPreMultiplyAlpha) { + if (pTextureOptions.mPreMultiplyAlpha) { this.setBlendFunction(IShape.BLENDFUNCTION_SOURCE_PREMULTIPLYALPHA_DEFAULT, IShape.BLENDFUNCTION_DESTINATION_PREMULTIPLYALPHA_DEFAULT); } } diff --git a/src/org/andengine/entity/sprite/AnimatedSprite.java b/src/org/andengine/entity/sprite/AnimatedSprite.java index a35c8f668..40fb4bb40 100644 --- a/src/org/andengine/entity/sprite/AnimatedSprite.java +++ b/src/org/andengine/entity/sprite/AnimatedSprite.java @@ -11,7 +11,7 @@ /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 15:25:46 - 10.03.2010 */ @@ -105,20 +105,20 @@ public boolean isAnimationRunning() { protected void onManagedUpdate(final float pSecondsElapsed) { super.onManagedUpdate(pSecondsElapsed); - if(this.mAnimationRunning) { + if (this.mAnimationRunning) { final int loopCount = this.mAnimationData.getLoopCount(); final int[] frames = this.mAnimationData.getFrames(); final long animationDuration = this.mAnimationData.getAnimationDuration(); - if(!this.mAnimationStartedFired && (this.mAnimationProgress == 0)) { + if (!this.mAnimationStartedFired && (this.mAnimationProgress == 0)) { this.mAnimationStartedFired = true; - if(frames == null) { + if (frames == null) { this.setCurrentTileIndex(this.mAnimationData.getFirstFrameIndex()); } else { this.setCurrentTileIndex(frames[0]); } this.mCurrentFrameIndex = 0; - if(this.mAnimationListener != null) { + if (this.mAnimationListener != null) { this.mAnimationListener.onAnimationStarted(this, loopCount); this.mAnimationListener.onAnimationFrameChanged(this, AnimatedSprite.FRAMEINDEX_INVALID, 0); } @@ -126,42 +126,42 @@ protected void onManagedUpdate(final float pSecondsElapsed) { final long nanoSecondsElapsed = (long) (pSecondsElapsed * TimeConstants.NANOSECONDS_PER_SECOND); this.mAnimationProgress += nanoSecondsElapsed; - if(loopCount == IAnimationData.LOOP_CONTINUOUS) { - while(this.mAnimationProgress > animationDuration ) { + if (loopCount == IAnimationData.LOOP_CONTINUOUS) { + while (this.mAnimationProgress > animationDuration) { this.mAnimationProgress -= animationDuration; - if(this.mAnimationListener != null) { + if (this.mAnimationListener != null) { this.mAnimationListener.onAnimationLoopFinished(this, this.mRemainingLoopCount, loopCount); } } } else { - while(this.mAnimationProgress > animationDuration) { + while (this.mAnimationProgress > animationDuration) { this.mAnimationProgress -= animationDuration; this.mRemainingLoopCount--; - if(this.mRemainingLoopCount < 0) { + if (this.mRemainingLoopCount < 0) { break; - } else if(this.mAnimationListener != null) { + } else if (this.mAnimationListener != null) { this.mAnimationListener.onAnimationLoopFinished(this, this.mRemainingLoopCount, loopCount); } } } - if((loopCount == IAnimationData.LOOP_CONTINUOUS) || (this.mRemainingLoopCount >= 0)) { + if ((loopCount == IAnimationData.LOOP_CONTINUOUS) || (this.mRemainingLoopCount >= 0)) { final int newFrameIndex = this.mAnimationData.calculateCurrentFrameIndex(this.mAnimationProgress); - if(this.mCurrentFrameIndex != newFrameIndex) { - if(frames == null) { + if (this.mCurrentFrameIndex != newFrameIndex) { + if (frames == null) { this.setCurrentTileIndex(this.mAnimationData.getFirstFrameIndex() + newFrameIndex); } else { this.setCurrentTileIndex(frames[newFrameIndex]); } - if(this.mAnimationListener != null) { + if (this.mAnimationListener != null) { this.mAnimationListener.onAnimationFrameChanged(this, this.mCurrentFrameIndex, newFrameIndex); } } this.mCurrentFrameIndex = newFrameIndex; } else { this.mAnimationRunning = false; - if(this.mAnimationListener != null) { + if (this.mAnimationListener != null) { this.mAnimationListener.onAnimationFinished(this); } } @@ -212,7 +212,7 @@ public void animate(final long pFrameDurationEach, final int pLoopCount, final I } public void animate(final long[] pFrameDurations) { - this.animate(pFrameDurations, (IAnimationListener)null); + this.animate(pFrameDurations, (IAnimationListener) null); } public void animate(final long[] pFrameDurations, final IAnimationListener pAnimationListener) { @@ -263,7 +263,7 @@ public void animate(final long[] pFrameDurations, final int pFirstTileIndex, fin /** * Animate specifics frames. - * + * * @param pFrameDurations must have the same length as pFrames. * @param pFrames indices of the frames to animate. */ @@ -273,7 +273,7 @@ public void animate(final long[] pFrameDurations, final int[] pFrames) { /** * Animate specifics frames. - * + * * @param pFrameDurations must have the same length as pFrames. * @param pFrames indices of the frames to animate. * @param pAnimationListener @@ -286,7 +286,7 @@ public void animate(final long[] pFrameDurations, final int[] pFrames, final IAn /** * Animate specifics frames. - * + * * @param pFrameDurations must have the same length as pFrames. * @param pFrames indices of the frames to animate. * @param pLoop @@ -297,7 +297,7 @@ public void animate(final long[] pFrameDurations, final int[] pFrames, final boo /** * Animate specifics frames. - * + * * @param pFrameDurations must have the same length as pFrames. * @param pFrames indices of the frames to animate. * @param pLoop @@ -311,7 +311,7 @@ public void animate(final long[] pFrameDurations, final int[] pFrames, final boo /** * Animate specifics frames. - * + * * @param pFrameDurations must have the same length as pFrames. * @param pFrames indices of the frames to animate. * @param pLoopCount @@ -322,7 +322,7 @@ public void animate(final long[] pFrameDurations, final int[] pFrames, final int /** * Animate specifics frames. - * + * * @param pFrameDurations must have the same length as pFrames. * @param pFrames indices of the frames to animate. * @param pLoopCount diff --git a/src/org/andengine/entity/sprite/AnimationData.java b/src/org/andengine/entity/sprite/AnimationData.java index 32d5a7f70..0c9ab47c9 100644 --- a/src/org/andengine/entity/sprite/AnimationData.java +++ b/src/org/andengine/entity/sprite/AnimationData.java @@ -2,12 +2,12 @@ import java.util.Arrays; -import org.andengine.util.math.MathUtils; +import org.andengine.util.adt.array.ArrayUtils; import org.andengine.util.modifier.IModifier.DeepCopyNotSupportedException; import org.andengine.util.time.TimeConstants; /** - * (c) Zynga 2012 + * (c) 2012 Zynga Inc. * * @author Nicolas Gramlich * @since 11:43:01 - 04.05.2012 @@ -70,7 +70,7 @@ public AnimationData(final long[] pFrameDurations, final int pFirstFrameIndex, f /** * Animate specifics frames. - * + * * @param pFrameDurations must have the same length as pFrames. * @param pFrames indices of the frames to animate. * @param pLoopCount @@ -102,6 +102,10 @@ public IAnimationData deepCopy() throws DeepCopyNotSupportedException { // Getter & Setter // =========================================================== + public void setLoopCount(final int pLoopCount) { + this.mLoopCount = pLoopCount; + } + // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @@ -144,8 +148,8 @@ public long getAnimationDuration() { public int calculateCurrentFrameIndex(final long pAnimationProgress) { final long[] frameEnds = this.mFrameEndsInNanoseconds; final int frameCount = this.mFrameCount; - for(int i = 0; i < frameCount; i++) { - if(frameEnds[i] > pAnimationProgress) { + for (int i = 0; i < frameCount; i++) { + if (frameEnds[i] > pAnimationProgress) { return i; } } @@ -203,14 +207,14 @@ public void set(final long[] pFrameDurations, final int pFirstFrameIndex, final public void set(final long[] pFrameDurations, final int pFirstFrameIndex, final int pLastFrameIndex, final int pLoopCount) { this.set(pFrameDurations, (pLastFrameIndex - pFirstFrameIndex) + 1, null, pFirstFrameIndex, pLoopCount); - if((pFirstFrameIndex + 1) > pLastFrameIndex) { + if ((pFirstFrameIndex + 1) > pLastFrameIndex) { throw new IllegalArgumentException("An animation needs at least two tiles to animate between."); } } /** * Animate specifics frames. - * + * * @param pFrameDurations must have the same length as pFrames. * @param pFrames indices of the frames to animate. */ @@ -221,7 +225,7 @@ public void set(final long[] pFrameDurations, final int[] pFrames) { /** * Animate specifics frames. - * + * * @param pFrameDurations must have the same length as pFrames. * @param pFrames indices of the frames to animate. * @param pLoop @@ -233,7 +237,7 @@ public void set(final long[] pFrameDurations, final int[] pFrames, final boolean /** * Animate specifics frames. - * + * * @param pFrameDurations must have the same length as pFrames. * @param pFrames indices of the frames to animate. * @param pLoopCount @@ -249,7 +253,7 @@ public void set(final IAnimationData pAnimationData) { } private void set(final long[] pFrameDurations, final int pFrameCount, final int[] pFrames, final int pFirstFrameIndex, final int pLoopCount) { - if(pFrameDurations.length != pFrameCount) { + if (pFrameDurations.length != pFrameCount) { throw new IllegalArgumentException("pFrameDurations does not equal pFrameCount!"); } @@ -259,12 +263,12 @@ private void set(final long[] pFrameDurations, final int pFrameCount, final int[ this.mFirstFrameIndex = pFirstFrameIndex; this.mLoopCount = pLoopCount; - if((this.mFrameEndsInNanoseconds == null) || (this.mFrameCount > this.mFrameEndsInNanoseconds.length)) { + if ((this.mFrameEndsInNanoseconds == null) || (this.mFrameCount > this.mFrameEndsInNanoseconds.length)) { this.mFrameEndsInNanoseconds = new long[this.mFrameCount]; } final long[] frameEndsInNanoseconds = this.mFrameEndsInNanoseconds; - MathUtils.arraySumInto(this.mFrameDurations, frameEndsInNanoseconds, TimeConstants.NANOSECONDS_PER_MILLISECOND); + ArrayUtils.sumCummulative(this.mFrameDurations, TimeConstants.NANOSECONDS_PER_MILLISECOND, frameEndsInNanoseconds); final long lastFrameEnd = frameEndsInNanoseconds[this.mFrameCount - 1]; this.mAnimationDuration = lastFrameEnd; @@ -274,6 +278,17 @@ private void set(final long[] pFrameDurations, final int pFrameCount, final int[ // Methods // =========================================================== + /** + * Scales the duration of this {@link AnimationData} by a given pFactor. + * + * @param pScale + */ + public void scale(final float pScale) { + ArrayUtils.multiply(this.mFrameDurations, pScale); + ArrayUtils.multiply(this.mFrameEndsInNanoseconds, pScale); + this.mAnimationDuration *= pScale; + } + private static long[] fillFrameDurations(final long pFrameDurationEach, final int pFrameCount) { final long[] frameDurations = new long[pFrameCount]; Arrays.fill(frameDurations, pFrameDurationEach); diff --git a/src/org/andengine/entity/sprite/ButtonSprite.java b/src/org/andengine/entity/sprite/ButtonSprite.java index a97484d9b..fc6fbb9fd 100644 --- a/src/org/andengine/entity/sprite/ButtonSprite.java +++ b/src/org/andengine/entity/sprite/ButtonSprite.java @@ -13,7 +13,7 @@ * Note: {@link ButtonSprite} needs to be registered as a {@link ITouchArea} to the {@link Scene} via {@link Scene#registerTouchArea(ITouchArea)}, otherwise it won't be clickable. * To make {@link ButtonSprite} function properly, you should consider setting {@link Scene#setTouchAreaBindingOnActionDownEnabled(boolean)} to true. * - * (c) Zynga 2012 + * (c) 2012 Zynga Inc. * * @author Scott Kennedy * @author Nicolas Gramlich @@ -72,7 +72,7 @@ public ButtonSprite(final float pX, final float pY, final ITiledTextureRegion pT this.mOnClickListener = pOnClickListener; this.mStateCount = pTiledTextureRegion.getTileCount(); - switch(this.mStateCount) { + switch (this.mStateCount) { case 1: Debug.w("No " + ITextureRegion.class.getSimpleName() + " supplied for " + State.class.getSimpleName() + "." + State.PRESSED + "."); case 2: @@ -98,9 +98,9 @@ public boolean isEnabled() { public void setEnabled(final boolean pEnabled) { this.mEnabled = pEnabled; - if(this.mEnabled && this.mState == State.DISABLED) { + if (this.mEnabled && this.mState == State.DISABLED) { this.changeState(State.NORMAL); - } else if(!this.mEnabled) { + } else if (!this.mEnabled) { this.changeState(State.DISABLED); } } @@ -123,16 +123,16 @@ public void setOnClickListener(final OnClickListener pOnClickListener) { @Override public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final float pTouchAreaLocalX, final float pTouchAreaLocalY) { - if(!this.isEnabled()) { + if (!this.isEnabled()) { this.changeState(State.DISABLED); - } else if(pSceneTouchEvent.isActionDown()) { + } else if (pSceneTouchEvent.isActionDown()) { this.changeState(State.PRESSED); - } else if(pSceneTouchEvent.isActionCancel() || !this.contains(pSceneTouchEvent.getX(), pSceneTouchEvent.getY())) { + } else if (pSceneTouchEvent.isActionCancel() || !this.contains(pSceneTouchEvent.getX(), pSceneTouchEvent.getY())) { this.changeState(State.NORMAL); - } else if(pSceneTouchEvent.isActionUp() && this.mState == State.PRESSED) { + } else if (pSceneTouchEvent.isActionUp() && this.mState == State.PRESSED) { this.changeState(State.NORMAL); - if(this.mOnClickListener != null) { + if (this.mOnClickListener != null) { this.mOnClickListener.onClick(this, pTouchAreaLocalX, pTouchAreaLocalY); } } @@ -142,7 +142,7 @@ public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final float pTou @Override public boolean contains(final float pX, final float pY) { - if(!this.isVisible()) { + if (!this.isVisible()) { return false; } else { return super.contains(pX, pY); @@ -154,14 +154,14 @@ public boolean contains(final float pX, final float pY) { // =========================================================== private void changeState(final State pState) { - if(pState == this.mState) { + if (pState == this.mState) { return; } this.mState = pState; final int stateTiledTextureRegionIndex = this.mState.getTiledTextureRegionIndex(); - if(stateTiledTextureRegionIndex >= this.mStateCount) { + if (stateTiledTextureRegionIndex >= this.mStateCount) { this.setCurrentTileIndex(0); Debug.w(this.getClass().getSimpleName() + " changed its " + State.class.getSimpleName() + " to " + pState.toString() + ", which doesn't have a " + ITextureRegion.class.getSimpleName() + " supplied. Applying default " + ITextureRegion.class.getSimpleName() + "."); } else { diff --git a/src/org/andengine/entity/sprite/DiamondSprite.java b/src/org/andengine/entity/sprite/DiamondSprite.java index 2047c516f..2d6eaaa1b 100644 --- a/src/org/andengine/entity/sprite/DiamondSprite.java +++ b/src/org/andengine/entity/sprite/DiamondSprite.java @@ -22,7 +22,7 @@ * +--------+ * * - * (c) Zynga 2011 + * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 20:26:32 - 24.10.2011 diff --git a/src/org/andengine/entity/sprite/IAnimationData.java b/src/org/andengine/entity/sprite/IAnimationData.java index e2c77a6f1..952a4f685 100644 --- a/src/org/andengine/entity/sprite/IAnimationData.java +++ b/src/org/andengine/entity/sprite/IAnimationData.java @@ -3,7 +3,7 @@ import org.andengine.util.modifier.IModifier.DeepCopyNotSupportedException; /** - * (c) Zynga 2012 + * (c) 2012 Zynga Inc. * * @author Nicolas Gramlich * @since 16:59:57 - 03.05.2012 @@ -18,7 +18,7 @@ public interface IAnimationData { // =========================================================== // Methods // =========================================================== - + public int[] getFrames(); public long[] getFrameDurations(); public int getLoopCount(); @@ -51,14 +51,14 @@ public interface IAnimationData { /** * Animate specifics frames. - * + * * @param pFrameDurations must have the same length as pFrames. * @param pFrames indices of the frames to animate. */ public void set(final long[] pFrameDurations, final int[] pFrames); /** * Animate specifics frames. - * + * * @param pFrameDurations must have the same length as pFrames. * @param pFrames indices of the frames to animate. * @param pLoop @@ -66,7 +66,7 @@ public interface IAnimationData { public void set(final long[] pFrameDurations, final int[] pFrames, final boolean pLoop); /** * Animate specifics frames. - * + * * @param pFrameDurations must have the same length as pFrames. * @param pFrames indices of the frames to animate. * @param pLoopCount diff --git a/src/org/andengine/entity/sprite/NineSliceSprite.java b/src/org/andengine/entity/sprite/NineSliceSprite.java new file mode 100644 index 000000000..a6ac414ef --- /dev/null +++ b/src/org/andengine/entity/sprite/NineSliceSprite.java @@ -0,0 +1,261 @@ +package org.andengine.entity.sprite; + +import org.andengine.entity.Entity; +import org.andengine.entity.sprite.batch.SpriteBatch; +import org.andengine.opengl.shader.PositionColorTextureCoordinatesShaderProgram; +import org.andengine.opengl.shader.ShaderProgram; +import org.andengine.opengl.texture.ITexture; +import org.andengine.opengl.texture.region.ITextureRegion; +import org.andengine.opengl.texture.region.TextureRegion; +import org.andengine.opengl.vbo.VertexBufferObjectManager; + +/** + * (c) 2012 Zynga Inc. + * + * @author Nicolas Gramlich + * @since 16:50:42 - 25.04.2012 + */ +public class NineSliceSprite extends Entity { + // =========================================================== + // Constants + // =========================================================== + + private static final int NINESLICESPRITE_CHILD_COUNT = 9; + + // =========================================================== + // Fields + // =========================================================== + + protected final ITextureRegion mTextureRegion; + + protected final ITextureRegion mTopLeftTextureRegion; + protected final ITextureRegion mTopCenterTextureRegion; + protected final ITextureRegion mTopRightTextureRegion; + protected final ITextureRegion mCenterLeftTextureRegion; + protected final ITextureRegion mCenterTextureRegion; + protected final ITextureRegion mCenterRightTextureRegion; + protected final ITextureRegion mBottomLeftTextureRegion; + protected final ITextureRegion mBottomCenterTextureRegion; + protected final ITextureRegion mBottomRightTextureRegion; + + protected final SpriteBatch mSpriteBatch; + + protected float mInsetLeft; + protected float mInsetTop; + protected float mInsetRight; + protected float mInsetBottom; + + // =========================================================== + // Constructors + // =========================================================== + + public NineSliceSprite(final float pX, final float pY, final ITextureRegion pTextureRegion, final float pInsetLeft, final float pInsetTop, final float pInsetRight, final float pInsetBottom, final VertexBufferObjectManager pVertexBufferObjectManager) { + this(pX, pY, pTextureRegion, pInsetLeft, pInsetTop, pInsetRight, pInsetBottom, pVertexBufferObjectManager, PositionColorTextureCoordinatesShaderProgram.getInstance()); + } + + public NineSliceSprite(final float pX, final float pY, final ITextureRegion pTextureRegion, final float pInsetLeft, final float pInsetTop, final float pInsetRight, final float pInsetBottom, final VertexBufferObjectManager pVertexBufferObjectManager, final ShaderProgram pShaderProgram) { + this(pX, pY, pTextureRegion.getWidth(), pTextureRegion.getHeight(), pTextureRegion, pInsetLeft, pInsetTop, pInsetRight, pInsetBottom, pVertexBufferObjectManager, pShaderProgram); + } + + public NineSliceSprite(final float pX, final float pY, final float pWidth, final float pHeight, final ITextureRegion pTextureRegion, final float pInsetLeft, final float pInsetTop, final float pInsetRight, final float pInsetBottom, final VertexBufferObjectManager pVertexBufferObjectManager) { + this(pX, pY, pWidth, pHeight, pTextureRegion, pInsetLeft, pInsetTop, pInsetRight, pInsetBottom, pVertexBufferObjectManager, PositionColorTextureCoordinatesShaderProgram.getInstance()); + } + + public NineSliceSprite(final float pX, final float pY, final float pWidth, final float pHeight, final ITextureRegion pTextureRegion, final float pInsetLeft, final float pInsetTop, final float pInsetRight, final float pInsetBottom, final VertexBufferObjectManager pVertexBufferObjectManager, final ShaderProgram pShaderProgram) { + super(pX, pY, pWidth, pHeight); + + this.mTextureRegion = pTextureRegion; + this.mInsetLeft = pInsetLeft; + this.mInsetTop = pInsetTop; + this.mInsetRight = pInsetRight; + this.mInsetBottom = pInsetBottom; + + final ITexture texture = pTextureRegion.getTexture(); + this.mSpriteBatch = new SpriteBatch(texture, NINESLICESPRITE_CHILD_COUNT, pVertexBufferObjectManager, pShaderProgram); + + this.mTopLeftTextureRegion = new TextureRegion(texture, 0, 0, 0, 0); + this.mTopCenterTextureRegion = new TextureRegion(texture, 0, 0, 0, 0); + this.mTopRightTextureRegion = new TextureRegion(texture, 0, 0, 0, 0); + this.mCenterLeftTextureRegion = new TextureRegion(texture, 0, 0, 0, 0); + this.mCenterTextureRegion = new TextureRegion(texture, 0, 0, 0, 0); + this.mCenterRightTextureRegion = new TextureRegion(texture, 0, 0, 0, 0); + this.mBottomLeftTextureRegion = new TextureRegion(texture, 0, 0, 0, 0); + this.mBottomCenterTextureRegion = new TextureRegion(texture, 0, 0, 0, 0); + this.mBottomRightTextureRegion = new TextureRegion(texture, 0, 0, 0, 0); + + this.updateTextureRegions(); + this.updateVertices(); + + this.attachChild(this.mSpriteBatch); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + public float getInsetLeft() { + return this.mInsetLeft; + } + + public void setInsetLeft(final float pInsetLeft) { + this.mInsetLeft = pInsetLeft; + + this.updateTextureRegions(); + this.updateVertices(); + } + + public float getInsetTop() { + return this.mInsetTop; + } + + public void setInsetTop(final float pInsetTop) { + this.mInsetTop = pInsetTop; + + this.updateTextureRegions(); + this.updateVertices(); + } + + public float getInsetRight() { + return this.mInsetRight; + } + + public void setInsetRight(final float pInsetRight) { + this.mInsetRight = pInsetRight; + + this.updateTextureRegions(); + this.updateVertices(); + } + + public float getInsetBottom() { + return this.mInsetBottom; + } + + public void setInsetBottom(final float pInsetBottom) { + this.mInsetBottom = pInsetBottom; + + this.updateTextureRegions(); + this.updateVertices(); + } + + public void setInsets(final float pInsetLeft, final float pInsetTop, final float pInsetRight, final float pInsetBottom) { + this.mInsetLeft = pInsetLeft; + this.mInsetTop = pInsetTop; + this.mInsetRight = pInsetRight; + this.mInsetBottom = pInsetBottom; + + this.updateTextureRegions(); + this.updateVertices(); + } + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + public void setWidth(final float pWidth) { + super.setWidth(pWidth); + + this.updateVertices(); + } + + @Override + public void setHeight(final float pHeight) { + super.setHeight(pHeight); + + this.updateVertices(); + } + + @Override + public void setSize(final float pWidth, final float pHeight) { + super.setSize(pWidth, pHeight); + + this.updateVertices(); + } + + @Override + protected void onUpdateColor() { + this.updateVertices(); + } + + @Override + public void dispose() { + super.dispose(); + + this.mSpriteBatch.dispose(); + } + + // =========================================================== + // Methods + // =========================================================== + + private void updateTextureRegions() { + final float baseX = this.mTextureRegion.getTextureX(); + final float baseY = this.mTextureRegion.getTextureY(); + final float baseWidth = this.mTextureRegion.getWidth(); + final float baseHeight = this.mTextureRegion.getHeight(); + + final float centerWidth = baseWidth - this.mInsetLeft - this.mInsetRight; + final float centerHeight = baseHeight - this.mInsetTop - this.mInsetBottom; + + /* Cache some variables. */ + final float leftX = baseX; + final float centerX = baseX + this.mInsetLeft; + final float rightX = (baseX + baseWidth) - this.mInsetRight; + + /* Top. */ + final float topY = baseY; + this.mTopLeftTextureRegion.set(leftX, topY, this.mInsetLeft, this.mInsetTop); + this.mTopCenterTextureRegion.set(centerX, topY, centerWidth, this.mInsetTop); + this.mTopRightTextureRegion.set(rightX, topY, this.mInsetRight, this.mInsetTop); + + /* Center. */ + final float centerY = baseY + this.mInsetTop; + this.mCenterLeftTextureRegion.set(leftX, centerY, this.mInsetLeft, centerHeight); + this.mCenterTextureRegion.set(centerX, centerY, centerWidth, centerHeight); + this.mCenterRightTextureRegion.set(rightX, centerY, this.mInsetRight, centerHeight); + + /* Bottom. */ + final float bottomY = (baseY + baseHeight) - this.mInsetBottom; + this.mBottomLeftTextureRegion.set(leftX, bottomY, this.mInsetLeft, this.mInsetBottom); + this.mBottomCenterTextureRegion.set(centerX, bottomY, centerWidth, this.mInsetBottom); + this.mBottomRightTextureRegion.set(rightX, bottomY, this.mInsetRight, this.mInsetBottom); + } + + private void updateVertices() { + this.mSpriteBatch.reset(); + + final float color = this.mColor.getABGRPackedFloat(); + + final float centerWidth = this.mWidth - this.mInsetLeft - this.mInsetRight; + final float centerHeight = this.mHeight - this.mInsetTop - this.mInsetBottom; + + /* Cache some variables. */ + final float leftX = 0; + final float centerX = this.mInsetLeft; + final float rightX = this.mWidth - this.mInsetRight; + + /* Top. */ + final float topY = this.mHeight - this.mInsetTop; + this.mSpriteBatch.draw(this.mTopLeftTextureRegion, leftX, topY, this.mInsetLeft, this.mInsetTop, color); + this.mSpriteBatch.draw(this.mTopCenterTextureRegion, centerX, topY, centerWidth, this.mInsetTop, color); + this.mSpriteBatch.draw(this.mTopRightTextureRegion, rightX, topY, this.mInsetRight, this.mInsetTop, color); + + /* Center. */ + final float centerY = this.mInsetBottom; + this.mSpriteBatch.draw(this.mCenterLeftTextureRegion, leftX, centerY, this.mInsetLeft, centerHeight, color); + this.mSpriteBatch.draw(this.mCenterTextureRegion, centerX, centerY, centerWidth, centerHeight, color); + this.mSpriteBatch.draw(this.mCenterRightTextureRegion, rightX, centerY, this.mInsetRight, centerHeight, color); + + /* Bottom. */ + final float bottomY = 0; + this.mSpriteBatch.draw(this.mBottomLeftTextureRegion, leftX, bottomY, this.mInsetLeft, this.mInsetBottom, color); + this.mSpriteBatch.draw(this.mBottomCenterTextureRegion, centerX, bottomY, centerWidth, this.mInsetBottom, color); + this.mSpriteBatch.draw(this.mBottomRightTextureRegion, rightX, bottomY, this.mInsetRight, this.mInsetBottom, color); + + this.mSpriteBatch.submit(); + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== +} diff --git a/src/org/andengine/entity/sprite/Sprite.java b/src/org/andengine/entity/sprite/Sprite.java index 12c7fa25e..c4bb4135a 100644 --- a/src/org/andengine/entity/sprite/Sprite.java +++ b/src/org/andengine/entity/sprite/Sprite.java @@ -1,7 +1,7 @@ package org.andengine.entity.sprite; import org.andengine.engine.camera.Camera; -import org.andengine.entity.shape.RectangularShape; +import org.andengine.entity.shape.Shape; import org.andengine.entity.sprite.vbo.HighPerformanceSpriteVertexBufferObject; import org.andengine.entity.sprite.vbo.ISpriteVertexBufferObject; import org.andengine.opengl.shader.PositionColorTextureCoordinatesShaderProgram; @@ -19,11 +19,11 @@ /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 19:22:38 - 09.03.2010 */ -public class Sprite extends RectangularShape { +public class Sprite extends Shape { // =========================================================== // Constants // =========================================================== @@ -103,15 +103,16 @@ public Sprite(final float pX, final float pY, final float pWidth, final float pH } public Sprite(final float pX, final float pY, final float pWidth, final float pHeight, final ITextureRegion pTextureRegion, final ISpriteVertexBufferObject pSpriteVertexBufferObject, final ShaderProgram pShaderProgram) { - super(pX, pY, pWidth, pHeight, pShaderProgram); - + super(pX, pY, pShaderProgram); + this.mTextureRegion = pTextureRegion; this.mSpriteVertexBufferObject = pSpriteVertexBufferObject; this.setBlendingEnabled(true); this.initBlendFunction(pTextureRegion); - - this.onUpdateVertices(); + + this.setSize(pWidth, pHeight); + this.onUpdateColor(); this.onUpdateTextureCoordinates(); } @@ -129,7 +130,7 @@ public boolean isFlippedHorizontal() { } public void setFlippedHorizontal(final boolean pFlippedHorizontal) { - if(this.mFlippedHorizontal != pFlippedHorizontal) { + if (this.mFlippedHorizontal != pFlippedHorizontal) { this.mFlippedHorizontal = pFlippedHorizontal; this.onUpdateTextureCoordinates(); @@ -141,7 +142,7 @@ public boolean isFlippedVertical() { } public void setFlippedVertical(final boolean pFlippedVertical) { - if(this.mFlippedVertical != pFlippedVertical) { + if (this.mFlippedVertical != pFlippedVertical) { this.mFlippedVertical = pFlippedVertical; this.onUpdateTextureCoordinates(); @@ -149,7 +150,7 @@ public void setFlippedVertical(final boolean pFlippedVertical) { } public void setFlipped(final boolean pFlippedHorizontal, final boolean pFlippedVertical) { - if((this.mFlippedHorizontal != pFlippedHorizontal) || (this.mFlippedVertical != pFlippedVertical)) { + if ((this.mFlippedHorizontal != pFlippedHorizontal) || (this.mFlippedVertical != pFlippedVertical)) { this.mFlippedHorizontal = pFlippedHorizontal; this.mFlippedVertical = pFlippedVertical; diff --git a/src/org/andengine/entity/sprite/TiledSprite.java b/src/org/andengine/entity/sprite/TiledSprite.java index 5290fd710..0bf979d8d 100644 --- a/src/org/andengine/entity/sprite/TiledSprite.java +++ b/src/org/andengine/entity/sprite/TiledSprite.java @@ -16,7 +16,7 @@ /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 19:30:13 - 09.03.2010 */ diff --git a/src/org/andengine/entity/sprite/UncoloredSprite.java b/src/org/andengine/entity/sprite/UncoloredSprite.java index 5f97a4fee..915f3629c 100644 --- a/src/org/andengine/entity/sprite/UncoloredSprite.java +++ b/src/org/andengine/entity/sprite/UncoloredSprite.java @@ -16,7 +16,7 @@ /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 19:22:38 - 09.03.2010 */ diff --git a/src/org/andengine/entity/sprite/UniformColorSprite.java b/src/org/andengine/entity/sprite/UniformColorSprite.java index a37e4013c..0135749a0 100644 --- a/src/org/andengine/entity/sprite/UniformColorSprite.java +++ b/src/org/andengine/entity/sprite/UniformColorSprite.java @@ -18,7 +18,7 @@ /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 19:22:38 - 09.03.2010 */ @@ -60,7 +60,7 @@ public UniformColorSprite(final float pX, final float pY, final ITextureRegion p public UniformColorSprite(final float pX, final float pY, final ITextureRegion pTextureRegion, final VertexBufferObjectManager pVertexBufferObjectManager, final DrawType pDrawType) { this(pX, pY, pTextureRegion.getWidth(), pTextureRegion.getHeight(), pTextureRegion, pVertexBufferObjectManager, pDrawType); } - + public UniformColorSprite(final float pX, final float pY, final ITextureRegion pTextureRegion, final VertexBufferObjectManager pVertexBufferObjectManager, final DrawType pDrawType, final ShaderProgram pShaderProgram) { this(pX, pY, pTextureRegion.getWidth(), pTextureRegion.getHeight(), pTextureRegion, pVertexBufferObjectManager, pDrawType, pShaderProgram); } @@ -68,7 +68,7 @@ public UniformColorSprite(final float pX, final float pY, final ITextureRegion p public UniformColorSprite(final float pX, final float pY, final ITextureRegion pTextureRegion, final IUniformColorSpriteVertexBufferObject pVertexBufferObject) { this(pX, pY, pTextureRegion.getWidth(), pTextureRegion.getHeight(), pTextureRegion, pVertexBufferObject); } - + public UniformColorSprite(final float pX, final float pY, final ITextureRegion pTextureRegion, final IUniformColorSpriteVertexBufferObject pVertexBufferObject, final ShaderProgram pShaderProgram) { this(pX, pY, pTextureRegion.getWidth(), pTextureRegion.getHeight(), pTextureRegion, pVertexBufferObject, pShaderProgram); } @@ -76,7 +76,7 @@ public UniformColorSprite(final float pX, final float pY, final ITextureRegion p public UniformColorSprite(final float pX, final float pY, final float pWidth, final float pHeight, final ITextureRegion pTextureRegion, final VertexBufferObjectManager pVertexBufferObjectManager) { this(pX, pY, pWidth, pHeight, pTextureRegion, pVertexBufferObjectManager, DrawType.STATIC); } - + public UniformColorSprite(final float pX, final float pY, final float pWidth, final float pHeight, final ITextureRegion pTextureRegion, final VertexBufferObjectManager pVertexBufferObjectManager, final ShaderProgram pShaderProgram) { this(pX, pY, pWidth, pHeight, pTextureRegion, pVertexBufferObjectManager, DrawType.STATIC, pShaderProgram); } @@ -105,6 +105,11 @@ public UniformColorSprite(final float pX, final float pY, final float pWidth, fi // Methods for/from SuperClass/Interfaces // =========================================================== + @Override + protected void onUpdateColor() { + /* Nothing. */ + } + @Override protected void preDraw(final GLState pGLState, final Camera pCamera) { super.preDraw(pGLState, pCamera); diff --git a/src/org/andengine/entity/sprite/batch/DynamicSpriteBatch.java b/src/org/andengine/entity/sprite/batch/DynamicSpriteBatch.java index 75a8720eb..a0ccf03fd 100644 --- a/src/org/andengine/entity/sprite/batch/DynamicSpriteBatch.java +++ b/src/org/andengine/entity/sprite/batch/DynamicSpriteBatch.java @@ -7,7 +7,7 @@ import org.andengine.opengl.vbo.VertexBufferObjectManager; /** - * (c) Zynga 2011 + * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 21:48:21 - 27.07.2011 @@ -90,7 +90,7 @@ public DynamicSpriteBatch(final float pX, final float pY, final ITexture pTextur protected void begin() { super.begin(); - if(this.onUpdateSpriteBatch()) { + if (this.onUpdateSpriteBatch()) { this.submit(); } } diff --git a/src/org/andengine/entity/sprite/batch/SpriteBatch.java b/src/org/andengine/entity/sprite/batch/SpriteBatch.java index efff62b7a..e5b2e93d8 100644 --- a/src/org/andengine/entity/sprite/batch/SpriteBatch.java +++ b/src/org/andengine/entity/sprite/batch/SpriteBatch.java @@ -1,7 +1,7 @@ package org.andengine.entity.sprite.batch; import org.andengine.engine.camera.Camera; -import org.andengine.entity.shape.IShape; +import org.andengine.entity.IEntity; import org.andengine.entity.shape.Shape; import org.andengine.entity.sprite.Sprite; import org.andengine.entity.sprite.batch.vbo.HighPerformanceSpriteBatchVertexBufferObject; @@ -16,18 +16,18 @@ import org.andengine.opengl.vbo.VertexBufferObjectManager; import org.andengine.opengl.vbo.attribute.VertexBufferObjectAttributes; import org.andengine.opengl.vbo.attribute.VertexBufferObjectAttributesBuilder; +import org.andengine.util.adt.color.ColorUtils; import org.andengine.util.adt.transformation.Transformation; -import org.andengine.util.color.ColorUtils; import android.opengl.GLES20; /** * TODO TRY DEGENERATE TRIANGLES! * TODO Check if there is this multiple-of-X-byte(?) alignment optimization? - * + * * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 11:45:48 - 14.06.2011 */ @@ -130,6 +130,10 @@ public SpriteBatch(final float pX, final float pY, final ITexture pTexture, fina // Getter & Setter // =========================================================== + public int getCapacity() { + return this.mCapacity; + } + public int getIndex() { return this.mIndex; } @@ -162,7 +166,7 @@ public ISpriteBatchVertexBufferObject getVertexBufferObject() { } @Override - public boolean collidesWith(final IShape pOtherShape) { + public boolean collidesWith(final IEntity pOtherEntity) { return false; } @@ -180,7 +184,7 @@ protected void onUpdateVertices() { protected void preDraw(final GLState pGLState, final Camera pCamera) { super.preDraw(pGLState, pCamera); - if(this.mBlendingEnabled) { + if (this.mBlendingEnabled) { pGLState.enableBlend(); pGLState.blendFunction(this.mBlendFunctionSource, this.mBlendFunctionDestination); } @@ -203,7 +207,7 @@ protected void draw(final GLState pGLState, final Camera pCamera) { protected void postDraw(final GLState pGLState, final Camera pCamera) { this.mSpriteBatchVertexBufferObject.unbind(pGLState, this.mShaderProgram); - if(this.mBlendingEnabled) { + if (this.mBlendingEnabled) { pGLState.disableBlend(); } @@ -221,7 +225,7 @@ public void reset() { public void dispose() { super.dispose(); - if(this.mSpriteBatchVertexBufferObject != null && this.mSpriteBatchVertexBufferObject.isAutoDispose() && !this.mSpriteBatchVertexBufferObject.isDisposed()) { + if (this.mSpriteBatchVertexBufferObject != null && this.mSpriteBatchVertexBufferObject.isAutoDispose() && !this.mSpriteBatchVertexBufferObject.isDisposed()) { this.mSpriteBatchVertexBufferObject.dispose(); } } @@ -250,6 +254,12 @@ public void draw(final ITextureRegion pTextureRegion, final float pX, final floa this.mIndex++; } + public void drawWithoutChecks(final ITextureRegion pTextureRegion, final float pX, final float pY, final float pWidth, final float pHeight, final float pRed, final float pGreen, final float pBlue, final float pAlpha) { + this.add(pTextureRegion, pX, pY, pWidth, pHeight, pRed, pGreen, pBlue, pAlpha); + + this.mIndex++; + } + /** * @see {@link SpriteBatchVertexBufferObject#add(ITextureRegion, float, float, float, float, float)}. */ @@ -262,21 +272,12 @@ public void draw(final ITextureRegion pTextureRegion, final float pX, final floa this.mIndex++; } - /** - * @see {@link SpriteBatchVertexBufferObject#add(ITextureRegion, float, float, float, float, float)}. - */ public void drawWithoutChecks(final ITextureRegion pTextureRegion, final float pX, final float pY, final float pWidth, final float pHeight, final float pColorABGRPackedInt) { this.add(pTextureRegion, pX, pY, pWidth, pHeight, pColorABGRPackedInt); this.mIndex++; } - public void drawWithoutChecks(final ITextureRegion pTextureRegion, final float pX, final float pY, final float pWidth, final float pHeight, final float pRed, final float pGreen, final float pBlue, final float pAlpha) { - this.add(pTextureRegion, pX, pY, pWidth, pHeight, pRed, pGreen, pBlue, pAlpha); - - this.mIndex++; - } - /** * @see {@link SpriteBatchVertexBufferObject#add(ITextureRegion, float, float, float, float, float, float, float, float)}. */ @@ -353,75 +354,102 @@ public void drawWithoutChecks(final ITextureRegion pTextureRegion, final float p * @see {@link SpriteBatchVertexBufferObject#add(ITextureRegion, float, float, float, float, float)} {@link SpriteBatchVertexBufferObject#add(ITextureRegion, float, float, Transformation, float)}. */ public void draw(final Sprite pSprite) { - this.draw(pSprite, pSprite.getColor().getABGRPackedFloat()); + this.draw(pSprite.getTextureRegion(), pSprite, pSprite.getColor().getABGRPackedFloat()); + } + + public void drawWithoutChecks(final Sprite pSprite) { + this.drawWithoutChecks(pSprite.getTextureRegion(), pSprite, pSprite.getColor().getABGRPackedFloat()); } /** * @see {@link SpriteBatchVertexBufferObject#add(ITextureRegion, float, float, float, float, float, float, float, float)} {@link SpriteBatchVertexBufferObject#add(ITextureRegion, float, float, Transformation, float, float, float, float)}. */ public void draw(final Sprite pSprite, final float pRed, final float pGreen, final float pBlue, final float pAlpha) { - if(pSprite.isVisible()) { - this.assertCapacity(); - - final ITextureRegion textureRegion = pSprite.getTextureRegion(); - this.assertTexture(textureRegion); - - if(pSprite.isRotatedOrScaledOrSkewed()) { - this.add(textureRegion, pSprite.getWidth(), pSprite.getHeight(), pSprite.getLocalToParentTransformation(), pRed, pGreen, pBlue, pAlpha); - } else { - this.add(textureRegion, pSprite.getX(), pSprite.getY(), pSprite.getWidth(), pSprite.getHeight(), pRed, pGreen, pBlue, pAlpha); - } + this.draw(pSprite.getTextureRegion(), pSprite, pRed, pGreen, pBlue, pAlpha); + } - this.mIndex++; - } + public void drawWithoutChecks(final Sprite pSprite, final float pRed, final float pGreen, final float pBlue, final float pAlpha) { + this.drawWithoutChecks(pSprite.getTextureRegion(), pSprite, pRed, pGreen, pBlue, pAlpha); } /** * @see {@link SpriteBatchVertexBufferObject#add(ITextureRegion, float, float, float, float, float)} {@link SpriteBatchVertexBufferObject#add(ITextureRegion, float, float, Transformation, float, float, float, float)}. */ public void draw(final Sprite pSprite, final float pColorABGRPackedInt) { - if(pSprite.isVisible()) { + this.draw(pSprite.getTextureRegion(), pSprite, pColorABGRPackedInt); + } + + public void drawWithoutChecks(final Sprite pSprite, final float pColorABGRPackedInt) { + this.drawWithoutChecks(pSprite.getTextureRegion(), pSprite, pColorABGRPackedInt); + } + + /** + * @see {@link SpriteBatchVertexBufferObject#add(ITextureRegion, float, float, float, float, float)} {@link SpriteBatchVertexBufferObject#add(ITextureRegion, float, float, Transformation, float)}. + */ + public void draw(final ITextureRegion pTextureRegion, final IEntity pEntity) { + this.draw(pTextureRegion, pEntity, pEntity.getColor().getABGRPackedFloat()); + } + + public void drawWithoutChecks(final ITextureRegion pTextureRegion, final IEntity pEntity) { + this.drawWithoutChecks(pTextureRegion, pEntity, pEntity.getColor().getABGRPackedFloat()); + } + + /** + * @see {@link SpriteBatchVertexBufferObject#add(ITextureRegion, float, float, float, float, float, float, float, float)} {@link SpriteBatchVertexBufferObject#add(ITextureRegion, float, float, Transformation, float, float, float, float)}. + */ + public void draw(final ITextureRegion pTextureRegion, final IEntity pEntity, final float pRed, final float pGreen, final float pBlue, final float pAlpha) { + if (pEntity.isVisible()) { this.assertCapacity(); - final ITextureRegion textureRegion = pSprite.getTextureRegion(); - this.assertTexture(textureRegion); + this.assertTexture(pTextureRegion); - if(pSprite.isRotatedOrScaledOrSkewed()) { - this.addWithPackedColor(textureRegion, pSprite.getWidth(), pSprite.getHeight(), pSprite.getLocalToParentTransformation(), pColorABGRPackedInt); + if (pEntity.isRotatedOrScaledOrSkewed()) { + this.add(pTextureRegion, pEntity.getWidth(), pEntity.getHeight(), pEntity.getLocalToParentTransformation(), pRed, pGreen, pBlue, pAlpha); } else { - this.addWithPackedColor(textureRegion, pSprite.getX(), pSprite.getY(), pSprite.getWidth(), pSprite.getHeight(), pColorABGRPackedInt); + this.add(pTextureRegion, pEntity.getX(), pEntity.getY(), pEntity.getWidth(), pEntity.getHeight(), pRed, pGreen, pBlue, pAlpha); } this.mIndex++; } } - public void drawWithoutChecks(final Sprite pSprite) { - this.drawWithoutChecks(pSprite, pSprite.getColor().getABGRPackedFloat()); + public void drawWithoutChecks(final ITextureRegion pTextureRegion, final IEntity pEntity, final float pRed, final float pGreen, final float pBlue, final float pAlpha) { + if (pEntity.isVisible()) { + if (pEntity.isRotatedOrScaledOrSkewed()) { + this.add(pTextureRegion, pEntity.getWidth(), pEntity.getHeight(), pEntity.getLocalToParentTransformation(), pRed, pGreen, pBlue, pAlpha); + } else { + this.add(pTextureRegion, pEntity.getX(), pEntity.getY(), pEntity.getWidth(), pEntity.getHeight(), pRed, pGreen, pBlue, pAlpha); + } + + this.mIndex++; + } } - public void drawWithoutChecks(final Sprite pSprite, final float pRed, final float pGreen, final float pBlue, final float pAlpha) { - if(pSprite.isVisible()) { - final ITextureRegion textureRegion = pSprite.getTextureRegion(); + /** + * @see {@link SpriteBatchVertexBufferObject#add(ITextureRegion, float, float, float, float, float)} {@link SpriteBatchVertexBufferObject#add(ITextureRegion, float, float, Transformation, float, float, float, float)}. + */ + public void draw(final ITextureRegion pTextureRegion, final IEntity pEntity, final float pColorABGRPackedInt) { + if (pEntity.isVisible()) { + this.assertCapacity(); - if(pSprite.isRotatedOrScaledOrSkewed()) { - this.add(textureRegion, pSprite.getWidth(), pSprite.getHeight(), pSprite.getLocalToParentTransformation(), pRed, pGreen, pBlue, pAlpha); + this.assertTexture(pTextureRegion); + + if (pEntity.isRotatedOrScaledOrSkewed()) { + this.addWithPackedColor(pTextureRegion, pEntity.getWidth(), pEntity.getHeight(), pEntity.getLocalToParentTransformation(), pColorABGRPackedInt); } else { - this.add(textureRegion, pSprite.getX(), pSprite.getY(), pSprite.getWidth(), pSprite.getHeight(), pRed, pGreen, pBlue, pAlpha); + this.addWithPackedColor(pTextureRegion, pEntity.getX(), pEntity.getY(), pEntity.getWidth(), pEntity.getHeight(), pColorABGRPackedInt); } this.mIndex++; } } - public void drawWithoutChecks(final Sprite pSprite, final float pColorABGRPackedInt) { - if(pSprite.isVisible()) { - final ITextureRegion textureRegion = pSprite.getTextureRegion(); - - if(pSprite.isRotatedOrScaledOrSkewed()) { - this.addWithPackedColor(textureRegion, pSprite.getWidth(), pSprite.getHeight(), pSprite.getLocalToParentTransformation(), pColorABGRPackedInt); + public void drawWithoutChecks(final ITextureRegion pTextureRegion, final IEntity pEntity, final float pColorABGRPackedInt) { + if (pEntity.isVisible()) { + if (pEntity.isRotatedOrScaledOrSkewed()) { + this.addWithPackedColor(pTextureRegion, pEntity.getWidth(), pEntity.getHeight(), pEntity.getLocalToParentTransformation(), pColorABGRPackedInt); } else { - this.addWithPackedColor(textureRegion, pSprite.getX(), pSprite.getY(), pSprite.getWidth(), pSprite.getHeight(), pColorABGRPackedInt); + this.addWithPackedColor(pTextureRegion, pEntity.getX(), pEntity.getY(), pEntity.getWidth(), pEntity.getHeight(), pColorABGRPackedInt); } this.mIndex++; @@ -442,20 +470,20 @@ protected void onSubmit() { } private void assertCapacity(final int pIndex) { - if(pIndex >= this.mCapacity) { - throw new IllegalStateException("This supplied pIndex: '" + pIndex + "' is exceeding the capacity: '" + this.mCapacity + "' of this SpriteBatch!"); + if (pIndex >= this.mCapacity) { + throw new IllegalStateException("This supplied pIndex: '" + pIndex + "' is exceeding the capacity: '" + this.mCapacity + "' of this " + this.getClass().getSimpleName() + "!"); } } private void assertCapacity() { - if(this.mIndex == this.mCapacity) { - throw new IllegalStateException("This SpriteBatch has already reached its capacity (" + this.mCapacity + ") !"); + if (this.mIndex == this.mCapacity) { + throw new IllegalStateException("This " + this.getClass().getSimpleName() + " has already reached its capacity (" + this.mCapacity + ") !"); } } protected void assertTexture(final ITextureRegion pTextureRegion) { - if(pTextureRegion.getTexture() != this.mTexture) { - throw new IllegalArgumentException("The supplied Texture does match the Texture of this SpriteBatch!"); + if (pTextureRegion.getTexture() != this.mTexture) { + throw new IllegalArgumentException("The supplied Texture does match the Texture of this " + this.getClass().getSimpleName() + "!"); } } @@ -641,7 +669,7 @@ protected void add(final ITextureRegion pTextureRegion, final float pWidth, fina pTransformation.transform(SpriteBatch.VERTICES_TMP); - this.addInner(pTextureRegion, SpriteBatch.VERTICES_TMP[0], SpriteBatch.VERTICES_TMP[1], SpriteBatch.VERTICES_TMP[2], SpriteBatch.VERTICES_TMP[3], SpriteBatch.VERTICES_TMP[4], SpriteBatch.VERTICES_TMP[5], SpriteBatch.VERTICES_TMP[6], SpriteBatch.VERTICES_TMP[7], pRed, pGreen, pBlue, pAlpha); + this.addInner(pTextureRegion, SpriteBatch.VERTICES_TMP[0], SpriteBatch.VERTICES_TMP[1], SpriteBatch.VERTICES_TMP[2], SpriteBatch.VERTICES_TMP[3], SpriteBatch.VERTICES_TMP[4], SpriteBatch.VERTICES_TMP[5], SpriteBatch.VERTICES_TMP[6], SpriteBatch.VERTICES_TMP[7], pRed, pGreen, pBlue, pAlpha); } /** @@ -666,7 +694,7 @@ protected void addWithPackedColor(final ITextureRegion pTextureRegion, final flo pTransformation.transform(SpriteBatch.VERTICES_TMP); - this.mSpriteBatchVertexBufferObject.addWithPackedColor(pTextureRegion, SpriteBatch.VERTICES_TMP[0], SpriteBatch.VERTICES_TMP[1], SpriteBatch.VERTICES_TMP[2], SpriteBatch.VERTICES_TMP[3], SpriteBatch.VERTICES_TMP[4], SpriteBatch.VERTICES_TMP[5], SpriteBatch.VERTICES_TMP[6], SpriteBatch.VERTICES_TMP[7], pColorABGRPackedInt); + this.mSpriteBatchVertexBufferObject.addWithPackedColor(pTextureRegion, SpriteBatch.VERTICES_TMP[0], SpriteBatch.VERTICES_TMP[1], SpriteBatch.VERTICES_TMP[2], SpriteBatch.VERTICES_TMP[3], SpriteBatch.VERTICES_TMP[4], SpriteBatch.VERTICES_TMP[5], SpriteBatch.VERTICES_TMP[6], SpriteBatch.VERTICES_TMP[7], pColorABGRPackedInt); } /** diff --git a/src/org/andengine/entity/sprite/batch/SpriteGroup.java b/src/org/andengine/entity/sprite/batch/SpriteGroup.java index d645ad690..85264c622 100644 --- a/src/org/andengine/entity/sprite/batch/SpriteGroup.java +++ b/src/org/andengine/entity/sprite/batch/SpriteGroup.java @@ -14,7 +14,7 @@ /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 12:10:35 - 15.06.2011 */ @@ -124,13 +124,13 @@ public SpriteGroup(final float pX, final float pY, final ITexture pTexture, fina // =========================================================== /** - * Instead use {@link SpriteGroup#attachChild(BaseSprite)}. + * Instead use {@link #attachChild(BaseSprite)}. */ @Override @Deprecated public void attachChild(final IEntity pEntity) throws IllegalArgumentException { - if(pEntity instanceof Sprite) { - this.attachChild((Sprite)pEntity); + if (pEntity instanceof Sprite) { + this.attachChild((Sprite) pEntity); } else { throw new IllegalArgumentException("A " + SpriteGroup.class.getSimpleName() + " can only handle children of type Sprite or subclasses of Sprite, like TiledSprite or AnimatedSprite."); } @@ -144,7 +144,7 @@ public void attachChild(final Sprite pSprite) { public void attachChildren(final ArrayList pSprites) { final int baseSpriteCount = pSprites.size(); - for(int i = 0; i < baseSpriteCount; i++) { + for (int i = 0; i < baseSpriteCount; i++) { this.attachChild(pSprites.get(i)); } } @@ -152,12 +152,12 @@ public void attachChildren(final ArrayList pSprites) { @Override protected boolean onUpdateSpriteBatch() { final SmartList children = this.mChildren; - if(children == null) { + if (children == null) { return false; } else { final int childCount = children.size(); - for(int i = 0; i < childCount; i++) { - this.drawWithoutChecks((Sprite)children.get(i)); + for (int i = 0; i < childCount; i++) { + this.drawWithoutChecks((Sprite) children.get(i)); } return true; } @@ -168,7 +168,7 @@ protected boolean onUpdateSpriteBatch() { // =========================================================== private void assertCapacity() { - if(this.getChildCount() >= this.mCapacity) { + if (this.getChildCount() >= this.mCapacity) { throw new IllegalStateException("This " + SpriteGroup.class.getSimpleName() + " has already reached its capacity (" + this.mCapacity + ") !"); } } diff --git a/src/org/andengine/entity/sprite/batch/vbo/HighPerformanceSpriteBatchVertexBufferObject.java b/src/org/andengine/entity/sprite/batch/vbo/HighPerformanceSpriteBatchVertexBufferObject.java index 037f0f799..38d67a88a 100644 --- a/src/org/andengine/entity/sprite/batch/vbo/HighPerformanceSpriteBatchVertexBufferObject.java +++ b/src/org/andengine/entity/sprite/batch/vbo/HighPerformanceSpriteBatchVertexBufferObject.java @@ -8,7 +8,7 @@ import org.andengine.opengl.vbo.attribute.VertexBufferObjectAttributes; /** - * (c) Zynga 2012 + * (c) 2012 Zynga Inc. * * @author Nicolas Gramlich * @since 12:35:28 - 29.03.2012 @@ -73,78 +73,78 @@ public void addWithPackedColor(final ITextureRegion pTextureRegion, final float final float u2 = pTextureRegion.getU2(); final float v2 = pTextureRegion.getV2(); - if(pTextureRegion.isRotated()) { + if (pTextureRegion.isRotated()) { bufferData[bufferDataOffset + 0 * SpriteBatch.VERTEX_SIZE + SpriteBatch.VERTEX_INDEX_X] = x1; bufferData[bufferDataOffset + 0 * SpriteBatch.VERTEX_SIZE + SpriteBatch.VERTEX_INDEX_Y] = y1; bufferData[bufferDataOffset + 0 * SpriteBatch.VERTEX_SIZE + SpriteBatch.COLOR_INDEX] = pColorABGRPackedInt; - bufferData[bufferDataOffset + 0 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_U] = u2; + bufferData[bufferDataOffset + 0 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_U] = u; bufferData[bufferDataOffset + 0 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_V] = v; bufferData[bufferDataOffset + 1 * SpriteBatch.VERTEX_SIZE + SpriteBatch.VERTEX_INDEX_X] = x2; bufferData[bufferDataOffset + 1 * SpriteBatch.VERTEX_SIZE + SpriteBatch.VERTEX_INDEX_Y] = y2; bufferData[bufferDataOffset + 1 * SpriteBatch.VERTEX_SIZE + SpriteBatch.COLOR_INDEX] = pColorABGRPackedInt; - bufferData[bufferDataOffset + 1 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_U] = u; + bufferData[bufferDataOffset + 1 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_U] = u2; bufferData[bufferDataOffset + 1 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_V] = v; bufferData[bufferDataOffset + 2 * SpriteBatch.VERTEX_SIZE + SpriteBatch.VERTEX_INDEX_X] = x3; bufferData[bufferDataOffset + 2 * SpriteBatch.VERTEX_SIZE + SpriteBatch.VERTEX_INDEX_Y] = y3; bufferData[bufferDataOffset + 2 * SpriteBatch.VERTEX_SIZE + SpriteBatch.COLOR_INDEX] = pColorABGRPackedInt; - bufferData[bufferDataOffset + 2 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_U] = u2; + bufferData[bufferDataOffset + 2 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_U] = u; bufferData[bufferDataOffset + 2 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_V] = v2; bufferData[bufferDataOffset + 3 * SpriteBatch.VERTEX_SIZE + SpriteBatch.VERTEX_INDEX_X] = x3; bufferData[bufferDataOffset + 3 * SpriteBatch.VERTEX_SIZE + SpriteBatch.VERTEX_INDEX_Y] = y3; bufferData[bufferDataOffset + 3 * SpriteBatch.VERTEX_SIZE + SpriteBatch.COLOR_INDEX] = pColorABGRPackedInt; - bufferData[bufferDataOffset + 3 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_U] = u2; + bufferData[bufferDataOffset + 3 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_U] = u; bufferData[bufferDataOffset + 3 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_V] = v2; bufferData[bufferDataOffset + 4 * SpriteBatch.VERTEX_SIZE + SpriteBatch.VERTEX_INDEX_X] = x2; bufferData[bufferDataOffset + 4 * SpriteBatch.VERTEX_SIZE + SpriteBatch.VERTEX_INDEX_Y] = y2; bufferData[bufferDataOffset + 4 * SpriteBatch.VERTEX_SIZE + SpriteBatch.COLOR_INDEX] = pColorABGRPackedInt; - bufferData[bufferDataOffset + 4 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_U] = u; + bufferData[bufferDataOffset + 4 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_U] = u2; bufferData[bufferDataOffset + 4 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_V] = v; bufferData[bufferDataOffset + 5 * SpriteBatch.VERTEX_SIZE + SpriteBatch.VERTEX_INDEX_X] = x4; bufferData[bufferDataOffset + 5 * SpriteBatch.VERTEX_SIZE + SpriteBatch.VERTEX_INDEX_Y] = y4; bufferData[bufferDataOffset + 5 * SpriteBatch.VERTEX_SIZE + SpriteBatch.COLOR_INDEX] = pColorABGRPackedInt; - bufferData[bufferDataOffset + 5 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_U] = u; + bufferData[bufferDataOffset + 5 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_U] = u2; bufferData[bufferDataOffset + 5 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_V] = v2; } else { bufferData[bufferDataOffset + 0 * SpriteBatch.VERTEX_SIZE + SpriteBatch.VERTEX_INDEX_X] = x1; bufferData[bufferDataOffset + 0 * SpriteBatch.VERTEX_SIZE + SpriteBatch.VERTEX_INDEX_Y] = y1; bufferData[bufferDataOffset + 0 * SpriteBatch.VERTEX_SIZE + SpriteBatch.COLOR_INDEX] = pColorABGRPackedInt; bufferData[bufferDataOffset + 0 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_U] = u; - bufferData[bufferDataOffset + 0 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_V] = v; + bufferData[bufferDataOffset + 0 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_V] = v2; bufferData[bufferDataOffset + 1 * SpriteBatch.VERTEX_SIZE + SpriteBatch.VERTEX_INDEX_X] = x2; bufferData[bufferDataOffset + 1 * SpriteBatch.VERTEX_SIZE + SpriteBatch.VERTEX_INDEX_Y] = y2; bufferData[bufferDataOffset + 1 * SpriteBatch.VERTEX_SIZE + SpriteBatch.COLOR_INDEX] = pColorABGRPackedInt; bufferData[bufferDataOffset + 1 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_U] = u; - bufferData[bufferDataOffset + 1 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_V] = v2; + bufferData[bufferDataOffset + 1 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_V] = v; bufferData[bufferDataOffset + 2 * SpriteBatch.VERTEX_SIZE + SpriteBatch.VERTEX_INDEX_X] = x3; bufferData[bufferDataOffset + 2 * SpriteBatch.VERTEX_SIZE + SpriteBatch.VERTEX_INDEX_Y] = y3; bufferData[bufferDataOffset + 2 * SpriteBatch.VERTEX_SIZE + SpriteBatch.COLOR_INDEX] = pColorABGRPackedInt; bufferData[bufferDataOffset + 2 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_U] = u2; - bufferData[bufferDataOffset + 2 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_V] = v; + bufferData[bufferDataOffset + 2 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_V] = v2; bufferData[bufferDataOffset + 3 * SpriteBatch.VERTEX_SIZE + SpriteBatch.VERTEX_INDEX_X] = x3; bufferData[bufferDataOffset + 3 * SpriteBatch.VERTEX_SIZE + SpriteBatch.VERTEX_INDEX_Y] = y3; bufferData[bufferDataOffset + 3 * SpriteBatch.VERTEX_SIZE + SpriteBatch.COLOR_INDEX] = pColorABGRPackedInt; bufferData[bufferDataOffset + 3 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_U] = u2; - bufferData[bufferDataOffset + 3 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_V] = v; + bufferData[bufferDataOffset + 3 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_V] = v2; bufferData[bufferDataOffset + 4 * SpriteBatch.VERTEX_SIZE + SpriteBatch.VERTEX_INDEX_X] = x2; bufferData[bufferDataOffset + 4 * SpriteBatch.VERTEX_SIZE + SpriteBatch.VERTEX_INDEX_Y] = y2; bufferData[bufferDataOffset + 4 * SpriteBatch.VERTEX_SIZE + SpriteBatch.COLOR_INDEX] = pColorABGRPackedInt; bufferData[bufferDataOffset + 4 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_U] = u; - bufferData[bufferDataOffset + 4 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_V] = v2; + bufferData[bufferDataOffset + 4 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_V] = v; bufferData[bufferDataOffset + 5 * SpriteBatch.VERTEX_SIZE + SpriteBatch.VERTEX_INDEX_X] = x4; bufferData[bufferDataOffset + 5 * SpriteBatch.VERTEX_SIZE + SpriteBatch.VERTEX_INDEX_Y] = y4; bufferData[bufferDataOffset + 5 * SpriteBatch.VERTEX_SIZE + SpriteBatch.COLOR_INDEX] = pColorABGRPackedInt; bufferData[bufferDataOffset + 5 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_U] = u2; - bufferData[bufferDataOffset + 5 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_V] = v2; + bufferData[bufferDataOffset + 5 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_V] = v; } this.mBufferDataOffset += SpriteBatch.SPRITE_SIZE; @@ -170,78 +170,78 @@ public void addWithPackedColor(final ITextureRegion pTextureRegion, final float final float u2 = pTextureRegion.getU2(); final float v2 = pTextureRegion.getV2(); - if(pTextureRegion.isRotated()) { + if (pTextureRegion.isRotated()) { bufferData[bufferDataOffset + 0 * SpriteBatch.VERTEX_SIZE + SpriteBatch.VERTEX_INDEX_X] = x1; bufferData[bufferDataOffset + 0 * SpriteBatch.VERTEX_SIZE + SpriteBatch.VERTEX_INDEX_Y] = y1; bufferData[bufferDataOffset + 0 * SpriteBatch.VERTEX_SIZE + SpriteBatch.COLOR_INDEX] = pColorABGRPackedInt; - bufferData[bufferDataOffset + 0 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_U] = u2; + bufferData[bufferDataOffset + 0 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_U] = u; bufferData[bufferDataOffset + 0 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_V] = v; bufferData[bufferDataOffset + 1 * SpriteBatch.VERTEX_SIZE + SpriteBatch.VERTEX_INDEX_X] = x1; bufferData[bufferDataOffset + 1 * SpriteBatch.VERTEX_SIZE + SpriteBatch.VERTEX_INDEX_Y] = y2; bufferData[bufferDataOffset + 1 * SpriteBatch.VERTEX_SIZE + SpriteBatch.COLOR_INDEX] = pColorABGRPackedInt; - bufferData[bufferDataOffset + 1 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_U] = u; + bufferData[bufferDataOffset + 1 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_U] = u2; bufferData[bufferDataOffset + 1 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_V] = v; bufferData[bufferDataOffset + 2 * SpriteBatch.VERTEX_SIZE + SpriteBatch.VERTEX_INDEX_X] = x2; bufferData[bufferDataOffset + 2 * SpriteBatch.VERTEX_SIZE + SpriteBatch.VERTEX_INDEX_Y] = y1; bufferData[bufferDataOffset + 2 * SpriteBatch.VERTEX_SIZE + SpriteBatch.COLOR_INDEX] = pColorABGRPackedInt; - bufferData[bufferDataOffset + 2 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_U] = u2; + bufferData[bufferDataOffset + 2 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_U] = u; bufferData[bufferDataOffset + 2 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_V] = v2; bufferData[bufferDataOffset + 3 * SpriteBatch.VERTEX_SIZE + SpriteBatch.VERTEX_INDEX_X] = x2; bufferData[bufferDataOffset + 3 * SpriteBatch.VERTEX_SIZE + SpriteBatch.VERTEX_INDEX_Y] = y1; bufferData[bufferDataOffset + 3 * SpriteBatch.VERTEX_SIZE + SpriteBatch.COLOR_INDEX] = pColorABGRPackedInt; - bufferData[bufferDataOffset + 3 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_U] = u2; + bufferData[bufferDataOffset + 3 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_U] = u; bufferData[bufferDataOffset + 3 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_V] = v2; bufferData[bufferDataOffset + 4 * SpriteBatch.VERTEX_SIZE + SpriteBatch.VERTEX_INDEX_X] = x1; bufferData[bufferDataOffset + 4 * SpriteBatch.VERTEX_SIZE + SpriteBatch.VERTEX_INDEX_Y] = y2; bufferData[bufferDataOffset + 4 * SpriteBatch.VERTEX_SIZE + SpriteBatch.COLOR_INDEX] = pColorABGRPackedInt; - bufferData[bufferDataOffset + 4 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_U] = u; + bufferData[bufferDataOffset + 4 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_U] = u2; bufferData[bufferDataOffset + 4 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_V] = v; bufferData[bufferDataOffset + 5 * SpriteBatch.VERTEX_SIZE + SpriteBatch.VERTEX_INDEX_X] = x2; bufferData[bufferDataOffset + 5 * SpriteBatch.VERTEX_SIZE + SpriteBatch.VERTEX_INDEX_Y] = y2; bufferData[bufferDataOffset + 5 * SpriteBatch.VERTEX_SIZE + SpriteBatch.COLOR_INDEX] = pColorABGRPackedInt; - bufferData[bufferDataOffset + 5 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_U] = u; + bufferData[bufferDataOffset + 5 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_U] = u2; bufferData[bufferDataOffset + 5 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_V] = v2; } else { bufferData[bufferDataOffset + 0 * SpriteBatch.VERTEX_SIZE + SpriteBatch.VERTEX_INDEX_X] = x1; bufferData[bufferDataOffset + 0 * SpriteBatch.VERTEX_SIZE + SpriteBatch.VERTEX_INDEX_Y] = y1; bufferData[bufferDataOffset + 0 * SpriteBatch.VERTEX_SIZE + SpriteBatch.COLOR_INDEX] = pColorABGRPackedInt; bufferData[bufferDataOffset + 0 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_U] = u; - bufferData[bufferDataOffset + 0 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_V] = v; + bufferData[bufferDataOffset + 0 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_V] = v2; bufferData[bufferDataOffset + 1 * SpriteBatch.VERTEX_SIZE + SpriteBatch.VERTEX_INDEX_X] = x1; bufferData[bufferDataOffset + 1 * SpriteBatch.VERTEX_SIZE + SpriteBatch.VERTEX_INDEX_Y] = y2; bufferData[bufferDataOffset + 1 * SpriteBatch.VERTEX_SIZE + SpriteBatch.COLOR_INDEX] = pColorABGRPackedInt; bufferData[bufferDataOffset + 1 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_U] = u; - bufferData[bufferDataOffset + 1 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_V] = v2; + bufferData[bufferDataOffset + 1 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_V] = v; bufferData[bufferDataOffset + 2 * SpriteBatch.VERTEX_SIZE + SpriteBatch.VERTEX_INDEX_X] = x2; bufferData[bufferDataOffset + 2 * SpriteBatch.VERTEX_SIZE + SpriteBatch.VERTEX_INDEX_Y] = y1; bufferData[bufferDataOffset + 2 * SpriteBatch.VERTEX_SIZE + SpriteBatch.COLOR_INDEX] = pColorABGRPackedInt; bufferData[bufferDataOffset + 2 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_U] = u2; - bufferData[bufferDataOffset + 2 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_V] = v; + bufferData[bufferDataOffset + 2 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_V] = v2; bufferData[bufferDataOffset + 3 * SpriteBatch.VERTEX_SIZE + SpriteBatch.VERTEX_INDEX_X] = x2; bufferData[bufferDataOffset + 3 * SpriteBatch.VERTEX_SIZE + SpriteBatch.VERTEX_INDEX_Y] = y1; bufferData[bufferDataOffset + 3 * SpriteBatch.VERTEX_SIZE + SpriteBatch.COLOR_INDEX] = pColorABGRPackedInt; bufferData[bufferDataOffset + 3 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_U] = u2; - bufferData[bufferDataOffset + 3 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_V] = v; + bufferData[bufferDataOffset + 3 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_V] = v2; bufferData[bufferDataOffset + 4 * SpriteBatch.VERTEX_SIZE + SpriteBatch.VERTEX_INDEX_X] = x1; bufferData[bufferDataOffset + 4 * SpriteBatch.VERTEX_SIZE + SpriteBatch.VERTEX_INDEX_Y] = y2; bufferData[bufferDataOffset + 4 * SpriteBatch.VERTEX_SIZE + SpriteBatch.COLOR_INDEX] = pColorABGRPackedInt; bufferData[bufferDataOffset + 4 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_U] = u; - bufferData[bufferDataOffset + 4 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_V] = v2; + bufferData[bufferDataOffset + 4 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_V] = v; bufferData[bufferDataOffset + 5 * SpriteBatch.VERTEX_SIZE + SpriteBatch.VERTEX_INDEX_X] = x2; bufferData[bufferDataOffset + 5 * SpriteBatch.VERTEX_SIZE + SpriteBatch.VERTEX_INDEX_Y] = y2; bufferData[bufferDataOffset + 5 * SpriteBatch.VERTEX_SIZE + SpriteBatch.COLOR_INDEX] = pColorABGRPackedInt; bufferData[bufferDataOffset + 5 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_U] = u2; - bufferData[bufferDataOffset + 5 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_V] = v2; + bufferData[bufferDataOffset + 5 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_V] = v; } this.mBufferDataOffset += SpriteBatch.SPRITE_SIZE; diff --git a/src/org/andengine/entity/sprite/batch/vbo/ISpriteBatchVertexBufferObject.java b/src/org/andengine/entity/sprite/batch/vbo/ISpriteBatchVertexBufferObject.java index 8e85de1e7..b59d6c97e 100644 --- a/src/org/andengine/entity/sprite/batch/vbo/ISpriteBatchVertexBufferObject.java +++ b/src/org/andengine/entity/sprite/batch/vbo/ISpriteBatchVertexBufferObject.java @@ -4,7 +4,7 @@ import org.andengine.opengl.vbo.IVertexBufferObject; /** - * (c) Zynga 2012 + * (c) 2012 Zynga Inc. * * @author Nicolas Gramlich * @since 12:35:06 - 29.03.2012 diff --git a/src/org/andengine/entity/sprite/batch/vbo/LowMemorySpriteBatchVertexBufferObject.java b/src/org/andengine/entity/sprite/batch/vbo/LowMemorySpriteBatchVertexBufferObject.java index b9e00ae7f..cf3b755d7 100644 --- a/src/org/andengine/entity/sprite/batch/vbo/LowMemorySpriteBatchVertexBufferObject.java +++ b/src/org/andengine/entity/sprite/batch/vbo/LowMemorySpriteBatchVertexBufferObject.java @@ -10,7 +10,7 @@ import org.andengine.opengl.vbo.attribute.VertexBufferObjectAttributes; /** - * (c) Zynga 2012 + * (c) 2012 Zynga Inc. * * @author Nicolas Gramlich * @since 12:34:46 - 29.03.2012 @@ -75,7 +75,7 @@ public void addWithPackedColor(final ITextureRegion pTextureRegion, final float final float u2 = pTextureRegion.getU2(); final float v2 = pTextureRegion.getV2(); - if(pTextureRegion.isRotated()) { + if (pTextureRegion.isRotated()) { bufferData.put(bufferDataOffset + 0 * SpriteBatch.VERTEX_SIZE + SpriteBatch.VERTEX_INDEX_X, x1); bufferData.put(bufferDataOffset + 0 * SpriteBatch.VERTEX_SIZE + SpriteBatch.VERTEX_INDEX_Y, y1); bufferData.put(bufferDataOffset + 0 * SpriteBatch.VERTEX_SIZE + SpriteBatch.COLOR_INDEX, pColorABGRPackedInt); @@ -85,68 +85,68 @@ public void addWithPackedColor(final ITextureRegion pTextureRegion, final float bufferData.put(bufferDataOffset + 1 * SpriteBatch.VERTEX_SIZE + SpriteBatch.VERTEX_INDEX_X, x2); bufferData.put(bufferDataOffset + 1 * SpriteBatch.VERTEX_SIZE + SpriteBatch.VERTEX_INDEX_Y, y2); bufferData.put(bufferDataOffset + 1 * SpriteBatch.VERTEX_SIZE + SpriteBatch.COLOR_INDEX, pColorABGRPackedInt); - bufferData.put(bufferDataOffset + 1 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_U, u); + bufferData.put(bufferDataOffset + 1 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_U, u2); bufferData.put(bufferDataOffset + 1 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_V, v); bufferData.put(bufferDataOffset + 2 * SpriteBatch.VERTEX_SIZE + SpriteBatch.VERTEX_INDEX_X, x3); bufferData.put(bufferDataOffset + 2 * SpriteBatch.VERTEX_SIZE + SpriteBatch.VERTEX_INDEX_Y, y3); bufferData.put(bufferDataOffset + 2 * SpriteBatch.VERTEX_SIZE + SpriteBatch.COLOR_INDEX, pColorABGRPackedInt); - bufferData.put(bufferDataOffset + 2 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_U, u2); + bufferData.put(bufferDataOffset + 2 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_U, u); bufferData.put(bufferDataOffset + 2 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_V, v2); bufferData.put(bufferDataOffset + 3 * SpriteBatch.VERTEX_SIZE + SpriteBatch.VERTEX_INDEX_X, x3); bufferData.put(bufferDataOffset + 3 * SpriteBatch.VERTEX_SIZE + SpriteBatch.VERTEX_INDEX_Y, y3); bufferData.put(bufferDataOffset + 3 * SpriteBatch.VERTEX_SIZE + SpriteBatch.COLOR_INDEX, pColorABGRPackedInt); - bufferData.put(bufferDataOffset + 3 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_U, u2); + bufferData.put(bufferDataOffset + 3 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_U, u); bufferData.put(bufferDataOffset + 3 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_V, v2); bufferData.put(bufferDataOffset + 4 * SpriteBatch.VERTEX_SIZE + SpriteBatch.VERTEX_INDEX_X, x2); bufferData.put(bufferDataOffset + 4 * SpriteBatch.VERTEX_SIZE + SpriteBatch.VERTEX_INDEX_Y, y2); bufferData.put(bufferDataOffset + 4 * SpriteBatch.VERTEX_SIZE + SpriteBatch.COLOR_INDEX, pColorABGRPackedInt); - bufferData.put(bufferDataOffset + 4 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_U, u); + bufferData.put(bufferDataOffset + 4 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_U, u2); bufferData.put(bufferDataOffset + 4 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_V, v); bufferData.put(bufferDataOffset + 5 * SpriteBatch.VERTEX_SIZE + SpriteBatch.VERTEX_INDEX_X, x4); bufferData.put(bufferDataOffset + 5 * SpriteBatch.VERTEX_SIZE + SpriteBatch.VERTEX_INDEX_Y, y4); bufferData.put(bufferDataOffset + 5 * SpriteBatch.VERTEX_SIZE + SpriteBatch.COLOR_INDEX, pColorABGRPackedInt); - bufferData.put(bufferDataOffset + 5 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_U, u); + bufferData.put(bufferDataOffset + 5 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_U, u2); bufferData.put(bufferDataOffset + 5 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_V, v2); } else { bufferData.put(bufferDataOffset + 0 * SpriteBatch.VERTEX_SIZE + SpriteBatch.VERTEX_INDEX_X, x1); bufferData.put(bufferDataOffset + 0 * SpriteBatch.VERTEX_SIZE + SpriteBatch.VERTEX_INDEX_Y, y1); bufferData.put(bufferDataOffset + 0 * SpriteBatch.VERTEX_SIZE + SpriteBatch.COLOR_INDEX, pColorABGRPackedInt); bufferData.put(bufferDataOffset + 0 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_U, u); - bufferData.put(bufferDataOffset + 0 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_V, v); + bufferData.put(bufferDataOffset + 0 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_V, v2); bufferData.put(bufferDataOffset + 1 * SpriteBatch.VERTEX_SIZE + SpriteBatch.VERTEX_INDEX_X, x2); bufferData.put(bufferDataOffset + 1 * SpriteBatch.VERTEX_SIZE + SpriteBatch.VERTEX_INDEX_Y, y2); bufferData.put(bufferDataOffset + 1 * SpriteBatch.VERTEX_SIZE + SpriteBatch.COLOR_INDEX, pColorABGRPackedInt); bufferData.put(bufferDataOffset + 1 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_U, u); - bufferData.put(bufferDataOffset + 1 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_V, v2); + bufferData.put(bufferDataOffset + 1 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_V, v); bufferData.put(bufferDataOffset + 2 * SpriteBatch.VERTEX_SIZE + SpriteBatch.VERTEX_INDEX_X, x3); bufferData.put(bufferDataOffset + 2 * SpriteBatch.VERTEX_SIZE + SpriteBatch.VERTEX_INDEX_Y, y3); bufferData.put(bufferDataOffset + 2 * SpriteBatch.VERTEX_SIZE + SpriteBatch.COLOR_INDEX, pColorABGRPackedInt); bufferData.put(bufferDataOffset + 2 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_U, u2); - bufferData.put(bufferDataOffset + 2 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_V, v); + bufferData.put(bufferDataOffset + 2 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_V, v2); bufferData.put(bufferDataOffset + 3 * SpriteBatch.VERTEX_SIZE + SpriteBatch.VERTEX_INDEX_X, x3); bufferData.put(bufferDataOffset + 3 * SpriteBatch.VERTEX_SIZE + SpriteBatch.VERTEX_INDEX_Y, y3); bufferData.put(bufferDataOffset + 3 * SpriteBatch.VERTEX_SIZE + SpriteBatch.COLOR_INDEX, pColorABGRPackedInt); bufferData.put(bufferDataOffset + 3 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_U, u2); - bufferData.put(bufferDataOffset + 3 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_V, v); + bufferData.put(bufferDataOffset + 3 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_V, v2); bufferData.put(bufferDataOffset + 4 * SpriteBatch.VERTEX_SIZE + SpriteBatch.VERTEX_INDEX_X, x2); bufferData.put(bufferDataOffset + 4 * SpriteBatch.VERTEX_SIZE + SpriteBatch.VERTEX_INDEX_Y, y2); bufferData.put(bufferDataOffset + 4 * SpriteBatch.VERTEX_SIZE + SpriteBatch.COLOR_INDEX, pColorABGRPackedInt); bufferData.put(bufferDataOffset + 4 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_U, u); - bufferData.put(bufferDataOffset + 4 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_V, v2); + bufferData.put(bufferDataOffset + 4 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_V, v); bufferData.put(bufferDataOffset + 5 * SpriteBatch.VERTEX_SIZE + SpriteBatch.VERTEX_INDEX_X, x4); bufferData.put(bufferDataOffset + 5 * SpriteBatch.VERTEX_SIZE + SpriteBatch.VERTEX_INDEX_Y, y4); bufferData.put(bufferDataOffset + 5 * SpriteBatch.VERTEX_SIZE + SpriteBatch.COLOR_INDEX, pColorABGRPackedInt); bufferData.put(bufferDataOffset + 5 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_U, u2); - bufferData.put(bufferDataOffset + 5 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_V, v2); + bufferData.put(bufferDataOffset + 5 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_V, v); } this.mBufferDataOffset += SpriteBatch.SPRITE_SIZE; @@ -172,78 +172,78 @@ public void addWithPackedColor(final ITextureRegion pTextureRegion, final float final float u2 = pTextureRegion.getU2(); final float v2 = pTextureRegion.getV2(); - if(pTextureRegion.isRotated()) { + if (pTextureRegion.isRotated()) { bufferData.put(bufferDataOffset + 0 * SpriteBatch.VERTEX_SIZE + SpriteBatch.VERTEX_INDEX_X, x1); bufferData.put(bufferDataOffset + 0 * SpriteBatch.VERTEX_SIZE + SpriteBatch.VERTEX_INDEX_Y, y1); bufferData.put(bufferDataOffset + 0 * SpriteBatch.VERTEX_SIZE + SpriteBatch.COLOR_INDEX, pColorABGRPackedInt); - bufferData.put(bufferDataOffset + 0 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_U, u2); + bufferData.put(bufferDataOffset + 0 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_U, u); bufferData.put(bufferDataOffset + 0 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_V, v); bufferData.put(bufferDataOffset + 1 * SpriteBatch.VERTEX_SIZE + SpriteBatch.VERTEX_INDEX_X, x1); bufferData.put(bufferDataOffset + 1 * SpriteBatch.VERTEX_SIZE + SpriteBatch.VERTEX_INDEX_Y, y2); bufferData.put(bufferDataOffset + 1 * SpriteBatch.VERTEX_SIZE + SpriteBatch.COLOR_INDEX, pColorABGRPackedInt); - bufferData.put(bufferDataOffset + 1 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_U, u); + bufferData.put(bufferDataOffset + 1 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_U, u2); bufferData.put(bufferDataOffset + 1 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_V, v); bufferData.put(bufferDataOffset + 2 * SpriteBatch.VERTEX_SIZE + SpriteBatch.VERTEX_INDEX_X, x2); bufferData.put(bufferDataOffset + 2 * SpriteBatch.VERTEX_SIZE + SpriteBatch.VERTEX_INDEX_Y, y1); bufferData.put(bufferDataOffset + 2 * SpriteBatch.VERTEX_SIZE + SpriteBatch.COLOR_INDEX, pColorABGRPackedInt); - bufferData.put(bufferDataOffset + 2 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_U, u2); + bufferData.put(bufferDataOffset + 2 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_U, u); bufferData.put(bufferDataOffset + 2 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_V, v2); bufferData.put(bufferDataOffset + 3 * SpriteBatch.VERTEX_SIZE + SpriteBatch.VERTEX_INDEX_X, x2); bufferData.put(bufferDataOffset + 3 * SpriteBatch.VERTEX_SIZE + SpriteBatch.VERTEX_INDEX_Y, y1); bufferData.put(bufferDataOffset + 3 * SpriteBatch.VERTEX_SIZE + SpriteBatch.COLOR_INDEX, pColorABGRPackedInt); - bufferData.put(bufferDataOffset + 3 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_U, u2); + bufferData.put(bufferDataOffset + 3 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_U, u); bufferData.put(bufferDataOffset + 3 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_V, v2); bufferData.put(bufferDataOffset + 4 * SpriteBatch.VERTEX_SIZE + SpriteBatch.VERTEX_INDEX_X, x1); bufferData.put(bufferDataOffset + 4 * SpriteBatch.VERTEX_SIZE + SpriteBatch.VERTEX_INDEX_Y, y2); bufferData.put(bufferDataOffset + 4 * SpriteBatch.VERTEX_SIZE + SpriteBatch.COLOR_INDEX, pColorABGRPackedInt); - bufferData.put(bufferDataOffset + 4 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_U, u); + bufferData.put(bufferDataOffset + 4 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_U, u2); bufferData.put(bufferDataOffset + 4 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_V, v); bufferData.put(bufferDataOffset + 5 * SpriteBatch.VERTEX_SIZE + SpriteBatch.VERTEX_INDEX_X, x2); bufferData.put(bufferDataOffset + 5 * SpriteBatch.VERTEX_SIZE + SpriteBatch.VERTEX_INDEX_Y, y2); bufferData.put(bufferDataOffset + 5 * SpriteBatch.VERTEX_SIZE + SpriteBatch.COLOR_INDEX, pColorABGRPackedInt); - bufferData.put(bufferDataOffset + 5 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_U, u); + bufferData.put(bufferDataOffset + 5 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_U, u2); bufferData.put(bufferDataOffset + 5 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_V, v2); } else { bufferData.put(bufferDataOffset + 0 * SpriteBatch.VERTEX_SIZE + SpriteBatch.VERTEX_INDEX_X, x1); bufferData.put(bufferDataOffset + 0 * SpriteBatch.VERTEX_SIZE + SpriteBatch.VERTEX_INDEX_Y, y1); bufferData.put(bufferDataOffset + 0 * SpriteBatch.VERTEX_SIZE + SpriteBatch.COLOR_INDEX, pColorABGRPackedInt); bufferData.put(bufferDataOffset + 0 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_U, u); - bufferData.put(bufferDataOffset + 0 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_V, v); + bufferData.put(bufferDataOffset + 0 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_V, v2); bufferData.put(bufferDataOffset + 1 * SpriteBatch.VERTEX_SIZE + SpriteBatch.VERTEX_INDEX_X, x1); bufferData.put(bufferDataOffset + 1 * SpriteBatch.VERTEX_SIZE + SpriteBatch.VERTEX_INDEX_Y, y2); bufferData.put(bufferDataOffset + 1 * SpriteBatch.VERTEX_SIZE + SpriteBatch.COLOR_INDEX, pColorABGRPackedInt); bufferData.put(bufferDataOffset + 1 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_U, u); - bufferData.put(bufferDataOffset + 1 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_V, v2); + bufferData.put(bufferDataOffset + 1 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_V, v); bufferData.put(bufferDataOffset + 2 * SpriteBatch.VERTEX_SIZE + SpriteBatch.VERTEX_INDEX_X, x2); bufferData.put(bufferDataOffset + 2 * SpriteBatch.VERTEX_SIZE + SpriteBatch.VERTEX_INDEX_Y, y1); bufferData.put(bufferDataOffset + 2 * SpriteBatch.VERTEX_SIZE + SpriteBatch.COLOR_INDEX, pColorABGRPackedInt); bufferData.put(bufferDataOffset + 2 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_U, u2); - bufferData.put(bufferDataOffset + 2 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_V, v); + bufferData.put(bufferDataOffset + 2 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_V, v2); bufferData.put(bufferDataOffset + 3 * SpriteBatch.VERTEX_SIZE + SpriteBatch.VERTEX_INDEX_X, x2); bufferData.put(bufferDataOffset + 3 * SpriteBatch.VERTEX_SIZE + SpriteBatch.VERTEX_INDEX_Y, y1); bufferData.put(bufferDataOffset + 3 * SpriteBatch.VERTEX_SIZE + SpriteBatch.COLOR_INDEX, pColorABGRPackedInt); bufferData.put(bufferDataOffset + 3 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_U, u2); - bufferData.put(bufferDataOffset + 3 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_V, v); + bufferData.put(bufferDataOffset + 3 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_V, v2); bufferData.put(bufferDataOffset + 4 * SpriteBatch.VERTEX_SIZE + SpriteBatch.VERTEX_INDEX_X, x1); bufferData.put(bufferDataOffset + 4 * SpriteBatch.VERTEX_SIZE + SpriteBatch.VERTEX_INDEX_Y, y2); bufferData.put(bufferDataOffset + 4 * SpriteBatch.VERTEX_SIZE + SpriteBatch.COLOR_INDEX, pColorABGRPackedInt); bufferData.put(bufferDataOffset + 4 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_U, u); - bufferData.put(bufferDataOffset + 4 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_V, v2); + bufferData.put(bufferDataOffset + 4 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_V, v); bufferData.put(bufferDataOffset + 5 * SpriteBatch.VERTEX_SIZE + SpriteBatch.VERTEX_INDEX_X, x2); bufferData.put(bufferDataOffset + 5 * SpriteBatch.VERTEX_SIZE + SpriteBatch.VERTEX_INDEX_Y, y2); bufferData.put(bufferDataOffset + 5 * SpriteBatch.VERTEX_SIZE + SpriteBatch.COLOR_INDEX, pColorABGRPackedInt); bufferData.put(bufferDataOffset + 5 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_U, u2); - bufferData.put(bufferDataOffset + 5 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_V, v2); + bufferData.put(bufferDataOffset + 5 * SpriteBatch.VERTEX_SIZE + SpriteBatch.TEXTURECOORDINATES_INDEX_V, v); } this.mBufferDataOffset += SpriteBatch.SPRITE_SIZE; diff --git a/src/org/andengine/entity/sprite/vbo/HighPerformanceDiamondSpriteVertexBufferObject.java b/src/org/andengine/entity/sprite/vbo/HighPerformanceDiamondSpriteVertexBufferObject.java index 943817973..a3efc4c7c 100644 --- a/src/org/andengine/entity/sprite/vbo/HighPerformanceDiamondSpriteVertexBufferObject.java +++ b/src/org/andengine/entity/sprite/vbo/HighPerformanceDiamondSpriteVertexBufferObject.java @@ -7,7 +7,7 @@ import org.andengine.opengl.vbo.attribute.VertexBufferObjectAttributes; /** - * (c) Zynga 2012 + * (c) 2012 Zynga Inc. * * @author Nicolas Gramlich * @since 18:43:22 - 28.03.2012 @@ -41,25 +41,23 @@ public HighPerformanceDiamondSpriteVertexBufferObject(final VertexBufferObjectMa public void onUpdateVertices(final Sprite pSprite) { final float[] bufferData = this.mBufferData; - final float x = 0; - final float y = 0; - final float x2 = pSprite.getWidth(); // TODO Optimize with field access? - final float y2 = pSprite.getHeight(); // TODO Optimize with field access? + final float width = pSprite.getWidth(); // TODO Optimize with field access? + final float height = pSprite.getHeight(); // TODO Optimize with field access? - final float xCenter = (x + x2) * 0.5f; - final float yCenter = (y + y2) * 0.5f; + final float halfWidth = width * 0.5f; + final float halfHeight = height * 0.5f; - bufferData[0 * Sprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_X] = x; - bufferData[0 * Sprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_Y] = yCenter; + bufferData[0 * Sprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_X] = halfWidth; + bufferData[0 * Sprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_Y] = 0; - bufferData[1 * Sprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_X] = xCenter; - bufferData[1 * Sprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_Y] = y2; + bufferData[1 * Sprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_X] = 0; + bufferData[1 * Sprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_Y] = halfHeight; - bufferData[2 * Sprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_X] = xCenter; - bufferData[2 * Sprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_Y] = y; + bufferData[2 * Sprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_X] = width; + bufferData[2 * Sprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_Y] = halfHeight; - bufferData[3 * Sprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_X] = x2; - bufferData[3 * Sprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_Y] = yCenter; + bufferData[3 * Sprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_X] = halfWidth; + bufferData[3 * Sprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_Y] = height; this.setDirtyOnHardware(); } @@ -75,8 +73,8 @@ public void onUpdateTextureCoordinates(final Sprite pSprite) { final float u2; final float v2; - if(pSprite.isFlippedVertical()) { // TODO Optimize with field access? - if(pSprite.isFlippedHorizontal()) { // TODO Optimize with field access? + if (pSprite.isFlippedVertical()) { // TODO Optimize with field access? + if (pSprite.isFlippedHorizontal()) { // TODO Optimize with field access? u = textureRegion.getU2(); u2 = textureRegion.getU(); v = textureRegion.getV2(); @@ -88,7 +86,7 @@ public void onUpdateTextureCoordinates(final Sprite pSprite) { v2 = textureRegion.getV(); } } else { - if(pSprite.isFlippedHorizontal()) { // TODO Optimize with field access? + if (pSprite.isFlippedHorizontal()) { // TODO Optimize with field access? u = textureRegion.getU2(); u2 = textureRegion.getU(); v = textureRegion.getV(); @@ -104,9 +102,21 @@ public void onUpdateTextureCoordinates(final Sprite pSprite) { final float uCenter = (u + u2) * 0.5f; final float vCenter = (v + v2) * 0.5f; - if(textureRegion.isRotated()) { + if (textureRegion.isRotated()) { + bufferData[0 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_U] = u2; + bufferData[0 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_V] = vCenter; + + bufferData[1 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_U] = uCenter; + bufferData[1 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_V] = v; + + bufferData[2 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_U] = uCenter; + bufferData[2 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_V] = v2; + + bufferData[3 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_U] = u; + bufferData[3 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_V] = vCenter; + } else { bufferData[0 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_U] = uCenter; - bufferData[0 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_V] = v; + bufferData[0 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_V] = v2; bufferData[1 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_U] = u; bufferData[1 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_V] = vCenter; @@ -115,19 +125,7 @@ public void onUpdateTextureCoordinates(final Sprite pSprite) { bufferData[2 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_V] = vCenter; bufferData[3 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_U] = uCenter; - bufferData[3 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_V] = v2; - } else { - bufferData[0 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_U] = u; - bufferData[0 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_V] = vCenter; - - bufferData[1 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_U] = uCenter; - bufferData[1 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_V] = v2; - - bufferData[2 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_U] = uCenter; - bufferData[2 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_V] = v; - - bufferData[3 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_U] = u2; - bufferData[3 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_V] = vCenter; + bufferData[3 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_V] = v; } this.setDirtyOnHardware(); diff --git a/src/org/andengine/entity/sprite/vbo/HighPerformanceSpriteVertexBufferObject.java b/src/org/andengine/entity/sprite/vbo/HighPerformanceSpriteVertexBufferObject.java index 2e0ba3dde..300054da3 100644 --- a/src/org/andengine/entity/sprite/vbo/HighPerformanceSpriteVertexBufferObject.java +++ b/src/org/andengine/entity/sprite/vbo/HighPerformanceSpriteVertexBufferObject.java @@ -8,7 +8,7 @@ import org.andengine.opengl.vbo.attribute.VertexBufferObjectAttributes; /** - * (c) Zynga 2012 + * (c) 2012 Zynga Inc. * * @author Nicolas Gramlich * @since 18:40:47 - 28.03.2012 @@ -56,22 +56,20 @@ public void onUpdateColor(final Sprite pSprite) { public void onUpdateVertices(final Sprite pSprite) { final float[] bufferData = this.mBufferData; - final float x = 0; - final float y = 0; - final float x2 = pSprite.getWidth(); // TODO Optimize with field access? - final float y2 = pSprite.getHeight(); // TODO Optimize with field access? + final float width = pSprite.getWidth(); // TODO Optimize with field access? + final float height = pSprite.getHeight(); // TODO Optimize with field access? - bufferData[0 * Sprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_X] = x; - bufferData[0 * Sprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_Y] = y; + bufferData[0 * Sprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_X] = 0; + bufferData[0 * Sprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_Y] = 0; - bufferData[1 * Sprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_X] = x; - bufferData[1 * Sprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_Y] = y2; + bufferData[1 * Sprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_X] = 0; + bufferData[1 * Sprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_Y] = height; - bufferData[2 * Sprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_X] = x2; - bufferData[2 * Sprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_Y] = y; + bufferData[2 * Sprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_X] = width; + bufferData[2 * Sprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_Y] = 0; - bufferData[3 * Sprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_X] = x2; - bufferData[3 * Sprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_Y] = y2; + bufferData[3 * Sprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_X] = width; + bufferData[3 * Sprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_Y] = height; this.setDirtyOnHardware(); } @@ -87,8 +85,8 @@ public void onUpdateTextureCoordinates(final Sprite pSprite) { final float u2; final float v2; - if(pSprite.isFlippedVertical()) { // TODO Optimize with field access? - if(pSprite.isFlippedHorizontal()) { // TODO Optimize with field access? + if (pSprite.isFlippedVertical()) { // TODO Optimize with field access? + if (pSprite.isFlippedHorizontal()) { // TODO Optimize with field access? u = textureRegion.getU2(); u2 = textureRegion.getU(); v = textureRegion.getV2(); @@ -100,7 +98,7 @@ public void onUpdateTextureCoordinates(final Sprite pSprite) { v2 = textureRegion.getV(); } } else { - if(pSprite.isFlippedHorizontal()) { // TODO Optimize with field access? + if (pSprite.isFlippedHorizontal()) { // TODO Optimize with field access? u = textureRegion.getU2(); u2 = textureRegion.getU(); v = textureRegion.getV(); @@ -113,30 +111,30 @@ public void onUpdateTextureCoordinates(final Sprite pSprite) { } } - if(textureRegion.isRotated()) { - bufferData[0 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_U] = u2; + if (textureRegion.isRotated()) { + bufferData[0 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_U] = u; bufferData[0 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_V] = v; - bufferData[1 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_U] = u; + bufferData[1 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_U] = u2; bufferData[1 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_V] = v; - bufferData[2 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_U] = u2; + bufferData[2 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_U] = u; bufferData[2 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_V] = v2; - bufferData[3 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_U] = u; + bufferData[3 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_U] = u2; bufferData[3 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_V] = v2; } else { bufferData[0 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_U] = u; - bufferData[0 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_V] = v; + bufferData[0 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_V] = v2; bufferData[1 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_U] = u; - bufferData[1 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_V] = v2; + bufferData[1 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_V] = v; bufferData[2 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_U] = u2; - bufferData[2 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_V] = v; + bufferData[2 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_V] = v2; bufferData[3 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_U] = u2; - bufferData[3 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_V] = v2; + bufferData[3 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_V] = v; } this.setDirtyOnHardware(); diff --git a/src/org/andengine/entity/sprite/vbo/HighPerformanceTiledSpriteVertexBufferObject.java b/src/org/andengine/entity/sprite/vbo/HighPerformanceTiledSpriteVertexBufferObject.java index 6a536496c..9cc8dfc7a 100644 --- a/src/org/andengine/entity/sprite/vbo/HighPerformanceTiledSpriteVertexBufferObject.java +++ b/src/org/andengine/entity/sprite/vbo/HighPerformanceTiledSpriteVertexBufferObject.java @@ -9,7 +9,7 @@ import org.andengine.opengl.vbo.attribute.VertexBufferObjectAttributes; /** - * (c) Zynga 2012 + * (c) 2012 Zynga Inc. * * @author Nicolas Gramlich * @since 18:39:06 - 28.03.2012 @@ -47,7 +47,7 @@ public void onUpdateColor(final TiledSprite pTiledSprite) { final int tileCount = pTiledSprite.getTileCount(); int bufferDataOffset = 0; - for(int i = 0; i < tileCount; i++) { + for (int i = 0; i < tileCount; i++) { bufferData[bufferDataOffset + 0 * TiledSprite.VERTEX_SIZE + Sprite.COLOR_INDEX] = packedColor; bufferData[bufferDataOffset + 1 * TiledSprite.VERTEX_SIZE + Sprite.COLOR_INDEX] = packedColor; bufferData[bufferDataOffset + 2 * TiledSprite.VERTEX_SIZE + Sprite.COLOR_INDEX] = packedColor; @@ -65,31 +65,29 @@ public void onUpdateColor(final TiledSprite pTiledSprite) { public void onUpdateVertices(final TiledSprite pTiledSprite) { final float[] bufferData = this.mBufferData; - final float x = 0; - final float y = 0; - final float x2 = pTiledSprite.getWidth(); // TODO Optimize with field access? - final float y2 = pTiledSprite.getHeight(); // TODO Optimize with field access? + final float width = pTiledSprite.getWidth(); // TODO Optimize with field access? + final float height = pTiledSprite.getHeight(); // TODO Optimize with field access? final int tileCount = pTiledSprite.getTileCount(); int bufferDataOffset = 0; - for(int i = 0; i < tileCount; i++) { - bufferData[bufferDataOffset + 0 * TiledSprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_X] = x; - bufferData[bufferDataOffset + 0 * TiledSprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_Y] = y; + for (int i = 0; i < tileCount; i++) { + bufferData[bufferDataOffset + 0 * TiledSprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_X] = 0; + bufferData[bufferDataOffset + 0 * TiledSprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_Y] = 0; - bufferData[bufferDataOffset + 1 * TiledSprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_X] = x; - bufferData[bufferDataOffset + 1 * TiledSprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_Y] = y2; + bufferData[bufferDataOffset + 1 * TiledSprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_X] = 0; + bufferData[bufferDataOffset + 1 * TiledSprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_Y] = height; - bufferData[bufferDataOffset + 2 * TiledSprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_X] = x2; - bufferData[bufferDataOffset + 2 * TiledSprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_Y] = y; + bufferData[bufferDataOffset + 2 * TiledSprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_X] = width; + bufferData[bufferDataOffset + 2 * TiledSprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_Y] = 0; - bufferData[bufferDataOffset + 3 * TiledSprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_X] = x2; - bufferData[bufferDataOffset + 3 * TiledSprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_Y] = y; + bufferData[bufferDataOffset + 3 * TiledSprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_X] = width; + bufferData[bufferDataOffset + 3 * TiledSprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_Y] = 0; - bufferData[bufferDataOffset + 4 * TiledSprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_X] = x; - bufferData[bufferDataOffset + 4 * TiledSprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_Y] = y2; + bufferData[bufferDataOffset + 4 * TiledSprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_X] = 0; + bufferData[bufferDataOffset + 4 * TiledSprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_Y] = height; - bufferData[bufferDataOffset + 5 * TiledSprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_X] = x2; - bufferData[bufferDataOffset + 5 * TiledSprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_Y] = y2; + bufferData[bufferDataOffset + 5 * TiledSprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_X] = width; + bufferData[bufferDataOffset + 5 * TiledSprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_Y] = height; bufferDataOffset += TiledSprite.TILEDSPRITE_SIZE; } @@ -105,7 +103,7 @@ public void onUpdateTextureCoordinates(final TiledSprite pTiledSprite) { final int tileCount = pTiledSprite.getTileCount(); int bufferDataOffset = 0; - for(int i = 0; i < tileCount; i++) { + for (int i = 0; i < tileCount; i++) { final ITextureRegion textureRegion = tiledTextureRegion.getTextureRegion(i); final float u; @@ -113,8 +111,8 @@ public void onUpdateTextureCoordinates(final TiledSprite pTiledSprite) { final float u2; final float v2; - if(pTiledSprite.isFlippedVertical()) { // TODO Optimize with field access? - if(pTiledSprite.isFlippedHorizontal()) { // TODO Optimize with field access? + if (pTiledSprite.isFlippedVertical()) { // TODO Optimize with field access? + if (pTiledSprite.isFlippedHorizontal()) { // TODO Optimize with field access? u = textureRegion.getU2(); u2 = textureRegion.getU(); v = textureRegion.getV2(); @@ -126,7 +124,7 @@ public void onUpdateTextureCoordinates(final TiledSprite pTiledSprite) { v2 = textureRegion.getV(); } } else { - if(pTiledSprite.isFlippedHorizontal()) { // TODO Optimize with field access? + if (pTiledSprite.isFlippedHorizontal()) { // TODO Optimize with field access? u = textureRegion.getU2(); u2 = textureRegion.getU(); v = textureRegion.getV(); @@ -139,42 +137,42 @@ public void onUpdateTextureCoordinates(final TiledSprite pTiledSprite) { } } - if(textureRegion.isRotated()) { - bufferData[bufferDataOffset + 0 * TiledSprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_U] = u2; + if (textureRegion.isRotated()) { + bufferData[bufferDataOffset + 0 * TiledSprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_U] = u; bufferData[bufferDataOffset + 0 * TiledSprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_V] = v; - bufferData[bufferDataOffset + 1 * TiledSprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_U] = u; + bufferData[bufferDataOffset + 1 * TiledSprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_U] = u2; bufferData[bufferDataOffset + 1 * TiledSprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_V] = v; - bufferData[bufferDataOffset + 2 * TiledSprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_U] = u2; + bufferData[bufferDataOffset + 2 * TiledSprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_U] = u; bufferData[bufferDataOffset + 2 * TiledSprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_V] = v2; - bufferData[bufferDataOffset + 3 * TiledSprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_U] = u2; + bufferData[bufferDataOffset + 3 * TiledSprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_U] = u; bufferData[bufferDataOffset + 3 * TiledSprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_V] = v2; - bufferData[bufferDataOffset + 4 * TiledSprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_U] = u; + bufferData[bufferDataOffset + 4 * TiledSprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_U] = u2; bufferData[bufferDataOffset + 4 * TiledSprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_V] = v; - bufferData[bufferDataOffset + 5 * TiledSprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_U] = u; + bufferData[bufferDataOffset + 5 * TiledSprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_U] = u2; bufferData[bufferDataOffset + 5 * TiledSprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_V] = v2; } else { bufferData[bufferDataOffset + 0 * TiledSprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_U] = u; - bufferData[bufferDataOffset + 0 * TiledSprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_V] = v; + bufferData[bufferDataOffset + 0 * TiledSprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_V] = v2; bufferData[bufferDataOffset + 1 * TiledSprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_U] = u; - bufferData[bufferDataOffset + 1 * TiledSprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_V] = v2; + bufferData[bufferDataOffset + 1 * TiledSprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_V] = v; bufferData[bufferDataOffset + 2 * TiledSprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_U] = u2; - bufferData[bufferDataOffset + 2 * TiledSprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_V] = v; + bufferData[bufferDataOffset + 2 * TiledSprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_V] = v2; bufferData[bufferDataOffset + 3 * TiledSprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_U] = u2; - bufferData[bufferDataOffset + 3 * TiledSprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_V] = v; + bufferData[bufferDataOffset + 3 * TiledSprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_V] = v2; bufferData[bufferDataOffset + 4 * TiledSprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_U] = u; - bufferData[bufferDataOffset + 4 * TiledSprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_V] = v2; + bufferData[bufferDataOffset + 4 * TiledSprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_V] = v; bufferData[bufferDataOffset + 5 * TiledSprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_U] = u2; - bufferData[bufferDataOffset + 5 * TiledSprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_V] = v2; + bufferData[bufferDataOffset + 5 * TiledSprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_V] = v; } bufferDataOffset += TiledSprite.TILEDSPRITE_SIZE; diff --git a/src/org/andengine/entity/sprite/vbo/HighPerformanceUncoloredSpriteVertexBufferObject.java b/src/org/andengine/entity/sprite/vbo/HighPerformanceUncoloredSpriteVertexBufferObject.java index bab9b28a0..b16a34438 100644 --- a/src/org/andengine/entity/sprite/vbo/HighPerformanceUncoloredSpriteVertexBufferObject.java +++ b/src/org/andengine/entity/sprite/vbo/HighPerformanceUncoloredSpriteVertexBufferObject.java @@ -8,7 +8,7 @@ import org.andengine.opengl.vbo.attribute.VertexBufferObjectAttributes; /** - * (c) Zynga 2012 + * (c) 2012 Zynga Inc. * * @author Nicolas Gramlich * @since 18:37:49 - 28.03.2012 @@ -38,26 +38,29 @@ public HighPerformanceUncoloredSpriteVertexBufferObject(final VertexBufferObject // Methods for/from SuperClass/Interfaces // =========================================================== + @Override + public void onUpdateColor(final Sprite pSprite) { + /* Nothing. */ + } + @Override public void onUpdateVertices(final Sprite pSprite) { final float[] bufferData = this.mBufferData; - final float x = 0; - final float y = 0; - final float x2 = pSprite.getWidth(); // TODO Optimize with field access? - final float y2 = pSprite.getHeight(); // TODO Optimize with field access? + final float width = pSprite.getWidth(); // TODO Optimize with field access? + final float height = pSprite.getHeight(); // TODO Optimize with field access? - bufferData[0 * UncoloredSprite.VERTEX_SIZE + UncoloredSprite.VERTEX_INDEX_X] = x; - bufferData[0 * UncoloredSprite.VERTEX_SIZE + UncoloredSprite.VERTEX_INDEX_Y] = y; + bufferData[0 * UncoloredSprite.VERTEX_SIZE + UncoloredSprite.VERTEX_INDEX_X] = 0; + bufferData[0 * UncoloredSprite.VERTEX_SIZE + UncoloredSprite.VERTEX_INDEX_Y] = 0; - bufferData[1 * UncoloredSprite.VERTEX_SIZE + UncoloredSprite.VERTEX_INDEX_X] = x; - bufferData[1 * UncoloredSprite.VERTEX_SIZE + UncoloredSprite.VERTEX_INDEX_Y] = y2; + bufferData[1 * UncoloredSprite.VERTEX_SIZE + UncoloredSprite.VERTEX_INDEX_X] = 0; + bufferData[1 * UncoloredSprite.VERTEX_SIZE + UncoloredSprite.VERTEX_INDEX_Y] = height; - bufferData[2 * UncoloredSprite.VERTEX_SIZE + UncoloredSprite.VERTEX_INDEX_X] = x2; - bufferData[2 * UncoloredSprite.VERTEX_SIZE + UncoloredSprite.VERTEX_INDEX_Y] = y; + bufferData[2 * UncoloredSprite.VERTEX_SIZE + UncoloredSprite.VERTEX_INDEX_X] = width; + bufferData[2 * UncoloredSprite.VERTEX_SIZE + UncoloredSprite.VERTEX_INDEX_Y] = 0; - bufferData[3 * UncoloredSprite.VERTEX_SIZE + UncoloredSprite.VERTEX_INDEX_X] = x2; - bufferData[3 * UncoloredSprite.VERTEX_SIZE + UncoloredSprite.VERTEX_INDEX_Y] = y2; + bufferData[3 * UncoloredSprite.VERTEX_SIZE + UncoloredSprite.VERTEX_INDEX_X] = width; + bufferData[3 * UncoloredSprite.VERTEX_SIZE + UncoloredSprite.VERTEX_INDEX_Y] = height; this.setDirtyOnHardware(); } @@ -73,8 +76,8 @@ public void onUpdateTextureCoordinates(final Sprite pSprite) { final float u2; final float v2; - if(pSprite.isFlippedVertical()) { // TODO Optimize with field access? - if(pSprite.isFlippedHorizontal()) { // TODO Optimize with field access? + if (pSprite.isFlippedVertical()) { // TODO Optimize with field access? + if (pSprite.isFlippedHorizontal()) { // TODO Optimize with field access? u = textureRegion.getU2(); u2 = textureRegion.getU(); v = textureRegion.getV2(); @@ -86,7 +89,7 @@ public void onUpdateTextureCoordinates(final Sprite pSprite) { v2 = textureRegion.getV(); } } else { - if(pSprite.isFlippedHorizontal()) { // TODO Optimize with field access? + if (pSprite.isFlippedHorizontal()) { // TODO Optimize with field access? u = textureRegion.getU2(); u2 = textureRegion.getU(); v = textureRegion.getV(); @@ -99,30 +102,30 @@ public void onUpdateTextureCoordinates(final Sprite pSprite) { } } - if(textureRegion.isRotated()) { - bufferData[0 * UncoloredSprite.VERTEX_SIZE + UncoloredSprite.TEXTURECOORDINATES_INDEX_U] = u2; + if (textureRegion.isRotated()) { + bufferData[0 * UncoloredSprite.VERTEX_SIZE + UncoloredSprite.TEXTURECOORDINATES_INDEX_U] = u; bufferData[0 * UncoloredSprite.VERTEX_SIZE + UncoloredSprite.TEXTURECOORDINATES_INDEX_V] = v; - bufferData[1 * UncoloredSprite.VERTEX_SIZE + UncoloredSprite.TEXTURECOORDINATES_INDEX_U] = u; + bufferData[1 * UncoloredSprite.VERTEX_SIZE + UncoloredSprite.TEXTURECOORDINATES_INDEX_U] = u2; bufferData[1 * UncoloredSprite.VERTEX_SIZE + UncoloredSprite.TEXTURECOORDINATES_INDEX_V] = v; - bufferData[2 * UncoloredSprite.VERTEX_SIZE + UncoloredSprite.TEXTURECOORDINATES_INDEX_U] = u2; + bufferData[2 * UncoloredSprite.VERTEX_SIZE + UncoloredSprite.TEXTURECOORDINATES_INDEX_U] = u; bufferData[2 * UncoloredSprite.VERTEX_SIZE + UncoloredSprite.TEXTURECOORDINATES_INDEX_V] = v2; - bufferData[3 * UncoloredSprite.VERTEX_SIZE + UncoloredSprite.TEXTURECOORDINATES_INDEX_U] = u; + bufferData[3 * UncoloredSprite.VERTEX_SIZE + UncoloredSprite.TEXTURECOORDINATES_INDEX_U] = u2; bufferData[3 * UncoloredSprite.VERTEX_SIZE + UncoloredSprite.TEXTURECOORDINATES_INDEX_V] = v2; } else { bufferData[0 * UncoloredSprite.VERTEX_SIZE + UncoloredSprite.TEXTURECOORDINATES_INDEX_U] = u; - bufferData[0 * UncoloredSprite.VERTEX_SIZE + UncoloredSprite.TEXTURECOORDINATES_INDEX_V] = v; + bufferData[0 * UncoloredSprite.VERTEX_SIZE + UncoloredSprite.TEXTURECOORDINATES_INDEX_V] = v2; bufferData[1 * UncoloredSprite.VERTEX_SIZE + UncoloredSprite.TEXTURECOORDINATES_INDEX_U] = u; - bufferData[1 * UncoloredSprite.VERTEX_SIZE + UncoloredSprite.TEXTURECOORDINATES_INDEX_V] = v2; + bufferData[1 * UncoloredSprite.VERTEX_SIZE + UncoloredSprite.TEXTURECOORDINATES_INDEX_V] = v; bufferData[2 * UncoloredSprite.VERTEX_SIZE + UncoloredSprite.TEXTURECOORDINATES_INDEX_U] = u2; - bufferData[2 * UncoloredSprite.VERTEX_SIZE + UncoloredSprite.TEXTURECOORDINATES_INDEX_V] = v; + bufferData[2 * UncoloredSprite.VERTEX_SIZE + UncoloredSprite.TEXTURECOORDINATES_INDEX_V] = v2; bufferData[3 * UncoloredSprite.VERTEX_SIZE + UncoloredSprite.TEXTURECOORDINATES_INDEX_U] = u2; - bufferData[3 * UncoloredSprite.VERTEX_SIZE + UncoloredSprite.TEXTURECOORDINATES_INDEX_V] = v2; + bufferData[3 * UncoloredSprite.VERTEX_SIZE + UncoloredSprite.TEXTURECOORDINATES_INDEX_V] = v; } this.setDirtyOnHardware(); diff --git a/src/org/andengine/entity/sprite/vbo/HighPerformanceUniformColorSpriteVertexBufferObject.java b/src/org/andengine/entity/sprite/vbo/HighPerformanceUniformColorSpriteVertexBufferObject.java index 9ade337b7..993da081f 100644 --- a/src/org/andengine/entity/sprite/vbo/HighPerformanceUniformColorSpriteVertexBufferObject.java +++ b/src/org/andengine/entity/sprite/vbo/HighPerformanceUniformColorSpriteVertexBufferObject.java @@ -9,7 +9,7 @@ import org.andengine.opengl.vbo.attribute.VertexBufferObjectAttributes; /** - * (c) Zynga 2012 + * (c) 2012 Zynga Inc. * * @author Nicolas Gramlich * @since 18:37:01 - 28.03.2012 @@ -48,22 +48,20 @@ public void onUpdateColor(final Sprite pSprite) { public void onUpdateVertices(final Sprite pSprite) { final float[] bufferData = this.mBufferData; - final float x = 0; - final float y = 0; - final float x2 = pSprite.getWidth(); // TODO Optimize with field access? - final float y2 = pSprite.getHeight(); // TODO Optimize with field access? + final float width = pSprite.getWidth(); // TODO Optimize with field access? + final float height = pSprite.getHeight(); // TODO Optimize with field access? - bufferData[0 * UniformColorSprite.VERTEX_SIZE + UniformColorSprite.VERTEX_INDEX_X] = x; - bufferData[0 * UniformColorSprite.VERTEX_SIZE + UniformColorSprite.VERTEX_INDEX_Y] = y; + bufferData[0 * UniformColorSprite.VERTEX_SIZE + UniformColorSprite.VERTEX_INDEX_X] = 0; + bufferData[0 * UniformColorSprite.VERTEX_SIZE + UniformColorSprite.VERTEX_INDEX_Y] = 0; - bufferData[1 * UniformColorSprite.VERTEX_SIZE + UniformColorSprite.VERTEX_INDEX_X] = x; - bufferData[1 * UniformColorSprite.VERTEX_SIZE + UniformColorSprite.VERTEX_INDEX_Y] = y2; + bufferData[1 * UniformColorSprite.VERTEX_SIZE + UniformColorSprite.VERTEX_INDEX_X] = 0; + bufferData[1 * UniformColorSprite.VERTEX_SIZE + UniformColorSprite.VERTEX_INDEX_Y] = height; - bufferData[2 * UniformColorSprite.VERTEX_SIZE + UniformColorSprite.VERTEX_INDEX_X] = x2; - bufferData[2 * UniformColorSprite.VERTEX_SIZE + UniformColorSprite.VERTEX_INDEX_Y] = y; + bufferData[2 * UniformColorSprite.VERTEX_SIZE + UniformColorSprite.VERTEX_INDEX_X] = width; + bufferData[2 * UniformColorSprite.VERTEX_SIZE + UniformColorSprite.VERTEX_INDEX_Y] = 0; - bufferData[3 * UniformColorSprite.VERTEX_SIZE + UniformColorSprite.VERTEX_INDEX_X] = x2; - bufferData[3 * UniformColorSprite.VERTEX_SIZE + UniformColorSprite.VERTEX_INDEX_Y] = y2; + bufferData[3 * UniformColorSprite.VERTEX_SIZE + UniformColorSprite.VERTEX_INDEX_X] = width; + bufferData[3 * UniformColorSprite.VERTEX_SIZE + UniformColorSprite.VERTEX_INDEX_Y] = height; this.setDirtyOnHardware(); } @@ -79,8 +77,8 @@ public void onUpdateTextureCoordinates(final Sprite pSprite) { final float u2; final float v2; - if(pSprite.isFlippedVertical()) { // TODO Optimize with field access? - if(pSprite.isFlippedHorizontal()) { // TODO Optimize with field access? + if (pSprite.isFlippedVertical()) { // TODO Optimize with field access? + if (pSprite.isFlippedHorizontal()) { // TODO Optimize with field access? u = textureRegion.getU2(); u2 = textureRegion.getU(); v = textureRegion.getV2(); @@ -92,7 +90,7 @@ public void onUpdateTextureCoordinates(final Sprite pSprite) { v2 = textureRegion.getV(); } } else { - if(pSprite.isFlippedHorizontal()) { // TODO Optimize with field access? + if (pSprite.isFlippedHorizontal()) { // TODO Optimize with field access? u = textureRegion.getU2(); u2 = textureRegion.getU(); v = textureRegion.getV(); @@ -105,30 +103,30 @@ public void onUpdateTextureCoordinates(final Sprite pSprite) { } } - if(textureRegion.isRotated()) { - bufferData[0 * UniformColorSprite.VERTEX_SIZE + UniformColorSprite.TEXTURECOORDINATES_INDEX_U] = u2; + if (textureRegion.isRotated()) { + bufferData[0 * UniformColorSprite.VERTEX_SIZE + UniformColorSprite.TEXTURECOORDINATES_INDEX_U] = u; bufferData[0 * UniformColorSprite.VERTEX_SIZE + UniformColorSprite.TEXTURECOORDINATES_INDEX_V] = v; - bufferData[1 * UniformColorSprite.VERTEX_SIZE + UniformColorSprite.TEXTURECOORDINATES_INDEX_U] = u; + bufferData[1 * UniformColorSprite.VERTEX_SIZE + UniformColorSprite.TEXTURECOORDINATES_INDEX_U] = u2; bufferData[1 * UniformColorSprite.VERTEX_SIZE + UniformColorSprite.TEXTURECOORDINATES_INDEX_V] = v; - bufferData[2 * UniformColorSprite.VERTEX_SIZE + UniformColorSprite.TEXTURECOORDINATES_INDEX_U] = u2; + bufferData[2 * UniformColorSprite.VERTEX_SIZE + UniformColorSprite.TEXTURECOORDINATES_INDEX_U] = u; bufferData[2 * UniformColorSprite.VERTEX_SIZE + UniformColorSprite.TEXTURECOORDINATES_INDEX_V] = v2; - bufferData[3 * UniformColorSprite.VERTEX_SIZE + UniformColorSprite.TEXTURECOORDINATES_INDEX_U] = u; + bufferData[3 * UniformColorSprite.VERTEX_SIZE + UniformColorSprite.TEXTURECOORDINATES_INDEX_U] = u2; bufferData[3 * UniformColorSprite.VERTEX_SIZE + UniformColorSprite.TEXTURECOORDINATES_INDEX_V] = v2; } else { bufferData[0 * UniformColorSprite.VERTEX_SIZE + UniformColorSprite.TEXTURECOORDINATES_INDEX_U] = u; - bufferData[0 * UniformColorSprite.VERTEX_SIZE + UniformColorSprite.TEXTURECOORDINATES_INDEX_V] = v; + bufferData[0 * UniformColorSprite.VERTEX_SIZE + UniformColorSprite.TEXTURECOORDINATES_INDEX_V] = v2; bufferData[1 * UniformColorSprite.VERTEX_SIZE + UniformColorSprite.TEXTURECOORDINATES_INDEX_U] = u; - bufferData[1 * UniformColorSprite.VERTEX_SIZE + UniformColorSprite.TEXTURECOORDINATES_INDEX_V] = v2; + bufferData[1 * UniformColorSprite.VERTEX_SIZE + UniformColorSprite.TEXTURECOORDINATES_INDEX_V] = v; bufferData[2 * UniformColorSprite.VERTEX_SIZE + UniformColorSprite.TEXTURECOORDINATES_INDEX_U] = u2; - bufferData[2 * UniformColorSprite.VERTEX_SIZE + UniformColorSprite.TEXTURECOORDINATES_INDEX_V] = v; + bufferData[2 * UniformColorSprite.VERTEX_SIZE + UniformColorSprite.TEXTURECOORDINATES_INDEX_V] = v2; bufferData[3 * UniformColorSprite.VERTEX_SIZE + UniformColorSprite.TEXTURECOORDINATES_INDEX_U] = u2; - bufferData[3 * UniformColorSprite.VERTEX_SIZE + UniformColorSprite.TEXTURECOORDINATES_INDEX_V] = v2; + bufferData[3 * UniformColorSprite.VERTEX_SIZE + UniformColorSprite.TEXTURECOORDINATES_INDEX_V] = v; } this.setDirtyOnHardware(); diff --git a/src/org/andengine/entity/sprite/vbo/IDiamondSpriteVertexBufferObject.java b/src/org/andengine/entity/sprite/vbo/IDiamondSpriteVertexBufferObject.java index c29e23511..c2e1f0686 100644 --- a/src/org/andengine/entity/sprite/vbo/IDiamondSpriteVertexBufferObject.java +++ b/src/org/andengine/entity/sprite/vbo/IDiamondSpriteVertexBufferObject.java @@ -1,7 +1,7 @@ package org.andengine.entity.sprite.vbo; /** - * (c) Zynga 2012 + * (c) 2012 Zynga Inc. * * @author Nicolas Gramlich * @since 18:43:22 - 28.03.2012 diff --git a/src/org/andengine/entity/sprite/vbo/ISpriteVertexBufferObject.java b/src/org/andengine/entity/sprite/vbo/ISpriteVertexBufferObject.java index 92e678b4e..79565bddb 100644 --- a/src/org/andengine/entity/sprite/vbo/ISpriteVertexBufferObject.java +++ b/src/org/andengine/entity/sprite/vbo/ISpriteVertexBufferObject.java @@ -4,7 +4,7 @@ import org.andengine.opengl.vbo.IVertexBufferObject; /** - * (c) Zynga 2012 + * (c) 2012 Zynga Inc. * * @author Nicolas Gramlich * @since 18:40:47 - 28.03.2012 diff --git a/src/org/andengine/entity/sprite/vbo/ITiledSpriteVertexBufferObject.java b/src/org/andengine/entity/sprite/vbo/ITiledSpriteVertexBufferObject.java index e06337bf3..7bd8fdc7a 100644 --- a/src/org/andengine/entity/sprite/vbo/ITiledSpriteVertexBufferObject.java +++ b/src/org/andengine/entity/sprite/vbo/ITiledSpriteVertexBufferObject.java @@ -3,7 +3,7 @@ import org.andengine.entity.sprite.TiledSprite; /** - * (c) Zynga 2012 + * (c) 2012 Zynga Inc. * * @author Nicolas Gramlich * @since 18:39:06 - 28.03.2012 diff --git a/src/org/andengine/entity/sprite/vbo/IUncoloredSpriteVertexBufferObject.java b/src/org/andengine/entity/sprite/vbo/IUncoloredSpriteVertexBufferObject.java index f692aec0b..63682dc17 100644 --- a/src/org/andengine/entity/sprite/vbo/IUncoloredSpriteVertexBufferObject.java +++ b/src/org/andengine/entity/sprite/vbo/IUncoloredSpriteVertexBufferObject.java @@ -2,7 +2,7 @@ /** - * (c) Zynga 2012 + * (c) 2012 Zynga Inc. * * @author Nicolas Gramlich * @since 18:37:49 - 28.03.2012 diff --git a/src/org/andengine/entity/sprite/vbo/IUniformColorSpriteVertexBufferObject.java b/src/org/andengine/entity/sprite/vbo/IUniformColorSpriteVertexBufferObject.java index 04db6f88c..aebdd6ab7 100644 --- a/src/org/andengine/entity/sprite/vbo/IUniformColorSpriteVertexBufferObject.java +++ b/src/org/andengine/entity/sprite/vbo/IUniformColorSpriteVertexBufferObject.java @@ -2,7 +2,7 @@ /** - * (c) Zynga 2012 + * (c) 2012 Zynga Inc. * * @author Nicolas Gramlich * @since 18:35:57 - 28.03.2012 diff --git a/src/org/andengine/entity/sprite/vbo/LowMemoryDiamondSpriteVertexBufferObject.java b/src/org/andengine/entity/sprite/vbo/LowMemoryDiamondSpriteVertexBufferObject.java index bf9af4997..53ad6070c 100644 --- a/src/org/andengine/entity/sprite/vbo/LowMemoryDiamondSpriteVertexBufferObject.java +++ b/src/org/andengine/entity/sprite/vbo/LowMemoryDiamondSpriteVertexBufferObject.java @@ -9,7 +9,7 @@ import org.andengine.opengl.vbo.attribute.VertexBufferObjectAttributes; /** - * (c) Zynga 2012 + * (c) 2012 Zynga Inc. * * @author Nicolas Gramlich * @since 18:43:22 - 28.03.2012 @@ -43,25 +43,23 @@ public LowMemoryDiamondSpriteVertexBufferObject(final VertexBufferObjectManager public void onUpdateVertices(final Sprite pSprite) { final FloatBuffer bufferData = this.mFloatBuffer; - final float x = 0; - final float y = 0; - final float x2 = pSprite.getWidth(); // TODO Optimize with field access? - final float y2 = pSprite.getHeight(); // TODO Optimize with field access? + final float width = pSprite.getWidth(); // TODO Optimize with field access? + final float height = pSprite.getHeight(); // TODO Optimize with field access? - final float xCenter = (x + x2) * 0.5f; - final float yCenter = (y + y2) * 0.5f; + final float halfWidth = width * 0.5f; + final float halfHeight = height * 0.5f; - bufferData.put(0 * Sprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_X, x); - bufferData.put(0 * Sprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_Y, yCenter); + bufferData.put(0 * Sprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_X, halfWidth); + bufferData.put(0 * Sprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_Y, 0); - bufferData.put(1 * Sprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_X, xCenter); - bufferData.put(1 * Sprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_Y, y2); + bufferData.put(1 * Sprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_X, 0); + bufferData.put(1 * Sprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_Y, halfHeight); - bufferData.put(2 * Sprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_X, xCenter); - bufferData.put(2 * Sprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_Y, y); + bufferData.put(2 * Sprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_X, width); + bufferData.put(2 * Sprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_Y, halfHeight); - bufferData.put(3 * Sprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_X, x2); - bufferData.put(3 * Sprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_Y, yCenter); + bufferData.put(3 * Sprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_X, halfWidth); + bufferData.put(3 * Sprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_Y, height); this.setDirtyOnHardware(); } @@ -77,8 +75,8 @@ public void onUpdateTextureCoordinates(final Sprite pSprite) { final float u2; final float v2; - if(pSprite.isFlippedVertical()) { // TODO Optimize with field access? - if(pSprite.isFlippedHorizontal()) { // TODO Optimize with field access? + if (pSprite.isFlippedVertical()) { // TODO Optimize with field access? + if (pSprite.isFlippedHorizontal()) { // TODO Optimize with field access? u = textureRegion.getU2(); u2 = textureRegion.getU(); v = textureRegion.getV2(); @@ -90,7 +88,7 @@ public void onUpdateTextureCoordinates(final Sprite pSprite) { v2 = textureRegion.getV(); } } else { - if(pSprite.isFlippedHorizontal()) { // TODO Optimize with field access? + if (pSprite.isFlippedHorizontal()) { // TODO Optimize with field access? u = textureRegion.getU2(); u2 = textureRegion.getU(); v = textureRegion.getV(); @@ -106,9 +104,21 @@ public void onUpdateTextureCoordinates(final Sprite pSprite) { final float uCenter = (u + u2) * 0.5f; final float vCenter = (v + v2) * 0.5f; - if(textureRegion.isRotated()) { + if (textureRegion.isRotated()) { + bufferData.put(0 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_U, u2); + bufferData.put(0 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_V, vCenter); + + bufferData.put(1 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_U, uCenter); + bufferData.put(1 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_V, v); + + bufferData.put(2 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_U, uCenter); + bufferData.put(2 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_V, v2); + + bufferData.put(3 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_U, u); + bufferData.put(3 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_V, vCenter); + } else { bufferData.put(0 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_U, uCenter); - bufferData.put(0 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_V, v); + bufferData.put(0 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_V, v2); bufferData.put(1 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_U, u); bufferData.put(1 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_V, vCenter); @@ -117,19 +127,7 @@ public void onUpdateTextureCoordinates(final Sprite pSprite) { bufferData.put(2 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_V, vCenter); bufferData.put(3 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_U, uCenter); - bufferData.put(3 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_V, v2); - } else { - bufferData.put(0 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_U, u); - bufferData.put(0 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_V, vCenter); - - bufferData.put(1 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_U, uCenter); - bufferData.put(1 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_V, v2); - - bufferData.put(2 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_U, uCenter); - bufferData.put(2 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_V, v); - - bufferData.put(3 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_U, u2); - bufferData.put(3 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_V, vCenter); + bufferData.put(3 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_V, v); } this.setDirtyOnHardware(); diff --git a/src/org/andengine/entity/sprite/vbo/LowMemorySpriteVertexBufferObject.java b/src/org/andengine/entity/sprite/vbo/LowMemorySpriteVertexBufferObject.java index 5d1574b6b..7ecd1116e 100644 --- a/src/org/andengine/entity/sprite/vbo/LowMemorySpriteVertexBufferObject.java +++ b/src/org/andengine/entity/sprite/vbo/LowMemorySpriteVertexBufferObject.java @@ -10,7 +10,7 @@ import org.andengine.opengl.vbo.attribute.VertexBufferObjectAttributes; /** - * (c) Zynga 2012 + * (c) 2012 Zynga Inc. * * @author Nicolas Gramlich * @since 18:40:47 - 28.03.2012 @@ -58,22 +58,20 @@ public void onUpdateColor(final Sprite pSprite) { public void onUpdateVertices(final Sprite pSprite) { final FloatBuffer bufferData = this.mFloatBuffer; - final float x = 0; - final float y = 0; - final float x2 = pSprite.getWidth(); // TODO Optimize with field access? - final float y2 = pSprite.getHeight(); // TODO Optimize with field access? + final float width = pSprite.getWidth(); // TODO Optimize with field access? + final float height = pSprite.getHeight(); // TODO Optimize with field access? - bufferData.put(0 * Sprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_X, x); - bufferData.put(0 * Sprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_Y, y); + bufferData.put(0 * Sprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_X, 0); + bufferData.put(0 * Sprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_Y, 0); - bufferData.put(1 * Sprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_X, x); - bufferData.put(1 * Sprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_Y, y2); + bufferData.put(1 * Sprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_X, 0); + bufferData.put(1 * Sprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_Y, height); - bufferData.put(2 * Sprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_X, x2); - bufferData.put(2 * Sprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_Y, y); + bufferData.put(2 * Sprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_X, width); + bufferData.put(2 * Sprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_Y, 0); - bufferData.put(3 * Sprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_X, x2); - bufferData.put(3 * Sprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_Y, y2); + bufferData.put(3 * Sprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_X, width); + bufferData.put(3 * Sprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_Y, height); this.setDirtyOnHardware(); } @@ -89,8 +87,8 @@ public void onUpdateTextureCoordinates(final Sprite pSprite) { final float u2; final float v2; - if(pSprite.isFlippedVertical()) { // TODO Optimize with field access? - if(pSprite.isFlippedHorizontal()) { // TODO Optimize with field access? + if (pSprite.isFlippedVertical()) { // TODO Optimize with field access? + if (pSprite.isFlippedHorizontal()) { // TODO Optimize with field access? u = textureRegion.getU2(); u2 = textureRegion.getU(); v = textureRegion.getV2(); @@ -102,7 +100,7 @@ public void onUpdateTextureCoordinates(final Sprite pSprite) { v2 = textureRegion.getV(); } } else { - if(pSprite.isFlippedHorizontal()) { // TODO Optimize with field access? + if (pSprite.isFlippedHorizontal()) { // TODO Optimize with field access? u = textureRegion.getU2(); u2 = textureRegion.getU(); v = textureRegion.getV(); @@ -115,30 +113,30 @@ public void onUpdateTextureCoordinates(final Sprite pSprite) { } } - if(textureRegion.isRotated()) { - bufferData.put(0 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_U, u2); + if (textureRegion.isRotated()) { + bufferData.put(0 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_U, u); bufferData.put(0 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_V, v); - bufferData.put(1 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_U, u); + bufferData.put(1 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_U, u2); bufferData.put(1 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_V, v); - bufferData.put(2 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_U, u2); + bufferData.put(2 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_U, u); bufferData.put(2 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_V, v2); - bufferData.put(3 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_U, u); + bufferData.put(3 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_U, u2); bufferData.put(3 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_V, v2); } else { bufferData.put(0 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_U, u); - bufferData.put(0 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_V, v); + bufferData.put(0 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_V, v2); bufferData.put(1 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_U, u); - bufferData.put(1 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_V, v2); + bufferData.put(1 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_V, v); bufferData.put(2 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_U, u2); - bufferData.put(2 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_V, v); + bufferData.put(2 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_V, v2); bufferData.put(3 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_U, u2); - bufferData.put(3 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_V, v2); + bufferData.put(3 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_V, v); } this.setDirtyOnHardware(); diff --git a/src/org/andengine/entity/sprite/vbo/LowMemoryTiledSpriteVertexBufferObject.java b/src/org/andengine/entity/sprite/vbo/LowMemoryTiledSpriteVertexBufferObject.java index 28f91e4b5..ffc21da1d 100644 --- a/src/org/andengine/entity/sprite/vbo/LowMemoryTiledSpriteVertexBufferObject.java +++ b/src/org/andengine/entity/sprite/vbo/LowMemoryTiledSpriteVertexBufferObject.java @@ -11,7 +11,7 @@ import org.andengine.opengl.vbo.attribute.VertexBufferObjectAttributes; /** - * (c) Zynga 2012 + * (c) 2012 Zynga Inc. * * @author Nicolas Gramlich * @since 18:39:06 - 28.03.2012 @@ -49,7 +49,7 @@ public void onUpdateColor(final TiledSprite pTiledSprite) { final int tileCount = pTiledSprite.getTileCount(); int bufferDataOffset = 0; - for(int i = 0; i < tileCount; i++) { + for (int i = 0; i < tileCount; i++) { bufferData.put(bufferDataOffset + 0 * TiledSprite.VERTEX_SIZE + Sprite.COLOR_INDEX, packedColor); bufferData.put(bufferDataOffset + 1 * TiledSprite.VERTEX_SIZE + Sprite.COLOR_INDEX, packedColor); bufferData.put(bufferDataOffset + 2 * TiledSprite.VERTEX_SIZE + Sprite.COLOR_INDEX, packedColor); @@ -67,31 +67,29 @@ public void onUpdateColor(final TiledSprite pTiledSprite) { public void onUpdateVertices(final TiledSprite pTiledSprite) { final FloatBuffer bufferData = this.mFloatBuffer; - final float x = 0; - final float y = 0; - final float x2 = pTiledSprite.getWidth(); // TODO Optimize with field access? - final float y2 = pTiledSprite.getHeight(); // TODO Optimize with field access? + final float width = pTiledSprite.getWidth(); // TODO Optimize with field access? + final float height = pTiledSprite.getHeight(); // TODO Optimize with field access? final int tileCount = pTiledSprite.getTileCount(); int bufferDataOffset = 0; - for(int i = 0; i < tileCount; i++) { - bufferData.put(bufferDataOffset + 0 * TiledSprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_X, x); - bufferData.put(bufferDataOffset + 0 * TiledSprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_Y, y); + for (int i = 0; i < tileCount; i++) { + bufferData.put(bufferDataOffset + 0 * TiledSprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_X, 0); + bufferData.put(bufferDataOffset + 0 * TiledSprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_Y, 0); - bufferData.put(bufferDataOffset + 1 * TiledSprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_X, x); - bufferData.put(bufferDataOffset + 1 * TiledSprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_Y, y2); + bufferData.put(bufferDataOffset + 1 * TiledSprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_X, 0); + bufferData.put(bufferDataOffset + 1 * TiledSprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_Y, height); - bufferData.put(bufferDataOffset + 2 * TiledSprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_X, x2); - bufferData.put(bufferDataOffset + 2 * TiledSprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_Y, y); + bufferData.put(bufferDataOffset + 2 * TiledSprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_X, width); + bufferData.put(bufferDataOffset + 2 * TiledSprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_Y, 0); - bufferData.put(bufferDataOffset + 3 * TiledSprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_X, x2); - bufferData.put(bufferDataOffset + 3 * TiledSprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_Y, y); + bufferData.put(bufferDataOffset + 3 * TiledSprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_X, width); + bufferData.put(bufferDataOffset + 3 * TiledSprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_Y, 0); - bufferData.put(bufferDataOffset + 4 * TiledSprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_X, x); - bufferData.put(bufferDataOffset + 4 * TiledSprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_Y, y2); + bufferData.put(bufferDataOffset + 4 * TiledSprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_X, 0); + bufferData.put(bufferDataOffset + 4 * TiledSprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_Y, height); - bufferData.put(bufferDataOffset + 5 * TiledSprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_X, x2); - bufferData.put(bufferDataOffset + 5 * TiledSprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_Y, y2); + bufferData.put(bufferDataOffset + 5 * TiledSprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_X, width); + bufferData.put(bufferDataOffset + 5 * TiledSprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_Y, height); bufferDataOffset += TiledSprite.TILEDSPRITE_SIZE; } @@ -107,7 +105,7 @@ public void onUpdateTextureCoordinates(final TiledSprite pTiledSprite) { final int tileCount = pTiledSprite.getTileCount(); int bufferDataOffset = 0; - for(int i = 0; i < tileCount; i++) { + for (int i = 0; i < tileCount; i++) { final ITextureRegion textureRegion = tiledTextureRegion.getTextureRegion(i); final float u; @@ -115,8 +113,8 @@ public void onUpdateTextureCoordinates(final TiledSprite pTiledSprite) { final float u2; final float v2; - if(pTiledSprite.isFlippedVertical()) { // TODO Optimize with field access? - if(pTiledSprite.isFlippedHorizontal()) { // TODO Optimize with field access? + if (pTiledSprite.isFlippedVertical()) { // TODO Optimize with field access? + if (pTiledSprite.isFlippedHorizontal()) { // TODO Optimize with field access? u = textureRegion.getU2(); u2 = textureRegion.getU(); v = textureRegion.getV2(); @@ -128,7 +126,7 @@ public void onUpdateTextureCoordinates(final TiledSprite pTiledSprite) { v2 = textureRegion.getV(); } } else { - if(pTiledSprite.isFlippedHorizontal()) { // TODO Optimize with field access? + if (pTiledSprite.isFlippedHorizontal()) { // TODO Optimize with field access? u = textureRegion.getU2(); u2 = textureRegion.getU(); v = textureRegion.getV(); @@ -141,42 +139,42 @@ public void onUpdateTextureCoordinates(final TiledSprite pTiledSprite) { } } - if(textureRegion.isRotated()) { - bufferData.put(bufferDataOffset + 0 * TiledSprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_U, u2); + if (textureRegion.isRotated()) { + bufferData.put(bufferDataOffset + 0 * TiledSprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_U, u); bufferData.put(bufferDataOffset + 0 * TiledSprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_V, v); - bufferData.put(bufferDataOffset + 1 * TiledSprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_U, u); + bufferData.put(bufferDataOffset + 1 * TiledSprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_U, u2); bufferData.put(bufferDataOffset + 1 * TiledSprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_V, v); - bufferData.put(bufferDataOffset + 2 * TiledSprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_U, u2); + bufferData.put(bufferDataOffset + 2 * TiledSprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_U, u); bufferData.put(bufferDataOffset + 2 * TiledSprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_V, v2); - bufferData.put(bufferDataOffset + 3 * TiledSprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_U, u2); + bufferData.put(bufferDataOffset + 3 * TiledSprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_U, u); bufferData.put(bufferDataOffset + 3 * TiledSprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_V, v2); - bufferData.put(bufferDataOffset + 4 * TiledSprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_U, u); + bufferData.put(bufferDataOffset + 4 * TiledSprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_U, u2); bufferData.put(bufferDataOffset + 4 * TiledSprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_V, v); - bufferData.put(bufferDataOffset + 5 * TiledSprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_U, u); + bufferData.put(bufferDataOffset + 5 * TiledSprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_U, u2); bufferData.put(bufferDataOffset + 5 * TiledSprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_V, v2); } else { bufferData.put(bufferDataOffset + 0 * TiledSprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_U, u); - bufferData.put(bufferDataOffset + 0 * TiledSprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_V, v); + bufferData.put(bufferDataOffset + 0 * TiledSprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_V, v2); bufferData.put(bufferDataOffset + 1 * TiledSprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_U, u); - bufferData.put(bufferDataOffset + 1 * TiledSprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_V, v2); + bufferData.put(bufferDataOffset + 1 * TiledSprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_V, v); bufferData.put(bufferDataOffset + 2 * TiledSprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_U, u2); - bufferData.put(bufferDataOffset + 2 * TiledSprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_V, v); + bufferData.put(bufferDataOffset + 2 * TiledSprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_V, v2); bufferData.put(bufferDataOffset + 3 * TiledSprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_U, u2); - bufferData.put(bufferDataOffset + 3 * TiledSprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_V, v); + bufferData.put(bufferDataOffset + 3 * TiledSprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_V, v2); bufferData.put(bufferDataOffset + 4 * TiledSprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_U, u); - bufferData.put(bufferDataOffset + 4 * TiledSprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_V, v2); + bufferData.put(bufferDataOffset + 4 * TiledSprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_V, v); bufferData.put(bufferDataOffset + 5 * TiledSprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_U, u2); - bufferData.put(bufferDataOffset + 5 * TiledSprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_V, v2); + bufferData.put(bufferDataOffset + 5 * TiledSprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_V, v); } bufferDataOffset += TiledSprite.TILEDSPRITE_SIZE; diff --git a/src/org/andengine/entity/sprite/vbo/LowMemoryUncoloredSpriteVertexBufferObject.java b/src/org/andengine/entity/sprite/vbo/LowMemoryUncoloredSpriteVertexBufferObject.java index 16b80499e..7b278c9bf 100644 --- a/src/org/andengine/entity/sprite/vbo/LowMemoryUncoloredSpriteVertexBufferObject.java +++ b/src/org/andengine/entity/sprite/vbo/LowMemoryUncoloredSpriteVertexBufferObject.java @@ -3,13 +3,14 @@ import java.nio.FloatBuffer; import org.andengine.entity.sprite.Sprite; +import org.andengine.entity.sprite.UncoloredSprite; import org.andengine.opengl.texture.region.ITextureRegion; import org.andengine.opengl.vbo.DrawType; import org.andengine.opengl.vbo.VertexBufferObjectManager; import org.andengine.opengl.vbo.attribute.VertexBufferObjectAttributes; /** - * (c) Zynga 2012 + * (c) 2012 Zynga Inc. * * @author Nicolas Gramlich * @since 18:37:49 - 28.03.2012 @@ -39,29 +40,29 @@ public LowMemoryUncoloredSpriteVertexBufferObject(final VertexBufferObjectManage // Methods for/from SuperClass/Interfaces // =========================================================== + @Override + public void onUpdateColor(final Sprite pSprite) { + /* Nothing. */ + } + @Override public void onUpdateVertices(final Sprite pSprite) { final FloatBuffer bufferData = this.mFloatBuffer; - final float x = 0; - final float y = 0; - final float x2 = pSprite.getWidth(); // TODO Optimize with field access? - final float y2 = pSprite.getHeight(); // TODO Optimize with field access? + final float width = pSprite.getWidth(); // TODO Optimize with field access? + final float height = pSprite.getHeight(); // TODO Optimize with field access? - final float xCenter = (x + x2) * 0.5f; - final float yCenter = (y + y2) * 0.5f; + bufferData.put(0 * UncoloredSprite.VERTEX_SIZE + UncoloredSprite.VERTEX_INDEX_X, 0); + bufferData.put(0 * UncoloredSprite.VERTEX_SIZE + UncoloredSprite.VERTEX_INDEX_Y, 0); - bufferData.put(0 * Sprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_X, x); - bufferData.put(0 * Sprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_Y, yCenter); + bufferData.put(1 * UncoloredSprite.VERTEX_SIZE + UncoloredSprite.VERTEX_INDEX_X, 0); + bufferData.put(1 * UncoloredSprite.VERTEX_SIZE + UncoloredSprite.VERTEX_INDEX_Y, height); - bufferData.put(1 * Sprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_X, xCenter); - bufferData.put(1 * Sprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_Y, y2); + bufferData.put(2 * UncoloredSprite.VERTEX_SIZE + UncoloredSprite.VERTEX_INDEX_X, width); + bufferData.put(2 * UncoloredSprite.VERTEX_SIZE + UncoloredSprite.VERTEX_INDEX_Y, 0); - bufferData.put(2 * Sprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_X, xCenter); - bufferData.put(2 * Sprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_Y, y); - - bufferData.put(3 * Sprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_X, x2); - bufferData.put(3 * Sprite.VERTEX_SIZE + Sprite.VERTEX_INDEX_Y, yCenter); + bufferData.put(3 * UncoloredSprite.VERTEX_SIZE + UncoloredSprite.VERTEX_INDEX_X, width); + bufferData.put(3 * UncoloredSprite.VERTEX_SIZE + UncoloredSprite.VERTEX_INDEX_Y, height); this.setDirtyOnHardware(); } @@ -77,8 +78,8 @@ public void onUpdateTextureCoordinates(final Sprite pSprite) { final float u2; final float v2; - if(pSprite.isFlippedVertical()) { // TODO Optimize with field access? - if(pSprite.isFlippedHorizontal()) { // TODO Optimize with field access? + if (pSprite.isFlippedVertical()) { // TODO Optimize with field access? + if (pSprite.isFlippedHorizontal()) { // TODO Optimize with field access? u = textureRegion.getU2(); u2 = textureRegion.getU(); v = textureRegion.getV2(); @@ -90,7 +91,7 @@ public void onUpdateTextureCoordinates(final Sprite pSprite) { v2 = textureRegion.getV(); } } else { - if(pSprite.isFlippedHorizontal()) { // TODO Optimize with field access? + if (pSprite.isFlippedHorizontal()) { // TODO Optimize with field access? u = textureRegion.getU2(); u2 = textureRegion.getU(); v = textureRegion.getV(); @@ -103,33 +104,30 @@ public void onUpdateTextureCoordinates(final Sprite pSprite) { } } - final float uCenter = (u + u2) * 0.5f; - final float vCenter = (v + v2) * 0.5f; - - if(textureRegion.isRotated()) { - bufferData.put(0 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_U, uCenter); - bufferData.put(0 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_V, v); + if (textureRegion.isRotated()) { + bufferData.put(0 * UncoloredSprite.VERTEX_SIZE + UncoloredSprite.TEXTURECOORDINATES_INDEX_U, u); + bufferData.put(0 * UncoloredSprite.VERTEX_SIZE + UncoloredSprite.TEXTURECOORDINATES_INDEX_V, v); - bufferData.put(1 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_U, u); - bufferData.put(1 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_V, vCenter); + bufferData.put(1 * UncoloredSprite.VERTEX_SIZE + UncoloredSprite.TEXTURECOORDINATES_INDEX_U, u2); + bufferData.put(1 * UncoloredSprite.VERTEX_SIZE + UncoloredSprite.TEXTURECOORDINATES_INDEX_V, v); - bufferData.put(2 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_U, u2); - bufferData.put(2 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_V, vCenter); + bufferData.put(2 * UncoloredSprite.VERTEX_SIZE + UncoloredSprite.TEXTURECOORDINATES_INDEX_U, u); + bufferData.put(2 * UncoloredSprite.VERTEX_SIZE + UncoloredSprite.TEXTURECOORDINATES_INDEX_V, v2); - bufferData.put(3 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_U, uCenter); - bufferData.put(3 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_V, v2); + bufferData.put(3 * UncoloredSprite.VERTEX_SIZE + UncoloredSprite.TEXTURECOORDINATES_INDEX_U, u2); + bufferData.put(3 * UncoloredSprite.VERTEX_SIZE + UncoloredSprite.TEXTURECOORDINATES_INDEX_V, v2); } else { - bufferData.put(0 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_U, u); - bufferData.put(0 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_V, vCenter); + bufferData.put(0 * UncoloredSprite.VERTEX_SIZE + UncoloredSprite.TEXTURECOORDINATES_INDEX_U, u); + bufferData.put(0 * UncoloredSprite.VERTEX_SIZE + UncoloredSprite.TEXTURECOORDINATES_INDEX_V, v2); - bufferData.put(1 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_U, uCenter); - bufferData.put(1 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_V, v2); + bufferData.put(1 * UncoloredSprite.VERTEX_SIZE + UncoloredSprite.TEXTURECOORDINATES_INDEX_U, u); + bufferData.put(1 * UncoloredSprite.VERTEX_SIZE + UncoloredSprite.TEXTURECOORDINATES_INDEX_V, v); - bufferData.put(2 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_U, uCenter); - bufferData.put(2 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_V, v); + bufferData.put(2 * UncoloredSprite.VERTEX_SIZE + UncoloredSprite.TEXTURECOORDINATES_INDEX_U, u2); + bufferData.put(2 * UncoloredSprite.VERTEX_SIZE + UncoloredSprite.TEXTURECOORDINATES_INDEX_V, v2); - bufferData.put(3 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_U, u2); - bufferData.put(3 * Sprite.VERTEX_SIZE + Sprite.TEXTURECOORDINATES_INDEX_V, vCenter); + bufferData.put(3 * UncoloredSprite.VERTEX_SIZE + UncoloredSprite.TEXTURECOORDINATES_INDEX_U, u2); + bufferData.put(3 * UncoloredSprite.VERTEX_SIZE + UncoloredSprite.TEXTURECOORDINATES_INDEX_V, v); } this.setDirtyOnHardware(); diff --git a/src/org/andengine/entity/sprite/vbo/LowMemoryUniformColorSpriteVertexBufferObject.java b/src/org/andengine/entity/sprite/vbo/LowMemoryUniformColorSpriteVertexBufferObject.java index b12ec7718..15dc83797 100644 --- a/src/org/andengine/entity/sprite/vbo/LowMemoryUniformColorSpriteVertexBufferObject.java +++ b/src/org/andengine/entity/sprite/vbo/LowMemoryUniformColorSpriteVertexBufferObject.java @@ -11,7 +11,7 @@ import org.andengine.opengl.vbo.attribute.VertexBufferObjectAttributes; /** - * (c) Zynga 2012 + * (c) 2012 Zynga Inc. * * @author Nicolas Gramlich * @since 18:36:31 - 28.03.2012 @@ -50,22 +50,20 @@ public void onUpdateColor(final Sprite pSprite) { public void onUpdateVertices(final Sprite pSprite) { final FloatBuffer bufferData = this.mFloatBuffer; - final float x = 0; - final float y = 0; - final float x2 = pSprite.getWidth(); // TODO Optimize with field access? - final float y2 = pSprite.getHeight(); // TODO Optimize with field access? + final float width = pSprite.getWidth(); // TODO Optimize with field access? + final float height = pSprite.getHeight(); // TODO Optimize with field access? - bufferData.put(0 * UniformColorSprite.VERTEX_SIZE + UniformColorSprite.VERTEX_INDEX_X, x); - bufferData.put(0 * UniformColorSprite.VERTEX_SIZE + UniformColorSprite.VERTEX_INDEX_Y, y); + bufferData.put(0 * UniformColorSprite.VERTEX_SIZE + UniformColorSprite.VERTEX_INDEX_X, 0); + bufferData.put(0 * UniformColorSprite.VERTEX_SIZE + UniformColorSprite.VERTEX_INDEX_Y, 0); - bufferData.put(1 * UniformColorSprite.VERTEX_SIZE + UniformColorSprite.VERTEX_INDEX_X, x); - bufferData.put(1 * UniformColorSprite.VERTEX_SIZE + UniformColorSprite.VERTEX_INDEX_Y, y2); + bufferData.put(1 * UniformColorSprite.VERTEX_SIZE + UniformColorSprite.VERTEX_INDEX_X, 0); + bufferData.put(1 * UniformColorSprite.VERTEX_SIZE + UniformColorSprite.VERTEX_INDEX_Y, height); - bufferData.put(2 * UniformColorSprite.VERTEX_SIZE + UniformColorSprite.VERTEX_INDEX_X, x2); - bufferData.put(2 * UniformColorSprite.VERTEX_SIZE + UniformColorSprite.VERTEX_INDEX_Y, y); + bufferData.put(2 * UniformColorSprite.VERTEX_SIZE + UniformColorSprite.VERTEX_INDEX_X, width); + bufferData.put(2 * UniformColorSprite.VERTEX_SIZE + UniformColorSprite.VERTEX_INDEX_Y, 0); - bufferData.put(3 * UniformColorSprite.VERTEX_SIZE + UniformColorSprite.VERTEX_INDEX_X, x2); - bufferData.put(3 * UniformColorSprite.VERTEX_SIZE + UniformColorSprite.VERTEX_INDEX_Y, y2); + bufferData.put(3 * UniformColorSprite.VERTEX_SIZE + UniformColorSprite.VERTEX_INDEX_X, width); + bufferData.put(3 * UniformColorSprite.VERTEX_SIZE + UniformColorSprite.VERTEX_INDEX_Y, height); this.setDirtyOnHardware(); } @@ -81,8 +79,8 @@ public void onUpdateTextureCoordinates(final Sprite pSprite) { final float u2; final float v2; - if(pSprite.isFlippedVertical()) { // TODO Optimize with field access? - if(pSprite.isFlippedHorizontal()) { // TODO Optimize with field access? + if (pSprite.isFlippedVertical()) { // TODO Optimize with field access? + if (pSprite.isFlippedHorizontal()) { // TODO Optimize with field access? u = textureRegion.getU2(); u2 = textureRegion.getU(); v = textureRegion.getV2(); @@ -94,7 +92,7 @@ public void onUpdateTextureCoordinates(final Sprite pSprite) { v2 = textureRegion.getV(); } } else { - if(pSprite.isFlippedHorizontal()) { // TODO Optimize with field access? + if (pSprite.isFlippedHorizontal()) { // TODO Optimize with field access? u = textureRegion.getU2(); u2 = textureRegion.getU(); v = textureRegion.getV(); @@ -107,30 +105,30 @@ public void onUpdateTextureCoordinates(final Sprite pSprite) { } } - if(textureRegion.isRotated()) { - bufferData.put(0 * UniformColorSprite.VERTEX_SIZE + UniformColorSprite.TEXTURECOORDINATES_INDEX_U, u2); + if (textureRegion.isRotated()) { + bufferData.put(0 * UniformColorSprite.VERTEX_SIZE + UniformColorSprite.TEXTURECOORDINATES_INDEX_U, u); bufferData.put(0 * UniformColorSprite.VERTEX_SIZE + UniformColorSprite.TEXTURECOORDINATES_INDEX_V, v); - bufferData.put(1 * UniformColorSprite.VERTEX_SIZE + UniformColorSprite.TEXTURECOORDINATES_INDEX_U, u); + bufferData.put(1 * UniformColorSprite.VERTEX_SIZE + UniformColorSprite.TEXTURECOORDINATES_INDEX_U, u2); bufferData.put(1 * UniformColorSprite.VERTEX_SIZE + UniformColorSprite.TEXTURECOORDINATES_INDEX_V, v); - bufferData.put(2 * UniformColorSprite.VERTEX_SIZE + UniformColorSprite.TEXTURECOORDINATES_INDEX_U, u2); + bufferData.put(2 * UniformColorSprite.VERTEX_SIZE + UniformColorSprite.TEXTURECOORDINATES_INDEX_U, u); bufferData.put(2 * UniformColorSprite.VERTEX_SIZE + UniformColorSprite.TEXTURECOORDINATES_INDEX_V, v2); - bufferData.put(3 * UniformColorSprite.VERTEX_SIZE + UniformColorSprite.TEXTURECOORDINATES_INDEX_U, u); + bufferData.put(3 * UniformColorSprite.VERTEX_SIZE + UniformColorSprite.TEXTURECOORDINATES_INDEX_U, u2); bufferData.put(3 * UniformColorSprite.VERTEX_SIZE + UniformColorSprite.TEXTURECOORDINATES_INDEX_V, v2); } else { bufferData.put(0 * UniformColorSprite.VERTEX_SIZE + UniformColorSprite.TEXTURECOORDINATES_INDEX_U, u); - bufferData.put(0 * UniformColorSprite.VERTEX_SIZE + UniformColorSprite.TEXTURECOORDINATES_INDEX_V, v); + bufferData.put(0 * UniformColorSprite.VERTEX_SIZE + UniformColorSprite.TEXTURECOORDINATES_INDEX_V, v2); - bufferData.put(1 * UniformColorSprite.VERTEX_SIZE + UniformColorSprite.TEXTURECOORDINATES_INDEX_U, u); - bufferData.put(1 * UniformColorSprite.VERTEX_SIZE + UniformColorSprite.TEXTURECOORDINATES_INDEX_V, v2); + bufferData.put(1 * UniformColorSprite.VERTEX_SIZE + UniformColorSprite.TEXTURECOORDINATES_INDEX_U, u2); + bufferData.put(1 * UniformColorSprite.VERTEX_SIZE + UniformColorSprite.TEXTURECOORDINATES_INDEX_V, v); bufferData.put(2 * UniformColorSprite.VERTEX_SIZE + UniformColorSprite.TEXTURECOORDINATES_INDEX_U, u2); - bufferData.put(2 * UniformColorSprite.VERTEX_SIZE + UniformColorSprite.TEXTURECOORDINATES_INDEX_V, v); + bufferData.put(2 * UniformColorSprite.VERTEX_SIZE + UniformColorSprite.TEXTURECOORDINATES_INDEX_V, v2); bufferData.put(3 * UniformColorSprite.VERTEX_SIZE + UniformColorSprite.TEXTURECOORDINATES_INDEX_U, u2); - bufferData.put(3 * UniformColorSprite.VERTEX_SIZE + UniformColorSprite.TEXTURECOORDINATES_INDEX_V, v2); + bufferData.put(3 * UniformColorSprite.VERTEX_SIZE + UniformColorSprite.TEXTURECOORDINATES_INDEX_V, v); } this.setDirtyOnHardware(); diff --git a/src/org/andengine/entity/text/AutoWrap.java b/src/org/andengine/entity/text/AutoWrap.java index ebc6141cc..faf5e4e1a 100644 --- a/src/org/andengine/entity/text/AutoWrap.java +++ b/src/org/andengine/entity/text/AutoWrap.java @@ -1,7 +1,7 @@ package org.andengine.entity.text; /** - * (c) Zynga 2012 + * (c) 2012 Zynga Inc. * * @author Nicolas Gramlich * @since 12:36:44 - 29.03.2012 diff --git a/src/org/andengine/entity/text/Text.java b/src/org/andengine/entity/text/Text.java index 6e9a88043..94c5b832b 100644 --- a/src/org/andengine/entity/text/Text.java +++ b/src/org/andengine/entity/text/Text.java @@ -3,7 +3,7 @@ import java.util.ArrayList; import org.andengine.engine.camera.Camera; -import org.andengine.entity.shape.RectangularShape; +import org.andengine.entity.shape.Shape; import org.andengine.entity.text.exception.OutOfCharactersException; import org.andengine.entity.text.vbo.HighPerformanceTextVertexBufferObject; import org.andengine.entity.text.vbo.ITextVertexBufferObject; @@ -17,8 +17,8 @@ import org.andengine.opengl.vbo.VertexBufferObjectManager; import org.andengine.opengl.vbo.attribute.VertexBufferObjectAttributes; import org.andengine.opengl.vbo.attribute.VertexBufferObjectAttributesBuilder; -import org.andengine.util.HorizontalAlign; -import org.andengine.util.adt.DataConstants; +import org.andengine.util.adt.align.HorizontalAlign; +import org.andengine.util.adt.data.constants.DataConstants; import org.andengine.util.adt.list.FloatArrayList; import org.andengine.util.adt.list.IFloatList; @@ -29,11 +29,11 @@ * * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 10:54:59 - 03.04.2010 */ -public class Text extends RectangularShape { +public class Text extends Shape { // =========================================================== // Constants // =========================================================== @@ -134,6 +134,10 @@ public Text(final float pX, final float pY, final IFont pFont, final CharSequenc this(pX, pY, pFont, pText, pCharactersMaximum, pTextOptions, pVertexBufferObjectManager, DrawType.STATIC); } + public Text(final float pX, final float pY, final IFont pFont, final CharSequence pText, final int pCharactersMaximum, final TextOptions pTextOptions, final VertexBufferObjectManager pVertexBufferObjectManager, final ShaderProgram pShaderProgram) { + this(pX, pY, pFont, pText, pCharactersMaximum, pTextOptions, pVertexBufferObjectManager, DrawType.STATIC, pShaderProgram); + } + public Text(final float pX, final float pY, final IFont pFont, final CharSequence pText, final int pCharactersMaximum, final TextOptions pTextOptions, final VertexBufferObjectManager pVertexBufferObjectManager, final DrawType pDrawType) { this(pX, pY, pFont, pText, pCharactersMaximum, pTextOptions, new HighPerformanceTextVertexBufferObject(pVertexBufferObjectManager, Text.LETTER_SIZE * pCharactersMaximum, pDrawType, true, Text.VERTEXBUFFEROBJECTATTRIBUTES_DEFAULT)); } @@ -147,7 +151,7 @@ public Text(final float pX, final float pY, final IFont pFont, final CharSequenc } public Text(final float pX, final float pY, final IFont pFont, final CharSequence pText, final int pCharactersMaximum, final TextOptions pTextOptions, final ITextVertexBufferObject pTextVertexBufferObject, final ShaderProgram pShaderProgram) { - super(pX, pY, 0, 0, pShaderProgram); + super(pX, pY, pShaderProgram); this.mFont = pFont; this.mTextOptions = pTextOptions; @@ -180,7 +184,7 @@ public CharSequence getText() { /** * @param pText - * @throws OutOfCharactersException leaves this {@link Text} object in an undefined state, until {@link Text#setText(CharSequence)} is called again and no {@link OutOfCharactersException} is thrown. + * @throws OutOfCharactersException leaves this {@link Text} object in an undefined state, until {@link #setText(CharSequence)} is called again and no {@link OutOfCharactersException} is thrown. */ public void setText(final CharSequence pText) throws OutOfCharactersException { this.mText = pText; @@ -189,7 +193,7 @@ public void setText(final CharSequence pText) throws OutOfCharactersException { this.mLines.clear(); this.mLineWidths.clear(); - if(this.mTextOptions.mAutoWrap == AutoWrap.NONE) { + if (this.mTextOptions.mAutoWrap == AutoWrap.NONE) { this.mLines = FontUtils.splitLines(this.mText, this.mLines); // TODO Add whitespace-trimming. } else { this.mLines = FontUtils.splitLines(this.mFont, this.mText, this.mLines, this.mTextOptions.mAutoWrap, this.mTextOptions.mAutoWrapWidth); @@ -205,22 +209,16 @@ public void setText(final CharSequence pText) throws OutOfCharactersException { } this.mLineWidthMaximum = maximumLineWidth; - if(this.mTextOptions.mAutoWrap == AutoWrap.NONE) { + if (this.mTextOptions.mAutoWrap == AutoWrap.NONE) { this.mLineAlignmentWidth = this.mLineWidthMaximum; } else { this.mLineAlignmentWidth = this.mTextOptions.mAutoWrapWidth; } - super.mWidth = this.mLineAlignmentWidth; - super.mHeight = lineCount * font.getLineHeight() + (lineCount - 1) * this.mTextOptions.mLeading; - - this.mRotationCenterX = super.mWidth * 0.5f; - this.mRotationCenterY = super.mHeight * 0.5f; - - this.mScaleCenterX = this.mRotationCenterX; - this.mScaleCenterY = this.mRotationCenterY; + final float width = this.mLineAlignmentWidth; + final float height = lineCount * font.getLineHeight() + (lineCount - 1) * this.mTextOptions.mLeading; - this.onUpdateVertices(); + this.setSize(width, height); } public ArrayList getLines() { @@ -288,7 +286,7 @@ public void setTextOptions(final TextOptions pTextOptions) { } public void setCharactersToDraw(final int pCharactersToDraw) { - if(pCharactersToDraw > this.mCharactersMaximum) { + if (pCharactersToDraw > this.mCharactersMaximum) { throw new OutOfCharactersException("Characters: maximum: '" + this.mCharactersMaximum + "' required: '" + pCharactersToDraw + "'."); } this.mCharactersToDraw = pCharactersToDraw; diff --git a/src/org/andengine/entity/text/TextOptions.java b/src/org/andengine/entity/text/TextOptions.java index 72dbc3638..a07906822 100644 --- a/src/org/andengine/entity/text/TextOptions.java +++ b/src/org/andengine/entity/text/TextOptions.java @@ -1,9 +1,9 @@ package org.andengine.entity.text; -import org.andengine.util.HorizontalAlign; +import org.andengine.util.adt.align.HorizontalAlign; /** - * (c) Zynga 2012 + * (c) 2012 Zynga Inc. * * @author Nicolas Gramlich * @since 12:37:02 - 29.03.2012 diff --git a/src/org/andengine/entity/text/TickerText.java b/src/org/andengine/entity/text/TickerText.java index 540149198..4f5a9fc1c 100644 --- a/src/org/andengine/entity/text/TickerText.java +++ b/src/org/andengine/entity/text/TickerText.java @@ -5,14 +5,14 @@ import org.andengine.opengl.font.IFont; import org.andengine.opengl.util.GLState; import org.andengine.opengl.vbo.VertexBufferObjectManager; -import org.andengine.util.HorizontalAlign; +import org.andengine.util.adt.align.HorizontalAlign; import android.opengl.GLES20; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 10:02:04 - 05.05.2010 */ @@ -76,10 +76,10 @@ public int getCharactersVisible() { } @Override - public void setText(CharSequence pText) throws OutOfCharactersException { + public void setText(final CharSequence pText) throws OutOfCharactersException { super.setText(pText); - if(this.mTickerTextOptions != null) { + if (this.mTickerTextOptions != null) { this.mDuration = this.mCharactersToDraw * this.mTickerTextOptions.mCharactersPerSecond; } } @@ -92,13 +92,13 @@ public void setText(CharSequence pText) throws OutOfCharactersException { protected void onManagedUpdate(final float pSecondsElapsed) { super.onManagedUpdate(pSecondsElapsed); - if(this.mTickerTextOptions.mReverse) { - if(this.mCharactersVisible < this.mCharactersToDraw) { + if (this.mTickerTextOptions.mReverse) { + if (this.mCharactersVisible < this.mCharactersToDraw) { this.mSecondsElapsed = Math.max(0, this.mSecondsElapsed - pSecondsElapsed); this.mCharactersVisible = (int) (this.mSecondsElapsed * this.mTickerTextOptions.mCharactersPerSecond); } } else { - if(this.mCharactersVisible < this.mCharactersToDraw) { + if (this.mCharactersVisible < this.mCharactersToDraw) { this.mSecondsElapsed = Math.min(this.mDuration, this.mSecondsElapsed + pSecondsElapsed); this.mCharactersVisible = (int) (this.mSecondsElapsed * this.mTickerTextOptions.mCharactersPerSecond); } diff --git a/src/org/andengine/entity/text/exception/OutOfCharactersException.java b/src/org/andengine/entity/text/exception/OutOfCharactersException.java index 526e1ce4e..c60cb3d6f 100644 --- a/src/org/andengine/entity/text/exception/OutOfCharactersException.java +++ b/src/org/andengine/entity/text/exception/OutOfCharactersException.java @@ -2,7 +2,7 @@ /** - * (c) Zynga 2011 + * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 17:53:31 - 01.11.2011 diff --git a/src/org/andengine/entity/text/exception/TextException.java b/src/org/andengine/entity/text/exception/TextException.java index b9acb023a..b7e8693af 100644 --- a/src/org/andengine/entity/text/exception/TextException.java +++ b/src/org/andengine/entity/text/exception/TextException.java @@ -3,7 +3,7 @@ import org.andengine.util.exception.AndEngineRuntimeException; /** - * (c) Zynga 2011 + * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 17:53:31 - 01.11.2011 diff --git a/src/org/andengine/entity/text/vbo/HighPerformanceTextVertexBufferObject.java b/src/org/andengine/entity/text/vbo/HighPerformanceTextVertexBufferObject.java index 03c276ee4..411ed79cf 100644 --- a/src/org/andengine/entity/text/vbo/HighPerformanceTextVertexBufferObject.java +++ b/src/org/andengine/entity/text/vbo/HighPerformanceTextVertexBufferObject.java @@ -9,10 +9,11 @@ import org.andengine.opengl.vbo.HighPerformanceVertexBufferObject; import org.andengine.opengl.vbo.VertexBufferObjectManager; import org.andengine.opengl.vbo.attribute.VertexBufferObjectAttributes; +import org.andengine.util.adt.align.HorizontalAlign; import org.andengine.util.adt.list.IFloatList; /** - * (c) Zynga 2012 + * (c) 2012 Zynga Inc. * * @author Nicolas Gramlich * @since 12:38:43 - 29.03.2012 @@ -50,7 +51,7 @@ public void onUpdateColor(final Text pText) { int bufferDataOffset = 0; final int charactersMaximum = pText.getCharactersMaximum(); - for(int i = 0; i < charactersMaximum; i++) { + for (int i = 0; i < charactersMaximum; i++) { bufferData[bufferDataOffset + 0 * Text.VERTEX_SIZE + Text.COLOR_INDEX] = packedColor; bufferData[bufferDataOffset + 1 * Text.VERTEX_SIZE + Text.COLOR_INDEX] = packedColor; bufferData[bufferDataOffset + 2 * Text.VERTEX_SIZE + Text.COLOR_INDEX] = packedColor; @@ -68,11 +69,13 @@ public void onUpdateColor(final Text pText) { public void onUpdateVertices(final Text pText) { final float[] bufferData = this.mBufferData; - // TODO Optimize with field access? final IFont font = pText.getFont(); + final HorizontalAlign horizontalAlign = pText.getHorizontalAlign(); final ArrayList lines = pText.getLines(); final float lineHeight = font.getLineHeight(); final IFloatList lineWidths = pText.getLineWidths(); + final float leading = pText.getLeading(); + final float ascent = font.getAscent(); final float lineAlignmentWidth = pText.getLineAlignmentWidth(); @@ -84,7 +87,7 @@ public void onUpdateVertices(final Text pText) { final CharSequence line = lines.get(row); float xBase; - switch(pText.getHorizontalAlign()) { + switch (horizontalAlign) { case RIGHT: xBase = lineAlignmentWidth - lineWidths.get(row); break; @@ -96,22 +99,22 @@ public void onUpdateVertices(final Text pText) { xBase = 0; } - final float yBase = row * (lineHeight + pText.getLeading()); + final float yBase = (lineCount - row) * lineHeight + ((lineCount - row - 1) * leading) + ascent; final int lineLength = line.length(); Letter previousLetter = null; - for(int i = 0; i < lineLength; i++) { + for (int i = 0; i < lineLength; i++) { final Letter letter = font.getLetter(line.charAt(i)); - if(previousLetter != null) { + if (previousLetter != null) { xBase += previousLetter.getKerning(letter.mCharacter); } - if(!letter.isWhitespace()) { + if (!letter.isWhitespace()) { final float x = xBase + letter.mOffsetX; - final float y = yBase + letter.mOffsetY; + final float y = yBase - letter.mOffsetY; - final float y2 = y + letter.mHeight; final float x2 = x + letter.mWidth; + final float y2 = y - letter.mHeight; final float u = letter.mU; final float v = letter.mV; @@ -119,14 +122,14 @@ public void onUpdateVertices(final Text pText) { final float v2 = letter.mV2; bufferData[bufferDataOffset + 0 * Text.VERTEX_SIZE + Text.VERTEX_INDEX_X] = x; - bufferData[bufferDataOffset + 0 * Text.VERTEX_SIZE + Text.VERTEX_INDEX_Y] = y; + bufferData[bufferDataOffset + 0 * Text.VERTEX_SIZE + Text.VERTEX_INDEX_Y] = y2; bufferData[bufferDataOffset + 0 * Text.VERTEX_SIZE + Text.TEXTURECOORDINATES_INDEX_U] = u; - bufferData[bufferDataOffset + 0 * Text.VERTEX_SIZE + Text.TEXTURECOORDINATES_INDEX_V] = v; + bufferData[bufferDataOffset + 0 * Text.VERTEX_SIZE + Text.TEXTURECOORDINATES_INDEX_V] = v2; bufferData[bufferDataOffset + 1 * Text.VERTEX_SIZE + Text.VERTEX_INDEX_X] = x; - bufferData[bufferDataOffset + 1 * Text.VERTEX_SIZE + Text.VERTEX_INDEX_Y] = y2; + bufferData[bufferDataOffset + 1 * Text.VERTEX_SIZE + Text.VERTEX_INDEX_Y] = y; bufferData[bufferDataOffset + 1 * Text.VERTEX_SIZE + Text.TEXTURECOORDINATES_INDEX_U] = u; - bufferData[bufferDataOffset + 1 * Text.VERTEX_SIZE + Text.TEXTURECOORDINATES_INDEX_V] = v2; + bufferData[bufferDataOffset + 1 * Text.VERTEX_SIZE + Text.TEXTURECOORDINATES_INDEX_V] = v; bufferData[bufferDataOffset + 2 * Text.VERTEX_SIZE + Text.VERTEX_INDEX_X] = x2; bufferData[bufferDataOffset + 2 * Text.VERTEX_SIZE + Text.VERTEX_INDEX_Y] = y2; @@ -138,14 +141,14 @@ public void onUpdateVertices(final Text pText) { bufferData[bufferDataOffset + 3 * Text.VERTEX_SIZE + Text.TEXTURECOORDINATES_INDEX_U] = u2; bufferData[bufferDataOffset + 3 * Text.VERTEX_SIZE + Text.TEXTURECOORDINATES_INDEX_V] = v2; - bufferData[bufferDataOffset + 4 * Text.VERTEX_SIZE + Text.VERTEX_INDEX_X] = x2; + bufferData[bufferDataOffset + 4 * Text.VERTEX_SIZE + Text.VERTEX_INDEX_X] = x; bufferData[bufferDataOffset + 4 * Text.VERTEX_SIZE + Text.VERTEX_INDEX_Y] = y; - bufferData[bufferDataOffset + 4 * Text.VERTEX_SIZE + Text.TEXTURECOORDINATES_INDEX_U] = u2; + bufferData[bufferDataOffset + 4 * Text.VERTEX_SIZE + Text.TEXTURECOORDINATES_INDEX_U] = u; bufferData[bufferDataOffset + 4 * Text.VERTEX_SIZE + Text.TEXTURECOORDINATES_INDEX_V] = v; - bufferData[bufferDataOffset + 5 * Text.VERTEX_SIZE + Text.VERTEX_INDEX_X] = x; + bufferData[bufferDataOffset + 5 * Text.VERTEX_SIZE + Text.VERTEX_INDEX_X] = x2; bufferData[bufferDataOffset + 5 * Text.VERTEX_SIZE + Text.VERTEX_INDEX_Y] = y; - bufferData[bufferDataOffset + 5 * Text.VERTEX_SIZE + Text.TEXTURECOORDINATES_INDEX_U] = u; + bufferData[bufferDataOffset + 5 * Text.VERTEX_SIZE + Text.TEXTURECOORDINATES_INDEX_U] = u2; bufferData[bufferDataOffset + 5 * Text.VERTEX_SIZE + Text.TEXTURECOORDINATES_INDEX_V] = v; bufferDataOffset += Text.LETTER_SIZE; diff --git a/src/org/andengine/entity/text/vbo/ITextVertexBufferObject.java b/src/org/andengine/entity/text/vbo/ITextVertexBufferObject.java index abac08460..a4e49ccef 100644 --- a/src/org/andengine/entity/text/vbo/ITextVertexBufferObject.java +++ b/src/org/andengine/entity/text/vbo/ITextVertexBufferObject.java @@ -4,8 +4,8 @@ import org.andengine.opengl.vbo.IVertexBufferObject; /** - * - * (c) Zynga 2012 + * + * (c) 2012 Zynga Inc. * * @author Nicolas Gramlich * @since 12:38:05 - 29.03.2012 diff --git a/src/org/andengine/entity/text/vbo/LowMemoryTextVertexBufferObject.java b/src/org/andengine/entity/text/vbo/LowMemoryTextVertexBufferObject.java index 648c8a0bb..510bd6d74 100644 --- a/src/org/andengine/entity/text/vbo/LowMemoryTextVertexBufferObject.java +++ b/src/org/andengine/entity/text/vbo/LowMemoryTextVertexBufferObject.java @@ -10,10 +10,11 @@ import org.andengine.opengl.vbo.LowMemoryVertexBufferObject; import org.andengine.opengl.vbo.VertexBufferObjectManager; import org.andengine.opengl.vbo.attribute.VertexBufferObjectAttributes; +import org.andengine.util.adt.align.HorizontalAlign; import org.andengine.util.adt.list.IFloatList; /** - * (c) Zynga 2012 + * (c) 2012 Zynga Inc. * * @author Nicolas Gramlich * @since 12:38:22 - 29.03.2012 @@ -51,7 +52,7 @@ public void onUpdateColor(final Text pText) { int bufferDataOffset = 0; final int charactersMaximum = pText.getCharactersMaximum(); - for(int i = 0; i < charactersMaximum; i++) { + for (int i = 0; i < charactersMaximum; i++) { bufferData.put(bufferDataOffset + 0 * Text.VERTEX_SIZE + Text.COLOR_INDEX, packedColor); bufferData.put(bufferDataOffset + 1 * Text.VERTEX_SIZE + Text.COLOR_INDEX, packedColor); bufferData.put(bufferDataOffset + 2 * Text.VERTEX_SIZE + Text.COLOR_INDEX, packedColor); @@ -69,11 +70,13 @@ public void onUpdateColor(final Text pText) { public void onUpdateVertices(final Text pText) { final FloatBuffer bufferData = this.mFloatBuffer; - // TODO Optimize with field access? final IFont font = pText.getFont(); + final HorizontalAlign horizontalAlign = pText.getHorizontalAlign(); final ArrayList lines = pText.getLines(); final float lineHeight = font.getLineHeight(); final IFloatList lineWidths = pText.getLineWidths(); + final float leading = pText.getLeading(); + final float ascent = font.getAscent(); final float lineAlignmentWidth = pText.getLineAlignmentWidth(); @@ -81,39 +84,39 @@ public void onUpdateVertices(final Text pText) { int bufferDataOffset = 0; final int lineCount = lines.size(); - for (int i = 0; i < lineCount; i++) { - final CharSequence line = lines.get(i); + for (int row = 0; row < lineCount; row++) { + final CharSequence line = lines.get(row); float xBase; - switch(pText.getHorizontalAlign()) { + switch (horizontalAlign) { case RIGHT: - xBase = lineAlignmentWidth - lineWidths.get(i); + xBase = lineAlignmentWidth - lineWidths.get(row); break; case CENTER: - xBase = (lineAlignmentWidth - lineWidths.get(i)) * 0.5f; + xBase = (lineAlignmentWidth - lineWidths.get(row)) * 0.5f; break; case LEFT: default: xBase = 0; } - final float yBase = i * (lineHeight + pText.getLeading()); + final float yBase = (lineCount - row) * lineHeight + ((lineCount - row - 1) * leading) + ascent; final int lineLength = line.length(); Letter previousLetter = null; - for(int j = 0; j < lineLength; j++) { - final Letter letter = font.getLetter(line.charAt(j)); - if(previousLetter != null) { + for (int i = 0; i < lineLength; i++) { + final Letter letter = font.getLetter(line.charAt(i)); + if (previousLetter != null) { xBase += previousLetter.getKerning(letter.mCharacter); } - if(!letter.isWhitespace()) { + if (!letter.isWhitespace()) { final float x = xBase + letter.mOffsetX; - final float y = yBase + letter.mOffsetY; + final float y = yBase - letter.mOffsetY; - final float y2 = y + letter.mHeight; final float x2 = x + letter.mWidth; + final float y2 = y - letter.mHeight; final float u = letter.mU; final float v = letter.mV; @@ -121,14 +124,14 @@ public void onUpdateVertices(final Text pText) { final float v2 = letter.mV2; bufferData.put(bufferDataOffset + 0 * Text.VERTEX_SIZE + Text.VERTEX_INDEX_X, x); - bufferData.put(bufferDataOffset + 0 * Text.VERTEX_SIZE + Text.VERTEX_INDEX_Y, y); + bufferData.put(bufferDataOffset + 0 * Text.VERTEX_SIZE + Text.VERTEX_INDEX_Y, y2); bufferData.put(bufferDataOffset + 0 * Text.VERTEX_SIZE + Text.TEXTURECOORDINATES_INDEX_U, u); - bufferData.put(bufferDataOffset + 0 * Text.VERTEX_SIZE + Text.TEXTURECOORDINATES_INDEX_V, v); + bufferData.put(bufferDataOffset + 0 * Text.VERTEX_SIZE + Text.TEXTURECOORDINATES_INDEX_V, v2); bufferData.put(bufferDataOffset + 1 * Text.VERTEX_SIZE + Text.VERTEX_INDEX_X, x); - bufferData.put(bufferDataOffset + 1 * Text.VERTEX_SIZE + Text.VERTEX_INDEX_Y, y2); + bufferData.put(bufferDataOffset + 1 * Text.VERTEX_SIZE + Text.VERTEX_INDEX_Y, y); bufferData.put(bufferDataOffset + 1 * Text.VERTEX_SIZE + Text.TEXTURECOORDINATES_INDEX_U, u); - bufferData.put(bufferDataOffset + 1 * Text.VERTEX_SIZE + Text.TEXTURECOORDINATES_INDEX_V, v2); + bufferData.put(bufferDataOffset + 1 * Text.VERTEX_SIZE + Text.TEXTURECOORDINATES_INDEX_V, v); bufferData.put(bufferDataOffset + 2 * Text.VERTEX_SIZE + Text.VERTEX_INDEX_X, x2); bufferData.put(bufferDataOffset + 2 * Text.VERTEX_SIZE + Text.VERTEX_INDEX_Y, y2); @@ -140,14 +143,14 @@ public void onUpdateVertices(final Text pText) { bufferData.put(bufferDataOffset + 3 * Text.VERTEX_SIZE + Text.TEXTURECOORDINATES_INDEX_U, u2); bufferData.put(bufferDataOffset + 3 * Text.VERTEX_SIZE + Text.TEXTURECOORDINATES_INDEX_V, v2); - bufferData.put(bufferDataOffset + 4 * Text.VERTEX_SIZE + Text.VERTEX_INDEX_X, x2); + bufferData.put(bufferDataOffset + 4 * Text.VERTEX_SIZE + Text.VERTEX_INDEX_X, x); bufferData.put(bufferDataOffset + 4 * Text.VERTEX_SIZE + Text.VERTEX_INDEX_Y, y); - bufferData.put(bufferDataOffset + 4 * Text.VERTEX_SIZE + Text.TEXTURECOORDINATES_INDEX_U, u2); + bufferData.put(bufferDataOffset + 4 * Text.VERTEX_SIZE + Text.TEXTURECOORDINATES_INDEX_U, u); bufferData.put(bufferDataOffset + 4 * Text.VERTEX_SIZE + Text.TEXTURECOORDINATES_INDEX_V, v); - bufferData.put(bufferDataOffset + 5 * Text.VERTEX_SIZE + Text.VERTEX_INDEX_X, x); + bufferData.put(bufferDataOffset + 5 * Text.VERTEX_SIZE + Text.VERTEX_INDEX_X, x2); bufferData.put(bufferDataOffset + 5 * Text.VERTEX_SIZE + Text.VERTEX_INDEX_Y, y); - bufferData.put(bufferDataOffset + 5 * Text.VERTEX_SIZE + Text.TEXTURECOORDINATES_INDEX_U, u); + bufferData.put(bufferDataOffset + 5 * Text.VERTEX_SIZE + Text.TEXTURECOORDINATES_INDEX_U, u2); bufferData.put(bufferDataOffset + 5 * Text.VERTEX_SIZE + Text.TEXTURECOORDINATES_INDEX_V, v); bufferDataOffset += Text.LETTER_SIZE; diff --git a/src/org/andengine/entity/util/AverageFPSCounter.java b/src/org/andengine/entity/util/AverageFPSCounter.java index 7dd65ee70..a1bd1a98c 100644 --- a/src/org/andengine/entity/util/AverageFPSCounter.java +++ b/src/org/andengine/entity/util/AverageFPSCounter.java @@ -3,9 +3,9 @@ /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 19:52:31 - 09.03.2010 */ @@ -48,7 +48,7 @@ public AverageFPSCounter(final float pAverageDuration) { public void onUpdate(final float pSecondsElapsed) { super.onUpdate(pSecondsElapsed); - if(this.mSecondsElapsed > this.mAverageDuration){ + if (this.mSecondsElapsed > this.mAverageDuration) { this.onHandleAverageDurationElapsed(this.getFPS()); this.mSecondsElapsed -= this.mAverageDuration; diff --git a/src/org/andengine/entity/util/FPSCounter.java b/src/org/andengine/entity/util/FPSCounter.java index ceeddac26..5b1f813f1 100644 --- a/src/org/andengine/entity/util/FPSCounter.java +++ b/src/org/andengine/entity/util/FPSCounter.java @@ -3,9 +3,9 @@ import org.andengine.engine.handler.IUpdateHandler; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 19:52:31 - 09.03.2010 */ diff --git a/src/org/andengine/entity/util/FPSLogger.java b/src/org/andengine/entity/util/FPSLogger.java index 71315307f..df02d9f62 100644 --- a/src/org/andengine/entity/util/FPSLogger.java +++ b/src/org/andengine/entity/util/FPSLogger.java @@ -2,12 +2,13 @@ import org.andengine.BuildConfig; import org.andengine.util.debug.Debug; +import org.andengine.util.debug.Debug.DebugLevel; import org.andengine.util.time.TimeConstants; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 19:52:31 - 09.03.2010 */ @@ -20,6 +21,8 @@ public class FPSLogger extends AverageFPSCounter { // Fields // =========================================================== + private final DebugLevel mDebugLevel; + protected float mShortestFrame = Float.MAX_VALUE; protected float mLongestFrame = Float.MIN_VALUE; @@ -28,11 +31,21 @@ public class FPSLogger extends AverageFPSCounter { // =========================================================== public FPSLogger() { - super(); + this(DebugLevel.DEBUG); + } + + public FPSLogger(final DebugLevel pDebugLevel) { + this.mDebugLevel = pDebugLevel; } public FPSLogger(final float pAverageDuration) { + this(pAverageDuration, DebugLevel.DEBUG); + } + + public FPSLogger(final float pAverageDuration, final DebugLevel pDebugLevel) { super(pAverageDuration); + + this.mDebugLevel = pDebugLevel; } // =========================================================== @@ -72,11 +85,12 @@ public void reset() { // =========================================================== protected void onLogFPS() { - if(BuildConfig.DEBUG) { - Debug.d(String.format("FPS: %.2f (MIN: %.0f ms | MAX: %.0f ms)", - this.mFrames / this.mSecondsElapsed, - this.mShortestFrame * TimeConstants.MILLISECONDS_PER_SECOND, - this.mLongestFrame * TimeConstants.MILLISECONDS_PER_SECOND)); + if (BuildConfig.DEBUG) { + final float framesPerSecond = this.mFrames / this.mSecondsElapsed; + final float shortestFrameInMilliseconds = this.mShortestFrame * TimeConstants.MILLISECONDS_PER_SECOND; + final float longestFrameInMilliseconds = this.mLongestFrame * TimeConstants.MILLISECONDS_PER_SECOND; + + Debug.log(this.mDebugLevel, String.format("FPS: %.2f (MIN: %.0f ms | MAX: %.0f ms)", framesPerSecond, shortestFrameInMilliseconds, longestFrameInMilliseconds)); } } diff --git a/src/org/andengine/entity/util/FrameCountCrasher.java b/src/org/andengine/entity/util/FrameCountCrasher.java index 5c6175c14..b1d2b31be 100644 --- a/src/org/andengine/entity/util/FrameCountCrasher.java +++ b/src/org/andengine/entity/util/FrameCountCrasher.java @@ -5,9 +5,9 @@ import org.andengine.util.debug.Debug; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 19:52:31 - 09.03.2010 */ @@ -46,11 +46,11 @@ public void onUpdate(final float pSecondsElapsed) { this.mFramesLeft--; final float[] frameLengths = this.mFrameLengths; - if(this.mFramesLeft >= 0) { + if (this.mFramesLeft >= 0) { frameLengths[this.mFramesLeft] = pSecondsElapsed; } else { - if(BuildConfig.DEBUG) { - for(int i = frameLengths.length - 1; i >= 0; i--) { + if (BuildConfig.DEBUG) { + for (int i = frameLengths.length - 1; i >= 0; i--) { Debug.d("Elapsed: " + frameLengths[i]); } } diff --git a/src/org/andengine/entity/util/FrameCounter.java b/src/org/andengine/entity/util/FrameCounter.java index 49a4740b1..5ee3d578f 100644 --- a/src/org/andengine/entity/util/FrameCounter.java +++ b/src/org/andengine/entity/util/FrameCounter.java @@ -3,9 +3,9 @@ import org.andengine.engine.handler.IUpdateHandler; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 11:00:55 - 22.06.2010 */ diff --git a/src/org/andengine/entity/util/MemoryLogger.java b/src/org/andengine/entity/util/MemoryLogger.java new file mode 100644 index 000000000..7ac265a13 --- /dev/null +++ b/src/org/andengine/entity/util/MemoryLogger.java @@ -0,0 +1,242 @@ +package org.andengine.entity.util; + +import org.andengine.BuildConfig; +import org.andengine.engine.handler.IUpdateHandler; +import org.andengine.util.TextUtils; +import org.andengine.util.debug.Debug; +import org.andengine.util.debug.Debug.DebugLevel; +import org.andengine.util.system.SystemUtils; +import org.andengine.util.system.SystemUtils.SystemUtilsException; + + + +/** + * (c) 2012 Zynga Inc. + * + * @author Nicolas Gramlich + * @since 14:50:15 - 14.05.2012 + */ +public class MemoryLogger implements IUpdateHandler { + // =========================================================== + // Constants + // =========================================================== + + private static final float AVERAGE_DURATION_DEFAULT = 5; + + // =========================================================== + // Fields + // =========================================================== + + private final float mAverageDuration; + private final DebugLevel mDebugLevel; + + private float mSecondsElapsed; + + private boolean mLogSystemMemory; + private long mPreviousSystemMemorySize; + private long mPreviousSystemMemoryFreeSize; + + private boolean mLogDalvikHeap; + private long mPreviousDalvikHeapSize; + private long mPreviousDalvikHeapFreeSize; + private long mPreviousDalvikHeapAllocatedSize; + + private boolean mLogDalvikMemoryInfo; + private long mPreviousDalvikProportionalSetSize; + private long mPreviousDalvikPrivateDirtyPages; + private long mPreviousDalvikSharedDirtyPages; + + private boolean mLogNativeHeap; + private long mPreviousNativeHeapSize; + private long mPreviousNativeHeapFreeSize; + private long mPreviousNativeHeapAllocatedSize; + + private boolean mLogNativeMemoryInfo; + private long mPreviousNativeProportionalSetSize; + private long mPreviousNativePrivateDirtyPages; + private long mPreviousNativeSharedDirtyPages; + + // =========================================================== + // Constructors + // =========================================================== + + public MemoryLogger() { + this(DebugLevel.DEBUG); + } + + public MemoryLogger(final DebugLevel pDebugLevel) { + this(MemoryLogger.AVERAGE_DURATION_DEFAULT, pDebugLevel); + } + + public MemoryLogger(final float pAverageDuration) { + this(pAverageDuration, DebugLevel.DEBUG); + } + + public MemoryLogger(final float pAverageDuration, final DebugLevel pDebugLevel) { + this(pAverageDuration, pDebugLevel, true, true, false, true, false); + } + + public MemoryLogger(final float pAverageDuration, final DebugLevel pDebugLevel, final boolean pLogSystemMemory, final boolean pLogDalvikHeap, final boolean pLogDalvikMemoryInfo, final boolean pLogNativeHeap, final boolean pLogNativeMemoryInfo) { + this.mAverageDuration = pAverageDuration; + this.mDebugLevel = pDebugLevel; + + this.mLogSystemMemory = pLogSystemMemory; + this.mLogDalvikHeap = pLogDalvikHeap; + this.mLogDalvikMemoryInfo = pLogDalvikMemoryInfo; + this.mLogNativeHeap = pLogNativeHeap; + this.mLogNativeMemoryInfo = pLogNativeMemoryInfo; + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + public void onUpdate(final float pSecondsElapsed) { + this.mSecondsElapsed += pSecondsElapsed; + + if (this.mSecondsElapsed > this.mAverageDuration) { + this.onHandleLogDurationElapsed(); + + this.mSecondsElapsed -= this.mAverageDuration; + } + } + + @Override + public void reset() { + this.mSecondsElapsed = 0; + } + + // =========================================================== + // Methods + // =========================================================== + + protected void onHandleLogDurationElapsed() { + if (BuildConfig.DEBUG) { + /* Execute GC. */ + System.gc(); + try { + final StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.append("+------------------------------+---------------+-----------------+\n"); + stringBuilder.append("| Memory Stat | Current | Change |\n"); + stringBuilder.append("+------------------------------+---------------+-----------------+\n"); + + if (this.mLogSystemMemory) { + final long systemMemorySize = SystemUtils.getSystemMemorySize(); + final long systemMemoryFreeSize = SystemUtils.getSystemMemoryFreeSize(); + + final long systemMemorySizeDiff = systemMemorySize - this.mPreviousSystemMemorySize; + final long systemMemoryFreeSizeDiff = systemMemoryFreeSize - this.mPreviousSystemMemoryFreeSize; + + this.mPreviousSystemMemorySize = systemMemorySize; + this.mPreviousSystemMemoryFreeSize = systemMemoryFreeSize; + + stringBuilder.append("| System memory size | " + MemoryLogger.formatRight(systemMemorySize, ' ', 10) + " kB | (" + MemoryLogger.formatRight(systemMemorySizeDiff, ' ', 10, true) + " kB) |\n"); + stringBuilder.append("| System memory free size | " + MemoryLogger.formatRight(systemMemoryFreeSize, ' ', 10) + " kB | (" + MemoryLogger.formatRight(systemMemoryFreeSizeDiff, ' ', 10, true) + " kB) |\n"); + stringBuilder.append("+------------------------------+---------------+-----------------+\n"); + } + + if (this.mLogDalvikHeap) { + final long dalvikHeapSize = SystemUtils.getDalvikHeapSize(); + final long dalvikHeapFreeSize = SystemUtils.getDalvikHeapFreeSize(); + final long dalvikHeapAllocatedSize = SystemUtils.getDalvikHeapAllocatedSize(); + + final long dalvikHeapSizeDiff = dalvikHeapSize - this.mPreviousDalvikHeapSize; + final long dalvikHeapFreeSizeDiff = dalvikHeapFreeSize - this.mPreviousDalvikHeapFreeSize; + final long dalvikHeapAllocatedSizeDiff = dalvikHeapAllocatedSize - this.mPreviousDalvikHeapAllocatedSize; + + stringBuilder.append("| Dalvik memory size | " + MemoryLogger.formatRight(dalvikHeapSize, ' ', 10) + " kB | (" + MemoryLogger.formatRight(dalvikHeapSizeDiff, ' ', 10, true) + " kB) |\n"); + stringBuilder.append("| Dalvik memory free size | " + MemoryLogger.formatRight(dalvikHeapFreeSize, ' ', 10) + " kB | (" + MemoryLogger.formatRight(dalvikHeapFreeSizeDiff, ' ', 10, true) + " kB) |\n"); + stringBuilder.append("| Dalvik memory allocated size | " + MemoryLogger.formatRight(dalvikHeapAllocatedSize, ' ', 10) + " kB | (" + MemoryLogger.formatRight(dalvikHeapAllocatedSizeDiff, ' ', 10, true) + " kB) |\n"); + stringBuilder.append("+------------------------------+---------------+-----------------+\n"); + + this.mPreviousDalvikHeapSize = dalvikHeapSize; + this.mPreviousDalvikHeapFreeSize = dalvikHeapFreeSize; + this.mPreviousDalvikHeapAllocatedSize = dalvikHeapAllocatedSize; + } + + if (this.mLogDalvikMemoryInfo) { + final long dalvikProportionalSetSize = SystemUtils.getDalvikProportionalSetSize(); + final long dalvikPrivateDirtyPages = SystemUtils.getDalvikPrivateDirtyPages(); + final long dalvikSharedDirtyPages = SystemUtils.getDalvikSharedDirtyPages(); + + final long dalvikProportionalSetSizeDiff = dalvikProportionalSetSize - this.mPreviousDalvikProportionalSetSize; + final long dalvikPrivateDirtyPagesDiff = dalvikPrivateDirtyPages - this.mPreviousDalvikPrivateDirtyPages; + final long dalvikSharedDirtyPagesDiff = dalvikSharedDirtyPages - this.mPreviousDalvikSharedDirtyPages; + + stringBuilder.append("| Dalvik proportional set size | " + MemoryLogger.formatRight(dalvikProportionalSetSize, ' ', 10) + " | (" + MemoryLogger.formatRight(dalvikProportionalSetSizeDiff, ' ', 10, true) + " ) |\n"); + stringBuilder.append("| Dalvik private dirty pages | " + MemoryLogger.formatRight(dalvikPrivateDirtyPages, ' ', 10) + " | (" + MemoryLogger.formatRight(dalvikPrivateDirtyPagesDiff, ' ', 10, true) + " ) |\n"); + stringBuilder.append("| Dalvik shared dirty pages | " + MemoryLogger.formatRight(dalvikSharedDirtyPages, ' ', 10) + " | (" + MemoryLogger.formatRight(dalvikSharedDirtyPagesDiff, ' ', 10, true) + " ) |\n"); + stringBuilder.append("+------------------------------+---------------+-----------------+\n"); + + this.mPreviousDalvikProportionalSetSize = dalvikProportionalSetSize; + this.mPreviousDalvikPrivateDirtyPages = dalvikPrivateDirtyPages; + this.mPreviousDalvikSharedDirtyPages = dalvikSharedDirtyPages; + } + + if (this.mLogNativeHeap) { + final long nativeHeapSize = SystemUtils.getNativeHeapSize(); + final long nativeHeapFreeSize = SystemUtils.getNativeHeapFreeSize(); + final long nativeHeapAllocatedSize = SystemUtils.getNativeHeapAllocatedSize(); + + final long nativeHeapSizeDiff = nativeHeapSize - this.mPreviousNativeHeapSize; + final long nativeHeapFreeSizeDiff = nativeHeapFreeSize - this.mPreviousNativeHeapFreeSize; + final long nativeHeapAllocatedSizeDiff = nativeHeapAllocatedSize - this.mPreviousNativeHeapAllocatedSize; + + stringBuilder.append("| Native memory size | " + MemoryLogger.formatRight(nativeHeapSize, ' ', 10) + " kB | (" + MemoryLogger.formatRight(nativeHeapSizeDiff, ' ', 10, true) + " kB) |\n"); + stringBuilder.append("| Native memory free size | " + MemoryLogger.formatRight(nativeHeapFreeSize, ' ', 10) + " kB | (" + MemoryLogger.formatRight(nativeHeapFreeSizeDiff, ' ', 10, true) + " kB) |\n"); + stringBuilder.append("| Native memory allocated size | " + MemoryLogger.formatRight(nativeHeapAllocatedSize, ' ', 10) + " kB | (" + MemoryLogger.formatRight(nativeHeapAllocatedSizeDiff, ' ', 10, true) + " kB) |\n"); + stringBuilder.append("+------------------------------+---------------+-----------------+\n"); + + this.mPreviousNativeHeapSize = nativeHeapSize; + this.mPreviousNativeHeapFreeSize = nativeHeapFreeSize; + this.mPreviousNativeHeapAllocatedSize = nativeHeapAllocatedSize; + } + + if (this.mLogNativeMemoryInfo) { + final long nativeProportionalSetSize = SystemUtils.getNativeProportionalSetSize(); + final long nativePrivateDirtyPages = SystemUtils.getNativePrivateDirtyPages(); + final long nativeSharedDirtyPages = SystemUtils.getNativeSharedDirtyPages(); + + final long nativeProportionalSetSizeDiff = nativeProportionalSetSize - this.mPreviousNativeProportionalSetSize; + final long nativePrivateDirtyPagesDiff = nativePrivateDirtyPages - this.mPreviousNativePrivateDirtyPages; + final long nativeSharedDirtyPagesDiff = nativeSharedDirtyPages - this.mPreviousNativeSharedDirtyPages; + + stringBuilder.append("| Native proportional set size | " + MemoryLogger.formatRight(nativeProportionalSetSize, ' ', 10) + " | (" + MemoryLogger.formatRight(nativeProportionalSetSizeDiff, ' ', 10, true) + " ) |\n"); + stringBuilder.append("| Native private dirty pages | " + MemoryLogger.formatRight(nativePrivateDirtyPages, ' ', 10) + " | (" + MemoryLogger.formatRight(nativePrivateDirtyPagesDiff, ' ', 10, true) + " ) |\n"); + stringBuilder.append("| Native shared dirty pages | " + MemoryLogger.formatRight(nativeSharedDirtyPages, ' ', 10) + " | (" + MemoryLogger.formatRight(nativeSharedDirtyPagesDiff, ' ', 10, true) + " ) |\n"); + stringBuilder.append("+------------------------------+---------------+-----------------+\n"); + + this.mPreviousNativeProportionalSetSize = nativeProportionalSetSize; + this.mPreviousNativePrivateDirtyPages = nativePrivateDirtyPages; + this.mPreviousNativeSharedDirtyPages = nativeSharedDirtyPages; + } + + Debug.log(this.mDebugLevel, stringBuilder.toString()); + } catch (final SystemUtilsException e) { + Debug.e(e); + } + System.gc(); + } + } + + public static final CharSequence formatRight(final long pLong, final char pPadChar, final int pLength) { + return MemoryLogger.formatRight(pLong, pPadChar, pLength, false); + } + + public static final CharSequence formatRight(final long pLong, final char pPadChar, final int pLength, final boolean pAddPositiveSign) { + if ((pLong > 0) && pAddPositiveSign) { + return TextUtils.padFront("+" + String.valueOf(pLong), pPadChar, pLength); + } else { + return TextUtils.padFront(String.valueOf(pLong), pPadChar, pLength); + } + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== +} diff --git a/src/org/andengine/entity/util/ScreenCapture.java b/src/org/andengine/entity/util/ScreenCapture.java index 4e69edd37..53b78579d 100644 --- a/src/org/andengine/entity/util/ScreenCapture.java +++ b/src/org/andengine/entity/util/ScreenCapture.java @@ -14,9 +14,9 @@ import android.graphics.Bitmap.CompressFormat; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 15:11:50 - 15.03.2010 */ @@ -25,6 +25,8 @@ public class ScreenCapture extends Entity implements IScreenGrabberCallback { // Constants // =========================================================== + private static final int PNG_QUALITY_MAXIMUM = 100; + // =========================================================== // Fields // =========================================================== @@ -95,9 +97,9 @@ private static void saveCapture(final Bitmap pBitmap, final String pFilePath) th FileOutputStream out = null; try { out = new FileOutputStream(pFilePath); - pBitmap.compress(CompressFormat.PNG, 100, out); + pBitmap.compress(CompressFormat.PNG, PNG_QUALITY_MAXIMUM, out); } catch (final FileNotFoundException e) { - StreamUtils.flushCloseStream(out); + StreamUtils.flushAndCloseStream(out); Debug.e("Error saving file to: " + pFilePath, e); throw e; } diff --git a/src/org/andengine/entity/util/ScreenGrabber.java b/src/org/andengine/entity/util/ScreenGrabber.java index dfc70557b..371e76464 100644 --- a/src/org/andengine/entity/util/ScreenGrabber.java +++ b/src/org/andengine/entity/util/ScreenGrabber.java @@ -4,6 +4,7 @@ import org.andengine.engine.camera.Camera; import org.andengine.entity.Entity; +import org.andengine.opengl.util.GLHelper; import org.andengine.opengl.util.GLState; import android.graphics.Bitmap; @@ -11,9 +12,9 @@ import android.opengl.GLES20; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 15:27:22 - 10.01.2011 */ @@ -31,7 +32,7 @@ public class ScreenGrabber extends Entity { private int mGrabWidth; private int mGrabHeight; - private boolean mScreenGrabPending = false; + private boolean mScreenGrabPending; private IScreenGrabberCallback mScreenGrabCallback; // =========================================================== @@ -48,7 +49,7 @@ public class ScreenGrabber extends Entity { @Override protected void onManagedDraw(final GLState pGLState, final Camera pCamera) { - if(this.mScreenGrabPending) { + if (this.mScreenGrabPending) { try { final Bitmap screenGrab = ScreenGrabber.grab(this.mGrabX, this.mGrabY, this.mGrabWidth, this.mGrabHeight); @@ -90,31 +91,16 @@ public void grab(final int pGrabX, final int pGrabY, final int pGrabWidth, final } private static Bitmap grab(final int pGrabX, final int pGrabY, final int pGrabWidth, final int pGrabHeight) { - final int[] source = new int[pGrabWidth * (pGrabY + pGrabHeight)]; - final IntBuffer sourceBuffer = IntBuffer.wrap(source); - sourceBuffer.position(0); + final int[] pixelsRGBA_8888 = new int[pGrabWidth * pGrabHeight]; + final IntBuffer pixelsRGBA_8888_Buffer = IntBuffer.wrap(pixelsRGBA_8888); // TODO Check availability of OpenGL and GLES20.GL_RGBA combinations that require less conversion operations. - // Note: There is (said to be) a bug with glReadPixels when 'y != 0', so we simply read starting from 'y == 0'. - // TODO Does that bug still exist? - GLES20.glReadPixels(pGrabX, 0, pGrabWidth, pGrabY + pGrabHeight, GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, sourceBuffer); - - final int[] pixels = new int[pGrabWidth * pGrabHeight]; - - // Convert from RGBA_8888 (Which is actually ABGR as the whole buffer seems to be inverted) --> ARGB_8888 - for (int y = 0; y < pGrabHeight; y++) { - for (int x = 0; x < pGrabWidth; x++) { - final int pixel = source[x + ((pGrabY + y) * pGrabWidth)]; - - final int blue = (pixel & 0x00FF0000) >> 16; - final int red = (pixel & 0x000000FF) << 16; - final int greenAlpha = pixel & 0xFF00FF00; - - pixels[x + ((pGrabHeight - y - 1) * pGrabWidth)] = greenAlpha | red | blue; - } - } + GLES20.glReadPixels(pGrabX, pGrabY, pGrabWidth, pGrabHeight, GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, pixelsRGBA_8888_Buffer); + + /* Convert from RGBA_8888 (Which is actually ABGR as the whole buffer seems to be inverted) --> ARGB_8888. */ + final int[] pixelsARGB_8888 = GLHelper.convertRGBA_8888toARGB_8888(pixelsRGBA_8888); - return Bitmap.createBitmap(pixels, pGrabWidth, pGrabHeight, Config.ARGB_8888); + return Bitmap.createBitmap(pixelsARGB_8888, pGrabWidth, pGrabHeight, Config.ARGB_8888); } // =========================================================== diff --git a/src/org/andengine/entity/util/TextureMemoryLogger.java b/src/org/andengine/entity/util/TextureMemoryLogger.java new file mode 100644 index 000000000..36a60acf7 --- /dev/null +++ b/src/org/andengine/entity/util/TextureMemoryLogger.java @@ -0,0 +1,102 @@ +package org.andengine.entity.util; + +import org.andengine.BuildConfig; +import org.andengine.engine.handler.IUpdateHandler; +import org.andengine.opengl.texture.TextureManager; +import org.andengine.util.debug.Debug; +import org.andengine.util.debug.Debug.DebugLevel; + +/** + * (c) 2013 Nicolas Gramlich + * + * @author Arturo GutiƩrrez + * @author Nicolas Gramlich + * @since 22:07:46 - 03.03.2013 + */ +public class TextureMemoryLogger implements IUpdateHandler { + // =========================================================== + // Constants + // =========================================================== + + private static final float AVERAGE_DURATION_DEFAULT = 5; + + // =========================================================== + // Fields + // =========================================================== + + private final TextureManager mTextureManager; + + private final float mAverageDuration; + private float mSecondsElapsed; + + private int mTextureMemoryUsedMax; + private int mTexturesLoadedCountMax; + + private final DebugLevel mDebugLevel; + + // =========================================================== + // Constructors + // =========================================================== + + public TextureMemoryLogger(final TextureManager pTextureManager) { + this(pTextureManager, DebugLevel.DEBUG); + } + + public TextureMemoryLogger(final TextureManager pTextureManager, final DebugLevel pDebugLevel) { + this(pTextureManager, TextureMemoryLogger.AVERAGE_DURATION_DEFAULT); + } + + public TextureMemoryLogger(final TextureManager pTextureManager, final float pAverageDuration) { + this(pTextureManager, pAverageDuration, DebugLevel.DEBUG); + } + + public TextureMemoryLogger(final TextureManager pTextureManager, final float pAverageDuration, final DebugLevel pDebugLevel) { + this.mTextureManager = pTextureManager; + this.mAverageDuration = pAverageDuration; + this.mDebugLevel = pDebugLevel; + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + public void onUpdate(final float pSecondsElapsed) { + this.mSecondsElapsed += pSecondsElapsed; + + if (this.mSecondsElapsed > this.mAverageDuration) { + this.onHandleAverageDurationElapsed(); + + this.mSecondsElapsed -= this.mAverageDuration; + } + } + + @Override + public void reset() { + this.mSecondsElapsed = 0; + } + + // =========================================================== + // Methods + // =========================================================== + + private void onHandleAverageDurationElapsed() { + if (BuildConfig.DEBUG) { + final int texturesLoadedCount = this.mTextureManager.getTexturesLoadedCount(); + final int textureMemoryUsed = this.mTextureManager.getTextureMemoryUsed(); + + this.mTexturesLoadedCountMax = Math.max(texturesLoadedCount, this.mTexturesLoadedCountMax); + this.mTextureMemoryUsedMax = Math.max(textureMemoryUsed, this.mTextureMemoryUsedMax); + + Debug.log(this.mDebugLevel, String.format("MEM: %d kB in %d textures (MAX: %d kB in %d textures)", textureMemoryUsed, texturesLoadedCount, this.mTextureMemoryUsedMax, this.mTexturesLoadedCountMax)); + } + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== +} \ No newline at end of file diff --git a/src/org/andengine/input/sensor/BaseSensorData.java b/src/org/andengine/input/sensor/BaseSensorData.java index 5af5c2489..4633f9d5c 100644 --- a/src/org/andengine/input/sensor/BaseSensorData.java +++ b/src/org/andengine/input/sensor/BaseSensorData.java @@ -3,9 +3,9 @@ import java.util.Arrays; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 16:50:44 - 10.03.2010 */ @@ -26,10 +26,8 @@ public class BaseSensorData { // Constructors // =========================================================== - public BaseSensorData(final int pValueCount, int pDisplayRotation) { + public BaseSensorData(final int pValueCount) { this.mValues = new float[pValueCount]; - - this.mDisplayRotation = pDisplayRotation; } // =========================================================== @@ -44,12 +42,20 @@ public void setValues(final float[] pValues) { System.arraycopy(pValues, 0, this.mValues, 0, pValues.length); } + public int getAccuracy() { + return this.mAccuracy; + } + public void setAccuracy(final int pAccuracy) { this.mAccuracy = pAccuracy; } - public int getAccuracy() { - return this.mAccuracy; + public int getDisplayRotation() { + return this.mDisplayRotation; + } + + public void setDisplayRotation(final int pDisplayRotation) { + this.mDisplayRotation = pDisplayRotation; } // =========================================================== diff --git a/src/org/andengine/input/sensor/SensorDelay.java b/src/org/andengine/input/sensor/SensorDelay.java index ef8cf082c..99ae2d9f8 100644 --- a/src/org/andengine/input/sensor/SensorDelay.java +++ b/src/org/andengine/input/sensor/SensorDelay.java @@ -4,9 +4,9 @@ /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 11:14:38 - 31.10.2010 */ diff --git a/src/org/andengine/input/sensor/acceleration/AccelerationData.java b/src/org/andengine/input/sensor/acceleration/AccelerationData.java index 61392a73b..47fc7e784 100644 --- a/src/org/andengine/input/sensor/acceleration/AccelerationData.java +++ b/src/org/andengine/input/sensor/acceleration/AccelerationData.java @@ -8,9 +8,9 @@ import android.view.Surface; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 16:50:44 - 10.03.2010 */ @@ -26,7 +26,7 @@ public class AccelerationData extends BaseSensorData { @Override public void swapAxis(final float[] pValues) { final float x = -pValues[SensorManager.DATA_X]; - final float y = pValues[SensorManager.DATA_Y]; + final float y = -pValues[SensorManager.DATA_Y]; pValues[SensorManager.DATA_X] = x; pValues[SensorManager.DATA_Y] = y; } @@ -36,7 +36,7 @@ public void swapAxis(final float[] pValues) { @Override public void swapAxis(final float[] pValues) { final float x = pValues[SensorManager.DATA_Y]; - final float y = pValues[SensorManager.DATA_X]; + final float y = -pValues[SensorManager.DATA_X]; pValues[SensorManager.DATA_X] = x; pValues[SensorManager.DATA_Y] = y; } @@ -46,7 +46,7 @@ public void swapAxis(final float[] pValues) { @Override public void swapAxis(final float[] pValues) { final float x = pValues[SensorManager.DATA_X]; - final float y = -pValues[SensorManager.DATA_Y]; + final float y = pValues[SensorManager.DATA_Y]; pValues[SensorManager.DATA_X] = x; pValues[SensorManager.DATA_Y] = y; } @@ -56,7 +56,7 @@ public void swapAxis(final float[] pValues) { @Override public void swapAxis(final float[] pValues) { final float x = -pValues[SensorManager.DATA_Y]; - final float y = -pValues[SensorManager.DATA_X]; + final float y = pValues[SensorManager.DATA_X]; pValues[SensorManager.DATA_X] = x; pValues[SensorManager.DATA_Y] = y; } @@ -71,8 +71,8 @@ public void swapAxis(final float[] pValues) { // Constructors // =========================================================== - public AccelerationData(final int pDisplayOrientation) { - super(3, pDisplayOrientation); + public AccelerationData() { + super(3); } // =========================================================== @@ -100,7 +100,7 @@ public void setY(final float pY) { } public void setZ(final float pZ) { - this.mValues[SensorManager.DATA_Z] = pZ; + this.mValues[SensorManager.DATA_Z] = pZ; } @Override diff --git a/src/org/andengine/input/sensor/acceleration/AccelerationSensorOptions.java b/src/org/andengine/input/sensor/acceleration/AccelerationSensorOptions.java index 675b76bbf..b68bf6b68 100644 --- a/src/org/andengine/input/sensor/acceleration/AccelerationSensorOptions.java +++ b/src/org/andengine/input/sensor/acceleration/AccelerationSensorOptions.java @@ -3,9 +3,9 @@ import org.andengine.input.sensor.SensorDelay; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 11:10:34 - 31.10.2010 */ diff --git a/src/org/andengine/input/sensor/acceleration/IAccelerationListener.java b/src/org/andengine/input/sensor/acceleration/IAccelerationListener.java index e37893a68..0bf394a1a 100644 --- a/src/org/andengine/input/sensor/acceleration/IAccelerationListener.java +++ b/src/org/andengine/input/sensor/acceleration/IAccelerationListener.java @@ -1,9 +1,9 @@ package org.andengine.input.sensor.acceleration; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 16:58:38 - 10.03.2010 */ diff --git a/src/org/andengine/input/sensor/location/ILocationListener.java b/src/org/andengine/input/sensor/location/ILocationListener.java index 117f31503..6eeb8c2b3 100644 --- a/src/org/andengine/input/sensor/location/ILocationListener.java +++ b/src/org/andengine/input/sensor/location/ILocationListener.java @@ -5,9 +5,9 @@ import android.os.Bundle; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 10:39:23 - 31.10.2010 */ diff --git a/src/org/andengine/input/sensor/location/LocationProviderStatus.java b/src/org/andengine/input/sensor/location/LocationProviderStatus.java index 0ef84e35c..ec003407e 100644 --- a/src/org/andengine/input/sensor/location/LocationProviderStatus.java +++ b/src/org/andengine/input/sensor/location/LocationProviderStatus.java @@ -1,9 +1,9 @@ package org.andengine.input.sensor.location; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 10:55:57 - 31.10.2010 */ diff --git a/src/org/andengine/input/sensor/location/LocationSensorOptions.java b/src/org/andengine/input/sensor/location/LocationSensorOptions.java index 8689b7667..74cdc3a60 100644 --- a/src/org/andengine/input/sensor/location/LocationSensorOptions.java +++ b/src/org/andengine/input/sensor/location/LocationSensorOptions.java @@ -5,9 +5,9 @@ import android.location.Criteria; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 11:02:12 - 31.10.2010 */ @@ -33,15 +33,7 @@ public class LocationSensorOptions extends Criteria { // =========================================================== /** - * @see {@link LocationSensorOptions#setAccuracy(int)}, - * {@link LocationSensorOptions#setAltitudeRequired(boolean)}, - * {@link LocationSensorOptions#setBearingRequired(boolean)}, - * {@link LocationSensorOptions#setCostAllowed(boolean)}, - * {@link LocationSensorOptions#setEnabledOnly(boolean)}, - * {@link LocationSensorOptions#setMinimumTriggerDistance(long)}, - * {@link LocationSensorOptions#setMinimumTriggerTime(long)}, - * {@link LocationSensorOptions#setPowerRequirement(int)}, - * {@link LocationSensorOptions#setSpeedRequired(boolean)}. + * @see {@link #setAccuracy(int)}, {@link #setAltitudeRequired(boolean)}, {@link #setBearingRequired(boolean)}, {@link #setCostAllowed(boolean)}, {@link #setEnabledOnly(boolean)}, {@link #setMinimumTriggerDistance(long)}, {@link #setMinimumTriggerTime(long)}, {@link #setPowerRequirement(int)}, {@link #setSpeedRequired(boolean)}. */ public LocationSensorOptions() { diff --git a/src/org/andengine/input/sensor/orientation/IOrientationListener.java b/src/org/andengine/input/sensor/orientation/IOrientationListener.java index 1964f509f..6cd1da4ed 100644 --- a/src/org/andengine/input/sensor/orientation/IOrientationListener.java +++ b/src/org/andengine/input/sensor/orientation/IOrientationListener.java @@ -1,9 +1,9 @@ package org.andengine.input.sensor.orientation; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 11:30:42 - 25.05.2010 */ diff --git a/src/org/andengine/input/sensor/orientation/OrientationData.java b/src/org/andengine/input/sensor/orientation/OrientationData.java index 3f503cc7b..7d56e1baf 100644 --- a/src/org/andengine/input/sensor/orientation/OrientationData.java +++ b/src/org/andengine/input/sensor/orientation/OrientationData.java @@ -9,9 +9,9 @@ import android.view.Surface; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 11:30:33 - 25.05.2010 */ @@ -34,8 +34,8 @@ public class OrientationData extends BaseSensorData { // Constructors // =========================================================== - public OrientationData(final int pDisplayRotation) { - super(3, pDisplayRotation); + public OrientationData() { + super(3); } // =========================================================== @@ -68,11 +68,13 @@ public void setAccuracy(final int pAccuracy) { public void setAccelerationValues(final float[] pValues) { System.arraycopy(pValues, 0, this.mAccelerationValues, 0, pValues.length); + this.updateOrientation(); } public void setMagneticFieldValues(final float[] pValues) { System.arraycopy(pValues, 0, this.mMagneticFieldValues, 0, pValues.length); + this.updateOrientation(); } @@ -80,7 +82,7 @@ private void updateOrientation() { SensorManager.getRotationMatrix(this.mRotationMatrix, null, this.mAccelerationValues, this.mMagneticFieldValues); // TODO Use dont't use identical matrixes in remapCoordinateSystem, due to performance reasons. - switch(this.mDisplayRotation) { + switch (this.mDisplayRotation) { case Surface.ROTATION_0: /* Nothing. */ break; @@ -98,7 +100,7 @@ private void updateOrientation() { final float[] values = this.mValues; SensorManager.getOrientation(this.mRotationMatrix, values); - for(int i = values.length - 1; i >= 0; i--) { + for (int i = values.length - 1; i >= 0; i--) { values[i] = values[i] * MathConstants.RAD_TO_DEG; } } diff --git a/src/org/andengine/input/sensor/orientation/OrientationSensorOptions.java b/src/org/andengine/input/sensor/orientation/OrientationSensorOptions.java index 5945a010a..200440377 100644 --- a/src/org/andengine/input/sensor/orientation/OrientationSensorOptions.java +++ b/src/org/andengine/input/sensor/orientation/OrientationSensorOptions.java @@ -3,9 +3,9 @@ import org.andengine.input.sensor.SensorDelay; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 11:12:36 - 31.10.2010 */ diff --git a/src/org/andengine/input/touch/TouchEvent.java b/src/org/andengine/input/touch/TouchEvent.java index a56be937c..b58455349 100644 --- a/src/org/andengine/input/touch/TouchEvent.java +++ b/src/org/andengine/input/touch/TouchEvent.java @@ -5,9 +5,9 @@ import android.view.MotionEvent; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 10:17:42 - 13.07.2010 */ @@ -77,6 +77,14 @@ public float getY() { return this.mY; } + public void setX(final float pX) { + this.mX = pX; + } + + public void setY(final float pY) { + this.mY = pY; + } + public void set(final float pX, final float pY) { this.mX = pX; this.mY = pY; diff --git a/src/org/andengine/input/touch/controller/BaseTouchController.java b/src/org/andengine/input/touch/controller/BaseTouchController.java index 1afab377e..0fdbbf441 100644 --- a/src/org/andengine/input/touch/controller/BaseTouchController.java +++ b/src/org/andengine/input/touch/controller/BaseTouchController.java @@ -9,11 +9,11 @@ /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 21:06:40 - 13.07.2010 */ -public abstract class BaseTouchController implements ITouchController { +public abstract class BaseTouchController implements ITouchController { // =========================================================== // Constants // =========================================================== diff --git a/src/org/andengine/input/touch/controller/ITouchController.java b/src/org/andengine/input/touch/controller/ITouchController.java index 06ffcf93c..888a41800 100644 --- a/src/org/andengine/input/touch/controller/ITouchController.java +++ b/src/org/andengine/input/touch/controller/ITouchController.java @@ -5,9 +5,9 @@ import android.view.MotionEvent; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 20:23:45 - 13.07.2010 */ diff --git a/src/org/andengine/input/touch/controller/ITouchEventCallback.java b/src/org/andengine/input/touch/controller/ITouchEventCallback.java index a79a2a46c..6e1003252 100644 --- a/src/org/andengine/input/touch/controller/ITouchEventCallback.java +++ b/src/org/andengine/input/touch/controller/ITouchEventCallback.java @@ -3,7 +3,7 @@ import org.andengine.input.touch.TouchEvent; /** - * (c) Zynga 2012 + * (c) 2012 Zynga Inc. * * @author Nicolas Gramlich * @since 16:44:26 - 04.04.2012 diff --git a/src/org/andengine/input/touch/controller/MultiTouch.java b/src/org/andengine/input/touch/controller/MultiTouch.java index 067118a5d..e5c8a5b97 100644 --- a/src/org/andengine/input/touch/controller/MultiTouch.java +++ b/src/org/andengine/input/touch/controller/MultiTouch.java @@ -8,11 +8,11 @@ /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 16:00:38 - 14.07.2010 */ -public class MultiTouch { +public final class MultiTouch { // =========================================================== // Constants // =========================================================== @@ -21,13 +21,17 @@ public class MultiTouch { // Fields // =========================================================== - private static Boolean SUPPORTED = null; - private static Boolean SUPPORTED_DISTINCT = null; + private static Boolean sSupported; + private static Boolean sSupportedDistinct; // =========================================================== // Constructors // =========================================================== + private MultiTouch() { + + } + // =========================================================== // Getter & Setter // =========================================================== @@ -41,19 +45,19 @@ public class MultiTouch { // =========================================================== public static boolean isSupported(final Context pContext) { - if(MultiTouch.SUPPORTED == null) { - MultiTouch.SUPPORTED = SystemUtils.hasSystemFeature(pContext, PackageManager.FEATURE_TOUCHSCREEN_MULTITOUCH); + if (MultiTouch.sSupported == null) { + MultiTouch.sSupported = SystemUtils.hasSystemFeature(pContext, PackageManager.FEATURE_TOUCHSCREEN_MULTITOUCH, false); } - return MultiTouch.SUPPORTED; + return MultiTouch.sSupported; } public static boolean isSupportedDistinct(final Context pContext) { - if(MultiTouch.SUPPORTED_DISTINCT == null) { - MultiTouch.SUPPORTED_DISTINCT = SystemUtils.hasSystemFeature(pContext, PackageManager.FEATURE_TOUCHSCREEN_MULTITOUCH_DISTINCT); + if (MultiTouch.sSupportedDistinct == null) { + MultiTouch.sSupportedDistinct = SystemUtils.hasSystemFeature(pContext, PackageManager.FEATURE_TOUCHSCREEN_MULTITOUCH_DISTINCT, false); } - return MultiTouch.SUPPORTED_DISTINCT; + return MultiTouch.sSupportedDistinct; } // =========================================================== diff --git a/src/org/andengine/input/touch/controller/MultiTouchController.java b/src/org/andengine/input/touch/controller/MultiTouchController.java index 747e1ecab..3bde441f4 100644 --- a/src/org/andengine/input/touch/controller/MultiTouchController.java +++ b/src/org/andengine/input/touch/controller/MultiTouchController.java @@ -5,7 +5,7 @@ /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 20:23:33 - 13.07.2010 */ @@ -33,7 +33,7 @@ public class MultiTouchController extends BaseTouchController { @Override public void onHandleMotionEvent(final MotionEvent pMotionEvent) { final int action = pMotionEvent.getAction() & MotionEvent.ACTION_MASK; - switch(action) { + switch (action) { case MotionEvent.ACTION_DOWN: case MotionEvent.ACTION_POINTER_DOWN: this.onHandleTouchAction(MotionEvent.ACTION_DOWN, pMotionEvent); @@ -59,7 +59,7 @@ public void onHandleMotionEvent(final MotionEvent pMotionEvent) { // =========================================================== private void onHandleTouchMove(final MotionEvent pMotionEvent) { - for(int i = pMotionEvent.getPointerCount() - 1; i >= 0; i--) { + for (int i = pMotionEvent.getPointerCount() - 1; i >= 0; i--) { final int pointerIndex = i; final int pointerID = pMotionEvent.getPointerId(pointerIndex); this.fireTouchEvent(pMotionEvent.getX(pointerIndex), pMotionEvent.getY(pointerIndex), MotionEvent.ACTION_MOVE, pointerID, pMotionEvent); diff --git a/src/org/andengine/input/touch/controller/SingleTouchController.java b/src/org/andengine/input/touch/controller/SingleTouchController.java index e0eeeefab..6e0a1d236 100644 --- a/src/org/andengine/input/touch/controller/SingleTouchController.java +++ b/src/org/andengine/input/touch/controller/SingleTouchController.java @@ -3,9 +3,9 @@ import android.view.MotionEvent; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 20:23:33 - 13.07.2010 */ diff --git a/src/org/andengine/input/touch/detector/BaseDetector.java b/src/org/andengine/input/touch/detector/BaseDetector.java index 8a66f27c7..a97e6d418 100644 --- a/src/org/andengine/input/touch/detector/BaseDetector.java +++ b/src/org/andengine/input/touch/detector/BaseDetector.java @@ -7,7 +7,7 @@ /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 15:59:00 - 05.11.2010 */ @@ -52,7 +52,7 @@ public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouc } public final boolean onTouchEvent(final TouchEvent pSceneTouchEvent) { - if(this.mEnabled) { + if (this.mEnabled) { return this.onManagedTouchEvent(pSceneTouchEvent); } else { return false; diff --git a/src/org/andengine/input/touch/detector/ClickDetector.java b/src/org/andengine/input/touch/detector/ClickDetector.java index 1059a8dc4..4a5153ba1 100644 --- a/src/org/andengine/input/touch/detector/ClickDetector.java +++ b/src/org/andengine/input/touch/detector/ClickDetector.java @@ -5,7 +5,7 @@ /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @author Greg Haynes * @since 14:29:59 - 16.08.2010 @@ -65,23 +65,34 @@ public void reset() { @Override public boolean onManagedTouchEvent(final TouchEvent pSceneTouchEvent) { - switch(pSceneTouchEvent.getAction()) { + switch (pSceneTouchEvent.getAction()) { case TouchEvent.ACTION_DOWN: this.prepareClick(pSceneTouchEvent); return true; + case TouchEvent.ACTION_MOVE: + if (this.mPointerID == pSceneTouchEvent.getPointerID()) { + final long moveTimeMilliseconds = pSceneTouchEvent.getMotionEvent().getEventTime(); + if (moveTimeMilliseconds - this.mDownTimeMilliseconds <= this.mTriggerClickMaximumMilliseconds) { + return true; + } + } + return false; case TouchEvent.ACTION_UP: case TouchEvent.ACTION_CANCEL: - if(this.mPointerID == pSceneTouchEvent.getPointerID()) { - boolean handled = false; + if (this.mPointerID == pSceneTouchEvent.getPointerID()) { final long upTimeMilliseconds = pSceneTouchEvent.getMotionEvent().getEventTime(); - if(upTimeMilliseconds - this.mDownTimeMilliseconds <= this.mTriggerClickMaximumMilliseconds) { + boolean handled; + if (upTimeMilliseconds - this.mDownTimeMilliseconds <= this.mTriggerClickMaximumMilliseconds) { this.mDownTimeMilliseconds = Long.MIN_VALUE; - this.mClickDetectorListener.onClick(this, pSceneTouchEvent.getPointerID(), pSceneTouchEvent.getX(), pSceneTouchEvent.getY()); + this.mClickDetectorListener.onClick(this, this.mPointerID, pSceneTouchEvent.getX(), pSceneTouchEvent.getY()); handled = true; + } else { + handled = false; } this.mPointerID = TouchEvent.INVALID_POINTER_ID; + return handled; } else { return false; @@ -94,7 +105,7 @@ public boolean onManagedTouchEvent(final TouchEvent pSceneTouchEvent) { // =========================================================== // Methods // =========================================================== - + private void prepareClick(final TouchEvent pSceneTouchEvent) { this.mDownTimeMilliseconds = pSceneTouchEvent.getMotionEvent().getDownTime(); this.mPointerID = pSceneTouchEvent.getPointerID(); diff --git a/src/org/andengine/input/touch/detector/ContinuousHoldDetector.java b/src/org/andengine/input/touch/detector/ContinuousHoldDetector.java index cfd2b8523..513c2bfbb 100644 --- a/src/org/andengine/input/touch/detector/ContinuousHoldDetector.java +++ b/src/org/andengine/input/touch/detector/ContinuousHoldDetector.java @@ -11,10 +11,10 @@ /** * Note: Needs to be registered as an {@link IUpdateHandler} to the {@link Engine} or {@link Scene} to work properly. - * + * * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @author Greg Haynes * @since 20:49:25 - 23.08.2010 @@ -65,7 +65,7 @@ public void onUpdate(final float pSecondsElapsed) { } /** - * When {@link ContinuousHoldDetector#isHolding()} this method will call through to {@link IHoldDetectorListener#onHoldFinished(HoldDetector, long, int, float, float)}. + * When {@link #isHolding()} this method will call through to {@link IHoldDetectorListener#onHoldFinished(HoldDetector, long, int, float, float)}. */ @Override public void reset() { @@ -77,9 +77,9 @@ public void reset() { public boolean onManagedTouchEvent(final TouchEvent pSceneTouchEvent) { final MotionEvent motionEvent = pSceneTouchEvent.getMotionEvent(); - switch(pSceneTouchEvent.getAction()) { + switch (pSceneTouchEvent.getAction()) { case TouchEvent.ACTION_DOWN: - if(this.mPointerID == TouchEvent.INVALID_POINTER_ID) { + if (this.mPointerID == TouchEvent.INVALID_POINTER_ID) { this.prepareHold(pSceneTouchEvent); return true; } else { @@ -87,7 +87,7 @@ public boolean onManagedTouchEvent(final TouchEvent pSceneTouchEvent) { } case TouchEvent.ACTION_MOVE: { - if(this.mPointerID == pSceneTouchEvent.getPointerID()) { + if (this.mPointerID == pSceneTouchEvent.getPointerID()) { this.mHoldX = pSceneTouchEvent.getX(); this.mHoldY = pSceneTouchEvent.getY(); @@ -100,11 +100,11 @@ public boolean onManagedTouchEvent(final TouchEvent pSceneTouchEvent) { case TouchEvent.ACTION_UP: case TouchEvent.ACTION_CANCEL: { - if(this.mPointerID == pSceneTouchEvent.getPointerID()) { + if (this.mPointerID == pSceneTouchEvent.getPointerID()) { this.mHoldX = pSceneTouchEvent.getX(); this.mHoldY = pSceneTouchEvent.getY(); - if(this.mTriggering) { + if (this.mTriggering) { this.triggerOnHoldFinished(motionEvent.getEventTime() - this.mDownTimeMilliseconds); } @@ -130,12 +130,12 @@ protected void prepareHold(final TouchEvent pSceneTouchEvent) { // =========================================================== void fireListener() { - if(this.mPointerID != TouchEvent.INVALID_POINTER_ID) { + if (this.mPointerID != TouchEvent.INVALID_POINTER_ID) { final long holdTimeMilliseconds = System.currentTimeMillis() - this.mDownTimeMilliseconds; - if(holdTimeMilliseconds >= this.mTriggerHoldMinimumMilliseconds) { - if(this.mTriggering) { + if (holdTimeMilliseconds >= this.mTriggerHoldMinimumMilliseconds) { + if (this.mTriggering) { this.triggerOnHold(holdTimeMilliseconds); - } else if(!this.mMaximumDistanceExceeded) { + } else if (!this.mMaximumDistanceExceeded) { this.triggerOnHoldStarted(); } } diff --git a/src/org/andengine/input/touch/detector/HoldDetector.java b/src/org/andengine/input/touch/detector/HoldDetector.java index 63a6eeded..bb9bfcd8f 100644 --- a/src/org/andengine/input/touch/detector/HoldDetector.java +++ b/src/org/andengine/input/touch/detector/HoldDetector.java @@ -7,7 +7,7 @@ /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @author Greg Haynes * @since 20:49:25 - 23.08.2010 @@ -65,7 +65,7 @@ public long getTriggerHoldMinimumMilliseconds() { } public void setTriggerHoldMinimumMilliseconds(final long pTriggerHoldMinimumMilliseconds) { - if(pTriggerHoldMinimumMilliseconds < 0) { + if (pTriggerHoldMinimumMilliseconds < 0) { throw new IllegalArgumentException("pTriggerHoldMinimumMilliseconds must not be < 0."); } this.mTriggerHoldMinimumMilliseconds = pTriggerHoldMinimumMilliseconds; @@ -76,7 +76,7 @@ public float getTriggerHoldMaximumDistance() { } public void setTriggerHoldMaximumDistance(final float pTriggerHoldMaximumDistance) { - if(pTriggerHoldMaximumDistance < 0) { + if (pTriggerHoldMaximumDistance < 0) { throw new IllegalArgumentException("pTriggerHoldMaximumDistance must not be < 0."); } this.mTriggerHoldMaximumDistance = pTriggerHoldMaximumDistance; @@ -91,11 +91,11 @@ public boolean isHolding() { // =========================================================== /** - * When {@link HoldDetector#isHolding()} this method will call through to {@link IHoldDetectorListener#onHoldFinished(HoldDetector, long, int, float, float). + * When {@link #isHolding()} this method will call through to {@link IHoldDetectorListener#onHoldFinished(HoldDetector, long, int, float, float). */ @Override public void reset() { - if(this.mTriggering) { + if (this.mTriggering) { this.triggerOnHoldFinished(System.currentTimeMillis() - this.mDownTimeMilliseconds); } @@ -109,9 +109,9 @@ public void reset() { public boolean onManagedTouchEvent(final TouchEvent pSceneTouchEvent) { final MotionEvent motionEvent = pSceneTouchEvent.getMotionEvent(); - switch(pSceneTouchEvent.getAction()) { + switch (pSceneTouchEvent.getAction()) { case TouchEvent.ACTION_DOWN: - if(this.mPointerID == TouchEvent.INVALID_POINTER_ID) { + if (this.mPointerID == TouchEvent.INVALID_POINTER_ID) { this.prepareHold(pSceneTouchEvent); return true; } else { @@ -119,20 +119,20 @@ public boolean onManagedTouchEvent(final TouchEvent pSceneTouchEvent) { } case TouchEvent.ACTION_MOVE: { - if(this.mPointerID == pSceneTouchEvent.getPointerID()) { + if (this.mPointerID == pSceneTouchEvent.getPointerID()) { this.mHoldX = pSceneTouchEvent.getX(); this.mHoldY = pSceneTouchEvent.getY(); final long holdTimeMilliseconds = System.currentTimeMillis() - this.mDownTimeMilliseconds; - if(holdTimeMilliseconds >= this.mTriggerHoldMinimumMilliseconds) { - if(this.mTriggering) { + if (holdTimeMilliseconds >= this.mTriggerHoldMinimumMilliseconds) { + if (this.mTriggering) { this.triggerOnHold(holdTimeMilliseconds); } else { final float triggerHoldMaximumDistance = this.mTriggerHoldMaximumDistance; - this.mMaximumDistanceExceeded = this.mMaximumDistanceExceeded || Math.abs(this.mDownX - motionEvent.getX()) > triggerHoldMaximumDistance || Math.abs(this.mDownY - motionEvent.getY()) > triggerHoldMaximumDistance; + this.mMaximumDistanceExceeded = this.mMaximumDistanceExceeded || Math.abs(this.mDownX - motionEvent.getX()) > triggerHoldMaximumDistance || Math.abs(this.mDownY - motionEvent.getY()) > triggerHoldMaximumDistance; - if(!this.mMaximumDistanceExceeded) { - if(!this.mTriggering) { + if (!this.mMaximumDistanceExceeded) { + if (!this.mTriggering) { this.triggerOnHoldStarted(); } else { this.triggerOnHold(holdTimeMilliseconds); @@ -148,19 +148,19 @@ public boolean onManagedTouchEvent(final TouchEvent pSceneTouchEvent) { case TouchEvent.ACTION_UP: case TouchEvent.ACTION_CANCEL: { - if(this.mPointerID == pSceneTouchEvent.getPointerID()) { + if (this.mPointerID == pSceneTouchEvent.getPointerID()) { this.mHoldX = pSceneTouchEvent.getX(); this.mHoldY = pSceneTouchEvent.getY(); final long holdTimeMilliseconds = System.currentTimeMillis() - this.mDownTimeMilliseconds; - if(holdTimeMilliseconds >= this.mTriggerHoldMinimumMilliseconds) { - if(this.mTriggering) { + if (holdTimeMilliseconds >= this.mTriggerHoldMinimumMilliseconds) { + if (this.mTriggering) { this.triggerOnHoldFinished(holdTimeMilliseconds); } else { final float triggerHoldMaximumDistance = this.mTriggerHoldMaximumDistance; - this.mMaximumDistanceExceeded = this.mMaximumDistanceExceeded || Math.abs(this.mDownX - motionEvent.getX()) > triggerHoldMaximumDistance || Math.abs(this.mDownY - motionEvent.getY()) > triggerHoldMaximumDistance; + this.mMaximumDistanceExceeded = this.mMaximumDistanceExceeded || Math.abs(this.mDownX - motionEvent.getX()) > triggerHoldMaximumDistance || Math.abs(this.mDownY - motionEvent.getY()) > triggerHoldMaximumDistance; - if(!this.mMaximumDistanceExceeded) { + if (!this.mMaximumDistanceExceeded) { this.triggerOnHoldFinished(holdTimeMilliseconds); } } @@ -191,7 +191,7 @@ protected void prepareHold(final TouchEvent pSceneTouchEvent) { this.mHoldX = pSceneTouchEvent.getX(); this.mHoldY = pSceneTouchEvent.getY(); - if(this.mTriggerHoldMinimumMilliseconds == 0) { + if (this.mTriggerHoldMinimumMilliseconds == 0) { this.triggerOnHoldStarted(); } } @@ -199,13 +199,13 @@ protected void prepareHold(final TouchEvent pSceneTouchEvent) { protected void triggerOnHoldStarted() { this.mTriggering = true; - if(this.mPointerID != TouchEvent.INVALID_POINTER_ID) { + if (this.mPointerID != TouchEvent.INVALID_POINTER_ID) { this.mHoldDetectorListener.onHoldStarted(this, this.mPointerID, this.mHoldX, this.mHoldY); } } protected void triggerOnHold(final long pHoldTimeMilliseconds) { - if(this.mPointerID != TouchEvent.INVALID_POINTER_ID) { + if (this.mPointerID != TouchEvent.INVALID_POINTER_ID) { this.mHoldDetectorListener.onHold(this, pHoldTimeMilliseconds, this.mPointerID, this.mHoldX, this.mHoldY); } } @@ -213,7 +213,7 @@ protected void triggerOnHold(final long pHoldTimeMilliseconds) { protected void triggerOnHoldFinished(final long pHoldTimeMilliseconds) { this.mTriggering = false; - if(this.mPointerID != TouchEvent.INVALID_POINTER_ID) { + if (this.mPointerID != TouchEvent.INVALID_POINTER_ID) { this.mHoldDetectorListener.onHoldFinished(this, pHoldTimeMilliseconds, this.mPointerID, this.mHoldX, this.mHoldY); } } diff --git a/src/org/andengine/input/touch/detector/PinchZoomDetector.java b/src/org/andengine/input/touch/detector/PinchZoomDetector.java index cf0275183..69852a38a 100644 --- a/src/org/andengine/input/touch/detector/PinchZoomDetector.java +++ b/src/org/andengine/input/touch/detector/PinchZoomDetector.java @@ -8,7 +8,7 @@ /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 19:16:19 - 04.11.2010 */ @@ -51,11 +51,11 @@ public boolean isZooming() { // =========================================================== /** - * When {@link PinchZoomDetector#isZooming()} this method will call through to {@link IPinchZoomDetectorListener#onPinchZoomFinished(PinchZoomDetector, TouchEvent, float)}. + * When {@link #isZooming()} this method will call through to {@link IPinchZoomDetectorListener#onPinchZoomFinished(PinchZoomDetector, TouchEvent, float)}. */ @Override public void reset() { - if(this.mPinchZooming) { + if (this.mPinchZooming) { this.mPinchZoomDetectorListener.onPinchZoomFinished(this, null, this.getZoomFactor()); } @@ -70,12 +70,12 @@ public boolean onManagedTouchEvent(final TouchEvent pSceneTouchEvent) { final int action = motionEvent.getAction() & MotionEvent.ACTION_MASK; - switch(action) { + switch (action) { case MotionEvent.ACTION_POINTER_DOWN: - if(!this.mPinchZooming && this.hasTwoOrMorePointers(motionEvent)) { + if (!this.mPinchZooming && PinchZoomDetector.hasTwoOrMorePointers(motionEvent)) { this.mInitialDistance = PinchZoomDetector.calculatePointerDistance(motionEvent); this.mCurrentDistance = this.mInitialDistance; - if(this.mInitialDistance > PinchZoomDetector.TRIGGER_PINCHZOOM_MINIMUM_DISTANCE_DEFAULT) { + if (this.mInitialDistance > PinchZoomDetector.TRIGGER_PINCHZOOM_MINIMUM_DISTANCE_DEFAULT) { this.mPinchZooming = true; this.mPinchZoomDetectorListener.onPinchZoomStarted(this, pSceneTouchEvent); } @@ -84,16 +84,16 @@ public boolean onManagedTouchEvent(final TouchEvent pSceneTouchEvent) { case MotionEvent.ACTION_CANCEL: case MotionEvent.ACTION_UP: case MotionEvent.ACTION_POINTER_UP: - if(this.mPinchZooming) { + if (this.mPinchZooming) { this.mPinchZooming = false; this.mPinchZoomDetectorListener.onPinchZoomFinished(this, pSceneTouchEvent, this.getZoomFactor()); } break; case MotionEvent.ACTION_MOVE: - if(this.mPinchZooming) { - if (this.hasTwoOrMorePointers(motionEvent)) { + if (this.mPinchZooming) { + if (PinchZoomDetector.hasTwoOrMorePointers(motionEvent)) { this.mCurrentDistance = PinchZoomDetector.calculatePointerDistance(motionEvent); - if(this.mCurrentDistance > PinchZoomDetector.TRIGGER_PINCHZOOM_MINIMUM_DISTANCE_DEFAULT) { + if (this.mCurrentDistance > PinchZoomDetector.TRIGGER_PINCHZOOM_MINIMUM_DISTANCE_DEFAULT) { this.mPinchZoomDetectorListener.onPinchZoom(this, pSceneTouchEvent, this.getZoomFactor()); } } else { @@ -121,7 +121,7 @@ private static float calculatePointerDistance(final MotionEvent pMotionEvent) { return MathUtils.distance(pMotionEvent.getX(0), pMotionEvent.getY(0), pMotionEvent.getX(1), pMotionEvent.getY(1)); } - private boolean hasTwoOrMorePointers(final MotionEvent pMotionEvent) { + private static boolean hasTwoOrMorePointers(final MotionEvent pMotionEvent) { return pMotionEvent.getPointerCount() >= 2; } diff --git a/src/org/andengine/input/touch/detector/ScrollDetector.java b/src/org/andengine/input/touch/detector/ScrollDetector.java index dca6f9fb2..69bffb01e 100644 --- a/src/org/andengine/input/touch/detector/ScrollDetector.java +++ b/src/org/andengine/input/touch/detector/ScrollDetector.java @@ -5,7 +5,7 @@ /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 14:29:59 - 16.08.2010 */ @@ -22,7 +22,7 @@ public class ScrollDetector extends BaseDetector { private float mTriggerScrollMinimumDistance; private final IScrollDetectorListener mScrollDetectorListener; - + private int mPointerID = TouchEvent.INVALID_POINTER_ID; private boolean mTriggering; @@ -61,7 +61,7 @@ public void setTriggerScrollMinimumDistance(final float pTriggerScrollMinimumDis @Override public void reset() { - if(this.mTriggering) { + if (this.mTriggering) { this.mScrollDetectorListener.onScrollFinished(this, this.mPointerID, 0, 0); } @@ -76,26 +76,26 @@ public boolean onManagedTouchEvent(final TouchEvent pSceneTouchEvent) { final float touchX = this.getX(pSceneTouchEvent); final float touchY = this.getY(pSceneTouchEvent); - switch(pSceneTouchEvent.getAction()) { + switch (pSceneTouchEvent.getAction()) { case TouchEvent.ACTION_DOWN: this.prepareScroll(pSceneTouchEvent.getPointerID(), touchX, touchY); return true; case TouchEvent.ACTION_MOVE: - if(this.mPointerID == TouchEvent.INVALID_POINTER_ID) { + if (this.mPointerID == TouchEvent.INVALID_POINTER_ID) { this.prepareScroll(pSceneTouchEvent.getPointerID(), touchX, touchY); return true; - } else if(this.mPointerID == pSceneTouchEvent.getPointerID()) { + } else if (this.mPointerID == pSceneTouchEvent.getPointerID()) { final float distanceX = touchX - this.mLastX; final float distanceY = touchY - this.mLastY; final float triggerScrollMinimumDistance = this.mTriggerScrollMinimumDistance; - if(this.mTriggering || Math.abs(distanceX) > triggerScrollMinimumDistance || Math.abs(distanceY) > triggerScrollMinimumDistance) { - if(!this.mTriggering) { + if (this.mTriggering || Math.abs(distanceX) > triggerScrollMinimumDistance || Math.abs(distanceY) > triggerScrollMinimumDistance) { + if (!this.mTriggering) { this.triggerOnScrollStarted(distanceX, distanceY); } else { this.triggerOnScroll(distanceX, distanceY); } - + this.mLastX = touchX; this.mLastY = touchY; this.mTriggering = true; @@ -106,11 +106,11 @@ public boolean onManagedTouchEvent(final TouchEvent pSceneTouchEvent) { } case TouchEvent.ACTION_UP: case TouchEvent.ACTION_CANCEL: - if(this.mPointerID == pSceneTouchEvent.getPointerID()) { + if (this.mPointerID == pSceneTouchEvent.getPointerID()) { final float distanceX = touchX - this.mLastX; final float distanceY = touchY - this.mLastY; - if(this.mTriggering) { + if (this.mTriggering) { this.triggerOnScrollFinished(distanceX, distanceY); } @@ -125,30 +125,30 @@ public boolean onManagedTouchEvent(final TouchEvent pSceneTouchEvent) { // =========================================================== // Methods // =========================================================== - + private void prepareScroll(final int pPointerID, final float pTouchX, final float pTouchY) { this.mLastX = pTouchX; this.mLastY = pTouchY; this.mTriggering = false; this.mPointerID = pPointerID; } - + private void triggerOnScrollStarted(final float pDistanceX, final float pDistanceY) { - if(this.mPointerID != TouchEvent.INVALID_POINTER_ID) { + if (this.mPointerID != TouchEvent.INVALID_POINTER_ID) { this.mScrollDetectorListener.onScrollStarted(this, this.mPointerID, pDistanceX, pDistanceY); } } - + private void triggerOnScroll(final float pDistanceX, final float pDistanceY) { - if(this.mPointerID != TouchEvent.INVALID_POINTER_ID) { + if (this.mPointerID != TouchEvent.INVALID_POINTER_ID) { this.mScrollDetectorListener.onScroll(this, this.mPointerID, pDistanceX, pDistanceY); } } - + private void triggerOnScrollFinished(final float pDistanceX, final float pDistanceY) { this.mTriggering = false; - - if(this.mPointerID != TouchEvent.INVALID_POINTER_ID) { + + if (this.mPointerID != TouchEvent.INVALID_POINTER_ID) { this.mScrollDetectorListener.onScrollFinished(this, this.mPointerID, pDistanceX, pDistanceY); } } diff --git a/src/org/andengine/input/touch/detector/SurfaceGestureDetector.java b/src/org/andengine/input/touch/detector/SurfaceGestureDetector.java index cc556347b..21ce4b58b 100644 --- a/src/org/andengine/input/touch/detector/SurfaceGestureDetector.java +++ b/src/org/andengine/input/touch/detector/SurfaceGestureDetector.java @@ -11,7 +11,7 @@ * @author rkpost * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 11:36:26 - 11.10.2010 */ @@ -116,16 +116,16 @@ public boolean onFling(final MotionEvent pMotionEventStart, final MotionEvent pM final boolean isHorizontalFling = Math.abs(pVelocityX) > Math.abs(pVelocityY); - if(isHorizontalFling) { - if(pMotionEventStart.getX() - pMotionEventEnd.getX() > swipeMinDistance) { + if (isHorizontalFling) { + if (pMotionEventStart.getX() - pMotionEventEnd.getX() > swipeMinDistance) { return SurfaceGestureDetector.this.onSwipeLeft(); - } else if(pMotionEventEnd.getX() - pMotionEventStart.getX() > swipeMinDistance) { + } else if (pMotionEventEnd.getX() - pMotionEventStart.getX() > swipeMinDistance) { return SurfaceGestureDetector.this.onSwipeRight(); } } else { - if(pMotionEventStart.getY() - pMotionEventEnd.getY() > swipeMinDistance) { + if (pMotionEventStart.getY() - pMotionEventEnd.getY() > swipeMinDistance) { return SurfaceGestureDetector.this.onSwipeUp(); - } else if(pMotionEventEnd.getY() - pMotionEventStart.getY() > swipeMinDistance) { + } else if (pMotionEventEnd.getY() - pMotionEventStart.getY() > swipeMinDistance) { return SurfaceGestureDetector.this.onSwipeDown(); } } diff --git a/src/org/andengine/input/touch/detector/SurfaceGestureDetectorAdapter.java b/src/org/andengine/input/touch/detector/SurfaceGestureDetectorAdapter.java index 3c5cc03d1..f27fbf1f7 100644 --- a/src/org/andengine/input/touch/detector/SurfaceGestureDetectorAdapter.java +++ b/src/org/andengine/input/touch/detector/SurfaceGestureDetectorAdapter.java @@ -3,7 +3,7 @@ import android.content.Context; /** - * (c) Zynga 2012 + * (c) 2012 Zynga Inc. * * @author Nicolas Gramlich * @since 16:53:40 - 04.04.2012 @@ -23,7 +23,7 @@ public class SurfaceGestureDetectorAdapter extends SurfaceGestureDetector { public SurfaceGestureDetectorAdapter(final Context pContext) { super(pContext); - } + } public SurfaceGestureDetectorAdapter(final Context pContext, final float pSwipeMinDistance) { super(pContext, pSwipeMinDistance); diff --git a/src/org/andengine/input/touch/detector/SurfaceScrollDetector.java b/src/org/andengine/input/touch/detector/SurfaceScrollDetector.java index 5ffb86b9c..1d4ae44e6 100644 --- a/src/org/andengine/input/touch/detector/SurfaceScrollDetector.java +++ b/src/org/andengine/input/touch/detector/SurfaceScrollDetector.java @@ -5,7 +5,7 @@ /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 16:12:29 - 16.08.2010 */ diff --git a/src/org/andengine/opengl/GLES20Fix.java b/src/org/andengine/opengl/GLES20Fix.java index 349b9b7d9..6f4a14c42 100644 --- a/src/org/andengine/opengl/GLES20Fix.java +++ b/src/org/andengine/opengl/GLES20Fix.java @@ -3,21 +3,23 @@ import org.andengine.util.exception.AndEngineRuntimeException; import org.andengine.util.system.SystemUtils; +import android.annotation.TargetApi; import android.opengl.GLES20; import android.os.Build; /** - * (c) Zynga 2011 + * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 17:44:43 - 04.09.2011 */ +@TargetApi(Build.VERSION_CODES.GINGERBREAD) public class GLES20Fix { // =========================================================== // Constants // =========================================================== - private static boolean NATIVE_LIB_LOADED; + private static final boolean NATIVE_LIB_LOADED; /** Android issue 8931. */ private static final boolean WORKAROUND_MISSING_GLES20_METHODS; @@ -32,8 +34,8 @@ public class GLES20Fix { } NATIVE_LIB_LOADED = loadLibrarySuccess; - if(SystemUtils.isAndroidVersionOrLower(Build.VERSION_CODES.FROYO)) { - if(loadLibrarySuccess) { + if (SystemUtils.isAndroidVersionOrLower(Build.VERSION_CODES.FROYO)) { + if (loadLibrarySuccess) { WORKAROUND_MISSING_GLES20_METHODS = true; } else { throw new AndEngineRuntimeException("Inherently incompatible device detected."); @@ -71,7 +73,7 @@ private GLES20Fix() { public static native void glDrawElements(final int pMode, final int pCount, final int pType, final int pOffset); public static void glVertexAttribPointerFix(final int pIndex, final int pSize, final int pType, final boolean pNormalized, final int pStride, final int pOffset) { - if(GLES20Fix.WORKAROUND_MISSING_GLES20_METHODS) { + if (GLES20Fix.WORKAROUND_MISSING_GLES20_METHODS) { GLES20Fix.glVertexAttribPointerFix(pIndex, pSize, pType, pNormalized, pStride, pOffset); } else { GLES20.glVertexAttribPointer(pIndex, pSize, pType, pNormalized, pStride, pOffset); @@ -79,7 +81,7 @@ public static void glVertexAttribPointerFix(final int pIndex, final int pSize, f } public static void glDrawElementsFix(final int pMode, final int pCount, final int pType, final int pOffset) { - if(GLES20Fix.WORKAROUND_MISSING_GLES20_METHODS) { + if (GLES20Fix.WORKAROUND_MISSING_GLES20_METHODS) { GLES20Fix.glDrawElements(pMode, pCount, pType, pOffset); } else { GLES20.glDrawElements(pMode, pCount, pType, pOffset); diff --git a/src/org/andengine/opengl/exception/GLException.java b/src/org/andengine/opengl/exception/GLException.java index 7beaddd07..9d38587a9 100644 --- a/src/org/andengine/opengl/exception/GLException.java +++ b/src/org/andengine/opengl/exception/GLException.java @@ -3,7 +3,7 @@ import android.opengl.GLU; /** - * (c) Zynga 2012 + * (c) 2012 Zynga Inc. * * @author Nicolas Gramlich * @since 10:44:27 - 13.02.2012 @@ -53,7 +53,7 @@ public int getError() { private static String getErrorString(final int pError) { String errorString = GLU.gluErrorString(pError); - if(errorString == null) { + if (errorString == null) { errorString = "Unknown error '0x" + Integer.toHexString(pError) + "'."; } return errorString; diff --git a/src/org/andengine/opengl/exception/GLFrameBufferException.java b/src/org/andengine/opengl/exception/GLFrameBufferException.java index fc050dac6..71133b4ef 100644 --- a/src/org/andengine/opengl/exception/GLFrameBufferException.java +++ b/src/org/andengine/opengl/exception/GLFrameBufferException.java @@ -2,7 +2,7 @@ /** - * (c) Zynga 2012 + * (c) 2012 Zynga Inc. * * @author Nicolas Gramlich * @since 10:47:22 - 13.02.2012 diff --git a/src/org/andengine/opengl/exception/RenderTextureInitializationException.java b/src/org/andengine/opengl/exception/RenderTextureInitializationException.java index d3339d9cf..a6bbd8f05 100644 --- a/src/org/andengine/opengl/exception/RenderTextureInitializationException.java +++ b/src/org/andengine/opengl/exception/RenderTextureInitializationException.java @@ -3,7 +3,7 @@ import org.andengine.util.exception.AndEngineRuntimeException; /** - * (c) Zynga 2012 + * (c) 2012 Zynga Inc. * * @author Nicolas Gramlich * @since 11:59:45 AM - Feb 13, 2012 diff --git a/src/org/andengine/opengl/font/BitmapFont.java b/src/org/andengine/opengl/font/BitmapFont.java index 027804b7f..4c56735d9 100644 --- a/src/org/andengine/opengl/font/BitmapFont.java +++ b/src/org/andengine/opengl/font/BitmapFont.java @@ -33,7 +33,7 @@ *
  • http://www.angelcode.com/products/bmfont/ (Free, Windows only)
  • * * - * (c) Zynga 2011 + * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 17:54:59 - 01.11.2011 @@ -200,7 +200,7 @@ public BitmapFont(final TextureManager pTextureManager, final AssetManager pAsse final BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in), StreamUtils.IO_BUFFER_SIZE); final String assetBasePath; - if(pAssetPath.indexOf('/') == -1) { + if (pAssetPath.indexOf('/') == -1) { assetBasePath = ""; } else { assetBasePath = pAssetPath.substring(0, pAssetPath.lastIndexOf('/') + 1); @@ -214,12 +214,12 @@ public BitmapFont(final TextureManager pTextureManager, final AssetManager pAsse /* Common. */ { final String common = bufferedReader.readLine(); - if((common != null) && common.startsWith(BitmapFont.TAG_COMMON)) { + if ((common != null) && common.startsWith(BitmapFont.TAG_COMMON)) { final String[] commonAttributes = TextUtils.SPLITPATTERN_SPACE.split(common, BitmapFont.TAG_COMMON_ATTRIBUTECOUNT + 1); - if((commonAttributes.length - 1) != BitmapFont.TAG_COMMON_ATTRIBUTECOUNT) { + if ((commonAttributes.length - 1) != BitmapFont.TAG_COMMON_ATTRIBUTECOUNT) { throw new FontException("Expected: '" + BitmapFont.TAG_COMMON_ATTRIBUTECOUNT + "' " + BitmapFont.TAG_COMMON + " attributes, found: '" + (commonAttributes.length - 1) + "'."); } - if(!commonAttributes[0].equals(BitmapFont.TAG_COMMON)) { + if (!commonAttributes[0].equals(BitmapFont.TAG_COMMON)) { throw new FontException("Expected: '" + BitmapFont.TAG_COMMON + "' attributes."); } this.mLineHeight = BitmapFont.getIntAttribute(commonAttributes, BitmapFont.TAG_COMMON_ATTRIBUTE_LINEHEIGHT_INDEX, BitmapFont.TAG_COMMON_ATTRIBUTE_LINEHEIGHT); @@ -229,12 +229,12 @@ public BitmapFont(final TextureManager pTextureManager, final AssetManager pAsse this.mBitmapFontPageCount = BitmapFont.getIntAttribute(commonAttributes, BitmapFont.TAG_COMMON_ATTRIBUTE_PAGES_INDEX, BitmapFont.TAG_COMMON_ATTRIBUTE_PAGES); this.mPacked = BitmapFont.getBooleanAttribute(commonAttributes, BitmapFont.TAG_COMMON_ATTRIBUTE_PACKED_INDEX, BitmapFont.TAG_COMMON_ATTRIBUTE_PACKED); - if(this.mBitmapFontPageCount != 1) { + if (this.mBitmapFontPageCount != 1) { throw new FontException("Only a single page is supported."); } this.mBitmapFontPages = new BitmapFontPage[this.mBitmapFontPageCount]; - if(this.mPacked) { + if (this.mPacked) { throw new FontException("Packed is not supported."); } } else { @@ -243,19 +243,19 @@ public BitmapFont(final TextureManager pTextureManager, final AssetManager pAsse } /* Pages. */ - for(int i = 0; i < this.mBitmapFontPageCount; i++) { + for (int i = 0; i < this.mBitmapFontPageCount; i++) { this.mBitmapFontPages[i] = new BitmapFontPage(pAssetManager, assetBasePath, bufferedReader.readLine()); } /* Chars. */ { final String chars = bufferedReader.readLine(); - if((chars != null) && chars.startsWith(BitmapFont.TAG_CHARS)) { + if ((chars != null) && chars.startsWith(BitmapFont.TAG_CHARS)) { final String[] charsAttributes = TextUtils.SPLITPATTERN_SPACE.split(chars, BitmapFont.TAG_CHARS_ATTRIBUTECOUNT + 1); - if((charsAttributes.length - 1) != BitmapFont.TAG_CHARS_ATTRIBUTECOUNT) { + if ((charsAttributes.length - 1) != BitmapFont.TAG_CHARS_ATTRIBUTECOUNT) { throw new FontException("Expected: '" + BitmapFont.TAG_CHARS_ATTRIBUTECOUNT + "' " + BitmapFont.TAG_CHARS + " attributes, found: '" + (charsAttributes.length - 1) + "'."); } - if(!charsAttributes[0].equals(BitmapFont.TAG_CHARS)) { + if (!charsAttributes[0].equals(BitmapFont.TAG_CHARS)) { throw new FontException("Expected: '" + BitmapFont.TAG_CHARS + "' attributes."); } @@ -270,12 +270,12 @@ public BitmapFont(final TextureManager pTextureManager, final AssetManager pAsse /* Kernings. */ { final String kernings = bufferedReader.readLine(); - if((kernings != null) && kernings.startsWith(BitmapFont.TAG_KERNINGS)) { + if ((kernings != null) && kernings.startsWith(BitmapFont.TAG_KERNINGS)) { final String[] kerningsAttributes = TextUtils.SPLITPATTERN_SPACE.split(kernings, BitmapFont.TAG_KERNINGS_ATTRIBUTECOUNT + 1); - if((kerningsAttributes.length - 1) != BitmapFont.TAG_KERNINGS_ATTRIBUTECOUNT) { + if ((kerningsAttributes.length - 1) != BitmapFont.TAG_KERNINGS_ATTRIBUTECOUNT) { throw new FontException("Expected: '" + BitmapFont.TAG_KERNINGS_ATTRIBUTECOUNT + "' " + BitmapFont.TAG_KERNINGS + " attributes, found: '" + (kerningsAttributes.length - 1) + "'."); } - if(!kerningsAttributes[0].equals(BitmapFont.TAG_KERNINGS)) { + if (!kerningsAttributes[0].equals(BitmapFont.TAG_KERNINGS)) { throw new FontException("Expected: '" + BitmapFont.TAG_KERNINGS + "' attributes."); } @@ -346,6 +346,11 @@ public void unload() { this.unloadTextures(); } + @Override + public float getAscent() { + return 0; + } + @Override public float getLineHeight() { return this.mLineHeight; @@ -354,7 +359,7 @@ public float getLineHeight() { @Override public Letter getLetter(final char pChar) throws LetterNotFoundException { final Letter letter = this.mCharacterToLetterMap.get(pChar); - if(letter == null) { + if (letter == null) { throw new LetterNotFoundException("Letter '" + pChar + "' not found."); } return letter; @@ -367,7 +372,7 @@ public Letter getLetter(final char pChar) throws LetterNotFoundException { public void loadTextures() { final BitmapFontPage[] bitmapFontPages = this.mBitmapFontPages; final int bitmapFontPageCount = bitmapFontPages.length; - for(int i = 0; i < bitmapFontPageCount; i++) { + for (int i = 0; i < bitmapFontPageCount; i++) { bitmapFontPages[i].getTexture().load(); } } @@ -375,19 +380,19 @@ public void loadTextures() { public void unloadTextures() { final BitmapFontPage[] bitmapFontPages = this.mBitmapFontPages; final int bitmapFontPageCount = bitmapFontPages.length; - for(int i = 0; i < bitmapFontPageCount; i++) { + for (int i = 0; i < bitmapFontPageCount; i++) { bitmapFontPages[i].getTexture().unload(); } } private void parseCharacters(final int pCharacterCount, final BufferedReader pBufferedReader) throws IOException { - for(int i = pCharacterCount - 1; i >= 0; i--) { + for (int i = pCharacterCount - 1; i >= 0; i--) { final String character = pBufferedReader.readLine(); final String[] charAttributes = TextUtils.SPLITPATTERN_SPACES.split(character, BitmapFont.TAG_CHAR_ATTRIBUTECOUNT + 1); - if((charAttributes.length - 1) != BitmapFont.TAG_CHAR_ATTRIBUTECOUNT) { + if ((charAttributes.length - 1) != BitmapFont.TAG_CHAR_ATTRIBUTECOUNT) { throw new FontException("Expected: '" + BitmapFont.TAG_CHAR_ATTRIBUTECOUNT + "' " + BitmapFont.TAG_CHAR + " attributes, found: '" + (charAttributes.length - 1) + "'."); } - if(!charAttributes[0].equals(BitmapFont.TAG_CHAR)) { + if (!charAttributes[0].equals(BitmapFont.TAG_CHAR)) { throw new FontException("Expected: '" + BitmapFont.TAG_CHAR + "' attributes."); } @@ -411,18 +416,18 @@ private void parseCharacters(final int pCharacterCount, final BufferedReader pBu final float u2 = (x + width) / textureWidth; final float v2 = (y + height) / textureHeight; - this.mCharacterToLetterMap.put(id, new Letter((char)id, x, y, width, height, xOffset, yOffset, xAdvance, u, v, u2, v2)); + this.mCharacterToLetterMap.put(id, new Letter((char) id, x, y, width, height, xOffset, yOffset, xAdvance, u, v, u2, v2)); } } private void parseKernings(final int pKerningsCount, final BufferedReader pBufferedReader) throws IOException { - for(int i = pKerningsCount - 1; i >= 0; i--) { + for (int i = pKerningsCount - 1; i >= 0; i--) { final String kerning = pBufferedReader.readLine(); final String[] charAttributes = TextUtils.SPLITPATTERN_SPACES.split(kerning, BitmapFont.TAG_KERNING_ATTRIBUTECOUNT + 1); - if((charAttributes.length - 1) != BitmapFont.TAG_KERNING_ATTRIBUTECOUNT) { + if ((charAttributes.length - 1) != BitmapFont.TAG_KERNING_ATTRIBUTECOUNT) { throw new FontException("Expected: '" + BitmapFont.TAG_KERNING_ATTRIBUTECOUNT + "' " + BitmapFont.TAG_KERNING + " attributes, found: '" + (charAttributes.length - 1) + "'."); } - if(!charAttributes[0].equals(BitmapFont.TAG_KERNING)) { + if (!charAttributes[0].equals(BitmapFont.TAG_KERNING)) { throw new FontException("Expected: '" + BitmapFont.TAG_KERNING + "' attributes."); } @@ -438,13 +443,13 @@ private static boolean getBooleanAttribute(final String[] pData, final int pPosi final String data = pData[pPosition]; final int attributeLength = pAttribute.length(); - if(!data.startsWith(pAttribute) || (data.charAt(attributeLength) != '=')) { + if (!data.startsWith(pAttribute) || (data.charAt(attributeLength) != '=')) { throw new FontException("Expected '" + pAttribute + "' at position '" + pPosition + "', but found: '" + data + "'."); } return Integer.parseInt(data.substring(attributeLength + 1)) != 0; } - + private static char getCharAttribute(final String[] pData, final int pPosition, final String pAttribute) { return (char) BitmapFont.getIntAttribute(pData, pPosition, pAttribute); } @@ -453,7 +458,7 @@ private static int getIntAttribute(final String[] pData, final int pPosition, fi final String data = pData[pPosition]; final int attributeLength = pAttribute.length(); - if(!data.startsWith(pAttribute) || (data.charAt(attributeLength) != '=')) { + if (!data.startsWith(pAttribute) || (data.charAt(attributeLength) != '=')) { throw new FontException("Expected '" + pAttribute + "' at position '" + pPosition + "', but found: '" + data + "'."); } @@ -464,7 +469,7 @@ private static String getStringAttribute(final String[] pData, final int pPositi final String data = pData[pPosition]; final int attributeLength = pAttribute.length(); - if(!data.startsWith(pAttribute) || (data.charAt(attributeLength) != '=')) { + if (!data.startsWith(pAttribute) || (data.charAt(attributeLength) != '=')) { throw new FontException("Expected '" + pAttribute + "' at position '" + pPosition + "', but found: '" + data + "'."); } @@ -475,7 +480,7 @@ private static String getAttribute(final String[] pData, final int pPosition, fi final String data = pData[pPosition]; final int attributeLength = pAttribute.length(); - if(!data.startsWith(pAttribute)) { + if (!data.startsWith(pAttribute)) { throw new FontException("Expected '" + pAttribute + "' at position '" + pPosition + "', but found: '" + data + "'."); } @@ -574,16 +579,16 @@ public class BitmapFontInfo { // =========================================================== public BitmapFontInfo(final String pData) throws FontException { - if(pData == null) { + if (pData == null) { throw new FontException("pData must not be null."); } final String[] infoAttributes = TextUtils.SPLITPATTERN_SPACE.split(pData, BitmapFont.TAG_INFO_ATTRIBUTECOUNT + 1); - if((infoAttributes.length - 1) != BitmapFont.TAG_INFO_ATTRIBUTECOUNT) { + if ((infoAttributes.length - 1) != BitmapFont.TAG_INFO_ATTRIBUTECOUNT) { throw new FontException("Expected: '" + BitmapFont.TAG_INFO_ATTRIBUTECOUNT + "' " + BitmapFont.TAG_INFO + " attributes, found: '" + (infoAttributes.length - 1) + "'."); } - if(!infoAttributes[0].equals(BitmapFont.TAG_INFO)) { + if (!infoAttributes[0].equals(BitmapFont.TAG_INFO)) { throw new FontException("Expected: '" + BitmapFont.TAG_INFO + "' attributes."); } @@ -706,10 +711,10 @@ public class BitmapFontPage { public BitmapFontPage(final AssetManager pAssetManager, final String pAssetBasePath, final String pData) throws IOException { final String[] pageAttributes = TextUtils.SPLITPATTERN_SPACE.split(pData, BitmapFont.TAG_PAGE_ATTRIBUTECOUNT + 1); - if((pageAttributes.length - 1) != BitmapFont.TAG_PAGE_ATTRIBUTECOUNT) { + if ((pageAttributes.length - 1) != BitmapFont.TAG_PAGE_ATTRIBUTECOUNT) { throw new FontException("Expected: '" + BitmapFont.TAG_PAGE_ATTRIBUTECOUNT + "' " + BitmapFont.TAG_PAGE + " attributes, found: '" + (pageAttributes.length - 1) + "'."); } - if(!pageAttributes[0].equals(BitmapFont.TAG_PAGE)) { + if (!pageAttributes[0].equals(BitmapFont.TAG_PAGE)) { throw new FontException("Expected: '" + BitmapFont.TAG_PAGE + "' attributes."); } diff --git a/src/org/andengine/opengl/font/Font.java b/src/org/andengine/opengl/font/Font.java index 14d788fc9..d9e29d962 100644 --- a/src/org/andengine/opengl/font/Font.java +++ b/src/org/andengine/opengl/font/Font.java @@ -6,8 +6,8 @@ import org.andengine.opengl.texture.ITexture; import org.andengine.opengl.texture.PixelFormat; import org.andengine.opengl.util.GLState; +import org.andengine.util.adt.color.Color; import org.andengine.util.adt.map.SparseArrayUtils; -import org.andengine.util.color.Color; import org.andengine.util.math.MathUtils; import android.graphics.Bitmap; @@ -25,7 +25,7 @@ /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 10:39:33 - 03.04.2010 */ @@ -142,7 +142,7 @@ public float getLineHeight() { @Override public synchronized Letter getLetter(final char pCharacter) throws FontException { Letter letter = this.mManagedCharacterToLetterMap.get(pCharacter); - if(letter == null) { + if (letter == null) { letter = this.createLetter(pCharacter); this.mLettersPendingToBeDrawnToTexture.add(letter); @@ -160,7 +160,7 @@ public synchronized void invalidateLetters() { final SparseArray managedCharacterToLetterMap = this.mManagedCharacterToLetterMap; /* Make all letters redraw to the texture. */ - for(int i = managedCharacterToLetterMap.size() - 1; i >= 0; i--) { + for (int i = managedCharacterToLetterMap.size() - 1; i >= 0; i--) { lettersPendingToBeDrawnToTexture.add(managedCharacterToLetterMap.valueAt(i)); } } @@ -185,7 +185,7 @@ protected Bitmap getLetterBitmap(final Letter pLetter) throws FontException { /* Actually draw the character. */ final float drawLetterLeft = -pLetter.mOffsetX; - final float drawLetterTop = -(pLetter.mOffsetY + this.getAscent()); + final float drawLetterTop = -pLetter.mOffsetY; this.drawLetter(characterAsString, drawLetterLeft, drawLetterTop); @@ -197,7 +197,7 @@ protected void drawLetter(final String pCharacterAsString, final float pLeft, fi } public void prepareLetters(final char... pCharacters) throws FontException { - for(final char character : pCharacters) { + for (final char character : pCharacters) { this.getLetter(character); } } @@ -219,16 +219,16 @@ private Letter createLetter(final char pCharacter) throws FontException { final float advance = this.getLetterAdvance(characterAsString); final boolean whitespace = Character.isWhitespace(pCharacter) || (letterWidth == 0) || (letterHeight == 0); - if(whitespace) { + if (whitespace) { letter = new Letter(pCharacter, advance); } else { - if((this.mCurrentTextureX + Font.LETTER_TEXTURE_PADDING + letterWidth) >= textureWidth) { + if ((this.mCurrentTextureX + Font.LETTER_TEXTURE_PADDING + letterWidth) >= textureWidth) { this.mCurrentTextureX = 0; this.mCurrentTextureY += this.mCurrentTextureYHeightMax + (2 * Font.LETTER_TEXTURE_PADDING); this.mCurrentTextureYHeightMax = 0; } - if((this.mCurrentTextureY + letterHeight) >= textureHeight) { + if ((this.mCurrentTextureY + letterHeight) >= textureHeight) { throw new FontException("Not enough space for " + Letter.class.getSimpleName() + ": '" + pCharacter + "' on the " + this.mTexture.getClass().getSimpleName() + ". Existing Letters: " + SparseArrayUtils.toString(this.mManagedCharacterToLetterMap)); } @@ -241,7 +241,7 @@ private Letter createLetter(final char pCharacter) throws FontException { final float u2 = (this.mCurrentTextureX + letterWidth) / textureWidth; final float v2 = (this.mCurrentTextureY + letterHeight) / textureHeight; - letter = new Letter(pCharacter, this.mCurrentTextureX - Font.LETTER_TEXTURE_PADDING, this.mCurrentTextureY - Font.LETTER_TEXTURE_PADDING, letterWidth, letterHeight, letterLeft, letterTop - this.getAscent(), advance, u, v, u2, v2); + letter = new Letter(pCharacter, this.mCurrentTextureX - Font.LETTER_TEXTURE_PADDING, this.mCurrentTextureY - Font.LETTER_TEXTURE_PADDING, letterWidth, letterHeight, letterLeft, letterTop, advance, u, v, u2, v2); this.mCurrentTextureX += letterWidth + Font.LETTER_TEXTURE_PADDING; } @@ -253,31 +253,31 @@ protected void updateTextBounds(final String pCharacterAsString) { } public synchronized void update(final GLState pGLState) { - if(this.mTexture.isLoadedToHardware()) { + if (this.mTexture.isLoadedToHardware()) { final ArrayList lettersPendingToBeDrawnToTexture = this.mLettersPendingToBeDrawnToTexture; - if(lettersPendingToBeDrawnToTexture.size() > 0) { + if (lettersPendingToBeDrawnToTexture.size() > 0) { this.mTexture.bind(pGLState); final PixelFormat pixelFormat = this.mTexture.getPixelFormat(); final boolean preMultipyAlpha = this.mTexture.getTextureOptions().mPreMultiplyAlpha; - for(int i = lettersPendingToBeDrawnToTexture.size() - 1; i >= 0; i--) { + for (int i = lettersPendingToBeDrawnToTexture.size() - 1; i >= 0; i--) { final Letter letter = lettersPendingToBeDrawnToTexture.get(i); - if(!letter.isWhitespace()) { + if (!letter.isWhitespace()) { final Bitmap bitmap = this.getLetterBitmap(letter); final boolean useDefaultAlignment = MathUtils.isPowerOfTwo(bitmap.getWidth()) && MathUtils.isPowerOfTwo(bitmap.getHeight()) && (pixelFormat == PixelFormat.RGBA_8888); - if(!useDefaultAlignment) { + if (!useDefaultAlignment) { /* Adjust unpack alignment. */ GLES20.glPixelStorei(GLES20.GL_UNPACK_ALIGNMENT, 1); } - if(preMultipyAlpha) { + if (preMultipyAlpha) { GLUtils.texSubImage2D(GLES20.GL_TEXTURE_2D, 0, letter.mTextureX, letter.mTextureY, bitmap); } else { pGLState.glTexSubImage2D(GLES20.GL_TEXTURE_2D, 0, letter.mTextureX, letter.mTextureY, bitmap, pixelFormat); } - if(!useDefaultAlignment) { + if (!useDefaultAlignment) { /* Restore default unpack alignment. */ GLES20.glPixelStorei(GLES20.GL_UNPACK_ALIGNMENT, GLState.GL_UNPACK_ALIGNMENT_DEFAULT); } diff --git a/src/org/andengine/opengl/font/FontFactory.java b/src/org/andengine/opengl/font/FontFactory.java index 9ece71bac..2f3e9bafd 100644 --- a/src/org/andengine/opengl/font/FontFactory.java +++ b/src/org/andengine/opengl/font/FontFactory.java @@ -1,11 +1,11 @@ package org.andengine.opengl.font; +import org.andengine.opengl.texture.EmptyTexture; import org.andengine.opengl.texture.ITexture; +import org.andengine.opengl.texture.PixelFormat; import org.andengine.opengl.texture.TextureManager; import org.andengine.opengl.texture.TextureOptions; -import org.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; -import org.andengine.opengl.texture.bitmap.BitmapTextureFormat; -import org.andengine.util.color.Color; +import org.andengine.util.adt.color.Color; import android.content.res.AssetManager; import android.graphics.Typeface; @@ -13,11 +13,11 @@ /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 17:17:28 - 16.06.2010 */ -public class FontFactory { +public final class FontFactory { // =========================================================== // Constants // =========================================================== @@ -35,6 +35,10 @@ public class FontFactory { // Constructors // =========================================================== + private FontFactory() { + + } + // =========================================================== // Getter & Setter // =========================================================== @@ -43,13 +47,17 @@ public class FontFactory { * @param pAssetBasePath must end with '/' or have .length() == 0. */ public static void setAssetBasePath(final String pAssetBasePath) { - if(pAssetBasePath.endsWith("/") || pAssetBasePath.length() == 0) { + if (pAssetBasePath.endsWith("/") || pAssetBasePath.length() == 0) { FontFactory.sAssetBasePath = pAssetBasePath; } else { - throw new IllegalStateException("pAssetBasePath must end with '/' or be lenght zero."); + throw new IllegalStateException("pAssetBasePath must end with '/' or be length zero."); } } + public static String getAssetBasePath() { + return FontFactory.sAssetBasePath; + } + public static void onCreate() { FontFactory.setAssetBasePath(""); } @@ -115,23 +123,23 @@ public static Font create(final FontManager pFontManager, final TextureManager p } public static Font create(final FontManager pFontManager, final TextureManager pTextureManager, final int pTextureWidth, final int pTextureHeight, final TextureOptions pTextureOptions, final Typeface pTypeface, final float pSize, final boolean pAntiAlias, final int pColor) { - return FontFactory.create(pFontManager, pTextureManager, pTextureWidth, pTextureHeight, BitmapTextureFormat.RGBA_8888, pTextureOptions, pTypeface, pSize, pAntiAlias, pColor); + return FontFactory.create(pFontManager, pTextureManager, pTextureWidth, pTextureHeight, PixelFormat.RGBA_8888, pTextureOptions, pTypeface, pSize, pAntiAlias, pColor); } - public static Font create(final FontManager pFontManager, final TextureManager pTextureManager, final int pTextureWidth, final int pTextureHeight, final BitmapTextureFormat pBitmapTextureFormat, final TextureOptions pTextureOptions, final Typeface pTypeface, final float pSize) { - return FontFactory.create(pFontManager, pTextureManager, pTextureWidth, pTextureHeight, pBitmapTextureFormat, pTextureOptions, pTypeface, pSize, FontFactory.ANTIALIAS_DEFAULT, FontFactory.COLOR_DEFAULT); + public static Font create(final FontManager pFontManager, final TextureManager pTextureManager, final int pTextureWidth, final int pTextureHeight, final PixelFormat pPixelFormat, final TextureOptions pTextureOptions, final Typeface pTypeface, final float pSize) { + return FontFactory.create(pFontManager, pTextureManager, pTextureWidth, pTextureHeight, pPixelFormat, pTextureOptions, pTypeface, pSize, FontFactory.ANTIALIAS_DEFAULT, FontFactory.COLOR_DEFAULT); } - public static Font create(final FontManager pFontManager, final TextureManager pTextureManager, final int pTextureWidth, final int pTextureHeight, final BitmapTextureFormat pBitmapTextureFormat, final TextureOptions pTextureOptions, final Typeface pTypeface, final float pSize, final boolean pAntiAlias) { - return FontFactory.create(pFontManager, pTextureManager, pTextureWidth, pTextureHeight, pBitmapTextureFormat, pTextureOptions, pTypeface, pSize, pAntiAlias, FontFactory.COLOR_DEFAULT); + public static Font create(final FontManager pFontManager, final TextureManager pTextureManager, final int pTextureWidth, final int pTextureHeight, final PixelFormat pPixelFormat, final TextureOptions pTextureOptions, final Typeface pTypeface, final float pSize, final boolean pAntiAlias) { + return FontFactory.create(pFontManager, pTextureManager, pTextureWidth, pTextureHeight, pPixelFormat, pTextureOptions, pTypeface, pSize, pAntiAlias, FontFactory.COLOR_DEFAULT); } - public static Font create(final FontManager pFontManager, final TextureManager pTextureManager, final int pTextureWidth, final int pTextureHeight, final BitmapTextureFormat pBitmapTextureFormat, final TextureOptions pTextureOptions, final Typeface pTypeface, final float pSize, final int pColor) { - return FontFactory.create(pFontManager, pTextureManager, pTextureWidth, pTextureHeight, pBitmapTextureFormat, pTextureOptions, pTypeface, pSize, FontFactory.ANTIALIAS_DEFAULT, pColor); + public static Font create(final FontManager pFontManager, final TextureManager pTextureManager, final int pTextureWidth, final int pTextureHeight, final PixelFormat pPixelFormat, final TextureOptions pTextureOptions, final Typeface pTypeface, final float pSize, final int pColor) { + return FontFactory.create(pFontManager, pTextureManager, pTextureWidth, pTextureHeight, pPixelFormat, pTextureOptions, pTypeface, pSize, FontFactory.ANTIALIAS_DEFAULT, pColor); } - public static Font create(final FontManager pFontManager, final TextureManager pTextureManager, final int pTextureWidth, final int pTextureHeight, final BitmapTextureFormat pBitmapTextureFormat, final TextureOptions pTextureOptions, final Typeface pTypeface, final float pSize, final boolean pAntiAlias, final int pColor) { - return FontFactory.create(pFontManager, new BitmapTextureAtlas(pTextureManager, pTextureWidth, pTextureHeight, pBitmapTextureFormat, pTextureOptions), pTypeface, pSize, pAntiAlias, pColor); + public static Font create(final FontManager pFontManager, final TextureManager pTextureManager, final int pTextureWidth, final int pTextureHeight, final PixelFormat pPixelFormat, final TextureOptions pTextureOptions, final Typeface pTypeface, final float pSize, final boolean pAntiAlias, final int pColor) { + return FontFactory.create(pFontManager, new EmptyTexture(pTextureManager, pTextureWidth, pTextureHeight, pPixelFormat, pTextureOptions), pTypeface, pSize, pAntiAlias, pColor); } public static Font create(final FontManager pFontManager, final ITexture pTexture, final Typeface pTypeface, final float pSize, final boolean pAntiAlias, final int pColor) { @@ -148,28 +156,105 @@ public static Font createFromAsset(final FontManager pFontManager, final Texture } public static Font createFromAsset(final FontManager pFontManager, final TextureManager pTextureManager, final int pTextureWidth, final int pTextureHeight, final TextureOptions pTextureOptions, final AssetManager pAssetManager, final String pAssetPath, final float pSize, final boolean pAntiAlias, final int pColor) { - return FontFactory.createFromAsset(pFontManager, pTextureManager, pTextureWidth, pTextureHeight, BitmapTextureFormat.RGBA_8888, pTextureOptions, pAssetManager, pAssetPath, pSize, pAntiAlias, pColor); + return FontFactory.createFromAsset(pFontManager, pTextureManager, pTextureWidth, pTextureHeight, PixelFormat.RGBA_8888, pTextureOptions, pAssetManager, pAssetPath, pSize, pAntiAlias, pColor); + } + + public static Font createFromAsset(final FontManager pFontManager, final TextureManager pTextureManager, final int pTextureWidth, final int pTextureHeight, final PixelFormat pPixelFormat, final TextureOptions pTextureOptions, final AssetManager pAssetManager, final String pAssetPath, final float pSize, final boolean pAntiAlias, final int pColor) { + return new Font(pFontManager, new EmptyTexture(pTextureManager, pTextureWidth, pTextureHeight, pPixelFormat, pTextureOptions), Typeface.createFromAsset(pAssetManager, FontFactory.sAssetBasePath + pAssetPath), pSize, pAntiAlias, pColor); + } + + + public static StrokeFont createStroke(final FontManager pFontManager, final ITexture pTexture, final float pSize, final float pStrokeWidth, final int pStrokeColor) { + return FontFactory.createStroke(pFontManager, pTexture, pSize, FontFactory.ANTIALIAS_DEFAULT, FontFactory.COLOR_DEFAULT, pStrokeWidth, pStrokeColor); + } + + public static StrokeFont createStroke(final FontManager pFontManager, final ITexture pTexture, final float pSize, final boolean pAntiAlias, final float pStrokeWidth, final int pStrokeColor) { + return FontFactory.createStroke(pFontManager, pTexture, pSize, pAntiAlias, FontFactory.COLOR_DEFAULT, pStrokeWidth, pStrokeColor); + } + + public static StrokeFont createStroke(final FontManager pFontManager, final ITexture pTexture, final float pSize, final int pColor, final float pStrokeWidth, final int pStrokeColor) { + return FontFactory.createStroke(pFontManager, pTexture, pSize, FontFactory.ANTIALIAS_DEFAULT, pColor, pStrokeWidth, pStrokeColor); + } + + public static StrokeFont createStroke(final FontManager pFontManager, final ITexture pTexture, final float pSize, final boolean pAntiAlias, final int pColor, final float pStrokeWidth, final int pStrokeColor) { + return FontFactory.createStroke(pFontManager, pTexture, Typeface.create(Typeface.DEFAULT, Typeface.NORMAL), pSize, pAntiAlias, pColor, pStrokeWidth, pStrokeColor); + } + + public static StrokeFont createStroke(final FontManager pFontManager, final TextureManager pTextureManager, final int pTextureWidth, final int pTextureHeight, final float pSize, final boolean pAntiAlias, final int pColor, final float pStrokeWidth, final int pStrokeColor) { + return FontFactory.createStroke(pFontManager, pTextureManager, pTextureWidth, pTextureHeight, TextureOptions.DEFAULT, pSize, pAntiAlias, pColor, pStrokeWidth, pStrokeColor); + } + + public static StrokeFont createStroke(final FontManager pFontManager, final TextureManager pTextureManager, final int pTextureWidth, final int pTextureHeight, final TextureOptions pTextureOptions, final float pSize, final boolean pAntiAlias, final int pColor, final float pStrokeWidth, final int pStrokeColor) { + return FontFactory.createStroke(pFontManager, pTextureManager, pTextureWidth, pTextureHeight, pTextureOptions, Typeface.create(Typeface.DEFAULT, Typeface.NORMAL), pSize, pAntiAlias, pColor, pStrokeWidth, pStrokeColor); + } + + public static StrokeFont createStroke(final FontManager pFontManager, final TextureManager pTextureManager, final int pTextureWidth, final int pTextureHeight, final Typeface pTypeface, final float pSize, final float pStrokeWidth, final int pStrokeColor) { + return FontFactory.createStroke(pFontManager, pTextureManager, pTextureWidth, pTextureHeight, TextureOptions.DEFAULT, pTypeface, pSize, FontFactory.ANTIALIAS_DEFAULT, FontFactory.COLOR_DEFAULT, pStrokeWidth, pStrokeColor); + } + + public static StrokeFont createStroke(final FontManager pFontManager, final TextureManager pTextureManager, final int pTextureWidth, final int pTextureHeight, final Typeface pTypeface, final float pSize, final boolean pAntiAlias, final float pStrokeWidth, final int pStrokeColor) { + return FontFactory.createStroke(pFontManager, pTextureManager, pTextureWidth, pTextureHeight, TextureOptions.DEFAULT, pTypeface, pSize, pAntiAlias, FontFactory.COLOR_DEFAULT, pStrokeWidth, pStrokeColor); + } + + public static StrokeFont createStroke(final FontManager pFontManager, final TextureManager pTextureManager, final int pTextureWidth, final int pTextureHeight, final Typeface pTypeface, final float pSize, final int pColor, final float pStrokeWidth, final int pStrokeColor) { + return FontFactory.createStroke(pFontManager, pTextureManager, pTextureWidth, pTextureHeight, TextureOptions.DEFAULT, pTypeface, pSize, FontFactory.ANTIALIAS_DEFAULT, pColor, pStrokeWidth, pStrokeColor); + } + + public static StrokeFont createStroke(final FontManager pFontManager, final TextureManager pTextureManager, final int pTextureWidth, final int pTextureHeight, final Typeface pTypeface, final float pSize, final boolean pAntiAlias, final int pColor, final float pStrokeWidth, final int pStrokeColor) { + return FontFactory.createStroke(pFontManager, pTextureManager, pTextureWidth, pTextureHeight, TextureOptions.DEFAULT, pTypeface, pSize, pAntiAlias, pColor, pStrokeWidth, pStrokeColor); + } + + public static StrokeFont createStroke(final FontManager pFontManager, final TextureManager pTextureManager, final int pTextureWidth, final int pTextureHeight, final TextureOptions pTextureOptions, final Typeface pTypeface, final float pSize, final float pStrokeWidth, final int pStrokeColor) { + return FontFactory.createStroke(pFontManager, pTextureManager, pTextureWidth, pTextureHeight, pTextureOptions, pTypeface, pSize, FontFactory.ANTIALIAS_DEFAULT, FontFactory.COLOR_DEFAULT, pStrokeWidth, pStrokeColor); + } + + public static StrokeFont createStroke(final FontManager pFontManager, final TextureManager pTextureManager, final int pTextureWidth, final int pTextureHeight, final TextureOptions pTextureOptions, final Typeface pTypeface, final float pSize, final boolean pAntiAlias, final float pStrokeWidth, final int pStrokeColor) { + return FontFactory.createStroke(pFontManager, pTextureManager, pTextureWidth, pTextureHeight, pTextureOptions, pTypeface, pSize, pAntiAlias, FontFactory.COLOR_DEFAULT, pStrokeWidth, pStrokeColor); } - public static Font createFromAsset(final FontManager pFontManager, final TextureManager pTextureManager, final int pTextureWidth, final int pTextureHeight, final BitmapTextureFormat pBitmapTextureFormat, final TextureOptions pTextureOptions, final AssetManager pAssetManager, final String pAssetPath, final float pSize, final boolean pAntiAlias, final int pColor) { - return new Font(pFontManager, new BitmapTextureAtlas(pTextureManager, pTextureWidth, pTextureHeight, pBitmapTextureFormat, pTextureOptions), Typeface.createFromAsset(pAssetManager, FontFactory.sAssetBasePath + pAssetPath), pSize, pAntiAlias, pColor); + public static StrokeFont createStroke(final FontManager pFontManager, final TextureManager pTextureManager, final int pTextureWidth, final int pTextureHeight, final TextureOptions pTextureOptions, final Typeface pTypeface, final float pSize, final int pColor, final float pStrokeWidth, final int pStrokeColor) { + return FontFactory.createStroke(pFontManager, pTextureManager, pTextureWidth, pTextureHeight, pTextureOptions, pTypeface, pSize, FontFactory.ANTIALIAS_DEFAULT, pColor, pStrokeWidth, pStrokeColor); } + public static StrokeFont createStroke(final FontManager pFontManager, final TextureManager pTextureManager, final int pTextureWidth, final int pTextureHeight, final TextureOptions pTextureOptions, final Typeface pTypeface, final float pSize, final boolean pAntiAlias, final int pColor, final float pStrokeWidth, final int pStrokeColor) { + return FontFactory.createStroke(pFontManager, pTextureManager, pTextureWidth, pTextureHeight, PixelFormat.RGBA_8888, pTextureOptions, pTypeface, pSize, pAntiAlias, pColor, pStrokeWidth, pStrokeColor); + } + + public static StrokeFont createStroke(final FontManager pFontManager, final TextureManager pTextureManager, final int pTextureWidth, final int pTextureHeight, final PixelFormat pPixelFormat, final TextureOptions pTextureOptions, final Typeface pTypeface, final float pSize, final float pStrokeWidth, final int pStrokeColor) { + return FontFactory.createStroke(pFontManager, pTextureManager, pTextureWidth, pTextureHeight, pPixelFormat, pTextureOptions, pTypeface, pSize, FontFactory.ANTIALIAS_DEFAULT, FontFactory.COLOR_DEFAULT, pStrokeWidth, pStrokeColor); + } + + public static StrokeFont createStroke(final FontManager pFontManager, final TextureManager pTextureManager, final int pTextureWidth, final int pTextureHeight, final PixelFormat pPixelFormat, final TextureOptions pTextureOptions, final Typeface pTypeface, final float pSize, final boolean pAntiAlias, final float pStrokeWidth, final int pStrokeColor) { + return FontFactory.createStroke(pFontManager, pTextureManager, pTextureWidth, pTextureHeight, pPixelFormat, pTextureOptions, pTypeface, pSize, pAntiAlias, FontFactory.COLOR_DEFAULT, pStrokeWidth, pStrokeColor); + } + + public static StrokeFont createStroke(final FontManager pFontManager, final TextureManager pTextureManager, final int pTextureWidth, final int pTextureHeight, final PixelFormat pPixelFormat, final TextureOptions pTextureOptions, final Typeface pTypeface, final float pSize, final int pColor, final float pStrokeWidth, final int pStrokeColor) { + return FontFactory.createStroke(pFontManager, pTextureManager, pTextureWidth, pTextureHeight, pPixelFormat, pTextureOptions, pTypeface, pSize, FontFactory.ANTIALIAS_DEFAULT, pColor, pStrokeWidth, pStrokeColor); + } + + public static StrokeFont createStroke(final FontManager pFontManager, final TextureManager pTextureManager, final int pTextureWidth, final int pTextureHeight, final PixelFormat pPixelFormat, final TextureOptions pTextureOptions, final Typeface pTypeface, final float pSize, final boolean pAntiAlias, final int pColor, final float pStrokeWidth, final int pStrokeColor) { + return FontFactory.createStroke(pFontManager, new EmptyTexture(pTextureManager, pTextureWidth, pTextureHeight, pPixelFormat, pTextureOptions), pTypeface, pSize, pAntiAlias, pColor, pStrokeWidth, pStrokeColor); + } public static StrokeFont createStroke(final FontManager pFontManager, final ITexture pTexture, final Typeface pTypeface, final float pSize, final boolean pAntiAlias, final int pColor, final float pStrokeWidth, final int pStrokeColor) { return new StrokeFont(pFontManager, pTexture, pTypeface, pSize, pAntiAlias, pColor, pStrokeWidth, pStrokeColor); } - public static StrokeFont createStroke(final FontManager pFontManager, final ITexture pTexture, final Typeface pTypeface, final float pSize, final boolean pAntiAlias, final int pColor, final float pStrokeWidth, final int pStrokeColor, final boolean pStrokeOnly) { - return new StrokeFont(pFontManager, pTexture, pTypeface, pSize, pAntiAlias, pColor, pStrokeWidth, pStrokeColor, pStrokeOnly); - } public static StrokeFont createStrokeFromAsset(final FontManager pFontManager, final ITexture pTexture, final AssetManager pAssetManager, final String pAssetPath, final float pSize, final boolean pAntiAlias, final int pColor, final float pStrokeWidth, final int pStrokeColor) { return new StrokeFont(pFontManager, pTexture, Typeface.createFromAsset(pAssetManager, FontFactory.sAssetBasePath + pAssetPath), pSize, pAntiAlias, pColor, pStrokeWidth, pStrokeColor); } - public static StrokeFont createStrokeFromAsset(final FontManager pFontManager, final ITexture pTexture, final AssetManager pAssetManager, final String pAssetPath, final float pSize, final boolean pAntiAlias, final int pColor, final float pStrokeWidth, final int pStrokeColor, final boolean pStrokeOnly) { - return new StrokeFont(pFontManager, pTexture, Typeface.createFromAsset(pAssetManager, FontFactory.sAssetBasePath + pAssetPath), pSize, pAntiAlias, pColor, pStrokeWidth, pStrokeColor, pStrokeOnly); + public static StrokeFont createStrokeFromAsset(final FontManager pFontManager, final TextureManager pTextureManager, final int pTextureWidth, final int pTextureHeight, final AssetManager pAssetManager, final String pAssetPath, final float pSize, final boolean pAntiAlias, final int pColor, final float pStrokeWidth, final int pStrokeColor) { + return FontFactory.createStrokeFromAsset(pFontManager, pTextureManager, pTextureWidth, pTextureHeight, TextureOptions.DEFAULT, pAssetManager, pAssetPath, pSize, pAntiAlias, pColor, pStrokeWidth, pStrokeColor); + } + + public static StrokeFont createStrokeFromAsset(final FontManager pFontManager, final TextureManager pTextureManager, final int pTextureWidth, final int pTextureHeight, final TextureOptions pTextureOptions, final AssetManager pAssetManager, final String pAssetPath, final float pSize, final boolean pAntiAlias, final int pColor, final float pStrokeWidth, final int pStrokeColor) { + return FontFactory.createStrokeFromAsset(pFontManager, pTextureManager, pTextureWidth, pTextureHeight, PixelFormat.RGBA_8888, pTextureOptions, pAssetManager, pAssetPath, pSize, pAntiAlias, pColor, pStrokeWidth, pStrokeColor); + } + + public static StrokeFont createStrokeFromAsset(final FontManager pFontManager, final TextureManager pTextureManager, final int pTextureWidth, final int pTextureHeight, final PixelFormat pPixelFormat, final TextureOptions pTextureOptions, final AssetManager pAssetManager, final String pAssetPath, final float pSize, final boolean pAntiAlias, final int pColor, final float pStrokeWidth, final int pStrokeColor) { + return new StrokeFont(pFontManager, new EmptyTexture(pTextureManager, pTextureWidth, pTextureHeight, pPixelFormat, pTextureOptions), Typeface.createFromAsset(pAssetManager, FontFactory.sAssetBasePath + pAssetPath), pSize, pAntiAlias, pColor, pStrokeWidth, pStrokeColor); } // =========================================================== diff --git a/src/org/andengine/opengl/font/FontLibrary.java b/src/org/andengine/opengl/font/FontLibrary.java index df09435b4..c107c7b53 100644 --- a/src/org/andengine/opengl/font/FontLibrary.java +++ b/src/org/andengine/opengl/font/FontLibrary.java @@ -5,9 +5,9 @@ import android.util.SparseArray; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 11:52:26 - 20.08.2010 */ @@ -46,9 +46,9 @@ public FontLibrary(final int pInitialCapacity) { public void loadFonts(final FontManager pFontManager) { final SparseArray items = this.mItems; - for(int i = items.size() - 1; i >= 0; i--) { + for (int i = items.size() - 1; i >= 0; i--) { final Font font = items.valueAt(i); - if(font != null) { + if (font != null) { pFontManager.loadFont(font); } } diff --git a/src/org/andengine/opengl/font/FontManager.java b/src/org/andengine/opengl/font/FontManager.java index 9032f45e0..40dce056a 100644 --- a/src/org/andengine/opengl/font/FontManager.java +++ b/src/org/andengine/opengl/font/FontManager.java @@ -1,6 +1,7 @@ package org.andengine.opengl.font; import java.util.ArrayList; +import java.util.HashMap; import org.andengine.opengl.util.GLState; @@ -8,7 +9,7 @@ /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 17:48:46 - 08.03.2010 */ @@ -22,6 +23,8 @@ public class FontManager { // =========================================================== private final ArrayList mFontsManaged = new ArrayList(); + private final ArrayList mBitmapFontsManaged = new ArrayList(); + private final HashMap mFontsMapped = new HashMap(); // =========================================================== // Constructors @@ -45,44 +48,104 @@ public void onCreate() { public synchronized void onDestroy() { final ArrayList managedFonts = this.mFontsManaged; - for(int i = managedFonts.size() - 1; i >= 0; i--) { + for (int i = managedFonts.size() - 1; i >= 0; i--) { managedFonts.get(i).invalidateLetters(); } this.mFontsManaged.clear(); + this.mBitmapFontsManaged.clear(); + this.mFontsMapped.clear(); + } + + public synchronized boolean hasMappedFont(final String pID) { + if (pID == null) { + throw new IllegalArgumentException("pID must not be null!"); + } + return this.mFontsMapped.containsKey(pID); + } + + public synchronized IFont getMappedFont(final String pID) { + if (pID == null) { + throw new IllegalArgumentException("pID must not be null!"); + } + return this.mFontsMapped.get(pID); + } + + public synchronized void addMappedFont(final String pID, final IFont pFont) throws IllegalArgumentException { + if (pID == null) { + throw new IllegalArgumentException("pID must not be null!"); + } else if (pFont == null) { + throw new IllegalArgumentException("pFont must not be null!"); + } else if (this.mFontsMapped.containsKey(pID)) { + throw new IllegalArgumentException("Collision for pID: '" + pID + "'."); + } + this.mFontsMapped.put(pID, pFont); + } + + public synchronized IFont removedMappedFont(final String pID) { + if (pID == null) { + throw new IllegalArgumentException("pID must not be null!"); + } + return this.mFontsMapped.remove(pID); } public synchronized void loadFont(final Font pFont) { - if(pFont == null) { + if (pFont == null) { throw new IllegalArgumentException("pFont must not be null!"); } this.mFontsManaged.add(pFont); } - public synchronized void loadFonts(final Font ...pFonts) { - for(int i = 0; i < pFonts.length; i++) { + public synchronized void loadFont(final BitmapFont pBitmapFont) { + if (pBitmapFont == null) { + throw new IllegalArgumentException("pBitmapFont must not be null!"); + } + this.mBitmapFontsManaged.add(pBitmapFont); + } + + public synchronized void loadFonts(final Font ... pFonts) { + for (int i = 0; i < pFonts.length; i++) { this.loadFont(pFonts[i]); } } + public synchronized void loadFonts(final BitmapFont ... pBitmapFonts) { + for (int i = 0; i < pBitmapFonts.length; i++) { + this.loadFont(pBitmapFonts[i]); + } + } + public synchronized void unloadFont(final Font pFont) { - if(pFont == null) { + if (pFont == null) { throw new IllegalArgumentException("pFont must not be null!"); } this.mFontsManaged.remove(pFont); } - public synchronized void unloadFonts(final Font ...pFonts) { - for(int i = 0; i < pFonts.length; i++) { + public synchronized void unloadFont(final BitmapFont pBitmapFont) { + if (pBitmapFont == null) { + throw new IllegalArgumentException("pBitmapFont must not be null!"); + } + this.mBitmapFontsManaged.remove(pBitmapFont); + } + + public synchronized void unloadFonts(final Font ... pFonts) { + for (int i = 0; i < pFonts.length; i++) { this.unloadFont(pFonts[i]); } } + public synchronized void unloadFonts(final BitmapFont ... pBitmapFonts) { + for (int i = 0; i < pBitmapFonts.length; i++) { + this.unloadFont(pBitmapFonts[i]); + } + } + public synchronized void updateFonts(final GLState pGLState) { final ArrayList fonts = this.mFontsManaged; final int fontCount = fonts.size(); - if(fontCount > 0){ - for(int i = fontCount - 1; i >= 0; i--){ + if (fontCount > 0) { + for (int i = fontCount - 1; i >= 0; i--) { fonts.get(i).update(pGLState); } } @@ -90,7 +153,7 @@ public synchronized void updateFonts(final GLState pGLState) { public synchronized void onReload() { final ArrayList managedFonts = this.mFontsManaged; - for(int i = managedFonts.size() - 1; i >= 0; i--) { + for (int i = managedFonts.size() - 1; i >= 0; i--) { managedFonts.get(i).invalidateLetters(); } } diff --git a/src/org/andengine/opengl/font/FontUtils.java b/src/org/andengine/opengl/font/FontUtils.java index d84153c3a..fe68e12ae 100644 --- a/src/org/andengine/opengl/font/FontUtils.java +++ b/src/org/andengine/opengl/font/FontUtils.java @@ -8,7 +8,7 @@ /** - * (c) Zynga 2012 + * (c) 2012 Zynga Inc. * * @author Nicolas Gramlich * @since 15:06:32 - 25.01.2012 @@ -83,29 +83,29 @@ public static float measureText(final IFont pFont, final CharSequence pText, fin public static float measureText(final IFont pFont, final CharSequence pText, final int pStart, final int pEnd, final float[] pWidths) { final int textLength = pEnd - pStart; /* Early exits. */ - if(pStart == pEnd) { + if (pStart == pEnd) { return 0; - } else if(textLength == 1) { + } else if (textLength == 1) { return pFont.getLetter(pText.charAt(pStart)).mWidth; } Letter previousLetter = null; float width = 0; - for(int pos = pStart, i = 0; pos < pEnd; pos++, i++) { + for (int pos = pStart, i = 0; pos < pEnd; pos++, i++) { final Letter letter = pFont.getLetter(pText.charAt(pos)); - if(previousLetter != null) { + if (previousLetter != null) { width += previousLetter.getKerning(letter.mCharacter); } previousLetter = letter; /* Check if this is the last character. */ - if(pos == (pEnd - 1)) { + if (pos == (pEnd - 1)) { width += letter.mOffsetX + letter.mWidth; } else { width += letter.mAdvance; } - if(pWidths != null) { + if (pWidths != null) { pWidths[i] = width; } } @@ -132,7 +132,7 @@ public static > L splitLines(final CharSequence pTe /** * Does not respect linebreaks! - * + * * @param pFont * @param pText * @param pResult @@ -141,9 +141,9 @@ public static > L splitLines(final CharSequence pTe */ public static > L splitLines(final IFont pFont, final CharSequence pText, final L pResult, final AutoWrap pAutoWrap, final float pAutoWrapWidth) { /** - * TODO In order to respect already existing linebreaks, {@link FontUtils#split(CharSequence, List)} could be leveraged and than the following methods could be called for each line. + * TODO In order to respect already existing linebreaks, {@link #split(CharSequence, List)} could be leveraged and than the following methods could be called for each line. */ - switch(pAutoWrap) { + switch (pAutoWrap) { case LETTERS: return FontUtils.splitLinesByLetters(pFont, pText, pResult, pAutoWrapWidth); case WORDS: @@ -164,10 +164,10 @@ private static > L splitLinesByLetters(final IFont int lastNonWhitespace = 0; boolean charsAvailable = false; - for(int i = 0; i < textLength; i++) { + for (int i = 0; i < textLength; i++) { final char character = pText.charAt(i); - if(character != ' ') { - if(charsAvailable) { + if (character != ' ') { + if (charsAvailable) { lastNonWhitespace = i + 1; } else { charsAvailable = true; @@ -177,7 +177,7 @@ private static > L splitLinesByLetters(final IFont } } - if(charsAvailable) { + if (charsAvailable) { // /* Just for debugging. */ // final CharSequence line = pText.subSequence(lineStart, lineEnd); // final float lineWidth = FontUtils.measureText(pFont, pText, lineStart, lineEnd); @@ -186,19 +186,19 @@ private static > L splitLinesByLetters(final IFont final float lookaheadLineWidth = FontUtils.measureText(pFont, pText, lineStart, lastNonWhitespace); final boolean isEndReached = (i == (textLength - 1)); - if(isEndReached) { + if (isEndReached) { /* When the end of the string is reached, add remainder to result. */ - if(lookaheadLineWidth <= pAutoWrapWidth) { + if (lookaheadLineWidth <= pAutoWrapWidth) { pResult.add(pText.subSequence(lineStart, lastNonWhitespace)); } else { pResult.add(pText.subSequence(lineStart, lineEnd)); /* Avoid special case where last line is added twice. */ - if(lineStart != i) { + if (lineStart != i) { pResult.add(pText.subSequence(i, lastNonWhitespace)); } } } else { - if(lookaheadLineWidth <= pAutoWrapWidth) { + if (lookaheadLineWidth <= pAutoWrapWidth) { lineEnd = lastNonWhitespace; } else { pResult.add(pText.subSequence(lineStart, lineEnd)); @@ -215,7 +215,7 @@ private static > L splitLinesByLetters(final IFont private static > L splitLinesByWords(final IFont pFont, final CharSequence pText, final L pResult, final float pAutoWrapWidth) { final int textLength = pText.length(); - if(textLength == 0) { + if (textLength == 0) { return pResult; } @@ -228,11 +228,11 @@ private static > L splitLinesByWords(final IFont pF float lineWidthRemaining = pAutoWrapWidth; boolean firstWordInLine = true; int i = 0; - while(i < textLength) { + while (i < textLength) { int spacesSkipped = 0; /* Find next word. */ { /* Skip whitespaces. */ - while((i < textLength) && (pText.charAt(i) == ' ')) { + while ((i < textLength) && (pText.charAt(i) == ' ')) { i++; spacesSkipped++; } @@ -240,20 +240,20 @@ private static > L splitLinesByWords(final IFont pF final int wordStart = i; /* Mark beginning of a new line. */ - if(lineStart == FontUtils.UNSPECIFIED) { + if (lineStart == FontUtils.UNSPECIFIED) { lineStart = wordStart; } { /* Skip non-whitespaces. */ - while((i < textLength) && (pText.charAt(i) != ' ')) { + while ((i < textLength) && (pText.charAt(i) != ' ')) { i++; } } final int wordEnd = i; /* Nothing more could be read. */ - if(wordStart == wordEnd) { - if(!firstWordInLine) { + if (wordStart == wordEnd) { + if (!firstWordInLine) { pResult.add(pText.subSequence(lineStart, lineEnd)); } break; @@ -266,7 +266,7 @@ private static > L splitLinesByWords(final IFont pF /* Determine the width actually needed for the current word. */ final float widthNeeded; - if(firstWordInLine) { + if (firstWordInLine) { widthNeeded = wordWidth; } else { widthNeeded = (spacesSkipped * spaceWidth) + wordWidth; @@ -274,7 +274,7 @@ private static > L splitLinesByWords(final IFont pF /* Check if the word fits into the rest of the line. */ if (widthNeeded <= lineWidthRemaining) { - if(firstWordInLine) { + if (firstWordInLine) { firstWordInLine = false; } else { lineWidthRemaining -= FontUtils.getAdvanceCorrection(pFont, pText, lastWordEnd - 1); @@ -284,23 +284,23 @@ private static > L splitLinesByWords(final IFont pF lineEnd = wordEnd; /* Check if the end was reached. */ - if(wordEnd == textLength) { + if (wordEnd == textLength) { pResult.add(pText.subSequence(lineStart, lineEnd)); /* Added the last line. */ break; } } else { /* Special case for lines with only one word. */ - if(firstWordInLine) { + if (firstWordInLine) { /* Check for lines that are just too big. */ - if(wordWidth >= pAutoWrapWidth) { + if (wordWidth >= pAutoWrapWidth) { pResult.add(pText.subSequence(wordStart, wordEnd)); lineWidthRemaining = pAutoWrapWidth; } else { lineWidthRemaining = pAutoWrapWidth - wordWidth; /* Check if the end was reached. */ - if(wordEnd == textLength) { + if (wordEnd == textLength) { pResult.add(pText.subSequence(wordStart, wordEnd)); /* Added the last line. */ break; @@ -317,7 +317,7 @@ private static > L splitLinesByWords(final IFont pF pResult.add(pText.subSequence(lineStart, lineEnd)); /* Check if the end was reached. */ - if(wordEnd == textLength) { + if (wordEnd == textLength) { /* Add the last word. */ pResult.add(pText.subSequence(wordStart, wordEnd)); // TODO Does this cover all cases? break; @@ -334,7 +334,7 @@ private static > L splitLinesByWords(final IFont pF } return pResult; } - + private static > L splitLinesByCJK(final IFont pFont, final CharSequence pText, final L pResult, final float pAutoWrapWidth) { final int textLength = pText.length(); @@ -342,47 +342,47 @@ private static > L splitLinesByCJK(final IFont pFon int lineEnd = 0; /* Skip whitespaces at the beginning of the string. */ - while((lineStart < textLength) && (pText.charAt(lineStart) == ' ')) { + while ((lineStart < textLength) && (pText.charAt(lineStart) == ' ')) { lineStart++; lineEnd++; } - + int i = lineEnd; - while(i < textLength) { + while (i < textLength) { lineStart = lineEnd; { /* Look for a sub string */ boolean charsAvailable = true; - while(i < textLength) { - + while (i < textLength) { + { /* Skip whitespaces at the end of the string */ int j = lineEnd; - while ( j < textLength ) { - if ( pText.charAt( j ) == ' ' ) { + while (j < textLength) { + if (pText.charAt(j) == ' ') { j++; } else { break; } } - if ( j == textLength ) { - if ( lineStart == lineEnd ) { + if (j == textLength) { + if (lineStart == lineEnd) { charsAvailable = false; } i = textLength; break; } } - + lineEnd++; final float lineWidth = FontUtils.measureText(pFont, pText, lineStart, lineEnd); - if(lineWidth > pAutoWrapWidth) { - if ( lineStart < lineEnd - 1 ) { + if (lineWidth > pAutoWrapWidth) { + if (lineStart < lineEnd - 1) { lineEnd--; } - + pResult.add(pText.subSequence(lineStart, lineEnd)); charsAvailable = false; i = lineEnd; @@ -391,7 +391,7 @@ private static > L splitLinesByCJK(final IFont pFon i = lineEnd; } - if(charsAvailable) { + if (charsAvailable) { pResult.add(pText.subSequence(lineStart, lineEnd)); } } diff --git a/src/org/andengine/opengl/font/IFont.java b/src/org/andengine/opengl/font/IFont.java index 99ff72d96..8e25f0bd7 100644 --- a/src/org/andengine/opengl/font/IFont.java +++ b/src/org/andengine/opengl/font/IFont.java @@ -4,7 +4,7 @@ import org.andengine.opengl.texture.ITexture; /** - * (c) Zynga 2011 + * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 12:15:25 - 03.11.2011 @@ -23,6 +23,7 @@ public interface IFont { public ITexture getTexture(); + public float getAscent(); public float getLineHeight(); public Letter getLetter(final char pChar) throws LetterNotFoundException; diff --git a/src/org/andengine/opengl/font/Letter.java b/src/org/andengine/opengl/font/Letter.java index a62ded3a9..356bc8157 100644 --- a/src/org/andengine/opengl/font/Letter.java +++ b/src/org/andengine/opengl/font/Letter.java @@ -5,7 +5,7 @@ /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 10:30:22 - 03.04.2010 */ @@ -69,7 +69,7 @@ private Letter(final char pCharacter, final boolean pWhitespace, final int pText // =========================================================== public int getKerning(final int pCharacter) { - if(this.mKernings == null) { + if (this.mKernings == null) { return 0; } return this.mKernings.get(pCharacter, 0); @@ -93,17 +93,17 @@ public int hashCode() { @Override public boolean equals(final Object pObject) { - if(this == pObject) { + if (this == pObject) { return true; } - if(pObject == null) { + if (pObject == null) { return false; } - if(this.getClass() != pObject.getClass()) { + if (this.getClass() != pObject.getClass()) { return false; } final Letter other = (Letter) pObject; - if(this.mCharacter != other.mCharacter) { + if (this.mCharacter != other.mCharacter) { return false; } return true; @@ -136,7 +136,7 @@ public String toString() { } void addKerning(final int pCharacter, final int pKerning) { - if(this.mKernings == null) { + if (this.mKernings == null) { this.mKernings = new SparseIntArray(); } this.mKernings.put(pCharacter, pKerning); diff --git a/src/org/andengine/opengl/font/StrokeFont.java b/src/org/andengine/opengl/font/StrokeFont.java index 16ef50aa1..0690568bb 100644 --- a/src/org/andengine/opengl/font/StrokeFont.java +++ b/src/org/andengine/opengl/font/StrokeFont.java @@ -1,19 +1,18 @@ package org.andengine.opengl.font; import org.andengine.opengl.texture.ITexture; -import org.andengine.util.color.Color; +import org.andengine.util.adt.color.Color; import android.graphics.Paint; import android.graphics.Paint.Style; import android.graphics.Typeface; -import android.util.FloatMath; /** * TODO Re-implement with Font changes. * - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 10:39:33 - 03.04.2010 */ @@ -33,7 +32,7 @@ public class StrokeFont extends Font { // =========================================================== // Constructors // =========================================================== - + public StrokeFont(final FontManager pFontManager, final ITexture pTexture, final Typeface pTypeface, final float pSize, final boolean pAntiAlias, final Color pColor, final float pStrokeWidth, final Color pStrokeColor) { this(pFontManager, pTexture, pTypeface, pSize, pAntiAlias, pColor.getARGBPackedInt(), pStrokeWidth, pStrokeColor.getARGBPackedInt()); } @@ -48,7 +47,7 @@ public StrokeFont(final FontManager pFontManager, final ITexture pTexture, final public StrokeFont(final FontManager pFontManager, final ITexture pTexture, final Typeface pTypeface, final float pSize, final boolean pAntiAlias, final int pColorARGBPackedInt, final float pStrokeWidth, final int pStrokeColorARGBPackedInt, final boolean pStrokeOnly) { super(pFontManager, pTexture, pTypeface, pSize, pAntiAlias, pColorARGBPackedInt); - + this.mStrokeWidth = pStrokeWidth; this.mStrokePaint = new Paint(); @@ -73,13 +72,13 @@ public StrokeFont(final FontManager pFontManager, final ITexture pTexture, final @Override protected void updateTextBounds(final String pCharacterAsString) { this.mStrokePaint.getTextBounds(pCharacterAsString, 0, 1, this.mTextBounds); - final int inset = -(int)FloatMath.floor(this.mStrokeWidth * 0.5f); + final int inset = -(int)Math.ceil(this.mStrokeWidth * 0.5f); this.mTextBounds.inset(inset, inset); } @Override protected void drawLetter(final String pCharacterAsString, final float pLeft, final float pTop) { - if(!this.mStrokeOnly) { + if (!this.mStrokeOnly) { super.drawLetter(pCharacterAsString, pLeft, pTop); } this.mCanvas.drawText(pCharacterAsString, pLeft + Font.LETTER_TEXTURE_PADDING, pTop + Font.LETTER_TEXTURE_PADDING, this.mStrokePaint); diff --git a/src/org/andengine/opengl/font/exception/FontException.java b/src/org/andengine/opengl/font/exception/FontException.java index 93370adaa..8819096d6 100644 --- a/src/org/andengine/opengl/font/exception/FontException.java +++ b/src/org/andengine/opengl/font/exception/FontException.java @@ -3,7 +3,7 @@ import org.andengine.util.exception.AndEngineRuntimeException; /** - * (c) Zynga 2011 + * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 17:53:31 - 01.11.2011 diff --git a/src/org/andengine/opengl/font/exception/LetterNotFoundException.java b/src/org/andengine/opengl/font/exception/LetterNotFoundException.java index 49ce1f6db..d32332a37 100644 --- a/src/org/andengine/opengl/font/exception/LetterNotFoundException.java +++ b/src/org/andengine/opengl/font/exception/LetterNotFoundException.java @@ -1,7 +1,7 @@ package org.andengine.opengl.font.exception; /** - * (c) Zynga 2011 + * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 12:19:24 - 03.11.2011 diff --git a/src/org/andengine/opengl/shader/PositionColorShaderProgram.java b/src/org/andengine/opengl/shader/PositionColorShaderProgram.java index 73d450644..1d7e77c3e 100644 --- a/src/org/andengine/opengl/shader/PositionColorShaderProgram.java +++ b/src/org/andengine/opengl/shader/PositionColorShaderProgram.java @@ -8,7 +8,7 @@ import android.opengl.GLES20; /** - * (c) Zynga 2011 + * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 13:56:44 - 25.08.2011 @@ -52,7 +52,7 @@ private PositionColorShaderProgram() { } public static PositionColorShaderProgram getInstance() { - if(PositionColorShaderProgram.INSTANCE == null) { + if (PositionColorShaderProgram.INSTANCE == null) { PositionColorShaderProgram.INSTANCE = new PositionColorShaderProgram(); } return PositionColorShaderProgram.INSTANCE; @@ -88,7 +88,7 @@ public void bind(final GLState pGLState, final VertexBufferObjectAttributes pVer @Override public void unbind(final GLState pGLState) { GLES20.glEnableVertexAttribArray(ShaderProgramConstants.ATTRIBUTE_TEXTURECOORDINATES_LOCATION); - + super.unbind(pGLState); } diff --git a/src/org/andengine/opengl/shader/PositionColorTextureCoordinatesShaderProgram.java b/src/org/andengine/opengl/shader/PositionColorTextureCoordinatesShaderProgram.java index ec6b9432c..de9d4ee92 100644 --- a/src/org/andengine/opengl/shader/PositionColorTextureCoordinatesShaderProgram.java +++ b/src/org/andengine/opengl/shader/PositionColorTextureCoordinatesShaderProgram.java @@ -8,7 +8,7 @@ import android.opengl.GLES20; /** - * (c) Zynga 2011 + * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 13:56:44 - 25.08.2011 @@ -58,7 +58,7 @@ private PositionColorTextureCoordinatesShaderProgram() { } public static PositionColorTextureCoordinatesShaderProgram getInstance() { - if(PositionColorTextureCoordinatesShaderProgram.INSTANCE == null) { + if (PositionColorTextureCoordinatesShaderProgram.INSTANCE == null) { PositionColorTextureCoordinatesShaderProgram.INSTANCE = new PositionColorTextureCoordinatesShaderProgram(); } return PositionColorTextureCoordinatesShaderProgram.INSTANCE; diff --git a/src/org/andengine/opengl/shader/PositionTextureCoordinatesPositionInterpolationTextureSelectShaderProgram.java b/src/org/andengine/opengl/shader/PositionTextureCoordinatesPositionInterpolationTextureSelectShaderProgram.java index 50584d7bc..039172c80 100644 --- a/src/org/andengine/opengl/shader/PositionTextureCoordinatesPositionInterpolationTextureSelectShaderProgram.java +++ b/src/org/andengine/opengl/shader/PositionTextureCoordinatesPositionInterpolationTextureSelectShaderProgram.java @@ -8,7 +8,7 @@ import android.opengl.GLES20; /** - * (c) Zynga 2011 + * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 13:56:44 - 25.08.2011 @@ -55,7 +55,7 @@ private PositionTextureCoordinatesPositionInterpolationTextureSelectShaderProgra } public static PositionTextureCoordinatesPositionInterpolationTextureSelectShaderProgram getInstance() { - if(PositionTextureCoordinatesPositionInterpolationTextureSelectShaderProgram.INSTANCE == null) { + if (PositionTextureCoordinatesPositionInterpolationTextureSelectShaderProgram.INSTANCE == null) { PositionTextureCoordinatesPositionInterpolationTextureSelectShaderProgram.INSTANCE = new PositionTextureCoordinatesPositionInterpolationTextureSelectShaderProgram(); } return PositionTextureCoordinatesPositionInterpolationTextureSelectShaderProgram.INSTANCE; @@ -104,7 +104,7 @@ public void unbind(final GLState pGLState) { GLES20.glEnableVertexAttribArray(ShaderProgramConstants.ATTRIBUTE_POSITION_LOCATION); GLES20.glDisableVertexAttribArray(ShaderProgramConstants.ATTRIBUTE_POSITION_0_LOCATION); GLES20.glDisableVertexAttribArray(ShaderProgramConstants.ATTRIBUTE_POSITION_1_LOCATION); - + super.unbind(pGLState); } diff --git a/src/org/andengine/opengl/shader/PositionTextureCoordinatesShaderProgram.java b/src/org/andengine/opengl/shader/PositionTextureCoordinatesShaderProgram.java index 7280a0b27..47f60e501 100644 --- a/src/org/andengine/opengl/shader/PositionTextureCoordinatesShaderProgram.java +++ b/src/org/andengine/opengl/shader/PositionTextureCoordinatesShaderProgram.java @@ -8,7 +8,7 @@ import android.opengl.GLES20; /** - * (c) Zynga 2011 + * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 13:56:44 - 25.08.2011 @@ -54,7 +54,7 @@ private PositionTextureCoordinatesShaderProgram() { } public static PositionTextureCoordinatesShaderProgram getInstance() { - if(PositionTextureCoordinatesShaderProgram.INSTANCE == null) { + if (PositionTextureCoordinatesShaderProgram.INSTANCE == null) { PositionTextureCoordinatesShaderProgram.INSTANCE = new PositionTextureCoordinatesShaderProgram(); } return PositionTextureCoordinatesShaderProgram.INSTANCE; @@ -92,7 +92,7 @@ public void bind(final GLState pGLState, final VertexBufferObjectAttributes pVer @Override public void unbind(final GLState pGLState) { GLES20.glEnableVertexAttribArray(ShaderProgramConstants.ATTRIBUTE_COLOR_LOCATION); - + super.unbind(pGLState); } diff --git a/src/org/andengine/opengl/shader/PositionTextureCoordinatesTextureSelectShaderProgram.java b/src/org/andengine/opengl/shader/PositionTextureCoordinatesTextureSelectShaderProgram.java index ff0c61fbb..b0c11c1e1 100644 --- a/src/org/andengine/opengl/shader/PositionTextureCoordinatesTextureSelectShaderProgram.java +++ b/src/org/andengine/opengl/shader/PositionTextureCoordinatesTextureSelectShaderProgram.java @@ -8,7 +8,7 @@ import android.opengl.GLES20; /** - * (c) Zynga 2011 + * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 13:56:44 - 25.08.2011 @@ -29,7 +29,7 @@ public class PositionTextureCoordinatesTextureSelectShaderProgram extends Shader "uniform bool " + ShaderProgramConstants.UNIFORM_TEXTURESELECT_TEXTURE_0 + ";\n" + "varying mediump vec2 " + ShaderProgramConstants.VARYING_TEXTURECOORDINATES + ";\n" + "void main() {\n" + - " if(" + ShaderProgramConstants.UNIFORM_TEXTURESELECT_TEXTURE_0 + ") {\n" + + " if (" + ShaderProgramConstants.UNIFORM_TEXTURESELECT_TEXTURE_0 + ") {\n" + " gl_FragColor = texture2D(" + ShaderProgramConstants.UNIFORM_TEXTURE_0 + ", " + ShaderProgramConstants.VARYING_TEXTURECOORDINATES + ");\n" + " } else {\n" + " gl_FragColor = texture2D(" + ShaderProgramConstants.UNIFORM_TEXTURE_1 + ", " + ShaderProgramConstants.VARYING_TEXTURECOORDINATES + ");\n" + @@ -54,7 +54,7 @@ private PositionTextureCoordinatesTextureSelectShaderProgram() { } public static PositionTextureCoordinatesTextureSelectShaderProgram getInstance() { - if(PositionTextureCoordinatesTextureSelectShaderProgram.INSTANCE == null) { + if (PositionTextureCoordinatesTextureSelectShaderProgram.INSTANCE == null) { PositionTextureCoordinatesTextureSelectShaderProgram.INSTANCE = new PositionTextureCoordinatesTextureSelectShaderProgram(); } return PositionTextureCoordinatesTextureSelectShaderProgram.INSTANCE; @@ -95,7 +95,7 @@ public void bind(final GLState pGLState, final VertexBufferObjectAttributes pVer @Override public void unbind(final GLState pGLState) { GLES20.glEnableVertexAttribArray(ShaderProgramConstants.ATTRIBUTE_COLOR_LOCATION); - + super.unbind(pGLState); } diff --git a/src/org/andengine/opengl/shader/PositionTextureCoordinatesUniformColorShaderProgram.java b/src/org/andengine/opengl/shader/PositionTextureCoordinatesUniformColorShaderProgram.java index 29157dace..b81131085 100644 --- a/src/org/andengine/opengl/shader/PositionTextureCoordinatesUniformColorShaderProgram.java +++ b/src/org/andengine/opengl/shader/PositionTextureCoordinatesUniformColorShaderProgram.java @@ -8,7 +8,7 @@ import android.opengl.GLES20; /** - * (c) Zynga 2012 + * (c) 2012 Zynga Inc. * * @author Nicolas Gramlich * @since 15:00:46 - 13.02.2012 @@ -33,7 +33,7 @@ public class PositionTextureCoordinatesUniformColorShaderProgram extends ShaderP public static final String FRAGMENTSHADER = "precision lowp float;\n" + "uniform sampler2D " + ShaderProgramConstants.UNIFORM_TEXTURE_0 + ";\n" + - "uniform vec4 " + ShaderProgramConstants.UNIFORM_COLOR + ";\n" + + "uniform vec4 " + ShaderProgramConstants.UNIFORM_COLOR + ";\n" + "varying mediump vec2 " + ShaderProgramConstants.VARYING_TEXTURECOORDINATES + ";\n" + "void main() {\n" + " gl_FragColor = " + ShaderProgramConstants.UNIFORM_COLOR + " * texture2D(" + ShaderProgramConstants.UNIFORM_TEXTURE_0 + ", " + ShaderProgramConstants.VARYING_TEXTURECOORDINATES + ");\n" + @@ -56,7 +56,7 @@ private PositionTextureCoordinatesUniformColorShaderProgram() { } public static PositionTextureCoordinatesUniformColorShaderProgram getInstance() { - if(PositionTextureCoordinatesUniformColorShaderProgram.INSTANCE == null) { + if (PositionTextureCoordinatesUniformColorShaderProgram.INSTANCE == null) { PositionTextureCoordinatesUniformColorShaderProgram.INSTANCE = new PositionTextureCoordinatesUniformColorShaderProgram(); } return PositionTextureCoordinatesUniformColorShaderProgram.INSTANCE; @@ -95,7 +95,7 @@ public void bind(final GLState pGLState, final VertexBufferObjectAttributes pVer @Override public void unbind(final GLState pGLState) { GLES20.glEnableVertexAttribArray(ShaderProgramConstants.ATTRIBUTE_COLOR_LOCATION); - + super.unbind(pGLState); } diff --git a/src/org/andengine/opengl/shader/ShaderProgram.java b/src/org/andengine/opengl/shader/ShaderProgram.java index 094575a07..944c2a8d1 100644 --- a/src/org/andengine/opengl/shader/ShaderProgram.java +++ b/src/org/andengine/opengl/shader/ShaderProgram.java @@ -16,7 +16,7 @@ /** - * (c) Zynga 2011 + * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 19:56:34 - 05.08.2011 @@ -75,7 +75,7 @@ public void setCompiled(final boolean pCompiled) { public int getAttributeLocation(final String pAttributeName) { final Integer location = this.mAttributeLocations.get(pAttributeName); - if(location != null) { + if (location != null) { return location.intValue(); } else { throw new ShaderProgramException("Unexpected attribute: '" + pAttributeName + "'. Existing attributes: " + this.mAttributeLocations.toString()); @@ -84,7 +84,7 @@ public int getAttributeLocation(final String pAttributeName) { public int getAttributeLocationOptional(final String pAttributeName) { final Integer location = this.mAttributeLocations.get(pAttributeName); - if(location != null) { + if (location != null) { return location.intValue(); } else { return ShaderProgramConstants.LOCATION_INVALID; @@ -93,7 +93,7 @@ public int getAttributeLocationOptional(final String pAttributeName) { public int getUniformLocation(final String pUniformName) { final Integer location = this.mUniformLocations.get(pUniformName); - if(location != null) { + if (location != null) { return location.intValue(); } else { throw new ShaderProgramException("Unexpected uniform: '" + pUniformName + "'. Existing uniforms: " + this.mUniformLocations.toString()); @@ -102,7 +102,7 @@ public int getUniformLocation(final String pUniformName) { public int getUniformLocationOptional(final String pUniformName) { final Integer location = this.mUniformLocations.get(pUniformName); - if(location != null) { + if (location != null) { return location.intValue(); } else { return ShaderProgramConstants.LOCATION_INVALID; @@ -118,7 +118,7 @@ public int getUniformLocationOptional(final String pUniformName) { // =========================================================== public void bind(final GLState pGLState, final VertexBufferObjectAttributes pVertexBufferObjectAttributes) throws ShaderProgramException { - if(!this.mCompiled) { + if (!this.mCompiled) { this.compile(pGLState); } pGLState.useProgram(this.mProgramID); @@ -131,7 +131,7 @@ public void unbind(final GLState pGLState) throws ShaderProgramException { } public void delete(final GLState pGLState) { - if(this.mCompiled) { + if (this.mCompiled) { this.mCompiled = false; pGLState.deleteProgram(this.mProgramID); this.mProgramID = -1; @@ -163,7 +163,7 @@ protected void link(final GLState pGLState) throws ShaderProgramLinkException { GLES20.glLinkProgram(this.mProgramID); GLES20.glGetProgramiv(this.mProgramID, GLES20.GL_LINK_STATUS, ShaderProgram.HARDWAREID_CONTAINER, 0); - if(ShaderProgram.HARDWAREID_CONTAINER[0] == 0) { + if (ShaderProgram.HARDWAREID_CONTAINER[0] == 0) { throw new ShaderProgramLinkException(GLES20.glGetProgramInfoLog(this.mProgramID)); } @@ -175,7 +175,7 @@ protected void link(final GLState pGLState) throws ShaderProgramLinkException { private static int compileShader(final String pSource, final int pType) throws ShaderProgramException { final int shaderID = GLES20.glCreateShader(pType); - if(shaderID == 0) { + if (shaderID == 0) { throw new ShaderProgramException("Could not create Shader of type: '" + pType + '"'); } @@ -183,7 +183,7 @@ private static int compileShader(final String pSource, final int pType) throws S GLES20.glCompileShader(shaderID); GLES20.glGetShaderiv(shaderID, GLES20.GL_COMPILE_STATUS, ShaderProgram.HARDWAREID_CONTAINER, 0); - if(ShaderProgram.HARDWAREID_CONTAINER[0] == 0) { + if (ShaderProgram.HARDWAREID_CONTAINER[0] == 0) { throw new ShaderProgramCompileException(GLES20.glGetShaderInfoLog(shaderID), pSource); } return shaderID; @@ -196,14 +196,14 @@ private void initUniformLocations() throws ShaderProgramLinkException { GLES20.glGetProgramiv(this.mProgramID, GLES20.GL_ACTIVE_UNIFORMS, ShaderProgram.PARAMETERS_CONTAINER, 0); final int numUniforms = ShaderProgram.PARAMETERS_CONTAINER[0]; - for(int i = 0; i < numUniforms; i++) { + for (int i = 0; i < numUniforms; i++) { GLES20.glGetActiveUniform(this.mProgramID, i, ShaderProgram.NAME_CONTAINER_SIZE, ShaderProgram.LENGTH_CONTAINER, 0, ShaderProgram.SIZE_CONTAINER, 0, ShaderProgram.TYPE_CONTAINER, 0, ShaderProgram.NAME_CONTAINER, 0); int length = ShaderProgram.LENGTH_CONTAINER[0]; /* Some drivers do not report the actual length here, but zero. Then the name is '\0' terminated. */ - if(length == 0) { - while((length < ShaderProgram.NAME_CONTAINER_SIZE) && (ShaderProgram.NAME_CONTAINER[length] != '\0')) { + if (length == 0) { + while ((length < ShaderProgram.NAME_CONTAINER_SIZE) && (ShaderProgram.NAME_CONTAINER[length] != '\0')) { length++; } } @@ -211,17 +211,17 @@ private void initUniformLocations() throws ShaderProgramLinkException { String name = new String(ShaderProgram.NAME_CONTAINER, 0, length); int location = GLES20.glGetUniformLocation(this.mProgramID, name); - if(location == ShaderProgramConstants.LOCATION_INVALID) { + if (location == ShaderProgramConstants.LOCATION_INVALID) { /* Some drivers do not report an incorrect length. Then the name is '\0' terminated. */ length = 0; - while(length < ShaderProgram.NAME_CONTAINER_SIZE && ShaderProgram.NAME_CONTAINER[length] != '\0') { + while (length < ShaderProgram.NAME_CONTAINER_SIZE && ShaderProgram.NAME_CONTAINER[length] != '\0') { length++; } name = new String(ShaderProgram.NAME_CONTAINER, 0, length); location = GLES20.glGetUniformLocation(this.mProgramID, name); - if(location == ShaderProgramConstants.LOCATION_INVALID) { + if (location == ShaderProgramConstants.LOCATION_INVALID) { throw new ShaderProgramLinkException("Invalid location for uniform: '" + name + "'."); } } @@ -241,14 +241,14 @@ private void initAttributeLocations() { GLES20.glGetProgramiv(this.mProgramID, GLES20.GL_ACTIVE_ATTRIBUTES, ShaderProgram.PARAMETERS_CONTAINER, 0); final int numAttributes = ShaderProgram.PARAMETERS_CONTAINER[0]; - for(int i = 0; i < numAttributes; i++) { + for (int i = 0; i < numAttributes; i++) { GLES20.glGetActiveAttrib(this.mProgramID, i, ShaderProgram.NAME_CONTAINER_SIZE, ShaderProgram.LENGTH_CONTAINER, 0, ShaderProgram.SIZE_CONTAINER, 0, ShaderProgram.TYPE_CONTAINER, 0, ShaderProgram.NAME_CONTAINER, 0); int length = ShaderProgram.LENGTH_CONTAINER[0]; /* Some drivers do not report the actual length here, but zero. Then the name is '\0' terminated. */ - if(length == 0) { - while((length < ShaderProgram.NAME_CONTAINER_SIZE) && (ShaderProgram.NAME_CONTAINER[length] != '\0')) { + if (length == 0) { + while ((length < ShaderProgram.NAME_CONTAINER_SIZE) && (ShaderProgram.NAME_CONTAINER[length] != '\0')) { length++; } } @@ -256,17 +256,17 @@ private void initAttributeLocations() { String name = new String(ShaderProgram.NAME_CONTAINER, 0, length); int location = GLES20.glGetAttribLocation(this.mProgramID, name); - if(location == ShaderProgramConstants.LOCATION_INVALID) { + if (location == ShaderProgramConstants.LOCATION_INVALID) { /* Some drivers do not report an incorrect length. Then the name is '\0' terminated. */ length = 0; - while(length < ShaderProgram.NAME_CONTAINER_SIZE && ShaderProgram.NAME_CONTAINER[length] != '\0') { + while (length < ShaderProgram.NAME_CONTAINER_SIZE && ShaderProgram.NAME_CONTAINER[length] != '\0') { length++; } name = new String(ShaderProgram.NAME_CONTAINER, 0, length); location = GLES20.glGetAttribLocation(this.mProgramID, name); - if(location == ShaderProgramConstants.LOCATION_INVALID) { + if (location == ShaderProgramConstants.LOCATION_INVALID) { throw new ShaderProgramLinkException("Invalid location for attribute: '" + name + "'."); } } @@ -281,7 +281,7 @@ public void setUniform(final String pUniformName, final float[] pGLMatrix) { public void setUniformOptional(final String pUniformName, final float[] pGLMatrix) { final int location = this.getUniformLocationOptional(pUniformName); - if(location != ShaderProgramConstants.LOCATION_INVALID) { + if (location != ShaderProgramConstants.LOCATION_INVALID) { GLES20.glUniformMatrix4fv(this.getUniformLocationOptional(pUniformName), 1, false, pGLMatrix, 0); } } @@ -292,7 +292,7 @@ public void setUniform(final String pUniformName, final float pX) { public void setUniformOptional(final String pUniformName, final float pX) { final int location = this.getUniformLocationOptional(pUniformName); - if(location != ShaderProgramConstants.LOCATION_INVALID) { + if (location != ShaderProgramConstants.LOCATION_INVALID) { GLES20.glUniform1f(this.getUniformLocationOptional(pUniformName), pX); } } @@ -303,7 +303,7 @@ public void setUniform(final String pUniformName, final float pX, final float pY public void setUniformOptional(final String pUniformName, final float pX, final float pY) { final int location = this.getUniformLocationOptional(pUniformName); - if(location != ShaderProgramConstants.LOCATION_INVALID) { + if (location != ShaderProgramConstants.LOCATION_INVALID) { GLES20.glUniform2f(this.getUniformLocationOptional(pUniformName), pX, pY); } } @@ -314,7 +314,7 @@ public void setUniform(final String pUniformName, final float pX, final float pY public void setUniformOptional(final String pUniformName, final float pX, final float pY, final float pZ) { final int location = this.getUniformLocationOptional(pUniformName); - if(location != ShaderProgramConstants.LOCATION_INVALID) { + if (location != ShaderProgramConstants.LOCATION_INVALID) { GLES20.glUniform3f(this.getUniformLocationOptional(pUniformName), pX, pY, pZ); } } @@ -325,7 +325,7 @@ public void setUniform(final String pUniformName, final float pX, final float pY public void setUniformOptional(final String pUniformName, final float pX, final float pY, final float pZ, final float pW) { final int location = this.getUniformLocationOptional(pUniformName); - if(location != ShaderProgramConstants.LOCATION_INVALID) { + if (location != ShaderProgramConstants.LOCATION_INVALID) { GLES20.glUniform4f(this.getUniformLocationOptional(pUniformName), pX, pY, pZ, pW); } } @@ -344,7 +344,7 @@ public void setTexture(final String pUniformName, final int pTexture) { */ public void setTextureOptional(final String pUniformName, final int pTexture) { final int location = this.getUniformLocationOptional(pUniformName); - if(location != ShaderProgramConstants.LOCATION_INVALID) { + if (location != ShaderProgramConstants.LOCATION_INVALID) { GLES20.glUniform1i(location, pTexture); } } diff --git a/src/org/andengine/opengl/shader/ShaderProgramManager.java b/src/org/andengine/opengl/shader/ShaderProgramManager.java index 245a949fd..7436f35c7 100644 --- a/src/org/andengine/opengl/shader/ShaderProgramManager.java +++ b/src/org/andengine/opengl/shader/ShaderProgramManager.java @@ -7,7 +7,7 @@ /** * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 12:55:26 - 11.08.2011 */ @@ -49,7 +49,7 @@ public synchronized void onCreate() { public synchronized void onDestroy() { final ArrayList managedShaderPrograms = this.mShaderProgramsManaged; - for(int i = managedShaderPrograms.size() - 1; i >= 0; i--) { + for (int i = managedShaderPrograms.size() - 1; i >= 0; i--) { managedShaderPrograms.get(i).setCompiled(false); } @@ -57,17 +57,17 @@ public synchronized void onDestroy() { } public synchronized void loadShaderProgram(final ShaderProgram pShaderProgram) { - if(pShaderProgram == null) { + if (pShaderProgram == null) { throw new IllegalArgumentException("pShaderProgram must not be null!"); } - if(pShaderProgram.isCompiled()) { + if (pShaderProgram.isCompiled()) { Debug.w("Loading an already compiled " + ShaderProgram.class.getSimpleName() + ": '" + pShaderProgram.getClass().getSimpleName() + "'. '" + pShaderProgram.getClass().getSimpleName() + "' will be recompiled."); pShaderProgram.setCompiled(false); } - if(this.mShaderProgramsManaged.contains(pShaderProgram)) { + if (this.mShaderProgramsManaged.contains(pShaderProgram)) { Debug.w("Loading an already loaded " + ShaderProgram.class.getSimpleName() + ": '" + pShaderProgram.getClass().getSimpleName() + "'."); } else { this.mShaderProgramsManaged.add(pShaderProgram); @@ -75,14 +75,14 @@ public synchronized void loadShaderProgram(final ShaderProgram pShaderProgram) { } public void loadShaderPrograms(final ShaderProgram ... pShaderPrograms) { - for(int i = pShaderPrograms.length - 1; i >= 0; i--) { + for (int i = pShaderPrograms.length - 1; i >= 0; i--) { this.loadShaderProgram(pShaderPrograms[i]); } } public synchronized void onReload() { final ArrayList managedShaderPrograms = this.mShaderProgramsManaged; - for(int i = managedShaderPrograms.size() - 1; i >= 0; i--) { + for (int i = managedShaderPrograms.size() - 1; i >= 0; i--) { managedShaderPrograms.get(i).setCompiled(false); } } diff --git a/src/org/andengine/opengl/shader/constants/ShaderProgramConstants.java b/src/org/andengine/opengl/shader/constants/ShaderProgramConstants.java index c36f04c1e..e007f18a8 100644 --- a/src/org/andengine/opengl/shader/constants/ShaderProgramConstants.java +++ b/src/org/andengine/opengl/shader/constants/ShaderProgramConstants.java @@ -1,7 +1,7 @@ package org.andengine.opengl.shader.constants; /** - * (c) Zynga 2011 + * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 01:03:16 - 07.08.2011 diff --git a/src/org/andengine/opengl/shader/exception/ShaderProgramCompileException.java b/src/org/andengine/opengl/shader/exception/ShaderProgramCompileException.java index 4c52629b2..bc5f0945d 100644 --- a/src/org/andengine/opengl/shader/exception/ShaderProgramCompileException.java +++ b/src/org/andengine/opengl/shader/exception/ShaderProgramCompileException.java @@ -1,6 +1,6 @@ package org.andengine.opengl.shader.exception; /** - * (c) Zynga 2011 + * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 02:31:53 - 07.08.2011 @@ -11,7 +11,7 @@ public class ShaderProgramCompileException extends ShaderProgramException { // =========================================================== private static final long serialVersionUID = 8284346688949370359L; - + // =========================================================== // Fields // =========================================================== diff --git a/src/org/andengine/opengl/shader/exception/ShaderProgramException.java b/src/org/andengine/opengl/shader/exception/ShaderProgramException.java index d507e91dc..c8d08f4a4 100644 --- a/src/org/andengine/opengl/shader/exception/ShaderProgramException.java +++ b/src/org/andengine/opengl/shader/exception/ShaderProgramException.java @@ -3,7 +3,7 @@ import org.andengine.util.exception.AndEngineRuntimeException; /** - * (c) Zynga 2011 + * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 02:33:27 - 07.08.2011 diff --git a/src/org/andengine/opengl/shader/exception/ShaderProgramLinkException.java b/src/org/andengine/opengl/shader/exception/ShaderProgramLinkException.java index cb2134679..0cf63f0e5 100644 --- a/src/org/andengine/opengl/shader/exception/ShaderProgramLinkException.java +++ b/src/org/andengine/opengl/shader/exception/ShaderProgramLinkException.java @@ -1,6 +1,6 @@ package org.andengine.opengl.shader.exception; /** - * (c) Zynga 2011 + * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 02:31:54 - 07.08.2011 @@ -11,7 +11,7 @@ public class ShaderProgramLinkException extends ShaderProgramException { // =========================================================== private static final long serialVersionUID = 5418521931032742504L; - + // =========================================================== // Fields // =========================================================== diff --git a/src/org/andengine/opengl/shader/source/CriteriaShaderSource.java b/src/org/andengine/opengl/shader/source/CriteriaShaderSource.java index 4178cdd8a..1f1b48d65 100644 --- a/src/org/andengine/opengl/shader/source/CriteriaShaderSource.java +++ b/src/org/andengine/opengl/shader/source/CriteriaShaderSource.java @@ -5,7 +5,7 @@ import org.andengine.opengl.util.criteria.IGLCriteria; /** - * (c) Zynga 2011 + * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 16:30:12 - 10.10.2011 @@ -39,9 +39,9 @@ public CriteriaShaderSource(final CriteriaShaderSourceEntry ... pCriteriaShaderS @Override public String getShaderSource(final GLState pGLState) { - for(int i = 0; i < this.mCriteriaShaderSourceEntries.length; i++) { + for (int i = 0; i < this.mCriteriaShaderSourceEntries.length; i++) { final CriteriaShaderSourceEntry criteriaShaderSourceEntry = this.mCriteriaShaderSourceEntries[i]; - if(criteriaShaderSourceEntry.isMet(pGLState)) { + if (criteriaShaderSourceEntry.isMet(pGLState)) { return criteriaShaderSourceEntry.getShaderSource(); } } @@ -71,7 +71,7 @@ public static class CriteriaShaderSourceEntry { // =========================================================== // Constructors // =========================================================== - + public CriteriaShaderSourceEntry(final String pShaderSource) { this(pShaderSource, (IGLCriteria[]) null); } @@ -98,9 +98,9 @@ public String getShaderSource() { // =========================================================== public boolean isMet(final GLState pGLState) { - if(this.mGLCriterias != null) { - for(IGLCriteria gLCriteria : this.mGLCriterias) { - if(!gLCriteria.isMet(pGLState)) { + if (this.mGLCriterias != null) { + for (IGLCriteria gLCriteria : this.mGLCriterias) { + if (!gLCriteria.isMet(pGLState)) { return false; } } diff --git a/src/org/andengine/opengl/shader/source/IShaderSource.java b/src/org/andengine/opengl/shader/source/IShaderSource.java index 3d98f8a38..063fc5be2 100644 --- a/src/org/andengine/opengl/shader/source/IShaderSource.java +++ b/src/org/andengine/opengl/shader/source/IShaderSource.java @@ -3,7 +3,7 @@ import org.andengine.opengl.util.GLState; /** - * (c) Zynga 2011 + * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 16:24:57 - 10.10.2011 diff --git a/src/org/andengine/opengl/shader/source/StringShaderSource.java b/src/org/andengine/opengl/shader/source/StringShaderSource.java index e7b0fc6aa..7ef30d402 100644 --- a/src/org/andengine/opengl/shader/source/StringShaderSource.java +++ b/src/org/andengine/opengl/shader/source/StringShaderSource.java @@ -3,7 +3,7 @@ import org.andengine.opengl.util.GLState; /** - * (c) Zynga 2011 + * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 16:26:08 - 10.10.2011 @@ -22,7 +22,7 @@ public class StringShaderSource implements IShaderSource { // =========================================================== // Constructors // =========================================================== - + public StringShaderSource(final String pShaderSource) { this.mShaderSource = pShaderSource; } @@ -34,7 +34,7 @@ public StringShaderSource(final String pShaderSource) { // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== - + @Override public String getShaderSource(final GLState pGLState) { return this.mShaderSource; diff --git a/src/org/andengine/opengl/texture/DebugTextureStateListener.java b/src/org/andengine/opengl/texture/DebugTextureStateListener.java index f0f796379..e5f70d22a 100644 --- a/src/org/andengine/opengl/texture/DebugTextureStateListener.java +++ b/src/org/andengine/opengl/texture/DebugTextureStateListener.java @@ -5,7 +5,7 @@ import org.andengine.util.debug.Debug; /** - * (c) Zynga 2012 + * (c) 2012 Zynga Inc. * * @author Nicolas Gramlich * @since 11:26:41 - 05.04.2012 @@ -33,14 +33,14 @@ public class DebugTextureStateListener implements @Override public void onLoadedToHardware(final ITexture pTexture) { - if(BuildConfig.DEBUG) { + if (BuildConfig.DEBUG) { Debug.d("Texture loaded: " + pTexture.toString()); } } @Override public void onUnloadedFromHardware(final ITexture pTexture) { - if(BuildConfig.DEBUG) { + if (BuildConfig.DEBUG) { Debug.d("Texture unloaded: " + pTexture.toString()); } } @@ -48,7 +48,7 @@ public void onUnloadedFromHardware(final ITexture pTexture) { // =========================================================== // Methods // =========================================================== - + // =========================================================== // Inner and Anonymous Classes // =========================================================== diff --git a/src/org/andengine/opengl/texture/EmptyTexture.java b/src/org/andengine/opengl/texture/EmptyTexture.java new file mode 100644 index 000000000..ee240dc69 --- /dev/null +++ b/src/org/andengine/opengl/texture/EmptyTexture.java @@ -0,0 +1,101 @@ +package org.andengine.opengl.texture; + +import java.io.IOException; + +import org.andengine.opengl.util.GLState; + +import android.opengl.GLES20; + +/** + * (c) 2012 Zynga Inc. + * + * @author Nicolas Gramlich + * @since 3:07:48 PM - Apr 24, 2012 + */ +public class EmptyTexture extends Texture{ + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + private final int mWidth; + private final int mHeight; + + // =========================================================== + // Constructors + // ========================================================== + + public EmptyTexture(final TextureManager pTextureManager, final int pWidth, final int pHeight) { + this(pTextureManager, pWidth, pHeight, (ITextureStateListener) null); + } + + public EmptyTexture(final TextureManager pTextureManager, final int pWidth, final int pHeight, final ITextureStateListener pTextureStateListener) { + this(pTextureManager, pWidth, pHeight, PixelFormat.RGBA_8888, pTextureStateListener); + } + + public EmptyTexture(final TextureManager pTextureManager, final int pWidth, final int pHeight, final PixelFormat pPixelFormat) { + this(pTextureManager, pWidth, pHeight, pPixelFormat, (ITextureStateListener) null); + } + + public EmptyTexture(final TextureManager pTextureManager, final int pWidth, final int pHeight, final PixelFormat pPixelFormat, final ITextureStateListener pTextureStateListener) { + this(pTextureManager, pWidth, pHeight, pPixelFormat, TextureOptions.DEFAULT, pTextureStateListener); + } + + public EmptyTexture(final TextureManager pTextureManager, final int pWidth, final int pHeight, final TextureOptions pTextureOptions) { + this(pTextureManager, pWidth, pHeight, pTextureOptions, (ITextureStateListener) null); + } + + public EmptyTexture(final TextureManager pTextureManager, final int pWidth, final int pHeight, final TextureOptions pTextureOptions, final ITextureStateListener pTextureStateListener) { + this(pTextureManager, pWidth, pHeight, PixelFormat.RGBA_8888, pTextureOptions, pTextureStateListener); + } + + public EmptyTexture(final TextureManager pTextureManager, final int pWidth, final int pHeight, final PixelFormat pPixelFormat, final TextureOptions pTextureOptions) { + this(pTextureManager, pWidth, pHeight, pPixelFormat, pTextureOptions, (ITextureStateListener) null); + } + + public EmptyTexture(final TextureManager pTextureManager, final int pWidth, final int pHeight, final PixelFormat pPixelFormat, final TextureOptions pTextureOptions, final ITextureStateListener pTextureStateListener) { + super(pTextureManager, pPixelFormat, pTextureOptions, pTextureStateListener); + + this.mWidth = pWidth; + this.mHeight = pHeight; + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + public int getWidth() { + return this.mWidth; + } + + @Override + public int getHeight() { + return this.mHeight; + } + + @Override + protected void writeTextureToHardware(final GLState pGLState) throws IOException { + final PixelFormat pixelFormat = this.mPixelFormat; + final int glInternalFormat = pixelFormat.getGLInternalFormat(); + final int glFormat = pixelFormat.getGLFormat(); + final int glType = pixelFormat.getGLType(); + + GLES20.glTexImage2D(GLES20.GL_TEXTURE_2D, 0, glInternalFormat, this.mWidth, this.mHeight, 0, glFormat, glType, null); + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== +} diff --git a/src/org/andengine/opengl/texture/ITexture.java b/src/org/andengine/opengl/texture/ITexture.java index 6fafaa8cb..3e43a35e8 100644 --- a/src/org/andengine/opengl/texture/ITexture.java +++ b/src/org/andengine/opengl/texture/ITexture.java @@ -9,7 +9,7 @@ /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 15:01:03 - 11.07.2011 */ @@ -56,13 +56,18 @@ public interface ITexture { public void bind(final GLState pGLState); /** - * @param pGLActiveTexture from {@link GLES20#GL_TEXTURE0} to {@link GLES20#GL_TEXTURE31}. + * @param pGLActiveTexture from {@link GLES20#GL_TEXTURE0} to {@link GLES20#GL_TEXTURE31}. */ public void bind(final GLState pGLState, final int pGLActiveTexture); public PixelFormat getPixelFormat(); public TextureOptions getTextureOptions(); + /** + * @return in kiloBytes. + */ + public int getTextureMemorySize(); + public boolean hasTextureStateListener(); public ITextureStateListener getTextureStateListener(); public void setTextureStateListener(final ITextureStateListener pTextureStateListener); diff --git a/src/org/andengine/opengl/texture/ITextureStateListener.java b/src/org/andengine/opengl/texture/ITextureStateListener.java index 9df32f739..3f77bb2f5 100644 --- a/src/org/andengine/opengl/texture/ITextureStateListener.java +++ b/src/org/andengine/opengl/texture/ITextureStateListener.java @@ -2,7 +2,7 @@ /** - * (c) Zynga 2012 + * (c) 2012 Zynga Inc. * * @author Nicolas Gramlich * @since 11:25:58 - 05.04.2012 diff --git a/src/org/andengine/opengl/texture/PixelFormat.java b/src/org/andengine/opengl/texture/PixelFormat.java index 55e523a89..a63c16f89 100644 --- a/src/org/andengine/opengl/texture/PixelFormat.java +++ b/src/org/andengine/opengl/texture/PixelFormat.java @@ -5,7 +5,7 @@ /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 14:55:02 - 08.03.2010 */ diff --git a/src/org/andengine/opengl/texture/Texture.java b/src/org/andengine/opengl/texture/Texture.java index 618de5f3c..52cbdff27 100644 --- a/src/org/andengine/opengl/texture/Texture.java +++ b/src/org/andengine/opengl/texture/Texture.java @@ -4,11 +4,12 @@ import org.andengine.opengl.texture.atlas.source.ITextureAtlasSource; import org.andengine.opengl.util.GLState; +import org.andengine.util.adt.data.constants.DataConstants; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 14:55:02 - 08.03.2010 */ @@ -87,6 +88,13 @@ public TextureOptions getTextureOptions() { return this.mTextureOptions; } + @Override + public int getTextureMemorySize() { + final int pixelCount = this.getWidth() * this.getHeight(); + final int bytesPerPixel = this.mPixelFormat.getBitsPerPixel() / DataConstants.BITS_PER_BYTE; + return pixelCount * bytesPerPixel / DataConstants.BYTES_PER_KILOBYTE; + } + @Override public ITextureStateListener getTextureStateListener() { return this.mTextureStateListener; @@ -140,7 +148,7 @@ public void loadToHardware(final GLState pGLState) throws IOException { this.mUpdateOnHardwareNeeded = false; - if(this.mTextureStateListener != null) { + if (this.mTextureStateListener != null) { this.mTextureStateListener.onLoadedToHardware(this); } } @@ -151,7 +159,7 @@ public void unloadFromHardware(final GLState pGLState) { this.mHardwareTextureID = Texture.HARDWARE_TEXTURE_ID_INVALID; - if(this.mTextureStateListener != null) { + if (this.mTextureStateListener != null) { this.mTextureStateListener.onUnloadedFromHardware(this); } } @@ -180,4 +188,4 @@ public void bind(final GLState pGLState, final int pGLActiveTexture) { // =========================================================== // Inner and Anonymous Classes // =========================================================== -} \ No newline at end of file +} diff --git a/src/org/andengine/opengl/texture/TextureManager.java b/src/org/andengine/opengl/texture/TextureManager.java index bea334ab9..82d9e56e5 100644 --- a/src/org/andengine/opengl/texture/TextureManager.java +++ b/src/org/andengine/opengl/texture/TextureManager.java @@ -5,10 +5,10 @@ import java.util.HashMap; import java.util.HashSet; +import org.andengine.opengl.texture.bitmap.AssetBitmapTexture; import org.andengine.opengl.texture.bitmap.BitmapTexture; import org.andengine.opengl.texture.bitmap.BitmapTextureFormat; import org.andengine.opengl.util.GLState; -import org.andengine.util.adt.io.in.AssetInputStreamOpener; import org.andengine.util.adt.io.in.IInputStreamOpener; import org.andengine.util.debug.Debug; @@ -17,7 +17,7 @@ /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 17:48:46 - 08.03.2010 */ @@ -38,6 +38,10 @@ public class TextureManager { private final ArrayList mTexturesToBeLoaded = new ArrayList(); private final ArrayList mTexturesToBeUnloaded = new ArrayList(); + private TextureWarmUpVertexBufferObject mTextureWarmUpVertexBufferObject; + + private int mTextureMemoryUsed; + // =========================================================== // Constructors // =========================================================== @@ -46,6 +50,14 @@ public class TextureManager { // Getter & Setter // =========================================================== + public int getTextureMemoryUsed() { + return this.mTextureMemoryUsed; + } + + public int getTexturesLoadedCount() { + return this.mTexturesLoaded.size(); + } + // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @@ -55,31 +67,35 @@ public class TextureManager { // =========================================================== public synchronized void onCreate() { - + this.mTextureWarmUpVertexBufferObject = new TextureWarmUpVertexBufferObject(); } public synchronized void onReload() { final HashSet managedTextures = this.mTexturesManaged; - if(!managedTextures.isEmpty()) { - for(final ITexture texture : managedTextures) { // TODO Can the use of the iterator be avoided somehow? + if (!managedTextures.isEmpty()) { + for (final ITexture texture : managedTextures) { // TODO Can the use of the iterator be avoided somehow? texture.setNotLoadedToHardware(); } } - if(!this.mTexturesLoaded.isEmpty()) { + if (!this.mTexturesLoaded.isEmpty()) { this.mTexturesToBeLoaded.addAll(this.mTexturesLoaded); // TODO Check if addAll uses iterator internally! this.mTexturesLoaded.clear(); } - if(!this.mTexturesToBeUnloaded.isEmpty()) { + if (!this.mTexturesToBeUnloaded.isEmpty()) { this.mTexturesManaged.removeAll(this.mTexturesToBeUnloaded); // TODO Check if removeAll uses iterator internally! this.mTexturesToBeUnloaded.clear(); } + + this.mTextureWarmUpVertexBufferObject.setNotLoadedToHardware(); + + this.mTextureMemoryUsed = 0; } public synchronized void onDestroy() { final HashSet managedTextures = this.mTexturesManaged; - for(final ITexture texture : managedTextures) { // TODO Can the use of the iterator be avoided somehow? + for (final ITexture texture : managedTextures) { // TODO Can the use of the iterator be avoided somehow? texture.setNotLoadedToHardware(); } @@ -87,35 +103,40 @@ public synchronized void onDestroy() { this.mTexturesLoaded.clear(); this.mTexturesManaged.clear(); this.mTexturesMapped.clear(); + + this.mTextureWarmUpVertexBufferObject.dispose(); + this.mTextureWarmUpVertexBufferObject = null; + + this.mTextureMemoryUsed = 0; } public synchronized boolean hasMappedTexture(final String pID) { - if(pID == null) { + if (pID == null) { throw new IllegalArgumentException("pID must not be null!"); } return this.mTexturesMapped.containsKey(pID); } public synchronized ITexture getMappedTexture(final String pID) { - if(pID == null) { + if (pID == null) { throw new IllegalArgumentException("pID must not be null!"); } return this.mTexturesMapped.get(pID); } public synchronized void addMappedTexture(final String pID, final ITexture pTexture) throws IllegalArgumentException { - if(pID == null) { + if (pID == null) { throw new IllegalArgumentException("pID must not be null!"); - } else if(pTexture == null) { + } else if (pTexture == null) { throw new IllegalArgumentException("pTexture must not be null!"); - } else if(this.mTexturesMapped.containsKey(pID)) { + } else if (this.mTexturesMapped.containsKey(pID)) { throw new IllegalArgumentException("Collision for pID: '" + pID + "'."); } this.mTexturesMapped.put(pID, pTexture); } public synchronized ITexture removedMappedTexture(final String pID) { - if(pID == null) { + if (pID == null) { throw new IllegalArgumentException("pID must not be null!"); } return this.mTexturesMapped.remove(pID); @@ -126,11 +147,11 @@ public synchronized ITexture removedMappedTexture(final String pID) { * @return true when the {@link ITexture} was previously not managed by this {@link TextureManager}, false if it was already managed. */ public synchronized boolean loadTexture(final ITexture pTexture) { - if(pTexture == null) { + if (pTexture == null) { throw new IllegalArgumentException("pTexture must not be null!"); } - if(this.mTexturesManaged.contains(pTexture)) { + if (this.mTexturesManaged.contains(pTexture)) { /* Just make sure it doesn't get deleted. */ this.mTexturesToBeUnloaded.remove(pTexture); return false; @@ -149,17 +170,17 @@ public synchronized boolean loadTexture(final ITexture pTexture) { * @return true when the {@link ITexture} was previously not managed by this {@link TextureManager}, false if it was already managed. */ public synchronized boolean loadTexture(final GLState pGLState, final ITexture pTexture) throws IOException { - if(pTexture == null) { + if (pTexture == null) { throw new IllegalArgumentException("pTexture must not be null!"); } - if(!pTexture.isLoadedToHardware()) { + if (!pTexture.isLoadedToHardware()) { pTexture.loadToHardware(pGLState); - } else if(pTexture.isUpdateOnHardwareNeeded()) { + } else if (pTexture.isUpdateOnHardwareNeeded()) { pTexture.reloadToHardware(pGLState); } - if(this.mTexturesManaged.contains(pTexture)) { + if (this.mTexturesManaged.contains(pTexture)) { /* Just make sure it doesn't get deleted. */ this.mTexturesToBeUnloaded.remove(pTexture); return false; @@ -175,16 +196,16 @@ public synchronized boolean loadTexture(final GLState pGLState, final ITexture p * @return true when the {@link ITexture} was already managed by this {@link TextureManager}, false if it was not managed. */ public synchronized boolean unloadTexture(final ITexture pTexture) { - if(pTexture == null) { + if (pTexture == null) { throw new IllegalArgumentException("pTexture must not be null!"); } - if(this.mTexturesManaged.contains(pTexture)) { + if (this.mTexturesManaged.contains(pTexture)) { /* If the Texture is loaded, unload it. * If the Texture is about to be loaded, stop it from being loaded. */ - if(this.mTexturesLoaded.contains(pTexture)) { + if (this.mTexturesLoaded.contains(pTexture)) { this.mTexturesToBeUnloaded.add(pTexture); - } else if(this.mTexturesToBeLoaded.remove(pTexture)) { + } else if (this.mTexturesToBeLoaded.remove(pTexture)) { this.mTexturesManaged.remove(pTexture); } return true; @@ -201,13 +222,13 @@ public synchronized boolean unloadTexture(final ITexture pTexture) { * @return true when the {@link ITexture} was already managed by this {@link TextureManager}, false if it was not managed. */ public synchronized boolean unloadTexture(final GLState pGLState, final ITexture pTexture) { - if(pTexture == null) { + if (pTexture == null) { throw new IllegalArgumentException("pTexture must not be null!"); - } else if(pTexture.isLoadedToHardware()) { + } else if (pTexture.isLoadedToHardware()) { pTexture.unloadFromHardware(pGLState); } - if(this.mTexturesManaged.contains(pTexture)) { + if (this.mTexturesManaged.contains(pTexture)) { /* Just make sure it doesn't get loaded. */ this.mTexturesLoaded.remove(pTexture); this.mTexturesToBeLoaded.remove(pTexture); @@ -224,10 +245,10 @@ public synchronized void updateTextures(final GLState pGLState) { final ArrayList texturesToBeLoaded = this.mTexturesToBeLoaded; final ArrayList texturesToBeUnloaded = this.mTexturesToBeUnloaded; - /* First reload Textures that need to be updated. */ - for(int i = texturesLoaded.size() - 1; i >= 0; i--) { + /* First reCreate Textures that need to be updated. */ + for (int i = texturesLoaded.size() - 1; i >= 0; i--) { final ITexture textureToBeReloaded = texturesLoaded.get(i); - if(textureToBeReloaded.isUpdateOnHardwareNeeded()) { + if (textureToBeReloaded.isUpdateOnHardwareNeeded()) { try { textureToBeReloaded.reloadToHardware(pGLState); } catch (final IOException e) { @@ -239,12 +260,17 @@ public synchronized void updateTextures(final GLState pGLState) { /* Then load pending Textures. */ final int texturesToBeLoadedCount = texturesToBeLoaded.size(); - if(texturesToBeLoadedCount > 0) { - for(int i = texturesToBeLoadedCount - 1; i >= 0; i--) { + if (texturesToBeLoadedCount > 0) { + for (int i = texturesToBeLoadedCount - 1; i >= 0; i--) { final ITexture textureToBeLoaded = texturesToBeLoaded.remove(i); - if(!textureToBeLoaded.isLoadedToHardware()) { + if (!textureToBeLoaded.isLoadedToHardware()) { try { textureToBeLoaded.loadToHardware(pGLState); + + this.mTextureMemoryUsed += textureToBeLoaded.getTextureMemorySize(); + + /* Execute the warm-up to ensure the texture data is actually moved to the GPU. */ + this.mTextureWarmUpVertexBufferObject.warmup(pGLState, textureToBeLoaded); } catch (final IOException e) { Debug.e(e); } @@ -256,11 +282,13 @@ public synchronized void updateTextures(final GLState pGLState) { /* Then unload pending Textures. */ final int texturesToBeUnloadedCount = texturesToBeUnloaded.size(); - if(texturesToBeUnloadedCount > 0) { - for(int i = texturesToBeUnloadedCount - 1; i >= 0; i--) { + if (texturesToBeUnloadedCount > 0) { + for (int i = texturesToBeUnloadedCount - 1; i >= 0; i--) { final ITexture textureToBeUnloaded = texturesToBeUnloaded.remove(i); - if(textureToBeUnloaded.isLoadedToHardware()) { + if (textureToBeUnloaded.isLoadedToHardware()) { textureToBeUnloaded.unloadFromHardware(pGLState); + + this.mTextureMemoryUsed -= textureToBeUnloaded.getTextureMemorySize(); } texturesLoaded.remove(textureToBeUnloaded); texturesManaged.remove(textureToBeUnloaded); @@ -268,7 +296,7 @@ public synchronized void updateTextures(final GLState pGLState) { } /* Finally invoke the GC if anything has changed. */ - if((texturesToBeLoadedCount > 0) || (texturesToBeUnloadedCount > 0)) { + if ((texturesToBeLoadedCount > 0) || (texturesToBeUnloadedCount > 0)) { System.gc(); } } @@ -278,10 +306,10 @@ public synchronized ITexture getTexture(final String pID, final AssetManager pAs } public synchronized ITexture getTexture(final String pID, final AssetManager pAssetManager, final String pAssetPath, final TextureOptions pTextureOptions) throws IOException { - if(this.hasMappedTexture(pID)) { + if (this.hasMappedTexture(pID)) { return this.getMappedTexture(pID); } else { - final ITexture texture = new BitmapTexture(this, new AssetInputStreamOpener(pAssetManager, pAssetPath), pTextureOptions); + final ITexture texture = new AssetBitmapTexture(this, pAssetManager, pAssetPath, pTextureOptions); this.loadTexture(texture); this.addMappedTexture(pID, texture); @@ -302,11 +330,11 @@ public synchronized ITexture getTexture(final String pID, final IInputStreamOpen } public synchronized ITexture getTexture(final String pID, final IInputStreamOpener pInputStreamOpener, final BitmapTextureFormat pBitmapTextureFormat, final TextureOptions pTextureOptions, final boolean pLoadToHardware) throws IOException { - if(this.hasMappedTexture(pID)) { + if (this.hasMappedTexture(pID)) { return this.getMappedTexture(pID); } else { final ITexture texture = new BitmapTexture(this, pInputStreamOpener, pBitmapTextureFormat, pTextureOptions); - if(pLoadToHardware) { + if (pLoadToHardware) { this.loadTexture(texture); } this.addMappedTexture(pID, texture); diff --git a/src/org/andengine/opengl/texture/TextureOptions.java b/src/org/andengine/opengl/texture/TextureOptions.java index 71219cae8..c5e682a3e 100644 --- a/src/org/andengine/opengl/texture/TextureOptions.java +++ b/src/org/andengine/opengl/texture/TextureOptions.java @@ -9,9 +9,9 @@ * WrapT and WrapS define how TextureCoordinates that exceed the [0,1] limit are treated. * I.e. {@link GLES20#GL_REPEAT} will repeat the {@link ITexture} and {@link GLES20#GL_CLAMP_TO_EDGE} will stretch the outermost pixels of the {@link ITexture}. * - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 13:00:09 - 05.04.2010 */ @@ -30,7 +30,7 @@ public class TextureOptions { public static final TextureOptions REPEATING_NEAREST_PREMULTIPLYALPHA = new TextureOptions(GLES20.GL_NEAREST, GLES20.GL_NEAREST, GLES20.GL_REPEAT, GLES20.GL_REPEAT, true); public static final TextureOptions REPEATING_BILINEAR_PREMULTIPLYALPHA = new TextureOptions(GLES20.GL_LINEAR, GLES20.GL_LINEAR, GLES20.GL_REPEAT, GLES20.GL_REPEAT, true); - public static final TextureOptions DEFAULT = NEAREST; + public static final TextureOptions DEFAULT = NEAREST; // =========================================================== // Fields diff --git a/src/org/andengine/opengl/texture/TextureStateAdapter.java b/src/org/andengine/opengl/texture/TextureStateAdapter.java index c7cdcd486..cc67369a1 100644 --- a/src/org/andengine/opengl/texture/TextureStateAdapter.java +++ b/src/org/andengine/opengl/texture/TextureStateAdapter.java @@ -3,7 +3,7 @@ import org.andengine.opengl.texture.atlas.source.ITextureAtlasSource; /** - * (c) Zynga 2012 + * (c) 2012 Zynga Inc. * * @author Nicolas Gramlich * @since 11:28:20 - 05.04.2012 @@ -37,11 +37,11 @@ public void onLoadedToHardware(final ITexture pTexture) { public void onUnloadedFromHardware(final ITexture pTexture) { } - + // =========================================================== // Methods // =========================================================== - + // =========================================================== // Inner and Anonymous Classes // =========================================================== diff --git a/src/org/andengine/opengl/texture/TextureWarmUpVertexBufferObject.java b/src/org/andengine/opengl/texture/TextureWarmUpVertexBufferObject.java new file mode 100644 index 000000000..087a753fe --- /dev/null +++ b/src/org/andengine/opengl/texture/TextureWarmUpVertexBufferObject.java @@ -0,0 +1,120 @@ +package org.andengine.opengl.texture; + +import java.nio.FloatBuffer; + +import org.andengine.entity.sprite.UncoloredSprite; +import org.andengine.opengl.shader.PositionTextureCoordinatesShaderProgram; +import org.andengine.opengl.shader.constants.ShaderProgramConstants; +import org.andengine.opengl.util.GLState; +import org.andengine.opengl.vbo.DrawType; +import org.andengine.opengl.vbo.VertexBufferObject; +import org.andengine.opengl.vbo.attribute.VertexBufferObjectAttributes; +import org.andengine.opengl.vbo.attribute.VertexBufferObjectAttributesBuilder; + +import android.opengl.GLES20; + +/** + * (c) 2012 Zynga Inc. + * + * @author Nicolas Gramlich + * @since 15:11:05 - 15.05.2012 + */ +public class TextureWarmUpVertexBufferObject extends VertexBufferObject { + // =========================================================== + // Constants + // =========================================================== + + public static final int VERTEX_INDEX_X = 0; + public static final int VERTEX_INDEX_Y = UncoloredSprite.VERTEX_INDEX_X + 1; + public static final int TEXTURECOORDINATES_INDEX_U = UncoloredSprite.VERTEX_INDEX_Y + 1; + public static final int TEXTURECOORDINATES_INDEX_V = UncoloredSprite.TEXTURECOORDINATES_INDEX_U + 1; + + public static final int VERTEX_SIZE = 2 + 2; + public static final int VERTICES_PER_VERTEXBUFFEROBJECT_SIZE = 3; + public static final int VERTEXBUFFEROBJECT_SIZE = TextureWarmUpVertexBufferObject.VERTEX_SIZE * TextureWarmUpVertexBufferObject.VERTICES_PER_VERTEXBUFFEROBJECT_SIZE; + + public static final VertexBufferObjectAttributes VERTEXBUFFEROBJECTATTRIBUTES_DEFAULT = new VertexBufferObjectAttributesBuilder(2) + .add(ShaderProgramConstants.ATTRIBUTE_POSITION_LOCATION, ShaderProgramConstants.ATTRIBUTE_POSITION, 2, GLES20.GL_FLOAT, false) + .add(ShaderProgramConstants.ATTRIBUTE_TEXTURECOORDINATES_LOCATION, ShaderProgramConstants.ATTRIBUTE_TEXTURECOORDINATES, 2, GLES20.GL_FLOAT, false) + .build(); + + // =========================================================== + // Fields + // =========================================================== + + protected final FloatBuffer mFloatBuffer; + + // =========================================================== + // Constructors + // =========================================================== + + public TextureWarmUpVertexBufferObject() { + super(null, TextureWarmUpVertexBufferObject.VERTEXBUFFEROBJECT_SIZE, DrawType.STATIC, true, TextureWarmUpVertexBufferObject.VERTEXBUFFEROBJECTATTRIBUTES_DEFAULT); + + this.mFloatBuffer = this.mByteBuffer.asFloatBuffer(); + + this.mFloatBuffer.put((0 * TextureWarmUpVertexBufferObject.VERTEX_SIZE) + TextureWarmUpVertexBufferObject.VERTEX_INDEX_X, 0); + this.mFloatBuffer.put((0 * TextureWarmUpVertexBufferObject.VERTEX_SIZE) + TextureWarmUpVertexBufferObject.VERTEX_INDEX_Y, 0); + this.mFloatBuffer.put((0 * TextureWarmUpVertexBufferObject.VERTEX_SIZE) + TextureWarmUpVertexBufferObject.TEXTURECOORDINATES_INDEX_U, 0); + this.mFloatBuffer.put((0 * TextureWarmUpVertexBufferObject.VERTEX_SIZE) + TextureWarmUpVertexBufferObject.TEXTURECOORDINATES_INDEX_V, 0); + + this.mFloatBuffer.put((1 * TextureWarmUpVertexBufferObject.VERTEX_SIZE) + TextureWarmUpVertexBufferObject.VERTEX_INDEX_X, 1); + this.mFloatBuffer.put((1 * TextureWarmUpVertexBufferObject.VERTEX_SIZE) + TextureWarmUpVertexBufferObject.VERTEX_INDEX_Y, 0); + this.mFloatBuffer.put((1 * TextureWarmUpVertexBufferObject.VERTEX_SIZE) + TextureWarmUpVertexBufferObject.TEXTURECOORDINATES_INDEX_U, 1); + this.mFloatBuffer.put((1 * TextureWarmUpVertexBufferObject.VERTEX_SIZE) + TextureWarmUpVertexBufferObject.TEXTURECOORDINATES_INDEX_V, 0); + + this.mFloatBuffer.put((2 * TextureWarmUpVertexBufferObject.VERTEX_SIZE) + TextureWarmUpVertexBufferObject.VERTEX_INDEX_X, 0); + this.mFloatBuffer.put((2 * TextureWarmUpVertexBufferObject.VERTEX_SIZE) + TextureWarmUpVertexBufferObject.VERTEX_INDEX_Y, 1); + this.mFloatBuffer.put((2 * TextureWarmUpVertexBufferObject.VERTEX_SIZE) + TextureWarmUpVertexBufferObject.TEXTURECOORDINATES_INDEX_U, 0); + this.mFloatBuffer.put((2 * TextureWarmUpVertexBufferObject.VERTEX_SIZE) + TextureWarmUpVertexBufferObject.TEXTURECOORDINATES_INDEX_V, 1); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + public int getHeapMemoryByteSize() { + return 0; + } + + @Override + public int getNativeHeapMemoryByteSize() { + return this.getByteCapacity(); + } + + @Override + protected void onBufferData() { + GLES20.glBufferData(GLES20.GL_ARRAY_BUFFER, this.mByteBuffer.limit(), this.mByteBuffer, this.mUsage); + } + + public void warmup(final GLState pGLState, final ITexture pTexture) { + pTexture.bind(pGLState); + this.bind(pGLState, PositionTextureCoordinatesShaderProgram.getInstance()); + + pGLState.pushModelViewGLMatrix(); + { + /* Far far away and really small. */ + pGLState.loadModelViewGLMatrixIdentity(); + pGLState.translateModelViewGLMatrixf(1000000, 1000000, 0); + pGLState.scaleModelViewGLMatrixf(0.0001f, 0.0001f, 0); + + this.draw(GLES20.GL_TRIANGLES, TextureWarmUpVertexBufferObject.VERTICES_PER_VERTEXBUFFEROBJECT_SIZE); + } + pGLState.popModelViewGLMatrix(); + + this.unbind(pGLState, PositionTextureCoordinatesShaderProgram.getInstance()); + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== +} diff --git a/src/org/andengine/opengl/texture/atlas/ITextureAtlas.java b/src/org/andengine/opengl/texture/atlas/ITextureAtlas.java index 1b1f2c72f..659e79ce8 100644 --- a/src/org/andengine/opengl/texture/atlas/ITextureAtlas.java +++ b/src/org/andengine/opengl/texture/atlas/ITextureAtlas.java @@ -9,7 +9,7 @@ /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 14:24:29 - 14.07.2011 */ @@ -80,7 +80,7 @@ public void onUnloadedFromHardware(final ITexture pTexture) { } public static class DebugTextureAtlasStateListener implements ITextureAtlasStateListener { @Override public void onLoadedToHardware(final ITexture pTexture) { - if(BuildConfig.DEBUG) { + if (BuildConfig.DEBUG) { Debug.d("Texture loaded: " + pTexture.toString()); } } @@ -97,7 +97,7 @@ public void onTextureAtlasSourceLoadExeption(final ITextureAtlas pTextureAtla @Override public void onUnloadedFromHardware(final ITexture pTexture) { - if(BuildConfig.DEBUG) { + if (BuildConfig.DEBUG) { Debug.d("Texture unloaded: " + pTexture.toString()); } } diff --git a/src/org/andengine/opengl/texture/atlas/TextureAtlas.java b/src/org/andengine/opengl/texture/atlas/TextureAtlas.java index 4ca51bb19..e16f9b421 100644 --- a/src/org/andengine/opengl/texture/atlas/TextureAtlas.java +++ b/src/org/andengine/opengl/texture/atlas/TextureAtlas.java @@ -12,7 +12,7 @@ /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 14:22:55 - 14.07.2011 */ @@ -74,7 +74,7 @@ public boolean hasTextureAtlasStateListener() { public ITextureAtlasStateListener getTextureStateListener() { return this.getTextureAtlasStateListener(); } - + @SuppressWarnings("unchecked") @Override public ITextureAtlasStateListener getTextureAtlasStateListener() { @@ -113,24 +113,24 @@ public void addTextureAtlasSource(final T pTextureAtlasSource, final int pTextur public void addTextureAtlasSource(final T pTextureAtlasSource, final int pTextureX, final int pTextureY, final int pTextureAtlasSourcePadding) throws IllegalArgumentException { this.addTextureAtlasSource(pTextureAtlasSource, pTextureX, pTextureY); - if(pTextureAtlasSourcePadding > 0) { + if (pTextureAtlasSourcePadding > 0) { /* Left padding. */ - if(pTextureX >= pTextureAtlasSourcePadding) { + if (pTextureX >= pTextureAtlasSourcePadding) { this.addEmptyTextureAtlasSource(pTextureX - pTextureAtlasSourcePadding, pTextureY, pTextureAtlasSourcePadding, pTextureAtlasSource.getTextureHeight()); } /* Top padding. */ - if(pTextureY >= pTextureAtlasSourcePadding) { + if (pTextureY >= pTextureAtlasSourcePadding) { this.addEmptyTextureAtlasSource(pTextureX, pTextureY - pTextureAtlasSourcePadding, pTextureAtlasSource.getTextureWidth(), pTextureAtlasSourcePadding); } /* Right padding. */ - if(pTextureX + pTextureAtlasSource.getTextureWidth() - 1 + pTextureAtlasSourcePadding <= this.getWidth()) { + if (pTextureX + pTextureAtlasSource.getTextureWidth() - 1 + pTextureAtlasSourcePadding <= this.getWidth()) { this.addEmptyTextureAtlasSource(pTextureX + pTextureAtlasSource.getTextureWidth(), pTextureY, pTextureAtlasSourcePadding, pTextureAtlasSource.getTextureHeight()); } /* Bottom padding. */ - if(pTextureY + pTextureAtlasSource.getTextureHeight() - 1 + pTextureAtlasSourcePadding <= this.getHeight()) { + if (pTextureY + pTextureAtlasSource.getTextureHeight() - 1 + pTextureAtlasSourcePadding <= this.getHeight()) { this.addEmptyTextureAtlasSource(pTextureX, pTextureY + pTextureAtlasSource.getTextureHeight(), pTextureAtlasSource.getTextureWidth(), pTextureAtlasSourcePadding); } } @@ -139,9 +139,9 @@ public void addTextureAtlasSource(final T pTextureAtlasSource, final int pTextur @Override public void removeTextureAtlasSource(final T pTextureAtlasSource, final int pTextureX, final int pTextureY) { final ArrayList textureSources = this.mTextureAtlasSources; - for(int i = textureSources.size() - 1; i >= 0; i--) { + for (int i = textureSources.size() - 1; i >= 0; i--) { final T textureSource = textureSources.get(i); - if(textureSource == pTextureAtlasSource && textureSource.getTextureX() == pTextureX && textureSource.getTextureY() == pTextureY) { + if (textureSource == pTextureAtlasSource && textureSource.getTextureX() == pTextureX && textureSource.getTextureY() == pTextureY) { textureSources.remove(i); this.mUpdateOnHardwareNeeded = true; return; @@ -160,11 +160,11 @@ public void clearTextureAtlasSources() { // =========================================================== private void checkTextureAtlasSourcePosition(final T pTextureAtlasSource, final int pTextureX, final int pTextureY) throws IllegalArgumentException { - if(pTextureX < 0) { + if (pTextureX < 0) { throw new IllegalArgumentException("Illegal negative pTextureX supplied: '" + pTextureX + "'"); - } else if(pTextureY < 0) { + } else if (pTextureY < 0) { throw new IllegalArgumentException("Illegal negative pTextureY supplied: '" + pTextureY + "'"); - } else if(pTextureX + pTextureAtlasSource.getTextureWidth() > this.getWidth() || pTextureY + pTextureAtlasSource.getTextureHeight() > this.getHeight()) { + } else if (pTextureX + pTextureAtlasSource.getTextureWidth() > this.getWidth() || pTextureY + pTextureAtlasSource.getTextureHeight() > this.getHeight()) { throw new IllegalArgumentException("Supplied pTextureAtlasSource must not exceed bounds of Texture."); } } diff --git a/src/org/andengine/opengl/texture/atlas/bitmap/BitmapTextureAtlas.java b/src/org/andengine/opengl/texture/atlas/bitmap/BitmapTextureAtlas.java index be24a14a6..3d2911974 100644 --- a/src/org/andengine/opengl/texture/atlas/bitmap/BitmapTextureAtlas.java +++ b/src/org/andengine/opengl/texture/atlas/bitmap/BitmapTextureAtlas.java @@ -22,7 +22,7 @@ /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 14:55:02 - 08.03.2010 */ @@ -121,7 +121,7 @@ public BitmapTextureFormat getBitmapTextureFormat() { // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== - + @Override public void addEmptyTextureAtlasSource(final int pTextureX, final int pTextureY, final int pWidth, final int pHeight) { this.addTextureAtlasSource(new EmptyBitmapTextureAtlasSource(pWidth, pHeight), pTextureX, pTextureY); @@ -148,38 +148,38 @@ protected void writeTextureToHardware(final GLState pGLState) { final int textureSourceCount = textureSources.size(); final ITextureAtlasStateListener textureStateListener = this.getTextureAtlasStateListener(); - for(int i = 0; i < textureSourceCount; i++) { + for (int i = 0; i < textureSourceCount; i++) { final IBitmapTextureAtlasSource bitmapTextureAtlasSource = textureSources.get(i); try { final Bitmap bitmap = bitmapTextureAtlasSource.onLoadBitmap(bitmapConfig); - if(bitmap == null) { + if (bitmap == null) { throw new NullBitmapException("Caused by: " + bitmapTextureAtlasSource.getClass().toString() + " --> " + bitmapTextureAtlasSource.toString() + " returned a null Bitmap."); } final boolean useDefaultAlignment = MathUtils.isPowerOfTwo(bitmap.getWidth()) && MathUtils.isPowerOfTwo(bitmap.getHeight()) && pixelFormat == PixelFormat.RGBA_8888; - if(!useDefaultAlignment) { + if (!useDefaultAlignment) { /* Adjust unpack alignment. */ GLES20.glPixelStorei(GLES20.GL_UNPACK_ALIGNMENT, 1); } - if(preMultipyAlpha) { + if (preMultipyAlpha) { GLUtils.texSubImage2D(GLES20.GL_TEXTURE_2D, 0, bitmapTextureAtlasSource.getTextureX(), bitmapTextureAtlasSource.getTextureY(), bitmap, glFormat, glType); } else { pGLState.glTexSubImage2D(GLES20.GL_TEXTURE_2D, 0, bitmapTextureAtlasSource.getTextureX(), bitmapTextureAtlasSource.getTextureY(), bitmap, this.mPixelFormat); } - if(!useDefaultAlignment) { + if (!useDefaultAlignment) { /* Restore default unpack alignment. */ GLES20.glPixelStorei(GLES20.GL_UNPACK_ALIGNMENT, GLState.GL_UNPACK_ALIGNMENT_DEFAULT); } bitmap.recycle(); - if(textureStateListener != null) { + if (textureStateListener != null) { textureStateListener.onTextureAtlasSourceLoaded(this, bitmapTextureAtlasSource); } } catch (final NullBitmapException e) { - if(textureStateListener != null) { + if (textureStateListener != null) { textureStateListener.onTextureAtlasSourceLoadExeption(this, bitmapTextureAtlasSource, e); } else { throw e; diff --git a/src/org/andengine/opengl/texture/atlas/bitmap/BitmapTextureAtlasTextureRegionFactory.java b/src/org/andengine/opengl/texture/atlas/bitmap/BitmapTextureAtlasTextureRegionFactory.java index 7c4990923..752853d32 100644 --- a/src/org/andengine/opengl/texture/atlas/bitmap/BitmapTextureAtlasTextureRegionFactory.java +++ b/src/org/andengine/opengl/texture/atlas/bitmap/BitmapTextureAtlasTextureRegionFactory.java @@ -1,13 +1,16 @@ package org.andengine.opengl.texture.atlas.bitmap; +import java.io.IOException; + import org.andengine.opengl.texture.atlas.bitmap.source.AssetBitmapTextureAtlasSource; import org.andengine.opengl.texture.atlas.bitmap.source.IBitmapTextureAtlasSource; import org.andengine.opengl.texture.atlas.bitmap.source.ResourceBitmapTextureAtlasSource; import org.andengine.opengl.texture.atlas.buildable.BuildableTextureAtlasTextureRegionFactory; -import org.andengine.opengl.texture.region.ITextureRegion; +import org.andengine.opengl.texture.region.TextureRegion; import org.andengine.opengl.texture.region.TextureRegionFactory; import org.andengine.opengl.texture.region.TiledTextureRegion; +import org.andengine.util.exception.AndEngineRuntimeException; import android.content.Context; import android.content.res.AssetManager; @@ -21,7 +24,7 @@ * @author Nicolas Gramlich * @since 18:15:14 - 09.03.2010 */ -public class BitmapTextureAtlasTextureRegionFactory { +public final class BitmapTextureAtlasTextureRegionFactory { // =========================================================== // Constants // =========================================================== @@ -36,6 +39,10 @@ public class BitmapTextureAtlasTextureRegionFactory { // Constructors // =========================================================== + private BitmapTextureAtlasTextureRegionFactory() { + + } + // =========================================================== // Getter & Setter // =========================================================== @@ -44,13 +51,17 @@ public class BitmapTextureAtlasTextureRegionFactory { * @param pAssetBasePath must end with '/' or have .length() == 0. */ public static void setAssetBasePath(final String pAssetBasePath) { - if(pAssetBasePath.endsWith("/") || pAssetBasePath.length() == 0) { + if (pAssetBasePath.endsWith("/") || pAssetBasePath.length() == 0) { BitmapTextureAtlasTextureRegionFactory.sAssetBasePath = pAssetBasePath; } else { - throw new IllegalArgumentException("pAssetBasePath must end with '/' or be lenght zero."); + throw new IllegalArgumentException("pAssetBasePath must end with '/' or be length zero."); } } + public static String getAssetBasePath() { + return BitmapTextureAtlasTextureRegionFactory.sAssetBasePath; + } + public static void reset() { BitmapTextureAtlasTextureRegionFactory.setAssetBasePath(""); } @@ -67,11 +78,11 @@ public static void reset() { // Methods using BitmapTexture // =========================================================== - public static ITextureRegion createFromAsset(final BitmapTextureAtlas pBitmapTextureAtlas, final Context pContext, final String pAssetPath, final int pTextureX, final int pTextureY) { + public static TextureRegion createFromAsset(final BitmapTextureAtlas pBitmapTextureAtlas, final Context pContext, final String pAssetPath, final int pTextureX, final int pTextureY) { return BitmapTextureAtlasTextureRegionFactory.createFromAsset(pBitmapTextureAtlas, pContext.getAssets(), pAssetPath, pTextureX, pTextureY); } - public static ITextureRegion createFromAsset(final BitmapTextureAtlas pBitmapTextureAtlas, final AssetManager pAssetManager, final String pAssetPath, final int pTextureX, final int pTextureY) { + public static TextureRegion createFromAsset(final BitmapTextureAtlas pBitmapTextureAtlas, final AssetManager pAssetManager, final String pAssetPath, final int pTextureX, final int pTextureY) { final IBitmapTextureAtlasSource bitmapTextureAtlasSource = AssetBitmapTextureAtlasSource.create(pAssetManager, BitmapTextureAtlasTextureRegionFactory.sAssetBasePath + pAssetPath); return BitmapTextureAtlasTextureRegionFactory.createFromSource(pBitmapTextureAtlas, bitmapTextureAtlasSource, pTextureX, pTextureY); } @@ -86,11 +97,11 @@ public static TiledTextureRegion createTiledFromAsset(final BitmapTextureAtlas p } - public static ITextureRegion createFromResource(final BitmapTextureAtlas pBitmapTextureAtlas, final Context pContext, final int pDrawableResourceID, final int pTextureX, final int pTextureY) { + public static TextureRegion createFromResource(final BitmapTextureAtlas pBitmapTextureAtlas, final Context pContext, final int pDrawableResourceID, final int pTextureX, final int pTextureY) { return BitmapTextureAtlasTextureRegionFactory.createFromResource(pBitmapTextureAtlas, pContext.getResources(), pDrawableResourceID, pTextureX, pTextureY); } - public static ITextureRegion createFromResource(final BitmapTextureAtlas pBitmapTextureAtlas, final Resources pResources, final int pDrawableResourceID, final int pTextureX, final int pTextureY) { + public static TextureRegion createFromResource(final BitmapTextureAtlas pBitmapTextureAtlas, final Resources pResources, final int pDrawableResourceID, final int pTextureX, final int pTextureY) { final IBitmapTextureAtlasSource bitmapTextureAtlasSource = ResourceBitmapTextureAtlasSource.create(pResources, pDrawableResourceID); return BitmapTextureAtlasTextureRegionFactory.createFromSource(pBitmapTextureAtlas, bitmapTextureAtlasSource, pTextureX, pTextureY); } @@ -105,7 +116,7 @@ public static TiledTextureRegion createTiledFromResource(final BitmapTextureAtla } - public static ITextureRegion createFromSource(final BitmapTextureAtlas pBitmapTextureAtlas, final IBitmapTextureAtlasSource pBitmapTextureAtlasSource, final int pTextureX, final int pTextureY) { + public static TextureRegion createFromSource(final BitmapTextureAtlas pBitmapTextureAtlas, final IBitmapTextureAtlasSource pBitmapTextureAtlasSource, final int pTextureX, final int pTextureY) { return TextureRegionFactory.createFromSource(pBitmapTextureAtlas, pBitmapTextureAtlasSource, pTextureX, pTextureY); } @@ -117,19 +128,19 @@ public static TiledTextureRegion createTiledFromSource(final BitmapTextureAtlas // Methods using BuildableTexture // =========================================================== - public static ITextureRegion createFromAsset(final BuildableBitmapTextureAtlas pBuildableBitmapTextureAtlas, final Context pContext, final String pAssetPath) { + public static TextureRegion createFromAsset(final BuildableBitmapTextureAtlas pBuildableBitmapTextureAtlas, final Context pContext, final String pAssetPath) { return BitmapTextureAtlasTextureRegionFactory.createFromAsset(pBuildableBitmapTextureAtlas, pContext.getAssets(), pAssetPath); } - public static ITextureRegion createFromAsset(final BuildableBitmapTextureAtlas pBuildableBitmapTextureAtlas, final AssetManager pAssetManager, final String pAssetPath) { + public static TextureRegion createFromAsset(final BuildableBitmapTextureAtlas pBuildableBitmapTextureAtlas, final AssetManager pAssetManager, final String pAssetPath) { return BitmapTextureAtlasTextureRegionFactory.createFromAsset(pBuildableBitmapTextureAtlas, pAssetManager, pAssetPath, false); } - public static ITextureRegion createFromAsset(final BuildableBitmapTextureAtlas pBuildableBitmapTextureAtlas, final Context pContext, final String pAssetPath, final boolean pRotated) { + public static TextureRegion createFromAsset(final BuildableBitmapTextureAtlas pBuildableBitmapTextureAtlas, final Context pContext, final String pAssetPath, final boolean pRotated) { return BitmapTextureAtlasTextureRegionFactory.createFromAsset(pBuildableBitmapTextureAtlas, pContext.getAssets(), pAssetPath, pRotated); } - public static ITextureRegion createFromAsset(final BuildableBitmapTextureAtlas pBuildableBitmapTextureAtlas, final AssetManager pAssetManager, final String pAssetPath, final boolean pRotated) { + public static TextureRegion createFromAsset(final BuildableBitmapTextureAtlas pBuildableBitmapTextureAtlas, final AssetManager pAssetManager, final String pAssetPath, final boolean pRotated) { final IBitmapTextureAtlasSource bitmapTextureAtlasSource = AssetBitmapTextureAtlasSource.create(pAssetManager, BitmapTextureAtlasTextureRegionFactory.sAssetBasePath + pAssetPath); return BitmapTextureAtlasTextureRegionFactory.createFromSource(pBuildableBitmapTextureAtlas, bitmapTextureAtlasSource, pRotated); } @@ -143,20 +154,19 @@ public static TiledTextureRegion createTiledFromAsset(final BuildableBitmapTextu return BitmapTextureAtlasTextureRegionFactory.createTiledFromSource(pBuildableBitmapTextureAtlas, bitmapTextureAtlasSource, pTileColumns, pTileRows); } - - public static ITextureRegion createFromResource(final BuildableBitmapTextureAtlas pBuildableBitmapTextureAtlas, final Context pContext, final int pDrawableResourceID) { + public static TextureRegion createFromResource(final BuildableBitmapTextureAtlas pBuildableBitmapTextureAtlas, final Context pContext, final int pDrawableResourceID) { return BitmapTextureAtlasTextureRegionFactory.createFromResource(pBuildableBitmapTextureAtlas, pContext.getResources(), pDrawableResourceID); } - public static ITextureRegion createFromResource(final BuildableBitmapTextureAtlas pBuildableBitmapTextureAtlas, final Resources pResources, final int pDrawableResourceID) { + public static TextureRegion createFromResource(final BuildableBitmapTextureAtlas pBuildableBitmapTextureAtlas, final Resources pResources, final int pDrawableResourceID) { return BitmapTextureAtlasTextureRegionFactory.createFromResource(pBuildableBitmapTextureAtlas, pResources, pDrawableResourceID, false); } - public static ITextureRegion createFromResource(final BuildableBitmapTextureAtlas pBuildableBitmapTextureAtlas, final Context pContext, final int pDrawableResourceID, final boolean pRotated) { + public static TextureRegion createFromResource(final BuildableBitmapTextureAtlas pBuildableBitmapTextureAtlas, final Context pContext, final int pDrawableResourceID, final boolean pRotated) { return BitmapTextureAtlasTextureRegionFactory.createFromResource(pBuildableBitmapTextureAtlas, pContext.getResources(), pDrawableResourceID, pRotated); } - public static ITextureRegion createFromResource(final BuildableBitmapTextureAtlas pBuildableBitmapTextureAtlas, final Resources pResources, final int pDrawableResourceID, final boolean pRotated) { + public static TextureRegion createFromResource(final BuildableBitmapTextureAtlas pBuildableBitmapTextureAtlas, final Resources pResources, final int pDrawableResourceID, final boolean pRotated) { final IBitmapTextureAtlasSource bitmapTextureAtlasSource = ResourceBitmapTextureAtlasSource.create(pResources, pDrawableResourceID); return BitmapTextureAtlasTextureRegionFactory.createFromSource(pBuildableBitmapTextureAtlas, bitmapTextureAtlasSource, pRotated); } @@ -171,11 +181,11 @@ public static TiledTextureRegion createTiledFromResource(final BuildableBitmapTe } - public static ITextureRegion createFromSource(final BuildableBitmapTextureAtlas pBuildableBitmapTextureAtlas, final IBitmapTextureAtlasSource pBitmapTextureAtlasSource) { + public static TextureRegion createFromSource(final BuildableBitmapTextureAtlas pBuildableBitmapTextureAtlas, final IBitmapTextureAtlasSource pBitmapTextureAtlasSource) { return BitmapTextureAtlasTextureRegionFactory.createFromSource(pBuildableBitmapTextureAtlas, pBitmapTextureAtlasSource, false); } - public static ITextureRegion createFromSource(final BuildableBitmapTextureAtlas pBuildableBitmapTextureAtlas, final IBitmapTextureAtlasSource pBitmapTextureAtlasSource, final boolean pRotated) { + public static TextureRegion createFromSource(final BuildableBitmapTextureAtlas pBuildableBitmapTextureAtlas, final IBitmapTextureAtlasSource pBitmapTextureAtlasSource, final boolean pRotated) { return BuildableTextureAtlasTextureRegionFactory.createFromSource(pBuildableBitmapTextureAtlas, pBitmapTextureAtlasSource, pRotated); } @@ -183,6 +193,32 @@ public static TiledTextureRegion createTiledFromSource(final BuildableBitmapText return BuildableTextureAtlasTextureRegionFactory.createTiledFromSource(pBuildableBitmapTextureAtlas, pBitmapTextureAtlasSource, pTileColumns, pTileRows); } + /** + * Loads all files from a given assets directory (in alphabetical order) as consecutive tiles of an {@link TiledTextureRegion}. + * + * @param pBuildableBitmapTextureAtlas + * @param pAssetManager + * @param pAssetSubdirectory to load all files from "gfx/flowers" put "flowers" here (assuming, that you've used {@link BitmapTextureAtlasTextureRegionFactory#setAssetBasePath(String)} with "gfx/" before.) + * @return + */ + public static TiledTextureRegion createTiledFromAssetDirectory(final BuildableBitmapTextureAtlas pBuildableBitmapTextureAtlas, final AssetManager pAssetManager, final String pAssetSubdirectory) { + final String[] files; + try { + files = pAssetManager.list(BitmapTextureAtlasTextureRegionFactory.sAssetBasePath + pAssetSubdirectory); + } catch (final IOException e) { + throw new AndEngineRuntimeException("Listing assets subdirectory: '" + BitmapTextureAtlasTextureRegionFactory.sAssetBasePath + pAssetSubdirectory + "' failed. Does it exist?", e); + } + final int fileCount = files.length; + final TextureRegion[] textures = new TextureRegion[fileCount]; + + for (int i = 0; i < fileCount; i++) { + final String assetPath = pAssetSubdirectory + "/" + files[i]; + textures[i] = BitmapTextureAtlasTextureRegionFactory.createFromAsset(pBuildableBitmapTextureAtlas, pAssetManager, assetPath); + } + + return new TiledTextureRegion(pBuildableBitmapTextureAtlas, textures); + } + // =========================================================== // Inner and Anonymous Classes // =========================================================== diff --git a/src/org/andengine/opengl/texture/atlas/bitmap/BuildableBitmapTextureAtlas.java b/src/org/andengine/opengl/texture/atlas/bitmap/BuildableBitmapTextureAtlas.java index 738da5ba3..225b30b19 100644 --- a/src/org/andengine/opengl/texture/atlas/bitmap/BuildableBitmapTextureAtlas.java +++ b/src/org/andengine/opengl/texture/atlas/bitmap/BuildableBitmapTextureAtlas.java @@ -8,9 +8,9 @@ import org.andengine.opengl.texture.bitmap.BitmapTextureFormat; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 15:51:46 - 12.07.2011 */ @@ -35,7 +35,7 @@ public BuildableBitmapTextureAtlas(final TextureManager pTextureManager, final i } /** - * @param pBitmapTextureFormat use {@link BitmapTextureFormat#RGBA_8888} or {@link BitmapTextureFormat#RGBA_4444} for a {@link BitmapTextureAtlas} with transparency and {@link BitmapTextureFormat#RGB_565} for a {@link BitmapTextureAtlas} without transparency. + * @param pBitmapTextureFormat use {@link BitmapTextureFormat#RGBA_8888} or {@link BitmapTextureFormat#RGBA_4444} for a {@link BitmapTextureAtlas} with transparency and {@link BitmapTextureFormat#RGB_565} for a {@link BitmapTextureAtlas} without transparency. */ public BuildableBitmapTextureAtlas(final TextureManager pTextureManager, final int pWidth, final int pHeight, final BitmapTextureFormat pBitmapTextureFormat) { this(pTextureManager, pWidth, pHeight, pBitmapTextureFormat, TextureOptions.DEFAULT, null); @@ -51,7 +51,7 @@ public BuildableBitmapTextureAtlas(final TextureManager pTextureManager, final i } /** - * @param pBitmapTextureFormat use {@link BitmapTextureFormat#RGBA_8888} or {@link BitmapTextureFormat#RGBA_4444} for a {@link BitmapTextureAtlas} with transparency and {@link BitmapTextureFormat#RGB_565} for a {@link BitmapTextureAtlas} without transparency. + * @param pBitmapTextureFormat use {@link BitmapTextureFormat#RGBA_8888} or {@link BitmapTextureFormat#RGBA_4444} for a {@link BitmapTextureAtlas} with transparency and {@link BitmapTextureFormat#RGB_565} for a {@link BitmapTextureAtlas} without transparency. * @param pTextureStateListener to be informed when this {@link BitmapTextureAtlas} is loaded, unloaded or a {@link ITextureAtlasSource} failed to load. */ public BuildableBitmapTextureAtlas(final TextureManager pTextureManager, final int pWidth, final int pHeight, final BitmapTextureFormat pBitmapTextureFormat, final ITextureAtlasStateListener pTextureStateListener) { @@ -68,7 +68,7 @@ public BuildableBitmapTextureAtlas(final TextureManager pTextureManager, final i } /** - * @param pBitmapTextureFormat use {@link BitmapTextureFormat#RGBA_8888} or {@link BitmapTextureFormat#RGBA_4444} for a {@link BitmapTextureAtlas} with transparency and {@link BitmapTextureFormat#RGB_565} for a {@link BitmapTextureAtlas} without transparency. + * @param pBitmapTextureFormat use {@link BitmapTextureFormat#RGBA_8888} or {@link BitmapTextureFormat#RGBA_4444} for a {@link BitmapTextureAtlas} with transparency and {@link BitmapTextureFormat#RGB_565} for a {@link BitmapTextureAtlas} without transparency. * @param pTextureOptions the (quality) settings of the BitmapTexture. */ public BuildableBitmapTextureAtlas(final TextureManager pTextureManager, final int pWidth, final int pHeight, final BitmapTextureFormat pBitmapTextureFormat, final TextureOptions pTextureOptions) throws IllegalArgumentException { @@ -86,7 +86,7 @@ public BuildableBitmapTextureAtlas(final TextureManager pTextureManager, final i } /** - * @param pBitmapTextureFormat use {@link BitmapTextureFormat#RGBA_8888} or {@link BitmapTextureFormat#RGBA_4444} for a {@link BitmapTextureAtlas} with transparency and {@link BitmapTextureFormat#RGB_565} for a {@link BitmapTextureAtlas} without transparency. + * @param pBitmapTextureFormat use {@link BitmapTextureFormat#RGBA_8888} or {@link BitmapTextureFormat#RGBA_4444} for a {@link BitmapTextureAtlas} with transparency and {@link BitmapTextureFormat#RGB_565} for a {@link BitmapTextureAtlas} without transparency. * @param pTextureOptions the (quality) settings of the BitmapTexture. * @param pTextureStateListener to be informed when this {@link BitmapTextureAtlas} is loaded, unloaded or a {@link ITextureAtlasSource} failed to load. */ diff --git a/src/org/andengine/opengl/texture/atlas/bitmap/source/AssetBitmapTextureAtlasSource.java b/src/org/andengine/opengl/texture/atlas/bitmap/source/AssetBitmapTextureAtlasSource.java index 9b8462aab..91edaadb4 100644 --- a/src/org/andengine/opengl/texture/atlas/bitmap/source/AssetBitmapTextureAtlasSource.java +++ b/src/org/andengine/opengl/texture/atlas/bitmap/source/AssetBitmapTextureAtlasSource.java @@ -4,18 +4,22 @@ import java.io.InputStream; import org.andengine.opengl.texture.atlas.source.BaseTextureAtlasSource; +import org.andengine.util.BitmapUtils; import org.andengine.util.StreamUtils; import org.andengine.util.debug.Debug; +import org.andengine.util.system.SystemUtils; +import android.annotation.TargetApi; import android.content.res.AssetManager; import android.graphics.Bitmap; import android.graphics.Bitmap.Config; import android.graphics.BitmapFactory; +import android.os.Build; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 12:07:52 - 09.03.2010 */ @@ -78,13 +82,31 @@ public AssetBitmapTextureAtlasSource deepCopy() { @Override public Bitmap onLoadBitmap(final Config pBitmapConfig) { + return this.onLoadBitmap(pBitmapConfig, false); + } + + @TargetApi(Build.VERSION_CODES.HONEYCOMB) + @Override + public Bitmap onLoadBitmap(final Config pBitmapConfig, final boolean pMutable) { InputStream in = null; try { final BitmapFactory.Options decodeOptions = new BitmapFactory.Options(); decodeOptions.inPreferredConfig = pBitmapConfig; + decodeOptions.inDither = false; + + if (pMutable && SystemUtils.isAndroidVersionOrHigher(Build.VERSION_CODES.HONEYCOMB)) { + decodeOptions.inMutable = pMutable; + } in = this.mAssetManager.open(this.mAssetPath); - return BitmapFactory.decodeStream(in, null, decodeOptions); + + final Bitmap bitmap = BitmapFactory.decodeStream(in, null, decodeOptions); + + if (pMutable) { + return BitmapUtils.ensureBitmapIsMutable(bitmap); + } else { + return bitmap; + } } catch (final IOException e) { Debug.e("Failed loading Bitmap in " + this.getClass().getSimpleName() + ". AssetPath: " + this.mAssetPath, e); return null; diff --git a/src/org/andengine/opengl/texture/atlas/bitmap/source/BaseBitmapTextureAtlasSource.java b/src/org/andengine/opengl/texture/atlas/bitmap/source/BaseBitmapTextureAtlasSource.java new file mode 100644 index 000000000..eac074d1d --- /dev/null +++ b/src/org/andengine/opengl/texture/atlas/bitmap/source/BaseBitmapTextureAtlasSource.java @@ -0,0 +1,74 @@ +package org.andengine.opengl.texture.atlas.bitmap.source; + +import org.andengine.opengl.texture.atlas.source.BaseTextureAtlasSource; + +import android.graphics.Bitmap; +import android.graphics.Bitmap.Config; + +/** + * (c) 2010 Nicolas Gramlich + * (c) 2011 Zynga Inc. + * + * @author Nicolas Gramlich + * @since 16:43:29 - 06.08.2010 + */ +public abstract class BaseBitmapTextureAtlasSource extends BaseTextureAtlasSource implements IBitmapTextureAtlasSource { + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + protected final IBitmapTextureAtlasSource mBitmapTextureAtlasSource; + + // =========================================================== + // Constructors + // =========================================================== + + public BaseBitmapTextureAtlasSource(final IBitmapTextureAtlasSource pBitmapTextureAtlasSource) { + super(pBitmapTextureAtlasSource.getTextureX(), pBitmapTextureAtlasSource.getTextureY(), pBitmapTextureAtlasSource.getTextureWidth(), pBitmapTextureAtlasSource.getTextureHeight()); + + this.mBitmapTextureAtlasSource = pBitmapTextureAtlasSource; + } + + @Override + public abstract BaseBitmapTextureAtlasSource deepCopy(); + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + public int getTextureWidth() { + return this.mBitmapTextureAtlasSource.getTextureWidth(); + } + + @Override + public int getTextureHeight() { + return this.mBitmapTextureAtlasSource.getTextureHeight(); + } + + @Override + public Bitmap onLoadBitmap(final Config pBitmapConfig) { + return this.mBitmapTextureAtlasSource.onLoadBitmap(pBitmapConfig); + } + + @Override + public Bitmap onLoadBitmap(final Config pBitmapConfig, final boolean pMutable) { + return this.mBitmapTextureAtlasSource.onLoadBitmap(pBitmapConfig, pMutable); + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== +} diff --git a/src/org/andengine/opengl/texture/atlas/bitmap/source/ColorKeyBitmapTextureAtlasSource.java b/src/org/andengine/opengl/texture/atlas/bitmap/source/ColorKeyBitmapTextureAtlasSource.java new file mode 100644 index 000000000..99c9edfa0 --- /dev/null +++ b/src/org/andengine/opengl/texture/atlas/bitmap/source/ColorKeyBitmapTextureAtlasSource.java @@ -0,0 +1,61 @@ +package org.andengine.opengl.texture.atlas.bitmap.source; + +import org.andengine.util.adt.color.Color; + +/** + * (c) 2010 Nicolas Gramlich + * (c) 2011 Zynga Inc. + * + * @author Nicolas Gramlich + * @since 22:16:41 - 06.08.2010 + */ +public class ColorKeyBitmapTextureAtlasSource extends ColorSwapBitmapTextureAtlasSource { + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + // =========================================================== + // Constructors + // =========================================================== + + public ColorKeyBitmapTextureAtlasSource(final IBitmapTextureAtlasSource pBitmapTextureAtlasSource, final Color pColorKeyColor) { + super(pBitmapTextureAtlasSource, pColorKeyColor, Color.TRANSPARENT); + } + + public ColorKeyBitmapTextureAtlasSource(final IBitmapTextureAtlasSource pBitmapTextureAtlasSource, final int pColorKeyColorARGBPackedInt) { + super(pBitmapTextureAtlasSource, pColorKeyColorARGBPackedInt, Color.TRANSPARENT_ARGB_PACKED_INT); + } + + public ColorKeyBitmapTextureAtlasSource(final IBitmapTextureAtlasSource pBitmapTextureAtlasSource, final Color pColorKeyColor, final int pTolerance) { + super(pBitmapTextureAtlasSource, pColorKeyColor, pTolerance, Color.TRANSPARENT); + } + + public ColorKeyBitmapTextureAtlasSource(final IBitmapTextureAtlasSource pBitmapTextureAtlasSource, final int pColorKeyColorARGBPackedInt, final int pTolerance) { + super(pBitmapTextureAtlasSource, pColorKeyColorARGBPackedInt, pTolerance, Color.TRANSPARENT_ARGB_PACKED_INT); + } + + @Override + public ColorKeyBitmapTextureAtlasSource deepCopy() { + return new ColorKeyBitmapTextureAtlasSource(this.mBitmapTextureAtlasSource, this.mColorKeyColorARGBPackedInt, this.mTolerance); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== +} diff --git a/src/org/andengine/opengl/texture/atlas/bitmap/source/ColorSwapBitmapTextureAtlasSource.java b/src/org/andengine/opengl/texture/atlas/bitmap/source/ColorSwapBitmapTextureAtlasSource.java new file mode 100644 index 000000000..2aff2fb6a --- /dev/null +++ b/src/org/andengine/opengl/texture/atlas/bitmap/source/ColorSwapBitmapTextureAtlasSource.java @@ -0,0 +1,127 @@ +package org.andengine.opengl.texture.atlas.bitmap.source; + +import org.andengine.opengl.util.GLHelper; +import org.andengine.util.adt.color.Color; +import org.andengine.util.debug.Debug; + +import android.graphics.Bitmap; +import android.graphics.Bitmap.Config; + +/** + * (c) 2010 Nicolas Gramlich + * (c) 2011 Zynga Inc. + * + * @author Nicolas Gramlich + * @since 19:41:39 - 07.06.2011 + */ +public class ColorSwapBitmapTextureAtlasSource extends BaseBitmapTextureAtlasSource { + // =========================================================== + // Constants + // =========================================================== + + private static final int TOLERANCE_DEFAULT = 0; + + // =========================================================== + // Fields + // =========================================================== + + protected final int mColorKeyColorARGBPackedInt; + protected final int mTolerance; + protected final int mColorSwapColorARGBPackedInt; + + // =========================================================== + // Constructors + // =========================================================== + + public ColorSwapBitmapTextureAtlasSource(final IBitmapTextureAtlasSource pBitmapTextureAtlasSource, final Color pColorKeyColor, final Color pColorSwapColor) { + this(pBitmapTextureAtlasSource, pColorKeyColor.getARGBPackedInt(), pColorSwapColor.getARGBPackedInt()); + } + + public ColorSwapBitmapTextureAtlasSource(final IBitmapTextureAtlasSource pBitmapTextureAtlasSource, final int pColorKeyColorARGBPackedInt, final int pColorSwapColorARGBPackedInt) { + this(pBitmapTextureAtlasSource, pColorKeyColorARGBPackedInt, ColorSwapBitmapTextureAtlasSource.TOLERANCE_DEFAULT, pColorSwapColorARGBPackedInt); + } + + public ColorSwapBitmapTextureAtlasSource(final IBitmapTextureAtlasSource pBitmapTextureAtlasSource, final Color pColorKeyColor, final int pTolerance, final Color pColorSwapColor) { + this(pBitmapTextureAtlasSource, pColorKeyColor.getARGBPackedInt(), pTolerance, pColorSwapColor.getARGBPackedInt()); + } + + public ColorSwapBitmapTextureAtlasSource(final IBitmapTextureAtlasSource pBitmapTextureAtlasSource, final int pColorKeyColorARGBPackedInt, final int pTolerance, final int pColorSwapColorARGBPackedInt) { + super(pBitmapTextureAtlasSource); + + this.mColorKeyColorARGBPackedInt = pColorKeyColorARGBPackedInt; + this.mTolerance = pTolerance; + this.mColorSwapColorARGBPackedInt = pColorSwapColorARGBPackedInt; + } + + @Override + public ColorSwapBitmapTextureAtlasSource deepCopy() { + return new ColorSwapBitmapTextureAtlasSource(this.mBitmapTextureAtlasSource, this.mColorKeyColorARGBPackedInt, this.mTolerance, this.mColorSwapColorARGBPackedInt); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + public Bitmap onLoadBitmap(final Config pBitmapConfig) { + return this.swapColor(super.onLoadBitmap(pBitmapConfig)); + } + + @Override + public Bitmap onLoadBitmap(final Config pBitmapConfig, final boolean pMutable) { + return this.swapColor(super.onLoadBitmap(pBitmapConfig, pMutable)); + } + + // =========================================================== + // Methods + // =========================================================== + + protected Bitmap swapColor(final Bitmap pBitmap) { + final Config config = pBitmap.getConfig(); + switch (config) { + case ARGB_8888: + return ColorSwapBitmapTextureAtlasSource.swapColorARGB_8888(pBitmap, this.mColorKeyColorARGBPackedInt, this.mTolerance, this.mColorSwapColorARGBPackedInt); + default: + Debug.w("Unexpected " + Bitmap.Config.class.getSimpleName() + ": '" + config + "'."); + return pBitmap; + } + } + + protected static final Bitmap swapColorARGB_8888(final Bitmap pBitmap, final int pColorKeyColorARGBPackedInt, final int pTolerance, final int pColorSwapColorARGBPackedInt) { + final int[] pixelsARGB_8888 = GLHelper.getPixelsARGB_8888(pBitmap); + pBitmap.recycle(); + + final int keyRed = (pColorKeyColorARGBPackedInt >> Color.ARGB_PACKED_RED_SHIFT) & 0xFF; + final int keyGreen = (pColorKeyColorARGBPackedInt >> Color.ARGB_PACKED_GREEN_SHIFT) & 0xFF; + final int keyBlue = (pColorKeyColorARGBPackedInt >> Color.ARGB_PACKED_BLUE_SHIFT) & 0xFF; + final int keyAlpha = (pColorKeyColorARGBPackedInt >> Color.ARGB_PACKED_ALPHA_SHIFT) & 0xFF; + + for (int i = pixelsARGB_8888.length - 1; i >= 0; i--) { + final int pixelARGB_8888 = pixelsARGB_8888[i]; + + final int red = (pixelARGB_8888 >> Color.ARGB_PACKED_RED_SHIFT) & 0xFF; + if (Math.abs(red - keyRed) <= pTolerance) { + final int green = (pixelARGB_8888 >> Color.ARGB_PACKED_GREEN_SHIFT) & 0xFF; + if (Math.abs(green - keyGreen) <= pTolerance) { + final int blue = (pixelARGB_8888 >> Color.ARGB_PACKED_BLUE_SHIFT) & 0xFF; + if (Math.abs(blue - keyBlue) <= pTolerance) { + final int alpha = (pixelARGB_8888 >> Color.ARGB_PACKED_ALPHA_SHIFT) & 0xFF; + if (Math.abs(alpha - keyAlpha) <= pTolerance) { + pixelsARGB_8888[i] = pColorSwapColorARGBPackedInt; + } + } + } + } + } + + return Bitmap.createBitmap(pixelsARGB_8888, pBitmap.getWidth(), pBitmap.getHeight(), Config.ARGB_8888); + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== +} diff --git a/src/org/andengine/opengl/texture/atlas/bitmap/source/EmptyBitmapTextureAtlasSource.java b/src/org/andengine/opengl/texture/atlas/bitmap/source/EmptyBitmapTextureAtlasSource.java index a8cd7a337..613fedc0c 100644 --- a/src/org/andengine/opengl/texture/atlas/bitmap/source/EmptyBitmapTextureAtlasSource.java +++ b/src/org/andengine/opengl/texture/atlas/bitmap/source/EmptyBitmapTextureAtlasSource.java @@ -7,9 +7,9 @@ import android.graphics.Bitmap.Config; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 20:20:36 - 08.08.2010 */ @@ -25,7 +25,7 @@ public class EmptyBitmapTextureAtlasSource extends BaseTextureAtlasSource implem // =========================================================== // Constructors // =========================================================== - + public EmptyBitmapTextureAtlasSource(final int pTextureWidth, final int pTextureHeight) { this(0, 0, pTextureWidth, pTextureHeight); } @@ -49,6 +49,11 @@ public EmptyBitmapTextureAtlasSource deepCopy() { @Override public Bitmap onLoadBitmap(final Config pBitmapConfig) { + return this.onLoadBitmap(pBitmapConfig, false); + } + + @Override + public Bitmap onLoadBitmap(final Config pBitmapConfig, final boolean pMutable) { return Bitmap.createBitmap(this.mTextureWidth, this.mTextureHeight, pBitmapConfig); } diff --git a/src/org/andengine/opengl/texture/atlas/bitmap/source/FileBitmapTextureAtlasSource.java b/src/org/andengine/opengl/texture/atlas/bitmap/source/FileBitmapTextureAtlasSource.java index a2ab5948f..dabfe617e 100644 --- a/src/org/andengine/opengl/texture/atlas/bitmap/source/FileBitmapTextureAtlasSource.java +++ b/src/org/andengine/opengl/texture/atlas/bitmap/source/FileBitmapTextureAtlasSource.java @@ -6,20 +6,24 @@ import java.io.InputStream; import org.andengine.opengl.texture.atlas.source.BaseTextureAtlasSource; +import org.andengine.util.BitmapUtils; import org.andengine.util.FileUtils; import org.andengine.util.StreamUtils; import org.andengine.util.debug.Debug; +import org.andengine.util.system.SystemUtils; +import android.annotation.TargetApi; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Bitmap.Config; import android.graphics.BitmapFactory; +import android.os.Build; /** - * - * (c) 2010 Nicolas Gramlich + * + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 16:39:22 - 10.08.2010 */ @@ -37,7 +41,7 @@ public class FileBitmapTextureAtlasSource extends BaseTextureAtlasSource impleme // =========================================================== // Constructors // =========================================================== - + public static FileBitmapTextureAtlasSource create(final File pFile) { return FileBitmapTextureAtlasSource.create(pFile, 0, 0); } @@ -88,13 +92,30 @@ public FileBitmapTextureAtlasSource deepCopy() { @Override public Bitmap onLoadBitmap(final Config pBitmapConfig) { + return this.onLoadBitmap(pBitmapConfig, false); + } + + @TargetApi(Build.VERSION_CODES.HONEYCOMB) + @Override + public Bitmap onLoadBitmap(final Config pBitmapConfig, final boolean pMutable) { final BitmapFactory.Options decodeOptions = new BitmapFactory.Options(); decodeOptions.inPreferredConfig = pBitmapConfig; + decodeOptions.inDither = false; + + if (pMutable && SystemUtils.isAndroidVersionOrHigher(Build.VERSION_CODES.HONEYCOMB)) { + decodeOptions.inMutable = pMutable; + } InputStream in = null; try { in = new FileInputStream(this.mFile); - return BitmapFactory.decodeStream(in, null, decodeOptions); + final Bitmap bitmap = BitmapFactory.decodeStream(in, null, decodeOptions); + + if (pMutable) { + return BitmapUtils.ensureBitmapIsMutable(bitmap); + } else { + return bitmap; + } } catch (final IOException e) { Debug.e("Failed loading Bitmap in " + this.getClass().getSimpleName() + ". File: " + this.mFile, e); return null; diff --git a/src/org/andengine/opengl/texture/atlas/bitmap/source/IBitmapTextureAtlasSource.java b/src/org/andengine/opengl/texture/atlas/bitmap/source/IBitmapTextureAtlasSource.java index a022f0b24..5c11f9035 100644 --- a/src/org/andengine/opengl/texture/atlas/bitmap/source/IBitmapTextureAtlasSource.java +++ b/src/org/andengine/opengl/texture/atlas/bitmap/source/IBitmapTextureAtlasSource.java @@ -6,9 +6,9 @@ import android.graphics.Bitmap.Config; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 12:08:52 - 09.03.2010 */ @@ -25,4 +25,5 @@ public interface IBitmapTextureAtlasSource extends ITextureAtlasSource { public IBitmapTextureAtlasSource deepCopy(); public Bitmap onLoadBitmap(final Config pBitmapConfig); + public Bitmap onLoadBitmap(final Config pBitmapConfig, final boolean pMutable); } \ No newline at end of file diff --git a/src/org/andengine/opengl/texture/atlas/bitmap/source/PictureBitmapTextureAtlasSource.java b/src/org/andengine/opengl/texture/atlas/bitmap/source/PictureBitmapTextureAtlasSource.java index 2082a323e..06d639711 100644 --- a/src/org/andengine/opengl/texture/atlas/bitmap/source/PictureBitmapTextureAtlasSource.java +++ b/src/org/andengine/opengl/texture/atlas/bitmap/source/PictureBitmapTextureAtlasSource.java @@ -9,9 +9,9 @@ import android.graphics.Picture; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 12:52:58 - 21.05.2011 */ @@ -33,7 +33,7 @@ public abstract class PictureBitmapTextureAtlasSource extends BaseTextureAtlasSo public PictureBitmapTextureAtlasSource(final Picture pPicture) { this(pPicture, 0, 0); } - + public PictureBitmapTextureAtlasSource(final Picture pPicture, final int pTextureX, final int pTextureY) { this(pPicture, pTextureX, pTextureY, pPicture.getWidth(), pPicture.getHeight()); } @@ -62,7 +62,7 @@ public PictureBitmapTextureAtlasSource(final Picture pPicture, final int pTextur @Override public Bitmap onLoadBitmap(final Config pBitmapConfig) { final Picture picture = this.mPicture; - if(picture == null) { + if (picture == null) { Debug.e("Failed loading Bitmap in " + this.getClass().getSimpleName() + "."); return null; } diff --git a/src/org/andengine/opengl/texture/atlas/bitmap/source/ResourceBitmapTextureAtlasSource.java b/src/org/andengine/opengl/texture/atlas/bitmap/source/ResourceBitmapTextureAtlasSource.java index 8bc451cf9..ca843db14 100644 --- a/src/org/andengine/opengl/texture/atlas/bitmap/source/ResourceBitmapTextureAtlasSource.java +++ b/src/org/andengine/opengl/texture/atlas/bitmap/source/ResourceBitmapTextureAtlasSource.java @@ -2,16 +2,20 @@ import org.andengine.opengl.texture.atlas.source.BaseTextureAtlasSource; +import org.andengine.util.BitmapUtils; +import org.andengine.util.system.SystemUtils; +import android.annotation.TargetApi; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.Bitmap.Config; import android.graphics.BitmapFactory; +import android.os.Build; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 15:07:23 - 09.03.2010 */ @@ -67,10 +71,28 @@ public ResourceBitmapTextureAtlasSource deepCopy() { @Override public Bitmap onLoadBitmap(final Config pBitmapConfig) { + return this.onLoadBitmap(pBitmapConfig, false); + } + + @TargetApi(Build.VERSION_CODES.HONEYCOMB) + @Override + public Bitmap onLoadBitmap(final Config pBitmapConfig, final boolean pMutable) { final BitmapFactory.Options decodeOptions = new BitmapFactory.Options(); decodeOptions.inPreferredConfig = pBitmapConfig; + decodeOptions.inDither = false; // decodeOptions.inScaled = false; // TODO Check how this behaves with drawable-""/nodpi/ldpi/mdpi/hdpi folders - return BitmapFactory.decodeResource(this.mResources, this.mDrawableResourceID, decodeOptions); + + if (pMutable && SystemUtils.isAndroidVersionOrHigher(Build.VERSION_CODES.HONEYCOMB)) { + decodeOptions.inMutable = pMutable; + } + + final Bitmap bitmap = BitmapFactory.decodeResource(this.mResources, this.mDrawableResourceID, decodeOptions); + + if (pMutable) { + return BitmapUtils.ensureBitmapIsMutable(bitmap); + } else { + return bitmap; + } } @Override diff --git a/src/org/andengine/opengl/texture/atlas/bitmap/source/decorator/BaseBitmapTextureAtlasSourceDecorator.java b/src/org/andengine/opengl/texture/atlas/bitmap/source/decorator/BaseBitmapTextureAtlasSourceDecorator.java index ae5577132..92eded248 100644 --- a/src/org/andengine/opengl/texture/atlas/bitmap/source/decorator/BaseBitmapTextureAtlasSourceDecorator.java +++ b/src/org/andengine/opengl/texture/atlas/bitmap/source/decorator/BaseBitmapTextureAtlasSourceDecorator.java @@ -1,7 +1,7 @@ package org.andengine.opengl.texture.atlas.bitmap.source.decorator; +import org.andengine.opengl.texture.atlas.bitmap.source.BaseBitmapTextureAtlasSource; import org.andengine.opengl.texture.atlas.bitmap.source.IBitmapTextureAtlasSource; -import org.andengine.opengl.texture.atlas.source.BaseTextureAtlasSource; import org.andengine.util.debug.Debug; import android.graphics.Bitmap; @@ -10,13 +10,13 @@ import android.graphics.Paint; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 16:43:29 - 06.08.2010 */ -public abstract class BaseBitmapTextureAtlasSourceDecorator extends BaseTextureAtlasSource implements IBitmapTextureAtlasSource { +public abstract class BaseBitmapTextureAtlasSourceDecorator extends BaseBitmapTextureAtlasSource { // =========================================================== // Constants // =========================================================== @@ -25,7 +25,6 @@ public abstract class BaseBitmapTextureAtlasSourceDecorator extends BaseTextureA // Fields // =========================================================== - protected final IBitmapTextureAtlasSource mBitmapTextureAtlasSource; protected TextureAtlasSourceDecoratorOptions mTextureAtlasSourceDecoratorOptions; protected Paint mPaint = new Paint(); @@ -38,9 +37,8 @@ public BaseBitmapTextureAtlasSourceDecorator(final IBitmapTextureAtlasSource pBi } public BaseBitmapTextureAtlasSourceDecorator(final IBitmapTextureAtlasSource pBitmapTextureAtlasSource, final TextureAtlasSourceDecoratorOptions pTextureAtlasSourceDecoratorOptions) { - super(pBitmapTextureAtlasSource.getTextureX(), pBitmapTextureAtlasSource.getTextureY(), pBitmapTextureAtlasSource.getTextureWidth(), pBitmapTextureAtlasSource.getTextureHeight()); + super(pBitmapTextureAtlasSource); - this.mBitmapTextureAtlasSource = pBitmapTextureAtlasSource; this.mTextureAtlasSourceDecoratorOptions = (pTextureAtlasSourceDecoratorOptions == null) ? new TextureAtlasSourceDecoratorOptions() : pTextureAtlasSourceDecoratorOptions; this.mPaint.setAntiAlias(this.mTextureAtlasSourceDecoratorOptions.getAntiAliasing()); } @@ -74,19 +72,9 @@ public void setTextureAtlasSourceDecoratorOptions(final TextureAtlasSourceDecora protected abstract void onDecorateBitmap(final Canvas pCanvas) throws Exception; - @Override - public int getTextureWidth() { - return this.mBitmapTextureAtlasSource.getTextureWidth(); - } - - @Override - public int getTextureHeight() { - return this.mBitmapTextureAtlasSource.getTextureHeight(); - } - @Override public Bitmap onLoadBitmap(final Config pBitmapConfig) { - final Bitmap bitmap = this.ensureLoadedBitmapIsMutable(this.mBitmapTextureAtlasSource.onLoadBitmap(pBitmapConfig)); + final Bitmap bitmap = this.onLoadBitmap(pBitmapConfig, true); final Canvas canvas = new Canvas(bitmap); try { @@ -101,16 +89,6 @@ public Bitmap onLoadBitmap(final Config pBitmapConfig) { // Methods // =========================================================== - private Bitmap ensureLoadedBitmapIsMutable(final Bitmap pBitmap) { - if(pBitmap.isMutable()) { - return pBitmap; - } else { - final Bitmap mutableBitmap = pBitmap.copy(pBitmap.getConfig(), true); - pBitmap.recycle(); - return mutableBitmap; - } - } - // =========================================================== // Inner and Anonymous Classes // =========================================================== diff --git a/src/org/andengine/opengl/texture/atlas/bitmap/source/decorator/BaseShapeBitmapTextureAtlasSourceDecorator.java b/src/org/andengine/opengl/texture/atlas/bitmap/source/decorator/BaseShapeBitmapTextureAtlasSourceDecorator.java index 5fa008c21..2c9b12c62 100644 --- a/src/org/andengine/opengl/texture/atlas/bitmap/source/decorator/BaseShapeBitmapTextureAtlasSourceDecorator.java +++ b/src/org/andengine/opengl/texture/atlas/bitmap/source/decorator/BaseShapeBitmapTextureAtlasSourceDecorator.java @@ -6,9 +6,9 @@ import android.graphics.Canvas; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 20:09:41 - 05.11.2010 */ @@ -45,7 +45,7 @@ public BaseShapeBitmapTextureAtlasSourceDecorator(final IBitmapTextureAtlasSourc // =========================================================== @Override - protected void onDecorateBitmap(final Canvas pCanvas){ + protected void onDecorateBitmap(final Canvas pCanvas) { this.mBitmapTextureAtlasSourceDecoratorShape.onDecorateBitmap(pCanvas, this.mPaint, (this.mTextureAtlasSourceDecoratorOptions == null) ? TextureAtlasSourceDecoratorOptions.DEFAULT : this.mTextureAtlasSourceDecoratorOptions); } diff --git a/src/org/andengine/opengl/texture/atlas/bitmap/source/decorator/ColorKeyBitmapTextureAtlasSourceDecorator.java b/src/org/andengine/opengl/texture/atlas/bitmap/source/decorator/ColorKeyBitmapTextureAtlasSourceDecorator.java index 60e5a1cb8..d3ebcfd2e 100644 --- a/src/org/andengine/opengl/texture/atlas/bitmap/source/decorator/ColorKeyBitmapTextureAtlasSourceDecorator.java +++ b/src/org/andengine/opengl/texture/atlas/bitmap/source/decorator/ColorKeyBitmapTextureAtlasSourceDecorator.java @@ -1,16 +1,24 @@ package org.andengine.opengl.texture.atlas.bitmap.source.decorator; +import org.andengine.opengl.texture.atlas.bitmap.source.ColorKeyBitmapTextureAtlasSource; import org.andengine.opengl.texture.atlas.bitmap.source.IBitmapTextureAtlasSource; import org.andengine.opengl.texture.atlas.bitmap.source.decorator.shape.IBitmapTextureAtlasSourceDecoratorShape; -import org.andengine.util.color.Color; +import org.andengine.util.adt.color.Color; + +import android.os.Build; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * + * @deprecated On {@link Build.VERSION_CODES#JELLY_BEAN} and higher! + * + * @see {@link ColorKeyBitmapTextureAtlasSource} + * * @author Nicolas Gramlich * @since 22:16:41 - 06.08.2010 */ +@Deprecated public class ColorKeyBitmapTextureAtlasSourceDecorator extends ColorSwapBitmapTextureAtlasSourceDecorator { // =========================================================== // Constants @@ -35,7 +43,7 @@ public ColorKeyBitmapTextureAtlasSourceDecorator(final IBitmapTextureAtlasSource public ColorKeyBitmapTextureAtlasSourceDecorator(final IBitmapTextureAtlasSource pBitmapTextureAtlasSource, final IBitmapTextureAtlasSourceDecoratorShape pBitmapTextureAtlasSourceDecoratorShape, final Color pColorKeyColor, final TextureAtlasSourceDecoratorOptions pTextureAtlasSourceDecoratorOptions) { super(pBitmapTextureAtlasSource, pBitmapTextureAtlasSourceDecoratorShape, pColorKeyColor, Color.TRANSPARENT, pTextureAtlasSourceDecoratorOptions); } - + public ColorKeyBitmapTextureAtlasSourceDecorator(final IBitmapTextureAtlasSource pBitmapTextureAtlasSource, final IBitmapTextureAtlasSourceDecoratorShape pBitmapTextureAtlasSourceDecoratorShape, final int pColorKeyColorARGBPackedInt, final TextureAtlasSourceDecoratorOptions pTextureAtlasSourceDecoratorOptions) { super(pBitmapTextureAtlasSource, pBitmapTextureAtlasSourceDecoratorShape, pColorKeyColorARGBPackedInt, Color.TRANSPARENT_ARGB_PACKED_INT, pTextureAtlasSourceDecoratorOptions); } @@ -43,7 +51,7 @@ public ColorKeyBitmapTextureAtlasSourceDecorator(final IBitmapTextureAtlasSource public ColorKeyBitmapTextureAtlasSourceDecorator(final IBitmapTextureAtlasSource pBitmapTextureAtlasSource, final IBitmapTextureAtlasSourceDecoratorShape pBitmapTextureAtlasSourceDecoratorShape, final Color pColorKeyColor, final int pTolerance) { super(pBitmapTextureAtlasSource, pBitmapTextureAtlasSourceDecoratorShape, pColorKeyColor, pTolerance, Color.TRANSPARENT); } - + public ColorKeyBitmapTextureAtlasSourceDecorator(final IBitmapTextureAtlasSource pBitmapTextureAtlasSource, final IBitmapTextureAtlasSourceDecoratorShape pBitmapTextureAtlasSourceDecoratorShape, final int pColorKeyColorARGBPackedInt, final int pTolerance) { super(pBitmapTextureAtlasSource, pBitmapTextureAtlasSourceDecoratorShape, pColorKeyColorARGBPackedInt, pTolerance, Color.TRANSPARENT_ARGB_PACKED_INT); } @@ -51,7 +59,7 @@ public ColorKeyBitmapTextureAtlasSourceDecorator(final IBitmapTextureAtlasSource public ColorKeyBitmapTextureAtlasSourceDecorator(final IBitmapTextureAtlasSource pBitmapTextureAtlasSource, final IBitmapTextureAtlasSourceDecoratorShape pBitmapTextureAtlasSourceDecoratorShape, final Color pColorKeyColor, final int pTolerance, final TextureAtlasSourceDecoratorOptions pTextureAtlasSourceDecoratorOptions) { super(pBitmapTextureAtlasSource, pBitmapTextureAtlasSourceDecoratorShape, pColorKeyColor, pTolerance, Color.TRANSPARENT, pTextureAtlasSourceDecoratorOptions); } - + public ColorKeyBitmapTextureAtlasSourceDecorator(final IBitmapTextureAtlasSource pBitmapTextureAtlasSource, final IBitmapTextureAtlasSourceDecoratorShape pBitmapTextureAtlasSourceDecoratorShape, final int pColorKeyColorARGBPackedInt, final int pTolerance, final TextureAtlasSourceDecoratorOptions pTextureAtlasSourceDecoratorOptions) { super(pBitmapTextureAtlasSource, pBitmapTextureAtlasSourceDecoratorShape, pColorKeyColorARGBPackedInt, pTolerance, Color.TRANSPARENT_ARGB_PACKED_INT, pTextureAtlasSourceDecoratorOptions); } diff --git a/src/org/andengine/opengl/texture/atlas/bitmap/source/decorator/ColorSwapBitmapTextureAtlasSourceDecorator.java b/src/org/andengine/opengl/texture/atlas/bitmap/source/decorator/ColorSwapBitmapTextureAtlasSourceDecorator.java index b36982502..8391d529f 100644 --- a/src/org/andengine/opengl/texture/atlas/bitmap/source/decorator/ColorSwapBitmapTextureAtlasSourceDecorator.java +++ b/src/org/andengine/opengl/texture/atlas/bitmap/source/decorator/ColorSwapBitmapTextureAtlasSourceDecorator.java @@ -1,19 +1,28 @@ package org.andengine.opengl.texture.atlas.bitmap.source.decorator; +import org.andengine.opengl.texture.atlas.bitmap.source.ColorSwapBitmapTextureAtlasSource; import org.andengine.opengl.texture.atlas.bitmap.source.IBitmapTextureAtlasSource; import org.andengine.opengl.texture.atlas.bitmap.source.decorator.shape.IBitmapTextureAtlasSourceDecoratorShape; -import org.andengine.util.color.Color; +import org.andengine.util.adt.color.Color; +import org.andengine.util.debug.Debug; +import org.andengine.util.system.SystemUtils; import android.graphics.AvoidXfermode; import android.graphics.AvoidXfermode.Mode; +import android.os.Build; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * + * @deprecated On {@link Build.VERSION_CODES#JELLY_BEAN} and higher! + * + * @see {@link ColorSwapBitmapTextureAtlasSource} + * * @author Nicolas Gramlich * @since 19:41:39 - 07.06.2011 */ +@Deprecated public class ColorSwapBitmapTextureAtlasSourceDecorator extends BaseShapeBitmapTextureAtlasSourceDecorator { // =========================================================== // Constants @@ -69,6 +78,10 @@ public ColorSwapBitmapTextureAtlasSourceDecorator(final IBitmapTextureAtlasSourc this.mColorSwapColorARGBPackedInt = pColorSwapColorARGBPackedInt; this.mPaint.setXfermode(new AvoidXfermode(pColorKeyColorARGBPackedInt, pTolerance, Mode.TARGET)); this.mPaint.setColor(pColorSwapColorARGBPackedInt); + + if (SystemUtils.isAndroidVersionOrHigher(Build.VERSION_CODES.JELLY_BEAN)) { + Debug.w("The class " + ColorSwapBitmapTextureAtlasSourceDecorator.class.getSimpleName() + " is deprecated for Android API Level: '" + Build.VERSION_CODES.JELLY_BEAN + "' and higher, since the class " + AvoidXfermode.class.getSimpleName() + " is deprecated since then."); + } } @Override diff --git a/src/org/andengine/opengl/texture/atlas/bitmap/source/decorator/FillBitmapTextureAtlasSourceDecorator.java b/src/org/andengine/opengl/texture/atlas/bitmap/source/decorator/FillBitmapTextureAtlasSourceDecorator.java index ca26cd8d2..5138e45b3 100644 --- a/src/org/andengine/opengl/texture/atlas/bitmap/source/decorator/FillBitmapTextureAtlasSourceDecorator.java +++ b/src/org/andengine/opengl/texture/atlas/bitmap/source/decorator/FillBitmapTextureAtlasSourceDecorator.java @@ -6,9 +6,9 @@ import android.graphics.Paint.Style; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 18:08:00 - 05.11.2010 */ diff --git a/src/org/andengine/opengl/texture/atlas/bitmap/source/decorator/LinearGradientFillBitmapTextureAtlasSourceDecorator.java b/src/org/andengine/opengl/texture/atlas/bitmap/source/decorator/LinearGradientFillBitmapTextureAtlasSourceDecorator.java index b9b6c2a6a..0845f6faf 100644 --- a/src/org/andengine/opengl/texture/atlas/bitmap/source/decorator/LinearGradientFillBitmapTextureAtlasSourceDecorator.java +++ b/src/org/andengine/opengl/texture/atlas/bitmap/source/decorator/LinearGradientFillBitmapTextureAtlasSourceDecorator.java @@ -8,9 +8,9 @@ import android.graphics.Shader.TileMode; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 19:21:24 - 05.11.2010 */ diff --git a/src/org/andengine/opengl/texture/atlas/bitmap/source/decorator/OutlineBitmapTextureAtlasSourceDecorator.java b/src/org/andengine/opengl/texture/atlas/bitmap/source/decorator/OutlineBitmapTextureAtlasSourceDecorator.java index ee319428c..3e9520aea 100644 --- a/src/org/andengine/opengl/texture/atlas/bitmap/source/decorator/OutlineBitmapTextureAtlasSourceDecorator.java +++ b/src/org/andengine/opengl/texture/atlas/bitmap/source/decorator/OutlineBitmapTextureAtlasSourceDecorator.java @@ -6,9 +6,9 @@ import android.graphics.Paint.Style; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 18:07:55 - 05.11.2010 */ diff --git a/src/org/andengine/opengl/texture/atlas/bitmap/source/decorator/RadialGradientFillBitmapTextureAtlasSourceDecorator.java b/src/org/andengine/opengl/texture/atlas/bitmap/source/decorator/RadialGradientFillBitmapTextureAtlasSourceDecorator.java index be6402bd8..cf7aaabf6 100644 --- a/src/org/andengine/opengl/texture/atlas/bitmap/source/decorator/RadialGradientFillBitmapTextureAtlasSourceDecorator.java +++ b/src/org/andengine/opengl/texture/atlas/bitmap/source/decorator/RadialGradientFillBitmapTextureAtlasSourceDecorator.java @@ -9,9 +9,9 @@ import android.graphics.Shader.TileMode; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 19:21:24 - 05.11.2010 */ @@ -19,8 +19,8 @@ public class RadialGradientFillBitmapTextureAtlasSourceDecorator extends BaseSha // =========================================================== // Constants // =========================================================== - - private static final float[] POSITIONS_DEFAULT = new float[] { 0.0f, 1.0f }; + + private static final float[] POSITIONS_DEFAULT = new float[] { 0.0f, 1.0f }; // =========================================================== // Fields @@ -42,7 +42,7 @@ public RadialGradientFillBitmapTextureAtlasSourceDecorator(final IBitmapTextureA this(pBitmapTextureAtlasSource, pBitmapTextureAtlasSourceDecoratorShape, new int[] { pFromColor, pToColor }, POSITIONS_DEFAULT, pRadialGradientDirection, pTextureAtlasSourceDecoratorOptions); } - public RadialGradientFillBitmapTextureAtlasSourceDecorator(final IBitmapTextureAtlasSource pBitmapTextureAtlasSource, final IBitmapTextureAtlasSourceDecoratorShape pBitmapTextureAtlasSourceDecoratorShape, final int[] pColors, final float[] pPositions, final RadialGradientDirection pRadialGradientDirection) { + public RadialGradientFillBitmapTextureAtlasSourceDecorator(final IBitmapTextureAtlasSource pBitmapTextureAtlasSource, final IBitmapTextureAtlasSourceDecoratorShape pBitmapTextureAtlasSourceDecoratorShape, final int[] pColors, final float[] pPositions, final RadialGradientDirection pRadialGradientDirection) { this(pBitmapTextureAtlasSource, pBitmapTextureAtlasSourceDecoratorShape, pColors, pPositions, pRadialGradientDirection, null); } @@ -62,7 +62,7 @@ public RadialGradientFillBitmapTextureAtlasSourceDecorator(final IBitmapTextureA final float radius = Math.max(centerX, centerY); - switch(pRadialGradientDirection) { + switch (pRadialGradientDirection) { case INSIDE_OUT: this.mPaint.setShader(new RadialGradient(centerX, centerY, radius, pColors, pPositions, TileMode.CLAMP)); break; diff --git a/src/org/andengine/opengl/texture/atlas/bitmap/source/decorator/shape/ArcBitmapTextureAtlasSourceDecoratorShape.java b/src/org/andengine/opengl/texture/atlas/bitmap/source/decorator/shape/ArcBitmapTextureAtlasSourceDecoratorShape.java index 404d0edb5..8279a929f 100644 --- a/src/org/andengine/opengl/texture/atlas/bitmap/source/decorator/shape/ArcBitmapTextureAtlasSourceDecoratorShape.java +++ b/src/org/andengine/opengl/texture/atlas/bitmap/source/decorator/shape/ArcBitmapTextureAtlasSourceDecoratorShape.java @@ -7,9 +7,9 @@ import android.graphics.RectF; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 12:52:55 - 04.01.2011 */ @@ -50,7 +50,7 @@ public ArcBitmapTextureAtlasSourceDecoratorShape(final float pStartAngle, final @Deprecated public static ArcBitmapTextureAtlasSourceDecoratorShape getDefaultInstance() { - if(sDefaultInstance == null) { + if (sDefaultInstance == null) { sDefaultInstance = new ArcBitmapTextureAtlasSourceDecoratorShape(); } return sDefaultInstance; diff --git a/src/org/andengine/opengl/texture/atlas/bitmap/source/decorator/shape/CircleBitmapTextureAtlasSourceDecoratorShape.java b/src/org/andengine/opengl/texture/atlas/bitmap/source/decorator/shape/CircleBitmapTextureAtlasSourceDecoratorShape.java index 0c061f9ce..d3401285b 100644 --- a/src/org/andengine/opengl/texture/atlas/bitmap/source/decorator/shape/CircleBitmapTextureAtlasSourceDecoratorShape.java +++ b/src/org/andengine/opengl/texture/atlas/bitmap/source/decorator/shape/CircleBitmapTextureAtlasSourceDecoratorShape.java @@ -6,9 +6,9 @@ import android.graphics.Paint; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 12:53:13 - 04.01.2011 */ @@ -32,7 +32,7 @@ public CircleBitmapTextureAtlasSourceDecoratorShape() { } public static CircleBitmapTextureAtlasSourceDecoratorShape getDefaultInstance() { - if(sDefaultInstance == null) { + if (sDefaultInstance == null) { sDefaultInstance = new CircleBitmapTextureAtlasSourceDecoratorShape(); } return sDefaultInstance; @@ -45,7 +45,7 @@ public static CircleBitmapTextureAtlasSourceDecoratorShape getDefaultInstance() // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== - + @Override public void onDecorateBitmap(final Canvas pCanvas, final Paint pPaint, final TextureAtlasSourceDecoratorOptions pDecoratorOptions) { final float width = pCanvas.getWidth() - pDecoratorOptions.getInsetLeft() - pDecoratorOptions.getInsetRight(); diff --git a/src/org/andengine/opengl/texture/atlas/bitmap/source/decorator/shape/EllipseBitmapTextureAtlasSourceDecoratorShape.java b/src/org/andengine/opengl/texture/atlas/bitmap/source/decorator/shape/EllipseBitmapTextureAtlasSourceDecoratorShape.java index e2a68fa8b..57d64a158 100644 --- a/src/org/andengine/opengl/texture/atlas/bitmap/source/decorator/shape/EllipseBitmapTextureAtlasSourceDecoratorShape.java +++ b/src/org/andengine/opengl/texture/atlas/bitmap/source/decorator/shape/EllipseBitmapTextureAtlasSourceDecoratorShape.java @@ -7,9 +7,9 @@ import android.graphics.RectF; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 12:52:55 - 04.01.2011 */ @@ -35,7 +35,7 @@ public EllipseBitmapTextureAtlasSourceDecoratorShape() { } public static EllipseBitmapTextureAtlasSourceDecoratorShape getDefaultInstance() { - if(sDefaultInstance == null) { + if (sDefaultInstance == null) { sDefaultInstance = new EllipseBitmapTextureAtlasSourceDecoratorShape(); } return sDefaultInstance; @@ -57,7 +57,7 @@ public void onDecorateBitmap(final Canvas pCanvas, final Paint pPaint, final Tex final float bottom = pCanvas.getHeight() - pDecoratorOptions.getInsetBottom(); this.mRectF.set(left, top, right, bottom); - + pCanvas.drawOval(this.mRectF, pPaint); } diff --git a/src/org/andengine/opengl/texture/atlas/bitmap/source/decorator/shape/IBitmapTextureAtlasSourceDecoratorShape.java b/src/org/andengine/opengl/texture/atlas/bitmap/source/decorator/shape/IBitmapTextureAtlasSourceDecoratorShape.java index a838878fd..e9fc8d6f7 100644 --- a/src/org/andengine/opengl/texture/atlas/bitmap/source/decorator/shape/IBitmapTextureAtlasSourceDecoratorShape.java +++ b/src/org/andengine/opengl/texture/atlas/bitmap/source/decorator/shape/IBitmapTextureAtlasSourceDecoratorShape.java @@ -6,9 +6,9 @@ import android.graphics.Paint; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 12:47:40 - 04.01.2011 */ diff --git a/src/org/andengine/opengl/texture/atlas/bitmap/source/decorator/shape/RectangleBitmapTextureAtlasSourceDecoratorShape.java b/src/org/andengine/opengl/texture/atlas/bitmap/source/decorator/shape/RectangleBitmapTextureAtlasSourceDecoratorShape.java index 33b993b34..a78becc84 100644 --- a/src/org/andengine/opengl/texture/atlas/bitmap/source/decorator/shape/RectangleBitmapTextureAtlasSourceDecoratorShape.java +++ b/src/org/andengine/opengl/texture/atlas/bitmap/source/decorator/shape/RectangleBitmapTextureAtlasSourceDecoratorShape.java @@ -25,7 +25,7 @@ public RectangleBitmapTextureAtlasSourceDecoratorShape() { } public static RectangleBitmapTextureAtlasSourceDecoratorShape getDefaultInstance() { - if(sDefaultInstance == null) { + if (sDefaultInstance == null) { sDefaultInstance = new RectangleBitmapTextureAtlasSourceDecoratorShape(); } return sDefaultInstance; @@ -45,7 +45,7 @@ public void onDecorateBitmap(final Canvas pCanvas, final Paint pPaint, final Tex final float top = pDecoratorOptions.getInsetTop(); final float right = pCanvas.getWidth() - pDecoratorOptions.getInsetRight(); final float bottom = pCanvas.getHeight() - pDecoratorOptions.getInsetBottom(); - + pCanvas.drawRect(left, top, right, bottom, pPaint); } diff --git a/src/org/andengine/opengl/texture/atlas/bitmap/source/decorator/shape/RoundedRectangleBitmapTextureAtlasSourceDecoratorShape.java b/src/org/andengine/opengl/texture/atlas/bitmap/source/decorator/shape/RoundedRectangleBitmapTextureAtlasSourceDecoratorShape.java index 24134ffe5..56d635f5d 100644 --- a/src/org/andengine/opengl/texture/atlas/bitmap/source/decorator/shape/RoundedRectangleBitmapTextureAtlasSourceDecoratorShape.java +++ b/src/org/andengine/opengl/texture/atlas/bitmap/source/decorator/shape/RoundedRectangleBitmapTextureAtlasSourceDecoratorShape.java @@ -7,9 +7,9 @@ import android.graphics.RectF; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 12:50:09 - 04.01.2011 */ @@ -45,7 +45,7 @@ public RoundedRectangleBitmapTextureAtlasSourceDecoratorShape(final float pCorne } public static RoundedRectangleBitmapTextureAtlasSourceDecoratorShape getDefaultInstance() { - if(sDefaultInstance == null) { + if (sDefaultInstance == null) { sDefaultInstance = new RoundedRectangleBitmapTextureAtlasSourceDecoratorShape(); } return sDefaultInstance; diff --git a/src/org/andengine/opengl/texture/atlas/buildable/BuildableTextureAtlas.java b/src/org/andengine/opengl/texture/atlas/buildable/BuildableTextureAtlas.java index 86ad5ba98..bb2fd0c07 100644 --- a/src/org/andengine/opengl/texture/atlas/buildable/BuildableTextureAtlas.java +++ b/src/org/andengine/opengl/texture/atlas/buildable/BuildableTextureAtlas.java @@ -17,7 +17,7 @@ /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 21:26:38 - 12.08.2010 */ @@ -139,6 +139,11 @@ public TextureOptions getTextureOptions() { return this.mTextureAtlas.getTextureOptions(); } + @Override + public int getTextureMemorySize() { + return this.mTextureAtlas.getTextureMemorySize(); + } + @Override @Deprecated public void addTextureAtlasSource(final S pTextureAtlasSource, final int pTextureX, final int pTextureY) { @@ -184,7 +189,7 @@ public boolean hasTextureAtlasStateListener() { public ITextureAtlasStateListener getTextureStateListener() { return this.mTextureAtlas.getTextureStateListener(); } - + @Override public ITextureAtlasStateListener getTextureAtlasStateListener() { return this.mTextureAtlas.getTextureAtlasStateListener(); @@ -221,9 +226,9 @@ public void addTextureAtlasSource(final S pTextureAtlasSource, final Callback @Override public void removeTextureAtlasSource(final ITextureAtlasSource pTextureAtlasSource) { final ArrayList> textureSources = this.mTextureAtlasSourcesToPlace; - for(int i = textureSources.size() - 1; i >= 0; i--) { + for (int i = textureSources.size() - 1; i >= 0; i--) { final TextureAtlasSourceWithWithLocationCallback textureSource = textureSources.get(i); - if(textureSource.mTextureAtlasSource == pTextureAtlasSource) { + if (textureSource.mTextureAtlasSource == pTextureAtlasSource) { textureSources.remove(i); this.mTextureAtlas.setUpdateOnHardwareNeeded(true); return; diff --git a/src/org/andengine/opengl/texture/atlas/buildable/BuildableTextureAtlasTextureRegionFactory.java b/src/org/andengine/opengl/texture/atlas/buildable/BuildableTextureAtlasTextureRegionFactory.java index 36eb8da3c..8b7773f07 100644 --- a/src/org/andengine/opengl/texture/atlas/buildable/BuildableTextureAtlasTextureRegionFactory.java +++ b/src/org/andengine/opengl/texture/atlas/buildable/BuildableTextureAtlasTextureRegionFactory.java @@ -3,20 +3,19 @@ import org.andengine.opengl.texture.atlas.ITextureAtlas; import org.andengine.opengl.texture.atlas.source.ITextureAtlasSource; -import org.andengine.opengl.texture.region.ITextureRegion; import org.andengine.opengl.texture.region.TextureRegion; import org.andengine.opengl.texture.region.TiledTextureRegion; import org.andengine.util.call.Callback; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 16:42:08 - 12.07.2011 */ -public class BuildableTextureAtlasTextureRegionFactory { +public final class BuildableTextureAtlasTextureRegionFactory { // =========================================================== // Constants // =========================================================== @@ -29,6 +28,10 @@ public class BuildableTextureAtlasTextureRegionFactory { // Constructors // =========================================================== + private BuildableTextureAtlasTextureRegionFactory() { + + } + // =========================================================== // Getter & Setter // =========================================================== @@ -49,7 +52,7 @@ public class BuildableTextureAtlasTextureRegionFactory { // Methods // =========================================================== - public static > ITextureRegion createFromSource(final BuildableTextureAtlas pBuildableTextureAtlas, final T pTextureAtlasSource, final boolean pRotated) { + public static > TextureRegion createFromSource(final BuildableTextureAtlas pBuildableTextureAtlas, final T pTextureAtlasSource, final boolean pRotated) { final TextureRegion textureRegion = new TextureRegion(pBuildableTextureAtlas, 0, 0, pTextureAtlasSource.getTextureWidth(), pTextureAtlasSource.getTextureHeight(), pRotated); pBuildableTextureAtlas.addTextureAtlasSource(pTextureAtlasSource, new Callback() { @Override @@ -67,14 +70,14 @@ public static > TiledT public void onCallback(final T pCallbackValue) { final int tileWidth = pTextureAtlasSource.getTextureWidth() / pTileColumns; final int tileHeight = pTextureAtlasSource.getTextureHeight() / pTileRows; - - for(int tileColumn = 0; tileColumn < pTileColumns; tileColumn++) { - for(int tileRow = 0; tileRow < pTileRows; tileRow++) { + + for (int tileColumn = 0; tileColumn < pTileColumns; tileColumn++) { + for (int tileRow = 0; tileRow < pTileRows; tileRow++) { final int tileIndex = tileRow * pTileColumns + tileColumn; final int x = pCallbackValue.getTextureX() + tileColumn * tileWidth; final int y = pCallbackValue.getTextureY() + tileRow * tileHeight; - + tiledTextureRegion.setTexturePosition(tileIndex, x, y); } } diff --git a/src/org/andengine/opengl/texture/atlas/buildable/IBuildableTextureAtlas.java b/src/org/andengine/opengl/texture/atlas/buildable/IBuildableTextureAtlas.java index de02f9d9e..6c0385299 100644 --- a/src/org/andengine/opengl/texture/atlas/buildable/IBuildableTextureAtlas.java +++ b/src/org/andengine/opengl/texture/atlas/buildable/IBuildableTextureAtlas.java @@ -1,19 +1,18 @@ package org.andengine.opengl.texture.atlas.buildable; import org.andengine.opengl.texture.atlas.ITextureAtlas; -import org.andengine.opengl.texture.atlas.bitmap.BuildableBitmapTextureAtlas; import org.andengine.opengl.texture.atlas.buildable.builder.ITextureAtlasBuilder; import org.andengine.opengl.texture.atlas.buildable.builder.ITextureAtlasBuilder.TextureAtlasBuilderException; import org.andengine.opengl.texture.atlas.source.ITextureAtlasSource; import org.andengine.util.call.Callback; /** - * (c) Zynga 2012 + * (c) 2012 Zynga Inc. * * @author Nicolas Gramlich * @since 15:17:47 - 23.01.2012 */ -public interface IBuildableTextureAtlas> extends ITextureAtlas{ +public interface IBuildableTextureAtlas> extends ITextureAtlas { // =========================================================== // Constants // =========================================================== @@ -24,20 +23,20 @@ public interface IBuildableTextureAtlas pCallback); /** - * Removes a {@link ITextureAtlasSource} before {@link BuildableBitmapTextureAtlas#build(ITextureAtlasBuilder)} is called. + * Removes a {@link ITextureAtlasSource} before {@link #build(ITextureAtlasBuilder)} is called. * @param pBitmapTextureAtlasSource to be removed. */ public void removeTextureAtlasSource(final ITextureAtlasSource pTextureAtlasSource); @@ -53,9 +52,9 @@ public interface IBuildableTextureAtlas build(final ITextureAtlasBuilder pTextureAtlasBuilder) throws TextureAtlasBuilderException; } \ No newline at end of file diff --git a/src/org/andengine/opengl/texture/atlas/buildable/builder/BlackPawnTextureAtlasBuilder.java b/src/org/andengine/opengl/texture/atlas/buildable/builder/BlackPawnTextureAtlasBuilder.java index 8d4df2fd8..ce9c76cb4 100644 --- a/src/org/andengine/opengl/texture/atlas/buildable/builder/BlackPawnTextureAtlasBuilder.java +++ b/src/org/andengine/opengl/texture/atlas/buildable/builder/BlackPawnTextureAtlasBuilder.java @@ -9,13 +9,14 @@ import org.andengine.opengl.texture.atlas.source.ITextureAtlasSource; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @author Jim Scott (BlackPawn) * @since 16:03:01 - 12.08.2010 - * @see http://www.blackpawn.com/texts/lightmaps/default.html + * + * @see blackpawn.com/texts/lightmaps/default.html */ public class BlackPawnTextureAtlasBuilder> implements ITextureAtlasBuilder { // =========================================================== @@ -26,7 +27,7 @@ public class BlackPawnTextureAtlasBuilder pTextureAtlasSourceWithWithLocationCallbackA, final TextureAtlasSourceWithWithLocationCallback pTextureAtlasSourceWithWithLocationCallbackB) { final int deltaWidth = pTextureAtlasSourceWithWithLocationCallbackB.getTextureAtlasSource().getTextureWidth() - pTextureAtlasSourceWithWithLocationCallbackA.getTextureAtlasSource().getTextureWidth(); - if(deltaWidth != 0) { + if (deltaWidth != 0) { return deltaWidth; } else { return pTextureAtlasSourceWithWithLocationCallbackB.getTextureAtlasSource().getTextureHeight() - pTextureAtlasSourceWithWithLocationCallbackA.getTextureAtlasSource().getTextureHeight(); @@ -47,7 +48,7 @@ public int compare(final TextureAtlasSourceWithWithLocationCallback pTextureA // =========================================================== /** - * @param pTextureAtlasBorderSpacing the minimum spacing between the border of the texture and the {@link ITextureAtlasSource}s. + * @param pTextureAtlasBorderSpacing the minimum spacing between the border of the texture and the {@link ITextureAtlasSource}s. * @param pTextureAtlasSourceSpacing the spacing between the different {@link ITextureAtlasSource}s. * @param pTextureAtlasSourcePadding the transparent padding around each {@link ITextureAtlasSource} (prevents texture bleeding). */ @@ -77,19 +78,19 @@ public void build(final A pTextureAtlas, final ArrayList textureSourceWithLocationCallback = pTextureAtlasSourcesWithLocationCallback.get(i); final T textureAtlasSource = textureSourceWithLocationCallback.getTextureAtlasSource(); final Node inserted = root.insert(textureAtlasSource, rootWidth, rootHeight, this.mTextureAtlasSourceSpacing, this.mTextureAtlasSourcePadding); - if(inserted == null) { + if (inserted == null) { throw new TextureAtlasBuilderException("Could not build: '" + textureAtlasSource.toString() + "' into: '" + pTextureAtlas.getClass().getSimpleName() + "'."); } final int textureAtlasSourceLeft = inserted.mRect.mLeft + this.mTextureAtlasBorderSpacing + this.mTextureAtlasSourcePadding; final int textureAtlasSourceTop = inserted.mRect.mTop + this.mTextureAtlasBorderSpacing + this.mTextureAtlasSourcePadding; - if(this.mTextureAtlasSourcePadding == 0) { + if (this.mTextureAtlasSourcePadding == 0) { pTextureAtlas.addTextureAtlasSource(textureAtlasSource, textureAtlasSourceLeft, textureAtlasSourceTop); } else { pTextureAtlas.addTextureAtlasSource(textureAtlasSource, textureAtlasSourceLeft, textureAtlasSourceTop, this.mTextureAtlasSourcePadding); @@ -229,15 +230,15 @@ public Node getChildB() { // =========================================================== public Node insert(final ITextureAtlasSource pTextureAtlasSource, final int pTextureWidth, final int pTextureHeight, final int pTextureAtlasSourceSpacing, final int pTextureAtlasSourcePadding) throws IllegalArgumentException { - if(this.mChildA != null && this.mChildB != null) { + if (this.mChildA != null && this.mChildB != null) { final Node newNode = this.mChildA.insert(pTextureAtlasSource, pTextureWidth, pTextureHeight, pTextureAtlasSourceSpacing, pTextureAtlasSourcePadding); - if(newNode != null){ + if (newNode != null) { return newNode; } else { return this.mChildB.insert(pTextureAtlasSource, pTextureWidth, pTextureHeight, pTextureAtlasSourceSpacing, pTextureAtlasSourcePadding); } } else { - if(this.mTextureAtlasSource != null) { + if (this.mTextureAtlasSource != null) { return null; } @@ -247,7 +248,7 @@ public Node insert(final ITextureAtlasSource pTextureAtlasSource, final int pTex final int rectWidth = this.mRect.getWidth(); final int rectHeight = this.mRect.getHeight(); - if(textureSourceWidth > rectWidth || textureSourceHeight > rectHeight) { + if (textureSourceWidth > rectWidth || textureSourceHeight > rectHeight) { return null; } @@ -260,40 +261,40 @@ public Node insert(final ITextureAtlasSource pTextureAtlasSource, final int pTex final boolean fitToBottomWithoutSpacing = textureSourceHeight == rectHeight && rectTop + textureSourceHeight == pTextureHeight; final boolean fitToRightWithoutSpacing = textureSourceWidth == rectWidth && rectLeft + textureSourceWidth == pTextureWidth; - if(textureSourceWidthWithSpacing == rectWidth){ - if(textureSourceHeightWithSpacing == rectHeight) { /* Normal case with padding. */ + if (textureSourceWidthWithSpacing == rectWidth) { + if (textureSourceHeightWithSpacing == rectHeight) { /* Normal case with padding. */ this.mTextureAtlasSource = pTextureAtlasSource; return this; - } else if(fitToBottomWithoutSpacing) { /* Bottom edge of the BitmapTexture. */ + } else if (fitToBottomWithoutSpacing) { /* Bottom edge of the BitmapTexture. */ this.mTextureAtlasSource = pTextureAtlasSource; return this; } } - if(fitToRightWithoutSpacing) { /* Right edge of the BitmapTexture. */ - if(textureSourceHeightWithSpacing == rectHeight) { + if (fitToRightWithoutSpacing) { /* Right edge of the BitmapTexture. */ + if (textureSourceHeightWithSpacing == rectHeight) { this.mTextureAtlasSource = pTextureAtlasSource; return this; - } else if(fitToBottomWithoutSpacing) { /* Bottom edge of the BitmapTexture. */ + } else if (fitToBottomWithoutSpacing) { /* Bottom edge of the BitmapTexture. */ this.mTextureAtlasSource = pTextureAtlasSource; return this; - } else if(textureSourceHeightWithSpacing > rectHeight) { + } else if (textureSourceHeightWithSpacing > rectHeight) { return null; } else { return this.createChildren(pTextureAtlasSource, pTextureWidth, pTextureHeight, pTextureAtlasSourceSpacing, pTextureAtlasSourcePadding, rectWidth - textureSourceWidth, rectHeight - textureSourceHeightWithSpacing); } } - if(fitToBottomWithoutSpacing) { - if(textureSourceWidthWithSpacing == rectWidth) { + if (fitToBottomWithoutSpacing) { + if (textureSourceWidthWithSpacing == rectWidth) { this.mTextureAtlasSource = pTextureAtlasSource; return this; - } else if(textureSourceWidthWithSpacing > rectWidth) { + } else if (textureSourceWidthWithSpacing > rectWidth) { return null; } else { return this.createChildren(pTextureAtlasSource, pTextureWidth, pTextureHeight, pTextureAtlasSourceSpacing, pTextureAtlasSourcePadding, rectWidth - textureSourceWidthWithSpacing, rectHeight - textureSourceHeight); } - } else if(textureSourceWidthWithSpacing > rectWidth || textureSourceHeightWithSpacing > rectHeight) { + } else if (textureSourceWidthWithSpacing > rectWidth || textureSourceHeightWithSpacing > rectHeight) { return null; } else { return this.createChildren(pTextureAtlasSource, pTextureWidth, pTextureHeight, pTextureAtlasSourceSpacing, pTextureAtlasSourcePadding, rectWidth - textureSourceWidthWithSpacing, rectHeight - textureSourceHeightWithSpacing); @@ -304,7 +305,7 @@ public Node insert(final ITextureAtlasSource pTextureAtlasSource, final int pTex private Node createChildren(final ITextureAtlasSource pTextureAtlasSource, final int pTextureWidth, final int pTextureHeight, final int pTextureAtlasSourceSpacing, final int pTextureAtlasSourcePadding, final int pDeltaWidth, final int pDeltaHeight) { final Rect rect = this.mRect; - if(pDeltaWidth >= pDeltaHeight) { + if (pDeltaWidth >= pDeltaHeight) { /* Split using a vertical axis. */ this.mChildA = new Node( rect.getLeft(), diff --git a/src/org/andengine/opengl/texture/atlas/buildable/builder/ITextureAtlasBuilder.java b/src/org/andengine/opengl/texture/atlas/buildable/builder/ITextureAtlasBuilder.java index d9c5af3a2..6af984213 100644 --- a/src/org/andengine/opengl/texture/atlas/buildable/builder/ITextureAtlasBuilder.java +++ b/src/org/andengine/opengl/texture/atlas/buildable/builder/ITextureAtlasBuilder.java @@ -5,11 +5,12 @@ import org.andengine.opengl.texture.atlas.ITextureAtlas; import org.andengine.opengl.texture.atlas.buildable.BuildableTextureAtlas.TextureAtlasSourceWithWithLocationCallback; import org.andengine.opengl.texture.atlas.source.ITextureAtlasSource; +import org.andengine.util.exception.AndEngineException; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 15:59:14 - 12.08.2010 */ @@ -28,7 +29,7 @@ public interface ITextureAtlasBuilder * @since 10:45:48 - 02.03.2012 diff --git a/src/org/andengine/opengl/texture/bitmap/BitmapTexture.java b/src/org/andengine/opengl/texture/bitmap/BitmapTexture.java index 86f935e13..588c49334 100644 --- a/src/org/andengine/opengl/texture/bitmap/BitmapTexture.java +++ b/src/org/andengine/opengl/texture/bitmap/BitmapTexture.java @@ -21,7 +21,7 @@ import android.opengl.GLUtils; /** - * (c) Zynga 2011 + * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 16:16:25 - 30.07.2011 @@ -103,24 +103,24 @@ protected void writeTextureToHardware(final GLState pGLState) throws IOException final Config bitmapConfig = this.mBitmapTextureFormat.getBitmapConfig(); final Bitmap bitmap = this.onGetBitmap(bitmapConfig); - if(bitmap == null) { + if (bitmap == null) { throw new NullBitmapException("Caused by: '" + this.toString() + "'."); } final boolean useDefaultAlignment = MathUtils.isPowerOfTwo(bitmap.getWidth()) && MathUtils.isPowerOfTwo(bitmap.getHeight()) && (this.mPixelFormat == PixelFormat.RGBA_8888); - if(!useDefaultAlignment) { + if (!useDefaultAlignment) { /* Adjust unpack alignment. */ GLES20.glPixelStorei(GLES20.GL_UNPACK_ALIGNMENT, 1); } final boolean preMultipyAlpha = this.mTextureOptions.mPreMultiplyAlpha; - if(preMultipyAlpha) { + if (preMultipyAlpha) { GLUtils.texImage2D(GLES20.GL_TEXTURE_2D, 0, bitmap, 0); } else { pGLState.glTexImage2D(GLES20.GL_TEXTURE_2D, 0, bitmap, 0, this.mPixelFormat); } - if(!useDefaultAlignment) { + if (!useDefaultAlignment) { /* Restore default unpack alignment. */ GLES20.glPixelStorei(GLES20.GL_UNPACK_ALIGNMENT, GLState.GL_UNPACK_ALIGNMENT_DEFAULT); } @@ -135,6 +135,7 @@ protected void writeTextureToHardware(final GLState pGLState) throws IOException protected Bitmap onGetBitmap(final Config pBitmapConfig) throws IOException { final BitmapFactory.Options decodeOptions = new BitmapFactory.Options(); decodeOptions.inPreferredConfig = pBitmapConfig; + decodeOptions.inDither = false; return BitmapFactory.decodeStream(this.mInputStreamOpener.open(), null, decodeOptions); } diff --git a/src/org/andengine/opengl/texture/bitmap/BitmapTextureFormat.java b/src/org/andengine/opengl/texture/bitmap/BitmapTextureFormat.java index 49ad3d4ab..dd9e88797 100644 --- a/src/org/andengine/opengl/texture/bitmap/BitmapTextureFormat.java +++ b/src/org/andengine/opengl/texture/bitmap/BitmapTextureFormat.java @@ -5,7 +5,7 @@ import android.graphics.Bitmap.Config; /** - * (c) Zynga 2012 + * (c) 2012 Zynga Inc. * * @author Nicolas Gramlich * @since 11:36:45 - 05.04.2012 @@ -41,7 +41,7 @@ private BitmapTextureFormat(final Config pBitmapConfig, final PixelFormat pPixel } public static BitmapTextureFormat fromPixelFormat(final PixelFormat pPixelFormat) { - switch(pPixelFormat) { + switch (pPixelFormat) { case RGBA_8888: return RGBA_8888; case RGBA_4444: diff --git a/src/org/andengine/opengl/texture/bitmap/ResourceBitmapTexture.java b/src/org/andengine/opengl/texture/bitmap/ResourceBitmapTexture.java index af2e6424e..1a639f3bd 100644 --- a/src/org/andengine/opengl/texture/bitmap/ResourceBitmapTexture.java +++ b/src/org/andengine/opengl/texture/bitmap/ResourceBitmapTexture.java @@ -10,7 +10,7 @@ import android.content.res.Resources; /** - * (c) Zynga 2012 + * (c) 2012 Zynga Inc. * * @author Nicolas Gramlich * @since 12:10:08 - 02.03.2012 diff --git a/src/org/andengine/opengl/texture/compressed/etc1/ETC1Texture.java b/src/org/andengine/opengl/texture/compressed/etc1/ETC1Texture.java index 99b1b0b39..a40d7cce2 100644 --- a/src/org/andengine/opengl/texture/compressed/etc1/ETC1Texture.java +++ b/src/org/andengine/opengl/texture/compressed/etc1/ETC1Texture.java @@ -5,20 +5,23 @@ import java.nio.ByteBuffer; import java.nio.ByteOrder; +import org.andengine.BuildConfig; import org.andengine.opengl.texture.ITextureStateListener; import org.andengine.opengl.texture.PixelFormat; import org.andengine.opengl.texture.Texture; import org.andengine.opengl.texture.TextureManager; import org.andengine.opengl.texture.TextureOptions; import org.andengine.opengl.util.GLState; +import org.andengine.util.debug.Debug; import org.andengine.util.StreamUtils; +import org.andengine.util.math.MathUtils; import android.opengl.ETC1; import android.opengl.ETC1Util; import android.opengl.GLES20; /** - * TODO if(!SystemUtils.isAndroidVersionOrHigher(Build.VERSION_CODES.FROYO)) --> Meaningful Exception! + * TODO if (!SystemUtils.isAndroidVersionOrHigher(Build.VERSION_CODES.FROYO)) --> Meaningful Exception! * * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. @@ -61,6 +64,12 @@ public ETC1Texture(final TextureManager pTextureManager, final TextureOptions pT inputStream = this.getInputStream(); this.mETC1TextureHeader = new ETC1TextureHeader(StreamUtils.streamToBytes(inputStream, ETC1.ETC_PKM_HEADER_SIZE)); + + if (BuildConfig.DEBUG) { + if (!(MathUtils.isPowerOfTwo(this.mETC1TextureHeader.mWidth) && MathUtils.isPowerOfTwo(this.mETC1TextureHeader.mHeight))) { + Debug.w("ETC1 textures with NPOT sizes can cause a crash on PowerVR GPUs!"); + } + } } finally { StreamUtils.close(inputStream); } @@ -119,7 +128,7 @@ public static class ETC1TextureHeader { // =========================================================== public ETC1TextureHeader(final byte[] pData) { - if(pData.length != ETC1.ETC_PKM_HEADER_SIZE) { + if (pData.length != ETC1.ETC_PKM_HEADER_SIZE) { throw new IllegalArgumentException("Invalid " + this.getClass().getSimpleName() + "!"); } diff --git a/src/org/andengine/opengl/texture/compressed/pvr/PVRCCZTexture.java b/src/org/andengine/opengl/texture/compressed/pvr/PVRCCZTexture.java index bb91df0de..b9ddaaaaf 100644 --- a/src/org/andengine/opengl/texture/compressed/pvr/PVRCCZTexture.java +++ b/src/org/andengine/opengl/texture/compressed/pvr/PVRCCZTexture.java @@ -137,7 +137,7 @@ public CCZHeader(final byte[] pData) { this.mDataByteBuffer.order(ByteOrder.BIG_ENDIAN); /* Check magic bytes. */ - if(!ArrayUtils.equals(pData, 0, CCZHeader.MAGIC_IDENTIFIER, 0, CCZHeader.MAGIC_IDENTIFIER.length)) { + if (!ArrayUtils.equals(pData, 0, CCZHeader.MAGIC_IDENTIFIER, 0, CCZHeader.MAGIC_IDENTIFIER.length)) { throw new IllegalArgumentException("Invalid " + this.getClass().getSimpleName() + "!"); } @@ -212,7 +212,7 @@ private CCZCompressionFormat(final short pID) { } public InflaterInputStream wrap(final InputStream pInputStream) throws IOException { - switch(this) { + switch (this) { case GZIP: return new GZIPInputStream(pInputStream); case ZLIB: @@ -227,9 +227,9 @@ public InflaterInputStream wrap(final InputStream pInputStream) throws IOExcepti public static CCZCompressionFormat fromID(final short pID) { final CCZCompressionFormat[] cczCompressionFormats = CCZCompressionFormat.values(); final int cczCompressionFormatCount = cczCompressionFormats.length; - for(int i = 0; i < cczCompressionFormatCount; i++) { + for (int i = 0; i < cczCompressionFormatCount; i++) { final CCZCompressionFormat cczCompressionFormat = cczCompressionFormats[i]; - if(cczCompressionFormat.mID == pID) { + if (cczCompressionFormat.mID == pID) { return cczCompressionFormat; } } diff --git a/src/org/andengine/opengl/texture/compressed/pvr/PVRTexture.java b/src/org/andengine/opengl/texture/compressed/pvr/PVRTexture.java index d37274ee5..851f708de 100644 --- a/src/org/andengine/opengl/texture/compressed/pvr/PVRTexture.java +++ b/src/org/andengine/opengl/texture/compressed/pvr/PVRTexture.java @@ -16,8 +16,8 @@ import org.andengine.opengl.texture.compressed.pvr.pixelbufferstrategy.IPVRTexturePixelBufferStrategy.IPVRTexturePixelBufferStrategyBufferManager; import org.andengine.opengl.util.GLState; import org.andengine.util.StreamUtils; -import org.andengine.util.adt.DataConstants; import org.andengine.util.adt.array.ArrayUtils; +import org.andengine.util.adt.data.constants.DataConstants; import org.andengine.util.adt.io.out.ByteBufferOutputStream; import org.andengine.util.debug.Debug; import org.andengine.util.math.MathUtils; @@ -97,23 +97,23 @@ public PVRTexture(final TextureManager pTextureManager, final PVRTextureFormat p StreamUtils.close(inputStream); } - if(this.mPVRTextureHeader.getPVRTextureFormat().getPixelFormat() != pPVRTextureFormat.getPixelFormat()) { + if (this.mPVRTextureHeader.getPVRTextureFormat().getPixelFormat() != pPVRTextureFormat.getPixelFormat()) { throw new IllegalArgumentException("Other PVRTextureFormat: '" + this.mPVRTextureHeader.getPVRTextureFormat().getPixelFormat() + "' found than expected: '" + pPVRTextureFormat.getPixelFormat() + "'."); } - if(this.mPVRTextureHeader.getPVRTextureFormat().isCompressed()) { // TODO && ! GLHELPER_EXTENSION_PVRTC] ) { + if (this.mPVRTextureHeader.getPVRTextureFormat().isCompressed()) { // TODO && ! GLHELPER_EXTENSION_PVRTC] ) { throw new IllegalArgumentException("Invalid PVRTextureFormat: '" + this.mPVRTextureHeader.getPVRTextureFormat() + "'."); } - if(this.hasMipMaps()) { - switch(pTextureOptions.mMinFilter){ + if (this.hasMipMaps()) { + switch (pTextureOptions.mMinFilter) { case GLES20.GL_NEAREST_MIPMAP_NEAREST: case GLES20.GL_NEAREST_MIPMAP_LINEAR: case GLES20.GL_LINEAR_MIPMAP_NEAREST: case GLES20.GL_LINEAR_MIPMAP_LINEAR: break; default: - if(BuildConfig.DEBUG) { + if (BuildConfig.DEBUG) { Debug.w("This '" + this.getClass().getSimpleName() + "' contains mipmaps, but the provided '" + pTextureOptions.getClass().getSimpleName() + "' don't have MipMaps enabled on the MinFilter!"); } } @@ -244,7 +244,7 @@ public PVRTextureHeader(final byte[] pData) { this.mDataByteBuffer.order(ByteOrder.LITTLE_ENDIAN); /* Check magic bytes. */ - if(!ArrayUtils.equals(pData, 11 * DataConstants.BYTES_PER_INT, PVRTextureHeader.MAGIC_IDENTIFIER, 0, PVRTextureHeader.MAGIC_IDENTIFIER.length)) { + if (!ArrayUtils.equals(pData, 11 * DataConstants.BYTES_PER_INT, PVRTextureHeader.MAGIC_IDENTIFIER, 0, PVRTextureHeader.MAGIC_IDENTIFIER.length)) { throw new IllegalArgumentException("Invalid " + this.getClass().getSimpleName() + "!"); } @@ -371,9 +371,9 @@ private PVRTextureFormat(final int pID, final boolean pCompressed, final PixelFo public static PVRTextureFormat fromID(final int pID) { final PVRTextureFormat[] pvrTextureFormats = PVRTextureFormat.values(); final int pvrTextureFormatCount = pvrTextureFormats.length; - for(int i = 0; i < pvrTextureFormatCount; i++) { + for (int i = 0; i < pvrTextureFormatCount; i++) { final PVRTextureFormat pvrTextureFormat = pvrTextureFormats[i]; - if(pvrTextureFormat.mID == pID) { + if (pvrTextureFormat.mID == pID) { return pvrTextureFormat; } } @@ -381,7 +381,7 @@ public static PVRTextureFormat fromID(final int pID) { } public static PVRTextureFormat fromPixelFormat(final PixelFormat pPixelFormat) throws IllegalArgumentException { - switch(pPixelFormat) { + switch (pPixelFormat) { case RGBA_8888: return PVRTextureFormat.RGBA_8888; case RGBA_4444: diff --git a/src/org/andengine/opengl/texture/compressed/pvr/pixelbufferstrategy/GreedyPVRTexturePixelBufferStrategy.java b/src/org/andengine/opengl/texture/compressed/pvr/pixelbufferstrategy/GreedyPVRTexturePixelBufferStrategy.java index 8162694ce..deee6100c 100644 --- a/src/org/andengine/opengl/texture/compressed/pvr/pixelbufferstrategy/GreedyPVRTexturePixelBufferStrategy.java +++ b/src/org/andengine/opengl/texture/compressed/pvr/pixelbufferstrategy/GreedyPVRTexturePixelBufferStrategy.java @@ -11,7 +11,7 @@ import android.opengl.GLES20; /** - * (c) Zynga 2011 + * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 11:26:07 - 27.09.2011 diff --git a/src/org/andengine/opengl/texture/compressed/pvr/pixelbufferstrategy/IPVRTexturePixelBufferStrategy.java b/src/org/andengine/opengl/texture/compressed/pvr/pixelbufferstrategy/IPVRTexturePixelBufferStrategy.java index ca6375e3f..564974b02 100644 --- a/src/org/andengine/opengl/texture/compressed/pvr/pixelbufferstrategy/IPVRTexturePixelBufferStrategy.java +++ b/src/org/andengine/opengl/texture/compressed/pvr/pixelbufferstrategy/IPVRTexturePixelBufferStrategy.java @@ -7,7 +7,7 @@ import org.andengine.opengl.texture.compressed.pvr.PVRTexture; /** - * (c) Zynga 2011 + * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 11:26:07 - 27.09.2011 diff --git a/src/org/andengine/opengl/texture/compressed/pvr/pixelbufferstrategy/SmartPVRTexturePixelBufferStrategy.java b/src/org/andengine/opengl/texture/compressed/pvr/pixelbufferstrategy/SmartPVRTexturePixelBufferStrategy.java index bb3b1989d..476b3a132 100644 --- a/src/org/andengine/opengl/texture/compressed/pvr/pixelbufferstrategy/SmartPVRTexturePixelBufferStrategy.java +++ b/src/org/andengine/opengl/texture/compressed/pvr/pixelbufferstrategy/SmartPVRTexturePixelBufferStrategy.java @@ -14,7 +14,7 @@ import android.opengl.GLES20; /** - * (c) Zynga 2011 + * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 11:26:07 - 27.09.2011 @@ -65,7 +65,7 @@ public void loadPVRTextureData(final IPVRTexturePixelBufferStrategyBufferManager /* Load stripes. */ int currentStripePixelDataOffset = pCurrentPixelDataOffset; int currentStripeOffsetY = 0; - while(currentStripeOffsetY < pHeight) { + while (currentStripeOffsetY < pHeight) { final int currentStripeHeight = Math.min(pHeight - currentStripeOffsetY, stripeHeight); final int currentStripePixelDataSize = currentStripeHeight * bytesPerRow; @@ -120,23 +120,23 @@ public SmartPVRTexturePixelBufferStrategyBufferManager(final PVRTexture pPVRText @Override public ByteBuffer getPixelBuffer(final int pStart, final int pByteCount) throws IOException { - if(pStart < this.mInputStreamPosition) { + if (pStart < this.mInputStreamPosition) { throw new AndEngineRuntimeException("Cannot read data that has been read already. (pStart: '" + pStart + "', this.mInputStreamPosition: '" + this.mInputStreamPosition + "')"); } /* Ensure data buffer is bug enough. */ - if(this.mData == null || this.mData.length < pByteCount) { + if (this.mData == null || this.mData.length < pByteCount) { this.mData = new byte[pByteCount]; } /* If needed, skip bytes up to where the data was requested. */ - if(this.mInputStreamPosition < pStart) { + if (this.mInputStreamPosition < pStart) { final int bytesToSkip = pStart - this.mInputStreamPosition; final long skipped = this.mInputStream.skip(bytesToSkip); this.mInputStreamPosition += skipped; - if(bytesToSkip != skipped) { + if (bytesToSkip != skipped) { throw new AndEngineRuntimeException("Skipped: '" + skipped + "' instead of '" + bytesToSkip + "'."); } } diff --git a/src/org/andengine/opengl/texture/region/BaseTextureRegion.java b/src/org/andengine/opengl/texture/region/BaseTextureRegion.java index 56357362a..62dca82a6 100644 --- a/src/org/andengine/opengl/texture/region/BaseTextureRegion.java +++ b/src/org/andengine/opengl/texture/region/BaseTextureRegion.java @@ -5,7 +5,7 @@ /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 14:29:59 - 08.03.2010 */ @@ -27,7 +27,7 @@ public abstract class BaseTextureRegion implements ITextureRegion { public BaseTextureRegion(final ITexture pTexture) { this.mTexture = pTexture; } - + @Override public abstract ITextureRegion deepCopy(); diff --git a/src/org/andengine/opengl/texture/region/ITextureRegion.java b/src/org/andengine/opengl/texture/region/ITextureRegion.java index ceb38c2f0..2e0775f92 100644 --- a/src/org/andengine/opengl/texture/region/ITextureRegion.java +++ b/src/org/andengine/opengl/texture/region/ITextureRegion.java @@ -1,9 +1,10 @@ package org.andengine.opengl.texture.region; import org.andengine.opengl.texture.ITexture; +import org.andengine.util.modifier.IModifier.DeepCopyNotSupportedException; /** - * (c) Zynga 2011 + * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 20:07:17 - 07.08.2011 @@ -25,11 +26,11 @@ public interface ITextureRegion { public void setTexturePosition(final float pTextureX, final float pTextureY); /** - * Note: Takes {@link ITextureRegion#getScale()} into account! + * Note: Takes {@link #getScale()} into account! */ public float getWidth(); /** - * Note: Takes {@link ITextureRegion#getScale()} into account! + * Note: Takes {@link #getScale()} into account! */ public float getHeight(); @@ -50,5 +51,5 @@ public interface ITextureRegion { public ITexture getTexture(); - public ITextureRegion deepCopy(); + public ITextureRegion deepCopy() throws DeepCopyNotSupportedException; } \ No newline at end of file diff --git a/src/org/andengine/opengl/texture/region/ITiledTextureRegion.java b/src/org/andengine/opengl/texture/region/ITiledTextureRegion.java index f7577da37..15e39e50f 100644 --- a/src/org/andengine/opengl/texture/region/ITiledTextureRegion.java +++ b/src/org/andengine/opengl/texture/region/ITiledTextureRegion.java @@ -1,7 +1,7 @@ package org.andengine.opengl.texture.region; /** - * (c) Zynga 2011 + * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 23:31:52 - 08.08.2011 @@ -29,11 +29,11 @@ public interface ITiledTextureRegion extends ITextureRegion { public void setTexturePosition(final int pTileIndex, final float pTextureX, final float pTextureY); /** - * Note: Takes {@link ITiledTextureRegion#getScale(int)} into account! + * Note: Takes {@link #getScale(int)} into account! */ public float getWidth(final int pTileIndex); /** - * Note: Takes {@link ITiledTextureRegion#getScale(int)} into account! + * Note: Takes {@link #getScale(int)} into account! */ public float getHeight(final int pTileIndex); diff --git a/src/org/andengine/opengl/texture/region/TextureRegion.java b/src/org/andengine/opengl/texture/region/TextureRegion.java index 90e59fe3d..203a54383 100644 --- a/src/org/andengine/opengl/texture/region/TextureRegion.java +++ b/src/org/andengine/opengl/texture/region/TextureRegion.java @@ -5,7 +5,7 @@ /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 14:29:59 - 08.03.2010 */ @@ -55,14 +55,11 @@ public TextureRegion(final ITexture pTexture, final float pTextureX, final float this.mTextureX = pTextureX; this.mTextureY = pTextureY; - if(pRotated) { - this.mRotated = true; - + this.mRotated = pRotated; + if (this.mRotated) { this.mTextureWidth = pTextureHeight; this.mTextureHeight = pTextureWidth; } else { - this.mRotated = false; - this.mTextureWidth = pTextureWidth; this.mTextureHeight = pTextureHeight; } @@ -74,7 +71,7 @@ public TextureRegion(final ITexture pTexture, final float pTextureX, final float @Override public TextureRegion deepCopy() { - if(this.mRotated) { + if (this.mRotated) { return new TextureRegion(this.mTexture, this.mTextureX, this.mTextureY, this.mTextureHeight, this.mTextureWidth, this.mScale, this.mRotated); } else { return new TextureRegion(this.mTexture, this.mTextureX, this.mTextureY, this.mTextureWidth, this.mTextureHeight, this.mScale, this.mRotated); @@ -119,7 +116,7 @@ public void setTexturePosition(final float pTextureX, final float pTextureY) { @Override public float getWidth() { - if(this.mRotated) { + if (this.mRotated) { return this.mTextureHeight * this.mScale; } else { return this.mTextureWidth * this.mScale; @@ -128,7 +125,7 @@ public float getWidth() { @Override public float getHeight() { - if(this.mRotated) { + if (this.mRotated) { return this.mTextureWidth * this.mScale; } else { return this.mTextureHeight * this.mScale; diff --git a/src/org/andengine/opengl/texture/region/TextureRegionFactory.java b/src/org/andengine/opengl/texture/region/TextureRegionFactory.java index 1a222f94d..68069d798 100644 --- a/src/org/andengine/opengl/texture/region/TextureRegionFactory.java +++ b/src/org/andengine/opengl/texture/region/TextureRegionFactory.java @@ -9,11 +9,11 @@ /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 18:15:14 - 09.03.2010 */ -public class TextureRegionFactory { +public final class TextureRegionFactory { // =========================================================== // Constants // =========================================================== @@ -26,6 +26,10 @@ public class TextureRegionFactory { // Constructors // =========================================================== + private TextureRegionFactory() { + + } + // =========================================================== // Getter & Setter // =========================================================== @@ -37,28 +41,36 @@ public class TextureRegionFactory { // =========================================================== // Methods // =========================================================== - - public static ITextureRegion extractFromTexture(final ITexture pTexture) { + + public static TextureRegion extractFromTexture(final ITexture pTexture) { return TextureRegionFactory.extractFromTexture(pTexture, false); } - public static ITextureRegion extractFromTexture(final ITexture pTexture, final int pTextureX, final int pTextureY, final int pWidth, final int pHeight) { + public static TextureRegion extractFromTexture(final ITexture pTexture, final int pTextureX, final int pTextureY, final int pWidth, final int pHeight) { return TextureRegionFactory.extractFromTexture(pTexture, pTextureX, pTextureY, pWidth, pHeight, false); } - public static ITextureRegion extractFromTexture(final ITexture pTexture, final boolean pRotated) { + public static TextureRegion extractFromTexture(final ITexture pTexture, final boolean pRotated) { return new TextureRegion(pTexture, 0, 0, pTexture.getWidth(), pTexture.getHeight(), pRotated); } - public static ITextureRegion extractFromTexture(final ITexture pTexture, final int pTextureX, final int pTextureY, final int pWidth, final int pHeight, final boolean pRotated) { + public static TextureRegion extractFromTexture(final ITexture pTexture, final int pTextureX, final int pTextureY, final int pWidth, final int pHeight, final boolean pRotated) { return new TextureRegion(pTexture, pTextureX, pTextureY, pWidth, pHeight, pRotated); } - public static ITextureRegion createFromSource(final ITextureAtlas pTextureAtlas, final T pTextureAtlasSource, final int pTextureX, final int pTextureY) { + public static TiledTextureRegion extractTiledFromTexture(final ITexture pTexture, final int pTileColumns, final int pTileRows) { + return TiledTextureRegion.create(pTexture, 0, 0, pTexture.getWidth(), pTexture.getHeight(), pTileColumns, pTileRows); + } + + public static TiledTextureRegion extractTiledFromTexture(final ITexture pTexture, final int pTextureX, final int pTextureY, final int pWidth, final int pHeight, final int pTileColumns, final int pTileRows) { + return TiledTextureRegion.create(pTexture, pTextureX, pTextureY, pWidth, pHeight, pTileColumns, pTileRows); + } + + public static TextureRegion createFromSource(final ITextureAtlas pTextureAtlas, final T pTextureAtlasSource, final int pTextureX, final int pTextureY) { return TextureRegionFactory.createFromSource(pTextureAtlas, pTextureAtlasSource, pTextureX, pTextureY, false); } - public static ITextureRegion createFromSource(final ITextureAtlas pTextureAtlas, final T pTextureAtlasSource, final int pTextureX, final int pTextureY, final boolean pRotated) { + public static TextureRegion createFromSource(final ITextureAtlas pTextureAtlas, final T pTextureAtlasSource, final int pTextureX, final int pTextureY, final boolean pRotated) { final TextureRegion textureRegion = new TextureRegion(pTextureAtlas, pTextureX, pTextureY, pTextureAtlasSource.getTextureWidth(), pTextureAtlasSource.getTextureHeight(), pRotated); pTextureAtlas.addTextureAtlasSource(pTextureAtlasSource, pTextureX, pTextureY); return textureRegion; diff --git a/src/org/andengine/opengl/texture/region/TextureRegionLibrary.java b/src/org/andengine/opengl/texture/region/TextureRegionLibrary.java index e45eb88ba..70f6fd52a 100644 --- a/src/org/andengine/opengl/texture/region/TextureRegionLibrary.java +++ b/src/org/andengine/opengl/texture/region/TextureRegionLibrary.java @@ -5,7 +5,7 @@ /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 11:52:26 - 20.08.2010 */ diff --git a/src/org/andengine/opengl/texture/region/TiledTextureRegion.java b/src/org/andengine/opengl/texture/region/TiledTextureRegion.java index bb0d05e76..7c4d564c9 100644 --- a/src/org/andengine/opengl/texture/region/TiledTextureRegion.java +++ b/src/org/andengine/opengl/texture/region/TiledTextureRegion.java @@ -6,7 +6,7 @@ /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 18:14:42 - 09.03.2010 */ @@ -42,9 +42,9 @@ public TiledTextureRegion(final ITexture pTexture, final boolean pPerformSameTex this.mTextureRegions = pTextureRegions; this.mTileCount = this.mTextureRegions.length; - if(pPerformSameTextureSanityCheck) { - for(int i = this.mTileCount - 1; i >= 0; i--) { - if(pTextureRegions[i].getTexture() != pTexture) { + if (pPerformSameTextureSanityCheck) { + for (int i = this.mTileCount - 1; i >= 0; i--) { + if (pTextureRegions[i].getTexture() != pTexture) { throw new IllegalArgumentException("The " + ITextureRegion.class.getSimpleName() + ": '" + pTextureRegions[i].toString() + "' at index: '" + i + "' is not on the same " + ITexture.class.getSimpleName() + ": '" + pTextureRegions[i].getTexture().toString() + "' as the supplied " + ITexture.class.getSimpleName() + ": '" + pTexture.toString() + "'."); } } @@ -61,8 +61,8 @@ public static TiledTextureRegion create(final ITexture pTexture, final int pText final int tileWidth = pTextureWidth / pTileColumns; final int tileHeight = pTextureHeight / pTileRows; - for(int tileColumn = 0; tileColumn < pTileColumns; tileColumn++) { - for(int tileRow = 0; tileRow < pTileRows; tileRow++) { + for (int tileColumn = 0; tileColumn < pTileColumns; tileColumn++) { + for (int tileRow = 0; tileRow < pTileRows; tileRow++) { final int tileIndex = tileRow * pTileColumns + tileColumn; final int x = pTextureX + tileColumn * tileWidth; @@ -80,7 +80,7 @@ public TiledTextureRegion deepCopy() { final ITextureRegion[] textureRegions = new ITextureRegion[tileCount]; - for(int i = 0; i < tileCount; i++) { + for (int i = 0; i < tileCount; i++) { textureRegions[i] = this.mTextureRegions[i].deepCopy(); } @@ -104,7 +104,7 @@ public void setCurrentTileIndex(final int pCurrentTileIndex) { @Override public void nextTile() { this.mCurrentTileIndex++; - if(this.mCurrentTileIndex >= this.mTileCount) { + if (this.mCurrentTileIndex >= this.mTileCount) { this.mCurrentTileIndex = this.mCurrentTileIndex % this.mTileCount; } } @@ -146,7 +146,7 @@ public void setTextureX(final float pTextureX) { @Override public void setTextureX(final int pTileIndex, final float pTextureX) { - this.mTextureRegions[pTileIndex].setTextureY(pTextureX); + this.mTextureRegions[pTileIndex].setTextureX(pTextureX); } @Override diff --git a/src/org/andengine/opengl/texture/render/RenderTexture.java b/src/org/andengine/opengl/texture/render/RenderTexture.java index e02ff85cf..f7dd8fd4e 100644 --- a/src/org/andengine/opengl/texture/render/RenderTexture.java +++ b/src/org/andengine/opengl/texture/render/RenderTexture.java @@ -13,16 +13,16 @@ import org.andengine.opengl.texture.TextureOptions; import org.andengine.opengl.util.GLHelper; import org.andengine.opengl.util.GLState; -import org.andengine.util.color.Color; +import org.andengine.util.adt.color.Color; import android.graphics.Bitmap; import android.graphics.Bitmap.Config; import android.opengl.GLES20; /** - * The general workflow with a {@link RenderTexture} is: {@link RenderTexture#init(GLState)} -> {@link RenderTexture#begin(GLState)} -> {@link RenderTexture#end(GLState)} -> {@link RenderTexture#destroy(GLState)}. + * The general workflow with a {@link RenderTexture} is: {@link #init(GLState)} -> {@link #begin(GLState)} -> {@link #end(GLState)} -> {@link #destroy(GLState)}. * - * (c) Zynga 2011 + * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 07:13:05 - 24.08.2011 @@ -124,7 +124,7 @@ protected void writeTextureToHardware(final GLState pGLState) { /** * @param pGLState - * @throws RenderTextureInitializationException when this {@link RenderTexture} could not be initialized. The {@link GLException} contains the error code. When this exception is throw, all cleanup will be automatically performed through {@link RenderTexture#destroy(GLState)}. + * @throws RenderTextureInitializationException when this {@link RenderTexture} could not be initialized. The {@link GLException} contains the error code. When this exception is throw, all cleanup will be automatically performed through {@link #destroy(GLState)}. */ public void init(final GLState pGLState) throws GLFrameBufferException, GLException { this.savePreviousFramebufferObjectID(pGLState); @@ -159,16 +159,16 @@ public void init(final GLState pGLState) throws GLFrameBufferException, GLExcept } /** - * @see {@link RenderTexture#end(GLState)}, - * {@link RenderTexture#end(GLState, boolean, boolean}}. + * @see {@link #end(GLState)}, + * {@link #end(GLState, boolean, boolean}}. */ public void begin(final GLState pGLState) { this.begin(pGLState, false, false); } /** - * @see {@link RenderTexture#end(GLState)}, - * {@link RenderTexture#end(GLState, boolean, boolean}}. + * @see {@link #end(GLState)}, + * {@link #end(GLState, boolean, boolean}}. * * @param pColor the {@link Color} to clear this {@link RenderTexture}. */ @@ -177,8 +177,8 @@ public void begin(final GLState pGLState, final Color pColor) { } /** - * @see {@link RenderTexture#end(GLState)}, - * {@link RenderTexture#end(GLState, boolean, boolean}}. + * @see {@link #end(GLState)}, + * {@link #end(GLState, boolean, boolean}}. * * @param pRed the red portion of the color to clear this {@link RenderTexture}. * @param pGreen the green portion of the color to clear this {@link RenderTexture}. @@ -190,8 +190,8 @@ public void begin(final GLState pGLState, final float pRed, final float pGreen, } /** - * @see {@link RenderTexture#end(GLState)}, - * {@link RenderTexture#end(GLState, boolean, boolean}}. + * @see {@link #end(GLState)}, + * {@link #end(GLState, boolean, boolean}}. * * @param pColor the {@link Color} to clear this {@link RenderTexture}. */ @@ -200,8 +200,8 @@ public void begin(final GLState pGLState, final boolean pFlipX, final boolean pF } /** - * @see {@link RenderTexture#end(GLState)}, - * {@link RenderTexture#end(GLState, boolean, boolean}}. + * @see {@link #end(GLState)}, + * {@link #end(GLState, boolean, boolean}}. * * @param pRed the red portion of the color to clear this {@link RenderTexture}. * @param pGreen the green portion of the color to clear this {@link RenderTexture}. @@ -222,8 +222,8 @@ public void begin(final GLState pGLState, final boolean pFlipX, final boolean pF } /** - * @see {@link RenderTexture#end(GLState)}, - * {@link RenderTexture#end(GLState, boolean, boolean}}. + * @see {@link #end(GLState)}, + * {@link #end(GLState, boolean, boolean}}. */ public void begin(final GLState pGLState, final boolean pFlipX, final boolean pFlipY) { this.savePreviousViewport(); @@ -235,19 +235,19 @@ public void begin(final GLState pGLState, final boolean pFlipX, final boolean pF final float right; final float bottom; final float top; - if(pFlipX) { + if (pFlipX) { left = this.mWidth; right = 0; } else { left = 0; right = this.mWidth; } - if(pFlipY) { - top = this.mHeight; - bottom = 0; - } else { + if (pFlipY) { top = 0; bottom = this.mHeight; + } else { + top = this.mHeight; + bottom = 0; } pGLState.orthoProjectionGLMatrixf(left, right, bottom, top, -1, 1); @@ -273,12 +273,12 @@ public void finish(final GLState pGLState) { } /** - * @see {@link RenderTexture#begin(GLState)}, - * {@link RenderTexture#begin(GLState, boolean, boolean)}, - * {@link RenderTexture#begin(GLState, Color)}, - * {@link RenderTexture#begin(GLState, float, float, float, float)}, - * {@link RenderTexture#begin(GLState, boolean, boolean, Color)}. - * {@link RenderTexture#begin(GLState, boolean, boolean, float, float, float, float)}. + * @see {@link #begin(GLState)}, + * {@link #begin(GLState, boolean, boolean)}, + * {@link #begin(GLState, Color)}, + * {@link #begin(GLState, float, float, float, float)}, + * {@link #begin(GLState, boolean, boolean, Color)}. + * {@link #begin(GLState, boolean, boolean, float, float, float, float)}. */ public void end(final GLState pGLState) { this.end(pGLState, false, false); @@ -288,18 +288,18 @@ public void end(final GLState pGLState) { * @param pGLState * @param pFlush {@link GLState#flush()} has lower preference than pFinish. * @param pFinish {@link GLState#finish()} had higher preference than pFlush. - * - * @see {@link RenderTexture#begin(GLState)}, - * {@link RenderTexture#begin(GLState, boolean, boolean)}, - * {@link RenderTexture#begin(GLState, Color)}, - * {@link RenderTexture#begin(GLState, float, float, float, float)}, - * {@link RenderTexture#begin(GLState, boolean, boolean, Color)}. - * {@link RenderTexture#begin(GLState, boolean, boolean, float, float, float, float)}. + * + * @see {@link #begin(GLState)}, + * {@link #begin(GLState, boolean, boolean)}, + * {@link #begin(GLState, Color)}, + * {@link #begin(GLState, float, float, float, float)}, + * {@link #begin(GLState, boolean, boolean, Color)}. + * {@link #begin(GLState, boolean, boolean, float, float, float, float)}. */ public void end(final GLState pGLState, final boolean pFlush, final boolean pFinish) { - if(pFinish) { + if (pFinish) { this.finish(pGLState); - } else if(pFlush) { + } else if (pFlush) { this.flush(pGLState); } @@ -362,7 +362,7 @@ public Bitmap getBitmap(final GLState pGLState) { } public Bitmap getBitmap(final GLState pGLState, final int pX, final int pY, final int pWidth, final int pHeight) { - if(this.mPixelFormat != PixelFormat.RGBA_8888) { + if (this.mPixelFormat != PixelFormat.RGBA_8888) { throw new IllegalStateException("Currently only 'PixelFormat." + PixelFormat.RGBA_8888 + "' is supported to be retrieved as a Bitmap."); } diff --git a/src/org/andengine/opengl/util/BufferUtils.java b/src/org/andengine/opengl/util/BufferUtils.java index 9fa34cc39..ece1e9038 100644 --- a/src/org/andengine/opengl/util/BufferUtils.java +++ b/src/org/andengine/opengl/util/BufferUtils.java @@ -8,12 +8,13 @@ import android.os.Build; /** - * (c) Zynga 2011 + * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 23:06:51 - 11.08.2011 - * @see http://code.google.com/p/android/issues/detail?id=11078 - * @see http://code.google.com/p/android/issues/detail?id=16941 + * + * @see Issue 11078 + * @see Issue 16941 */ public class BufferUtils { // =========================================================== @@ -37,21 +38,21 @@ public class BufferUtils { } NATIVE_LIB_LOADED = loadLibrarySuccess; - if(BufferUtils.NATIVE_LIB_LOADED) { - if(SystemUtils.isAndroidVersion(Build.VERSION_CODES.HONEYCOMB, Build.VERSION_CODES.HONEYCOMB_MR2)) { + if (BufferUtils.NATIVE_LIB_LOADED) { + if (SystemUtils.isAndroidVersion(Build.VERSION_CODES.HONEYCOMB, Build.VERSION_CODES.HONEYCOMB_MR2)) { WORKAROUND_BYTEBUFFER_ALLOCATE_DIRECT = true; } else { WORKAROUND_BYTEBUFFER_ALLOCATE_DIRECT = false; } - if(SystemUtils.isAndroidVersionOrLower(Build.VERSION_CODES.FROYO)) { + if (SystemUtils.isAndroidVersionOrLower(Build.VERSION_CODES.FROYO)) { WORKAROUND_BYTEBUFFER_PUT_FLOATARRAY = true; } else { WORKAROUND_BYTEBUFFER_PUT_FLOATARRAY = false; } } else { WORKAROUND_BYTEBUFFER_ALLOCATE_DIRECT = false; - if(SystemUtils.isAndroidVersion(Build.VERSION_CODES.HONEYCOMB, Build.VERSION_CODES.HONEYCOMB_MR2)) { + if (SystemUtils.isAndroidVersion(Build.VERSION_CODES.HONEYCOMB, Build.VERSION_CODES.HONEYCOMB_MR2)) { Debug.w("Creating a " + ByteBuffer.class.getSimpleName() + " will actually allocate 4x the memory than requested!"); } @@ -84,7 +85,7 @@ public class BufferUtils { * @return */ public static ByteBuffer allocateDirectByteBuffer(final int pCapacity) { - if(BufferUtils.WORKAROUND_BYTEBUFFER_ALLOCATE_DIRECT) { + if (BufferUtils.WORKAROUND_BYTEBUFFER_ALLOCATE_DIRECT) { return BufferUtils.jniAllocateDirect(pCapacity); } else { return ByteBuffer.allocateDirect(pCapacity); @@ -92,7 +93,7 @@ public static ByteBuffer allocateDirectByteBuffer(final int pCapacity) { } public static void freeDirectByteBuffer(final ByteBuffer pByteBuffer) { - if(BufferUtils.WORKAROUND_BYTEBUFFER_ALLOCATE_DIRECT) { + if (BufferUtils.WORKAROUND_BYTEBUFFER_ALLOCATE_DIRECT) { BufferUtils.jniFreeDirect(pByteBuffer); } } @@ -107,10 +108,10 @@ public static void freeDirectByteBuffer(final ByteBuffer pByteBuffer) { * @param pOffset in pSource. */ public static void put(final ByteBuffer pByteBuffer, final float[] pSource, final int pLength, final int pOffset) { - if(BufferUtils.WORKAROUND_BYTEBUFFER_PUT_FLOATARRAY) { + if (BufferUtils.WORKAROUND_BYTEBUFFER_PUT_FLOATARRAY) { BufferUtils.jniPut(pByteBuffer, pSource, pLength, pOffset); } else { - for(int i = pOffset; i < (pOffset + pLength); i++) { + for (int i = pOffset; i < (pOffset + pLength); i++) { pByteBuffer.putFloat(pSource[i]); } } diff --git a/src/org/andengine/opengl/util/GLHelper.java b/src/org/andengine/opengl/util/GLHelper.java index 4f5c971e2..e58398da6 100644 --- a/src/org/andengine/opengl/util/GLHelper.java +++ b/src/org/andengine/opengl/util/GLHelper.java @@ -40,7 +40,7 @@ public static Buffer getPixels(final Bitmap pBitmap, final PixelFormat pPixelFor public static Buffer getPixels(final Bitmap pBitmap, final PixelFormat pPixelFormat, final ByteOrder pByteOrder) { final int[] pixelsARGB_8888 = GLHelper.getPixelsARGB_8888(pBitmap); - switch(pPixelFormat) { + switch (pPixelFormat) { case RGB_565: return ShortBuffer.wrap(GLHelper.convertARGB_8888toRGB_565(pixelsARGB_8888, pByteOrder)); // TODO Is ShortBuffer or IntBuffer faster? case RGBA_8888: @@ -61,8 +61,8 @@ public static int[] convertARGB_8888toRGBA_8888(final int[] pPixelsARGB_8888) { } public static int[] convertARGB_8888toRGBA_8888(final int[] pPixelsARGB_8888, final ByteOrder pByteOrder) { - if(pByteOrder == ByteOrder.LITTLE_ENDIAN) { - for(int i = pPixelsARGB_8888.length - 1; i >= 0; i--) { + if (pByteOrder == ByteOrder.LITTLE_ENDIAN) { + for (int i = pPixelsARGB_8888.length - 1; i >= 0; i--) { final int pixel = pPixelsARGB_8888[i]; /* [A][R][G][B] to [A][B][G][R] */ @@ -71,7 +71,7 @@ public static int[] convertARGB_8888toRGBA_8888(final int[] pPixelsARGB_8888, fi pPixelsARGB_8888[i] = (pixel & 0xFF00FF00) | ((pixel << 16) & 0x00FF0000) | ((pixel >> 16) & 0x000000FF); } } else { - for(int i = pPixelsARGB_8888.length - 1; i >= 0; i--) { + for (int i = pPixelsARGB_8888.length - 1; i >= 0; i--) { final int pixel = pPixelsARGB_8888[i]; /* [A][R][G][B] to [R][G][B][A] */ @@ -89,8 +89,8 @@ public static short[] convertARGB_8888toRGB_565(final int[] pPixelsARGB_8888) { public static short[] convertARGB_8888toRGB_565(final int[] pPixelsARGB_8888, final ByteOrder pByteOrder) { final short[] pixelsRGB_565 = new short[pPixelsARGB_8888.length]; - if(pByteOrder == ByteOrder.LITTLE_ENDIAN) { - for(int i = pPixelsARGB_8888.length - 1; i >= 0; i--) { + if (pByteOrder == ByteOrder.LITTLE_ENDIAN) { + for (int i = pPixelsARGB_8888.length - 1; i >= 0; i--) { final int pixel = pPixelsARGB_8888[i]; /* [A][R][G][B] to [GB][RG] */ @@ -101,7 +101,7 @@ public static short[] convertARGB_8888toRGB_565(final int[] pPixelsARGB_8888, fi pixelsRGB_565[i] = (short)(((pixel >> 16) & 0x00F8) | ((pixel >> 13) & 0x07) | ((pixel << 3) & 0xE000) | ((pixel << 5) & 0x1F00)); } } else { - for(int i = pPixelsARGB_8888.length - 1; i >= 0; i--) { + for (int i = pPixelsARGB_8888.length - 1; i >= 0; i--) { final int pixel = pPixelsARGB_8888[i]; /* [A][R][G][B] to [RG][GB] */ @@ -121,8 +121,8 @@ public static short[] convertARGB_8888toRGBA_4444(final int[] pPixelsARGB_8888) public static short[] convertARGB_8888toRGBA_4444(final int[] pPixelsARGB_8888, final ByteOrder pByteOrder) { final short[] pixelsRGBA_4444 = new short[pPixelsARGB_8888.length]; - if(pByteOrder == ByteOrder.LITTLE_ENDIAN) { - for(int i = pPixelsARGB_8888.length - 1; i >= 0; i--) { + if (pByteOrder == ByteOrder.LITTLE_ENDIAN) { + for (int i = pPixelsARGB_8888.length - 1; i >= 0; i--) { final int pixel = pPixelsARGB_8888[i]; /* [A][R][G][B] to [BA][RG] */ @@ -133,7 +133,7 @@ public static short[] convertARGB_8888toRGBA_4444(final int[] pPixelsARGB_8888, pixelsRGBA_4444[i] = (short)(((pixel >> 16) & 0x00F0) | ((pixel >> 12) & 0x000F) | ((pixel << 8) & 0xF000) | ((pixel >> 20) & 0x0F00)); } } else { - for(int i = pPixelsARGB_8888.length - 1; i >= 0; i--) { + for (int i = pPixelsARGB_8888.length - 1; i >= 0; i--) { final int pixel = pPixelsARGB_8888[i]; /* [A][R][G][B] to [RG][BA] */ @@ -149,7 +149,7 @@ public static short[] convertARGB_8888toRGBA_4444(final int[] pPixelsARGB_8888, public static byte[] convertARGB_8888toA_8(final int[] pPixelsARGB_8888) { final byte[] pixelsA_8 = new byte[pPixelsARGB_8888.length]; - for(int i = pPixelsARGB_8888.length - 1; i >= 0; i--) { + for (int i = pPixelsARGB_8888.length - 1; i >= 0; i--) { /* [A][R][G][B] to [A] */ /* From : [ A7 A6 A5 A4 A3 A2 A1 A0 | R7 R6 R5 R4 R3 R2 R1 R0 | G7 G6 G5 G4 G3 G2 G1 G0 | B7 B6 B5 B4 B3 B2 B1 B0 ] */ /* To : [ A7 A6 A5 A4 A3 A2 A1 A0 ] */ @@ -173,8 +173,8 @@ public static int[] convertRGBA_8888toARGB_8888(final int[] pPixelsRGBA_8888) { } public static int[] convertRGBA_8888toARGB_8888(final int[] pPixelsRGBA_8888, final ByteOrder pByteOrder) { - if(pByteOrder == ByteOrder.LITTLE_ENDIAN) { - for(int i = pPixelsRGBA_8888.length - 1; i >= 0; i--) { + if (pByteOrder == ByteOrder.LITTLE_ENDIAN) { + for (int i = pPixelsRGBA_8888.length - 1; i >= 0; i--) { final int pixel = pPixelsRGBA_8888[i]; /* [A][B][G][R] to [A][R][G][B] */ /* From : [ A7 A6 A5 A4 A3 A2 A1 A0 | B7 B6 B5 B4 B3 B2 B1 B0 | G7 G6 G5 G4 G3 G2 G1 G0 | R7 R6 R5 R4 R3 R2 R1 R0 ] */ @@ -182,7 +182,7 @@ public static int[] convertRGBA_8888toARGB_8888(final int[] pPixelsRGBA_8888, fi pPixelsRGBA_8888[i] = (pixel & 0xFF00FF00) | ((pixel << 16) & 0x00FF0000) | ((pixel >> 16) & 0x000000FF); } } else { - for(int i = pPixelsRGBA_8888.length - 1; i >= 0; i--) { + for (int i = pPixelsRGBA_8888.length - 1; i >= 0; i--) { final int pixel = pPixelsRGBA_8888[i]; /* [R][G][B][A] to [A][R][G][B] */ /* From : [ R7 R6 R5 R4 R3 R2 R1 R0 | G7 G6 G5 G4 G3 G2 G1 G0 | B7 B6 B5 B4 B3 B2 B1 B0 | A7 A6 A5 A4 A3 A2 A1 A0 ] */ @@ -200,9 +200,9 @@ public static int[] convertRGBA_8888toARGB_8888_FlippedVertical(final int[] pPix public static int[] convertRGBA_8888toARGB_8888_FlippedVertical(final int[] pPixelsRGBA_8888, final int pWidth, final int pHeight, final ByteOrder pByteOrder) { final int[] pixelsARGB_8888 = new int[pWidth * pHeight]; - if(pByteOrder == ByteOrder.LITTLE_ENDIAN) { - for(int y = 0; y < pHeight; y++) { - for(int x = 0; x < pWidth; x++) { + if (pByteOrder == ByteOrder.LITTLE_ENDIAN) { + for (int y = 0; y < pHeight; y++) { + for (int x = 0; x < pWidth; x++) { final int pixel = pPixelsRGBA_8888[x + (y * pWidth)]; /* [A][B][G][R] to [A][R][G][B] */ /* From : [ A7 A6 A5 A4 A3 A2 A1 A0 | B7 B6 B5 B4 B3 B2 B1 B0 | G7 G6 G5 G4 G3 G2 G1 G0 | R7 R6 R5 R4 R3 R2 R1 R0 ] */ @@ -211,8 +211,8 @@ public static int[] convertRGBA_8888toARGB_8888_FlippedVertical(final int[] pPix } } } else { - for(int y = 0; y < pHeight; y++) { - for(int x = 0; x < pWidth; x++) { + for (int y = 0; y < pHeight; y++) { + for (int x = 0; x < pWidth; x++) { final int pixel = pPixelsRGBA_8888[x + (y * pWidth)]; /* [R][G][B][A] to [A][R][G][B] */ /* From : [ R7 R6 R5 R4 R3 R2 R1 R0 | G7 G6 G5 G4 G3 G2 G1 G0 | B7 B6 B5 B4 B3 B2 B1 B0 | A7 A6 A5 A4 A3 A2 A1 A0 ] */ diff --git a/src/org/andengine/opengl/util/GLMatrixStack.java b/src/org/andengine/opengl/util/GLMatrixStack.java index c2559afe1..d159ebdc8 100644 --- a/src/org/andengine/opengl/util/GLMatrixStack.java +++ b/src/org/andengine/opengl/util/GLMatrixStack.java @@ -7,8 +7,8 @@ /** * TODO Measure performance with inlined or native Matrix implementations. - * - * (c) Zynga 2011 + * + * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 14:49:23 - 04.08.2011 @@ -50,6 +50,10 @@ public GLMatrixStack() { // =========================================================== public void getMatrix(final float[] pMatrix) { + if (this.mMatrixStackOffset - GLMatrixStack.GLMATRIX_SIZE <= GLMatrixStack.GLMATRIXSTACKOFFSET_UNDERFLOW) { + throw new GLMatrixStackUnderflowException(); + } + System.arraycopy(this.mMatrixStack, this.mMatrixStackOffset, pMatrix, 0, GLMatrixStack.GLMATRIX_SIZE); } diff --git a/src/org/andengine/opengl/util/GLScissorStack.java b/src/org/andengine/opengl/util/GLScissorStack.java new file mode 100644 index 000000000..6dae8f197 --- /dev/null +++ b/src/org/andengine/opengl/util/GLScissorStack.java @@ -0,0 +1,211 @@ +package org.andengine.opengl.util; + +import org.andengine.util.exception.AndEngineRuntimeException; + +import android.opengl.GLES20; + +/** + * TODO Measure performance against regular Java Stack + * + * (c) 2013 Zynga Inc. + * + * @author Nicolas Gramlich + * @author Michal Stawinski + * @since 14:49:23 - 02.05.2013 + */ +public class GLScissorStack { + // =========================================================== + // Constants + // =========================================================== + + public static final int GLSCISSOR_X_INDEX = 0; + public static final int GLSCISSOR_Y_INDEX = 1; + public static final int GLSCISSOR_WIDTH_INDEX = 2; + public static final int GLSCISSOR_HEIGHT_INDEX = 3; + + public static final int GLSCISSORSTACK_DEPTH_MAX = 32; + public static final int GLSCISSOR_SIZE = 4; + + private static final int GLSCISSORSTACKOFFSET_UNDERFLOW = -1 * GLScissorStack.GLSCISSOR_SIZE; + private static final int GLSCISSORSTACKOFFSET_OVERFLOW = GLScissorStack.GLSCISSORSTACK_DEPTH_MAX * GLScissorStack.GLSCISSOR_SIZE; + + // =========================================================== + // Fields + // =========================================================== + + private final int[] mScissorStack = new int[GLScissorStack.GLSCISSORSTACK_DEPTH_MAX * GLScissorStack.GLSCISSOR_SIZE]; + private int mScissorStackOffset; + + // =========================================================== + // Constructors + // =========================================================== + + public GLScissorStack() { + + } + + // =========================================================== + // Constructors + // =========================================================== + + // =========================================================== + // Getter & Setter + // =========================================================== + + public int[] getScissor(final int[] pScissors) { + if (this.mScissorStackOffset - GLScissorStack.GLSCISSOR_SIZE <= GLScissorStack.GLSCISSORSTACKOFFSET_UNDERFLOW) { + throw new GLScissorStackUnderflowException(); + } + + System.arraycopy(this.mScissorStack, this.mScissorStackOffset, pScissors, 0, GLScissorStack.GLSCISSOR_SIZE); + return pScissors; + } + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + public void glPushScissor(final int pX, final int pY, final int pWidth, final int pHeight) { + if (this.mScissorStackOffset + GLScissorStack.GLSCISSOR_SIZE >= GLScissorStack.GLSCISSORSTACKOFFSET_OVERFLOW) { + throw new GLScissorStackOverflowException(); + } + + final int x; + final int y; + final int width; + final int height; + if (this.mScissorStackOffset == 0) { + x = pX; + y = pY; + width = pWidth; + height = pHeight; + } else { + /* Take the intersection between the current and the new scissor: */ + final int currentX = this.mScissorStack[this.mScissorStackOffset - (GLSCISSOR_SIZE - GLSCISSOR_X_INDEX)]; + final int currentY = this.mScissorStack[this.mScissorStackOffset - (GLSCISSOR_SIZE - GLSCISSOR_Y_INDEX)]; + final int currentWidth = this.mScissorStack[this.mScissorStackOffset - (GLSCISSOR_SIZE - GLSCISSOR_WIDTH_INDEX)]; + final int currentHeight = this.mScissorStack[this.mScissorStackOffset - (GLSCISSOR_SIZE - GLSCISSOR_HEIGHT_INDEX)]; + + final float xMin = Math.max(currentX, pX); + final float xMax = Math.min(currentX + currentWidth, pX + pWidth); + + final float yMin = Math.max(currentY, pY); + final float yMax = Math.min(currentY + currentHeight, pY + pHeight); + + x = (int) xMin; + y = (int) yMin; + width = (int) (xMax - xMin); + height = (int) (yMax - yMin); + } + + this.mScissorStack[this.mScissorStackOffset + GLSCISSOR_X_INDEX] = pX; + this.mScissorStack[this.mScissorStackOffset + GLSCISSOR_Y_INDEX] = pY; + this.mScissorStack[this.mScissorStackOffset + GLSCISSOR_WIDTH_INDEX] = pWidth; + this.mScissorStack[this.mScissorStackOffset + GLSCISSOR_HEIGHT_INDEX] = pHeight; + + GLES20.glScissor(x, y, width, height); + + this.mScissorStackOffset += GLScissorStack.GLSCISSOR_SIZE; + } + + public void glPopScissor() { + if (this.mScissorStackOffset - GLScissorStack.GLSCISSOR_SIZE <= GLScissorStack.GLSCISSORSTACKOFFSET_UNDERFLOW) { + throw new GLScissorStackUnderflowException(); + } + + this.mScissorStackOffset -= GLScissorStack.GLSCISSOR_SIZE; + + final int x = this.mScissorStack[this.mScissorStackOffset + GLSCISSOR_X_INDEX]; + final int y = this.mScissorStack[this.mScissorStackOffset + GLSCISSOR_Y_INDEX]; + final int width = this.mScissorStack[this.mScissorStackOffset + GLSCISSOR_WIDTH_INDEX]; + final int height = this.mScissorStack[this.mScissorStackOffset + GLSCISSOR_HEIGHT_INDEX]; + + GLES20.glScissor(x, y, width, height); + } + + public void reset() { + this.mScissorStackOffset = 0; + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== + + public static class GLScissorStackOverflowException extends AndEngineRuntimeException { + + // =========================================================== + // Constants + // =========================================================== + + private static final long serialVersionUID = 8253962794945142016L; + + // =========================================================== + // Fields + // =========================================================== + + // =========================================================== + // Constructors + // =========================================================== + + public GLScissorStackOverflowException() { + + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== + } + + public static class GLScissorStackUnderflowException extends AndEngineRuntimeException { + + // =========================================================== + // Constants + // =========================================================== + + private static final long serialVersionUID = -2962655760038324091L; + + // =========================================================== + // Fields + // =========================================================== + + // =========================================================== + // Constructors + // =========================================================== + + public GLScissorStackUnderflowException() { + + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== + } +} diff --git a/src/org/andengine/opengl/util/GLState.java b/src/org/andengine/opengl/util/GLState.java index 0fcb86bbc..eb0fc5067 100644 --- a/src/org/andengine/opengl/util/GLState.java +++ b/src/org/andengine/opengl/util/GLState.java @@ -35,6 +35,8 @@ public class GLState { public static final int GL_UNPACK_ALIGNMENT_DEFAULT = 4; + public static final float LINE_WIDTH_DEFAULT = 1.0f; + // =========================================================== // Fields // =========================================================== @@ -72,6 +74,7 @@ public class GLState { private final GLMatrixStack mModelViewGLMatrixStack = new GLMatrixStack(); private final GLMatrixStack mProjectionGLMatrixStack = new GLMatrixStack(); + private final GLScissorStack mScissorStack = new GLScissorStack(); private final float[] mModelViewGLMatrix = new float[GLMatrixStack.GLMATRIX_SIZE]; private final float[] mProjectionGLMatrix = new float[GLMatrixStack.GLMATRIX_SIZE]; @@ -128,10 +131,10 @@ public void reset(final RenderOptions pRenderOptions, final ConfigChooser pConfi this.mMaximumTextureUnits = this.getInteger(GLES20.GL_MAX_TEXTURE_IMAGE_UNITS); this.mMaximumTextureSize = this.getInteger(GLES20.GL_MAX_TEXTURE_SIZE); - if(BuildConfig.DEBUG) { + if (BuildConfig.DEBUG) { Debug.d("VERSION: " + this.mVersion); Debug.d("RENDERER: " + this.mRenderer); - Debug.d("EGLCONFIG: " + EGLConfig.class.getSimpleName() + "(Red=" + pConfigChooser.getRedSize() + ", Green=" + pConfigChooser.getGreenSize() + ", Blue=" + pConfigChooser.getBlueSize() + ", Alpha=" + pConfigChooser.getAlphaSize() + ", Depth=" + pConfigChooser.getDepthSize() + ", Stencil=" + pConfigChooser.getStencilSize() + ")"); + Debug.d("EGLCONFIG: " + EGLConfig.class.getSimpleName() + "(Red=" + pConfigChooser.getActualRedSize() + ", Green=" + pConfigChooser.getActualGreenSize() + ", Blue=" + pConfigChooser.getActualBlueSize() + ", Alpha=" + pConfigChooser.getActualAlphaSize() + ", Depth=" + pConfigChooser.getActualDepthSize() + ", Stencil=" + pConfigChooser.getActualStencilSize() + ")"); Debug.d("EXTENSIONS: " + this.mExtensions); Debug.d("MAX_VERTEX_ATTRIBS: " + this.mMaximumVertexAttributeCount); Debug.d("MAX_VERTEX_UNIFORM_VECTORS: " + this.mMaximumVertexShaderUniformVectorCount); @@ -142,6 +145,7 @@ public void reset(final RenderOptions pRenderOptions, final ConfigChooser pConfi this.mModelViewGLMatrixStack.reset(); this.mProjectionGLMatrixStack.reset(); + this.mScissorStack.reset(); this.mCurrentArrayBufferID = -1; this.mCurrentIndexBufferID = -1; @@ -159,6 +163,8 @@ public void reset(final RenderOptions pRenderOptions, final ConfigChooser pConfi this.disableBlend(); this.disableCulling(); + this.lineWidth(GLState.LINE_WIDTH_DEFAULT); + GLES20.glEnableVertexAttribArray(ShaderProgramConstants.ATTRIBUTE_POSITION_LOCATION); GLES20.glEnableVertexAttribArray(ShaderProgramConstants.ATTRIBUTE_COLOR_LOCATION); GLES20.glEnableVertexAttribArray(ShaderProgramConstants.ATTRIBUTE_TEXTURECOORDINATES_LOCATION); @@ -173,10 +179,10 @@ public boolean isScissorTestEnabled() { * @return the previous state. */ public boolean enableScissorTest() { - if(this.mScissorTestEnabled) { + if (this.mScissorTestEnabled) { return true; } - + this.mScissorTestEnabled = true; GLES20.glEnable(GLES20.GL_SCISSOR_TEST); return false; @@ -185,7 +191,7 @@ public boolean enableScissorTest() { * @return the previous state. */ public boolean disableScissorTest() { - if(!this.mScissorTestEnabled) { + if (!this.mScissorTestEnabled) { return false; } @@ -197,7 +203,7 @@ public boolean disableScissorTest() { * @return the previous state. */ public boolean setScissorTestEnabled(final boolean pEnabled) { - if(pEnabled) { + if (pEnabled) { return this.enableScissorTest(); } else { return this.disableScissorTest(); @@ -211,7 +217,7 @@ public boolean isBlendEnabled() { * @return the previous state. */ public boolean enableBlend() { - if(this.mBlendEnabled) { + if (this.mBlendEnabled) { return true; } @@ -223,7 +229,7 @@ public boolean enableBlend() { * @return the previous state. */ public boolean disableBlend() { - if(!this.mBlendEnabled) { + if (!this.mBlendEnabled) { return false; } @@ -235,7 +241,7 @@ public boolean disableBlend() { * @return the previous state. */ public boolean setBlendEnabled(final boolean pEnabled) { - if(pEnabled) { + if (pEnabled) { return this.enableBlend(); } else { return this.disableBlend(); @@ -249,7 +255,7 @@ public boolean isCullingEnabled() { * @return the previous state. */ public boolean enableCulling() { - if(this.mCullingEnabled) { + if (this.mCullingEnabled) { return true; } @@ -261,7 +267,7 @@ public boolean enableCulling() { * @return the previous state. */ public boolean disableCulling() { - if(!this.mCullingEnabled) { + if (!this.mCullingEnabled) { return false; } @@ -273,7 +279,7 @@ public boolean disableCulling() { * @return the previous state. */ public boolean setCullingEnabled(final boolean pEnabled) { - if(pEnabled) { + if (pEnabled) { return this.enableCulling(); } else { return this.disableCulling(); @@ -287,7 +293,7 @@ public boolean isDitherEnabled() { * @return the previous state. */ public boolean enableDither() { - if(this.mDitherEnabled) { + if (this.mDitherEnabled) { return true; } @@ -299,7 +305,7 @@ public boolean enableDither() { * @return the previous state. */ public boolean disableDither() { - if(!this.mDitherEnabled) { + if (!this.mDitherEnabled) { return false; } @@ -311,7 +317,7 @@ public boolean disableDither() { * @return the previous state. */ public boolean setDitherEnabled(final boolean pEnabled) { - if(pEnabled) { + if (pEnabled) { return this.enableDither(); } else { return this.disableDither(); @@ -325,7 +331,7 @@ public boolean isDepthTestEnabled() { * @return the previous state. */ public boolean enableDepthTest() { - if(this.mDepthTestEnabled) { + if (this.mDepthTestEnabled) { return true; } @@ -337,7 +343,7 @@ public boolean enableDepthTest() { * @return the previous state. */ public boolean disableDepthTest() { - if(!this.mDepthTestEnabled) { + if (!this.mDepthTestEnabled) { return false; } @@ -349,7 +355,7 @@ public boolean disableDepthTest() { * @return the previous state. */ public boolean setDepthTestEnabled(final boolean pEnabled) { - if(pEnabled) { + if (pEnabled) { return this.enableDepthTest(); } else { return this.disableDepthTest(); @@ -373,14 +379,14 @@ public int generateArrayBuffer(final int pSize, final int pUsage) { } public void bindArrayBuffer(final int pHardwareBufferID) { - if(this.mCurrentArrayBufferID != pHardwareBufferID) { + if (this.mCurrentArrayBufferID != pHardwareBufferID) { this.mCurrentArrayBufferID = pHardwareBufferID; GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, pHardwareBufferID); } } public void deleteArrayBuffer(final int pHardwareBufferID) { - if(this.mCurrentArrayBufferID == pHardwareBufferID) { + if (this.mCurrentArrayBufferID == pHardwareBufferID) { this.mCurrentArrayBufferID = -1; } this.mHardwareIDContainer[0] = pHardwareBufferID; @@ -390,23 +396,23 @@ public void deleteArrayBuffer(final int pHardwareBufferID) { public int generateIndexBuffer(final int pSize, final int pUsage) { GLES20.glGenBuffers(1, this.mHardwareIDContainer, 0); final int hardwareBufferID = this.mHardwareIDContainer[0]; - + this.bindIndexBuffer(hardwareBufferID); GLES20.glBufferData(GLES20.GL_ELEMENT_ARRAY_BUFFER, pSize, null, pUsage); this.bindIndexBuffer(0); - + return hardwareBufferID; } public void bindIndexBuffer(final int pHardwareBufferID) { - if(this.mCurrentIndexBufferID != pHardwareBufferID) { + if (this.mCurrentIndexBufferID != pHardwareBufferID) { this.mCurrentIndexBufferID = pHardwareBufferID; GLES20.glBindBuffer(GLES20.GL_ELEMENT_ARRAY_BUFFER, pHardwareBufferID); } } public void deleteIndexBuffer(final int pHardwareBufferID) { - if(this.mCurrentIndexBufferID == pHardwareBufferID) { + if (this.mCurrentIndexBufferID == pHardwareBufferID) { this.mCurrentIndexBufferID = -1; } this.mHardwareIDContainer[0] = pHardwareBufferID; @@ -428,7 +434,7 @@ public int getFramebufferStatus() { public void checkFramebufferStatus() throws GLFrameBufferException, GLException { final int framebufferStatus = this.getFramebufferStatus(); - switch(framebufferStatus) { + switch (framebufferStatus) { case GLES20.GL_FRAMEBUFFER_COMPLETE: return; case GLES20.GL_FRAMEBUFFER_UNSUPPORTED: @@ -451,7 +457,7 @@ public int getActiveFramebuffer() { } public void deleteFramebuffer(final int pHardwareFramebufferID) { - if(this.mCurrentFramebufferID == pHardwareFramebufferID) { + if (this.mCurrentFramebufferID == pHardwareFramebufferID) { this.mCurrentFramebufferID = -1; } this.mHardwareIDContainer[0] = pHardwareFramebufferID; @@ -459,14 +465,14 @@ public void deleteFramebuffer(final int pHardwareFramebufferID) { } public void useProgram(final int pShaderProgramID) { - if(this.mCurrentShaderProgramID != pShaderProgramID) { + if (this.mCurrentShaderProgramID != pShaderProgramID) { this.mCurrentShaderProgramID = pShaderProgramID; GLES20.glUseProgram(pShaderProgramID); } } public void deleteProgram(final int pShaderProgramID) { - if(this.mCurrentShaderProgramID == pShaderProgramID) { + if (this.mCurrentShaderProgramID == pShaderProgramID) { this.mCurrentShaderProgramID = -1; } GLES20.glDeleteProgram(pShaderProgramID); @@ -493,26 +499,26 @@ public int getActiveTexture() { */ public void activeTexture(final int pGLActiveTexture) { final int activeTextureIndex = pGLActiveTexture - GLES20.GL_TEXTURE0; - if(pGLActiveTexture != this.mCurrentActiveTextureIndex) { + if (pGLActiveTexture != this.mCurrentActiveTextureIndex) { this.mCurrentActiveTextureIndex = activeTextureIndex; GLES20.glActiveTexture(pGLActiveTexture); } } /** - * @see {@link GLState#forceBindTexture(GLES20, int)} + * @see {@link #forceBindTexture(GLES20, int)} * @param GLES20 * @param pHardwareTextureID */ public void bindTexture(final int pHardwareTextureID) { - if(this.mCurrentBoundTextureIDs[this.mCurrentActiveTextureIndex] != pHardwareTextureID) { + if (this.mCurrentBoundTextureIDs[this.mCurrentActiveTextureIndex] != pHardwareTextureID) { this.mCurrentBoundTextureIDs[this.mCurrentActiveTextureIndex] = pHardwareTextureID; GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, pHardwareTextureID); } } public void deleteTexture(final int pHardwareTextureID) { - if(this.mCurrentBoundTextureIDs[this.mCurrentActiveTextureIndex] == pHardwareTextureID) { + if (this.mCurrentBoundTextureIDs[this.mCurrentActiveTextureIndex] == pHardwareTextureID) { this.mCurrentBoundTextureIDs[this.mCurrentActiveTextureIndex] = -1; } this.mHardwareIDContainer[0] = pHardwareTextureID; @@ -520,7 +526,7 @@ public void deleteTexture(final int pHardwareTextureID) { } public void blendFunction(final int pSourceBlendMode, final int pDestinationBlendMode) { - if(this.mCurrentSourceBlendMode != pSourceBlendMode || this.mCurrentDestinationBlendMode != pDestinationBlendMode) { + if (this.mCurrentSourceBlendMode != pSourceBlendMode || this.mCurrentDestinationBlendMode != pDestinationBlendMode) { this.mCurrentSourceBlendMode = pSourceBlendMode; this.mCurrentDestinationBlendMode = pDestinationBlendMode; GLES20.glBlendFunc(pSourceBlendMode, pDestinationBlendMode); @@ -528,7 +534,7 @@ public void blendFunction(final int pSourceBlendMode, final int pDestinationBlen } public void lineWidth(final float pLineWidth) { - if(this.mLineWidth != pLineWidth) { + if (this.mLineWidth != pLineWidth) { this.mLineWidth = pLineWidth; GLES20.glLineWidth(pLineWidth); } @@ -626,6 +632,14 @@ public void resetGLMatrixStacks() { this.mProjectionGLMatrixStack.reset(); } + public void glPushScissor(final int pX, final int pY, final int pWidth, final int pHeight) { + this.mScissorStack.glPushScissor(pX, pY, pWidth, pHeight); + } + + public void glPopScissor() { + this.mScissorStack.glPopScissor(); + } + /** * Note: does not pre-multiply the alpha channel!
    * Except that difference, same as: {@link GLUtils#texSubImage2D(int, int, int, int, Bitmap, int, int)}
    @@ -654,7 +668,7 @@ public void glTexSubImage2D(final int pTarget, final int pLevel, final int pX, f /** * Tells the OpenGL driver to send all pending commands to the GPU immediately. * - * @see {@link GLState#finish()}, + * @see {@link #finish()}, * {@link RenderTexture#end(GLState, boolean, boolean)}. */ public void flush() { @@ -666,7 +680,7 @@ public void flush() { * and then blocks until the effects of those commands have been completed on the GPU. * Since this is a costly method it should be only called when really needed. * - * @see {@link GLState#flush()}, + * @see {@link #flush()}, * {@link RenderTexture#end(GLState, boolean, boolean)}. */ public void finish() { @@ -684,7 +698,7 @@ public int getError() { public void checkError() throws GLException { final int error = GLES20.glGetError(); - if(error != GLES20.GL_NO_ERROR) { + if (error != GLES20.GL_NO_ERROR) { throw new GLException(error); } } diff --git a/src/org/andengine/opengl/util/VertexUtils.java b/src/org/andengine/opengl/util/VertexUtils.java index 2f031b27e..4066da277 100644 --- a/src/org/andengine/opengl/util/VertexUtils.java +++ b/src/org/andengine/opengl/util/VertexUtils.java @@ -1,7 +1,7 @@ package org.andengine.opengl.util; /** - * (c) Zynga 2012 + * (c) 2012 Zynga Inc. * * @author Nicolas Gramlich * @since 11:18:30 - 10.02.2012 @@ -36,7 +36,7 @@ public class VertexUtils { * @param pVertexOffset * @param pVertexStride * @param pVertexIndex - * @return the value of the pVertexOffset-th attribute of the pVertexIndex-th vertex. + * @return the value of the pVertexOffset-th attribute of the pVertexIndex-th vertex. */ public static float getVertex(final float[] pVertices, final int pVertexOffset, final int pVertexStride, final int pVertexIndex) { return pVertices[(pVertexIndex * pVertexStride) + pVertexOffset]; diff --git a/src/org/andengine/opengl/util/criteria/AndroidVersionCodeGLCriteria.java b/src/org/andengine/opengl/util/criteria/AndroidVersionCodeGLCriteria.java index 720ad91dd..10bc2bca7 100644 --- a/src/org/andengine/opengl/util/criteria/AndroidVersionCodeGLCriteria.java +++ b/src/org/andengine/opengl/util/criteria/AndroidVersionCodeGLCriteria.java @@ -6,7 +6,7 @@ import android.os.Build; /** - * (c) Zynga 2011 + * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 17:21:13 - 10.10.2011 diff --git a/src/org/andengine/opengl/util/criteria/BuildModelGLCriteria.java b/src/org/andengine/opengl/util/criteria/BuildModelGLCriteria.java index a95a582b9..9e4274398 100644 --- a/src/org/andengine/opengl/util/criteria/BuildModelGLCriteria.java +++ b/src/org/andengine/opengl/util/criteria/BuildModelGLCriteria.java @@ -6,7 +6,7 @@ import android.os.Build; /** - * (c) Zynga 2011 + * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 17:25:47 - 10.10.2011 diff --git a/src/org/andengine/opengl/util/criteria/GLExtensionsGLCriteria.java b/src/org/andengine/opengl/util/criteria/GLExtensionsGLCriteria.java index d66a4f901..4f8cb2a64 100644 --- a/src/org/andengine/opengl/util/criteria/GLExtensionsGLCriteria.java +++ b/src/org/andengine/opengl/util/criteria/GLExtensionsGLCriteria.java @@ -4,7 +4,7 @@ import org.andengine.util.adt.data.operator.StringOperator; /** - * (c) Zynga 2011 + * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 21:02:01 - 10.10.2011 diff --git a/src/org/andengine/opengl/util/criteria/GLRendererGLCriteria.java b/src/org/andengine/opengl/util/criteria/GLRendererGLCriteria.java index 09d68f58f..4cf5161bd 100644 --- a/src/org/andengine/opengl/util/criteria/GLRendererGLCriteria.java +++ b/src/org/andengine/opengl/util/criteria/GLRendererGLCriteria.java @@ -4,7 +4,7 @@ import org.andengine.util.adt.data.operator.StringOperator; /** - * (c) Zynga 2011 + * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 17:04:27 - 10.10.2011 diff --git a/src/org/andengine/opengl/util/criteria/GLVersionGLCriteria.java b/src/org/andengine/opengl/util/criteria/GLVersionGLCriteria.java index 0ba3a0a2d..35bd17a99 100644 --- a/src/org/andengine/opengl/util/criteria/GLVersionGLCriteria.java +++ b/src/org/andengine/opengl/util/criteria/GLVersionGLCriteria.java @@ -4,7 +4,7 @@ import org.andengine.util.adt.data.operator.StringOperator; /** - * (c) Zynga 2011 + * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 16:52:33 - 10.10.2011 diff --git a/src/org/andengine/opengl/util/criteria/IGLCriteria.java b/src/org/andengine/opengl/util/criteria/IGLCriteria.java index 9d5dea5ec..5034c9ebf 100644 --- a/src/org/andengine/opengl/util/criteria/IGLCriteria.java +++ b/src/org/andengine/opengl/util/criteria/IGLCriteria.java @@ -3,7 +3,7 @@ import org.andengine.opengl.util.GLState; /** - * (c) Zynga 2011 + * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 16:43:34 - 10.10.2011 diff --git a/src/org/andengine/opengl/util/criteria/IntGLCriteria.java b/src/org/andengine/opengl/util/criteria/IntGLCriteria.java index 84ec11bb8..62029d473 100644 --- a/src/org/andengine/opengl/util/criteria/IntGLCriteria.java +++ b/src/org/andengine/opengl/util/criteria/IntGLCriteria.java @@ -4,7 +4,7 @@ import org.andengine.util.adt.data.operator.IntOperator; /** - * (c) Zynga 2011 + * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 16:59:32 - 10.10.2011 diff --git a/src/org/andengine/opengl/util/criteria/LogicalAndGLCriteria.java b/src/org/andengine/opengl/util/criteria/LogicalAndGLCriteria.java index 8e8511f3b..2bfd55a3b 100644 --- a/src/org/andengine/opengl/util/criteria/LogicalAndGLCriteria.java +++ b/src/org/andengine/opengl/util/criteria/LogicalAndGLCriteria.java @@ -3,7 +3,7 @@ import org.andengine.opengl.util.GLState; /** - * (c) Zynga 2011 + * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 18:15:55 - 12.10.2011 @@ -37,8 +37,8 @@ public LogicalAndGLCriteria(final IGLCriteria ... pGLCriterias) { @Override public boolean isMet(final GLState pGLState) { - for(final IGLCriteria gLCriteria : this.mGLCriterias) { - if(!gLCriteria.isMet(pGLState)) { + for (final IGLCriteria gLCriteria : this.mGLCriterias) { + if (!gLCriteria.isMet(pGLState)) { return false; } } diff --git a/src/org/andengine/opengl/util/criteria/LogicalOrGLCriteria.java b/src/org/andengine/opengl/util/criteria/LogicalOrGLCriteria.java index d21aa86e2..2db011646 100644 --- a/src/org/andengine/opengl/util/criteria/LogicalOrGLCriteria.java +++ b/src/org/andengine/opengl/util/criteria/LogicalOrGLCriteria.java @@ -3,7 +3,7 @@ import org.andengine.opengl.util.GLState; /** - * (c) Zynga 2011 + * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 18:10:26 - 12.10.2011 @@ -37,8 +37,8 @@ public LogicalOrGLCriteria(final IGLCriteria ... pGLCriterias) { @Override public boolean isMet(final GLState pGLState) { - for(final IGLCriteria gLCriteria : this.mGLCriterias) { - if(gLCriteria.isMet(pGLState)) { + for (final IGLCriteria gLCriteria : this.mGLCriterias) { + if (gLCriteria.isMet(pGLState)) { return true; } } diff --git a/src/org/andengine/opengl/util/criteria/StringGLCriteria.java b/src/org/andengine/opengl/util/criteria/StringGLCriteria.java index 12bd2599a..400bd3664 100644 --- a/src/org/andengine/opengl/util/criteria/StringGLCriteria.java +++ b/src/org/andengine/opengl/util/criteria/StringGLCriteria.java @@ -4,7 +4,7 @@ import org.andengine.util.adt.data.operator.StringOperator; /** - * (c) Zynga 2011 + * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 16:59:32 - 10.10.2011 diff --git a/src/org/andengine/opengl/vbo/DrawType.java b/src/org/andengine/opengl/vbo/DrawType.java index d932fe311..ae166bc4f 100644 --- a/src/org/andengine/opengl/vbo/DrawType.java +++ b/src/org/andengine/opengl/vbo/DrawType.java @@ -3,7 +3,7 @@ import android.opengl.GLES20; /** - * (c) Zynga 2012 + * (c) 2012 Zynga Inc. * * @author Nicolas Gramlich * @since 15:41:14 - 27.03.2012 diff --git a/src/org/andengine/opengl/vbo/HighPerformanceVertexBufferObject.java b/src/org/andengine/opengl/vbo/HighPerformanceVertexBufferObject.java index df7b8acd8..72f8aa9fb 100644 --- a/src/org/andengine/opengl/vbo/HighPerformanceVertexBufferObject.java +++ b/src/org/andengine/opengl/vbo/HighPerformanceVertexBufferObject.java @@ -9,12 +9,12 @@ import android.opengl.GLES20; /** - * Compared to a {@link LowMemoryVertexBufferObject}, the {@link HighPerformanceVertexBufferObject} uses 2x the heap memory, + * Compared to a {@link LowMemoryVertexBufferObject}, the {@link HighPerformanceVertexBufferObject} uses 2x the heap memory, * at the benefit of significantly faster data buffering (up to 5x faster!). - * + * * @see {@link LowMemoryVertexBufferObject} when to prefer a {@link LowMemoryVertexBufferObject} instead of a {@link HighPerformanceVertexBufferObject} * - *

    (c) Zynga 2011

    + *

    (c) 2011 Zynga Inc.

    * * @author Nicolas Gramlich * @since 14:42:18 - 15.11.2011 @@ -39,7 +39,7 @@ public HighPerformanceVertexBufferObject(final VertexBufferObjectManager pVertex super(pVertexBufferObjectManager, pCapacity, pDrawType, pAutoDispose, pVertexBufferObjectAttributes); this.mBufferData = new float[pCapacity]; - if(SystemUtils.SDK_VERSION_HONEYCOMB_OR_LATER) { + if (SystemUtils.SDK_VERSION_HONEYCOMB_OR_LATER) { this.mFloatBuffer = this.mByteBuffer.asFloatBuffer(); } else { this.mFloatBuffer = null; @@ -49,8 +49,8 @@ public HighPerformanceVertexBufferObject(final VertexBufferObjectManager pVertex public HighPerformanceVertexBufferObject(final VertexBufferObjectManager pVertexBufferObjectManager, final float[] pBufferData, final DrawType pDrawType, final boolean pAutoDispose, final VertexBufferObjectAttributes pVertexBufferObjectAttributes) { super(pVertexBufferObjectManager, pBufferData.length, pDrawType, pAutoDispose, pVertexBufferObjectAttributes); this.mBufferData = pBufferData; - - if(SystemUtils.SDK_VERSION_HONEYCOMB_OR_LATER) { + + if (SystemUtils.SDK_VERSION_HONEYCOMB_OR_LATER) { this.mFloatBuffer = this.mByteBuffer.asFloatBuffer(); } else { this.mFloatBuffer = null; @@ -82,7 +82,7 @@ public int getNativeHeapMemoryByteSize() { @Override protected void onBufferData() { // TODO Check if, and how mow this condition affects performance. - if(SystemUtils.SDK_VERSION_HONEYCOMB_OR_LATER) { + if (SystemUtils.SDK_VERSION_HONEYCOMB_OR_LATER) { // TODO Check if this is similar fast or faster than the non Honeycomb codepath. this.mFloatBuffer.position(0); this.mFloatBuffer.put(this.mBufferData); diff --git a/src/org/andengine/opengl/vbo/IVertexBufferObject.java b/src/org/andengine/opengl/vbo/IVertexBufferObject.java index aa7023c7b..67560efca 100644 --- a/src/org/andengine/opengl/vbo/IVertexBufferObject.java +++ b/src/org/andengine/opengl/vbo/IVertexBufferObject.java @@ -7,7 +7,7 @@ import org.andengine.util.IDisposable; /** - * (c) Zynga 2011 + * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 14:32:10 - 15.11.2011 diff --git a/src/org/andengine/opengl/vbo/LowMemoryVertexBufferObject.java b/src/org/andengine/opengl/vbo/LowMemoryVertexBufferObject.java index f648d9615..0b0fc4dc1 100644 --- a/src/org/andengine/opengl/vbo/LowMemoryVertexBufferObject.java +++ b/src/org/andengine/opengl/vbo/LowMemoryVertexBufferObject.java @@ -7,17 +7,17 @@ import android.opengl.GLES20; /** - * Compared to a {@link HighPerformanceVertexBufferObject}, the {@link LowMemoryVertexBufferObject} uses 50% less heap memory, + * Compared to a {@link HighPerformanceVertexBufferObject}, the {@link LowMemoryVertexBufferObject} uses 50% less heap memory, * at the cost of significantly slower data buffering (up to 5x slower!). - * + * * Usually a {@link LowMemoryVertexBufferObject} is preferred to a {@link HighPerformanceVertexBufferObject} when the following conditions are met: *
      *
    1. The applications is close to run out of memory.
    2. *
    3. You have very big {@link HighPerformanceVertexBufferObject} or an extreme number of small {@link HighPerformanceVertexBufferObject}s, where a 50% heap memory reduction would actually be significant.
    4. - *
    5. The content (color, vertices, texturecoordinates) of the {@link LowMemoryVertexBufferObject} is changed not often, or even better: never.
    6. + *
    7. The content (color, vertices, texturecoordinates) of the {@link LowMemoryVertexBufferObject} is changed not often, or even better: never.
    8. *
    * - * (c) Zynga 2011 + * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 14:42:18 - 15.11.2011 diff --git a/src/org/andengine/opengl/vbo/SharedMemoryVertexBufferObject.java b/src/org/andengine/opengl/vbo/SharedMemoryVertexBufferObject.java index 2de8b26e2..87306405b 100644 --- a/src/org/andengine/opengl/vbo/SharedMemoryVertexBufferObject.java +++ b/src/org/andengine/opengl/vbo/SharedMemoryVertexBufferObject.java @@ -16,7 +16,7 @@ *
  • Minimum amount of runtime GarbageCollector activity.
  • * *

    - * (c) Zynga 2011 + * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @author Greg Haynes @@ -36,7 +36,7 @@ public static int getSharedByteBufferByteCapacity() { SharedMemoryVertexBufferObject.sSharedByteBufferLock.lock(); final ByteBuffer sharedByteBuffer = SharedMemoryVertexBufferObject.sSharedByteBuffer; - if(sharedByteBuffer == null) { + if (sharedByteBuffer == null) { byteCapacity = 0; } else { byteCapacity = sharedByteBuffer.capacity(); @@ -74,8 +74,8 @@ public void dispose() { try { SharedMemoryVertexBufferObject.sSharedByteBufferLock.lock(); - - if(SharedMemoryVertexBufferObject.sSharedByteBuffer != null) { + + if (SharedMemoryVertexBufferObject.sSharedByteBuffer != null) { BufferUtils.freeDirectByteBuffer(SharedMemoryVertexBufferObject.sSharedByteBuffer); SharedMemoryVertexBufferObject.sSharedByteBuffer = null; @@ -91,8 +91,8 @@ protected ByteBuffer aquireByteBuffer() { final int byteCapacity = this.getByteCapacity(); - if(SharedMemoryVertexBufferObject.sSharedByteBuffer == null || SharedMemoryVertexBufferObject.sSharedByteBuffer.capacity() < byteCapacity) { - if(SharedMemoryVertexBufferObject.sSharedByteBuffer != null) { + if (SharedMemoryVertexBufferObject.sSharedByteBuffer == null || SharedMemoryVertexBufferObject.sSharedByteBuffer.capacity() < byteCapacity) { + if (SharedMemoryVertexBufferObject.sSharedByteBuffer != null) { BufferUtils.freeDirectByteBuffer(SharedMemoryVertexBufferObject.sSharedByteBuffer); } diff --git a/src/org/andengine/opengl/vbo/VertexBufferObject.java b/src/org/andengine/opengl/vbo/VertexBufferObject.java index b91b944a6..da576770a 100644 --- a/src/org/andengine/opengl/vbo/VertexBufferObject.java +++ b/src/org/andengine/opengl/vbo/VertexBufferObject.java @@ -7,17 +7,17 @@ import org.andengine.opengl.util.BufferUtils; import org.andengine.opengl.util.GLState; import org.andengine.opengl.vbo.attribute.VertexBufferObjectAttributes; -import org.andengine.util.adt.DataConstants; +import org.andengine.util.adt.data.constants.DataConstants; import android.opengl.GLES20; /** * TODO Extract a common base class from {@link VertexBufferObject} and {@link ZeroMemoryVertexBufferObject} (due to significant code duplication). - * For naming, maybe be inspired by the java ByteBuffer naming (i.e. HeapBackedFloatArrayVertexBufferObject, StreamBufferVertexBufferObject, SharedBufferStreamVertexBufferObject). + * For naming, maybe be inspired by the java ByteBuffer naming (i.e. HeapBackedFloatArrayVertexBufferObject, StreamBufferVertexBufferObject, SharedBufferStreamVertexBufferObject). * * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 14:22:56 - 07.04.2010 */ @@ -48,11 +48,11 @@ public abstract class VertexBufferObject implements IVertexBufferObject { // =========================================================== /** - * @param pVertexBufferObjectManager + * @param pVertexBufferObjectManager (Optional, if you manage reloading on your own.) * @param pCapacity * @param pDrawType * @param pAutoDispose when passing true this {@link VertexBufferObject} loads itself to the active {@link VertexBufferObjectManager}. WARNING: When passing false one needs to take care of that by oneself! - * @param pVertexBufferObjectAttributes to be automatically enabled on the {@link ShaderProgram} used in {@link VertexBufferObject#bind(ShaderProgram)}. + * @param pVertexBufferObjectAttributes to be automatically enabled on the {@link ShaderProgram} used in {@link #bind(ShaderProgram)}. */ public VertexBufferObject(final VertexBufferObjectManager pVertexBufferObjectManager, final int pCapacity, final DrawType pDrawType, final boolean pAutoDispose, final VertexBufferObjectAttributes pVertexBufferObjectAttributes) { this.mVertexBufferObjectManager = pVertexBufferObjectManager; @@ -123,7 +123,7 @@ public int getByteCapacity() { @Override public int getGPUMemoryByteSize() { - if(this.isLoadedToHardware()) { + if (this.isLoadedToHardware()) { return this.getByteCapacity(); } else { return 0; @@ -138,15 +138,17 @@ public int getGPUMemoryByteSize() { @Override public void bind(final GLState pGLState) { - if(this.mHardwareBufferID == IVertexBufferObject.HARDWARE_BUFFER_ID_INVALID) { + if (this.mHardwareBufferID == IVertexBufferObject.HARDWARE_BUFFER_ID_INVALID) { this.loadToHardware(pGLState); - this.mVertexBufferObjectManager.onVertexBufferObjectLoaded(this); + if (this.mVertexBufferObjectManager != null) { + this.mVertexBufferObjectManager.onVertexBufferObjectLoaded(this); + } } pGLState.bindArrayBuffer(this.mHardwareBufferID); - if(this.mDirtyOnHardware) { + if (this.mDirtyOnHardware) { this.onBufferData(); this.mDirtyOnHardware = false; @@ -187,10 +189,12 @@ public void draw(final int pPrimitiveType, final int pOffset, final int pCount) @Override public void dispose() { - if(!this.mDisposed) { + if (!this.mDisposed) { this.mDisposed = true; - this.mVertexBufferObjectManager.onUnloadVertexBufferObject(this); + if (this.mVertexBufferObjectManager != null) { + this.mVertexBufferObjectManager.onUnloadVertexBufferObject(this); + } BufferUtils.freeDirectByteBuffer(this.mByteBuffer); } else { @@ -202,7 +206,7 @@ public void dispose() { protected void finalize() throws Throwable { super.finalize(); - if(!this.mDisposed) { + if (!this.mDisposed) { this.dispose(); } } diff --git a/src/org/andengine/opengl/vbo/VertexBufferObjectManager.java b/src/org/andengine/opengl/vbo/VertexBufferObjectManager.java index 0c9762093..64290e2be 100644 --- a/src/org/andengine/opengl/vbo/VertexBufferObjectManager.java +++ b/src/org/andengine/opengl/vbo/VertexBufferObjectManager.java @@ -35,7 +35,7 @@ public class VertexBufferObjectManager { public synchronized int getHeapMemoryByteSize() { int byteSize = 0; final ArrayList vertexBufferObjectsLoaded = this.mVertexBufferObjectsLoaded; - for(int i = vertexBufferObjectsLoaded.size() - 1; i >= 0; i--) { + for (int i = vertexBufferObjectsLoaded.size() - 1; i >= 0; i--) { byteSize += vertexBufferObjectsLoaded.get(i).getHeapMemoryByteSize(); } return byteSize; @@ -44,7 +44,7 @@ public synchronized int getHeapMemoryByteSize() { public synchronized int getNativeHeapMemoryByteSize() { int byteSize = 0; final ArrayList vertexBufferObjectsLoaded = this.mVertexBufferObjectsLoaded; - for(int i = vertexBufferObjectsLoaded.size() - 1; i >= 0; i--) { + for (int i = vertexBufferObjectsLoaded.size() - 1; i >= 0; i--) { byteSize += vertexBufferObjectsLoaded.get(i).getNativeHeapMemoryByteSize(); } return byteSize; @@ -53,7 +53,7 @@ public synchronized int getNativeHeapMemoryByteSize() { public synchronized int getGPUHeapMemoryByteSize() { int byteSize = 0; final ArrayList vertexBufferObjectsLoaded = this.mVertexBufferObjectsLoaded; - for(int i = vertexBufferObjectsLoaded.size() - 1; i >= 0; i--) { + for (int i = vertexBufferObjectsLoaded.size() - 1; i >= 0; i--) { byteSize += vertexBufferObjectsLoaded.get(i).getGPUMemoryByteSize(); } return byteSize; @@ -73,7 +73,7 @@ public void onCreate() { public synchronized void onDestroy() { final ArrayList vertexBufferObjectsLoaded = this.mVertexBufferObjectsLoaded; - for(int i = vertexBufferObjectsLoaded.size() - 1; i >= 0; i--) { + for (int i = vertexBufferObjectsLoaded.size() - 1; i >= 0; i--) { vertexBufferObjectsLoaded.get(i).setNotLoadedToHardware(); } @@ -85,14 +85,14 @@ public synchronized void onVertexBufferObjectLoaded(final IVertexBufferObject pV } public synchronized void onUnloadVertexBufferObject(final IVertexBufferObject pVertexBufferObject) { - if(this.mVertexBufferObjectsLoaded.remove(pVertexBufferObject)) { + if (this.mVertexBufferObjectsLoaded.remove(pVertexBufferObject)) { this.mVertexBufferObjectsToBeUnloaded.add(pVertexBufferObject); } } public synchronized void onReload() { final ArrayList vertexBufferObjectsLoaded = this.mVertexBufferObjectsLoaded; - for(int i = vertexBufferObjectsLoaded.size() - 1; i >= 0; i--) { + for (int i = vertexBufferObjectsLoaded.size() - 1; i >= 0; i--) { vertexBufferObjectsLoaded.get(i).setNotLoadedToHardware(); } @@ -104,9 +104,9 @@ public synchronized void updateVertexBufferObjects(final GLState pGLState) { final ArrayList vertexBufferObjectsToBeUnloaded = this.mVertexBufferObjectsToBeUnloaded; /* Unload pending VertexBufferObjects. */ - for(int i = vertexBufferObjectsToBeUnloaded.size() - 1; i >= 0; i--){ + for (int i = vertexBufferObjectsToBeUnloaded.size() - 1; i >= 0; i--) { final IVertexBufferObject vertexBufferObjectToBeUnloaded = vertexBufferObjectsToBeUnloaded.remove(i); - if(vertexBufferObjectToBeUnloaded.isLoadedToHardware()){ + if (vertexBufferObjectToBeUnloaded.isLoadedToHardware()) { vertexBufferObjectToBeUnloaded.unloadFromHardware(pGLState); } vertexBufferObjectsLoaded.remove(vertexBufferObjectToBeUnloaded); diff --git a/src/org/andengine/opengl/vbo/ZeroMemoryVertexBufferObject.java b/src/org/andengine/opengl/vbo/ZeroMemoryVertexBufferObject.java index 3617267c7..0a72376f9 100644 --- a/src/org/andengine/opengl/vbo/ZeroMemoryVertexBufferObject.java +++ b/src/org/andengine/opengl/vbo/ZeroMemoryVertexBufferObject.java @@ -7,7 +7,7 @@ import org.andengine.opengl.util.BufferUtils; import org.andengine.opengl.util.GLState; import org.andengine.opengl.vbo.attribute.VertexBufferObjectAttributes; -import org.andengine.util.adt.DataConstants; +import org.andengine.util.adt.data.constants.DataConstants; import android.opengl.GLES20; @@ -22,7 +22,7 @@ *

  • The content (color, vertices, texturecoordinates) of the {@link ZeroMemoryVertexBufferObject} is changed not often, or even better: never.
  • * *

    - * (c) Zynga 2011 + * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @author Greg Haynes @@ -128,7 +128,7 @@ public int getNativeHeapMemoryByteSize() { @Override public int getGPUMemoryByteSize() { - if(this.isLoadedToHardware()) { + if (this.isLoadedToHardware()) { return this.getByteCapacity(); } else { return 0; @@ -139,27 +139,27 @@ public int getGPUMemoryByteSize() { // Methods for/from SuperClass/Interfaces // =========================================================== - protected abstract void onPopulateBufferData(final ByteBuffer byteBuffer); + protected abstract void onPopulateBufferData(final ByteBuffer pByteBuffer); @Override public void bind(final GLState pGLState) { - if(this.mHardwareBufferID == IVertexBufferObject.HARDWARE_BUFFER_ID_INVALID) { + if (this.mHardwareBufferID == IVertexBufferObject.HARDWARE_BUFFER_ID_INVALID) { this.loadToHardware(pGLState); this.mVertexBufferObjectManager.onVertexBufferObjectLoaded(this); } pGLState.bindArrayBuffer(this.mHardwareBufferID); - if(this.mDirtyOnHardware) { + if (this.mDirtyOnHardware) { ByteBuffer byteBuffer = null; try { byteBuffer = this.aquireByteBuffer(); this.onPopulateBufferData(byteBuffer); - + GLES20.glBufferData(GLES20.GL_ARRAY_BUFFER, byteBuffer.limit(), byteBuffer, this.mUsage); } finally { - if(byteBuffer != null) { + if (byteBuffer != null) { this.releaseByteBuffer(byteBuffer); } } @@ -201,7 +201,7 @@ public void draw(final int pPrimitiveType, final int pOffset, final int pCount) @Override public void dispose() { - if(!this.mDisposed) { + if (!this.mDisposed) { this.mDisposed = true; this.mVertexBufferObjectManager.onUnloadVertexBufferObject(this); @@ -214,7 +214,7 @@ public void dispose() { protected void finalize() throws Throwable { super.finalize(); - if(!this.mDisposed) { + if (!this.mDisposed) { this.dispose(); } } @@ -229,8 +229,8 @@ private void loadToHardware(final GLState pGLState) { } /** - * When a non null {@link ByteBuffer} is returned by this function, it is guaranteed that {@link ZeroMemoryVertexBufferObject#releaseByteBuffer(ByteBuffer)} is called. - * @return a {@link ByteBuffer} to be passed to {@link ZeroMemoryVertexBufferObject#onPopulateBufferData(ByteBuffer)}. + * When a non null {@link ByteBuffer} is returned by this function, it is guaranteed that {@link #releaseByteBuffer(ByteBuffer)} is called. + * @return a {@link ByteBuffer} to be passed to {@link #onPopulateBufferData(ByteBuffer)}. */ protected ByteBuffer aquireByteBuffer() { final ByteBuffer byteBuffer = BufferUtils.allocateDirectByteBuffer(this.getByteCapacity()); @@ -238,8 +238,8 @@ protected ByteBuffer aquireByteBuffer() { return byteBuffer; } - protected void releaseByteBuffer(final ByteBuffer byteBuffer) { - BufferUtils.freeDirectByteBuffer(byteBuffer); + protected void releaseByteBuffer(final ByteBuffer pByteBuffer) { + BufferUtils.freeDirectByteBuffer(pByteBuffer); } // =========================================================== diff --git a/src/org/andengine/opengl/vbo/attribute/VertexBufferObjectAttribute.java b/src/org/andengine/opengl/vbo/attribute/VertexBufferObjectAttribute.java index 0c2bad7e2..d1d525544 100644 --- a/src/org/andengine/opengl/vbo/attribute/VertexBufferObjectAttribute.java +++ b/src/org/andengine/opengl/vbo/attribute/VertexBufferObjectAttribute.java @@ -3,7 +3,7 @@ import android.opengl.GLES20; /** - * (c) Zynga 2011 + * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 13:57:13 - 15.08.2011 diff --git a/src/org/andengine/opengl/vbo/attribute/VertexBufferObjectAttributeFix.java b/src/org/andengine/opengl/vbo/attribute/VertexBufferObjectAttributeFix.java index 2715b677b..719db1d03 100644 --- a/src/org/andengine/opengl/vbo/attribute/VertexBufferObjectAttributeFix.java +++ b/src/org/andengine/opengl/vbo/attribute/VertexBufferObjectAttributeFix.java @@ -3,8 +3,8 @@ import org.andengine.opengl.GLES20Fix; /** - * The {@link VertexBufferObjectAttributeFix} is a special - * (c) Zynga 2012 + * The {@link VertexBufferObjectAttributeFix} is a special + * (c) 2012 Zynga Inc. * * @author Nicolas Gramlich * @since 12:52:33 - 08.03.2012 diff --git a/src/org/andengine/opengl/vbo/attribute/VertexBufferObjectAttributes.java b/src/org/andengine/opengl/vbo/attribute/VertexBufferObjectAttributes.java index 2843d79f9..0496763e5 100644 --- a/src/org/andengine/opengl/vbo/attribute/VertexBufferObjectAttributes.java +++ b/src/org/andengine/opengl/vbo/attribute/VertexBufferObjectAttributes.java @@ -2,7 +2,7 @@ /** - * (c) Zynga 2011 + * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 14:22:06 - 15.08.2011 @@ -46,7 +46,7 @@ public void glVertexAttribPointers() { final int stride = this.mStride; final int vertexBufferObjectAttributeCount = vertexBufferObjectAttributes.length; - for(int i = 0; i < vertexBufferObjectAttributeCount; i++) { + for (int i = 0; i < vertexBufferObjectAttributeCount; i++) { vertexBufferObjectAttributes[i].glVertexAttribPointer(stride); } } diff --git a/src/org/andengine/opengl/vbo/attribute/VertexBufferObjectAttributesBuilder.java b/src/org/andengine/opengl/vbo/attribute/VertexBufferObjectAttributesBuilder.java index 2b9098a57..c2bb6e780 100644 --- a/src/org/andengine/opengl/vbo/attribute/VertexBufferObjectAttributesBuilder.java +++ b/src/org/andengine/opengl/vbo/attribute/VertexBufferObjectAttributesBuilder.java @@ -1,6 +1,6 @@ package org.andengine.opengl.vbo.attribute; -import org.andengine.util.adt.DataConstants; +import org.andengine.util.adt.data.constants.DataConstants; import org.andengine.util.exception.AndEngineRuntimeException; import org.andengine.util.system.SystemUtils; @@ -8,7 +8,7 @@ import android.os.Build; /** - * (c) Zynga 2011 + * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 13:58:05 - 15.08.2011 @@ -55,13 +55,13 @@ public VertexBufferObjectAttributesBuilder(final int pCount) { // =========================================================== public VertexBufferObjectAttributesBuilder add(final int pLocation, final String pName, final int pSize, final int pType, final boolean pNormalized) { - if(VertexBufferObjectAttributesBuilder.WORAROUND_GLES2_GLVERTEXATTRIBPOINTER_MISSING) { + if (VertexBufferObjectAttributesBuilder.WORAROUND_GLES2_GLVERTEXATTRIBPOINTER_MISSING) { this.mVertexBufferObjectAttributes[this.mIndex] = new VertexBufferObjectAttributeFix(pLocation, pName, pSize, pType, pNormalized, this.mOffset); } else { this.mVertexBufferObjectAttributes[this.mIndex] = new VertexBufferObjectAttribute(pLocation, pName, pSize, pType, pNormalized, this.mOffset); } - switch(pType) { + switch (pType) { case GLES20.GL_FLOAT: this.mOffset += pSize * DataConstants.BYTES_PER_FLOAT; break; @@ -78,7 +78,7 @@ public VertexBufferObjectAttributesBuilder add(final int pLocation, final String } public VertexBufferObjectAttributes build() { - if(this.mIndex != this.mVertexBufferObjectAttributes.length) { + if (this.mIndex != this.mVertexBufferObjectAttributes.length) { throw new AndEngineRuntimeException("Not enough " + VertexBufferObjectAttribute.class.getSimpleName() + "s added to this " + this.getClass().getSimpleName() + "."); } diff --git a/src/org/andengine/opengl/view/ConfigChooser.java b/src/org/andengine/opengl/view/ConfigChooser.java index a1ccfe157..680ec38c1 100644 --- a/src/org/andengine/opengl/view/ConfigChooser.java +++ b/src/org/andengine/opengl/view/ConfigChooser.java @@ -4,10 +4,12 @@ import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.egl.EGLDisplay; +import org.andengine.engine.options.ConfigChooserOptions; + import android.opengl.GLSurfaceView; /** - * (c) Zynga 2011 + * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 15:31:48 - 04.08.2011 @@ -19,115 +21,159 @@ public class ConfigChooser implements GLSurfaceView.EGLConfigChooser { private static final int[] BUFFER = new int[1]; - private static final int RED_SIZE = 5; - private static final int GREEN_SIZE = 6; - private static final int BLUE_SIZE = 5; - private static final int DEPTH_SIZE = 0; - private static final int ALPHA_SIZE = 0; - private static final int STENCIL_SIZE = 0; - private static final int MULTISAMPLE_COUNT = 2; // TODO Could be made variable? private static final int EGL_GLES2_BIT = 4; - private static final int[] EGLCONFIG_ATTRIBUTES_MULTISAMPLE = { - EGL10.EGL_RED_SIZE, ConfigChooser.RED_SIZE, - EGL10.EGL_GREEN_SIZE, ConfigChooser.GREEN_SIZE, - EGL10.EGL_BLUE_SIZE, ConfigChooser.BLUE_SIZE, - EGL10.EGL_ALPHA_SIZE, ConfigChooser.ALPHA_SIZE, - EGL10.EGL_DEPTH_SIZE, ConfigChooser.DEPTH_SIZE, - EGL10.EGL_STENCIL_SIZE, ConfigChooser.STENCIL_SIZE, - EGL10.EGL_RENDERABLE_TYPE, ConfigChooser.EGL_GLES2_BIT, - EGL10.EGL_SAMPLE_BUFFERS, 1, - EGL10.EGL_SAMPLES, ConfigChooser.MULTISAMPLE_COUNT, - EGL10.EGL_NONE - }; - private static final int EGL_COVERAGE_BUFFERS_NV = 0x30E0; private static final int EGL_COVERAGE_SAMPLES_NV = 0x30E1; - private static final int[] EGLCONFIG_ATTRIBUTES_COVERAGEMULTISAMPLE_NVIDIA = new int[]{ - EGL10.EGL_RED_SIZE, ConfigChooser.RED_SIZE, - EGL10.EGL_GREEN_SIZE, ConfigChooser.GREEN_SIZE, - EGL10.EGL_BLUE_SIZE, ConfigChooser.BLUE_SIZE, - EGL10.EGL_ALPHA_SIZE, ConfigChooser.ALPHA_SIZE, - EGL10.EGL_DEPTH_SIZE, ConfigChooser.DEPTH_SIZE, - EGL10.EGL_STENCIL_SIZE, ConfigChooser.STENCIL_SIZE, - EGL10.EGL_RENDERABLE_TYPE, ConfigChooser.EGL_GLES2_BIT, - ConfigChooser.EGL_COVERAGE_BUFFERS_NV, 1, - ConfigChooser.EGL_COVERAGE_SAMPLES_NV, ConfigChooser.MULTISAMPLE_COUNT, // always 5 in practice on tegra 2 - EGL10.EGL_NONE - }; - - private static final int[] EGLCONFIG_ATTRIBUTES_FALLBACK = new int[] { - EGL10.EGL_RED_SIZE, ConfigChooser.RED_SIZE, - EGL10.EGL_GREEN_SIZE, ConfigChooser.GREEN_SIZE, - EGL10.EGL_BLUE_SIZE, ConfigChooser.BLUE_SIZE, - EGL10.EGL_ALPHA_SIZE, ConfigChooser.ALPHA_SIZE, - EGL10.EGL_DEPTH_SIZE, ConfigChooser.DEPTH_SIZE, - EGL10.EGL_STENCIL_SIZE, ConfigChooser.STENCIL_SIZE, - EGL10.EGL_RENDERABLE_TYPE, ConfigChooser.EGL_GLES2_BIT, - EGL10.EGL_NONE - }; + private final int[] mMultiSampleEGLConfig; + + private final int[] mNvidiaCoverageMultiSampleEGLConfig; + + private final int[] mDefaultEGLConfig; // =========================================================== // Fields // =========================================================== - private final boolean mMultiSamplingRequested; + private final boolean mRequestedMultiSampling; + + private boolean mActualMultiSampling; + private boolean mActualCoverageMultiSampling; - private boolean mMultiSampling; - private boolean mCoverageMultiSampling; + private final int mRequestedRedSize; + private final int mRequestedGreenSize; + private final int mRequestedBlueSize; + private final int mRequestedAlphaSize; + private final int mRequestedDepthSize; + private final int mRequestedStencilSize; - private int mRedSize = -1; - private int mGreenSize = -1; - private int mBlueSize = -1; - private int mAlphaSize = -1; - private int mDepthSize = -1; - private int mStencilSize = -1; + private int mActualRedSize = -1; + private int mActualGreenSize = -1; + private int mActualBlueSize = -1; + private int mActualAlphaSize = -1; + private int mActualDepthSize = -1; + private int mActualStencilSize = -1; // =========================================================== // Constructors // =========================================================== - public ConfigChooser(final boolean pMultiSamplingRequested) { - this.mMultiSamplingRequested = pMultiSamplingRequested; + public ConfigChooser(final ConfigChooserOptions pConfigChooserOptions) { + this(pConfigChooserOptions.getRequestedRedSize(), pConfigChooserOptions.getRequestedGreenSize(), pConfigChooserOptions.getRequestedBlueSize(), pConfigChooserOptions.getRequestedAlphaSize(), pConfigChooserOptions.getRequestedDepthSize(), pConfigChooserOptions.getRequestedStencilSize(), pConfigChooserOptions.isRequestedMultiSampling()); + } + + public ConfigChooser(final int pRequestedRedSize, final int pRequestedGreenSize, final int pRequestedBlueSize, final int pRequestedAlphaSize, final int pRequestedDepthSize, final int pRequestedStencilSize, final boolean pRequestedMultiSampling) { + this.mRequestedRedSize = pRequestedRedSize; + this.mRequestedGreenSize = pRequestedGreenSize; + this.mRequestedBlueSize = pRequestedBlueSize; + this.mRequestedAlphaSize = pRequestedAlphaSize; + this.mRequestedDepthSize = pRequestedDepthSize; + this.mRequestedStencilSize = pRequestedStencilSize; + this.mRequestedMultiSampling = pRequestedMultiSampling; + + this.mMultiSampleEGLConfig = new int[] { + EGL10.EGL_RED_SIZE, pRequestedRedSize, + EGL10.EGL_GREEN_SIZE, pRequestedGreenSize, + EGL10.EGL_BLUE_SIZE, pRequestedBlueSize, + EGL10.EGL_ALPHA_SIZE, pRequestedAlphaSize, + EGL10.EGL_DEPTH_SIZE, pRequestedDepthSize, + EGL10.EGL_STENCIL_SIZE, pRequestedStencilSize, + EGL10.EGL_RENDERABLE_TYPE, ConfigChooser.EGL_GLES2_BIT, + EGL10.EGL_SAMPLE_BUFFERS, 1, + EGL10.EGL_SAMPLES, ConfigChooser.MULTISAMPLE_COUNT, + EGL10.EGL_NONE + }; + + this.mNvidiaCoverageMultiSampleEGLConfig = new int[] { + EGL10.EGL_RED_SIZE, pRequestedRedSize, + EGL10.EGL_GREEN_SIZE, pRequestedGreenSize, + EGL10.EGL_BLUE_SIZE, pRequestedBlueSize, + EGL10.EGL_ALPHA_SIZE, pRequestedAlphaSize, + EGL10.EGL_DEPTH_SIZE, pRequestedDepthSize, + EGL10.EGL_STENCIL_SIZE, pRequestedStencilSize, + EGL10.EGL_RENDERABLE_TYPE, ConfigChooser.EGL_GLES2_BIT, + ConfigChooser.EGL_COVERAGE_BUFFERS_NV, 1, + ConfigChooser.EGL_COVERAGE_SAMPLES_NV, ConfigChooser.MULTISAMPLE_COUNT, + EGL10.EGL_NONE + }; + + this.mDefaultEGLConfig = new int[] { + EGL10.EGL_RED_SIZE, pRequestedRedSize, + EGL10.EGL_GREEN_SIZE, pRequestedGreenSize, + EGL10.EGL_BLUE_SIZE, pRequestedBlueSize, + EGL10.EGL_ALPHA_SIZE, pRequestedAlphaSize, + EGL10.EGL_DEPTH_SIZE, pRequestedDepthSize, + EGL10.EGL_STENCIL_SIZE, pRequestedStencilSize, + EGL10.EGL_RENDERABLE_TYPE, ConfigChooser.EGL_GLES2_BIT, + EGL10.EGL_NONE + }; } // =========================================================== // Getter & Setter // =========================================================== - public boolean isMultiSampling() { - return this.mMultiSampling; + public boolean isRequestedMultiSampling() { + return this.mRequestedMultiSampling; + } + + public boolean isActualMultiSampling() { + return this.mActualMultiSampling; + } + + public boolean isActualCoverageMultiSampling() { + return this.mActualCoverageMultiSampling; + } + + public int getRequestedRedSize() { + return this.mRequestedRedSize; + } + + public int getActualRedSize() { + return this.mActualRedSize; + } + + public int getRequestedGreenSize() { + return this.mRequestedGreenSize; } - public boolean isCoverageMultiSampling() { - return this.mCoverageMultiSampling; + public int getActualGreenSize() { + return this.mActualGreenSize; } - public int getRedSize() { - return this.mRedSize; + public int getRequestedSize() { + return this.mRequestedBlueSize; } - public int getGreenSize() { - return this.mGreenSize; + public int getActualBlueSize() { + return this.mActualBlueSize; } - public int getBlueSize() { - return this.mBlueSize; + public int getRequestedAlphaSize() { + return this.mRequestedAlphaSize; } - public int getAlphaSize() { - return this.mAlphaSize; + public int getActualAlphaSize() { + return this.mActualAlphaSize; } - public int getDepthSize() { - return this.mDepthSize; + public int getRequestedDepthSize() { + return this.mRequestedDepthSize; } - public int getStencilSize() { - return this.mStencilSize; + public int getActualDepthSize() { + return this.mActualDepthSize; + } + + public int getRequestedStencilSize() { + return this.mRequestedStencilSize; + } + + public int getActualStencilSize() { + return this.mActualStencilSize; } // =========================================================== @@ -162,23 +208,23 @@ private EGLConfig chooseConfig(final EGL10 pEGL, final EGLDisplay pEGLDisplay, f int eglConfigCount; - if(this.mMultiSamplingRequested) { - eglConfigCount = this.getEGLConfigCount(pEGL, pEGLDisplay, ConfigChooser.EGLCONFIG_ATTRIBUTES_MULTISAMPLE); - if(eglConfigCount > 0) { - this.mMultiSampling = true; - return this.findEGLConfig(pEGL, pEGLDisplay, ConfigChooser.EGLCONFIG_ATTRIBUTES_MULTISAMPLE, eglConfigCount, pConfigChooserMatcher); + if (this.mRequestedMultiSampling) { + eglConfigCount = this.getEGLConfigCount(pEGL, pEGLDisplay, this.mMultiSampleEGLConfig); + if (eglConfigCount > 0) { + this.mActualMultiSampling = true; + return this.findEGLConfig(pEGL, pEGLDisplay, this.mMultiSampleEGLConfig, eglConfigCount, pConfigChooserMatcher); } - eglConfigCount = this.getEGLConfigCount(pEGL, pEGLDisplay, ConfigChooser.EGLCONFIG_ATTRIBUTES_COVERAGEMULTISAMPLE_NVIDIA); - if(eglConfigCount > 0) { - this.mCoverageMultiSampling = true; - return this.findEGLConfig(pEGL, pEGLDisplay, ConfigChooser.EGLCONFIG_ATTRIBUTES_COVERAGEMULTISAMPLE_NVIDIA, eglConfigCount, pConfigChooserMatcher); + eglConfigCount = this.getEGLConfigCount(pEGL, pEGLDisplay, this.mNvidiaCoverageMultiSampleEGLConfig); + if (eglConfigCount > 0) { + this.mActualCoverageMultiSampling = true; + return this.findEGLConfig(pEGL, pEGLDisplay, this.mNvidiaCoverageMultiSampleEGLConfig, eglConfigCount, pConfigChooserMatcher); } } - eglConfigCount = this.getEGLConfigCount(pEGL, pEGLDisplay, ConfigChooser.EGLCONFIG_ATTRIBUTES_FALLBACK); - if(eglConfigCount > 0) { - return this.findEGLConfig(pEGL, pEGLDisplay, ConfigChooser.EGLCONFIG_ATTRIBUTES_FALLBACK, eglConfigCount, pConfigChooserMatcher); + eglConfigCount = this.getEGLConfigCount(pEGL, pEGLDisplay, this.mDefaultEGLConfig); + if (eglConfigCount > 0) { + return this.findEGLConfig(pEGL, pEGLDisplay, this.mDefaultEGLConfig, eglConfigCount, pConfigChooserMatcher); } else { throw new IllegalArgumentException("No " + EGLConfig.class.getSimpleName() + " found!"); } @@ -189,7 +235,7 @@ private EGLConfig chooseConfig(final EGL10 pEGL, final EGLDisplay pEGLDisplay, f // =========================================================== private int getEGLConfigCount(final EGL10 pEGL, final EGLDisplay pEGLDisplay, final int[] pEGLConfigAttributes) { - if(pEGL.eglChooseConfig(pEGLDisplay, pEGLConfigAttributes, null, 0, ConfigChooser.BUFFER) == false) { + if (pEGL.eglChooseConfig(pEGLDisplay, pEGLConfigAttributes, null, 0, ConfigChooser.BUFFER) == false) { throw new IllegalArgumentException("EGLCONFIG_FALLBACK failed!"); } return ConfigChooser.BUFFER[0]; @@ -197,7 +243,7 @@ private int getEGLConfigCount(final EGL10 pEGL, final EGLDisplay pEGLDisplay, fi private EGLConfig findEGLConfig(final EGL10 pEGL, final EGLDisplay pEGLDisplay, final int[] pEGLConfigAttributes, final int pEGLConfigCount, final ConfigChooserMatcher pConfigChooserMatcher) { final EGLConfig[] eglConfigs = new EGLConfig[pEGLConfigCount]; - if(!pEGL.eglChooseConfig(pEGLDisplay, pEGLConfigAttributes, eglConfigs, pEGLConfigCount, ConfigChooser.BUFFER)) { + if (!pEGL.eglChooseConfig(pEGLDisplay, pEGLConfigAttributes, eglConfigs, pEGLConfigCount, ConfigChooser.BUFFER)) { throw new IllegalArgumentException("findEGLConfig failed!"); } @@ -205,9 +251,9 @@ private EGLConfig findEGLConfig(final EGL10 pEGL, final EGLDisplay pEGLDisplay, } private EGLConfig findEGLConfig(final EGL10 pEGL, final EGLDisplay pEGLDisplay, final EGLConfig[] pEGLConfigs, final ConfigChooserMatcher pConfigChooserMatcher) { - for(int i = 0; i < pEGLConfigs.length; ++i) { + for (int i = 0; i < pEGLConfigs.length; ++i) { final EGLConfig config = pEGLConfigs[i]; - if(config != null) { + if (config != null) { final int redSize = this.getConfigAttrib(pEGL, pEGLDisplay, config, EGL10.EGL_RED_SIZE, 0); final int greenSize = this.getConfigAttrib(pEGL, pEGLDisplay, config, EGL10.EGL_GREEN_SIZE, 0); final int blueSize = this.getConfigAttrib(pEGL, pEGLDisplay, config, EGL10.EGL_BLUE_SIZE, 0); @@ -215,13 +261,13 @@ private EGLConfig findEGLConfig(final EGL10 pEGL, final EGLDisplay pEGLDisplay, final int depthSize = this.getConfigAttrib(pEGL, pEGLDisplay, config, EGL10.EGL_DEPTH_SIZE, 0); final int stencilSize = this.getConfigAttrib(pEGL, pEGLDisplay, config, EGL10.EGL_STENCIL_SIZE, 0); - if(pConfigChooserMatcher.matches(redSize, greenSize, blueSize, alphaSize, depthSize, stencilSize)) { - this.mRedSize = redSize; - this.mGreenSize = greenSize; - this.mBlueSize = blueSize; - this.mAlphaSize = alphaSize; - this.mDepthSize = depthSize; - this.mStencilSize = stencilSize; + if (pConfigChooserMatcher.matches(this.mRequestedRedSize, redSize, this.mRequestedGreenSize, greenSize, this.mRequestedBlueSize, blueSize, this.mRequestedAlphaSize, alphaSize, this.mRequestedDepthSize, depthSize, this.mRequestedStencilSize, stencilSize)) { + this.mActualRedSize = redSize; + this.mActualGreenSize = greenSize; + this.mActualBlueSize = blueSize; + this.mActualAlphaSize = alphaSize; + this.mActualDepthSize = depthSize; + this.mActualStencilSize = stencilSize; return config; } } @@ -230,7 +276,7 @@ private EGLConfig findEGLConfig(final EGL10 pEGL, final EGLDisplay pEGLDisplay, } private int getConfigAttrib(final EGL10 pEGL, final EGLDisplay pEGLDisplay, final EGLConfig pEGLConfig, final int pAttribute, final int pDefaultValue) { - if(pEGL.eglGetConfigAttrib(pEGLDisplay, pEGLConfig, pAttribute, ConfigChooser.BUFFER)) { + if (pEGL.eglGetConfigAttrib(pEGLDisplay, pEGLConfig, pAttribute, ConfigChooser.BUFFER)) { return ConfigChooser.BUFFER[0]; } else { return pDefaultValue; @@ -240,80 +286,4 @@ private int getConfigAttrib(final EGL10 pEGL, final EGLDisplay pEGLDisplay, fina // =========================================================== // Inner and Anonymous Classes // =========================================================== - - public enum ConfigChooserMatcher { - // =========================================================== - // Elements - // =========================================================== - - STRICT() { - @Override - public boolean matches(final int pRedSize, final int pGreenSize, final int pBlueSize, final int pAlphaSize, final int pDepthSize, final int pStencilSize) { - if(pDepthSize == ConfigChooser.DEPTH_SIZE && pStencilSize == ConfigChooser.STENCIL_SIZE) { - if(pRedSize == ConfigChooser.RED_SIZE && pGreenSize == ConfigChooser.GREEN_SIZE && pBlueSize == ConfigChooser.BLUE_SIZE && pAlphaSize == ConfigChooser.ALPHA_SIZE) { - return true; - } - } - return false; - } - }, - LOOSE_STENCIL() { - @Override - public boolean matches(final int pRedSize, final int pGreenSize, final int pBlueSize, final int pAlphaSize, final int pDepthSize, final int pStencilSize) { - if(pDepthSize == ConfigChooser.DEPTH_SIZE && pStencilSize >= ConfigChooser.STENCIL_SIZE) { - if(pRedSize == ConfigChooser.RED_SIZE && pGreenSize == ConfigChooser.GREEN_SIZE && pBlueSize == ConfigChooser.BLUE_SIZE && pAlphaSize == ConfigChooser.ALPHA_SIZE) { - return true; - } - } - return false; - } - }, - LOOSE_DEPTH_AND_STENCIL() { - @Override - public boolean matches(final int pRedSize, final int pGreenSize, final int pBlueSize, final int pAlphaSize, final int pDepthSize, final int pStencilSize) { - if(pDepthSize >= ConfigChooser.DEPTH_SIZE && pStencilSize >= ConfigChooser.STENCIL_SIZE) { - if(pRedSize == ConfigChooser.RED_SIZE && pGreenSize == ConfigChooser.GREEN_SIZE && pBlueSize == ConfigChooser.BLUE_SIZE && pAlphaSize == ConfigChooser.ALPHA_SIZE) { - return true; - } - } - return false; - } - }, - ANY() { - @Override - public boolean matches(final int pRedSize, final int pGreenSize, final int pBlueSize, final int pAlphaSize, final int pDepthSize, final int pStencilSize) { - return true; - } - }; - - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - // =========================================================== - // Constructors - // =========================================================== - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - public abstract boolean matches(final int pRedSize, final int pGreenSize, final int pBlueSize, final int pAlphaSize, final int pDepthSize, final int pStencilSize); - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== - } } \ No newline at end of file diff --git a/src/org/andengine/opengl/view/ConfigChooserMatcher.java b/src/org/andengine/opengl/view/ConfigChooserMatcher.java new file mode 100644 index 000000000..0d0035249 --- /dev/null +++ b/src/org/andengine/opengl/view/ConfigChooserMatcher.java @@ -0,0 +1,82 @@ +package org.andengine.opengl.view; + +/** + * (c) 2012 Zynga Inc. + * + * @author Nicolas Gramlich + * @since 15:34:13 - 12.05.2012 + */ +public abstract class ConfigChooserMatcher { + // =========================================================== + // Constants + // =========================================================== + + public static final ConfigChooserMatcher STRICT = new ConfigChooserMatcher() { + @Override + public boolean matches(final int pRequestedRedSize, final int pRedSize, final int pRequestedGreenSize, final int pGreenSize, final int pRequestedBlueSize, final int pBlueSize, final int pRequestedAlphaSize, final int pAlphaSize, final int pRequestedDepthSize, final int pDepthSize, final int pRequestedStencilSize, final int pStencilSize) { + if (pDepthSize == pRequestedDepthSize && pStencilSize == pRequestedStencilSize) { + if (pRedSize == pRequestedRedSize && pGreenSize == pRequestedGreenSize && pBlueSize == pRequestedBlueSize && pAlphaSize == pRequestedAlphaSize) { + return true; + } + } + return false; + } + }; + + public static final ConfigChooserMatcher LOOSE_STENCIL = new ConfigChooserMatcher() { + @Override + public boolean matches(final int pRequestedRedSize, final int pRedSize, final int pRequestedGreenSize, final int pGreenSize, final int pRequestedBlueSize, final int pBlueSize, final int pRequestedAlphaSize, final int pAlphaSize, final int pRequestedDepthSize, final int pDepthSize, final int pRequestedStencilSize, final int pStencilSize) { + if (pDepthSize == pRequestedDepthSize && pStencilSize >= pRequestedStencilSize) { + if (pRedSize == pRequestedRedSize && pGreenSize == pRequestedGreenSize && pBlueSize == pRequestedBlueSize && pAlphaSize == pRequestedAlphaSize) { + return true; + } + } + return false; + } + }; + + public static final ConfigChooserMatcher LOOSE_DEPTH_AND_STENCIL = new ConfigChooserMatcher() { + @Override + public boolean matches(final int pRequestedRedSize, final int pRedSize, final int pRequestedGreenSize, final int pGreenSize, final int pRequestedBlueSize, final int pBlueSize, final int pRequestedAlphaSize, final int pAlphaSize, final int pRequestedDepthSize, final int pDepthSize, final int pRequestedStencilSize, final int pStencilSize) { + if (pDepthSize >= pRequestedDepthSize && pStencilSize >= pRequestedStencilSize) { + if (pRedSize == pRequestedRedSize && pGreenSize == pRequestedGreenSize && pBlueSize == pRequestedBlueSize && pAlphaSize == pRequestedAlphaSize) { + return true; + } + } + return false; + } + }; + + public static final ConfigChooserMatcher ANY = new ConfigChooserMatcher() { + @Override + public boolean matches(final int pRequestedRedSize, final int pRedSize, final int pRequestedGreenSize, final int pGreenSize, final int pRequestedBlueSize, final int pBlueSize, final int pRequestedAlphaSize, final int pAlphaSize, final int pRequestedDepthSize, final int pDepthSize, final int pRequestedStencilSize, final int pStencilSize) { + return true; + } + }; + + // =========================================================== + // Fields + // =========================================================== + + // =========================================================== + // Constructors + // =========================================================== + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + public abstract boolean matches(final int pRequestedRedSize, final int pRedSize, final int pRequestedGreenSize, final int pGreenSize, final int pRequestedBlueSize, final int pBlueSize, final int pRequestedAlphaSize, final int pAlphaSize, final int pRequestedDepthSize, final int pDepthSize, final int pRequestedStencilSize, final int pStencilSize); + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== +} \ No newline at end of file diff --git a/src/org/andengine/opengl/view/EngineRenderer.java b/src/org/andengine/opengl/view/EngineRenderer.java index d84e1fd86..bea7bb3b3 100644 --- a/src/org/andengine/opengl/view/EngineRenderer.java +++ b/src/org/andengine/opengl/view/EngineRenderer.java @@ -14,7 +14,7 @@ /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 11:57:29 - 08.03.2010 */ @@ -42,7 +42,7 @@ public EngineRenderer(final Engine pEngine, final ConfigChooser pConfigChooser, this.mConfigChooser = pConfigChooser; this.mRendererListener = pRendererListener; this.mGLState = new GLState(); - this.mMultiSampling = this.mEngine.getEngineOptions().getRenderOptions().isMultiSampling(); + this.mMultiSampling = this.mEngine.getEngineOptions().getRenderOptions().getConfigChooserOptions().isRequestedMultiSampling(); } // =========================================================== @@ -76,7 +76,7 @@ public void onSurfaceCreated(final GL10 pGL, final EGLConfig pEGLConfig) { // GLES20.glFrontFace(GLES20.GL_CCW); // GLES20.glCullFace(GLES20.GL_BACK); - if(this.mRendererListener != null) { + if (this.mRendererListener != null) { this.mRendererListener.onSurfaceCreated(this.mGLState); } } @@ -88,7 +88,7 @@ public void onSurfaceChanged(final GL10 pGL, final int pWidth, final int pHeight GLES20.glViewport(0, 0, pWidth, pHeight); this.mGLState.loadProjectionGLMatrixIdentity(); - if(this.mRendererListener != null) { + if (this.mRendererListener != null) { this.mRendererListener.onSurfaceChanged(this.mGLState, pWidth, pHeight); } } @@ -96,7 +96,7 @@ public void onSurfaceChanged(final GL10 pGL, final int pWidth, final int pHeight @Override public void onDrawFrame(final GL10 pGL) { synchronized(GLState.class) { - if (this.mMultiSampling && this.mConfigChooser.isCoverageMultiSampling()) { + if (this.mMultiSampling && this.mConfigChooser.isActualCoverageMultiSampling()) { final int GL_COVERAGE_BUFFER_BIT_NV = 0x8000; GLES20.glClear(GL_COVERAGE_BUFFER_BIT_NV); } diff --git a/src/org/andengine/opengl/view/IRendererListener.java b/src/org/andengine/opengl/view/IRendererListener.java index c2788d5b4..66d244b7b 100644 --- a/src/org/andengine/opengl/view/IRendererListener.java +++ b/src/org/andengine/opengl/view/IRendererListener.java @@ -5,7 +5,7 @@ /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 11:57:29 - 08.03.2010 */ diff --git a/src/org/andengine/opengl/view/RenderSurfaceView.java b/src/org/andengine/opengl/view/RenderSurfaceView.java index bae24a18a..7e9bf479b 100644 --- a/src/org/andengine/opengl/view/RenderSurfaceView.java +++ b/src/org/andengine/opengl/view/RenderSurfaceView.java @@ -1,6 +1,8 @@ package org.andengine.opengl.view; import org.andengine.engine.Engine; +import org.andengine.engine.options.ConfigChooserOptions; +import org.andengine.engine.options.resolutionpolicy.IResolutionPolicy; import android.content.Context; import android.opengl.GLSurfaceView; @@ -9,11 +11,11 @@ /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 11:57:29 - 08.03.2010 */ -public class RenderSurfaceView extends GLSurfaceView { +public class RenderSurfaceView extends GLSurfaceView implements IResolutionPolicy.Callback { // =========================================================== // Constants // =========================================================== @@ -46,7 +48,7 @@ public RenderSurfaceView(final Context pContext, final AttributeSet pAttrs) { // =========================================================== public ConfigChooser getConfigChooser() throws IllegalStateException { - if(this.mConfigChooser == null) { + if (this.mConfigChooser == null) { throw new IllegalStateException(ConfigChooser.class.getSimpleName() + " not yet set."); } return this.mConfigChooser; @@ -64,18 +66,26 @@ protected void onMeasure(final int pWidthMeasureSpec, final int pHeightMeasureSp this.mEngineRenderer.mEngine.getEngineOptions().getResolutionPolicy().onMeasure(this, pWidthMeasureSpec, pHeightMeasureSpec); } + @Override + public void onResolutionChanged(final int pWidth, final int pHeight) { + this.setMeasuredDimension(pWidth, pHeight); + } + // =========================================================== // Methods // =========================================================== - public void setMeasuredDimensionProxy(final int pMeasuredWidth, final int pMeasuredHeight) { - this.setMeasuredDimension(pMeasuredWidth, pMeasuredHeight); - } - public void setRenderer(final Engine pEngine, final IRendererListener pRendererListener) { - if(this.mConfigChooser == null) { - final boolean multiSampling = pEngine.getEngineOptions().getRenderOptions().isMultiSampling(); - this.mConfigChooser = new ConfigChooser(multiSampling); + if (this.mConfigChooser == null) { + final ConfigChooserOptions configChooserOptions = pEngine.getEngineOptions().getRenderOptions().getConfigChooserOptions(); + this.mConfigChooser = new ConfigChooser(configChooserOptions); + + // TODO We don't know yet if the requested color size will actually be accepted! + if (configChooserOptions.isRequestedRGBA8888()) { + this.getHolder().setFormat(android.graphics.PixelFormat.RGBA_8888); + } else if (configChooserOptions.isRequestedRGB565()) { + this.getHolder().setFormat(android.graphics.PixelFormat.RGB_565); + } } this.setEGLConfigChooser(this.mConfigChooser); diff --git a/src/org/andengine/ui/IGameInterface.java b/src/org/andengine/ui/IGameInterface.java index 0830162f4..93baac8bf 100644 --- a/src/org/andengine/ui/IGameInterface.java +++ b/src/org/andengine/ui/IGameInterface.java @@ -1,13 +1,15 @@ package org.andengine.ui; +import java.io.IOException; + import org.andengine.engine.Engine; import org.andengine.engine.options.EngineOptions; import org.andengine.entity.scene.Scene; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 12:03:08 - 14.03.2010 */ @@ -23,12 +25,12 @@ public interface IGameInterface { public EngineOptions onCreateEngineOptions(); public Engine onCreateEngine(final EngineOptions pEngineOptions); - public void onCreateResources(final OnCreateResourcesCallback pOnCreateResourcesCallback) throws Exception; - public void onCreateScene(final OnCreateSceneCallback pOnCreateSceneCallback) throws Exception; - public void onPopulateScene(final Scene pScene, final OnPopulateSceneCallback pOnPopulateSceneCallback) throws Exception; + public void onCreateResources(final OnCreateResourcesCallback pOnCreateResourcesCallback) throws IOException; + public void onCreateScene(final OnCreateSceneCallback pOnCreateSceneCallback) throws IOException; + public void onPopulateScene(final Scene pScene, final OnPopulateSceneCallback pOnPopulateSceneCallback) throws IOException; - public void onReloadResources() throws Exception; - public void onDestroyResources() throws Exception; + public void onReloadResources() throws IOException; + public void onDestroyResources() throws IOException; public void onGameCreated(); public void onResumeGame(); diff --git a/src/org/andengine/ui/activity/BaseActivity.java b/src/org/andengine/ui/activity/BaseActivity.java index 1697202df..9a2ed1bdc 100644 --- a/src/org/andengine/ui/activity/BaseActivity.java +++ b/src/org/andengine/ui/activity/BaseActivity.java @@ -1,6 +1,7 @@ package org.andengine.ui.activity; import org.andengine.util.ActivityUtils; +import org.andengine.util.DialogUtils; import org.andengine.util.call.AsyncCallable; import org.andengine.util.call.Callable; import org.andengine.util.call.Callback; @@ -8,13 +9,13 @@ import android.app.Activity; import android.app.ProgressDialog; -import android.os.Looper; +import android.os.Bundle; import android.widget.Toast; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 18:35:28 - 29.08.2009 */ @@ -43,12 +44,12 @@ public abstract class BaseActivity extends Activity { // Methods // =========================================================== - public void toastOnUIThread(final CharSequence pText) { - this.toastOnUIThread(pText, Toast.LENGTH_LONG); + public void toastOnUiThread(final CharSequence pText) { + this.toastOnUiThread(pText, Toast.LENGTH_SHORT); } - public void toastOnUIThread(final CharSequence pText, final int pDuration) { - if(Looper.getMainLooper().getThread() == Thread.currentThread()) { + public void toastOnUiThread(final CharSequence pText, final int pDuration) { + if (ActivityUtils.isOnUiThread()) { Toast.makeText(BaseActivity.this, pText, pDuration).show(); } else { this.runOnUiThread(new Runnable() { @@ -60,10 +61,20 @@ public void run() { } } + @Deprecated + public void showDialogOnUiThread(final int pDialogID) { + DialogUtils.showDialogOnUiThread(this, pDialogID); + } + + @Deprecated + public void showDialogOnUiThread(final int pDialogID, final Bundle pBundle) { + DialogUtils.showDialogOnUiThread(this, pDialogID, pBundle); + } + /** * Performs a task in the background, showing a {@link ProgressDialog}, * while the {@link Callable} is being processed. - * + * * @param * @param pTitleResourceID * @param pMessageResourceID @@ -78,7 +89,7 @@ protected void doAsync(final int pTitleResourceID, final int pMessageResourc /** * Performs a task in the background, showing a indeterminate {@link ProgressDialog}, * while the {@link Callable} is being processed. - * + * * @param * @param pTitleResourceID * @param pMessageResourceID @@ -94,7 +105,7 @@ protected void doAsync(final int pTitleResourceID, final int pMessageResourc /** * Performs a task in the background, showing a {@link ProgressDialog} with an ProgressBar, * while the {@link AsyncCallable} is being processed. - * + * * @param * @param pTitleResourceID * @param pMessageResourceID @@ -109,7 +120,7 @@ protected void doProgressAsync(final int pTitleResourceID, final int pIconRe /** * Performs a task in the background, showing a {@link ProgressDialog} with a ProgressBar, * while the {@link AsyncCallable} is being processed. - * + * * @param * @param pTitleResourceID * @param pMessageResourceID @@ -125,7 +136,7 @@ protected void doProgressAsync(final int pTitleResourceID, final int pIconRe /** * Performs a task in the background, showing an indeterminate {@link ProgressDialog}, * while the {@link AsyncCallable} is being processed. - * + * * @param * @param pTitleResourceID * @param pMessageResourceID diff --git a/src/org/andengine/ui/activity/BaseGameActivity.java b/src/org/andengine/ui/activity/BaseGameActivity.java index 8d90fc6ed..05b8b5bb2 100644 --- a/src/org/andengine/ui/activity/BaseGameActivity.java +++ b/src/org/andengine/ui/activity/BaseGameActivity.java @@ -1,5 +1,7 @@ package org.andengine.ui.activity; +import java.io.IOException; + import org.andengine.BuildConfig; import org.andengine.audio.music.MusicManager; import org.andengine.audio.sound.SoundManager; @@ -39,7 +41,7 @@ /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 11:27:06 - 08.03.2010 */ @@ -69,7 +71,7 @@ public abstract class BaseGameActivity extends BaseActivity implements IGameInte @Override protected void onCreate(final Bundle pSavedInstanceState) { - if(BuildConfig.DEBUG) { + if (BuildConfig.DEBUG) { Debug.d(this.getClass().getSimpleName() + ".onCreate" + " @(Thread: '" + Thread.currentThread().getName() + "')"); } @@ -78,6 +80,7 @@ protected void onCreate(final Bundle pSavedInstanceState) { this.mGamePaused = true; this.mEngine = this.onCreateEngine(this.onCreateEngineOptions()); + this.mEngine.startUpdateThread(); this.applyEngineOptions(); @@ -91,18 +94,18 @@ public Engine onCreateEngine(final EngineOptions pEngineOptions) { @Override public synchronized void onSurfaceCreated(final GLState pGLState) { - if(BuildConfig.DEBUG) { + if (BuildConfig.DEBUG) { Debug.d(this.getClass().getSimpleName() + ".onSurfaceCreated" + " @(Thread: '" + Thread.currentThread().getName() + "')"); } - if(this.mGameCreated) { + if (this.mGameCreated) { this.onReloadResources(); - if(this.mGamePaused && this.mGameCreated) { + if (this.mGamePaused && this.mGameCreated && !this.isFinishing()) { this.onResumeGame(); } } else { - if(this.mCreateGameCalled) { + if (this.mCreateGameCalled) { this.mOnReloadResourcesScheduled = true; } else { this.mCreateGameCalled = true; @@ -113,13 +116,13 @@ public synchronized void onSurfaceCreated(final GLState pGLState) { @Override public synchronized void onSurfaceChanged(final GLState pGLState, final int pWidth, final int pHeight) { - if(BuildConfig.DEBUG) { - Debug.d(this.getClass().getSimpleName() + ".onSurfaceChanged(Width=" + pWidth + ", Height=" + pHeight + ")" + " @(Thread: '" + Thread.currentThread().getName() + "')"); + if (BuildConfig.DEBUG) { + Debug.d(this.getClass().getSimpleName() + ".onSurfaceChanged(Width=" + pWidth + ", Height=" + pHeight + ")" + " @(Thread: '" + Thread.currentThread().getName() + "')"); } } protected synchronized void onCreateGame() { - if(BuildConfig.DEBUG) { + if (BuildConfig.DEBUG) { Debug.d(this.getClass().getSimpleName() + ".onCreateGame" + " @(Thread: '" + Thread.currentThread().getName() + "')"); } @@ -127,7 +130,7 @@ protected synchronized void onCreateGame() { @Override public void onPopulateSceneFinished() { try { - if(BuildConfig.DEBUG) { + if (BuildConfig.DEBUG) { Debug.d(BaseGameActivity.this.getClass().getSimpleName() + ".onGameCreated" + " @(Thread: '" + Thread.currentThread().getName() + "')"); } @@ -146,7 +149,7 @@ public void onCreateSceneFinished(final Scene pScene) { BaseGameActivity.this.mEngine.setScene(pScene); try { - if(BuildConfig.DEBUG) { + if (BuildConfig.DEBUG) { Debug.d(BaseGameActivity.this.getClass().getSimpleName() + ".onPopulateScene" + " @(Thread: '" + Thread.currentThread().getName() + "')"); } @@ -161,7 +164,7 @@ public void onCreateSceneFinished(final Scene pScene) { @Override public void onCreateResourcesFinished() { try { - if(BuildConfig.DEBUG) { + if (BuildConfig.DEBUG) { Debug.d(BaseGameActivity.this.getClass().getSimpleName() + ".onCreateScene" + " @(Thread: '" + Thread.currentThread().getName() + "')"); } @@ -173,7 +176,7 @@ public void onCreateResourcesFinished() { }; try { - if(BuildConfig.DEBUG) { + if (BuildConfig.DEBUG) { Debug.d(this.getClass().getSimpleName() + ".onCreateResources" + " @(Thread: '" + Thread.currentThread().getName() + "')"); } @@ -190,7 +193,7 @@ public synchronized void onGameCreated() { /* Since the potential asynchronous resource creation, * the surface might already be invalid * and a resource reloading might be necessary. */ - if(this.mOnReloadResourcesScheduled) { + if (this.mOnReloadResourcesScheduled) { this.mOnReloadResourcesScheduled = false; try { this.onReloadResources(); @@ -202,7 +205,7 @@ public synchronized void onGameCreated() { @Override protected synchronized void onResume() { - if(BuildConfig.DEBUG) { + if (BuildConfig.DEBUG) { Debug.d(this.getClass().getSimpleName() + ".onResume" + " @(Thread: '" + Thread.currentThread().getName() + "')"); } @@ -214,7 +217,7 @@ protected synchronized void onResume() { @Override public synchronized void onResumeGame() { - if(BuildConfig.DEBUG) { + if (BuildConfig.DEBUG) { Debug.d(this.getClass().getSimpleName() + ".onResumeGame" + " @(Thread: '" + Thread.currentThread().getName() + "')"); } @@ -227,14 +230,14 @@ public synchronized void onResumeGame() { public synchronized void onWindowFocusChanged(final boolean pHasWindowFocus) { super.onWindowFocusChanged(pHasWindowFocus); - if(pHasWindowFocus && this.mGamePaused && this.mGameCreated) { + if (pHasWindowFocus && this.mGamePaused && this.mGameCreated && !this.isFinishing()) { this.onResumeGame(); } } @Override public void onReloadResources() { - if(BuildConfig.DEBUG) { + if (BuildConfig.DEBUG) { Debug.d(this.getClass().getSimpleName() + ".onReloadResources" + " @(Thread: '" + Thread.currentThread().getName() + "')"); } @@ -243,7 +246,7 @@ public void onReloadResources() { @Override protected void onPause() { - if(BuildConfig.DEBUG) { + if (BuildConfig.DEBUG) { Debug.d(this.getClass().getSimpleName() + ".onPause" + " @(Thread: '" + Thread.currentThread().getName() + "')"); } @@ -252,14 +255,14 @@ protected void onPause() { this.mRenderSurfaceView.onPause(); this.releaseWakeLock(); - if(!this.mGamePaused) { + if (!this.mGamePaused) { this.onPauseGame(); } } @Override public synchronized void onPauseGame() { - if(BuildConfig.DEBUG) { + if (BuildConfig.DEBUG) { Debug.d(this.getClass().getSimpleName() + ".onPauseGame" + " @(Thread: '" + Thread.currentThread().getName() + "')"); } @@ -270,7 +273,7 @@ public synchronized void onPauseGame() { @Override protected void onDestroy() { - if(BuildConfig.DEBUG) { + if (BuildConfig.DEBUG) { Debug.d(this.getClass().getSimpleName() + ".onDestroy" + " @(Thread: '" + Thread.currentThread().getName() + "')"); } @@ -290,23 +293,23 @@ protected void onDestroy() { } @Override - public void onDestroyResources() throws Exception { - if(BuildConfig.DEBUG) { + public void onDestroyResources() throws IOException { + if (BuildConfig.DEBUG) { Debug.d(this.getClass().getSimpleName() + ".onDestroyResources" + " @(Thread: '" + Thread.currentThread().getName() + "')"); } - if(this.mEngine.getEngineOptions().getAudioOptions().needsMusic()) { + if (this.mEngine.getEngineOptions().getAudioOptions().needsMusic()) { this.getMusicManager().releaseAll(); } - if(this.mEngine.getEngineOptions().getAudioOptions().needsSound()) { + if (this.mEngine.getEngineOptions().getAudioOptions().needsSound()) { this.getSoundManager().releaseAll(); } } @Override public synchronized void onGameDestroyed() { - if(BuildConfig.DEBUG) { + if (BuildConfig.DEBUG) { Debug.d(this.getClass().getSimpleName() + ".onGameDestroyed" + " @(Thread: '" + Thread.currentThread().getName() + "')"); } @@ -369,7 +372,9 @@ private void callGameResumedOnUIThread() { BaseGameActivity.this.runOnUiThread(new Runnable() { @Override public void run() { - BaseGameActivity.this.onResumeGame(); + if (!BaseGameActivity.this.isFinishing()) { + BaseGameActivity.this.onResumeGame(); + } } }); } @@ -400,7 +405,7 @@ private void acquireWakeLock() { } private void acquireWakeLock(final WakeLockOptions pWakeLockOptions) { - if(pWakeLockOptions == WakeLockOptions.SCREEN_ON) { + if (pWakeLockOptions == WakeLockOptions.SCREEN_ON) { ActivityUtils.keepScreenOn(this); } else { final PowerManager pm = (PowerManager) this.getSystemService(Context.POWER_SERVICE); @@ -414,7 +419,7 @@ private void acquireWakeLock(final WakeLockOptions pWakeLockOptions) { } private void releaseWakeLock() { - if(this.mWakeLock != null && this.mWakeLock.isHeld()) { + if (this.mWakeLock != null && this.mWakeLock.isHeld()) { this.mWakeLock.release(); } } @@ -422,20 +427,20 @@ private void releaseWakeLock() { private void applyEngineOptions() { final EngineOptions engineOptions = this.mEngine.getEngineOptions(); - if(engineOptions.isFullscreen()) { + if (engineOptions.isFullscreen()) { ActivityUtils.requestFullscreen(this); } - if(engineOptions.getAudioOptions().needsMusic() || engineOptions.getAudioOptions().needsSound()) { + if (engineOptions.getAudioOptions().needsMusic() || engineOptions.getAudioOptions().needsSound()) { this.setVolumeControlStream(AudioManager.STREAM_MUSIC); } - switch(engineOptions.getScreenOrientation()) { + switch (engineOptions.getScreenOrientation()) { case LANDSCAPE_FIXED: this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); break; case LANDSCAPE_SENSOR: - if(SystemUtils.SDK_VERSION_GINGERBREAD_OR_LATER) { + if (SystemUtils.SDK_VERSION_GINGERBREAD_OR_LATER) { this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE); } else { Debug.w(ScreenOrientation.class.getSimpleName() + "." + ScreenOrientation.LANDSCAPE_SENSOR + " is not supported on this device. Falling back to " + ScreenOrientation.class.getSimpleName() + "." + ScreenOrientation.LANDSCAPE_FIXED); @@ -446,7 +451,7 @@ private void applyEngineOptions() { this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); break; case PORTRAIT_SENSOR: - if(SystemUtils.SDK_VERSION_GINGERBREAD_OR_LATER) { + if (SystemUtils.SDK_VERSION_GINGERBREAD_OR_LATER) { this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT); } else { Debug.w(ScreenOrientation.class.getSimpleName() + "." + ScreenOrientation.PORTRAIT_SENSOR + " is not supported on this device. Falling back to " + ScreenOrientation.class.getSimpleName() + "." + ScreenOrientation.PORTRAIT_FIXED); diff --git a/src/org/andengine/ui/activity/LayoutGameActivity.java b/src/org/andengine/ui/activity/LayoutGameActivity.java index 88cf51e67..498259906 100644 --- a/src/org/andengine/ui/activity/LayoutGameActivity.java +++ b/src/org/andengine/ui/activity/LayoutGameActivity.java @@ -3,9 +3,9 @@ import org.andengine.opengl.view.RenderSurfaceView; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 10:18:50 - 06.10.2010 */ diff --git a/src/org/andengine/ui/activity/LegacyBaseGameActivity.java b/src/org/andengine/ui/activity/LegacyBaseGameActivity.java index a6df6b7dc..c17631963 100644 --- a/src/org/andengine/ui/activity/LegacyBaseGameActivity.java +++ b/src/org/andengine/ui/activity/LegacyBaseGameActivity.java @@ -1,5 +1,7 @@ package org.andengine.ui.activity; +import java.io.IOException; + import org.andengine.engine.Engine; import org.andengine.engine.options.EngineOptions; import org.andengine.entity.scene.Scene; @@ -11,7 +13,7 @@ * * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 11:27:06 - 08.03.2010 */ @@ -54,26 +56,26 @@ public final Engine onCreateEngine(final EngineOptions pEngineOptions) { } @Override - public final void onCreateResources(final OnCreateResourcesCallback pOnCreateResourcesCallback) throws Exception { + public final void onCreateResources(final OnCreateResourcesCallback pOnCreateResourcesCallback) throws IOException { this.onLoadResources(); pOnCreateResourcesCallback.onCreateResourcesFinished(); } @Override - public final void onCreateScene(final OnCreateSceneCallback pOnCreateSceneCallback) throws Exception { + public final void onCreateScene(final OnCreateSceneCallback pOnCreateSceneCallback) throws IOException { final Scene scene = this.onLoadScene(); pOnCreateSceneCallback.onCreateSceneFinished(scene); } @Override - public final void onPopulateScene(final Scene pScene, final OnPopulateSceneCallback pOnPopulateSceneCallback) throws Exception { + public final void onPopulateScene(final Scene pScene, final OnPopulateSceneCallback pOnPopulateSceneCallback) throws IOException { pOnPopulateSceneCallback.onPopulateSceneFinished(); } @Override - public final void onDestroyResources() throws Exception { + public final void onDestroyResources() throws IOException { super.onDestroyResources(); this.onUnloadResources(); diff --git a/src/org/andengine/ui/activity/SimpleAsyncGameActivity.java b/src/org/andengine/ui/activity/SimpleAsyncGameActivity.java index 201a8b01d..51485affa 100644 --- a/src/org/andengine/ui/activity/SimpleAsyncGameActivity.java +++ b/src/org/andengine/ui/activity/SimpleAsyncGameActivity.java @@ -7,7 +7,7 @@ import org.andengine.util.progress.ProgressCallable; /** - * (c) Zynga 2011 + * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 01:24:18 - 03.12.2011 @@ -88,7 +88,7 @@ public void onCallback(final Void pCallbackValue) { } }); } - + @Override public void onPopulateScene(final Scene pScene, final OnPopulateSceneCallback pOnPopulateSceneCallback) { this.runOnUiThread(new Runnable() { @@ -98,11 +98,11 @@ public void run() { @Override public Void call(final IProgressListener pProgressListener) throws Exception { SimpleAsyncGameActivity.this.onPopulateSceneAsync(pScene, pProgressListener); - + pProgressListener.onProgressChanged(100); - + pOnPopulateSceneCallback.onPopulateSceneFinished(); - + return null; } }, new Callback() { diff --git a/src/org/andengine/ui/activity/SimpleBaseGameActivity.java b/src/org/andengine/ui/activity/SimpleBaseGameActivity.java index 6401941e6..935be3ad1 100644 --- a/src/org/andengine/ui/activity/SimpleBaseGameActivity.java +++ b/src/org/andengine/ui/activity/SimpleBaseGameActivity.java @@ -1,13 +1,15 @@ package org.andengine.ui.activity; +import java.io.IOException; + import org.andengine.entity.scene.Scene; import org.andengine.ui.IGameInterface; /** * This class exists so that the callback parameters of the methods in {@link IGameInterface} get called automatically. - * - * (c) Zynga 2011 + * + * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 19:05:42 - 23.12.2011 @@ -33,25 +35,25 @@ public abstract class SimpleBaseGameActivity extends BaseGameActivity { // Methods for/from SuperClass/Interfaces // =========================================================== - protected abstract void onCreateResources(); + protected abstract void onCreateResources() throws IOException; protected abstract Scene onCreateScene(); @Override - public final void onCreateResources(final OnCreateResourcesCallback pOnCreateResourcesCallback) throws Exception { + public final void onCreateResources(final OnCreateResourcesCallback pOnCreateResourcesCallback) throws IOException { this.onCreateResources(); pOnCreateResourcesCallback.onCreateResourcesFinished(); } @Override - public final void onCreateScene(final OnCreateSceneCallback pOnCreateSceneCallback) throws Exception { + public final void onCreateScene(final OnCreateSceneCallback pOnCreateSceneCallback) throws IOException { final Scene scene = this.onCreateScene(); pOnCreateSceneCallback.onCreateSceneFinished(scene); } @Override - public final void onPopulateScene(final Scene pScene, final OnPopulateSceneCallback pOnPopulateSceneCallback) throws Exception { + public final void onPopulateScene(final Scene pScene, final OnPopulateSceneCallback pOnPopulateSceneCallback) throws IOException { pOnPopulateSceneCallback.onPopulateSceneFinished(); } diff --git a/src/org/andengine/ui/activity/SimpleLayoutGameActivity.java b/src/org/andengine/ui/activity/SimpleLayoutGameActivity.java index 35538c592..8ead0146d 100644 --- a/src/org/andengine/ui/activity/SimpleLayoutGameActivity.java +++ b/src/org/andengine/ui/activity/SimpleLayoutGameActivity.java @@ -1,5 +1,7 @@ package org.andengine.ui.activity; +import java.io.IOException; + import org.andengine.entity.scene.Scene; import org.andengine.ui.IGameInterface; @@ -7,7 +9,7 @@ /** * This class exists so that the callback parameters of the methods in {@link IGameInterface} get called automatically. * - * (c) Zynga 2012 + * (c) 2012 Zynga Inc. * * @author Nicolas Gramlich * @since 3:11:05 PM - Jan 12, 2012 @@ -33,25 +35,25 @@ public abstract class SimpleLayoutGameActivity extends LayoutGameActivity { // Methods for/from SuperClass/Interfaces // =========================================================== - protected abstract void onCreateResources(); - protected abstract Scene onCreateScene(); + protected abstract void onCreateResources() throws IOException; + protected abstract Scene onCreateScene() throws IOException; @Override - public final void onCreateResources(final OnCreateResourcesCallback pOnCreateResourcesCallback) throws Exception { + public final void onCreateResources(final OnCreateResourcesCallback pOnCreateResourcesCallback) throws IOException { this.onCreateResources(); pOnCreateResourcesCallback.onCreateResourcesFinished(); } @Override - public final void onCreateScene(final OnCreateSceneCallback pOnCreateSceneCallback) throws Exception { + public final void onCreateScene(final OnCreateSceneCallback pOnCreateSceneCallback) throws IOException { final Scene scene = this.onCreateScene(); pOnCreateSceneCallback.onCreateSceneFinished(scene); } @Override - public final void onPopulateScene(final Scene pScene, final OnPopulateSceneCallback pOnPopulateSceneCallback) throws Exception { + public final void onPopulateScene(final Scene pScene, final OnPopulateSceneCallback pOnPopulateSceneCallback) throws IOException { pOnPopulateSceneCallback.onPopulateSceneFinished(); } diff --git a/src/org/andengine/ui/dialog/GenericInputDialogBuilder.java b/src/org/andengine/ui/dialog/GenericInputDialogBuilder.java index 4d9b724d6..eaef8becb 100644 --- a/src/org/andengine/ui/dialog/GenericInputDialogBuilder.java +++ b/src/org/andengine/ui/dialog/GenericInputDialogBuilder.java @@ -13,9 +13,9 @@ import android.widget.Toast; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 09:35:55 - 14.12.2009 */ @@ -41,11 +41,11 @@ public abstract class GenericInputDialogBuilder { // Constructors // =========================================================== - public GenericInputDialogBuilder(final Context pContext, final int pTitleResID, final int pMessageResID, final int pErrorResID, final int pIconResID, final Callback pSuccessCallback, final OnCancelListener pOnCancelListener){ + public GenericInputDialogBuilder(final Context pContext, final int pTitleResID, final int pMessageResID, final int pErrorResID, final int pIconResID, final Callback pSuccessCallback, final OnCancelListener pOnCancelListener) { this(pContext, pTitleResID, pMessageResID, pErrorResID, pIconResID, "", pSuccessCallback, pOnCancelListener); } - public GenericInputDialogBuilder(final Context pContext, final int pTitleResID, final int pMessageResID, final int pErrorResID, final int pIconResID, final String pDefaultText, final Callback pSuccessCallback, final OnCancelListener pOnCancelListener){ + public GenericInputDialogBuilder(final Context pContext, final int pTitleResID, final int pMessageResID, final int pErrorResID, final int pIconResID, final String pDefaultText, final Callback pSuccessCallback, final OnCancelListener pOnCancelListener) { this.mContext = pContext; this.mTitleResID = pTitleResID; this.mMessageResID = pMessageResID; @@ -75,13 +75,13 @@ public Dialog create() { etInput.setText(this.mDefaultText); final AlertDialog.Builder ab = new AlertDialog.Builder(this.mContext); - if(this.mTitleResID != 0) { + if (this.mTitleResID != 0) { ab.setTitle(this.mTitleResID); } - if(this.mMessageResID != 0) { + if (this.mMessageResID != 0) { ab.setMessage(this.mMessageResID); } - if(this.mIconResID != 0) { + if (this.mIconResID != 0) { ab.setIcon(this.mIconResID); } @@ -91,7 +91,7 @@ public Dialog create() { @Override public void onClick(final DialogInterface pDialog, final int pWhich) { final T result; - try{ + try { result = GenericInputDialogBuilder.this.generateResult(etInput.getText().toString()); } catch (final IllegalArgumentException e) { Debug.e("Error in GenericInputDialogBuilder.generateResult()", e); diff --git a/src/org/andengine/ui/dialog/StringInputDialogBuilder.java b/src/org/andengine/ui/dialog/StringInputDialogBuilder.java index 3fc22ad9d..adc560733 100644 --- a/src/org/andengine/ui/dialog/StringInputDialogBuilder.java +++ b/src/org/andengine/ui/dialog/StringInputDialogBuilder.java @@ -6,9 +6,9 @@ import android.content.DialogInterface.OnCancelListener; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 09:46:00 - 14.12.2009 */ diff --git a/src/org/andengine/util/ActivityUtils.java b/src/org/andengine/util/ActivityUtils.java index 72d233029..75e76a69b 100644 --- a/src/org/andengine/util/ActivityUtils.java +++ b/src/org/andengine/util/ActivityUtils.java @@ -14,17 +14,18 @@ import android.content.DialogInterface; import android.content.DialogInterface.OnCancelListener; import android.os.AsyncTask; +import android.os.Looper; import android.view.Window; import android.view.WindowManager; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 18:11:54 - 07.03.2011 */ -public class ActivityUtils { +public final class ActivityUtils { // =========================================================== // Constants // =========================================================== @@ -37,6 +38,10 @@ public class ActivityUtils { // Constructors // =========================================================== + private ActivityUtils() { + + } + // =========================================================== // Getter & Setter // =========================================================== @@ -49,7 +54,11 @@ public class ActivityUtils { // Methods // =========================================================== - public static void requestFullscreen(final Activity pActivity) { + public static final boolean isOnUiThread() { + return Looper.getMainLooper().getThread() == Thread.currentThread(); + } + + public static final void requestFullscreen(final Activity pActivity) { final Window window = pActivity.getWindow(); window.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); window.clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN); @@ -60,54 +69,54 @@ public static void requestFullscreen(final Activity pActivity) { * @param pActivity * @param pScreenBrightness [0..1] */ - public static void setScreenBrightness(final Activity pActivity, final float pScreenBrightness) { + public static final void setScreenBrightness(final Activity pActivity, final float pScreenBrightness) { final Window window = pActivity.getWindow(); final WindowManager.LayoutParams windowLayoutParams = window.getAttributes(); windowLayoutParams.screenBrightness = pScreenBrightness; window.setAttributes(windowLayoutParams); } - public static void keepScreenOn(final Activity pActivity) { + public static final void keepScreenOn(final Activity pActivity) { pActivity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); } - public static void doAsync(final Context pContext, final int pTitleResourceID, final int pMessageResourceID, final Callable pCallable, final Callback pCallback) { + public static final void doAsync(final Context pContext, final int pTitleResourceID, final int pMessageResourceID, final Callable pCallable, final Callback pCallback) { ActivityUtils.doAsync(pContext, pTitleResourceID, pMessageResourceID, pCallable, pCallback, null, false); } - public static void doAsync(final Context pContext, final CharSequence pTitle, final CharSequence pMessage, final Callable pCallable, final Callback pCallback) { + public static final void doAsync(final Context pContext, final CharSequence pTitle, final CharSequence pMessage, final Callable pCallable, final Callback pCallback) { ActivityUtils.doAsync(pContext, pTitle, pMessage, pCallable, pCallback, null, false); } - public static void doAsync(final Context pContext, final int pTitleResourceID, final int pMessageResourceID, final Callable pCallable, final Callback pCallback, final boolean pCancelable) { + public static final void doAsync(final Context pContext, final int pTitleResourceID, final int pMessageResourceID, final Callable pCallable, final Callback pCallback, final boolean pCancelable) { ActivityUtils.doAsync(pContext, pTitleResourceID, pMessageResourceID, pCallable, pCallback, null, pCancelable); } - public static void doAsync(final Context pContext, final CharSequence pTitle, final CharSequence pMessage, final Callable pCallable, final Callback pCallback, final boolean pCancelable) { + public static final void doAsync(final Context pContext, final CharSequence pTitle, final CharSequence pMessage, final Callable pCallable, final Callback pCallback, final boolean pCancelable) { ActivityUtils.doAsync(pContext, pTitle, pMessage, pCallable, pCallback, null, pCancelable); } - public static void doAsync(final Context pContext, final int pTitleResourceID, final int pMessageResourceID, final Callable pCallable, final Callback pCallback, final Callback pExceptionCallback) { + public static final void doAsync(final Context pContext, final int pTitleResourceID, final int pMessageResourceID, final Callable pCallable, final Callback pCallback, final Callback pExceptionCallback) { ActivityUtils.doAsync(pContext, pTitleResourceID, pMessageResourceID, pCallable, pCallback, pExceptionCallback, false); } - public static void doAsync(final Context pContext, final CharSequence pTitle, final CharSequence pMessage, final Callable pCallable, final Callback pCallback, final Callback pExceptionCallback) { + public static final void doAsync(final Context pContext, final CharSequence pTitle, final CharSequence pMessage, final Callable pCallable, final Callback pCallback, final Callback pExceptionCallback) { ActivityUtils.doAsync(pContext, pTitle, pMessage, pCallable, pCallback, pExceptionCallback, false); } - public static void doAsync(final Context pContext, final int pTitleResourceID, final int pMessageResourceID, final Callable pCallable, final Callback pCallback, final Callback pExceptionCallback, final boolean pCancelable) { + public static final void doAsync(final Context pContext, final int pTitleResourceID, final int pMessageResourceID, final Callable pCallable, final Callback pCallback, final Callback pExceptionCallback, final boolean pCancelable) { ActivityUtils.doAsync(pContext, pContext.getString(pTitleResourceID), pContext.getString(pMessageResourceID), pCallable, pCallback, pExceptionCallback, pCancelable); } - public static void doAsync(final Context pContext, final CharSequence pTitle, final CharSequence pMessage, final Callable pCallable, final Callback pCallback, final Callback pExceptionCallback, final boolean pCancelable) { - new AsyncTask() { + public static final void doAsync(final Context pContext, final CharSequence pTitle, final CharSequence pMessage, final Callable pCallable, final Callback pCallback, final Callback pExceptionCallback, final boolean pCancelable) { + AsyncTaskUtils.execute(new AsyncTask() { private ProgressDialog mPD; - private Exception mException = null; + private Exception mException; @Override public void onPreExecute() { this.mPD = ProgressDialog.show(pContext, pTitle, pMessage, true, pCancelable); - if(pCancelable) { + if (pCancelable) { this.mPD.setOnCancelListener(new OnCancelListener() { @Override public void onCancel(final DialogInterface pDialogInterface) { @@ -130,48 +139,48 @@ public T doInBackground(final Void... params) { } @Override - public void onPostExecute(final T result) { + public void onPostExecute(final T pResult) { try { this.mPD.dismiss(); } catch (final Exception e) { Debug.e("Error", e); } - if(this.isCancelled()) { + if (this.isCancelled()) { this.mException = new CancelledException(); } - if(this.mException == null) { - pCallback.onCallback(result); + if (this.mException == null) { + pCallback.onCallback(pResult); } else { - if(pExceptionCallback == null) { + if (pExceptionCallback == null) { Debug.e("Error", this.mException); } else { pExceptionCallback.onCallback(this.mException); } } - super.onPostExecute(result); + super.onPostExecute(pResult); } - }.execute((Void[]) null); + }); } - - public static void doProgressAsync(final Context pContext, final int pTitleResourceID, final int pIconResourceID, final ProgressCallable pCallable, final Callback pCallback) { + + public static final void doProgressAsync(final Context pContext, final int pTitleResourceID, final int pIconResourceID, final ProgressCallable pCallable, final Callback pCallback) { ActivityUtils.doProgressAsync(pContext, pTitleResourceID, pIconResourceID, pCallable, pCallback, null); } - public static void doProgressAsync(final Context pContext, final CharSequence pTitle, final int pIconResourceID, final ProgressCallable pCallable, final Callback pCallback) { + public static final void doProgressAsync(final Context pContext, final CharSequence pTitle, final int pIconResourceID, final ProgressCallable pCallable, final Callback pCallback) { ActivityUtils.doProgressAsync(pContext, pTitle, pIconResourceID, pCallable, pCallback, null); } - public static void doProgressAsync(final Context pContext, final int pTitleResourceID, final int pIconResourceID, final ProgressCallable pCallable, final Callback pCallback, final Callback pExceptionCallback) { + public static final void doProgressAsync(final Context pContext, final int pTitleResourceID, final int pIconResourceID, final ProgressCallable pCallable, final Callback pCallback, final Callback pExceptionCallback) { ActivityUtils.doProgressAsync(pContext, pContext.getString(pTitleResourceID), pIconResourceID, pCallable, pCallback, pExceptionCallback); } - public static void doProgressAsync(final Context pContext, final CharSequence pTitle, final int pIconResourceID, final ProgressCallable pCallable, final Callback pCallback, final Callback pExceptionCallback) { - new AsyncTask() { + public static final void doProgressAsync(final Context pContext, final CharSequence pTitle, final int pIconResourceID, final ProgressCallable pCallable, final Callback pCallback, final Callback pExceptionCallback) { + AsyncTaskUtils.execute(new AsyncTask() { private ProgressDialog mPD; - private Exception mException = null; + private Exception mException; @Override public void onPreExecute() { @@ -200,12 +209,12 @@ public void onProgressChanged(final int pProgress) { } @Override - public void onProgressUpdate(final Integer... values) { - this.mPD.setProgress(values[0]); + public void onProgressUpdate(final Integer... pValues) { + this.mPD.setProgress(pValues[0]); } @Override - public void onPostExecute(final T result) { + public void onPostExecute(final T pResult) { try { this.mPD.dismiss(); } catch (final Exception e) { @@ -213,34 +222,34 @@ public void onPostExecute(final T result) { /* Nothing. */ } - if(this.isCancelled()) { + if (this.isCancelled()) { this.mException = new CancelledException(); } - if(this.mException == null) { - pCallback.onCallback(result); + if (this.mException == null) { + pCallback.onCallback(pResult); } else { - if(pExceptionCallback == null) { + if (pExceptionCallback == null) { Debug.e("Error", this.mException); } else { pExceptionCallback.onCallback(this.mException); } } - super.onPostExecute(result); + super.onPostExecute(pResult); } - }.execute((Void[]) null); + }); } - public static void doAsync(final Context pContext, final int pTitleResourceID, final int pMessageResourceID, final AsyncCallable pAsyncCallable, final Callback pCallback, final Callback pExceptionCallback) { + public static final void doAsync(final Context pContext, final int pTitleResourceID, final int pMessageResourceID, final AsyncCallable pAsyncCallable, final Callback pCallback, final Callback pExceptionCallback) { ActivityUtils.doAsync(pContext, pContext.getString(pTitleResourceID), pContext.getString(pMessageResourceID), pAsyncCallable, pCallback, pExceptionCallback); } - public static void doAsync(final Context pContext, final CharSequence pTitle, final CharSequence pMessage, final AsyncCallable pAsyncCallable, final Callback pCallback, final Callback pExceptionCallback) { + public static final void doAsync(final Context pContext, final CharSequence pTitle, final CharSequence pMessage, final AsyncCallable pAsyncCallable, final Callback pCallback, final Callback pExceptionCallback) { final ProgressDialog pd = ProgressDialog.show(pContext, pTitle, pMessage); pAsyncCallable.call(new Callback() { @Override - public void onCallback(final T result) { + public void onCallback(final T pResult) { try { pd.dismiss(); } catch (final Exception e) { @@ -248,7 +257,7 @@ public void onCallback(final T result) { /* Nothing. */ } - pCallback.onCallback(result); + pCallback.onCallback(pResult); } }, pExceptionCallback); } diff --git a/src/org/andengine/util/AsyncTaskUtils.java b/src/org/andengine/util/AsyncTaskUtils.java new file mode 100644 index 000000000..83c9eb263 --- /dev/null +++ b/src/org/andengine/util/AsyncTaskUtils.java @@ -0,0 +1,60 @@ +package org.andengine.util; + +import org.andengine.util.system.SystemUtils; + +import android.annotation.TargetApi; +import android.os.AsyncTask; +import android.os.Build; + + +/** + * (c) 2013 Nicolas Gramlich + * + * @author Nicolas Gramlich + * @since 12:42:12 - 11.05.2013 + */ +public final class AsyncTaskUtils { + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + // =========================================================== + // Constructors + // =========================================================== + + private AsyncTaskUtils() { + + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + /** + * @see groups.google.com/forum/?fromgroups=#!topic/android-developers/8M0RTFfO7-M + */ + @TargetApi(Build.VERSION_CODES.HONEYCOMB) + public static void execute(final AsyncTask pAsyncTask, final T ... pParameters) { + if (SystemUtils.isAndroidVersionOrHigher(Build.VERSION_CODES.HONEYCOMB)) { + pAsyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, pParameters); + } else { + pAsyncTask.execute(pParameters); + } + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== +} diff --git a/src/org/andengine/util/BetaUtils.java b/src/org/andengine/util/BetaUtils.java index 635ea5dc6..4c98c5ec1 100644 --- a/src/org/andengine/util/BetaUtils.java +++ b/src/org/andengine/util/BetaUtils.java @@ -14,13 +14,13 @@ /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 22:43:32 - 02.11.2010 */ -public class BetaUtils { +public final class BetaUtils { // =========================================================== // Constants // =========================================================== @@ -35,6 +35,10 @@ public class BetaUtils { // Constructors // =========================================================== + private BetaUtils() { + + } + // =========================================================== // Getter & Setter // =========================================================== @@ -61,16 +65,16 @@ public static boolean finishWhenExpired(final Activity pActivity, final Gregoria final GregorianCalendar lastuseDate = new GregorianCalendar(); lastuseDate.setTimeInMillis(lastuse); - if(lastuseDate.after(pExpirationDate)){ + if (lastuseDate.after(pExpirationDate)) { final Builder alertDialogBuilder = new AlertDialog.Builder(pActivity) .setTitle(pTitleResourceID) .setIcon(android.R.drawable.ic_dialog_alert) .setMessage(pMessageResourceID); - alertDialogBuilder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener(){ + alertDialogBuilder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(final DialogInterface pDialog, final int pWhich) { - if(pOkIntent != null) { + if (pOkIntent != null) { pActivity.startActivity(pOkIntent); } pActivity.finish(); @@ -79,7 +83,7 @@ public void onClick(final DialogInterface pDialog, final int pWhich) { alertDialogBuilder.setNegativeButton(android.R.string.cancel, new OnClickListener() { @Override public void onClick(final DialogInterface pDialog, final int pWhich) { - if(pCancelIntent != null) { + if (pCancelIntent != null) { pActivity.startActivity(pCancelIntent); } pActivity.finish(); @@ -87,7 +91,7 @@ public void onClick(final DialogInterface pDialog, final int pWhich) { }) .create().show(); return true; - }else{ + } else { return false; } } diff --git a/src/org/andengine/util/BezierCurveUtils.java b/src/org/andengine/util/BezierCurveUtils.java new file mode 100644 index 000000000..c911283d3 --- /dev/null +++ b/src/org/andengine/util/BezierCurveUtils.java @@ -0,0 +1,207 @@ +package org.andengine.util; + +import org.andengine.util.math.MathUtils; + +/** + * (c) 2013 Nicolas Gramlich + * + * @author Nicolas Gramlich + * @since 23:09:15 - 01.06.2013 + * + * @see BƩzier curve (Wikipedia) + * @see Derivatives of a BƩzier Curve (Michigan Tech University) + * @see Continuous Curvature Path Generation Based on Bezier Curves for Autonomous Vehicles (Choi, Curry, Elkaim) + * @see BƩzier Curves (Stanislav) + * @see Curvature of singular BƩzier curves and surfaces (Zhejiang University) + * @see Bernstein polynomial (Wikipedia) + */ +public final class BezierCurveUtils { + // =========================================================== + // Constants + // =========================================================== + + private static final int LENGTH_SAMPLES_DEFAULT = 10; + + private static final float[] COORDINATES_TMP = new float[2]; + + // =========================================================== + // Fields + // =========================================================== + + // =========================================================== + // Constructors + // =========================================================== + + private BezierCurveUtils() { + + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + /** + * Calculates the (x|y|z|...)-coordinate for the given control point (x|y|z|...)-coordinates at value t. + * + * @param t in the interval [0, 1]. + * @param pControlPointCoordinates (x|y|z|...)-coordinates of control points of the BƩzier curve. + * @return + */ + public static final float getBezierCurveCoordinate(final float t, final float[] pControlPointCoordinates) { + float result = 0; + final int n = pControlPointCoordinates.length - 1; + for (int i = 0; i <= n; i++) { + result += pControlPointCoordinates[i] * BezierCurveUtils.getBernsteinPolynomial(t, i, n); + } + return result; + } + + /** + * Calculates the x/y-coordinate for the given control point x/y-coordinates at value t. + * + * @param t in the interval [0, 1]. + * @param pXs x-coordinates of the control points of the BƩzier curve. + * @param pYs y-coordinates of the control points of the BƩzier curve. + * @return a shared(!) float[] of length 2. + */ + public static final float[] getBezierCurveCoordinates(final float t, final float[] pXs, final float[] pYs) { + return BezierCurveUtils.getBezierCurveCoordinates(t, pXs, pYs, COORDINATES_TMP); + } + + /** + * Calculates the x/y-coordinate for the given control point x/y-coordinates at value t. + * + * @param t in the interval [0, 1]. + * @param pXs x-coordinates of the control points of the BƩzier curve. + * @param pYs y-coordinates of the control points of the BƩzier curve. + * @param pReuse must be of length 2. + * @return pReuse as a convenience. + */ + public static final float[] getBezierCurveCoordinates(final float t, final float[] pXs, final float[] pYs, final float[] pReuse) { + final int n = pXs.length - 1; + pReuse[Constants.VERTEX_INDEX_X] = 0; + pReuse[Constants.VERTEX_INDEX_Y] = 0; + for (int i = 0; i <= n; i++) { + final float bernsteinPolynomial = BezierCurveUtils.getBernsteinPolynomial(t, i, n); + pReuse[Constants.VERTEX_INDEX_X] += pXs[i] * bernsteinPolynomial; + pReuse[Constants.VERTEX_INDEX_Y] += pYs[i] * bernsteinPolynomial; + } + return pReuse; + } + + /** + * Calculates the length of a BƩzier curve by taking {@link #LENGTH_SAMPLES_DEFAULT} samples. + * + * @param pXs x-coordinates of the control points of the BƩzier curve. + * @param pYs y-coordinates of the control points of the BƩzier curve. + */ + public static final float getBezierCurveLength(final float[] pXs, final float[] pYs) { + return BezierCurveUtils.getBezierCurveLength(pXs, pYs, LENGTH_SAMPLES_DEFAULT); + } + + /** + * Calculates the length of a BƩzier curve by taking pSamples samples. + * + * @param pXs x-coordinates of the control points of the BƩzier curve. + * @param pYs y-coordinates of the control points of the BƩzier curve. + * @param pSamples the number of samples to take. The higher the more accurate. + * @return + */ + public static final float getBezierCurveLength(final float[] pXs, final float[] pYs, final int pSamples) { + float length = 0; + final int n = pXs.length - 1; + + float lastX = pXs[0]; + float lastY = pYs[0]; + for (int k = 1; k <= LENGTH_SAMPLES_DEFAULT; k++) { + final float t = (1f * k) / LENGTH_SAMPLES_DEFAULT; + + float x = 0; + float y = 0; + for (int i = 0; i <= n; i++) { + final float bernstein = BezierCurveUtils.getBernsteinPolynomial(t, i, n); + x += pXs[i] * bernstein; + y += pYs[i] * bernstein; + } + + length += MathUtils.distance(lastX, lastY, x, y); + + lastX = x; + lastY = y; + } + + return length; + } + + /** + * Calculates the curvature for the given control points of a BƩzier curve at value t. + * + * @param t in the interval [0, 1]. + * @param pXs x-coordinates of the control points of the BƩzier curve. + * @param pYs y-coordinates of the control points of the BƩzier curve. + */ + public static final float getBezierCurveCurvature(final float t, final float[] pXs, final float[] pYs) { + final float dxt = BezierCurveUtils.getBezierCurveDerivativeValue(t, 1, pXs); + final float dyt = BezierCurveUtils.getBezierCurveDerivativeValue(t, 1, pYs); + final float ddxt = BezierCurveUtils.getBezierCurveDerivativeValue(t, 2, pXs); + final float ddyt = BezierCurveUtils.getBezierCurveDerivativeValue(t, 2, pYs); + + return BezierCurveUtils.getCurvature(dxt, dyt, ddxt, ddyt); + } + + /** + * Calculates the value of the kth derivative of given control point (x|y|z|...)-coordinates of a BƩzier curve at value t. + * + * @param t in the interval [0, 1]. + * @param k the kth derivative. + * @param pControlPointCoordinates (x|y|z|...)-coordinates of the BƩzier curve. + * @return + */ + public static final float getBezierCurveDerivativeValue(final float t, final int k, final float[] pControlPointCoordinates) { + final int n = pControlPointCoordinates.length - 1; + float result = 1; + for (int i = n; i > n - k; i--) { + result *= i; + } + + float sum = 0; + for (int i = 0; i <= n - k; i++) { + final float bernstein = BezierCurveUtils.getBernsteinPolynomial(t, i, n - k); + final float d = BezierCurveUtils.getLevelDifference(i, k, pControlPointCoordinates); + sum += bernstein * d; + } + + result *= sum; + + return result; + } + + + private static float getCurvature(final float dxt, final float dyt, final float ddxt, final float ddyt) { + return Math.abs(dxt * ddyt - dyt * ddxt) / (float) Math.pow(dxt * dxt + dyt * dyt, 3f / 2f); + } + + private static final float getBernsteinPolynomial(final float x, final int i, final int n) { + return ((float) MathUtils.factorial(n) / (float) (MathUtils.factorial(i) * MathUtils.factorial(n - i))) * (float) Math.pow(x, i) * (float) Math.pow(1 - x, n - i); + } + + private static float getLevelDifference(final int i, final int level, final float[] pControlPointCoordinates) { + if (level == 0) { + return pControlPointCoordinates[i]; + } else { + return BezierCurveUtils.getLevelDifference(i + 1, level - 1, pControlPointCoordinates) - BezierCurveUtils.getLevelDifference(i, level - 1, pControlPointCoordinates); + } + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== +} diff --git a/src/org/andengine/util/BitmapUtils.java b/src/org/andengine/util/BitmapUtils.java new file mode 100644 index 000000000..73cb25610 --- /dev/null +++ b/src/org/andengine/util/BitmapUtils.java @@ -0,0 +1,58 @@ +package org.andengine.util; + +import android.graphics.Bitmap; + +/** + * (c) 2013 Nicolas Gramlich + * + * @author Nicolas Gramlich + * @since 18:52:32 - 18.02.2013 + */ +public final class BitmapUtils { + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + // =========================================================== + // Constructors + // =========================================================== + + private BitmapUtils() { + + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods from SuperClass/Interfaces + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + /** + * @param pBitmap + * + * @return a {@link Bitmap} that is {@link Bitmap#isMutable()}. If pBitmap is {@link Bitmap#isMutable()} then pBitmap is returned, otherwise a new {@link Bitmap} instance is returned that is {@link Bitmap#isMutable()} and pBitmap is {@link Bitmap#recycle()}d. + */ + public static Bitmap ensureBitmapIsMutable(final Bitmap pBitmap) { + if (pBitmap.isMutable()) { + return pBitmap; + } else { + final Bitmap mutableBitmap = pBitmap.copy(pBitmap.getConfig(), true); + pBitmap.recycle(); + return mutableBitmap; + } + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== +} diff --git a/src/org/andengine/util/Bluetooth.java b/src/org/andengine/util/Bluetooth.java new file mode 100644 index 000000000..face24cb8 --- /dev/null +++ b/src/org/andengine/util/Bluetooth.java @@ -0,0 +1,71 @@ +package org.andengine.util; + +import org.andengine.util.system.SystemUtils; +import org.andengine.util.system.SystemUtils.SystemUtilsException; + +import android.content.Context; +import android.content.pm.PackageManager; +import android.os.Build; + +/** + * (c) 2010 Nicolas Gramlich + * (c) 2011 Zynga Inc. + * + * @author Nicolas Gramlich + * @since 21:44:07 - 04.03.2011 + */ +public final class Bluetooth { + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + private static Boolean sSupported; + + // =========================================================== + // Constructors + // =========================================================== + + private Bluetooth() { + + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + public static boolean isSupported(final Context pContext) { + if (sSupported == null) { + if (SystemUtils.isAndroidVersionOrHigher(Build.VERSION_CODES.ECLAIR_MR1)) { + try { + sSupported = SystemUtils.hasSystemFeature(pContext, PackageManager.FEATURE_BLUETOOTH); + } catch (final SystemUtilsException e) { + sSupported = Boolean.FALSE; + } + } else { + sSupported = Boolean.FALSE; + } + } + + return sSupported; + } + + public static boolean isSupportedByAndroidVersion() { + return SystemUtils.isAndroidVersionOrHigher(Build.VERSION_CODES.ECLAIR_MR1); + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== +} diff --git a/src/org/andengine/util/ConnectivityUtils.java b/src/org/andengine/util/ConnectivityUtils.java new file mode 100644 index 000000000..e12a219b3 --- /dev/null +++ b/src/org/andengine/util/ConnectivityUtils.java @@ -0,0 +1,176 @@ +package org.andengine.util; + +import org.andengine.util.exception.AndEngineException; +import org.andengine.util.system.SystemUtils; + +import android.annotation.TargetApi; +import android.content.Context; +import android.net.ConnectivityManager; +import android.net.NetworkInfo; +import android.os.Build; + +/** + * (c) 2013 Nicolas Gramlich + * + * @author Nicolas Gramlich + * @since 19:33:01 - 21.05.2013 + */ +public final class ConnectivityUtils { + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + // =========================================================== + // Constructors + // =========================================================== + + private ConnectivityUtils() { + + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + public static ConnectivityManager getConnectivityManager(final Context pContext) { + return (ConnectivityManager) pContext.getSystemService(Context.CONNECTIVITY_SERVICE); + } + + /** + * @param pContext + * @param pNetworkType {@link ConnectivityManager#TYPE_WIFI}, etc... + * @return + */ + public static NetworkInfo getNetworkInfo(final Context pContext, final int pNetworkType) { + return ConnectivityUtils.getConnectivityManager(pContext).getNetworkInfo(pNetworkType); + } + + /** + * @param pContext + * @param pNetworkType {@link ConnectivityManager#TYPE_WIFI}, etc... + * @return + */ + public static boolean isNetworkAvailable(final Context pContext, final int pNetworkType) { + return ConnectivityUtils.getNetworkInfo(pContext, pNetworkType).isAvailable(); + } + + /** + * @param pContext + * @param pNetworkType {@link ConnectivityManager#TYPE_WIFI}, etc... + * @return + */ + public static boolean isNetworkConnected(final Context pContext, final int pNetworkType) { + return ConnectivityUtils.getNetworkInfo(pContext, pNetworkType).isConnected(); + } + + /** + * @param pContext + * @param pNetworkType {@link ConnectivityManager#TYPE_WIFI}, etc... + * @return + */ + public static boolean isNetworkConnectedOrConnecting(final Context pContext, final int pNetworkType) { + return ConnectivityUtils.getNetworkInfo(pContext, pNetworkType).isConnectedOrConnecting(); + } + + @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2) + public static boolean isEthernetAvailable(final Context pContext) throws ConnectivityUtilsException { + if (SystemUtils.isAndroidVersionOrHigher(Build.VERSION_CODES.HONEYCOMB_MR2)) { + return ConnectivityUtils.isNetworkAvailable(pContext, ConnectivityManager.TYPE_ETHERNET); + } else { + throw new ConnectivityUtilsException(); + } + } + + @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2) + public static boolean isEthernetAvailable(final Context pContext, final boolean pDefault) { + if (SystemUtils.isAndroidVersionOrHigher(Build.VERSION_CODES.HONEYCOMB_MR2)) { + return ConnectivityUtils.isNetworkAvailable(pContext, ConnectivityManager.TYPE_ETHERNET); + } else { + return pDefault; + } + } + + @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2) + public static boolean isEthernetConnected(final Context pContext) throws ConnectivityUtilsException { + if (SystemUtils.isAndroidVersionOrHigher(Build.VERSION_CODES.HONEYCOMB_MR2)) { + return ConnectivityUtils.isNetworkConnected(pContext, ConnectivityManager.TYPE_ETHERNET); + } else { + throw new ConnectivityUtilsException(); + } + } + + @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2) + public static boolean isEthernetConnected(final Context pContext, final boolean pDefault) { + if (SystemUtils.isAndroidVersionOrHigher(Build.VERSION_CODES.HONEYCOMB_MR2)) { + return ConnectivityUtils.isNetworkConnected(pContext, ConnectivityManager.TYPE_ETHERNET); + } else { + return pDefault; + } + } + + @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2) + public static boolean isEthernetConnectedOrConnecting(final Context pContext) throws ConnectivityUtilsException { + if (SystemUtils.isAndroidVersionOrHigher(Build.VERSION_CODES.HONEYCOMB_MR2)) { + return ConnectivityUtils.isNetworkConnectedOrConnecting(pContext, ConnectivityManager.TYPE_ETHERNET); + } else { + throw new ConnectivityUtilsException(); + } + } + + @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2) + public static boolean isEthernetConnectedOrConnecting(final Context pContext, final boolean pDefault) { + if (SystemUtils.isAndroidVersionOrHigher(Build.VERSION_CODES.HONEYCOMB_MR2)) { + return ConnectivityUtils.isNetworkConnectedOrConnecting(pContext, ConnectivityManager.TYPE_ETHERNET); + } else { + return pDefault; + } + } + + public static boolean isWifiAvailable(final Context pContext) throws ConnectivityUtilsException { + return ConnectivityUtils.isNetworkAvailable(pContext, ConnectivityManager.TYPE_WIFI); + } + + public static boolean isWifiConnected(final Context pContext) { + return ConnectivityUtils.isNetworkConnected(pContext, ConnectivityManager.TYPE_WIFI); + } + + public static boolean isWifiConnectedOrConnecting(final Context pContext) { + return ConnectivityUtils.isNetworkConnectedOrConnecting(pContext, ConnectivityManager.TYPE_WIFI); + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== + + public static class ConnectivityUtilsException extends AndEngineException { + // =========================================================== + // Constants + // =========================================================== + + private static final long serialVersionUID = 4955967914807211384L; + + // =========================================================== + // Constructors + // =========================================================== + + public ConnectivityUtilsException() { + + } + + public ConnectivityUtilsException(final Throwable pThrowable) { + super(pThrowable); + } + } +} diff --git a/src/org/andengine/util/Constants.java b/src/org/andengine/util/Constants.java index ca2f28169..09228ae73 100644 --- a/src/org/andengine/util/Constants.java +++ b/src/org/andengine/util/Constants.java @@ -1,9 +1,9 @@ package org.andengine.util; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 13:52:21 - 08.03.2010 */ diff --git a/src/org/andengine/util/DatabaseUtils.java b/src/org/andengine/util/DatabaseUtils.java new file mode 100644 index 000000000..2a9b6372a --- /dev/null +++ b/src/org/andengine/util/DatabaseUtils.java @@ -0,0 +1,49 @@ +package org.andengine.util; + +import android.database.Cursor; + +/** + * (c) 2013 Zynga Inc. + * + * @author Nicolas Gramlich + * @since 15:30:15 - 23.01.2013 + */ +public final class DatabaseUtils { + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + // =========================================================== + // Constructors + // =========================================================== + + private DatabaseUtils() { + + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + public static final void close(final Cursor pCursor) { + if (pCursor != null) { + pCursor.close(); + } + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== +} diff --git a/src/org/andengine/util/DialogUtils.java b/src/org/andengine/util/DialogUtils.java index 5aad4a09e..3f00e6630 100644 --- a/src/org/andengine/util/DialogUtils.java +++ b/src/org/andengine/util/DialogUtils.java @@ -1,16 +1,18 @@ package org.andengine.util; +import android.app.Activity; import android.app.Dialog; +import android.os.Bundle; import android.view.WindowManager; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 13:04:09 - 12.05.2011 */ -public class DialogUtils { +public final class DialogUtils { // =========================================================== // Constants // =========================================================== @@ -23,6 +25,10 @@ public class DialogUtils { // Constructors // =========================================================== + private DialogUtils() { + + } + // =========================================================== // Getter & Setter // =========================================================== @@ -39,6 +45,25 @@ public static void keepScreenOn(final Dialog pDialog) { pDialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); } + @Deprecated + public static void showDialogOnUiThread(final Activity pActivity, final int pDialogID) { + DialogUtils.showDialogOnUiThread(pActivity, pDialogID, null); + } + + @Deprecated + public static void showDialogOnUiThread(final Activity pActivity, final int pDialogID, final Bundle pBundle) { + if (ActivityUtils.isOnUiThread()) { + pActivity.showDialog(pDialogID, pBundle); + } else { + pActivity.runOnUiThread(new Runnable() { + @Override + public void run() { + pActivity.showDialog(pDialogID, pBundle); + } + }); + } + } + // =========================================================== // Inner and Anonymous Classes // =========================================================== diff --git a/src/org/andengine/util/EthernetUtils.java b/src/org/andengine/util/EthernetUtils.java new file mode 100644 index 000000000..67d648615 --- /dev/null +++ b/src/org/andengine/util/EthernetUtils.java @@ -0,0 +1,130 @@ +package org.andengine.util; + +import java.net.InetAddress; +import java.net.NetworkInterface; +import java.net.SocketException; +import java.net.UnknownHostException; +import java.util.Enumeration; + +import org.andengine.util.exception.AndEngineException; +import org.andengine.util.system.SystemUtils; + +import android.annotation.TargetApi; +import android.os.Build; + +/** + * (c) 2013 Nicolas Gramlich + * + * @author Nicolas Gramlich + * @since 16:54:01 - 20.03.2013 + */ +public final class EthernetUtils { + // =========================================================== + // Constants + // =========================================================== + + private static final String IP_DEFAULT = "0.0.0.0"; + + // =========================================================== + // Fields + // =========================================================== + + // =========================================================== + // Constructors + // =========================================================== + + private EthernetUtils() { + + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + @TargetApi(Build.VERSION_CODES.GINGERBREAD) + public static byte[] getEthernetIPAddressRaw() throws EthernetUtilsException { + try { + byte[] ipv6Address = null; + + final Enumeration networkInterfaceEnumeration = NetworkInterface.getNetworkInterfaces(); + while (networkInterfaceEnumeration.hasMoreElements()) { + final NetworkInterface networkInterface = networkInterfaceEnumeration.nextElement(); + if (SystemUtils.isAndroidVersionOrLower(Build.VERSION_CODES.FROYO) || !networkInterface.isLoopback()) { + final Enumeration inetAddressEnumeration = networkInterface.getInetAddresses(); + while (inetAddressEnumeration.hasMoreElements()) { + final InetAddress inetAddress = inetAddressEnumeration.nextElement(); + + if (!inetAddress.isLoopbackAddress()) { + final byte[] ipAddress = inetAddress.getAddress(); + if (ipAddress.length == IPUtils.IPV4_LENGTH) { + return ipAddress; + } else { + ipv6Address = ipAddress; + } + } + } + } + } + + if (ipv6Address != null) { + return ipv6Address; + } else { + throw new EthernetUtilsException("No ethernet IP found that is not bound to localhost!"); + } + } catch (final SocketException e) { + throw new EthernetUtilsException("Unexpected error!", e); + } + } + + public static String getEthernetIPAddress() throws EthernetUtilsException { + try { + return IPUtils.ipAddressToString(EthernetUtils.getEthernetIPAddressRaw()); + } catch (final UnknownHostException e) { + throw new EthernetUtilsException("Unexpected error!", e); + } + } + + public static boolean getEthernetIPAddressValid() throws EthernetUtilsException { // TODO! + return !EthernetUtils.IP_DEFAULT.equals(EthernetUtils.getEthernetIPAddress()); + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== + + public static class EthernetUtilsException extends AndEngineException { + // =========================================================== + // Constants + // =========================================================== + + private static final long serialVersionUID = 795214345441314983L; + + // =========================================================== + // Constructors + // =========================================================== + + public EthernetUtilsException() { + + } + + public EthernetUtilsException(final Throwable pThrowable) { + super(pThrowable); + } + + private EthernetUtilsException(final String pMessage) { + super(pMessage); + } + + private EthernetUtilsException(final String pMessage, final Throwable pThrowable) { + super(pMessage, pThrowable); + } + } +} diff --git a/src/org/andengine/util/FileUtils.java b/src/org/andengine/util/FileUtils.java index 02766efce..51fd01016 100644 --- a/src/org/andengine/util/FileUtils.java +++ b/src/org/andengine/util/FileUtils.java @@ -13,13 +13,13 @@ import android.os.Environment; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 13:53:33 - 20.06.2010 */ -public class FileUtils { +public final class FileUtils { // =========================================================== // Constants // =========================================================== @@ -32,6 +32,10 @@ public class FileUtils { // Constructors // =========================================================== + private FileUtils() { + + } + // =========================================================== // Getter & Setter // =========================================================== @@ -44,6 +48,10 @@ public class FileUtils { // Methods // =========================================================== + public static String[] readLines(final File pFile) throws IOException { + return StreamUtils.readLines(new FileInputStream(pFile)); + } + public static void copyToExternalStorage(final Context pContext, final int pSourceResourceID, final String pFilename) throws FileNotFoundException { FileUtils.copyToExternalStorage(pContext, pContext.getResources().openRawResource(pSourceResourceID), pFilename); } @@ -180,26 +188,24 @@ public static void copyFile(final File pSourceFile, final File pDestinationFile) } /** - * Deletes all files and sub-directories under dir. Returns - * true if all deletions were successful. If a deletion fails, the method - * stops attempting to delete and returns false. - * + * Recursively deletes all files and sub-directories under pFileOrDirectory. + * * @param pFileOrDirectory - * @return + * @return true, if all deletions were successful. false, if a deletion fails (the recursion is stopped then). */ - public static boolean deleteDirectory(final File pFileOrDirectory) { - if(pFileOrDirectory.isDirectory()) { + public static boolean delete(final File pFileOrDirectory) { + if (pFileOrDirectory.isDirectory()) { final String[] children = pFileOrDirectory.list(); - final int childrenCount = children.length; - for(int i = 0; i < childrenCount; i++) { - final boolean success = FileUtils.deleteDirectory(new File(pFileOrDirectory, children[i])); - if(!success) { + final int childCount = children.length; + for (int i = 0; i < childCount; i++) { + final boolean success = FileUtils.delete(new File(pFileOrDirectory, children[i])); + if (!success) { return false; } } } - // The directory is now empty so delete it + /* The directory is now empty so delete it. */ return pFileOrDirectory.delete(); } diff --git a/src/org/andengine/util/GooglePlayUtils.java b/src/org/andengine/util/GooglePlayUtils.java new file mode 100644 index 000000000..f0e4d566c --- /dev/null +++ b/src/org/andengine/util/GooglePlayUtils.java @@ -0,0 +1,82 @@ +package org.andengine.util; + +import org.andengine.util.system.SystemUtils; + +import android.app.Activity; +import android.content.Context; +import android.content.Intent; +import android.net.Uri; + +/** + * (c) 2013 Nicolas Gramlich + * + * @author Nicolas Gramlich + * @since 20:49:32 - 24.04.2013 + */ +public final class GooglePlayUtils { + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + // =========================================================== + // Constructors + // =========================================================== + + private GooglePlayUtils() { + + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods from SuperClass/Interfaces + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + public static void startGooglePlayActivity(final Context pContext) { + GooglePlayUtils.startGooglePlayActivity(pContext, SystemUtils.getPackageName(pContext)); + } + + public static void startGooglePlayActivity(final Context pContext, final String pPackageName) { + final Intent googlePlayAppIntent = getGooglePlayAppIntent(pPackageName); + if (IntentUtils.isIntentResolvable(pContext, googlePlayAppIntent)) { + pContext.startActivity(googlePlayAppIntent); + } else { + pContext.startActivity(getGooglePlayWebsiteIntent(pPackageName)); + } + } + + public static void startGooglePlayActivityForResult(final Activity pActivity, final int pRequestCode) { + GooglePlayUtils.startGooglePlayActivityForResult(pActivity, SystemUtils.getPackageName(pActivity), pRequestCode); + } + + public static void startGooglePlayActivityForResult(final Activity pActivity, final String pPackageName, final int pRequestCode) { + final Intent googlePlayAppIntent = getGooglePlayAppIntent(pPackageName); + if (IntentUtils.isIntentResolvable(pActivity, googlePlayAppIntent)) { + pActivity.startActivityForResult(googlePlayAppIntent, pRequestCode); + } else { + pActivity.startActivityForResult(getGooglePlayWebsiteIntent(pPackageName), pRequestCode); + } + } + + public static Intent getGooglePlayAppIntent(final String pPackageName) { + return new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + pPackageName)); + } + + public static Intent getGooglePlayWebsiteIntent(final String pPackageName) { + return new Intent(Intent.ACTION_VIEW, Uri.parse("http://play.google.com/store/apps/details?id=" + pPackageName)); + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== +} diff --git a/src/org/andengine/util/HashUtils.java b/src/org/andengine/util/HashUtils.java new file mode 100644 index 000000000..fbd6687a4 --- /dev/null +++ b/src/org/andengine/util/HashUtils.java @@ -0,0 +1,65 @@ +package org.andengine.util; + + +/** + * (c) 2013 Nicolas Gramlich + * + * @author Nicolas Gramlich + * @since 00:02:12 - 23.03.2013 + */ +public final class HashUtils { + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + // =========================================================== + // Constructors + // =========================================================== + + private HashUtils() { + + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + public static int getHashCode(final byte ... pBytes) { + final int prime = 31; + int result = 1; + + for (int i = 0; i < pBytes.length; i++) { + result = prime * result + pBytes[i]; + } + + return result; + } + + public static int getHashCode(final Object ... pObjects) { + final int prime = 31; + int result = 1; + + for (int i = 0; i < pObjects.length; i++) { + final Object object = pObjects[i]; + result = prime * result + ((object == null) ? 0 : object.hashCode()); + } + + return result; + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== +} diff --git a/src/org/andengine/util/IDisposable.java b/src/org/andengine/util/IDisposable.java index 5bb6410b7..a776f4651 100644 --- a/src/org/andengine/util/IDisposable.java +++ b/src/org/andengine/util/IDisposable.java @@ -3,7 +3,7 @@ import org.andengine.util.exception.AndEngineRuntimeException; /** - * (c) Zynga 2012 + * (c) 2012 Zynga Inc. * * @author Nicolas Gramlich * @since 00:45:48 - 17.01.2012 @@ -40,18 +40,18 @@ public class AlreadyDisposedException extends AndEngineRuntimeException { // =========================================================== public AlreadyDisposedException() { - + } - public AlreadyDisposedException(String pMessage) { + public AlreadyDisposedException(final String pMessage) { super(pMessage); } - public AlreadyDisposedException(Throwable pThrowable) { + public AlreadyDisposedException(final Throwable pThrowable) { super(pThrowable); } - - public AlreadyDisposedException(String pMessage, Throwable pThrowable) { + + public AlreadyDisposedException(final String pMessage, final Throwable pThrowable) { super(pMessage, pThrowable); } diff --git a/src/org/andengine/util/IMatcher.java b/src/org/andengine/util/IMatcher.java index d4317f56a..d9c097644 100644 --- a/src/org/andengine/util/IMatcher.java +++ b/src/org/andengine/util/IMatcher.java @@ -1,9 +1,9 @@ package org.andengine.util; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 12:32:22 - 26.12.2010 */ @@ -16,6 +16,5 @@ public interface IMatcher { // Methods // =========================================================== - public boolean matches(final T pObject); + public boolean matches(final T pItem); } - diff --git a/src/org/andengine/util/IPUtils.java b/src/org/andengine/util/IPUtils.java new file mode 100644 index 000000000..58504a7dc --- /dev/null +++ b/src/org/andengine/util/IPUtils.java @@ -0,0 +1,73 @@ +package org.andengine.util; + +import java.net.InetAddress; +import java.net.UnknownHostException; +import java.util.regex.Pattern; + +/** + * (c) 2010 Nicolas Gramlich + * (c) 2011 Zynga Inc. + * + * @author Nicolas Gramlich + * @since 17:16:20 - 20.06.2010 + */ +public class IPUtils { + // =========================================================== + // Constants + // =========================================================== + + public static final String LOCALHOST_IP = "127.0.0.1"; + + private static final String REGEXP_255 = "(25[0-5]|2[0-4]\\d|[01]?\\d\\d?)"; // 25(<=5) or 2(<=4)(<=9) or (0|1)(<=9)(<=9) + public static final String REGEXP_IPv4 = REGEXP_255 + "\\." + REGEXP_255 + "\\." + REGEXP_255 + "\\." + REGEXP_255; + + private static final Pattern IPv4_PATTERN = Pattern.compile(REGEXP_IPv4); + + public static final int IPV4_LENGTH = 4; + public static final int IPV6_LENGTH = 16; + + // =========================================================== + // Fields + // =========================================================== + + // =========================================================== + // Constructors + // =========================================================== + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + public static byte[] ipv4AddressToIPAddress(final int pIPv4Address) { + final byte[] ip = new byte[4]; + ip[0] = (byte)((pIPv4Address >> 0) & 0xff); + ip[1] = (byte)((pIPv4Address >> 8) & 0xff); + ip[2] = (byte)((pIPv4Address >> 16) & 0xff); + ip[3] = (byte)((pIPv4Address >> 24) & 0xff); + return ip; + } + + public static String ipAddressToString(final byte[] pIPAddress) throws UnknownHostException { + return InetAddress.getByAddress(pIPAddress).getHostAddress(); + } + + public static byte[] stringToIPAddress(final String pString) throws UnknownHostException { + return InetAddress.getByName(pString).getAddress(); + } + + public static boolean isValidIPv4(final String pIPv4Address) { + return IPv4_PATTERN.matcher(pIPv4Address).matches(); + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== +} diff --git a/src/org/andengine/util/IntentUtils.java b/src/org/andengine/util/IntentUtils.java new file mode 100644 index 000000000..64a95d4d6 --- /dev/null +++ b/src/org/andengine/util/IntentUtils.java @@ -0,0 +1,102 @@ +package org.andengine.util; + +import java.util.List; + +import org.andengine.util.exception.AndEngineException; + +import android.content.Context; +import android.content.Intent; +import android.content.pm.ResolveInfo; + +/** + * (c) 2013 Nicolas Gramlich + * + * @author Nicolas Gramlich + * @since 12:30:32 - 14.04.2013 + */ +public final class IntentUtils { + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + // =========================================================== + // Constructors + // =========================================================== + + private IntentUtils() { + + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods from SuperClass/Interfaces + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + public static boolean isIntentResolvable(final Context pContext, final Intent pIntent) { + final List resolveInfo = pContext.getPackageManager().queryIntentActivities(pIntent, 0); + return (resolveInfo != null) && !resolveInfo.isEmpty(); + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== + + public static class IntentNotResolveableException extends AndEngineException { + // =========================================================== + // Constants + // =========================================================== + + private static final long serialVersionUID = 249698759677552332L; + + // =========================================================== + // Fields + // =========================================================== + + // =========================================================== + // Constructors + // =========================================================== + + public IntentNotResolveableException() { + + } + + public IntentNotResolveableException(final String pMessage) { + super(pMessage); + } + + public IntentNotResolveableException(final Throwable pThrowable) { + super(pThrowable); + } + + public IntentNotResolveableException(final String pMessage, final Throwable pThrowable) { + super(pMessage, pThrowable); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== + } +} diff --git a/src/org/andengine/util/MailUtils.java b/src/org/andengine/util/MailUtils.java new file mode 100644 index 000000000..31a8dbfa4 --- /dev/null +++ b/src/org/andengine/util/MailUtils.java @@ -0,0 +1,108 @@ +package org.andengine.util; + +import org.andengine.util.mime.MIMEType; + +import android.content.Context; +import android.content.Intent; +import android.net.Uri; +import android.text.TextUtils; + +/** + * (c) 2013 Nicolas Gramlich + * + * @author Nicolas Gramlich + * @since 14:34:09 - 14.04.2013 + */ +public final class MailUtils { + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + // =========================================================== + // Constructors + // =========================================================== + + private MailUtils() { + + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + public static void sendMail(final Context pContext, final int pIntentChooserTitleResID, final String [] pRecipients, final int pSubjectResID, final int pBodyResID) { + final String intentChooserTitle = pContext.getString(pIntentChooserTitleResID); + final String subject = pContext.getString(pSubjectResID); + final String body = pContext.getString(pBodyResID); + MailUtils.sendMail(pContext, intentChooserTitle, pRecipients, subject, body); + } + + public static void sendMail(final Context pContext, final String pIntentChooserTitle, final String [] pRecipients, final String pSubject, final String pBody) { + final Intent sendMailIntent = MailUtils.getSendMailIntent(pContext, pRecipients, pSubject, pBody); + + pContext.startActivity(Intent.createChooser(sendMailIntent, pIntentChooserTitle)); + } + + public static Intent getSendMailIntent(final Context pContext, final String [] pRecipients, final String pSubject, final String pBody) { + /* Attempt using ACTION_SENDTO: */ + final Intent sendToIntent = new Intent(Intent.ACTION_SENDTO); + + final StringBuilder sendToUriStringBuilder = new StringBuilder(); + sendToUriStringBuilder.append("mailto:"); + if (!org.andengine.util.TextUtils.isEmpty(pRecipients)) { + final String recipientsString = TextUtils.join(",", pRecipients); + sendToUriStringBuilder.append(Uri.encode(recipientsString)); + } + if (!TextUtils.isEmpty(pSubject)) { + sendToUriStringBuilder.append("?subject=").append(Uri.encode(pSubject)); + } + if (!TextUtils.isEmpty(pBody)) { + if (TextUtils.isEmpty(pSubject)) { + sendToUriStringBuilder.append("?body="); + } else { + sendToUriStringBuilder.append("&body="); + } + sendToUriStringBuilder.append(Uri.encode(pBody)); + } + + final String sendToUriString = sendToUriStringBuilder.toString(); + final Uri sendToUri = Uri.parse(sendToUriString); + sendToIntent.setData(sendToUri); + + if (IntentUtils.isIntentResolvable(pContext, sendToIntent)) { + return sendToIntent; + } else { + /* Fallback using ACTION_SEND: */ + final Intent sendIntent = new Intent(Intent.ACTION_SEND); + + sendIntent.setType(MIMEType.TEXT.getTypeString()); + if (!org.andengine.util.TextUtils.isEmpty(pRecipients)) { + sendIntent.putExtra(Intent.EXTRA_EMAIL, pRecipients); + } + if (!TextUtils.isEmpty(pSubject)) { + sendIntent.putExtra(Intent.EXTRA_SUBJECT, pSubject); + } + if (!TextUtils.isEmpty(pBody)) { + sendIntent.putExtra(Intent.EXTRA_TEXT, pBody); + } + + return sendIntent; + } + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== +} diff --git a/src/org/andengine/util/ProbabilityGenerator.java b/src/org/andengine/util/ProbabilityGenerator.java index 15e5f1c40..b66f44b29 100644 --- a/src/org/andengine/util/ProbabilityGenerator.java +++ b/src/org/andengine/util/ProbabilityGenerator.java @@ -6,9 +6,9 @@ import org.andengine.util.math.MathUtils; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 16:54:24 - 07.11.2010 */ @@ -40,7 +40,7 @@ public class ProbabilityGenerator { // Methods // =========================================================== - public void add(final float pFactor, final T ... pElements){ + public void add(final float pFactor, final T ... pElements) { this.mProbabilitySum += pFactor; this.mEntries.add(new Entry(pFactor, pElements)); } @@ -50,10 +50,10 @@ public T next() { final ArrayList> factors = this.mEntries; - for(int i = factors.size() - 1; i >= 0; i--){ + for (int i = factors.size() - 1; i >= 0; i--) { final Entry entry = factors.get(i); random -= entry.mFactor; - if(random <= 0){ + if (random <= 0) { return entry.getReturnValue(); } } @@ -87,7 +87,7 @@ private static class Entry { // Constructors // =========================================================== - public Entry(final float pFactor, final T ... pData){ + public Entry(final float pFactor, final T ... pData) { this.mFactor = pFactor; this.mData = pData; } @@ -97,10 +97,10 @@ public Entry(final float pFactor, final T ... pData){ // =========================================================== public T getReturnValue() { - if(this.mData.length == 1){ + if (this.mData.length == 1) { return this.mData[0]; - }else{ - return ArrayUtils.random(mData); + } else { + return ArrayUtils.random(this.mData); } } diff --git a/src/org/andengine/util/SAXUtils.java b/src/org/andengine/util/SAXUtils.java index 95240ed83..27360c660 100644 --- a/src/org/andengine/util/SAXUtils.java +++ b/src/org/andengine/util/SAXUtils.java @@ -3,9 +3,9 @@ import org.xml.sax.Attributes; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 22:02:09 - 21.07.2010 */ @@ -22,6 +22,10 @@ public final class SAXUtils { // Constructors // =========================================================== + private SAXUtils() { + + } + // =========================================================== // Getter & Setter // =========================================================== @@ -34,6 +38,18 @@ public final class SAXUtils { // Methods // =========================================================== + public static final boolean hasAttribute(final Attributes pAttributes, final String pAttributeName) { + final String value = pAttributes.getValue("", pAttributeName); + return value != null; + } + + public static final void hasAttributeOrThrow(final Attributes pAttributes, final String pAttributeName) throws IllegalArgumentException { + final String value = pAttributes.getValue("", pAttributeName); + if (value == null) { + throw new IllegalArgumentException("No value found for attribute: '" + pAttributeName + "'"); + } + } + public static final String getAttribute(final Attributes pAttributes, final String pAttributeName, final String pDefaultValue) { final String value = pAttributes.getValue("", pAttributeName); return (value != null) ? value : pDefaultValue; @@ -41,7 +57,7 @@ public static final String getAttribute(final Attributes pAttributes, final Stri public static final String getAttributeOrThrow(final Attributes pAttributes, final String pAttributeName) { final String value = pAttributes.getValue("", pAttributeName); - if(value != null) { + if (value != null) { return value; } else { throw new IllegalArgumentException("No value found for attribute: '" + pAttributeName + "'"); diff --git a/src/org/andengine/util/SocketUtils.java b/src/org/andengine/util/SocketUtils.java index 0503345a0..20a2a2adf 100644 --- a/src/org/andengine/util/SocketUtils.java +++ b/src/org/andengine/util/SocketUtils.java @@ -8,9 +8,9 @@ import org.andengine.util.debug.Debug; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 14:42:15 - 18.09.2009 */ @@ -27,6 +27,10 @@ public final class SocketUtils { // Constructors // =========================================================== + private SocketUtils() { + + } + // =========================================================== // Getter & Setter // =========================================================== @@ -40,13 +44,13 @@ public final class SocketUtils { // =========================================================== public static final void closeSocket(final DatagramSocket pDatagramSocket) { - if(pDatagramSocket != null && !pDatagramSocket.isClosed()) { + if (pDatagramSocket != null && !pDatagramSocket.isClosed()) { pDatagramSocket.close(); } } public static final void closeSocket(final Socket pSocket) { - if(pSocket != null && !pSocket.isClosed()) { + if (pSocket != null && !pSocket.isClosed()) { try { pSocket.close(); } catch (final IOException e) { @@ -56,7 +60,7 @@ public static final void closeSocket(final Socket pSocket) { } public static final void closeSocket(final ServerSocket pServerSocket) { - if(pServerSocket != null && !pServerSocket.isClosed()) { + if (pServerSocket != null && !pServerSocket.isClosed()) { try { pServerSocket.close(); } catch (final IOException e) { diff --git a/src/org/andengine/util/StreamUtils.java b/src/org/andengine/util/StreamUtils.java index d96b9792e..473a686f4 100644 --- a/src/org/andengine/util/StreamUtils.java +++ b/src/org/andengine/util/StreamUtils.java @@ -11,11 +11,14 @@ import java.io.StringWriter; import java.io.Writer; import java.nio.ByteBuffer; +import java.util.ArrayList; + +import org.andengine.util.debug.Debug; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 15:48:56 - 03.09.2009 */ @@ -36,6 +39,10 @@ public final class StreamUtils { // Constructors // =========================================================== + private StreamUtils() { + + } + // =========================================================== // Getter & Setter // =========================================================== @@ -48,13 +55,30 @@ public final class StreamUtils { // Methods // =========================================================== + public static String[] readLines(final InputStream pInputStream) throws IOException { + return StreamUtils.readLines(new InputStreamReader(pInputStream)); + } + + public static String[] readLines(final Reader pReader) throws IOException { + final BufferedReader reader = new BufferedReader(pReader); + + final ArrayList lines = new ArrayList(); + + String line = null; + while ((line = reader.readLine()) != null) { + lines.add(line); + } + + return lines.toArray(new String[lines.size()]); + } + public static final String readFully(final InputStream pInputStream) throws IOException { final StringWriter writer = new StringWriter(); final char[] buf = new char[StreamUtils.IO_BUFFER_SIZE]; try { final Reader reader = new BufferedReader(new InputStreamReader(pInputStream, "UTF-8")); int read; - while((read = reader.read(buf)) != StreamUtils.END_OF_STREAM) { + while ((read = reader.read(buf)) != StreamUtils.END_OF_STREAM) { writer.write(buf, 0, read); } } finally { @@ -74,7 +98,7 @@ public static final byte[] streamToBytes(final InputStream pInputStream, final i } /** - * @see {@link StreamUtils#streamToBytes(InputStream, int, byte[], int)} + * @see {@link #streamToBytes(InputStream, int, byte[], int)} */ public static final void streamToBytes(final InputStream pInputStream, final int pByteLimit, final byte[] pData) throws IOException { StreamUtils.streamToBytes(pInputStream, pByteLimit, pData, 0); @@ -88,23 +112,23 @@ public static final void streamToBytes(final InputStream pInputStream, final int * @throws IOException */ public static final void streamToBytes(final InputStream pInputStream, final int pByteLimit, final byte[] pData, final int pOffset) throws IOException { - if(pByteLimit > pData.length - pOffset) { + if (pByteLimit > pData.length - pOffset) { throw new IOException("pData is not big enough."); } int pBytesLeftToRead = pByteLimit; int readTotal = 0; int read; - while((read = pInputStream.read(pData, pOffset + readTotal, pBytesLeftToRead)) != StreamUtils.END_OF_STREAM) { + while ((read = pInputStream.read(pData, pOffset + readTotal, pBytesLeftToRead)) != StreamUtils.END_OF_STREAM) { readTotal += read; - if(pBytesLeftToRead > read) { + if (pBytesLeftToRead > read) { pBytesLeftToRead -= read; } else { break; } } - if(readTotal != pByteLimit) { + if (readTotal != pByteLimit) { throw new IOException("ReadLimit: '" + pByteLimit + "', Read: '" + readTotal + "'."); } } @@ -117,7 +141,7 @@ public static final void copy(final InputStream pInputStream, final byte[] pData int dataOffset = 0; final byte[] buf = new byte[StreamUtils.IO_BUFFER_SIZE]; int read; - while((read = pInputStream.read(buf)) != StreamUtils.END_OF_STREAM) { + while ((read = pInputStream.read(buf)) != StreamUtils.END_OF_STREAM) { System.arraycopy(buf, 0, pData, dataOffset, read); dataOffset += read; } @@ -126,7 +150,7 @@ public static final void copy(final InputStream pInputStream, final byte[] pData public static final void copy(final InputStream pInputStream, final ByteBuffer pByteBuffer) throws IOException { final byte[] buf = new byte[StreamUtils.IO_BUFFER_SIZE]; int read; - while((read = pInputStream.read(buf)) != StreamUtils.END_OF_STREAM) { + while ((read = pInputStream.read(buf)) != StreamUtils.END_OF_STREAM) { pByteBuffer.put(buf, 0, read); } } @@ -137,25 +161,25 @@ public static final void copy(final InputStream pInputStream, final ByteBuffer p * * @param pInputStream The input stream to copy from. * @param pOutputStream The output stream to copy to. - * @param pByteLimit not more than so much bytes to read, or unlimited if {@link StreamUtils#END_OF_STREAM}. + * @param pByteLimit not more than so much bytes to read, or unlimited if {@link #END_OF_STREAM}. * * @throws IOException If any error occurs during the copy. */ public static final void copy(final InputStream pInputStream, final OutputStream pOutputStream, final int pByteLimit) throws IOException { - if(pByteLimit == StreamUtils.END_OF_STREAM) { + if (pByteLimit == StreamUtils.END_OF_STREAM) { final byte[] buf = new byte[StreamUtils.IO_BUFFER_SIZE]; int read; - while((read = pInputStream.read(buf)) != StreamUtils.END_OF_STREAM) { + while ((read = pInputStream.read(buf)) != StreamUtils.END_OF_STREAM) { pOutputStream.write(buf, 0, read); } } else { final byte[] buf = new byte[StreamUtils.IO_BUFFER_SIZE]; - final int bufferReadLimit = Math.min((int)pByteLimit, StreamUtils.IO_BUFFER_SIZE); + final int bufferReadLimit = Math.min((int) pByteLimit, StreamUtils.IO_BUFFER_SIZE); long pBytesLeftToRead = pByteLimit; int read; - while((read = pInputStream.read(buf, 0, bufferReadLimit)) != StreamUtils.END_OF_STREAM) { - if(pBytesLeftToRead > read) { + while ((read = pInputStream.read(buf, 0, bufferReadLimit)) != StreamUtils.END_OF_STREAM) { + if (pBytesLeftToRead > read) { pOutputStream.write(buf, 0, read); pBytesLeftToRead -= read; } else { @@ -179,49 +203,34 @@ public static final boolean copyAndClose(final InputStream pInputStream, final O } } - /** - * Closes the specified stream. - * - * @param pCloseable The stream to close. - */ public static final void close(final Closeable pCloseable) { - if(pCloseable != null) { + if (pCloseable != null) { try { pCloseable.close(); } catch (final IOException e) { - e.printStackTrace(); + Debug.e("Error closing Closable", e); } } } - /** - * Flushes and closes the specified stream. - * - * @param pOutputStream The stream to close. - */ - public static final void flushCloseStream(final OutputStream pOutputStream) { - if(pOutputStream != null) { + public static final void flushAndCloseStream(final OutputStream pOutputStream) { + if (pOutputStream != null) { try { pOutputStream.flush(); } catch (final IOException e) { - e.printStackTrace(); + Debug.e("Error flusing OutputStream", e); } finally { StreamUtils.close(pOutputStream); } } } - /** - * Flushes and closes the specified stream. - * - * @param pWriter The Writer to close. - */ - public static final void flushCloseWriter(final Writer pWriter) { - if(pWriter != null) { + public static final void flushAndCloseWriter(final Writer pWriter) { + if (pWriter != null) { try { pWriter.flush(); } catch (final IOException e) { - e.printStackTrace(); + Debug.e("Error flusing Writer", e); } finally { StreamUtils.close(pWriter); } @@ -231,4 +240,4 @@ public static final void flushCloseWriter(final Writer pWriter) { // =========================================================== // Inner and Anonymous Classes // =========================================================== -} \ No newline at end of file +} diff --git a/src/org/andengine/util/TextUtils.java b/src/org/andengine/util/TextUtils.java index 07a270e8f..62f4ec378 100644 --- a/src/org/andengine/util/TextUtils.java +++ b/src/org/andengine/util/TextUtils.java @@ -4,10 +4,12 @@ import java.util.List; import java.util.regex.Pattern; +import org.andengine.util.adt.array.ArrayUtils; + /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 19:01:08 - 03.04.2010 */ @@ -28,6 +30,10 @@ public final class TextUtils { // Constructors // =========================================================== + private TextUtils() { + + } + // =========================================================== // Getter & Setter // =========================================================== @@ -40,14 +46,30 @@ public final class TextUtils { // Methods // =========================================================== + public static final CharSequence pad(final CharSequence pText, final char pPadChar, final int pLength) { + final int padCount = pLength - pText.length(); + if (padCount <= 0) { + return pText; + } else { + final StringBuilder sb = new StringBuilder(); + + sb.append(pText); + for (int i = padCount - 1; i >= 0; i--) { + sb.append(pPadChar); + } + + return sb.toString(); + } + } + public static final CharSequence padFront(final CharSequence pText, final char pPadChar, final int pLength) { final int padCount = pLength - pText.length(); - if(padCount <= 0) { + if (padCount <= 0) { return pText; } else { final StringBuilder sb = new StringBuilder(); - for(int i = padCount - 1; i >= 0; i--) { + for (int i = padCount - 1; i >= 0; i--) { sb.append(pPadChar); } sb.append(pText); @@ -84,7 +106,7 @@ public static final ArrayList split(final CharSequence pText, fina public static final > L split(final CharSequence pText, final char pCharacter, final L pResult) { final int partCount = TextUtils.countOccurrences(pText, pCharacter) + 1; - if(partCount == 0) { + if (partCount == 0) { pResult.add(pText); } else { int from = 0; @@ -104,23 +126,23 @@ public static final > L split(final CharSequence pT public static final String formatStackTrace(final StackTraceElement pStackTraceElement) { return new StringBuilder() - .append(pStackTraceElement.getClassName()) - .append('.') - .append(pStackTraceElement.getMethodName()) - .append('(') - .append(pStackTraceElement.getFileName()) - .append(':') - .append(pStackTraceElement.getLineNumber()) - .append(')') - .toString(); + .append(pStackTraceElement.getClassName()) + .append('.') + .append(pStackTraceElement.getMethodName()) + .append('(') + .append(pStackTraceElement.getFileName()) + .append(':') + .append(pStackTraceElement.getLineNumber()) + .append(')') + .toString(); } public static final String formatStackTrace(final StackTraceElement[] pStackTraceElements) { final StringBuilder sb = new StringBuilder(); final int stackTraceElementCount = pStackTraceElements.length; - for(int i = 0; i < stackTraceElementCount; i++) { + for (int i = 0; i < stackTraceElementCount; i++) { sb.append(pStackTraceElements[i]); - if(i < (stackTraceElementCount - 1)) { + if (i < (stackTraceElementCount - 1)) { sb.append('\n'); } } @@ -133,18 +155,18 @@ public static int countCharacters(final List pTexts) { public static int countCharacters(final List pTexts, final boolean pIgnoreWhitespaces) { int characters = 0; - if(pIgnoreWhitespaces) { - for(int i = pTexts.size() - 1; i >= 0; i--) { + if (pIgnoreWhitespaces) { + for (int i = pTexts.size() - 1; i >= 0; i--) { final CharSequence text = pTexts.get(i); - for(int j = text.length() - 1; j >= 0; j--) { + for (int j = text.length() - 1; j >= 0; j--) { final char character = text.charAt(j); - if(!Character.isWhitespace(character)) { + if (!Character.isWhitespace(character)) { characters++; } } } } else { - for(int i = pTexts.size() - 1; i >= 0; i--) { + for (int i = pTexts.size() - 1; i >= 0; i--) { final CharSequence text = pTexts.get(i); characters += text.length(); } @@ -152,6 +174,67 @@ public static int countCharacters(final List pTexts, final boolean return characters; } + /** + * As opposed to {@link ArrayUtils#isEmpty(Object[])}, this method performs a {@link android.text.TextUtils#isEmpty(String)} check on all elements of the array. + */ + public static boolean isEmpty(final CharSequence[] pTexts) { + if (pTexts == null) { + return true; + } else { + for (int i = pTexts.length - 1; i >= 0; i--) { + if (!android.text.TextUtils.isEmpty(pTexts[i])) { + return false; + } + } + return true; + } + } + + public static final String join(final char pSeparator, final Object ... pStrings) { + final StringBuilder stringBuilder = new StringBuilder(); + + final int count = pStrings.length; + for (int i = 0; i < count; i++) { + stringBuilder.append(pStrings[i]); + if (i < count - 1) { + stringBuilder.append(pSeparator); + } + } + + return stringBuilder.toString(); + } + + public static final String join(final String pSeparator, final Object ... pStrings) { + final StringBuilder stringBuilder = new StringBuilder(); + + final int count = pStrings.length; + for (int i = 0; i < count; i++) { + stringBuilder.append(pStrings[i]); + if (i < count - 1) { + stringBuilder.append(pSeparator); + } + } + + return stringBuilder.toString(); + } + + public static final String ellipsize(final String pText, final String pEllipsis, final int pMaxLength) throws IllegalArgumentException { + final int textLength = pText.length(); + if (textLength > pMaxLength) { + final int ellipsisLength = pEllipsis.length(); + if (ellipsisLength > pMaxLength) { + throw new IllegalArgumentException("pMaxLength: '" + pMaxLength + "' isn't long enough for pEllipsis: '" + pEllipsis + "'."); + } else { + final StringBuilder result = new StringBuilder(); + result.append(pText.substring(0, pMaxLength - ellipsisLength)); + result.append(pEllipsis); + return result.toString(); + } + } else { + return pText; + } + } + // =========================================================== // Inner and Anonymous Classes // =========================================================== diff --git a/src/org/andengine/util/ThreadUtils.java b/src/org/andengine/util/ThreadUtils.java index 45ecc8434..4e79d344b 100644 --- a/src/org/andengine/util/ThreadUtils.java +++ b/src/org/andengine/util/ThreadUtils.java @@ -4,12 +4,12 @@ import org.andengine.util.debug.Debug.DebugLevel; /** - * (c) Zynga 2012 + * (c) 2012 Zynga Inc. * * @author Nicolas Gramlich * @since 12:23:06 - 19.01.2012 */ -public class ThreadUtils { +public final class ThreadUtils { // =========================================================== // Constants // =========================================================== @@ -24,6 +24,10 @@ public class ThreadUtils { // Constructors // =========================================================== + private ThreadUtils() { + + } + // =========================================================== // Getter & Setter // =========================================================== diff --git a/src/org/andengine/util/TimeUtils.java b/src/org/andengine/util/TimeUtils.java index 1067e2689..3803f4daf 100644 --- a/src/org/andengine/util/TimeUtils.java +++ b/src/org/andengine/util/TimeUtils.java @@ -3,9 +3,9 @@ import org.andengine.util.time.TimeConstants; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 22:48:49 - 04.04.2011 */ @@ -22,6 +22,10 @@ public final class TimeUtils implements TimeConstants { // Constructors // =========================================================== + private TimeUtils() { + + } + // =========================================================== // Getter & Setter // =========================================================== @@ -37,15 +41,15 @@ public final class TimeUtils implements TimeConstants { public static final String formatSeconds(final int pSecondsTotal) { return formatSeconds(pSecondsTotal, new StringBuilder()); } - + public static final String formatSeconds(final int pSecondsTotal, final StringBuilder pStringBuilder) { final int minutes = pSecondsTotal / SECONDS_PER_MINUTE; final int seconds = pSecondsTotal % SECONDS_PER_MINUTE; - + pStringBuilder.append(minutes); pStringBuilder.append(':'); - - if(seconds < 10) { + + if (seconds < 10) { pStringBuilder.append('0'); } pStringBuilder.append(seconds); diff --git a/src/org/andengine/util/ViewUtils.java b/src/org/andengine/util/ViewUtils.java index b0fae518d..312e1c543 100644 --- a/src/org/andengine/util/ViewUtils.java +++ b/src/org/andengine/util/ViewUtils.java @@ -6,9 +6,9 @@ import android.view.ViewGroup; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 20:55:35 - 08.09.2009 */ @@ -25,6 +25,10 @@ public final class ViewUtils { // Constructors // =========================================================== + private ViewUtils() { + + } + // =========================================================== // Getter & Setter // =========================================================== @@ -37,11 +41,11 @@ public final class ViewUtils { // Methods // =========================================================== - public static final View inflate(final Context pContext, final int pLayoutID){ + public static final View inflate(final Context pContext, final int pLayoutID) { return LayoutInflater.from(pContext).inflate(pLayoutID, null); } - public static final View inflate(final Context pContext, final int pLayoutID, final ViewGroup pViewGroup){ + public static final View inflate(final Context pContext, final int pLayoutID, final ViewGroup pViewGroup) { return LayoutInflater.from(pContext).inflate(pLayoutID, pViewGroup, true); } diff --git a/src/org/andengine/util/WifiUtils.java b/src/org/andengine/util/WifiUtils.java new file mode 100644 index 000000000..8dcdc8dc2 --- /dev/null +++ b/src/org/andengine/util/WifiUtils.java @@ -0,0 +1,504 @@ +package org.andengine.util; + +import java.lang.reflect.Method; +import java.net.InetAddress; +import java.net.NetworkInterface; +import java.net.SocketException; +import java.net.UnknownHostException; +import java.util.Arrays; +import java.util.Enumeration; + +import org.andengine.util.adt.array.ArrayUtils; +import org.andengine.util.exception.AndEngineException; +import org.andengine.util.exception.MethodNotFoundException; +import org.andengine.util.system.SystemUtils; + +import android.annotation.TargetApi; +import android.content.Context; +import android.net.DhcpInfo; +import android.net.wifi.WifiConfiguration; +import android.net.wifi.WifiManager; +import android.net.wifi.WifiManager.MulticastLock; +import android.os.Build; + +/** + * (c) 2010 Nicolas Gramlich + * (c) 2011 Zynga Inc. + * + * @author Nicolas Gramlich + * @since 16:54:01 - 20.03.2011 + */ +public final class WifiUtils { + // =========================================================== + // Constants + // =========================================================== + + private static final String IP_DEFAULT = "0.0.0.0"; + private static final String[] HOTSPOT_NETWORKINTERFACE_NAMES = { "wl0.1", "wlan0" }; + private static final String MULTICASTLOCK_NAME_DEFAULT = "AndEngineMulticastLock"; + + // =========================================================== + // Fields + // =========================================================== + + // =========================================================== + // Constructors + // =========================================================== + + private WifiUtils() { + + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + public static WifiManager getWifiManager(final Context pContext) { + return (WifiManager) pContext.getSystemService(Context.WIFI_SERVICE); + } + + public static boolean isWifiEnabled(final Context pContext) { + return WifiUtils.getWifiManager(pContext).isWifiEnabled(); + } + + private static void setWifiEnabled(final Context pContext, final boolean pEnabled) { + WifiUtils.getWifiManager(pContext).setWifiEnabled(pEnabled); + } + + public static String getWifiSSID(final Context pContext) { + return WifiUtils.getWifiManager(pContext).getConnectionInfo().getSSID(); + } + + public static String getWifiSSID(final Context pContext, final boolean pStripQuotes) { + final String wifiSSID = WifiUtils.getWifiSSID(pContext); + + if (pStripQuotes) { + return WifiUtils.stripQuotes(wifiSSID); + } else { + return wifiSSID; + } + } + + public static byte[] getWifiIPv4AddressRaw(final Context pContext) { + return IPUtils.ipv4AddressToIPAddress(WifiUtils.getWifiManager(pContext).getConnectionInfo().getIpAddress()); + } + + public static String getWifiIPv4Address(final Context pContext) throws WifiUtilsException { + try { + return IPUtils.ipAddressToString(WifiUtils.getWifiIPv4AddressRaw(pContext)); + } catch (final UnknownHostException e) { + throw new WifiUtilsException("Unexpected error!", e); + } + } + + public static boolean isWifiIPAddressValid(final Context pContext) { + return WifiUtils.getWifiManager(pContext).getConnectionInfo().getIpAddress() != 0; + } + + + /** + * The check currently performed is not sufficient, as some carriers disabled this feature manually! + */ + public static boolean isWifiHotspotSupported(final Context pContext) { + if (SystemUtils.isAndroidVersionOrLower(Build.VERSION_CODES.ECLAIR_MR1)) { + return false; + } else { + final WifiManager wifiManager = WifiUtils.getWifiManager(pContext); + try { + final Method WifiManager_isWifiApEnabled = wifiManager.getClass().getMethod("isWifiApEnabled"); + return WifiManager_isWifiApEnabled != null; + } catch (final Throwable t) { + return false; + } + } + } + + public static boolean isWifiHotspotEnabled(final Context pContext) throws WifiUtilsException { + final WifiManager wifiManager = WifiUtils.getWifiManager(pContext); + + try { + final Method WifiManager_isWifiApEnabled = wifiManager.getClass().getMethod("isWifiApEnabled"); + if (WifiManager_isWifiApEnabled == null) { + throw new WifiUtilsException(new MethodNotFoundException(WifiManager.class.getSimpleName() + ".isWifiApEnabled()")); + } else { + final boolean result = (Boolean) WifiManager_isWifiApEnabled.invoke(wifiManager); + return result; + } + } catch (final Throwable t) { + throw new WifiUtilsException(t); + } + } + + public static boolean isWifiHotspotEnabled(final Context pContext, final boolean pDefault) { + try { + return WifiUtils.isWifiHotspotEnabled(pContext); + } catch (final WifiUtilsException e) { + return pDefault; + } + } + + public static boolean setWifiHostpotEnabled(final Context pContext, final boolean pEnabled) throws WifiUtilsException { + return WifiUtils.setWifiHostpotEnabled(pContext, null, pEnabled); + } + + public static boolean setWifiHostpotEnabled(final Context pContext, final WifiConfiguration pWifiConfiguration, final boolean pEnabled) throws WifiUtilsException { + final WifiManager wifiManager = WifiUtils.getWifiManager(pContext); + + try { + if (pEnabled) { + WifiUtils.setWifiEnabled(pContext, false); + } + + final Method WifiManager_setWifiApEnabled = wifiManager.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class, boolean.class); + if (WifiManager_setWifiApEnabled == null) { + throw new WifiUtilsException(new MethodNotFoundException(WifiManager.class.getSimpleName() + ".setWifiApEnabled(" + WifiConfiguration.class.getSimpleName() + ", " + boolean.class.getSimpleName() + ")")); + } else { + final boolean result = (Boolean) WifiManager_setWifiApEnabled.invoke(wifiManager, pWifiConfiguration, pEnabled); + return result; + } + } catch (final Throwable t) { + throw new WifiUtilsException(t); + } + } + + public static WifiConfiguration getWifiHotspotConfiguration(final Context pContext) throws WifiUtilsException { + final WifiManager wifiManager = WifiUtils.getWifiManager(pContext); + + try { + final Method WifiManager_getWifiApState = wifiManager.getClass().getMethod("getWifiApConfiguration"); + if (WifiManager_getWifiApState == null) { + throw new WifiUtilsException(new MethodNotFoundException(WifiManager.class.getSimpleName() + ".getWifiApConfiguration()")); + } else { + return (WifiConfiguration)WifiManager_getWifiApState.invoke(wifiManager); + } + } catch (final Throwable t) { + throw new WifiUtilsException(t); + } + } + + public static String getWifiHotspotSSID(final Context pContext) throws WifiUtilsException { + return WifiUtils.getWifiHotspotConfiguration(pContext).SSID; + } + + public static String getWifiHotspotSSID(final Context pContext, final boolean pStripQuotes) throws WifiUtilsException { + final String wifiHotspotSSID = WifiUtils.getWifiHotspotSSID(pContext); + + if (pStripQuotes) { + return WifiUtils.stripQuotes(wifiHotspotSSID); + } else { + return wifiHotspotSSID; + } + } + + public static WifiHotspotState getWifiHotspotState(final Context pContext) throws WifiUtilsException { + final WifiManager wifiManager = WifiUtils.getWifiManager(pContext); + + try { + final Method WifiManager_getWifiApState = wifiManager.getClass().getMethod("getWifiApState"); + if (WifiManager_getWifiApState == null) { + throw new WifiUtilsException(new MethodNotFoundException(WifiManager.class.getSimpleName() + ".getWifiApState()")); + } else { + final int result = (Integer) WifiManager_getWifiApState.invoke(wifiManager); + + return WifiHotspotState.fromWifiApState(result); + } + } catch (final Throwable t) { + throw new WifiUtilsException(t); + } + } + + public static boolean isWifiHotspotRunning(final Context pContext) throws WifiUtilsException { + return WifiUtils.getWifiHotspotState(pContext) == WifiHotspotState.ENABLED; + } + + /** + * @return prefers to return an IPv4 address if found, otherwise an IPv6 address. + * @throws WifiUtilsException + */ + @TargetApi(Build.VERSION_CODES.GINGERBREAD) + public static byte[] getWifiHotspotIPAddressRaw() throws WifiUtilsException { + try { + byte[] ipv6Address = null; + + final Enumeration networkInterfaceEnumeration = NetworkInterface.getNetworkInterfaces(); + while (networkInterfaceEnumeration.hasMoreElements()) { + final NetworkInterface networkInterface = networkInterfaceEnumeration.nextElement(); + if (SystemUtils.isAndroidVersionOrLower(Build.VERSION_CODES.FROYO) || !networkInterface.isLoopback()) { + final String networkInterfaceName = networkInterface.getName(); + + if (ArrayUtils.contains(WifiUtils.HOTSPOT_NETWORKINTERFACE_NAMES, networkInterfaceName)) { + final Enumeration inetAddressEnumeration = networkInterface.getInetAddresses(); + while (inetAddressEnumeration.hasMoreElements()) { + final InetAddress inetAddress = inetAddressEnumeration.nextElement(); + if (!inetAddress.isLoopbackAddress()) { + final byte[] ipAddress = inetAddress.getAddress(); + if (ipAddress.length == IPUtils.IPV4_LENGTH) { + return ipAddress; + } else { + ipv6Address = ipAddress; + } + } + } + } + } + } + + if (ipv6Address != null) { + return ipv6Address; + } else { + throw new WifiUtilsException("No IP bound to '" + Arrays.toString(WifiUtils.HOTSPOT_NETWORKINTERFACE_NAMES) + "'!"); + } + } catch (final SocketException e) { + throw new WifiUtilsException("Unexpected error!", e); + } + } + + public static String getWifiHotspotIPAddress() throws WifiUtilsException { + try { + return IPUtils.ipAddressToString(WifiUtils.getWifiHotspotIPAddressRaw()); + } catch (final UnknownHostException e) { + throw new WifiUtilsException("Unexpected error!", e); + } + } + + public static boolean isWifiHotspotIPAddressValid() throws WifiUtilsException { // TODO! + return !WifiUtils.IP_DEFAULT.equals(WifiUtils.getWifiHotspotIPAddress()); + } + + @TargetApi(Build.VERSION_CODES.GINGERBREAD) + public static byte[] getEmulatorIPAddressRaw() throws WifiUtilsException { + try { + byte[] ipv6Address = null; + + final Enumeration networkInterfaceEnumeration = NetworkInterface.getNetworkInterfaces(); + while (networkInterfaceEnumeration.hasMoreElements()) { + final NetworkInterface networkInterface = networkInterfaceEnumeration.nextElement(); + if (SystemUtils.isAndroidVersionOrLower(Build.VERSION_CODES.FROYO) || !networkInterface.isLoopback()) { + final Enumeration inetAddressEnumeration = networkInterface.getInetAddresses(); + while (inetAddressEnumeration.hasMoreElements()) { + final InetAddress inetAddress = inetAddressEnumeration.nextElement(); + if (!inetAddress.isLoopbackAddress()) { + final byte[] ipAddress = inetAddress.getAddress(); + if (ipAddress.length == IPUtils.IPV4_LENGTH) { + return ipAddress; + } else { + ipv6Address = ipAddress; + } + } + } + } + } + + if (ipv6Address != null) { + return ipv6Address; + } else { + throw new WifiUtilsException("No IP found that is not bound to localhost!"); + } + } catch (final SocketException e) { + throw new WifiUtilsException("Unexpected error!", e); + } + } + + public static String getEmulatorIPAddress() throws WifiUtilsException { + try { + return IPUtils.ipAddressToString(WifiUtils.getEmulatorIPAddressRaw()); + } catch (final UnknownHostException e) { + throw new WifiUtilsException("Unexpected error!", e); + } + } + + public static boolean getEmulatorIPAddressValid() throws WifiUtilsException { // TODO! + return !WifiUtils.IP_DEFAULT.equals(WifiUtils.getEmulatorIPAddress()); + } + + + public static boolean isMulticastEnabled(final Context pContext) throws WifiUtilsException { + final WifiManager wifiManager = WifiUtils.getWifiManager(pContext); + + try { + final Method WifiManager_isMulticastEnabled = wifiManager.getClass().getMethod("isMulticastEnabled"); + if (WifiManager_isMulticastEnabled == null) { + throw new WifiUtilsException(new MethodNotFoundException(WifiManager.class.getSimpleName() + ".isMulticastEnabled()")); + } else { + final boolean result = (Boolean) WifiManager_isMulticastEnabled.invoke(wifiManager); + return result; + } + } catch (final Throwable t) { + throw new WifiUtilsException(t); + } + } + + public static boolean isMulticastEnabled(final Context pContext, final boolean pDefault) { + try { + return WifiUtils.isMulticastEnabled(pContext); + } catch (final WifiUtilsException e) { + return pDefault; + } + } + + public static MulticastLock aquireMulticastLock(final Context pContext) { + return WifiUtils.aquireMulticastLock(pContext, WifiUtils.MULTICASTLOCK_NAME_DEFAULT); + } + + public static MulticastLock aquireMulticastLock(final Context pContext, final String pMulticastLockName) { + final WifiManager wifiManager = WifiUtils.getWifiManager(pContext); + final MulticastLock multicastLock = wifiManager.createMulticastLock(pMulticastLockName); + multicastLock.setReferenceCounted(true); + multicastLock.acquire(); + return multicastLock; + } + + public static void releaseMulticastLock(final MulticastLock pMulticastLock) { + if (pMulticastLock.isHeld()) { + pMulticastLock.release(); + } + } + + public static byte[] getBroadcastIPAddressRaw(final Context pContext) throws WifiUtilsException { + final WifiManager wifiManager = WifiUtils.getWifiManager(pContext); + final DhcpInfo dhcp = wifiManager.getDhcpInfo(); + // TODO handle null somehow... + + final int broadcast = (dhcp.ipAddress & dhcp.netmask) | ~dhcp.netmask; + final byte[] broadcastIP = new byte[IPUtils.IPV4_LENGTH]; + for (int k = 0; k < IPUtils.IPV4_LENGTH; k++) { + broadcastIP[k] = (byte) ((broadcast >> (k * 8)) & 0xFF); + } + return broadcastIP; + } + + private static String stripQuotes(final String pString) { + if (pString == null) { + return pString; + } else { + final int stringLength = pString.length(); + if (stringLength >= 2) { + if (pString.startsWith("\"") && pString.endsWith("\"") ) { + return pString.substring(1, stringLength - 1); + } else { + return pString; + } + } else { + return pString; + } + } + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== + + public static enum WifiHotspotState { + // =========================================================== + // Elements + // =========================================================== + + DISABLING, + DISABLED, + ENABLING, + ENABLED, + FAILED; + + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + // =========================================================== + // Constructors + // =========================================================== + + public static WifiHotspotState fromWifiApState(final int pWifiApState) throws WifiUtilsException { + if (SystemUtils.isAndroidVersionOrHigher(Build.VERSION_CODES.ICE_CREAM_SANDWICH)) { + switch (pWifiApState) { + case 10: + return DISABLING; + case 11: + return DISABLED; + case 12: + return ENABLING; + case 13: + return ENABLED; + case 14: + return FAILED; + default: + throw new WifiUtilsException("TODO..."); + } + } else { + switch (pWifiApState) { + case 0: + return DISABLING; + case 1: + return DISABLED; + case 2: + return ENABLING; + case 3: + return ENABLED; + case 4: + return FAILED; + default: + if (pWifiApState >= 10) { + return WifiHotspotState.fromWifiApState(pWifiApState - 10); + } else { + throw new WifiUtilsException("TODO..."); + } + } + } + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== + } + + public static class WifiUtilsException extends AndEngineException { + // =========================================================== + // Constants + // =========================================================== + + private static final long serialVersionUID = 1108697754015225179L; + + // =========================================================== + // Constructors + // =========================================================== + + public WifiUtilsException() { + + } + + public WifiUtilsException(final Throwable pThrowable) { + super(pThrowable); + } + + private WifiUtilsException(final String pMessage) { + super(pMessage); + } + + private WifiUtilsException(final String pMessage, final Throwable pThrowable) { + super(pMessage, pThrowable); + } + } +} diff --git a/src/org/andengine/util/HorizontalAlign.java b/src/org/andengine/util/adt/align/HorizontalAlign.java similarity index 95% rename from src/org/andengine/util/HorizontalAlign.java rename to src/org/andengine/util/adt/align/HorizontalAlign.java index 66f0f631a..98b56da98 100644 --- a/src/org/andengine/util/HorizontalAlign.java +++ b/src/org/andengine/util/adt/align/HorizontalAlign.java @@ -1,9 +1,9 @@ -package org.andengine.util; +package org.andengine.util.adt.align; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 10:47:33 - 11.05.2010 */ diff --git a/src/org/andengine/util/VerticalAlign.java b/src/org/andengine/util/adt/align/VerticalAlign.java similarity index 95% rename from src/org/andengine/util/VerticalAlign.java rename to src/org/andengine/util/adt/align/VerticalAlign.java index 526e76fcd..79ccd36d4 100644 --- a/src/org/andengine/util/VerticalAlign.java +++ b/src/org/andengine/util/adt/align/VerticalAlign.java @@ -1,9 +1,9 @@ -package org.andengine.util; +package org.andengine.util.adt.align; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 15:15:23 - 24.07.2010 */ diff --git a/src/org/andengine/util/adt/array/ArrayUtils.java b/src/org/andengine/util/adt/array/ArrayUtils.java index de0143bdd..4f62cd5a8 100644 --- a/src/org/andengine/util/adt/array/ArrayUtils.java +++ b/src/org/andengine/util/adt/array/ArrayUtils.java @@ -1,13 +1,15 @@ package org.andengine.util.adt.array; +import java.lang.reflect.Array; import java.util.List; +import org.andengine.util.IMatcher; import org.andengine.util.math.MathUtils; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 22:35:42 - 01.05.2011 */ @@ -24,6 +26,10 @@ public final class ArrayUtils { // Constructors // =========================================================== + private ArrayUtils() { + + } + // =========================================================== // Getter & Setter // =========================================================== @@ -36,6 +42,10 @@ public final class ArrayUtils { // Methods // =========================================================== + public static T[] newArray(final Class pClass, final int pLength) { + return pClass.cast(Array.newInstance(pClass.getComponentType(), pLength)); + } + public static final byte random(final byte[] pArray) { return pArray[MathUtils.random(0, pArray.length - 1)]; } @@ -65,13 +75,13 @@ public static final T random(final T[] pArray) { } public static final void reverse(final byte[] pArray) { - if(pArray == null) { + if (pArray == null) { return; } int i = 0; int j = pArray.length - 1; byte tmp; - while(j > i) { + while (j > i) { tmp = pArray[j]; pArray[j] = pArray[i]; pArray[i] = tmp; @@ -81,13 +91,13 @@ public static final void reverse(final byte[] pArray) { } public static final void reverse(final short[] pArray) { - if(pArray == null) { + if (pArray == null) { return; } int i = 0; int j = pArray.length - 1; short tmp; - while(j > i) { + while (j > i) { tmp = pArray[j]; pArray[j] = pArray[i]; pArray[i] = tmp; @@ -97,13 +107,13 @@ public static final void reverse(final short[] pArray) { } public static final void reverse(final int[] pArray) { - if(pArray == null) { + if (pArray == null) { return; } int i = 0; int j = pArray.length - 1; int tmp; - while(j > i) { + while (j > i) { tmp = pArray[j]; pArray[j] = pArray[i]; pArray[i] = tmp; @@ -113,13 +123,13 @@ public static final void reverse(final int[] pArray) { } public static final void reverse(final long[] pArray) { - if(pArray == null) { + if (pArray == null) { return; } int i = 0; int j = pArray.length - 1; long tmp; - while(j > i) { + while (j > i) { tmp = pArray[j]; pArray[j] = pArray[i]; pArray[i] = tmp; @@ -129,13 +139,13 @@ public static final void reverse(final long[] pArray) { } public static final void reverse(final float[] pArray) { - if(pArray == null) { + if (pArray == null) { return; } int i = 0; int j = pArray.length - 1; float tmp; - while(j > i) { + while (j > i) { tmp = pArray[j]; pArray[j] = pArray[i]; pArray[i] = tmp; @@ -145,13 +155,13 @@ public static final void reverse(final float[] pArray) { } public static final void reverse(final double[] pArray) { - if(pArray == null) { + if (pArray == null) { return; } int i = 0; int j = pArray.length - 1; double tmp; - while(j > i) { + while (j > i) { tmp = pArray[j]; pArray[j] = pArray[i]; pArray[i] = tmp; @@ -161,13 +171,13 @@ public static final void reverse(final double[] pArray) { } public static final void reverse(final Object[] pArray) { - if(pArray == null) { + if (pArray == null) { return; } int i = 0; int j = pArray.length - 1; Object tmp; - while(j > i) { + while (j > i) { tmp = pArray[j]; pArray[j] = pArray[i]; pArray[i] = tmp; @@ -178,17 +188,17 @@ public static final void reverse(final Object[] pArray) { public static final boolean equals(final byte[] pArrayA, final int pOffsetA, final byte[] pArrayB, final int pOffsetB, final int pLength) { final int lastIndexA = pOffsetA + pLength; - if(lastIndexA > pArrayA.length) { + if (lastIndexA > pArrayA.length) { throw new ArrayIndexOutOfBoundsException(pArrayA.length); } final int lastIndexB = pOffsetB + pLength; - if(lastIndexB > pArrayB.length) { + if (lastIndexB > pArrayB.length) { throw new ArrayIndexOutOfBoundsException(pArrayB.length); } - for(int a = pOffsetA, b = pOffsetB; a < lastIndexA; a++, b++) { - if(pArrayA[a] != pArrayB[b]) { + for (int a = pOffsetA, b = pOffsetB; a < lastIndexA; a++, b++) { + if (pArrayA[a] != pArrayB[b]) { return false; } } @@ -198,7 +208,7 @@ public static final boolean equals(final byte[] pArrayA, final int pOffsetA, fin public static final byte[] toByteArray(final List pItems) { final byte[] out = new byte[pItems.size()]; - for(int i = out.length - 1; i >= 0; i--) { + for (int i = out.length - 1; i >= 0; i--) { out[i] = pItems.get(i); } return out; @@ -206,7 +216,7 @@ public static final byte[] toByteArray(final List pItems) { public static final char[] toCharArray(final List pItems) { final char[] out = new char[pItems.size()]; - for(int i = out.length - 1; i >= 0; i--) { + for (int i = out.length - 1; i >= 0; i--) { out[i] = pItems.get(i); } return out; @@ -214,7 +224,7 @@ public static final char[] toCharArray(final List pItems) { public static final short[] toShortArray(final List pItems) { final short[] out = new short[pItems.size()]; - for(int i = out.length - 1; i >= 0; i--) { + for (int i = out.length - 1; i >= 0; i--) { out[i] = pItems.get(i); } return out; @@ -222,7 +232,7 @@ public static final short[] toShortArray(final List pItems) { public static final int[] toIntArray(final List pItems) { final int[] out = new int[pItems.size()]; - for(int i = out.length - 1; i >= 0; i--) { + for (int i = out.length - 1; i >= 0; i--) { out[i] = pItems.get(i); } return out; @@ -230,7 +240,7 @@ public static final int[] toIntArray(final List pItems) { public static final long[] toLongArray(final List pItems) { final long[] out = new long[pItems.size()]; - for(int i = out.length - 1; i >= 0; i--) { + for (int i = out.length - 1; i >= 0; i--) { out[i] = pItems.get(i); } return out; @@ -238,7 +248,7 @@ public static final long[] toLongArray(final List pItems) { public static final float[] toFloatArray(final List pItems) { final float[] out = new float[pItems.size()]; - for(int i = out.length - 1; i >= 0; i--) { + for (int i = out.length - 1; i >= 0; i--) { out[i] = pItems.get(i); } return out; @@ -246,15 +256,15 @@ public static final float[] toFloatArray(final List pItems) { public static final double[] toDoubleArray(final List pItems) { final double[] out = new double[pItems.size()]; - for(int i = out.length - 1; i >= 0; i--) { + for (int i = out.length - 1; i >= 0; i--) { out[i] = pItems.get(i); } return out; } public static final boolean contains(final byte[] pItems, final byte pItem) { - for(int i = pItems.length - 1; i >= 0; i--) { - if(pItems[i] == pItem) { + for (int i = pItems.length - 1; i >= 0; i--) { + if (pItems[i] == pItem) { return true; } } @@ -262,8 +272,8 @@ public static final boolean contains(final byte[] pItems, final byte pItem) { } public static final boolean contains(final char[] pItems, final char pItem) { - for(int i = pItems.length - 1; i >= 0; i--) { - if(pItems[i] == pItem) { + for (int i = pItems.length - 1; i >= 0; i--) { + if (pItems[i] == pItem) { return true; } } @@ -271,8 +281,8 @@ public static final boolean contains(final char[] pItems, final char pItem) { } public static final boolean contains(final short[] pItems, final short pItem) { - for(int i = pItems.length - 1; i >= 0; i--) { - if(pItems[i] == pItem) { + for (int i = pItems.length - 1; i >= 0; i--) { + if (pItems[i] == pItem) { return true; } } @@ -280,8 +290,8 @@ public static final boolean contains(final short[] pItems, final short pItem) { } public static final boolean contains(final int[] pItems, final int pItem) { - for(int i = pItems.length - 1; i >= 0; i--) { - if(pItems[i] == pItem) { + for (int i = pItems.length - 1; i >= 0; i--) { + if (pItems[i] == pItem) { return true; } } @@ -289,8 +299,8 @@ public static final boolean contains(final int[] pItems, final int pItem) { } public static final boolean contains(final long[] pItems, final long pItem) { - for(int i = pItems.length - 1; i >= 0; i--) { - if(pItems[i] == pItem) { + for (int i = pItems.length - 1; i >= 0; i--) { + if (pItems[i] == pItem) { return true; } } @@ -298,8 +308,8 @@ public static final boolean contains(final long[] pItems, final long pItem) { } public static final boolean contains(final float[] pItems, final float pItem) { - for(int i = pItems.length - 1; i >= 0; i--) { - if(pItems[i] == pItem) { + for (int i = pItems.length - 1; i >= 0; i--) { + if (pItems[i] == pItem) { return true; } } @@ -307,9 +317,29 @@ public static final boolean contains(final float[] pItems, final float pItem) { } public static final boolean contains(final double[] pItems, final double pItem) { - for(int i = pItems.length - 1; i >= 0; i--) { - if(pItems[i] == pItem) { + for (int i = pItems.length - 1; i >= 0; i--) { + if (pItems[i] == pItem) { + return true; + } + } + return false; + } + + public static final boolean contains(final Object[] pItems, final Object pItem) { + for (int i = pItems.length - 1; i >= 0; i--) { + final Object item = pItems[i]; + if (pItem == null && item == null) { return true; + } else { + if (item != null) { + if (item.equals(pItem)) { + return true; + } + } else { + if (pItem.equals(item)) { + return true; + } + } } } return false; @@ -320,38 +350,37 @@ public static final boolean contains(final double[] pItems, final double pItem) * @param pArrays items or pArrays itself can be null. * @return null when pArrays is null or all arrays in pArrays are null or of length zero. Otherwise an in-order joined array of T[] of all not null, not zero length arrays in pArrays. */ - @SuppressWarnings("unchecked") - public static T[] join(final Class pClass, final T[]... pArrays) { - if(pArrays == null) { + public static T[] join(final Class pClass, final T[]... pArrays) { + if (pArrays == null) { return null; } final int arrayCount = pArrays.length; - if(arrayCount == 0) { + if (arrayCount == 0) { return null; - } else if(arrayCount == 1) { + } else if (arrayCount == 1) { return pArrays[0]; } int resultLength = 0; /* Determine length of result. */ - for(int i = pArrays.length - 1; i >= 0; i--) { + for (int i = pArrays.length - 1; i >= 0; i--) { final T[] array = pArrays[i]; - if((array != null) && (array.length > 0)) { + if ((array != null) && (array.length > 0)) { resultLength += array.length; } } - if(resultLength == 0) { + if (resultLength == 0) { return null; } /* Determine length of result. */ - final T[] result = (T[]) java.lang.reflect.Array.newInstance(pClass.getComponentType(), resultLength); + final T[] result = ArrayUtils.newArray(pClass, resultLength); int offset = 0; - for(int i = 0; i < arrayCount; i++) { + for (int i = 0; i < arrayCount; i++) { final T[] array = pArrays[i]; - if((array != null) && (array.length > 0)) { + if ((array != null) && (array.length > 0)) { System.arraycopy(array, 0, result, offset, array.length); offset += array.length; } @@ -360,8 +389,8 @@ public static T[] join(final Class pClass, final T[]... pArrays) { } public static int idealByteArraySize(final int pSize) { - for(int i = 4; i < 32; i++) { - if(pSize <= ((1 << i) - 12)) { + for (int i = 4; i < 32; i++) { + if (pSize <= ((1 << i) - 12)) { return (1 << i) - 12; } } @@ -401,6 +430,96 @@ public static int idealObjectArraySize(final int pSize) { return ArrayUtils.idealByteArraySize(pSize << 2) >> 2; } + public static final void sumCummulative(final int[] pValues) { + final int valueCount = pValues.length; + for (int i = 1; i < valueCount; i++) { + pValues[i] = pValues[i - 1] + pValues[i]; + } + } + + public static final void sumCummulative(final long[] pValues) { + final int valueCount = pValues.length; + for (int i = 1; i < valueCount; i++) { + pValues[i] = pValues[i - 1] + pValues[i]; + } + } + + public static final void sumCummulative(final long[] pValues, final long pFactor) { + pValues[0] = pValues[0] * pFactor; + final int valueCount = pValues.length; + for (int i = 1; i < valueCount; i++) { + pValues[i] = pValues[i - 1] + (pValues[i] * pFactor); + } + } + + public static final void sumCummulative(final long[] pValues, final long pFactor, final long[] pTargetValues) { + pTargetValues[0] = pValues[0] * pFactor; + final int valueCount = pValues.length; + for (int i = 1; i < valueCount; i++) { + pTargetValues[i] = pTargetValues[i - 1] + (pValues[i] * pFactor); + } + } + + public static final float sum(final float[] pValues) { + float sum = 0; + final int valueCount = pValues.length; + for (int i = 0; i < valueCount; i++) { + sum += pValues[i]; + } + return sum; + } + + public static final float average(final float[] pValues) { + return ArrayUtils.sum(pValues) / pValues.length; + } + + public static void multiply(final int[] pArray, final float pFactor) { + for (int i = 0; i < pArray.length; i++) { + pArray[i] = Math.round(pArray[i] * pFactor); + } + } + + public static void multiply(final long[] pArray, final double pFactor) { + for (int i = 0; i < pArray.length; i++) { + pArray[i] = Math.round(pArray[i] * pFactor); + } + } + + public static T[] filter(final T[] pArray, final Class pClass, final IMatcher pMatcher) { + final int arrayLength = pArray.length; + + int filteredArrayLength = 0; + for (int i = arrayLength - 1; i >= 0; i--) { + if (pMatcher.matches(pArray[i])) { + filteredArrayLength++; + } + } + + final T[] filteredArray = ArrayUtils.newArray(pClass, filteredArrayLength); + int resultIndex = 0; + for (int i = 0; i < arrayLength; i++) { + if (pMatcher.matches(pArray[i])) { + filteredArray[resultIndex] = pArray[i]; + resultIndex++; + } + } + + return filteredArray; + } + + public static boolean isEmpty(final Object[] pArray) { + if (pArray == null) { + return true; + } else { + for (int i = pArray.length - 1; i >= 0; i--) { + if (pArray[i] != null) { + return false; + } + } + return true; + } + } + // =========================================================== // Inner and Anonymous Classes // =========================================================== diff --git a/src/org/andengine/util/adt/bit/BitVector.java b/src/org/andengine/util/adt/bit/BitVector.java index f6ca4373b..a7b96d50a 100644 --- a/src/org/andengine/util/adt/bit/BitVector.java +++ b/src/org/andengine/util/adt/bit/BitVector.java @@ -1,267 +1,174 @@ package org.andengine.util.adt.bit; -import org.andengine.util.adt.DataConstants; - - /** - * (c) Zynga 2011 + * (c) 2013 Nicolas Gramlich * * @author Nicolas Gramlich - * @since 15:56:32 - 30.10.2011 + * @since 18:14:12 - 02.03.2013 + * @author ngramlich */ -public final class BitVector { +public abstract class BitVector implements IBitVector { // =========================================================== // Constants // =========================================================== + public static final int TRUE = 1; + public static final int FALSE = 0; + // =========================================================== // Fields // =========================================================== - private final int mCapacity; - private final long[] mData; - // =========================================================== // Constructors // =========================================================== - private BitVector(final int pCapacity) { - if(pCapacity <= 0) { - throw new IllegalArgumentException("pCapacity must be > 0."); - } - this.mCapacity = pCapacity; + public static IBitVector wrap(final byte[] pData) { + return new ByteBackedBitVector(pData); + } - /* Check if bytes perfectly fit into the data fields or if there are some overflow bytes that need special treatment. */ - final boolean perfectDataFit = pCapacity % DataConstants.BITS_PER_LONG == 0; + public static IBitVector wrap(final int pSize, final byte[] pData) { + return new ByteBackedBitVector(pData); + } - final int dataCapacity; - if(perfectDataFit) { - dataCapacity = pCapacity / DataConstants.BITS_PER_LONG; - } else { - /* Extra field for overflow bytes. */ - dataCapacity = (pCapacity / DataConstants.BITS_PER_LONG) + 1; - } - this.mData = new long[dataCapacity]; + public static IBitVector wrap(final long[] pData) { + return new LongBackedBitVector(pData); } - public BitVector(final byte[] pBytes) { - this(pBytes.length * DataConstants.BITS_PER_BYTE); + public static IBitVector wrap(final int pSize, final long[] pData) { + return new LongBackedBitVector(pSize, pData); + } - final long[] data = this.mData; + // =========================================================== + // Getter & Setter + // =========================================================== - /* Check if bytes perfectly fit into the data fields or if there are some overflow bytes that need special treatment. */ - final boolean perfectDataFit = pBytes.length % DataConstants.BYTES_PER_LONG == 0; + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - final int dataCapacity = data.length; - final int lastCompleteDataIndex = (perfectDataFit) ? dataCapacity - 1 : dataCapacity - 2; + // =========================================================== + // Methods + // =========================================================== - for(int i = lastCompleteDataIndex; i >= 0; i--) { - final int bytesOffset = i * DataConstants.BYTES_PER_LONG; + public static int getByteIndex(final int pIndex) { + return pIndex / Byte.SIZE; + } - data[i] = ((((long)pBytes[bytesOffset + 0]) << 56) & 0xFF00000000000000L) - | ((((long)pBytes[bytesOffset + 1]) << 48) & 0xFF000000000000L) - | ((((long)pBytes[bytesOffset + 2]) << 40) & 0xFF0000000000L) - | ((((long)pBytes[bytesOffset + 3]) << 32) & 0xFF00000000L) - | ((((long)pBytes[bytesOffset + 4]) << 24) & 0xFF000000L) - | ((((long)pBytes[bytesOffset + 5]) << 16) & 0xFF0000L) - | ((((long)pBytes[bytesOffset + 6]) << 8) & 0xFF00L) - | ((((long)pBytes[bytesOffset + 7]) << 0) & 0xFFL); - } + public static int getLongIndex(final int pIndex) { + return pIndex / Long.SIZE; + } - /* Put overflow bytes into last data field. */ - if(!perfectDataFit) { - long overflowData = 0; - - final int overflowDataIndex = dataCapacity - 1; - final int overflowBytesOffset = overflowDataIndex * DataConstants.BYTES_PER_LONG; - - final int overflowByteCount = pBytes.length - overflowBytesOffset; - switch(overflowByteCount) { - case 7: - overflowData = overflowData | ((((long)pBytes[overflowBytesOffset + 6]) << 8) & 0xFF00L); - case 6: - overflowData = overflowData | ((((long)pBytes[overflowBytesOffset + 5]) << 16) & 0xFF0000L); - case 5: - overflowData = overflowData | ((((long)pBytes[overflowBytesOffset + 4]) << 24) & 0xFF000000L); - case 4: - overflowData = overflowData | ((((long)pBytes[overflowBytesOffset + 3]) << 32) & 0xFF00000000L); - case 3: - overflowData = overflowData | ((((long)pBytes[overflowBytesOffset + 2]) << 40) & 0xFF0000000000L); - case 2: - overflowData = overflowData | ((((long)pBytes[overflowBytesOffset + 1]) << 48) & 0xFF000000000000L); - case 1: - overflowData = overflowData | ((((long)pBytes[overflowBytesOffset + 0]) << 56) & 0xFF00000000000000L); - } - - data[overflowDataIndex] = overflowData; - } + public static int getIndexInByte(final int pIndex) { + return pIndex % Byte.SIZE; } - // =========================================================== - // Getter & Setter - // =========================================================== + public static int getIndexInLong(final int pIndex) { + return pIndex % Long.SIZE; + } - public int getCapacity() { - return this.mCapacity; + public static int getBitInByte(final byte pByte, final int pIndex) throws IllegalArgumentException { + return BitVector.getBitsInByte(pByte, pIndex, 1); } - public boolean getBit(final int pPosition) { - if(pPosition < 0) { - throw new IllegalArgumentException("pPosition must be >= 0."); + public static int getBitsInByte(final byte pByte, final int pIndex, final int pCount) throws IllegalArgumentException { + if ((pIndex < 0) || ((pIndex + pCount) > Byte.SIZE)) { + throw new IllegalArgumentException("pIndex out of bounds: " + pIndex); } - if(pPosition >= this.mCapacity) { - throw new IllegalArgumentException("pPosition must be < capacity."); + + if ((pCount < 0) || (pCount > Byte.SIZE)) { + throw new IllegalArgumentException("pBitCount out of bounds: " + pCount); } - final int dataIndex = pPosition / DataConstants.BITS_PER_LONG; - final int dataOffset = pPosition % DataConstants.BITS_PER_LONG; + final int shift = Byte.SIZE - pIndex - pCount; + final int shiftedByte = ((pByte & 0xFF) >> shift); - final long dataField = this.mData[dataIndex]; + final int mask = (0x01 << (pCount)) - 1; - final int rightShift = DataConstants.BITS_PER_LONG - dataOffset - 1; - final long bit = (dataField >> rightShift) & 0x01; + final int result = shiftedByte & mask; - return bit != 0; + return result; } - public byte getByte(final int pPosition) { - return (byte) this.getBits(pPosition, DataConstants.BITS_PER_BYTE); - } + public static byte setBitInByte(final byte pByte, final int pIndex, final boolean pTrue) throws IllegalArgumentException { + if ((pIndex < 0) || (pIndex >= Byte.SIZE)) { + throw new IllegalArgumentException("pIndex out of bounds: " + pIndex); + } - public short getShort(final int pPosition) { - return (short) this.getBits(pPosition, DataConstants.BITS_PER_SHORT); - } + if (pTrue) { + final int mask = (0x80 >> pIndex); - public int getInt(final int pPosition) { - return (int) this.getBits(pPosition, DataConstants.BITS_PER_INT); - } + final byte result = (byte)(pByte | mask); - public long getLong(final int pPosition) { - return this.getBits(pPosition, DataConstants.BITS_PER_LONG); - } + return result; + } else { + final int mask = 0xFF ^ (0x80 >> pIndex); - public long getBits(final int pPosition, final int pLength) { - /* Sanity checks. */ - if(pPosition < 0) { - throw new IllegalArgumentException("pPosition must be >= 0."); + final byte result = (byte)(pByte & mask); + + return result; } - if(pLength < 0) { - throw new IllegalArgumentException("pLength must be >= 0."); + } + + public static byte setBitsInByte(final byte pByte, final int pIndex, final byte pBits, final int pBitIndex, final int pBitCount) throws IllegalArgumentException { + if ((pIndex < 0) || ((pIndex + pBitCount) > Byte.SIZE)) { + throw new IllegalArgumentException("pIndex out of bounds: " + pIndex); } - if(pPosition + pLength > this.mCapacity) { - throw new IllegalArgumentException("pPosition + pLength must be <= capacity."); + + if ((pBitIndex + pBitCount) > Byte.SIZE) { + throw new IllegalArgumentException("pBitIndex out of bounds: " + pIndex); } - /* Early exit. */ - if(pLength == 0) { - return 0L; + if ((pBitCount < 0) || (pBitCount > Byte.SIZE)) { + throw new IllegalArgumentException("pBitCount out of bounds: " + pIndex); } - final int dataIndex = pPosition / DataConstants.BITS_PER_LONG; - final int offset = pPosition % DataConstants.BITS_PER_LONG; + final int sizeMask = (0x01 << (pBitCount)) - 1; - final long data; - if(offset == 0) { - data = this.mData[dataIndex]; - } else if(offset + pLength <= DataConstants.BITS_PER_LONG) { - data = this.mData[dataIndex] << offset; - } else { - /* Join bits from adjacent data fields. */ - data = (this.mData[dataIndex] << offset) | (this.mData[dataIndex + 1] >>> (DataConstants.BITS_PER_LONG - offset)); - } + final int byteMask = (sizeMask << (Byte.SIZE - (pBitCount + pIndex))) ^ 0xFF; + final int maskedByte = (pByte & byteMask) & 0xFF; - if(pLength == DataConstants.BITS_PER_LONG) { - return data; + final int bitMask = sizeMask << (Byte.SIZE - (pBitCount + pBitIndex)); + final int maskedBits = (pBits & bitMask) & 0xFF; + + final int shift = (pBitIndex - pIndex); + final int shiftedBits; + if (shift < 0) { + shiftedBits = maskedBits >> -shift; } else { - final int rightShift = DataConstants.BITS_PER_LONG - pLength; - final long mask = 0xFFFFFFFFFFFFFFFFL >>> rightShift; - final long unmaskedBits = data >> rightShift; - return unmaskedBits & mask; + shiftedBits = maskedBits << shift; } - } - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + final byte result = (byte) (maskedByte | shiftedBits); - @Override - public String toString() { - final StringBuilder sb = new StringBuilder(); - sb.append('['); - for(int i = 0; i < this.mCapacity; i++) { - sb.append(this.getBit(i) ? '1' : '0'); - if(i % 8 == 7 && i < this.mCapacity -1) { - sb.append(' '); - } - } - sb.append(']'); - return sb.toString(); + return result; } - // =========================================================== - // Methods - // =========================================================== + public static int calculateByteSize(final int pBitSize) { + if (pBitSize < 0) { + throw new IllegalArgumentException("pBitSize out of bounds: " + pBitSize); + } - public byte[] toByteArray() { - final int byteArrayLength; - if(this.mCapacity % DataConstants.BITS_PER_BYTE == 0) { - byteArrayLength = this.mCapacity / DataConstants.BITS_PER_BYTE; + if (BitVector.getIndexInByte(pBitSize) == 0) { + return pBitSize / Byte.SIZE; } else { - byteArrayLength = (this.mCapacity / DataConstants.BITS_PER_BYTE) + 1; + return 1 + (pBitSize / Byte.SIZE); } + } - final byte[] bytes = new byte[byteArrayLength]; - /* Check if bytes perfectly fit into the data fields or if there are some overflow bytes that need special treatment. */ - final boolean perfectDataFit = this.mCapacity % DataConstants.BITS_PER_LONG == 0; - - final long[] data = this.mData; - final int dataCapacity = data.length; - final int lastCompleteDataIndex = (perfectDataFit) ? dataCapacity - 1 : dataCapacity - 2; - - int bytesOffset = lastCompleteDataIndex * DataConstants.BYTES_PER_LONG + (DataConstants.BYTES_PER_LONG - 1); - for(int i = lastCompleteDataIndex; i >= 0; i--) { - final long dataField = data[i]; - - bytes[bytesOffset--] = (byte) ((dataField >> 0) & 0xFF); - bytes[bytesOffset--] = (byte) ((dataField >> 8) & 0xFF); - bytes[bytesOffset--] = (byte) ((dataField >> 16) & 0xFF); - bytes[bytesOffset--] = (byte) ((dataField >> 24) & 0xFF); - bytes[bytesOffset--] = (byte) ((dataField >> 32) & 0xFF); - bytes[bytesOffset--] = (byte) ((dataField >> 40) & 0xFF); - bytes[bytesOffset--] = (byte) ((dataField >> 48) & 0xFF); - bytes[bytesOffset--] = (byte) ((dataField >> 56) & 0xFF); + public static int calculateLongSize(final int pBitSize) { + if (pBitSize < 0) { + throw new IllegalArgumentException("pBitSize out of bounds: " + pBitSize); } - /* Put overflow bytes into last data field. */ - if(!perfectDataFit) { - final int overflowDataIndex = dataCapacity - 1; - final long overflowDataField = data[overflowDataIndex]; - - final int overflowBytesOffset = overflowDataIndex * DataConstants.BYTES_PER_LONG; - - final int overflowByteCount = bytes.length % DataConstants.BYTES_PER_LONG; - switch(overflowByteCount) { - case 7: - bytes[overflowBytesOffset + 6] = (byte) ((overflowDataField >> 8) & 0xFF); - case 6: - bytes[overflowBytesOffset + 5] = (byte) ((overflowDataField >> 16) & 0xFF); - case 5: - bytes[overflowBytesOffset + 4] = (byte) ((overflowDataField >> 24) & 0xFF); - case 4: - bytes[overflowBytesOffset + 3] = (byte) ((overflowDataField >> 32) & 0xFF); - case 3: - bytes[overflowBytesOffset + 2] = (byte) ((overflowDataField >> 40) & 0xFF); - case 2: - bytes[overflowBytesOffset + 1] = (byte) ((overflowDataField >> 48) & 0xFF); - case 1: - bytes[overflowBytesOffset + 0] = (byte) ((overflowDataField >> 56) & 0xFF); - } + if (BitVector.getIndexInLong(pBitSize) == 0) { + return pBitSize / Byte.SIZE; + } else { + return 1 + (pBitSize / Byte.SIZE); } - - return bytes; } // =========================================================== // Inner and Anonymous Classes // =========================================================== -} \ No newline at end of file +} diff --git a/src/org/andengine/util/adt/bit/ByteBackedBitVector.java b/src/org/andengine/util/adt/bit/ByteBackedBitVector.java new file mode 100644 index 000000000..ece8deaf3 --- /dev/null +++ b/src/org/andengine/util/adt/bit/ByteBackedBitVector.java @@ -0,0 +1,412 @@ +package org.andengine.util.adt.bit; + +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.util.Arrays; + +import org.andengine.util.adt.data.constants.DataConstants; +import org.andengine.util.exception.MethodNotYetImplementedException; + + +/** + * (c) 2013 Nicolas Gramlich + * + * @author Nicolas Gramlich + * @since Nov 20, 2012 + */ +public class ByteBackedBitVector extends BitVector { + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + private final int mSize; + private final byte[] mData; + + // =========================================================== + // Constructors + // =========================================================== + + public ByteBackedBitVector(final int pSize) throws IllegalArgumentException { + this(pSize, new byte[BitVector.calculateByteSize(pSize)]); + } + + public ByteBackedBitVector(final byte[] pData) throws IllegalArgumentException, NullPointerException { + this(pData.length * Byte.SIZE, pData); + } + + public ByteBackedBitVector(final int pSize, final byte[] pData) throws IllegalArgumentException, NullPointerException { + if (pData == null) { + throw new IllegalArgumentException("pData must not be null"); + } + + if (pSize > (pData.length * Byte.SIZE)) { + throw new IllegalArgumentException("pData is too short."); + } + + if (BitVector.calculateByteSize(pSize) < pData.length) { + throw new IllegalArgumentException("pData is too long."); + } + + this.mSize = pSize; + + this.mData = pData; + } + + public ByteBackedBitVector(final DataInputStream pDataInputStream) throws IOException { + this.mSize = pDataInputStream.readInt(); + this.mData = new byte[BitVector.calculateByteSize(this.mSize)]; + + pDataInputStream.readFully(this.mData); + } + + public static ByteBackedBitVector load(final DataInputStream pDataInputStream) throws IOException { + return new ByteBackedBitVector(pDataInputStream); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + @Override + public int getSize() { + return this.mSize; + } + + public int getByteSize() { + return this.mData.length; + } + + @Override + public int getBit(final int pIndex) throws IllegalArgumentException { + if ((pIndex < 0) || (pIndex >= this.mSize)) { + throw new IllegalArgumentException("pIndex out of bounds: " + pIndex); + } + + final int byteIndex = BitVector.getByteIndex(pIndex); + final int indexInByte = BitVector.getIndexInByte(pIndex); + + return BitVector.getBitInByte(this.mData[byteIndex], indexInByte); + } + + @Override + public boolean getBitAsBoolean(final int pIndex) throws IllegalArgumentException { + return this.getBit(pIndex) == BitVector.TRUE; + } + + @Override + public void setBit(final int pIndex) throws IllegalArgumentException { + this.setBit(pIndex, true); + } + + @Override + public void clearBit(final int pIndex) throws IllegalArgumentException { + this.setBit(pIndex, false); + } + + @Override + public void setBit(final int pIndex, final boolean pTrue) throws IllegalArgumentException { + if ((pIndex < 0) || (pIndex >= this.mSize)) { + throw new IllegalArgumentException("pIndex out of bounds: " + pIndex); + } + + final int byteIndex = BitVector.getByteIndex(pIndex); + final int indexInByte = BitVector.getIndexInByte(pIndex); + final byte oldByte = this.mData[byteIndex]; + + final byte newByte = BitVector.setBitInByte(oldByte, indexInByte, pTrue); + this.mData[byteIndex] = newByte; + } + + @Override + public int getBits(final int pIndex, final int pCount) throws IllegalArgumentException { + if ((pIndex < 0) || (pIndex + pCount > this.mSize)) { + throw new IllegalArgumentException("pIndex out of bounds: " + pIndex); + } + + int bits = 0; + + int bitsLeft = pCount; + int index = pIndex; + while (bitsLeft >= Byte.SIZE) { + bits = bits << Byte.SIZE; + bits |= (this.getByte(index)) & 0xFF; + index += Byte.SIZE; + bitsLeft -= Byte.SIZE; + } + + for (int i = 0; i < bitsLeft; i++) { + bits = bits << 1; + if(this.getBit(index) == BitVector.TRUE) { + bits |= 0x01; + } + index++; + } + + return bits; + } + + @Override + public long getLongBits(final int pIndex, final int pLength) throws IllegalArgumentException { + throw new MethodNotYetImplementedException(); + } + + @Override + public void setBits(final int pIndex, final byte pBits, final int pBitIndex, final int pBitCount) throws IllegalArgumentException { + if ((pIndex < 0) || ((pIndex + pBitCount) > this.mSize)) { + throw new IllegalArgumentException("pIndex out of bounds: " + pIndex); + } + + if ((pBitIndex < 0) || ((pBitIndex + pBitCount) > Byte.SIZE)) { + throw new IllegalArgumentException("pIndex out of bounds: " + pBitIndex); + } + + final int indexInByte = BitVector.getIndexInByte(pIndex); + final int byteIndex = BitVector.getByteIndex(pIndex); + if (indexInByte == 0) { + /* Perfect match, easy get. */ + final byte newByte = BitVector.setBitsInByte(this.mData[byteIndex], 0, pBits, pBitIndex, pBitCount); + this.mData[byteIndex] = newByte; + } else { + final byte highByte = this.mData[byteIndex]; + final int highByteBitCount = Math.min(pBitCount, Byte.SIZE - indexInByte); + + final byte newHighByte = BitVector.setBitsInByte(highByte, indexInByte, pBits, pBitIndex, highByteBitCount); + this.mData[byteIndex] = newHighByte; + + if (highByteBitCount < pBitCount) { + final byte lowByte = this.mData[byteIndex + 1]; + final int lowByteBitIndex = pBitIndex + highByteBitCount; + final int lowByteBitCount = pBitCount - highByteBitCount; + + final byte newLowByte = BitVector.setBitsInByte(lowByte, 0, pBits, lowByteBitIndex, lowByteBitCount); + this.mData[byteIndex + 1] = newLowByte; + } + } + } + + @Override + public void setBits(final int pIndex, final short pBits, final int pBitIndex, final int pBitCount) throws IllegalArgumentException { + if ((pIndex < 0) || ((pIndex + pBitCount) > this.mSize)) { + throw new IllegalArgumentException("pIndex out of bounds: " + pIndex); + } + + if ((pBitIndex < 0) || ((pBitIndex + pBitCount) > Short.SIZE)) { + throw new IllegalArgumentException("pBitIndex out of bounds: " + pBitIndex); + } + + final int highByteBitCount = Math.min(pBitCount, Math.max(0, Byte.SIZE - pBitIndex)); + if (highByteBitCount != 0) { + final byte highByte = (byte)((pBits >> (1 * Byte.SIZE)) & 0xFF); + this.setBits(pIndex, highByte, pBitIndex, highByteBitCount); + } + + if (pBitCount > highByteBitCount) { + final byte lowByte = (byte)((pBits >> (0 * Byte.SIZE)) & 0xFF); + final int lowByteBitCount = pBitCount - highByteBitCount; + + if(highByteBitCount == 0) { + this.setBits(pIndex, lowByte, (pBitIndex - Byte.SIZE) % Byte.SIZE, lowByteBitCount); + } else { + this.setBits(pIndex + highByteBitCount, lowByte, 0, lowByteBitCount); + } + } + } + + @Override + public void setBits(final int pIndex, final int pBits, final int pBitIndex, final int pBitCount) throws IllegalArgumentException { + if ((pIndex < 0) || ((pIndex + pBitCount) > this.mSize)) { + throw new IllegalArgumentException("pIndex out of bounds: " + pIndex); + } + + if ((pBitIndex < 0) || ((pBitIndex + pBitCount) > Integer.SIZE)) { + throw new IllegalArgumentException("pBitIndex out of bounds: " + pBitIndex); + } + + final int highShortBitCount = Math.min(pBitCount, Math.max(0, Short.SIZE - pBitIndex)); + if (highShortBitCount != 0) { + final short highShort = (short)((pBits >> (1 * Short.SIZE)) & 0xFFFF); + this.setBits(pIndex, highShort, pBitIndex, highShortBitCount); + } + + if (pBitCount > highShortBitCount) { + final short lowShort = (short)((pBits >> (0 * Short.SIZE)) & 0xFFFF); + final int lowShortBitCount = pBitCount - highShortBitCount; + + if(highShortBitCount == 0) { + this.setBits(pIndex, lowShort, (pBitIndex - Short.SIZE) % Short.SIZE, lowShortBitCount); + } else { + this.setBits(pIndex + highShortBitCount, lowShort, 0, lowShortBitCount); + } + } + } + + @Override + public byte getByte(final int pIndex) throws IllegalArgumentException { + if ((pIndex < 0) || ((pIndex + Byte.SIZE) > this.mSize)) { + throw new IllegalArgumentException("pIndex out of bounds: " + pIndex); + } + + final int indexInByte = BitVector.getIndexInByte(pIndex); + final int byteIndex = BitVector.getByteIndex(pIndex); + if (indexInByte == 0) { + /* Perfect match, easy get. */ + return this.mData[byteIndex]; + } else { + final byte highByte = this.mData[byteIndex]; + final byte lowByte = this.mData[byteIndex + 1]; + + final int highBits = BitVector.getBitsInByte(highByte, indexInByte, Byte.SIZE - indexInByte); + final int lowBits = BitVector.getBitsInByte(lowByte, 0, indexInByte); + + final int result = (highBits << indexInByte) + lowBits; + + return (byte)result; + } + } + + @Override + public final void setByte(final int pIndex, final byte pByte) throws IllegalArgumentException { + if ((pIndex < 0) || ((pIndex + Byte.SIZE) > this.mSize)) { + throw new IllegalArgumentException("pIndex out of bounds: " + pIndex); + } + + final int indexInByte = BitVector.getIndexInByte(pIndex); + final int byteIndex = BitVector.getByteIndex(pIndex); + if (indexInByte == 0) { + /* Perfect match, easy set. */ + this.mData[byteIndex] = pByte; + } else { + final byte highByte = this.mData[byteIndex]; + final byte lowByte = this.mData[byteIndex + 1]; + + this.mData[byteIndex] = BitVector.setBitsInByte(highByte, indexInByte, pByte, 0, Byte.SIZE - indexInByte); + this.mData[byteIndex + 1] = BitVector.setBitsInByte(lowByte, 0, pByte, Byte.SIZE - indexInByte, indexInByte); + } + } + + @Override + public short getShort(final int pIndex) throws IllegalArgumentException { + if ((pIndex < 0) || ((pIndex + Short.SIZE) > this.mSize)) { + throw new IllegalArgumentException("pIndex out of bounds: " + pIndex); + } + + final int highByte = this.getByte(pIndex) & 0xFF; + final int lowByte = this.getByte(pIndex + Byte.SIZE) & 0xFF; + + final short result = (short)((highByte << Byte.SIZE) | lowByte); + + return result; + } + + @Override + public final void setShort(final int pIndex, final short pShort) throws IllegalArgumentException { + if ((pIndex < 0) || ((pIndex + Short.SIZE) > this.mSize)) { + throw new IllegalArgumentException("pIndex out of bounds: " + pIndex); + } + + final byte highByte = (byte)((pShort >> Byte.SIZE) & 0xFF); + final byte lowByte = (byte)(pShort & 0xFF); + + this.setByte(pIndex, highByte); + this.setByte(pIndex + Byte.SIZE, lowByte); + } + + @Override + public int getInt(final int pIndex) throws IllegalArgumentException { + if ((pIndex < 0) || ((pIndex + Integer.SIZE) > this.mSize)) { + throw new IllegalArgumentException("pIndex out of bounds: " + pIndex); + } + + final int highestByte = this.getByte(pIndex + (0 * Byte.SIZE)) & 0xFF; + final int highByte = this.getByte(pIndex + (1 * Byte.SIZE)) & 0xFF; + final int lowByte = this.getByte(pIndex + (2 * Byte.SIZE)) & 0xFF; + final int lowestByte = this.getByte(pIndex + (3 * Byte.SIZE)) & 0xFF; + + final int result = (highestByte << (3 * Byte.SIZE)) | (highByte << (2 * Byte.SIZE)) | (lowByte << (1 * Byte.SIZE)) | lowestByte; + + return result; + } + + @Override + public void setInt(final int pIndex, final int pInt) throws IllegalArgumentException { + if ((pIndex < 0) || ((pIndex + Integer.SIZE) > this.mSize)) { + throw new IllegalArgumentException("pIndex out of bounds: " + pIndex); + } + + this.setByte(pIndex + (0 * Byte.SIZE), (byte)((pInt >> (3 * Byte.SIZE)) & 0xFF)); + this.setByte(pIndex + (1 * Byte.SIZE), (byte)((pInt >> (2 * Byte.SIZE)) & 0xFF)); + this.setByte(pIndex + (2 * Byte.SIZE), (byte)((pInt >> (1 * Byte.SIZE)) & 0xFF)); + this.setByte(pIndex + (3 * Byte.SIZE), (byte)((pInt >> (0 * Byte.SIZE)) & 0xFF)); + } + + @Override + public long getLong(final int pIndex) throws IllegalArgumentException { + return this.getLongBits(pIndex, DataConstants.BITS_PER_LONG); + } + + @Override + public void setLong(final int pIndex, final long pLong) throws IllegalArgumentException { + throw new MethodNotYetImplementedException(); + } + + @Override + public void clear() { + this.fill((byte)0x00); + } + + @Override + public void fill(final byte pByte) { + Arrays.fill(this.mData, pByte); + } + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + public void save(final DataOutputStream pDataOutputStream) throws IOException { + pDataOutputStream.writeInt(this.mSize); + pDataOutputStream.write(this.mData); + } + + @Override + public byte[] toByteArray() { + final byte[] bytes = new byte[this.mData.length]; + System.arraycopy(this.mData, 0, bytes, 0, this.mData.length); + return bytes; + } + + @Override + public String toString() { + final StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.append('['); + + for (int i = 0; i < this.mSize; i++) { + if (this.getBit(i) == BitVector.TRUE) { + stringBuilder.append('1'); + } else { + stringBuilder.append('0'); + } + + if (((i % Byte.SIZE) == (Byte.SIZE - 1)) && (i < (this.mSize - 1))) { + stringBuilder.append(',').append(' '); + } + } + + stringBuilder.append(']'); + return stringBuilder.toString(); + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== +} diff --git a/src/org/andengine/util/adt/bit/IBitVector.java b/src/org/andengine/util/adt/bit/IBitVector.java new file mode 100644 index 000000000..0c9a36f7d --- /dev/null +++ b/src/org/andengine/util/adt/bit/IBitVector.java @@ -0,0 +1,53 @@ +package org.andengine.util.adt.bit; + +import java.io.DataOutputStream; +import java.io.IOException; + +/** + * (c) 2013 Zynga Inc. + * + * @author Nicolas Gramlich + * @since 18:14:12 - 02.03.2013 + */ +public interface IBitVector { + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + public int getSize(); + public int getBit(final int pIndex) throws IllegalArgumentException; + public void setBit(final int pIndex) throws IllegalArgumentException; + public void clearBit(final int pIndex) throws IllegalArgumentException; + public void setBit(final int pIndex, final boolean pTrue) throws IllegalArgumentException; + boolean getBitAsBoolean(int pIndex) throws IllegalArgumentException; + + public byte getByte(final int pIndex) throws IllegalArgumentException; + public void setByte(final int pIndex, final byte pByte) throws IllegalArgumentException; + + public short getShort(final int pIndex) throws IllegalArgumentException; + public void setShort(final int pIndex, final short pShort) throws IllegalArgumentException; + + public int getInt(final int pIndex) throws IllegalArgumentException; + public void setInt(final int pIndex, final int pInt) throws IllegalArgumentException; + + public long getLong(final int pIndex) throws IllegalArgumentException; + public void setLong(final int pIndex, final long pLong) throws IllegalArgumentException; + + public int getBits(final int pIndex, final int pLength) throws IllegalArgumentException; + public void setBits(final int pIndex, final byte pBits, final int pBitIndex, final int pBitCount) throws IllegalArgumentException; + public void setBits(final int pIndex, final short pBits, final int pBitIndex, final int pBitCount) throws IllegalArgumentException; + public void setBits(final int pIndex, final int pBits, final int pBitIndex, final int pBitCount) throws IllegalArgumentException; + + public long getLongBits(int pIndex, int pLength) throws IllegalArgumentException; + + public byte[] toByteArray(); + + public void save(final DataOutputStream pDataOutputStream) throws IOException; + + public void clear(); + public void fill(final byte pByte); +} \ No newline at end of file diff --git a/src/org/andengine/util/adt/bit/LongBackedBitVector.java b/src/org/andengine/util/adt/bit/LongBackedBitVector.java new file mode 100644 index 000000000..249836a0f --- /dev/null +++ b/src/org/andengine/util/adt/bit/LongBackedBitVector.java @@ -0,0 +1,398 @@ +package org.andengine.util.adt.bit; + +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.util.Arrays; + +import org.andengine.util.adt.data.constants.DataConstants; +import org.andengine.util.exception.MethodNotYetImplementedException; + + +/** + * (c) 2011 Zynga Inc. + * + * @author Nicolas Gramlich + * @since 15:56:32 - 30.10.2011 + */ +public class LongBackedBitVector extends BitVector { + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + private final int mSize; + private final long[] mData; + + // =========================================================== + // Constructors + // =========================================================== + + public LongBackedBitVector(final int pSize) throws IllegalArgumentException { + if (pSize <= 0) { + throw new IllegalArgumentException("pSize must be > 0."); + } + this.mSize = pSize; + + /* Check if bytes perfectly fit into the data fields or if there are some overflow bytes that need special treatment. */ + final boolean perfectDataFit = (pSize % DataConstants.BITS_PER_LONG) == 0; + + final int dataLength; + if (perfectDataFit) { + dataLength = pSize / DataConstants.BITS_PER_LONG; + } else { + /* Extra field for overflow bytes. */ + dataLength = (pSize / DataConstants.BITS_PER_LONG) + 1; + } + this.mData = new long[dataLength]; + } + + public LongBackedBitVector(final long[] pData) throws IllegalArgumentException { + throw new MethodNotYetImplementedException(); + } + + public LongBackedBitVector(final int pSize, final long[] pData) throws IllegalArgumentException { + if (pData == null) { + throw new IllegalArgumentException("pData must not be null"); + } + + if (pSize > (pData.length * Long.SIZE)) { + throw new IllegalArgumentException("pData is too short."); + } + + if (BitVector.calculateLongSize(pSize) < pData.length) { + throw new IllegalArgumentException("pData is too long."); + } + + throw new MethodNotYetImplementedException(); + } + + public LongBackedBitVector(final byte[] pData) throws IllegalArgumentException, NullPointerException { + this(pData.length * DataConstants.BITS_PER_BYTE); + + final long[] data = this.mData; + + /* Check if bytes perfectly fit into the data fields or if there are some overflow bytes that need special treatment. */ + final boolean perfectDataFit = (pData.length % DataConstants.BYTES_PER_LONG) == 0; + + final int dataLength = data.length; + final int lastCompleteDataIndex = (perfectDataFit) ? dataLength - 1 : dataLength - 2; + + for (int i = lastCompleteDataIndex; i >= 0; i--) { + final int bytesOffset = i * DataConstants.BYTES_PER_LONG; + + data[i] = ((((long)pData[bytesOffset + 0]) << 56) & 0xFF00000000000000L) + | ((((long)pData[bytesOffset + 1]) << 48) & 0xFF000000000000L) + | ((((long)pData[bytesOffset + 2]) << 40) & 0xFF0000000000L) + | ((((long)pData[bytesOffset + 3]) << 32) & 0xFF00000000L) + | ((((long)pData[bytesOffset + 4]) << 24) & 0xFF000000L) + | ((((long)pData[bytesOffset + 5]) << 16) & 0xFF0000L) + | ((((long)pData[bytesOffset + 6]) << 8) & 0xFF00L) + | ((((long)pData[bytesOffset + 7]) << 0) & 0xFFL); + } + + /* Put overflow bytes into last data field. */ + if (!perfectDataFit) { + long overflowData = 0; + + final int overflowDataIndex = dataLength - 1; + final int overflowBytesOffset = overflowDataIndex * DataConstants.BYTES_PER_LONG; + + final int overflowByteCount = pData.length - overflowBytesOffset; + switch (overflowByteCount) { + case 7: + overflowData = overflowData | ((((long)pData[overflowBytesOffset + 6]) << 8) & 0xFF00L); + case 6: + overflowData = overflowData | ((((long)pData[overflowBytesOffset + 5]) << 16) & 0xFF0000L); + case 5: + overflowData = overflowData | ((((long)pData[overflowBytesOffset + 4]) << 24) & 0xFF000000L); + case 4: + overflowData = overflowData | ((((long)pData[overflowBytesOffset + 3]) << 32) & 0xFF00000000L); + case 3: + overflowData = overflowData | ((((long)pData[overflowBytesOffset + 2]) << 40) & 0xFF0000000000L); + case 2: + overflowData = overflowData | ((((long)pData[overflowBytesOffset + 1]) << 48) & 0xFF000000000000L); + case 1: + overflowData = overflowData | ((((long)pData[overflowBytesOffset + 0]) << 56) & 0xFF00000000000000L); + } + + data[overflowDataIndex] = overflowData; + } + } + + public LongBackedBitVector(final DataInputStream pDataInputStream) throws IOException { + this.mSize = pDataInputStream.readInt(); + this.mData = new long[BitVector.calculateLongSize(this.mSize)]; + + throw new MethodNotYetImplementedException(); + +// pDataInputStream.readFully(this.mData); + } + + public static LongBackedBitVector load(final DataInputStream pDataInputStream) throws IOException { + return new LongBackedBitVector(pDataInputStream); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + @Override + public int getSize() { + return this.mSize; + } + + @Override + public int getBit(final int pIndex) throws IllegalArgumentException { + if (pIndex < 0) { + throw new IllegalArgumentException("pIndex must be >= 0."); + } + if (pIndex >= this.mSize) { + throw new IllegalArgumentException("pIndex must be < size."); + } + + final int dataIndex = pIndex / DataConstants.BITS_PER_LONG; + final int dataOffset = pIndex % DataConstants.BITS_PER_LONG; + + final long dataField = this.mData[dataIndex]; + + final int rightShift = DataConstants.BITS_PER_LONG - dataOffset - 1; + final long dataBit = (dataField >> rightShift) & 0x01; + final int bit = (int)dataBit; + + return bit; + } + + @Override + public boolean getBitAsBoolean(final int pIndex) throws IllegalArgumentException { + return this.getBit(pIndex) == BitVector.TRUE; + } + + @Override + public void setBit(final int pIndex) throws IllegalArgumentException { + throw new MethodNotYetImplementedException(); + } + + @Override + public void clearBit(final int pIndex) throws IllegalArgumentException { + throw new MethodNotYetImplementedException(); + } + + @Override + public void setBit(final int pIndex, final boolean pTrue) throws IllegalArgumentException { + throw new MethodNotYetImplementedException(); + } + + @Override + public int getBits(final int pIndex, final int pLength) throws IllegalArgumentException { + throw new MethodNotYetImplementedException(); + } + + @Override + public long getLongBits(final int pIndex, final int pLength) throws IllegalArgumentException { + /* Sanity checks. */ + if (pIndex < 0) { + throw new IllegalArgumentException("pIndex must be >= 0."); + } + if (pLength < 0) { + throw new IllegalArgumentException("pLength must be >= 0."); + } + if ((pIndex + pLength) > this.mSize) { + throw new IllegalArgumentException("pIndex + pLength must be <= size."); + } + + /* Early exit. */ + if (pLength == 0) { + return 0L; + } + + final int dataIndex = pIndex / DataConstants.BITS_PER_LONG; + final int offset = pIndex % DataConstants.BITS_PER_LONG; + + final long data; + if (offset == 0) { + data = this.mData[dataIndex]; + } else if ((offset + pLength) <= DataConstants.BITS_PER_LONG) { + data = this.mData[dataIndex] << offset; + } else { + /* Join bits from adjacent data fields. */ + data = (this.mData[dataIndex] << offset) | (this.mData[dataIndex + 1] >>> (DataConstants.BITS_PER_LONG - offset)); + } + + if (pLength == DataConstants.BITS_PER_LONG) { + return data; + } else { + final int rightShift = DataConstants.BITS_PER_LONG - pLength; + final long mask = 0xFFFFFFFFFFFFFFFFL >>> rightShift; + final long unmaskedBits = data >> rightShift; + return unmaskedBits & mask; + } + } + + + @Override + public void setBits(final int pIndex, final byte pBits, final int pBitIndex, final int pBitCount) throws IllegalArgumentException { + throw new MethodNotYetImplementedException(); + } + + @Override + public void setBits(final int pIndex, final short pBits, final int pBitIndex, final int pBitCount) throws IllegalArgumentException { + throw new MethodNotYetImplementedException(); + } + + @Override + public void setBits(final int pIndex, final int pBits, final int pBitIndex, final int pBitCount) throws IllegalArgumentException { + throw new MethodNotYetImplementedException(); + } + + @Override + public byte getByte(final int pIndex) throws IllegalArgumentException { + return (byte) this.getBits(pIndex, DataConstants.BITS_PER_BYTE); + } + + @Override + public void setByte(final int pIndex, final byte pByte) throws IllegalArgumentException { + throw new MethodNotYetImplementedException(); + } + + @Override + public short getShort(final int pIndex) throws IllegalArgumentException { + return (short) this.getBits(pIndex, DataConstants.BITS_PER_SHORT); + } + + @Override + public void setShort(final int pIndex, final short pShort) throws IllegalArgumentException { + throw new MethodNotYetImplementedException(); + } + + @Override + public int getInt(final int pIndex) throws IllegalArgumentException { + return this.getBits(pIndex, DataConstants.BITS_PER_INT); + } + + @Override + public void setInt(final int pIndex, final int pInt) throws IllegalArgumentException { + throw new MethodNotYetImplementedException(); + } + + @Override + public long getLong(final int pIndex) throws IllegalArgumentException { + return this.getLongBits(pIndex, DataConstants.BITS_PER_LONG); + } + + @Override + public void setLong(final int pIndex, final long pLong) throws IllegalArgumentException { + throw new MethodNotYetImplementedException(); + } + + @Override + public void clear() { + Arrays.fill(this.mData, 0x00); + } + + @Override + public void fill(final byte pByte) { + throw new MethodNotYetImplementedException(); + } + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + public void save(final DataOutputStream pDataOutputStream) throws IOException { + throw new MethodNotYetImplementedException(); + } + + @Override + public byte[] toByteArray() { + final int byteArrayLength; + if ((this.mSize % DataConstants.BITS_PER_BYTE) == 0) { + byteArrayLength = this.mSize / DataConstants.BITS_PER_BYTE; + } else { + byteArrayLength = (this.mSize / DataConstants.BITS_PER_BYTE) + 1; + } + + final byte[] bytes = new byte[byteArrayLength]; + /* Check if bytes perfectly fit into the data fields or if there are some overflow bytes that need special treatment. */ + final boolean perfectDataFit = (this.mSize % DataConstants.BITS_PER_LONG) == 0; + + final long[] data = this.mData; + final int dataLength = data.length; + final int lastCompleteDataIndex = (perfectDataFit) ? dataLength - 1 : dataLength - 2; + + int bytesOffset = (lastCompleteDataIndex * DataConstants.BYTES_PER_LONG) + (DataConstants.BYTES_PER_LONG - 1); + for (int i = lastCompleteDataIndex; i >= 0; i--) { + final long dataField = data[i]; + + bytes[bytesOffset--] = (byte) ((dataField >> 0) & 0xFF); + bytes[bytesOffset--] = (byte) ((dataField >> 8) & 0xFF); + bytes[bytesOffset--] = (byte) ((dataField >> 16) & 0xFF); + bytes[bytesOffset--] = (byte) ((dataField >> 24) & 0xFF); + bytes[bytesOffset--] = (byte) ((dataField >> 32) & 0xFF); + bytes[bytesOffset--] = (byte) ((dataField >> 40) & 0xFF); + bytes[bytesOffset--] = (byte) ((dataField >> 48) & 0xFF); + bytes[bytesOffset--] = (byte) ((dataField >> 56) & 0xFF); + } + + /* Put overflow bytes into last data field. */ + if (!perfectDataFit) { + final int overflowDataIndex = dataLength - 1; + final long overflowDataField = data[overflowDataIndex]; + + final int overflowBytesOffset = overflowDataIndex * DataConstants.BYTES_PER_LONG; + + final int overflowByteCount = bytes.length % DataConstants.BYTES_PER_LONG; + switch (overflowByteCount) { + case 7: + bytes[overflowBytesOffset + 6] = (byte) ((overflowDataField >> 8) & 0xFF); + case 6: + bytes[overflowBytesOffset + 5] = (byte) ((overflowDataField >> 16) & 0xFF); + case 5: + bytes[overflowBytesOffset + 4] = (byte) ((overflowDataField >> 24) & 0xFF); + case 4: + bytes[overflowBytesOffset + 3] = (byte) ((overflowDataField >> 32) & 0xFF); + case 3: + bytes[overflowBytesOffset + 2] = (byte) ((overflowDataField >> 40) & 0xFF); + case 2: + bytes[overflowBytesOffset + 1] = (byte) ((overflowDataField >> 48) & 0xFF); + case 1: + bytes[overflowBytesOffset + 0] = (byte) ((overflowDataField >> 56) & 0xFF); + } + } + + return bytes; + } + + @Override + public String toString() { + final StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.append('['); + + for (int i = 0; i < this.mSize; i++) { + if (this.getBit(i) == BitVector.TRUE) { + stringBuilder.append('1'); + } else { + stringBuilder.append('0'); + } + + if (((i % Byte.SIZE) == (Long.SIZE - 1)) && (i < (this.mSize - 1))) { + stringBuilder.append(',').append(' '); + } + } + + stringBuilder.append(']'); + return stringBuilder.toString(); + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== +} \ No newline at end of file diff --git a/src/org/andengine/util/adt/bounds/BoundsSplit.java b/src/org/andengine/util/adt/bounds/BoundsSplit.java index f8641bc31..67607e641 100644 --- a/src/org/andengine/util/adt/bounds/BoundsSplit.java +++ b/src/org/andengine/util/adt/bounds/BoundsSplit.java @@ -3,7 +3,7 @@ import org.andengine.util.exception.AndEngineRuntimeException; /** - * (c) Zynga 2011 + * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 21:13:32 - 11.10.2011 diff --git a/src/org/andengine/util/adt/bounds/FloatBounds.java b/src/org/andengine/util/adt/bounds/FloatBounds.java index a4ceb5e25..ed29a18b3 100644 --- a/src/org/andengine/util/adt/bounds/FloatBounds.java +++ b/src/org/andengine/util/adt/bounds/FloatBounds.java @@ -3,7 +3,7 @@ import org.andengine.util.adt.spatial.bounds.util.FloatBoundsUtils; /** - * (c) Zynga 2011 + * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 21:48:53 - 11.10.2011 @@ -25,7 +25,7 @@ public class FloatBounds implements IFloatBounds { // =========================================================== // Constructors // =========================================================== - + public FloatBounds(final float pX, final float pY) { this.set(pX, pY); } @@ -42,7 +42,7 @@ public FloatBounds(final float pXMin, final float pYMin, final float pXMax, fina public float getXMin() { return this.mXMin; } - + @Override public float getYMin() { return this.mYMin; @@ -68,10 +68,10 @@ public void set(final float pXMin, final float pYMin, final float pXMax, final f this.mXMax = pXMax; this.mYMax = pYMax; - if(pXMin > pXMax) { + if (pXMin > pXMax) { throw new IllegalArgumentException("pXMin: '" + pXMin + "' must be smaller or equal to pXMax: '" + pXMax + "'."); } - if(pYMin > pYMax) { + if (pYMin > pYMax) { throw new IllegalArgumentException("pYMin: '" + pYMin + "' must be smaller or equal to pYMax: '" + pYMax + "'."); } } diff --git a/src/org/andengine/util/adt/bounds/IBounds.java b/src/org/andengine/util/adt/bounds/IBounds.java index b0f10a36b..c5a0cbd82 100644 --- a/src/org/andengine/util/adt/bounds/IBounds.java +++ b/src/org/andengine/util/adt/bounds/IBounds.java @@ -1,7 +1,7 @@ package org.andengine.util.adt.bounds; /** - * (c) Zynga 2011 + * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 7:45:19 AM - Oct 10, 2011 diff --git a/src/org/andengine/util/adt/bounds/IFloatBounds.java b/src/org/andengine/util/adt/bounds/IFloatBounds.java index a6d022be7..3b3d85a19 100644 --- a/src/org/andengine/util/adt/bounds/IFloatBounds.java +++ b/src/org/andengine/util/adt/bounds/IFloatBounds.java @@ -1,7 +1,7 @@ package org.andengine.util.adt.bounds; /** - * (c) Zynga 2011 + * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 7:42:02 AM - Oct 10, 2011 diff --git a/src/org/andengine/util/adt/bounds/IIntBounds.java b/src/org/andengine/util/adt/bounds/IIntBounds.java index c416f8aae..2711cbd9c 100644 --- a/src/org/andengine/util/adt/bounds/IIntBounds.java +++ b/src/org/andengine/util/adt/bounds/IIntBounds.java @@ -1,7 +1,7 @@ package org.andengine.util.adt.bounds; /** - * (c) Zynga 2011 + * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 7:42:02 AM - Oct 10, 2011 diff --git a/src/org/andengine/util/adt/bounds/IntBounds.java b/src/org/andengine/util/adt/bounds/IntBounds.java index 81b16bbfe..52ea14062 100644 --- a/src/org/andengine/util/adt/bounds/IntBounds.java +++ b/src/org/andengine/util/adt/bounds/IntBounds.java @@ -3,7 +3,7 @@ import org.andengine.util.adt.spatial.bounds.util.IntBoundsUtils; /** - * (c) Zynga 2011 + * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 21:45:04 - 11.11.2011 @@ -25,7 +25,7 @@ public class IntBounds implements IIntBounds { // =========================================================== // Constructors // =========================================================== - + public IntBounds(final int pX, final int pY) { this.set(pX, pY); } @@ -42,7 +42,7 @@ public IntBounds(final int pXMin, final int pYMin, final int pXMax, final int pY public int getXMin() { return this.mXMin; } - + @Override public int getYMin() { return this.mYMin; @@ -68,10 +68,10 @@ public void set(final int pXMin, final int pYMin, final int pXMax, final int pYM this.mXMax = pXMax; this.mYMax = pYMax; - if(pXMin > pXMax) { + if (pXMin > pXMax) { throw new IllegalArgumentException("pXMin: '" + pXMin + "' must be smaller or equal to pXMax: '" + pXMax + "'."); } - if(pYMin > pYMax) { + if (pYMin > pYMax) { throw new IllegalArgumentException("pYMin: '" + pYMin + "' must be smaller or equal to pYMax: '" + pYMax + "'."); } } diff --git a/src/org/andengine/util/adt/cache/IntLRUCache.java b/src/org/andengine/util/adt/cache/IntLRUCache.java index 3c816e07c..22d523fe8 100644 --- a/src/org/andengine/util/adt/cache/IntLRUCache.java +++ b/src/org/andengine/util/adt/cache/IntLRUCache.java @@ -5,7 +5,7 @@ import android.util.SparseArray; /** - * (c) Zynga 2011 + * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 12:19:22 - 08.12.2011 @@ -70,27 +70,27 @@ public boolean isEmpty() { public V put(final int pKey, final V pValue) { final IntLRUCacheValueHolder existingIntLRUCacheValueHolder = this.mSparseArray.get(pKey); - if(existingIntLRUCacheValueHolder != null) { + if (existingIntLRUCacheValueHolder != null) { /* Just heat up that item. */ this.mIntLRUCacheQueue.moveToTail(existingIntLRUCacheValueHolder.mIntLRUCacheQueueNode); return existingIntLRUCacheValueHolder.mValue; } - if(this.mSize >= this.mCapacity) { + if (this.mSize >= this.mCapacity) { final int deadKey = this.mIntLRUCacheQueue.poll(); this.mSparseArray.remove(deadKey); this.mSize--; } - final IntLRUCacheQueueNode IntLRUCacheQueueNode = this.mIntLRUCacheQueue.add(pKey); + final IntLRUCacheQueueNode intLRUCacheQueueNode = this.mIntLRUCacheQueue.add(pKey); - final IntLRUCacheValueHolder IntLRUCacheValueHolder = this.mIntLRUCacheValueHolderPool.obtainPoolItem(); -// final IntLRUCacheValueHolder IntLRUCacheValueHolder = new IntLRUCacheValueHolder(); - IntLRUCacheValueHolder.mValue = pValue; - IntLRUCacheValueHolder.mIntLRUCacheQueueNode = IntLRUCacheQueueNode; + final IntLRUCacheValueHolder intLRUCacheValueHolder = this.mIntLRUCacheValueHolderPool.obtainPoolItem(); +// final IntLRUCacheValueHolder intLRUCacheValueHolder = new IntLRUCacheValueHolder(); + intLRUCacheValueHolder.mValue = pValue; + intLRUCacheValueHolder.mIntLRUCacheQueueNode = intLRUCacheQueueNode; - this.mSparseArray.put(pKey, IntLRUCacheValueHolder); + this.mSparseArray.put(pKey, intLRUCacheValueHolder); this.mSize++; @@ -98,21 +98,21 @@ public V put(final int pKey, final V pValue) { } public V get(final int pKey) { - final IntLRUCacheValueHolder IntLRUCacheValueHolder = this.mSparseArray.get(pKey); - if(IntLRUCacheValueHolder == null) { + final IntLRUCacheValueHolder intLRUCacheValueHolder = this.mSparseArray.get(pKey); + if (intLRUCacheValueHolder == null) { return null; } - this.mIntLRUCacheQueue.moveToTail(IntLRUCacheValueHolder.mIntLRUCacheQueueNode); + this.mIntLRUCacheQueue.moveToTail(intLRUCacheValueHolder.mIntLRUCacheQueueNode); - return IntLRUCacheValueHolder.mValue; + return intLRUCacheValueHolder.mValue; } public void clear() { - while(!this.mIntLRUCacheQueue.isEmpty()) { + while (!this.mIntLRUCacheQueue.isEmpty()) { final int key = this.mIntLRUCacheQueue.poll(); final IntLRUCacheValueHolder lruCacheValueHolder = this.mSparseArray.get(key); - if(lruCacheValueHolder == null) { + if (lruCacheValueHolder == null) { throw new IllegalArgumentException(); } this.mSparseArray.remove(key); @@ -243,15 +243,15 @@ public boolean isEmpty() { } public IntLRUCacheQueueNode add(final int pKey) { - final IntLRUCacheQueueNode IntLRUCacheQueueNode = this.mIntLRUCacheQueueNodePool.obtainPoolItem(); -// final IntLRUCacheQueueNode IntLRUCacheQueueNode = new IntLRUCacheQueueNode(); - IntLRUCacheQueueNode.mKey = pKey; + final IntLRUCacheQueueNode intLRUCacheQueueNode = this.mIntLRUCacheQueueNodePool.obtainPoolItem(); +// final IntLRUCacheQueueNode intLRUCacheQueueNode = new IntLRUCacheQueueNode(); + intLRUCacheQueueNode.mKey = pKey; - return this.add(IntLRUCacheQueueNode); + return this.add(intLRUCacheQueueNode); } private IntLRUCacheQueueNode add(final IntLRUCacheQueueNode pIntLRUCacheQueueNode) { - if(this.isEmpty()) { + if (this.isEmpty()) { this.mHead = pIntLRUCacheQueueNode; this.mTail = this.mHead; } else { @@ -266,12 +266,12 @@ private IntLRUCacheQueueNode add(final IntLRUCacheQueueNode pIntLRUCacheQueueNod public int poll() { final IntLRUCacheQueueNode head = this.mHead; final int key = this.mHead.mKey; - if(key == 0) { + if (key == 0) { throw new IllegalStateException(); } /* Check if item to poll is the tail. */ - if(this.mHead.mNext == null) { + if (this.mHead.mNext == null) { this.mHead = null; this.mTail = null; } else { @@ -287,14 +287,14 @@ public void moveToTail(final IntLRUCacheQueueNode pIntLRUCacheQueueNode) { final IntLRUCacheQueueNode next = pIntLRUCacheQueueNode.mNext; /* Check if the node already is the tail. */ - if(next == null) { + if (next == null) { return; } else { final IntLRUCacheQueueNode previous = pIntLRUCacheQueueNode.mPrevious; next.mPrevious = previous; /* Check if item to bump is the head. */ - if(previous == null) { + if (previous == null) { this.mHead = next; } else { previous.mNext = next; diff --git a/src/org/andengine/util/adt/cache/LRUCache.java b/src/org/andengine/util/adt/cache/LRUCache.java index 5dfed46db..0c378a99e 100644 --- a/src/org/andengine/util/adt/cache/LRUCache.java +++ b/src/org/andengine/util/adt/cache/LRUCache.java @@ -5,7 +5,7 @@ import org.andengine.util.adt.pool.GenericPool; /** - * (c) Zynga 2011 + * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 00:24:52 - 02.11.2011 @@ -70,14 +70,14 @@ public boolean isEmpty() { public V put(final K pKey, final V pValue) { final LRUCacheValueHolder existingLRUCacheValueHolder = this.mMap.get(pKey); - if(existingLRUCacheValueHolder != null) { + if (existingLRUCacheValueHolder != null) { /* Just heat up that item. */ this.mLRUCacheQueue.moveToTail(existingLRUCacheValueHolder.mLRUCacheQueueNode); return existingLRUCacheValueHolder.mValue; } - if(this.mSize >= this.mCapacity) { + if (this.mSize >= this.mCapacity) { final K deadKey = this.mLRUCacheQueue.poll(); this.mMap.remove(deadKey); this.mSize--; @@ -99,7 +99,7 @@ public V put(final K pKey, final V pValue) { public V get(final K pKey) { final LRUCacheValueHolder lruCacheValueHolder = this.mMap.get(pKey); - if(lruCacheValueHolder == null) { + if (lruCacheValueHolder == null) { return null; } @@ -109,7 +109,7 @@ public V get(final K pKey) { } public void clear() { - while(!this.mLRUCacheQueue.isEmpty()) { + while (!this.mLRUCacheQueue.isEmpty()) { final K key = this.mLRUCacheQueue.poll(); final LRUCacheValueHolder lruCacheValueHolder = this.mMap.remove(key); this.mLRUCacheValueHolderPool.recyclePoolItem(lruCacheValueHolder); @@ -248,7 +248,7 @@ public LRUCacheQueueNode add(final K pKey) { } private LRUCacheQueueNode add(final LRUCacheQueueNode pLRUCacheQueueNode) { - if(this.isEmpty()) { + if (this.isEmpty()) { this.mHead = pLRUCacheQueueNode; this.mTail = this.mHead; } else { @@ -265,7 +265,7 @@ public K poll() { final K key = this.mHead.mKey; /* Check if item to poll is the tail. */ - if(this.mHead.mNext == null) { + if (this.mHead.mNext == null) { this.mHead = null; this.mTail = null; } else { @@ -281,14 +281,14 @@ public void moveToTail(final LRUCacheQueueNode pLRUCacheQueueNode) { final LRUCacheQueueNode next = pLRUCacheQueueNode.mNext; /* Check if the node already is the tail. */ - if(next == null) { + if (next == null) { return; } else { final LRUCacheQueueNode previous = pLRUCacheQueueNode.mPrevious; next.mPrevious = previous; /* Check if item to bump is the head. */ - if(previous == null) { + if (previous == null) { this.mHead = next; } else { previous.mNext = next; diff --git a/src/org/andengine/util/adt/cache/concurrent/SynchronizedIntLRUCache.java b/src/org/andengine/util/adt/cache/concurrent/SynchronizedIntLRUCache.java index 91d854b51..1d1c4a667 100644 --- a/src/org/andengine/util/adt/cache/concurrent/SynchronizedIntLRUCache.java +++ b/src/org/andengine/util/adt/cache/concurrent/SynchronizedIntLRUCache.java @@ -3,7 +3,7 @@ import org.andengine.util.adt.cache.IntLRUCache; /** - * (c) Zynga 2012 + * (c) 2012 Zynga Inc. * * @author Nicolas Gramlich * @since 18:26:47 - 16.01.2012 diff --git a/src/org/andengine/util/adt/cache/concurrent/SynchronizedLRUCache.java b/src/org/andengine/util/adt/cache/concurrent/SynchronizedLRUCache.java index e56b7d178..084333adb 100644 --- a/src/org/andengine/util/adt/cache/concurrent/SynchronizedLRUCache.java +++ b/src/org/andengine/util/adt/cache/concurrent/SynchronizedLRUCache.java @@ -3,7 +3,7 @@ import org.andengine.util.adt.cache.LRUCache; /** - * (c) Zynga 2012 + * (c) 2012 Zynga Inc. * * @author Nicolas Gramlich * @since 18:26:47 - 16.01.2012 diff --git a/src/org/andengine/util/color/Color.java b/src/org/andengine/util/adt/color/Color.java similarity index 94% rename from src/org/andengine/util/color/Color.java rename to src/org/andengine/util/adt/color/Color.java index 217dfb2b7..1f8d4c622 100644 --- a/src/org/andengine/util/color/Color.java +++ b/src/org/andengine/util/adt/color/Color.java @@ -1,7 +1,7 @@ -package org.andengine.util.color; +package org.andengine.util.adt.color; /** - * (c) Zynga 2011 + * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 02:23:08 - 12.08.2011 @@ -60,7 +60,7 @@ public class Color { public static final float BLUE_ABGR_PACKED_FLOAT = Color.BLUE.getABGRPackedFloat(); public static final float PINK_ABGR_PACKED_FLOAT = Color.PINK.getABGRPackedFloat(); public static final float TRANSPARENT_ABGR_PACKED_FLOAT = Color.TRANSPARENT.getABGRPackedFloat(); - + public static final int WHITE_ARGB_PACKED_INT = Color.WHITE.getARGBPackedInt(); public static final int BLACK_ARGB_PACKED_INT = Color.BLACK.getARGBPackedInt(); public static final int RED_ARGB_PACKED_INT = Color.RED.getARGBPackedInt(); @@ -87,6 +87,10 @@ public class Color { // Constructors // =========================================================== + /* package */ Color() { + + } + public Color(final Color pColor) { this.set(pColor); } @@ -126,7 +130,7 @@ public final void setRed(final float pRed) { } public final boolean setRedChecking(final float pRed) { - if(this.mRed != pRed) { + if (this.mRed != pRed) { this.mRed = pRed; this.packABGRRed(); @@ -142,7 +146,7 @@ public final void setGreen(final float pGreen) { } public final boolean setGreenChecking(final float pGreen) { - if(this.mGreen != pGreen) { + if (this.mGreen != pGreen) { this.mGreen = pGreen; this.packABGRGreen(); @@ -158,7 +162,7 @@ public final void setBlue(final float pBlue) { } public final boolean setBlueChecking(final float pBlue) { - if(this.mBlue != pBlue) { + if (this.mBlue != pBlue) { this.mBlue = pBlue; this.packABGRBlue(); @@ -174,7 +178,7 @@ public final void setAlpha(final float pAlpha) { } public final boolean setAlphaChecking(final float pAlpha) { - if(this.mAlpha != pAlpha) { + if (this.mAlpha != pAlpha) { this.mAlpha = pAlpha; this.packABGRAlpha(); @@ -192,7 +196,7 @@ public final void set(final float pRed, final float pGreen, final float pBlue) { } public final boolean setChecking(final float pRed, final float pGreen, final float pBlue) { - if((this.mRed != pRed) || (this.mGreen != pGreen) || (this.mBlue != pBlue)) { + if ((this.mRed != pRed) || (this.mGreen != pGreen) || (this.mBlue != pBlue)) { this.mRed = pRed; this.mGreen = pGreen; this.mBlue = pBlue; @@ -213,7 +217,7 @@ public final void set(final float pRed, final float pGreen, final float pBlue, f } public final boolean setChecking(final float pRed, final float pGreen, final float pBlue, final float pAlpha) { - if((this.mAlpha != pAlpha) || (this.mRed != pRed) || (this.mGreen != pGreen) || (this.mBlue != pBlue)) { + if ((this.mAlpha != pAlpha) || (this.mRed != pRed) || (this.mGreen != pGreen) || (this.mBlue != pBlue)) { this.mRed = pRed; this.mGreen = pGreen; this.mBlue = pBlue; @@ -236,7 +240,7 @@ public final void set(final Color pColor) { } public final boolean setChecking(final Color pColor) { - if(this.mABGRPackedInt != pColor.mABGRPackedInt) { + if (this.mABGRPackedInt != pColor.mABGRPackedInt) { this.mRed = pColor.mRed; this.mGreen = pColor.mGreen; this.mBlue = pColor.mBlue; @@ -279,11 +283,11 @@ public int hashCode() { @Override public boolean equals(final Object pObject) { - if(this == pObject) { + if (this == pObject) { return true; - } else if(pObject == null) { + } else if (pObject == null) { return false; - } else if(this.getClass() != pObject.getClass()) { + } else if (this.getClass() != pObject.getClass()) { return false; } @@ -301,7 +305,7 @@ public String toString() { .append(this.mBlue) .append(", Alpha: ") .append(this.mAlpha) - .append("]") + .append(']') .toString(); } diff --git a/src/org/andengine/util/color/ColorPool.java b/src/org/andengine/util/adt/color/ColorPool.java similarity index 96% rename from src/org/andengine/util/color/ColorPool.java rename to src/org/andengine/util/adt/color/ColorPool.java index a6167c7f0..036fd3a13 100644 --- a/src/org/andengine/util/color/ColorPool.java +++ b/src/org/andengine/util/adt/color/ColorPool.java @@ -1,9 +1,9 @@ -package org.andengine.util.color; +package org.andengine.util.adt.color; import org.andengine.util.adt.pool.GenericPool; /** - * (c) Zynga 2011 + * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 2:25:20 - 12.08.2011 diff --git a/src/org/andengine/util/color/ColorUtils.java b/src/org/andengine/util/adt/color/ColorUtils.java similarity index 90% rename from src/org/andengine/util/color/ColorUtils.java rename to src/org/andengine/util/adt/color/ColorUtils.java index c4903bb3f..238d78772 100644 --- a/src/org/andengine/util/color/ColorUtils.java +++ b/src/org/andengine/util/adt/color/ColorUtils.java @@ -1,13 +1,13 @@ -package org.andengine.util.color; +package org.andengine.util.adt.color; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 11:13:45 - 04.08.2010 */ -public class ColorUtils { +public final class ColorUtils { // =========================================================== // Constants // =========================================================== @@ -28,6 +28,10 @@ public class ColorUtils { // Constructors // =========================================================== + private ColorUtils() { + + } + // =========================================================== // Getter & Setter // =========================================================== @@ -64,21 +68,37 @@ public static final Color convertHSVToColor(final float pHue, final float pSatur public static Color convertARGBPackedIntToColor(final int pARGBPackedInt) { + final Color color = new Color(); + + ColorUtils.convertARGBPackedIntToColor(pARGBPackedInt, color); + + return color; + } + + public static void convertARGBPackedIntToColor(final int pARGBPackedInt, final Color pColor) { final float alpha = ColorUtils.extractAlphaFromARGBPackedInt(pARGBPackedInt); final float red = ColorUtils.extractRedFromARGBPackedInt(pARGBPackedInt); final float green = ColorUtils.extractGreenFromARGBPackedInt(pARGBPackedInt); final float blue = ColorUtils.extractBlueFromARGBPackedInt(pARGBPackedInt); - return new Color(red, green, blue, alpha); + pColor.set(red, green, blue, alpha); } public static Color convertABGRPackedIntToColor(final int pABGRPackedInt) { + final Color color = new Color(); + + ColorUtils.convertABGRPackedIntToColor(pABGRPackedInt, color); + + return color; + } + + public static void convertABGRPackedIntToColor(final int pABGRPackedInt, final Color pColor) { final float alpha = ColorUtils.extractAlphaFromABGRPackedInt(pABGRPackedInt); final float blue = ColorUtils.extractBlueFromABGRPackedInt(pABGRPackedInt); final float green = ColorUtils.extractGreenFromABGRPackedInt(pABGRPackedInt); final float red = ColorUtils.extractRedFromABGRPackedInt(pABGRPackedInt); - return new Color(red, green, blue, alpha); + pColor.set(red, green, blue, alpha); } diff --git a/src/org/andengine/util/color/constants/ColorConstants.java b/src/org/andengine/util/adt/color/constants/ColorConstants.java similarity index 85% rename from src/org/andengine/util/color/constants/ColorConstants.java rename to src/org/andengine/util/adt/color/constants/ColorConstants.java index 89005b7e6..eb862e2e4 100644 --- a/src/org/andengine/util/color/constants/ColorConstants.java +++ b/src/org/andengine/util/adt/color/constants/ColorConstants.java @@ -1,9 +1,9 @@ -package org.andengine.util.color.constants; +package org.andengine.util.adt.color.constants; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 10:21:46 - 19.07.2010 */ diff --git a/src/org/andengine/util/adt/data/DataUtils.java b/src/org/andengine/util/adt/data/DataUtils.java index b905a8e40..bb717c1dc 100644 --- a/src/org/andengine/util/adt/data/DataUtils.java +++ b/src/org/andengine/util/adt/data/DataUtils.java @@ -3,9 +3,9 @@ /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 15:01:49 - 20.03.2011 */ @@ -22,6 +22,10 @@ public final class DataUtils { // Constructors // =========================================================== + private DataUtils() { + + } + // =========================================================== // Getter & Setter // =========================================================== @@ -34,6 +38,10 @@ public static final int unsignedByteToInt(final byte pByte) { return pByte & 0xFF; } + public static final int getBitLength(final int pNumber) { + return Integer.SIZE - Integer.numberOfLeadingZeros(pNumber); + } + // =========================================================== // Methods // =========================================================== diff --git a/src/org/andengine/util/adt/DataConstants.java b/src/org/andengine/util/adt/data/constants/DataConstants.java similarity index 76% rename from src/org/andengine/util/adt/DataConstants.java rename to src/org/andengine/util/adt/data/constants/DataConstants.java index 81090915e..69f8e5c1a 100644 --- a/src/org/andengine/util/adt/DataConstants.java +++ b/src/org/andengine/util/adt/data/constants/DataConstants.java @@ -1,9 +1,9 @@ -package org.andengine.util.adt; +package org.andengine.util.adt.data.constants; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 17:59:55 - 14.07.2011 */ @@ -14,6 +14,7 @@ public interface DataConstants { public static final int BYTES_PER_BYTE = 1; public static final int BYTES_PER_SHORT = Short.SIZE / Byte.SIZE; + public static final int BYTES_PER_CHAR = Character.SIZE / Byte.SIZE; public static final int BYTES_PER_INT = Integer.SIZE / Byte.SIZE; public static final int BYTES_PER_LONG = Long.SIZE / Byte.SIZE; public static final int BYTES_PER_FLOAT = Float.SIZE / Byte.SIZE; @@ -27,12 +28,13 @@ public interface DataConstants { public static final int BYTE_TO_MEGABYTE_SHIFT = 20; public static final int BYTE_TO_GIGABYTE_SHIFT = 30; - public static final short UNSIGNED_BYTE_MAX_VALUE = (short)Byte.MAX_VALUE - (short)Byte.MIN_VALUE; - public static final int UNSIGNED_SHORT_MAX_VALUE = (int)Short.MAX_VALUE - (int)Short.MIN_VALUE; - public static final long UNSIGNED_INT_MAX_VALUE = (long)Integer.MAX_VALUE - (long)Integer.MIN_VALUE; + public static final short UNSIGNED_BYTE_MAX_VALUE = (short) Byte.MAX_VALUE - (short) Byte.MIN_VALUE; + public static final int UNSIGNED_SHORT_MAX_VALUE = (int) Short.MAX_VALUE - (int) Short.MIN_VALUE; + public static final long UNSIGNED_INT_MAX_VALUE = (long) Integer.MAX_VALUE - (long) Integer.MIN_VALUE; public static final int BITS_PER_BYTE = 8; public static final int BITS_PER_SHORT = BYTES_PER_SHORT * BITS_PER_BYTE; + public static final int BITS_PER_CHAR = BYTES_PER_CHAR * BITS_PER_BYTE; public static final int BITS_PER_INT = BYTES_PER_INT * BITS_PER_BYTE; public static final int BITS_PER_LONG = BYTES_PER_LONG * BITS_PER_BYTE; public static final int BITS_PER_FLOAT = BYTES_PER_FLOAT * BITS_PER_BYTE; diff --git a/src/org/andengine/util/adt/data/operator/ByteOperator.java b/src/org/andengine/util/adt/data/operator/ByteOperator.java index ff5649844..9c4749a1f 100644 --- a/src/org/andengine/util/adt/data/operator/ByteOperator.java +++ b/src/org/andengine/util/adt/data/operator/ByteOperator.java @@ -1,7 +1,7 @@ package org.andengine.util.adt.data.operator; /** - * (c) Zynga 2012 + * (c) 2012 Zynga Inc. * * @author Nicolas Gramlich * @since 14:24:15 - 02.02.2012 @@ -17,31 +17,31 @@ public boolean check(final byte pByteA, final byte pByteB) { return pByteA == pByteB; } }, - NOT_EQUALS() { + NOT_EQUALS() { @Override public boolean check(final byte pByteA, final byte pByteB) { return pByteA != pByteB; } }, - LESS_THAN() { + LESS_THAN() { @Override public boolean check(final byte pByteA, final byte pByteB) { return pByteA < pByteB; } }, - LESS_OR_EQUAL_THAN() { + LESS_OR_EQUAL_THAN() { @Override public boolean check(final byte pByteA, final byte pByteB) { return pByteA <= pByteB; } }, - MORE_THAN() { + MORE_THAN() { @Override public boolean check(final byte pByteA, final byte pByteB) { return pByteA > pByteB; } }, - MORE_OR_EQUAL_THAN() { + MORE_OR_EQUAL_THAN() { @Override public boolean check(final byte pByteA, final byte pByteB) { return pByteA >= pByteB; diff --git a/src/org/andengine/util/adt/data/operator/CharOperator.java b/src/org/andengine/util/adt/data/operator/CharOperator.java index 9d301ceb6..dbb77646f 100644 --- a/src/org/andengine/util/adt/data/operator/CharOperator.java +++ b/src/org/andengine/util/adt/data/operator/CharOperator.java @@ -1,7 +1,7 @@ package org.andengine.util.adt.data.operator; /** - * (c) Zynga 2012 + * (c) 2012 Zynga Inc. * * @author Nicolas Gramlich * @since 14:24:15 - 02.02.2012 @@ -17,31 +17,31 @@ public boolean check(final char pCharA, final char pCharB) { return pCharA == pCharB; } }, - NOT_EQUALS() { + NOT_EQUALS() { @Override public boolean check(final char pCharA, final char pCharB) { return pCharA != pCharB; } }, - LESS_THAN() { + LESS_THAN() { @Override public boolean check(final char pCharA, final char pCharB) { return pCharA < pCharB; } }, - LESS_OR_EQUAL_THAN() { + LESS_OR_EQUAL_THAN() { @Override public boolean check(final char pCharA, final char pCharB) { return pCharA <= pCharB; } }, - MORE_THAN() { + MORE_THAN() { @Override public boolean check(final char pCharA, final char pCharB) { return pCharA > pCharB; } }, - MORE_OR_EQUAL_THAN() { + MORE_OR_EQUAL_THAN() { @Override public boolean check(final char pCharA, final char pCharB) { return pCharA >= pCharB; diff --git a/src/org/andengine/util/adt/data/operator/DoubleOperator.java b/src/org/andengine/util/adt/data/operator/DoubleOperator.java index a566fec97..48835735c 100644 --- a/src/org/andengine/util/adt/data/operator/DoubleOperator.java +++ b/src/org/andengine/util/adt/data/operator/DoubleOperator.java @@ -1,7 +1,7 @@ package org.andengine.util.adt.data.operator; /** - * (c) Zynga 2012 + * (c) 2012 Zynga Inc. * * @author Nicolas Gramlich * @since 14:24:15 - 02.02.2012 @@ -17,31 +17,31 @@ public boolean check(final double pDoubleA, final double pDoubleB) { return pDoubleA == pDoubleB; } }, - NOT_EQUALS() { + NOT_EQUALS() { @Override public boolean check(final double pDoubleA, final double pDoubleB) { return pDoubleA != pDoubleB; } }, - LESS_THAN() { + LESS_THAN() { @Override public boolean check(final double pDoubleA, final double pDoubleB) { return pDoubleA < pDoubleB; } }, - LESS_OR_EQUAL_THAN() { + LESS_OR_EQUAL_THAN() { @Override public boolean check(final double pDoubleA, final double pDoubleB) { return pDoubleA <= pDoubleB; } }, - MORE_THAN() { + MORE_THAN() { @Override public boolean check(final double pDoubleA, final double pDoubleB) { return pDoubleA > pDoubleB; } }, - MORE_OR_EQUAL_THAN() { + MORE_OR_EQUAL_THAN() { @Override public boolean check(final double pDoubleA, final double pDoubleB) { return pDoubleA >= pDoubleB; diff --git a/src/org/andengine/util/adt/data/operator/FloatOperator.java b/src/org/andengine/util/adt/data/operator/FloatOperator.java index 0f5504405..1346f6286 100644 --- a/src/org/andengine/util/adt/data/operator/FloatOperator.java +++ b/src/org/andengine/util/adt/data/operator/FloatOperator.java @@ -1,7 +1,7 @@ package org.andengine.util.adt.data.operator; /** - * (c) Zynga 2012 + * (c) 2012 Zynga Inc. * * @author Nicolas Gramlich * @since 14:24:15 - 02.02.2012 @@ -17,31 +17,31 @@ public boolean check(final float pFloatA, final float pFloatB) { return pFloatA == pFloatB; } }, - NOT_EQUALS() { + NOT_EQUALS() { @Override public boolean check(final float pFloatA, final float pFloatB) { return pFloatA != pFloatB; } }, - LESS_THAN() { + LESS_THAN() { @Override public boolean check(final float pFloatA, final float pFloatB) { return pFloatA < pFloatB; } }, - LESS_OR_EQUAL_THAN() { + LESS_OR_EQUAL_THAN() { @Override public boolean check(final float pFloatA, final float pFloatB) { return pFloatA <= pFloatB; } }, - MORE_THAN() { + MORE_THAN() { @Override public boolean check(final float pFloatA, final float pFloatB) { return pFloatA > pFloatB; } }, - MORE_OR_EQUAL_THAN() { + MORE_OR_EQUAL_THAN() { @Override public boolean check(final float pFloatA, final float pFloatB) { return pFloatA >= pFloatB; diff --git a/src/org/andengine/util/adt/data/operator/IntOperator.java b/src/org/andengine/util/adt/data/operator/IntOperator.java index d37d3ec81..ca6e67ad0 100644 --- a/src/org/andengine/util/adt/data/operator/IntOperator.java +++ b/src/org/andengine/util/adt/data/operator/IntOperator.java @@ -1,7 +1,7 @@ package org.andengine.util.adt.data.operator; /** - * (c) Zynga 2011 + * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 17:21:27 - 10.10.2011 @@ -17,31 +17,31 @@ public boolean check(final int pIntA, final int pIntB) { return pIntA == pIntB; } }, - NOT_EQUALS() { + NOT_EQUALS() { @Override public boolean check(final int pIntA, final int pIntB) { return pIntA != pIntB; } }, - LESS_THAN() { + LESS_THAN() { @Override public boolean check(final int pIntA, final int pIntB) { return pIntA < pIntB; } }, - LESS_OR_EQUAL_THAN() { + LESS_OR_EQUAL_THAN() { @Override public boolean check(final int pIntA, final int pIntB) { return pIntA <= pIntB; } }, - MORE_THAN() { + MORE_THAN() { @Override public boolean check(final int pIntA, final int pIntB) { return pIntA > pIntB; } }, - MORE_OR_EQUAL_THAN() { + MORE_OR_EQUAL_THAN() { @Override public boolean check(final int pIntA, final int pIntB) { return pIntA >= pIntB; diff --git a/src/org/andengine/util/adt/data/operator/LongOperator.java b/src/org/andengine/util/adt/data/operator/LongOperator.java index d85ec127d..97cfc1844 100644 --- a/src/org/andengine/util/adt/data/operator/LongOperator.java +++ b/src/org/andengine/util/adt/data/operator/LongOperator.java @@ -1,7 +1,7 @@ package org.andengine.util.adt.data.operator; /** - * (c) Zynga 2012 + * (c) 2012 Zynga Inc. * * @author Nicolas Gramlich * @since 14:24:15 - 02.02.2012 @@ -17,31 +17,31 @@ public boolean check(final long pLongA, final long pLongB) { return pLongA == pLongB; } }, - NOT_EQUALS() { + NOT_EQUALS() { @Override public boolean check(final long pLongA, final long pLongB) { return pLongA != pLongB; } }, - LESS_THAN() { + LESS_THAN() { @Override public boolean check(final long pLongA, final long pLongB) { return pLongA < pLongB; } }, - LESS_OR_EQUAL_THAN() { + LESS_OR_EQUAL_THAN() { @Override public boolean check(final long pLongA, final long pLongB) { return pLongA <= pLongB; } }, - MORE_THAN() { + MORE_THAN() { @Override public boolean check(final long pLongA, final long pLongB) { return pLongA > pLongB; } }, - MORE_OR_EQUAL_THAN() { + MORE_OR_EQUAL_THAN() { @Override public boolean check(final long pLongA, final long pLongB) { return pLongA >= pLongB; diff --git a/src/org/andengine/util/adt/data/operator/ShortOperator.java b/src/org/andengine/util/adt/data/operator/ShortOperator.java index 401a2036a..29c73e5b8 100644 --- a/src/org/andengine/util/adt/data/operator/ShortOperator.java +++ b/src/org/andengine/util/adt/data/operator/ShortOperator.java @@ -1,7 +1,7 @@ package org.andengine.util.adt.data.operator; /** - * (c) Zynga 2012 + * (c) 2012 Zynga Inc. * * @author Nicolas Gramlich * @since 14:24:15 - 02.02.2012 @@ -17,31 +17,31 @@ public boolean check(final short pShortA, final short pShortB) { return pShortA == pShortB; } }, - NOT_EQUALS() { + NOT_EQUALS() { @Override public boolean check(final short pShortA, final short pShortB) { return pShortA != pShortB; } }, - LESS_THAN() { + LESS_THAN() { @Override public boolean check(final short pShortA, final short pShortB) { return pShortA < pShortB; } }, - LESS_OR_EQUAL_THAN() { + LESS_OR_EQUAL_THAN() { @Override public boolean check(final short pShortA, final short pShortB) { return pShortA <= pShortB; } }, - MORE_THAN() { + MORE_THAN() { @Override public boolean check(final short pShortA, final short pShortB) { return pShortA > pShortB; } }, - MORE_OR_EQUAL_THAN() { + MORE_OR_EQUAL_THAN() { @Override public boolean check(final short pShortA, final short pShortB) { return pShortA >= pShortB; diff --git a/src/org/andengine/util/adt/data/operator/StringOperator.java b/src/org/andengine/util/adt/data/operator/StringOperator.java index f618d937b..745f995bd 100644 --- a/src/org/andengine/util/adt/data/operator/StringOperator.java +++ b/src/org/andengine/util/adt/data/operator/StringOperator.java @@ -1,7 +1,7 @@ package org.andengine.util.adt.data.operator; /** - * (c) Zynga 2011 + * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 16:57:05 - 10.10.2011 @@ -23,13 +23,13 @@ public boolean check(final String pStringA, final String pStringB) { return pStringA.equalsIgnoreCase(pStringB); } }, - NOT_EQUALS() { + NOT_EQUALS() { @Override public boolean check(final String pStringA, final String pStringB) { return !pStringA.equals(pStringB); } }, - NOT_EQUALS_IGNORE_CASE() { + NOT_EQUALS_IGNORE_CASE() { @Override public boolean check(final String pStringA, final String pStringB) { return !pStringA.equalsIgnoreCase(pStringB); diff --git a/src/org/andengine/util/adt/dictionary/Dictionary.java b/src/org/andengine/util/adt/dictionary/Dictionary.java new file mode 100644 index 000000000..c088b4169 --- /dev/null +++ b/src/org/andengine/util/adt/dictionary/Dictionary.java @@ -0,0 +1,487 @@ +package org.andengine.util.adt.dictionary; + +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.Reader; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Comparator; + +import org.andengine.util.FileUtils; +import org.andengine.util.StreamUtils; +import org.andengine.util.adt.bit.BitVector; +import org.andengine.util.adt.bit.ByteBackedBitVector; +import org.andengine.util.adt.bit.IBitVector; +import org.andengine.util.adt.bit.LongBackedBitVector; +import org.andengine.util.adt.data.DataUtils; + + +/** + * @author Nicolas Gramlich + * @since Nov 20, 2012 + */ +public class Dictionary { + // =========================================================== + // Constants + // =========================================================== + + private static final short VERSION = 1; + + private static final Comparator CASEINSENSITIVE_REVERSE_LEXICOGRAPHICAL_COMPARATOR = new Comparator() { + @Override + public int compare(final String pStringA, final String pStringB) { + return -(pStringA.compareTo(pStringB)); + } + }; + + private static final int OFFSET_VERSION = 0; + private static final int SIZE_VERSION = Short.SIZE; + + private static final int OFFSET_CHARACTER_COUNT = Dictionary.OFFSET_VERSION + Dictionary.SIZE_VERSION; + private static final int SIZE_CHARACTER_COUNT = Integer.SIZE; + + private static final int OFFSET_CHARACTER_BITLENGTH = Dictionary.OFFSET_CHARACTER_COUNT + Dictionary.SIZE_CHARACTER_COUNT; + private static final int SIZE_CHARACTER_BITLENGTH = Byte.SIZE; + + private static final int OFFSET_INDEXENTRY_COUNT = Dictionary.OFFSET_CHARACTER_BITLENGTH + Dictionary.SIZE_CHARACTER_BITLENGTH; + private static final int SIZE_INDEXENTRY_COUNT = Integer.SIZE; + + private static final int OFFSET_INDEXENTRY_STARTINDEX_BITLENGTH = Dictionary.OFFSET_INDEXENTRY_COUNT + Dictionary.SIZE_INDEXENTRY_COUNT; + private static final int SIZE_INDEXENTRY_STARTINDEX_BITLENGTH = Byte.SIZE; + + private static final int OFFSET_INDEXENTRY_LENGTH_BITLENGTH = Dictionary.OFFSET_INDEXENTRY_STARTINDEX_BITLENGTH + Dictionary.SIZE_INDEXENTRY_STARTINDEX_BITLENGTH; + private static final int SIZE_INDEXENTRY_LENGTH_BITLENGTH = Byte.SIZE; + + private static final int OFFSET_CHARACTERS = Dictionary.OFFSET_INDEXENTRY_LENGTH_BITLENGTH + Dictionary.SIZE_INDEXENTRY_LENGTH_BITLENGTH; + + // =========================================================== + // Fields + // =========================================================== + + private final short mVersion; + private final IBitVector mBitVector; + + private final int mCharacterCount; + private final int mCharacterBitLength; + private final char[] mCharacterTable; + + private final int mEntryCount; + private final int mEntryStartIndexBitLength; + private final int mEntryLengthBitLength; + + private final int mEntriesOffset; + private final int mCharacterSequenceOffset; + + // =========================================================== + // Constructors + // =========================================================== + + public Dictionary(final byte[] pBytes) { + this(new LongBackedBitVector(pBytes)); + } + + public Dictionary(final IBitVector pBitVector) { + this.mBitVector = pBitVector; + + this.mVersion = this.mBitVector.getShort(Dictionary.OFFSET_VERSION); + if (this.mVersion != Dictionary.VERSION) { + throw new IllegalArgumentException("Illegal version: " + this.mVersion); + } + + this.mCharacterCount = this.mBitVector.getInt(Dictionary.OFFSET_CHARACTER_COUNT); + this.mCharacterBitLength = this.mBitVector.getByte(Dictionary.OFFSET_CHARACTER_BITLENGTH); + this.mCharacterTable = new char[this.mCharacterCount]; + for (int i = 0; i < this.mCharacterCount; i++) { + this.mCharacterTable[i] = (char) this.mBitVector.getShort(Dictionary.OFFSET_CHARACTERS + (i * Character.SIZE)); + } + + this.mEntryCount = this.mBitVector.getInt(Dictionary.OFFSET_INDEXENTRY_COUNT); + this.mEntryStartIndexBitLength = this.mBitVector.getByte(Dictionary.OFFSET_INDEXENTRY_STARTINDEX_BITLENGTH); + this.mEntryLengthBitLength = this.mBitVector.getByte(Dictionary.OFFSET_INDEXENTRY_LENGTH_BITLENGTH); + + this.mEntriesOffset = Dictionary.OFFSET_CHARACTERS + (this.mCharacterCount * Character.SIZE); + this.mCharacterSequenceOffset = this.mEntriesOffset + (this.mEntryCount * (this.mEntryStartIndexBitLength + this.mEntryLengthBitLength)); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + public int getVersion() { + return this.mVersion; + } + + public int getEntryCount() { + return this.mEntryCount; + } + + public String getEntry(final int pIndex) { + if ((pIndex < 0) || (pIndex > this.mEntryCount)) { + throw new IllegalArgumentException("pIndex out of bounds: " + pIndex); + } + + final int offsetInEntries = pIndex * (this.mEntryStartIndexBitLength + this.mEntryLengthBitLength); + final int entryOffset = this.mEntriesOffset + offsetInEntries; + + final int startIndex = this.mBitVector.getBits(entryOffset, this.mEntryStartIndexBitLength); + final int length = this.mBitVector.getBits(entryOffset + this.mEntryStartIndexBitLength, this.mEntryLengthBitLength); + + final char[] chars = new char[length]; // TODO Try to avoid allocation + + for (int i = 0; i < length; i++) { + final int characterOffset = this.mCharacterSequenceOffset + ((i + startIndex) * this.mCharacterBitLength); + + final int characterBits = this.mBitVector.getBits(characterOffset, this.mCharacterBitLength); + final char character = this.mCharacterTable[characterBits]; + + chars[i] = character; + } + + return new String(chars); + } + + public String[] getEntries() { + final String[] entries = new String[this.mEntryCount]; + + for (int i = 0; i < this.mEntryCount; i++) { + entries[i] = this.getEntry(i); + } + + return entries; + } + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + public void save(final OutputStream pOutputStream) throws IOException { + this.mBitVector.save(new DataOutputStream(pOutputStream)); + } + + public static Dictionary load(final InputStream pInputStream) throws IOException { + return new Dictionary(ByteBackedBitVector.load(new DataInputStream(pInputStream))); + } + + public boolean contains(final String pString) { + if (pString == null) { + throw new IllegalArgumentException("pCharSequence must not be null"); + } + + if (pString.length() < 0) { + throw new IllegalArgumentException("pCharSequence must not be empty"); + } + + int lowerBound = 0; + int higherBound = this.mEntryCount - 1; + + /* Binary search. */ + while (lowerBound <= higherBound) { + final int mid = ((lowerBound + higherBound) >>> 1); + + // TODO Optimization: don't decode the whole String, but compare char by char? + final String midEntry = this.getEntry(mid); + final int compared = midEntry.compareTo(pString); + + if (compared > 0) { + lowerBound = mid + 1; + } else if (compared < 0) { + higherBound = mid - 1; + } else { + return true; + } + } + + return false; + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== + + public static class Factory { + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + // =========================================================== + // Constructors + // =========================================================== + + public static Dictionary create(final File pFile) throws IOException { + return Dictionary.Factory.create(FileUtils.readLines(pFile)); + } + + public static Dictionary create(final InputStream pInputStream) throws IOException { + return Dictionary.Factory.create(StreamUtils.readLines(pInputStream)); + } + + public static Dictionary create(final Reader pReader) throws IOException { + return Dictionary.Factory.create(StreamUtils.readLines(pReader)); + } + + public static Dictionary create(final String ... pStrings) { + Arrays.sort(pStrings, Dictionary.CASEINSENSITIVE_REVERSE_LEXICOGRAPHICAL_COMPARATOR); + + final Dictionary.Factory.Entries entryDictionary = Dictionary.Factory.createDictionary(pStrings); + + final String string = entryDictionary.mString; + + final int characterCountTotal = string.length(); + final int characterCount = entryDictionary.mCharacters.length; + final int characterBitLength = DataUtils.getBitLength(entryDictionary.mCharacters.length); + final int entryCount = entryDictionary.mEntries.size(); + final int entryStartIndexBitLength = DataUtils.getBitLength(entryDictionary.mEntryStartIndexMaximum); + final int entryLengthBitLength = DataUtils.getBitLength(entryDictionary.mEntryLengthMaximum); + + final int bitsRequired = Dictionary.Factory.calculateBitsRequired(characterCountTotal, characterCount, characterBitLength, entryCount, entryStartIndexBitLength, entryLengthBitLength); + + final IBitVector bitVector = new ByteBackedBitVector(bitsRequired); + + /* Write meta data. */ + bitVector.setShort(Dictionary.OFFSET_VERSION, Dictionary.VERSION); + bitVector.setInt(Dictionary.OFFSET_CHARACTER_COUNT, characterCount); + bitVector.setByte(Dictionary.OFFSET_CHARACTER_BITLENGTH, (byte) characterBitLength); + bitVector.setInt(Dictionary.OFFSET_INDEXENTRY_COUNT, entryCount); + bitVector.setByte(Dictionary.OFFSET_INDEXENTRY_STARTINDEX_BITLENGTH, (byte) entryStartIndexBitLength); + bitVector.setByte(Dictionary.OFFSET_INDEXENTRY_LENGTH_BITLENGTH, (byte) entryLengthBitLength); + + /* Character table. */ + for (int i = 0; i < characterCount; i++) { + final char character = entryDictionary.mCharacters[i]; + final short characterBits = (short) character; + bitVector.setShort(Dictionary.OFFSET_CHARACTERS + (i * Character.SIZE), characterBits); + } + + /* Index entries. */ + final int offsetEntries = Dictionary.OFFSET_CHARACTERS + (characterCount * Character.SIZE); + for (int i = 0; i < entryCount; i++) { + final Entry entry = entryDictionary.mEntries.get(i); + + final int entryStartIndexBits = entry.mStartIndex; // TODO Fix bug when this goes over 2048? Maybe it's masking in the decoder? + final int entryLengthBits = entry.mLength; + + final int offsetInEntries = i * (entryStartIndexBitLength + entryLengthBitLength); + final int offsetEntryStartIndex = offsetEntries + offsetInEntries; + final int offsetEntryLength = offsetEntryStartIndex + entryStartIndexBitLength; + + bitVector.setBits(offsetEntryStartIndex, entryStartIndexBits, Integer.SIZE - entryStartIndexBitLength, entryStartIndexBitLength); + bitVector.setBits(offsetEntryLength, entryLengthBits, Integer.SIZE - entryLengthBitLength, entryLengthBitLength); + } + + final int offsetCharacterString = offsetEntries + (entryCount * (entryStartIndexBitLength + entryLengthBitLength)); + + /* Character string. */ + for (int i = 0; i < characterCountTotal; i++) { + final int offsetInCharacterString = i * characterBitLength; + final int offsetCharacter = offsetCharacterString + offsetInCharacterString; + + final char character = string.charAt(i); + final int characterBits = Arrays.binarySearch(entryDictionary.mCharacters, character); // TODO Use short? + + bitVector.setBits(offsetCharacter, characterBits, Integer.SIZE - characterBitLength, characterBitLength); + } + + return new Dictionary(bitVector); + } + + private static int calculateBitsRequired(final int pCharacterCountTotal, final int pCharacterCount, final int pCharacterBitLength, final int pEntryCount, final int pEntryStartIndexBitLength, final int pEntryLengthBitLength) { + return Dictionary.SIZE_VERSION + + Dictionary.SIZE_CHARACTER_COUNT + + Dictionary.SIZE_CHARACTER_BITLENGTH + + Dictionary.SIZE_INDEXENTRY_COUNT + + Dictionary.SIZE_INDEXENTRY_STARTINDEX_BITLENGTH + + Dictionary.SIZE_INDEXENTRY_LENGTH_BITLENGTH + + (pCharacterCount * Character.SIZE) + + (pEntryCount * (pEntryStartIndexBitLength + pEntryLengthBitLength)) + + (pCharacterBitLength * pCharacterCountTotal); + } + + private static Entries createDictionary(final String ... pStrings) { + final ArrayList entries = new ArrayList(); + final StringBuilder stringBuilder = new StringBuilder(); + + for (final String string : pStrings) { + final int existingStringStartIndex = stringBuilder.indexOf(string); + + final int stringBuilderLength = stringBuilder.length(); + final int stringLength = string.length(); + if (existingStringStartIndex >= 0) { + /* Reference string. */ + final int startIndex = existingStringStartIndex; + entries.add(new Entry(startIndex, stringLength)); + } else { + /* Check if the stringbuilder ends with any prefix of the string. */ + final int prefixLength = Dictionary.Factory.getPrefixLength(stringBuilder, string); + if (prefixLength == -1) { + /* Append new string. */ + final int startIndex = stringBuilderLength; + entries.add(new Entry(startIndex, stringLength)); + stringBuilder.append(string); + } else { + /* Append remainder of string after prefix. */ + final int startIndex = stringBuilderLength - prefixLength; + entries.add(new Entry(startIndex, stringLength)); + stringBuilder.append(string.substring(prefixLength)); + } + } + } + + return new Dictionary.Factory.Entries(entries, stringBuilder.toString()); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + private static int getPrefixLength(final StringBuilder pStringBuilder, final String pString) { + final int stringBuilderLength = pStringBuilder.length(); + + for (int prefixLength = pString.length() - 1; prefixLength > 0; prefixLength--) { + final String prefix = pString.substring(0, prefixLength); + final int prefixLastIndexStart = pStringBuilder.indexOf(prefix, stringBuilderLength - prefixLength); + if (prefixLastIndexStart >= 0) { + return prefixLength; + } + } + + return -1; + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== + + public static class Entries { + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + private final ArrayList mEntries; + private final String mString; + + private final int mEntryStartIndexMaximum; + private final int mEntryLengthMaximum; + private final char[] mCharacters; + + // =========================================================== + // Constructors + // =========================================================== + + public Entries(final ArrayList pEntries, final String pString) { + this.mEntries = pEntries; + this.mString = pString; + + int entryStartIndexMaximum = 0; + int entryLengthMaximum = 0; + for (final Entry entry : pEntries) { + entryStartIndexMaximum = Math.max(entryStartIndexMaximum, entry.mStartIndex); + entryLengthMaximum = Math.max(entryLengthMaximum, entry.mLength); + } + + this.mEntryStartIndexMaximum = entryStartIndexMaximum; + this.mEntryLengthMaximum = entryLengthMaximum; + + /* Determine all characters used. */ + final IBitVector characterBitVector = new ByteBackedBitVector(Character.MAX_VALUE); + + final int stringLength = pString.length(); + for (int i = 0; i < stringLength; i++) { + characterBitVector.setBit(pString.charAt(i)); + } + + int characterCount = 0; + for (int i = 0; i < Character.MAX_VALUE; i++) { + if (characterBitVector.getBit(i) == BitVector.TRUE) { + characterCount++; + } + } + this.mCharacters = new char[characterCount]; + + characterCount = 0; + for (int i = 0; i < Character.MAX_VALUE; i++) { + if (characterBitVector.getBit(i) == BitVector.TRUE) { + this.mCharacters[characterCount++] = (char) i; + } + } + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== + } + + public static class Entry { + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + private final int mStartIndex; + private final int mLength; + + // =========================================================== + // Constructors + // =========================================================== + + public Entry(final int pStartIndex, final int pLength) { + this.mStartIndex = pStartIndex; + this.mLength = pLength; + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== + } + } +} diff --git a/src/org/andengine/util/adt/io/in/AssetInputStreamOpener.java b/src/org/andengine/util/adt/io/in/AssetInputStreamOpener.java index e33b7388c..acef4a24e 100644 --- a/src/org/andengine/util/adt/io/in/AssetInputStreamOpener.java +++ b/src/org/andengine/util/adt/io/in/AssetInputStreamOpener.java @@ -6,7 +6,7 @@ import android.content.res.AssetManager; /** - * (c) Zynga 2012 + * (c) 2012 Zynga Inc. * * @author Nicolas Gramlich * @since 12:05:38 - 02.03.2012 diff --git a/src/org/andengine/util/adt/io/in/ByteArrayInputStreamOpener.java b/src/org/andengine/util/adt/io/in/ByteArrayInputStreamOpener.java index 460eb8763..bc88e9bd7 100644 --- a/src/org/andengine/util/adt/io/in/ByteArrayInputStreamOpener.java +++ b/src/org/andengine/util/adt/io/in/ByteArrayInputStreamOpener.java @@ -5,7 +5,7 @@ import java.io.InputStream; /** - * (c) Zynga 2012 + * (c) 2012 Zynga Inc. * * @author Nicolas Gramlich * @since 15:51:10 - 16.03.2012 diff --git a/src/org/andengine/util/adt/io/in/IInputStreamOpener.java b/src/org/andengine/util/adt/io/in/IInputStreamOpener.java index ade6215ac..aa79879ef 100644 --- a/src/org/andengine/util/adt/io/in/IInputStreamOpener.java +++ b/src/org/andengine/util/adt/io/in/IInputStreamOpener.java @@ -4,7 +4,7 @@ import java.io.InputStream; /** - * (c) Zynga 2012 + * (c) 2012 Zynga Inc. * * @author Nicolas Gramlich * @since 11:54:25 - 02.03.2012 @@ -20,4 +20,3 @@ public interface IInputStreamOpener { public InputStream open() throws IOException; } - diff --git a/src/org/andengine/util/adt/io/in/ResourceInputStreamOpener.java b/src/org/andengine/util/adt/io/in/ResourceInputStreamOpener.java index a9ac64b71..a8973f1ae 100644 --- a/src/org/andengine/util/adt/io/in/ResourceInputStreamOpener.java +++ b/src/org/andengine/util/adt/io/in/ResourceInputStreamOpener.java @@ -6,7 +6,7 @@ import android.content.res.Resources; /** - * (c) Zynga 2012 + * (c) 2012 Zynga Inc. * * @author Nicolas Gramlich * @since 12:07:14 - 02.03.2012 diff --git a/src/org/andengine/util/adt/io/out/ByteBufferOutputStream.java b/src/org/andengine/util/adt/io/out/ByteBufferOutputStream.java index 713f8a386..af3c93333 100644 --- a/src/org/andengine/util/adt/io/out/ByteBufferOutputStream.java +++ b/src/org/andengine/util/adt/io/out/ByteBufferOutputStream.java @@ -7,7 +7,7 @@ /** * TODO Instead of having mMaximumGrow there could be some kind of AllocationStrategy object. * - * (c) Zynga 2011 + * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 02:19:02 - 14.08.2011 @@ -67,7 +67,7 @@ public void close() throws IOException { // =========================================================== private void ensureCapacity(final int pDesiredCapacity) { - if(pDesiredCapacity - this.mData.length > 0) { + if (pDesiredCapacity - this.mData.length > 0) { this.grow(pDesiredCapacity); } } @@ -77,11 +77,11 @@ private void grow(final int pDesiredCapacity) { final int grow = Math.min(this.mMaximumGrow, oldCapacity); int newCapacity = oldCapacity + grow; - if(newCapacity - pDesiredCapacity < 0) { + if (newCapacity - pDesiredCapacity < 0) { newCapacity = pDesiredCapacity; } - if(newCapacity < 0) { - if(pDesiredCapacity < 0) { + if (newCapacity < 0) { + if (pDesiredCapacity < 0) { throw new OutOfMemoryError(); } else { newCapacity = Integer.MAX_VALUE; diff --git a/src/org/andengine/util/adt/list/BooleanArrayList.java b/src/org/andengine/util/adt/list/BooleanArrayList.java new file mode 100644 index 000000000..f3e877737 --- /dev/null +++ b/src/org/andengine/util/adt/list/BooleanArrayList.java @@ -0,0 +1,122 @@ +package org.andengine.util.adt.list; + +/** + * TODO This class could take some kind of AllocationStrategy object. + * + * (c) 2013 Zynga Inc. + * + * @author Nicolas Gramlich + * @since 13:10:25 - 19.01.2013 + */ +public class BooleanArrayList implements IBooleanList { + // =========================================================== + // Constants + // =========================================================== + + private static final int CAPACITY_INITIAL_DEFAULT = 0; + + // =========================================================== + // Fields + // =========================================================== + + private boolean[] mItems; + private int mSize; + + // =========================================================== + // Constructors + // =========================================================== + + public BooleanArrayList() { + this(BooleanArrayList.CAPACITY_INITIAL_DEFAULT); + } + + public BooleanArrayList(final int pInitialCapacity) { + this.mItems = new boolean[pInitialCapacity]; + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + public boolean isEmpty() { + return this.mSize == 0; + } + + @Override + public boolean get(final int pIndex) throws ArrayIndexOutOfBoundsException { + return this.mItems[pIndex]; + } + + @Override + public void add(final boolean pItem) { + this.ensureCapacity(this.mSize + 1); + + this.mItems[this.mSize] = pItem; + this.mSize++; + } + + @Override + public void add(final int pIndex, final boolean pItem) throws ArrayIndexOutOfBoundsException { + this.ensureCapacity(this.mSize + 1); + + System.arraycopy(this.mItems, pIndex, this.mItems, pIndex + 1, this.mSize - pIndex); + + this.mItems[pIndex] = pItem; + this.mSize++; + } + + @Override + public boolean remove(final int pIndex) throws ArrayIndexOutOfBoundsException { + final boolean oldValue = this.mItems[pIndex]; + + final int numMoved = this.mSize - pIndex - 1; + if (numMoved > 0) { + System.arraycopy(this.mItems, pIndex + 1, this.mItems, pIndex, numMoved); + } + + this.mSize--; + + return oldValue; + } + + @Override + public int size() { + return this.mSize; + } + + @Override + public void clear() { + this.mSize = 0; + } + + @Override + public int[] toArray() { + final int[] array = new int[this.mSize]; + System.arraycopy(this.mItems, 0, array, 0, this.mSize); + return array; + } + + // =========================================================== + // Methods + // =========================================================== + + private void ensureCapacity(final int pCapacity) { + final int currentCapacity = this.mItems.length; + if (currentCapacity < pCapacity) { + /* Increase array size. */ + final int newCapacity = ((currentCapacity * 3) >> 1) + 1; + final boolean[] newItems = new boolean[newCapacity]; + System.arraycopy(this.mItems, 0, newItems, 0, currentCapacity); + this.mItems = newItems; + } + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== +} diff --git a/src/org/andengine/util/adt/list/ByteArrayList.java b/src/org/andengine/util/adt/list/ByteArrayList.java new file mode 100644 index 000000000..5cf6f4052 --- /dev/null +++ b/src/org/andengine/util/adt/list/ByteArrayList.java @@ -0,0 +1,122 @@ +package org.andengine.util.adt.list; + +/** + * TODO This class could take some kind of AllocationStrategy object. + * + * (c) 2013 Zynga Inc. + * + * @author Nicolas Gramlich + * @since 13:17:43 - 19.01.2013 + */ +public class ByteArrayList implements IByteList { + // =========================================================== + // Constants + // =========================================================== + + private static final int CAPACITY_INITIAL_DEFAULT = 0; + + // =========================================================== + // Fields + // =========================================================== + + private byte[] mItems; + private int mSize; + + // =========================================================== + // Constructors + // =========================================================== + + public ByteArrayList() { + this(ByteArrayList.CAPACITY_INITIAL_DEFAULT); + } + + public ByteArrayList(final int pInitialCapacity) { + this.mItems = new byte[pInitialCapacity]; + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + public boolean isEmpty() { + return this.mSize == 0; + } + + @Override + public byte get(final int pIndex) throws ArrayIndexOutOfBoundsException { + return this.mItems[pIndex]; + } + + @Override + public void add(final byte pItem) { + this.ensureCapacity(this.mSize + 1); + + this.mItems[this.mSize] = pItem; + this.mSize++; + } + + @Override + public void add(final int pIndex, final byte pItem) throws ArrayIndexOutOfBoundsException { + this.ensureCapacity(this.mSize + 1); + + System.arraycopy(this.mItems, pIndex, this.mItems, pIndex + 1, this.mSize - pIndex); + + this.mItems[pIndex] = pItem; + this.mSize++; + } + + @Override + public byte remove(final int pIndex) throws ArrayIndexOutOfBoundsException { + final byte oldValue = this.mItems[pIndex]; + + final int numMoved = this.mSize - pIndex - 1; + if (numMoved > 0) { + System.arraycopy(this.mItems, pIndex + 1, this.mItems, pIndex, numMoved); + } + + this.mSize--; + + return oldValue; + } + + @Override + public int size() { + return this.mSize; + } + + @Override + public void clear() { + this.mSize = 0; + } + + @Override + public byte[] toArray() { + final byte[] array = new byte[this.mSize]; + System.arraycopy(this.mItems, 0, array, 0, this.mSize); + return array; + } + + // =========================================================== + // Methods + // =========================================================== + + private void ensureCapacity(final int pCapacity) { + final int currentCapacity = this.mItems.length; + if (currentCapacity < pCapacity) { + /* Increase array size. */ + final int newCapacity = ((currentCapacity * 3) >> 1) + 1; + final byte[] newItems = new byte[newCapacity]; + System.arraycopy(this.mItems, 0, newItems, 0, currentCapacity); + this.mItems = newItems; + } + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== +} diff --git a/src/org/andengine/util/adt/list/CharArrayList.java b/src/org/andengine/util/adt/list/CharArrayList.java new file mode 100644 index 000000000..1feebe02d --- /dev/null +++ b/src/org/andengine/util/adt/list/CharArrayList.java @@ -0,0 +1,122 @@ +package org.andengine.util.adt.list; + +/** + * TODO This class could take some kind of AllocationStrategy object. + * + * (c) 2013 Zynga Inc. + * + * @author Nicolas Gramlich + * @since 13:13:55 - 19.01.2013 + */ +public class CharArrayList implements ICharList { + // =========================================================== + // Constants + // =========================================================== + + private static final int CAPACITY_INITIAL_DEFAULT = 0; + + // =========================================================== + // Fields + // =========================================================== + + private char[] mItems; + private int mSize; + + // =========================================================== + // Constructors + // =========================================================== + + public CharArrayList() { + this(CharArrayList.CAPACITY_INITIAL_DEFAULT); + } + + public CharArrayList(final int pInitialCapacity) { + this.mItems = new char[pInitialCapacity]; + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + public boolean isEmpty() { + return this.mSize == 0; + } + + @Override + public char get(final int pIndex) throws ArrayIndexOutOfBoundsException { + return this.mItems[pIndex]; + } + + @Override + public void add(final char pItem) { + this.ensureCapacity(this.mSize + 1); + + this.mItems[this.mSize] = pItem; + this.mSize++; + } + + @Override + public void add(final int pIndex, final char pItem) throws ArrayIndexOutOfBoundsException { + this.ensureCapacity(this.mSize + 1); + + System.arraycopy(this.mItems, pIndex, this.mItems, pIndex + 1, this.mSize - pIndex); + + this.mItems[pIndex] = pItem; + this.mSize++; + } + + @Override + public char remove(final int pIndex) throws ArrayIndexOutOfBoundsException { + final char oldValue = this.mItems[pIndex]; + + final int numMoved = this.mSize - pIndex - 1; + if (numMoved > 0) { + System.arraycopy(this.mItems, pIndex + 1, this.mItems, pIndex, numMoved); + } + + this.mSize--; + + return oldValue; + } + + @Override + public int size() { + return this.mSize; + } + + @Override + public void clear() { + this.mSize = 0; + } + + @Override + public char[] toArray() { + final char[] array = new char[this.mSize]; + System.arraycopy(this.mItems, 0, array, 0, this.mSize); + return array; + } + + // =========================================================== + // Methods + // =========================================================== + + private void ensureCapacity(final int pCapacity) { + final int currentCapacity = this.mItems.length; + if (currentCapacity < pCapacity) { + /* Increase array size. */ + final int newCapacity = ((currentCapacity * 3) >> 1) + 1; + final char[] newItems = new char[newCapacity]; + System.arraycopy(this.mItems, 0, newItems, 0, currentCapacity); + this.mItems = newItems; + } + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== +} diff --git a/src/org/andengine/util/adt/list/CircularList.java b/src/org/andengine/util/adt/list/CircularList.java index 0cfeb6392..60435245d 100644 --- a/src/org/andengine/util/adt/list/CircularList.java +++ b/src/org/andengine/util/adt/list/CircularList.java @@ -9,7 +9,7 @@ * Its {@link java.util.Queue} like behavior performs better than a plain {@link java.util.ArrayList}, since it automatically shift the contents of its internal Array only when really necessary. * Besides sparse allocations to increase the size of the internal Array, {@link CircularList} is allocation free (unlike the {@link java.util.LinkedList} family). * - * (c) Zynga 2012 + * (c) 2012 Zynga Inc. * * @author Greg Haynes * @author Nicolas Gramlich @@ -77,15 +77,15 @@ public void set(final int pIndex, final T pItem) throws IndexOutOfBoundsExceptio @Override public int indexOf(final T pItem) { final int size = this.size(); - if(pItem == null) { - for(int i = 0; i < size; i++) { - if(this.get(i) == null) { + if (pItem == null) { + for (int i = 0; i < size; i++) { + if (this.get(i) == null) { return i; } } } else { - for(int i = 0; i < size; i++) { - if(pItem.equals(this.get(i))) { + for (int i = 0; i < size; i++) { + if (pItem.equals(this.get(i))) { return i; } } @@ -100,37 +100,37 @@ public void add(final int pIndex, final T pItem) { this.ensureCapacity(); final int internalTail = this.encodeToInternalIndex(this.mSize); - if(internalIndex == internalTail) { + if (internalIndex == internalTail) { // nothing to shift, tail is free - } else if(internalIndex == this.mHead) { + } else if (internalIndex == this.mHead) { this.mHead--; - if(this.mHead == -1) { + if (this.mHead == -1) { this.mHead = this.mItems.length - 1; } internalIndex--; - if(internalIndex == -1) { + if (internalIndex == -1) { internalIndex = this.mItems.length - 1; } - } else if((internalIndex < this.mHead) || (this.mHead == 0)) { + } else if ((internalIndex < this.mHead) || (this.mHead == 0)) { System.arraycopy(this.mItems, internalIndex, this.mItems, internalIndex + 1, internalTail - internalIndex); - } else if(internalIndex > internalTail) { + } else if (internalIndex > internalTail) { System.arraycopy(this.mItems, this.mHead, this.mItems, this.mHead - 1, pIndex); this.mHead--; - if(this.mHead == -1) { + if (this.mHead == -1) { this.mHead = this.mItems.length - 1; } internalIndex--; - if(internalIndex == -1) { + if (internalIndex == -1) { internalIndex = this.mItems.length - 1; } - } else if(pIndex < (this.mSize >> 1)) { + } else if (pIndex < (this.mSize >> 1)) { System.arraycopy(this.mItems, this.mHead, this.mItems, this.mHead - 1, pIndex); this.mHead--; - if(this.mHead == -1) { + if (this.mHead == -1) { this.mHead = this.mItems.length - 1; } internalIndex--; - if(internalIndex == -1) { + if (internalIndex == -1) { internalIndex = this.mItems.length - 1; } } else { @@ -144,7 +144,7 @@ public void add(final int pIndex, final T pItem) { public T removeFirst() { return this.remove(0); } - + @Override public T removeLast() { return this.remove(this.size() - 1); @@ -153,7 +153,7 @@ public T removeLast() { @Override public boolean remove(final T pItem) { final int index = this.indexOf(pItem); - if(index >= 0) { + if (index >= 0) { this.remove(index); return true; } else { @@ -169,29 +169,29 @@ public T remove(final int pIndex) { final int internalTail = this.encodeToInternalIndex(this.mSize - 1); - if(internalIndex == internalTail) { + if (internalIndex == internalTail) { this.mItems[internalTail] = null; - } else if(internalIndex == this.mHead) { + } else if (internalIndex == this.mHead) { this.mItems[this.mHead] = null; this.mHead++; - if(this.mHead == this.mItems.length) { + if (this.mHead == this.mItems.length) { this.mHead = 0; } - } else if(internalIndex < this.mHead) { + } else if (internalIndex < this.mHead) { System.arraycopy(this.mItems, internalIndex + 1, this.mItems, internalIndex, internalTail - internalIndex); this.mItems[internalTail] = null; - } else if(internalIndex > internalTail) { + } else if (internalIndex > internalTail) { System.arraycopy(this.mItems, this.mHead, this.mItems, this.mHead + 1, pIndex); this.mItems[this.mHead] = null; this.mHead++; - if(this.mHead == this.mItems.length) { + if (this.mHead == this.mItems.length) { this.mHead = 0; } - } else if(pIndex < (this.mSize >> 1)) { + } else if (pIndex < (this.mSize >> 1)) { System.arraycopy(this.mItems, this.mHead, this.mItems, this.mHead + 1, pIndex); this.mItems[this.mHead] = null; this.mHead++; - if(this.mHead == this.mItems.length) { + if (this.mHead == this.mItems.length) { this.mHead = 0; } } else { @@ -213,7 +213,7 @@ public void clear() { final int tail = this.mHead + this.mSize; final int capacity = this.mItems.length; /* Check if items can be blacked out in one or two calls. */ - if(tail <= capacity) { + if (tail <= capacity) { Arrays.fill(this.mItems, this.mHead, tail, null); } else { final int headToCapacity = capacity - this.mHead; @@ -226,13 +226,18 @@ public void clear() { this.mSize = 0; } + @Override + public String toString() { + return ListUtils.toString(this); + } + // =========================================================== // Methods // =========================================================== private void ensureCapacity() { final int currentCapacity = this.mItems.length; - if(this.mSize == currentCapacity) { + if (this.mSize == currentCapacity) { final int newCapacity = ((currentCapacity * 3) >> 1) + 1; final Object newItems[] = new Object[newCapacity]; @@ -246,7 +251,7 @@ private void ensureCapacity() { private int encodeToInternalIndex(final int pIndex) { int internalIndex = this.mHead + pIndex; - if(internalIndex >= this.mItems.length) { + if (internalIndex >= this.mItems.length) { internalIndex -= this.mItems.length; } return internalIndex; diff --git a/src/org/andengine/util/adt/list/DoubleArrayList.java b/src/org/andengine/util/adt/list/DoubleArrayList.java new file mode 100644 index 000000000..e53c85cf3 --- /dev/null +++ b/src/org/andengine/util/adt/list/DoubleArrayList.java @@ -0,0 +1,122 @@ +package org.andengine.util.adt.list; + +/** + * TODO This class could take some kind of AllocationStrategy object. + * + * (c) 2013 Zynga Inc. + * + * @author Nicolas Gramlich + * @since 13:18:43 - 19.01.2013 + */ +public class DoubleArrayList implements IDoubleList { + // =========================================================== + // Constants + // =========================================================== + + private static final int CAPACITY_INITIAL_DEFAULT = 0; + + // =========================================================== + // Fields + // =========================================================== + + private double[] mItems; + private int mSize; + + // =========================================================== + // Constructors + // =========================================================== + + public DoubleArrayList() { + this(DoubleArrayList.CAPACITY_INITIAL_DEFAULT); + } + + public DoubleArrayList(final int pInitialCapacity) { + this.mItems = new double[pInitialCapacity]; + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + public boolean isEmpty() { + return this.mSize == 0; + } + + @Override + public double get(final int pIndex) throws ArrayIndexOutOfBoundsException { + return this.mItems[pIndex]; + } + + @Override + public void add(final double pItem) { + this.ensureCapacity(this.mSize + 1); + + this.mItems[this.mSize] = pItem; + this.mSize++; + } + + @Override + public void add(final int pIndex, final double pItem) throws ArrayIndexOutOfBoundsException { + this.ensureCapacity(this.mSize + 1); + + System.arraycopy(this.mItems, pIndex, this.mItems, pIndex + 1, this.mSize - pIndex); + + this.mItems[pIndex] = pItem; + this.mSize++; + } + + @Override + public double remove(final int pIndex) throws ArrayIndexOutOfBoundsException { + final double oldValue = this.mItems[pIndex]; + + final int numMoved = this.mSize - pIndex - 1; + if (numMoved > 0) { + System.arraycopy(this.mItems, pIndex + 1, this.mItems, pIndex, numMoved); + } + + this.mSize--; + + return oldValue; + } + + @Override + public int size() { + return this.mSize; + } + + @Override + public void clear() { + this.mSize = 0; + } + + @Override + public double[] toArray() { + final double[] array = new double[this.mSize]; + System.arraycopy(this.mItems, 0, array, 0, this.mSize); + return array; + } + + // =========================================================== + // Methods + // =========================================================== + + private void ensureCapacity(final int pCapacity) { + final int currentCapacity = this.mItems.length; + if (currentCapacity < pCapacity) { + /* Increase array size. */ + final int newCapacity = ((currentCapacity * 3) >> 1) + 1; + final double[] newItems = new double[newCapacity]; + System.arraycopy(this.mItems, 0, newItems, 0, currentCapacity); + this.mItems = newItems; + } + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== +} diff --git a/src/org/andengine/util/adt/list/FloatArrayList.java b/src/org/andengine/util/adt/list/FloatArrayList.java index 694eabf42..ad4588dd6 100644 --- a/src/org/andengine/util/adt/list/FloatArrayList.java +++ b/src/org/andengine/util/adt/list/FloatArrayList.java @@ -3,7 +3,7 @@ /** * TODO This class could take some kind of AllocationStrategy object. * - * (c) Zynga 2012 + * (c) 2012 Zynga Inc. * * @author Nicolas Gramlich * @since 18:07:43 - 26.01.2012 @@ -75,7 +75,7 @@ public float remove(final int pIndex) throws ArrayIndexOutOfBoundsException { final float oldValue = this.mItems[pIndex]; final int numMoved = this.mSize - pIndex - 1; - if(numMoved > 0) { + if (numMoved > 0) { System.arraycopy(this.mItems, pIndex + 1, this.mItems, pIndex, numMoved); } @@ -98,7 +98,7 @@ public void clear() { public float[] toArray() { final float[] array = new float[this.mSize]; System.arraycopy(this.mItems, 0, array, 0, this.mSize); - return array ; + return array; } // =========================================================== @@ -107,10 +107,10 @@ public float[] toArray() { private void ensureCapacity(final int pCapacity) { final int currentCapacity = this.mItems.length; - if(currentCapacity < pCapacity) { + if (currentCapacity < pCapacity) { /* Increase array size. */ final int newCapacity = ((currentCapacity * 3) >> 1) + 1; - final float newItems[] = new float[newCapacity]; + final float[] newItems = new float[newCapacity]; System.arraycopy(this.mItems, 0, newItems, 0, currentCapacity); this.mItems = newItems; } diff --git a/src/org/andengine/util/adt/list/IBooleanList.java b/src/org/andengine/util/adt/list/IBooleanList.java new file mode 100644 index 000000000..74cf488d7 --- /dev/null +++ b/src/org/andengine/util/adt/list/IBooleanList.java @@ -0,0 +1,26 @@ +package org.andengine.util.adt.list; + +/** + * (c) 2013 Zynga Inc. + * + * @author Nicolas Gramlich + * @since 13:05:14 - 19.01.2013 + */ +public interface IBooleanList { + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + public boolean isEmpty(); + public boolean get(final int pIndex) throws ArrayIndexOutOfBoundsException; + public void add(final boolean pItem); + public void add(final int pIndex, final boolean pItem) throws ArrayIndexOutOfBoundsException; + public boolean remove(final int pIndex) throws ArrayIndexOutOfBoundsException; + public int size(); + public void clear(); + public int[] toArray(); +} \ No newline at end of file diff --git a/src/org/andengine/util/adt/list/IByteList.java b/src/org/andengine/util/adt/list/IByteList.java new file mode 100644 index 000000000..d1b4e0074 --- /dev/null +++ b/src/org/andengine/util/adt/list/IByteList.java @@ -0,0 +1,26 @@ +package org.andengine.util.adt.list; + +/** + * (c) 2013 Zynga Inc. + * + * @author Nicolas Gramlich + * @since 13:18:45 - 19.01.2013 + */ +public interface IByteList { + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + public boolean isEmpty(); + public byte get(final int pIndex) throws ArrayIndexOutOfBoundsException; + public void add(final byte pItem); + public void add(final int pIndex, final byte pItem) throws ArrayIndexOutOfBoundsException; + public byte remove(final int pIndex) throws ArrayIndexOutOfBoundsException; + public int size(); + public void clear(); + public byte[] toArray(); +} \ No newline at end of file diff --git a/src/org/andengine/util/adt/list/ICharList.java b/src/org/andengine/util/adt/list/ICharList.java new file mode 100644 index 000000000..495db2eec --- /dev/null +++ b/src/org/andengine/util/adt/list/ICharList.java @@ -0,0 +1,26 @@ +package org.andengine.util.adt.list; + +/** + * (c) 2013 Zynga Inc. + * + * @author Nicolas Gramlich + * @since 13:13:13 - 10.01.2013 + */ +public interface ICharList { + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + public boolean isEmpty(); + public char get(final int pIndex) throws ArrayIndexOutOfBoundsException; + public void add(final char pItem); + public void add(final int pIndex, final char pItem) throws ArrayIndexOutOfBoundsException; + public char remove(final int pIndex) throws ArrayIndexOutOfBoundsException; + public int size(); + public void clear(); + public char[] toArray(); +} \ No newline at end of file diff --git a/src/org/andengine/util/adt/list/IDoubleList.java b/src/org/andengine/util/adt/list/IDoubleList.java new file mode 100644 index 000000000..40e85d05a --- /dev/null +++ b/src/org/andengine/util/adt/list/IDoubleList.java @@ -0,0 +1,26 @@ +package org.andengine.util.adt.list; + +/** + * (c) 2013 Zynga Inc. + * + * @author Nicolas Gramlich + * @since 13:18:46 - 19.01.2013 + */ +public interface IDoubleList { + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + public boolean isEmpty(); + public double get(final int pIndex) throws ArrayIndexOutOfBoundsException; + public void add(final double pItem); + public void add(final int pIndex, final double pItem) throws ArrayIndexOutOfBoundsException; + public double remove(final int pIndex) throws ArrayIndexOutOfBoundsException; + public int size(); + public void clear(); + public double[] toArray(); +} \ No newline at end of file diff --git a/src/org/andengine/util/adt/list/IFloatList.java b/src/org/andengine/util/adt/list/IFloatList.java index 1a9785bcc..5df4ca2e6 100644 --- a/src/org/andengine/util/adt/list/IFloatList.java +++ b/src/org/andengine/util/adt/list/IFloatList.java @@ -1,7 +1,7 @@ package org.andengine.util.adt.list; /** - * (c) Zynga 2012 + * (c) 2012 Zynga Inc. * * @author Nicolas Gramlich * @since 11:14:45 - 27.01.2012 diff --git a/src/org/andengine/util/adt/list/IIntList.java b/src/org/andengine/util/adt/list/IIntList.java index 264fb9938..a405f8e6a 100644 --- a/src/org/andengine/util/adt/list/IIntList.java +++ b/src/org/andengine/util/adt/list/IIntList.java @@ -1,7 +1,7 @@ package org.andengine.util.adt.list; /** - * (c) Zynga 2012 + * (c) 2012 Zynga Inc. * * @author Nicolas Gramlich * @since 19:21:53 - 03.05.2012 @@ -16,10 +16,10 @@ public interface IIntList { // =========================================================== public boolean isEmpty(); - public float get(final int pIndex) throws ArrayIndexOutOfBoundsException; + public int get(final int pIndex) throws ArrayIndexOutOfBoundsException; public void add(final int pItem); public void add(final int pIndex, final int pItem) throws ArrayIndexOutOfBoundsException; - public float remove(final int pIndex) throws ArrayIndexOutOfBoundsException; + public int remove(final int pIndex) throws ArrayIndexOutOfBoundsException; public int size(); public void clear(); public int[] toArray(); diff --git a/src/org/andengine/util/adt/list/IList.java b/src/org/andengine/util/adt/list/IList.java index 8749557b7..43c511e1c 100644 --- a/src/org/andengine/util/adt/list/IList.java +++ b/src/org/andengine/util/adt/list/IList.java @@ -1,7 +1,7 @@ package org.andengine.util.adt.list; /** - * (c) Zynga 2012 + * (c) 2012 Zynga Inc. * * @author Nicolas Gramlich * @since 15:27:16 - 01.02.2012 diff --git a/src/org/andengine/util/adt/list/ILongList.java b/src/org/andengine/util/adt/list/ILongList.java index 8bff7abf1..17eb608fd 100644 --- a/src/org/andengine/util/adt/list/ILongList.java +++ b/src/org/andengine/util/adt/list/ILongList.java @@ -1,7 +1,7 @@ package org.andengine.util.adt.list; /** - * (c) Zynga 2012 + * (c) 2012 Zynga Inc. * * @author Nicolas Gramlich * @since 19:36:57 - 03.05.2012 @@ -16,10 +16,10 @@ public interface ILongList { // =========================================================== public boolean isEmpty(); - public float get(final int pIndex) throws ArrayIndexOutOfBoundsException; + public long get(final int pIndex) throws ArrayIndexOutOfBoundsException; public void add(final long pItem); public void add(final int pIndex, final long pItem) throws ArrayIndexOutOfBoundsException; - public float remove(final int pIndex) throws ArrayIndexOutOfBoundsException; + public long remove(final int pIndex) throws ArrayIndexOutOfBoundsException; public int size(); public void clear(); public long[] toArray(); diff --git a/src/org/andengine/util/adt/list/ISortedList.java b/src/org/andengine/util/adt/list/ISortedList.java index f8c846449..c4d48b0e9 100644 --- a/src/org/andengine/util/adt/list/ISortedList.java +++ b/src/org/andengine/util/adt/list/ISortedList.java @@ -2,7 +2,7 @@ /** - * (c) Zynga 2012 + * (c) 2012 Zynga Inc. * * @author Nicolas Gramlich * @since 15:37:19 - 01.02.2012 diff --git a/src/org/andengine/util/adt/list/IUniqueList.java b/src/org/andengine/util/adt/list/IUniqueList.java index 5afcd59f2..a194a4b16 100644 --- a/src/org/andengine/util/adt/list/IUniqueList.java +++ b/src/org/andengine/util/adt/list/IUniqueList.java @@ -2,7 +2,7 @@ /** - * (c) Zynga 2012 + * (c) 2012 Zynga Inc. * * @author Nicolas Gramlich * @since 15:37:19 - 01.02.2012 diff --git a/src/org/andengine/util/adt/list/IntArrayList.java b/src/org/andengine/util/adt/list/IntArrayList.java index 4e85f1a7d..232491d43 100644 --- a/src/org/andengine/util/adt/list/IntArrayList.java +++ b/src/org/andengine/util/adt/list/IntArrayList.java @@ -3,7 +3,7 @@ /** * TODO This class could take some kind of AllocationStrategy object. * - * (c) Zynga 2012 + * (c) 2012 Zynga Inc. * * @author Nicolas Gramlich * @since 19:22:29 - 03.05.2012 @@ -48,7 +48,7 @@ public boolean isEmpty() { } @Override - public float get(final int pIndex) throws ArrayIndexOutOfBoundsException { + public int get(final int pIndex) throws ArrayIndexOutOfBoundsException { return this.mItems[pIndex]; } @@ -71,11 +71,11 @@ public void add(final int pIndex, final int pItem) throws ArrayIndexOutOfBoundsE } @Override - public float remove(final int pIndex) throws ArrayIndexOutOfBoundsException { - final float oldValue = this.mItems[pIndex]; + public int remove(final int pIndex) throws ArrayIndexOutOfBoundsException { + final int oldValue = this.mItems[pIndex]; final int numMoved = this.mSize - pIndex - 1; - if(numMoved > 0) { + if (numMoved > 0) { System.arraycopy(this.mItems, pIndex + 1, this.mItems, pIndex, numMoved); } @@ -98,7 +98,7 @@ public void clear() { public int[] toArray() { final int[] array = new int[this.mSize]; System.arraycopy(this.mItems, 0, array, 0, this.mSize); - return array ; + return array; } // =========================================================== @@ -107,10 +107,10 @@ public int[] toArray() { private void ensureCapacity(final int pCapacity) { final int currentCapacity = this.mItems.length; - if(currentCapacity < pCapacity) { + if (currentCapacity < pCapacity) { /* Increase array size. */ final int newCapacity = ((currentCapacity * 3) >> 1) + 1; - final int newItems[] = new int[newCapacity]; + final int[] newItems = new int[newCapacity]; System.arraycopy(this.mItems, 0, newItems, 0, currentCapacity); this.mItems = newItems; } diff --git a/src/org/andengine/util/adt/list/ListUtils.java b/src/org/andengine/util/adt/list/ListUtils.java index 0d7134d73..7c1ec9fbd 100644 --- a/src/org/andengine/util/adt/list/ListUtils.java +++ b/src/org/andengine/util/adt/list/ListUtils.java @@ -3,6 +3,7 @@ import java.util.ArrayList; import java.util.List; +import org.andengine.util.IMatcher; import org.andengine.util.adt.queue.IQueue; import org.andengine.util.adt.queue.concurrent.SynchronizedQueue; import org.andengine.util.math.MathUtils; @@ -10,7 +11,7 @@ /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 12:43:39 - 11.03.2010 */ @@ -27,6 +28,10 @@ public final class ListUtils { // Constructors // =========================================================== + private ListUtils() { + + } + // =========================================================== // Getter & Setter // =========================================================== @@ -56,12 +61,24 @@ public static final ArrayList toList(final T pItem) { public static final ArrayList toList(final T ... pItems) { final ArrayList out = new ArrayList(); final int itemCount = pItems.length; - for(int i = 0; i < itemCount; i++) { + for (int i = 0; i < itemCount; i++) { out.add(pItems[i]); } return out; } + public static final ArrayList filter(final List pItems, final IMatcher pMatcher) { + final ArrayList out = new ArrayList(); + final int itemCount = pItems.size(); + for (int i = 0; i < itemCount; i++) { + final T item = pItems.get(i); + if (pMatcher.matches(item)) { + out.add(item); + } + } + return out; + } + public static void swap(final List pItems, final int pIndexA, final int pIndexB) { final T tmp = pItems.get(pIndexA); pItems.set(pIndexA, pItems.get(pIndexB)); @@ -78,6 +95,30 @@ public static final int encodeInsertionIndex(final int pIndex) { return (-pIndex) - 1; } + public static String toString(final IList pItems) { + final int size = pItems.size(); + if (size == 0) { + return "[]"; + } else { + final StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.append('['); + for (int i = 0; i < size; i++) { + final T item = pItems.get(i); + + stringBuilder.append(item.toString()); + + if (i < size - 1) { + stringBuilder.append(", "); + } else { + break; + } + } + stringBuilder.append(']'); + + return stringBuilder.toString(); + } + } + // =========================================================== // Inner and Anonymous Classes // =========================================================== diff --git a/src/org/andengine/util/adt/list/LongArrayList.java b/src/org/andengine/util/adt/list/LongArrayList.java index 0871e5405..95df007fa 100644 --- a/src/org/andengine/util/adt/list/LongArrayList.java +++ b/src/org/andengine/util/adt/list/LongArrayList.java @@ -3,7 +3,7 @@ /** * TODO This class could take some kind of AllocationStrategy object. * - * (c) Zynga 2012 + * (c) 2012 Zynga Inc. * * @author Nicolas Gramlich * @since 19:35:59 - 03.05.2012 @@ -48,7 +48,7 @@ public boolean isEmpty() { } @Override - public float get(final int pIndex) throws ArrayIndexOutOfBoundsException { + public long get(final int pIndex) throws ArrayIndexOutOfBoundsException { return this.mItems[pIndex]; } @@ -71,11 +71,11 @@ public void add(final int pIndex, final long pItem) throws ArrayIndexOutOfBounds } @Override - public float remove(final int pIndex) throws ArrayIndexOutOfBoundsException { - final float oldValue = this.mItems[pIndex]; + public long remove(final int pIndex) throws ArrayIndexOutOfBoundsException { + final long oldValue = this.mItems[pIndex]; final int numMoved = this.mSize - pIndex - 1; - if(numMoved > 0) { + if (numMoved > 0) { System.arraycopy(this.mItems, pIndex + 1, this.mItems, pIndex, numMoved); } @@ -98,7 +98,7 @@ public void clear() { public long[] toArray() { final long[] array = new long[this.mSize]; System.arraycopy(this.mItems, 0, array, 0, this.mSize); - return array ; + return array; } // =========================================================== @@ -107,10 +107,10 @@ public long[] toArray() { private void ensureCapacity(final int pCapacity) { final int currentCapacity = this.mItems.length; - if(currentCapacity < pCapacity) { + if (currentCapacity < pCapacity) { /* Increase array size. */ final int newCapacity = ((currentCapacity * 3) >> 1) + 1; - final long newItems[] = new long[newCapacity]; + final long[] newItems = new long[newCapacity]; System.arraycopy(this.mItems, 0, newItems, 0, currentCapacity); this.mItems = newItems; } diff --git a/src/org/andengine/util/adt/list/ShiftList.java b/src/org/andengine/util/adt/list/ShiftList.java index 0420f185a..e2af85c0d 100644 --- a/src/org/andengine/util/adt/list/ShiftList.java +++ b/src/org/andengine/util/adt/list/ShiftList.java @@ -10,10 +10,10 @@ * This implementation is particular useful/efficient for enter/poll operations. * Its {@link java.util.Queue} like behavior performs better than a plain {@link java.util.ArrayList}, since it automatically shift the contents of its internal Array only when really necessary. * Besides sparse allocations to increase the size of the internal Array, {@link ShiftList} is allocation free (unlike the {@link java.util.LinkedList} family). - * + * * Supports null items. * - * (c) Zynga 2012 + * (c) 2012 Zynga Inc. * * @author Nicolas Gramlich * @author Greg Haynes @@ -73,15 +73,15 @@ public void set(final int pIndex, final T pItem) throws IndexOutOfBoundsExceptio @Override public int indexOf(final T pItem) { - if(pItem == null) { - for(int i = this.mHead; i < this.mTail; i++) { - if(this.mItems[i] == null) { + if (pItem == null) { + for (int i = this.mHead; i < this.mTail; i++) { + if (this.mItems[i] == null) { return i - this.mHead; } } } else { - for(int i = this.mHead; i < this.mTail; i++) { - if(pItem.equals(this.mItems[i])) { + for (int i = this.mHead; i < this.mTail; i++) { + if (pItem.equals(this.mItems[i])) { return i - this.mHead; } } @@ -92,7 +92,7 @@ public int indexOf(final T pItem) { @SuppressWarnings("unchecked") @Override public T peek() { - if(this.mHead == this.mTail) { + if (this.mHead == this.mTail) { return null; } else { return (T) this.mItems[this.mHead]; @@ -102,13 +102,13 @@ public T peek() { @SuppressWarnings("unchecked") @Override public T poll() { - if(this.mHead == this.mTail) { + if (this.mHead == this.mTail) { return null; } else { final T item = (T) this.mItems[this.mHead]; this.mItems[this.mHead] = null; this.mHead++; - if(this.mHead == this.mTail) { + if (this.mHead == this.mTail) { this.mHead = 0; this.mTail = 0; } @@ -127,7 +127,7 @@ public void enter(final T pItem) { public void enter(final int pIndex, final T pItem) throws ArrayIndexOutOfBoundsException { final int size = this.mTail - this.mHead; /* Check which side to shift to is more efficient. */ - if(pIndex < (size >> 1)) { + if (pIndex < (size >> 1)) { /* Shift left. */ this.enterShiftingLeft(pIndex, pItem); } else { @@ -136,12 +136,12 @@ public void enter(final int pIndex, final T pItem) throws ArrayIndexOutOfBoundsE } } - private void enterShiftingRight(final int pIndex, final T pItem, final int size) { + private void enterShiftingRight(final int pIndex, final T pItem, final int pSize) { this.ensureShiftableRight(); /* Check if items need to be copied. */ - final int shiftAmount = size - pIndex; - if(shiftAmount == 0) { + final int shiftAmount = pSize - pIndex; + if (shiftAmount == 0) { /* Nothing to shift, we can insert at the tail. */ this.mItems[this.mTail] = pItem; } else { @@ -160,7 +160,7 @@ private void enterShiftingLeft(final int pIndex, final T pItem) { this.mHead--; /* Check if items need to be copied. */ - if(pIndex == 0) { + if (pIndex == 0) { /* Nothing to shift, we can insert at the head. */ this.mItems[this.mHead] = pItem; } else { @@ -185,7 +185,7 @@ public void add(final int pIndex, final T pItem) throws ArrayIndexOutOfBoundsExc public T removeFirst() { return this.remove(0); } - + @Override public T removeLast() { return this.remove(this.size() - 1); @@ -194,7 +194,7 @@ public T removeLast() { @Override public boolean remove(final T pItem) { final int index = this.indexOf(pItem); - if(index >= 0) { + if (index >= 0) { this.remove(index); return true; } else { @@ -212,9 +212,9 @@ public T remove(final int pIndex) throws ArrayIndexOutOfBoundsException { /* Determine which side to shift to makes more sense. */ final int center = size >> 1; - if(pIndex < center) { + if (pIndex < center) { /* Shift right. */ - if(internalIndex > this.mHead) { + if (internalIndex > this.mHead) { System.arraycopy(this.mItems, this.mHead, this.mItems, this.mHead + 1, pIndex); } this.mItems[this.mHead] = null; @@ -222,7 +222,7 @@ public T remove(final int pIndex) throws ArrayIndexOutOfBoundsException { } else { /* Shift left. */ final int shiftAmount = size - pIndex - 1; - if(shiftAmount > 0) { + if (shiftAmount > 0) { System.arraycopy(this.mItems, internalIndex + 1, this.mItems, internalIndex, shiftAmount); } this.mTail--; @@ -244,13 +244,18 @@ public void clear() { this.mTail = 0; } + @Override + public String toString() { + return ListUtils.toString(this); + } + // =========================================================== // Methods // =========================================================== public void shift() { final int size = this.mTail - this.mHead; - if(size == 0) { + if (size == 0) { this.mHead = 0; this.mTail = 0; } else { @@ -260,7 +265,7 @@ public void shift() { /* Null out old item references, ensuring not to overwrite just copied ones. */ final int start = Math.max(size, this.mHead); final int end = Math.max(start, this.mTail); - if(start < end) { + if (start < end) { Arrays.fill(this.mItems, start, end, null); } @@ -272,11 +277,11 @@ public void shift() { private void ensureShiftableRight() { final int currentCapacity = this.mItems.length; /* Check if tail reached the end. */ - if(this.mTail == currentCapacity) { + if (this.mTail == currentCapacity) { final int size = this.mTail - this.mHead; /* Check if space problem can be solved by shifting. */ - if(size != currentCapacity) { + if (size != currentCapacity) { this.shift(); } else { /* Increase array capacity. */ @@ -290,13 +295,13 @@ private void ensureShiftableRight() { private void ensureShiftableLeft() { /* Check if there is room at the head. */ - if(this.mHead == 0) { + if (this.mHead == 0) { final int size = this.mTail - this.mHead; final int currentCapacity = this.mItems.length; /* Check if space problem can be solved by shifting. */ - if(size < currentCapacity) { - if(size == 0) { + if (size < currentCapacity) { + if (size == 0) { this.mHead = 1; this.mTail = 1; } else { diff --git a/src/org/andengine/util/adt/list/SmartList.java b/src/org/andengine/util/adt/list/SmartList.java index 47f8b644e..57a5d98f3 100644 --- a/src/org/andengine/util/adt/list/SmartList.java +++ b/src/org/andengine/util/adt/list/SmartList.java @@ -9,7 +9,7 @@ /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 22:20:08 - 27.12.2010 */ @@ -62,9 +62,9 @@ public T getLast() throws IndexOutOfBoundsException { public T get(final IMatcher pMatcher) { final int size = this.size(); - for(int i = 0; i < size; i++) { + for (int i = 0; i < size; i++) { final T item = this.get(i); - if(pMatcher.matches(item)) { + if (pMatcher.matches(item)) { return item; } } @@ -85,15 +85,15 @@ public T removeLast() throws IndexOutOfBoundsException { */ public boolean remove(final T pItem, final ParameterCallable pParameterCallable) { final boolean removed = this.remove(pItem); - if(removed) { + if (removed) { pParameterCallable.call(pItem); } return removed; } public T remove(final IMatcher pMatcher) { - for(int i = 0; i < this.size(); i++) { - if(pMatcher.matches(this.get(i))) { + for (int i = 0; i < this.size(); i++) { + if (pMatcher.matches(this.get(i))) { return this.remove(i); } } @@ -101,8 +101,8 @@ public T remove(final IMatcher pMatcher) { } public T remove(final IMatcher pMatcher, final ParameterCallable pParameterCallable) { - for(int i = this.size() - 1; i >= 0; i--) { - if(pMatcher.matches(this.get(i))) { + for (int i = this.size() - 1; i >= 0; i--) { + if (pMatcher.matches(this.get(i))) { final T removed = this.remove(i); pParameterCallable.call(removed); return removed; @@ -113,8 +113,8 @@ public T remove(final IMatcher pMatcher, final ParameterCallable pParamete public boolean removeAll(final IMatcher pMatcher) { boolean result = false; - for(int i = this.size() - 1; i >= 0; i--) { - if(pMatcher.matches(this.get(i))) { + for (int i = this.size() - 1; i >= 0; i--) { + if (pMatcher.matches(this.get(i))) { this.remove(i); result = true; } @@ -128,8 +128,8 @@ public boolean removeAll(final IMatcher pMatcher) { */ public boolean removeAll(final IMatcher pMatcher, final ParameterCallable pParameterCallable) { boolean result = false; - for(int i = this.size() - 1; i >= 0; i--) { - if(pMatcher.matches(this.get(i))) { + for (int i = this.size() - 1; i >= 0; i--) { + if (pMatcher.matches(this.get(i))) { final T removed = this.remove(i); pParameterCallable.call(removed); result = true; @@ -139,7 +139,7 @@ public boolean removeAll(final IMatcher pMatcher, final ParameterCallable } public void clear(final ParameterCallable pParameterCallable) { - for(int i = this.size() - 1; i >= 0; i--) { + for (int i = this.size() - 1; i >= 0; i--) { final T removed = this.remove(i); pParameterCallable.call(removed); } @@ -147,9 +147,9 @@ public void clear(final ParameterCallable pParameterCallable) { public int indexOf(final IMatcher pMatcher) { final int size = this.size(); - for(int i = 0; i < size; i++) { + for (int i = 0; i < size; i++) { final T item = this.get(i); - if(pMatcher.matches(item)) { + if (pMatcher.matches(item)) { return i; } } @@ -157,9 +157,9 @@ public int indexOf(final IMatcher pMatcher) { } public int lastIndexOf(final IMatcher pMatcher) { - for(int i = this.size() - 1; i >= 0; i--) { + for (int i = this.size() - 1; i >= 0; i--) { final T item = this.get(i); - if(pMatcher.matches(item)) { + if (pMatcher.matches(item)) { return i; } } @@ -172,9 +172,9 @@ public ArrayList query(final IMatcher pMatcher) { public > L query(final IMatcher pMatcher, final L pResult) { final int size = this.size(); - for(int i = 0; i < size; i++) { + for (int i = 0; i < size; i++) { final T item = this.get(i); - if(pMatcher.matches(item)) { + if (pMatcher.matches(item)) { pResult.add(item); } } @@ -189,10 +189,10 @@ public ArrayList queryForSubclass(final IMatcher pMatcher) { @SuppressWarnings("unchecked") public , S extends T> L queryForSubclass(final IMatcher pMatcher, final L pResult) { final int size = this.size(); - for(int i = 0; i < size; i++) { + for (int i = 0; i < size; i++) { final T item = this.get(i); - if(pMatcher.matches(item)) { - pResult.add((S)item); + if (pMatcher.matches(item)) { + pResult.add((S) item); } } @@ -200,16 +200,16 @@ public , S extends T> L queryForSubclass(final IMatcher pMa } public void call(final ParameterCallable pParameterCallable) { - for(int i = this.size() - 1; i >= 0; i--) { + for (int i = this.size() - 1; i >= 0; i--) { final T item = this.get(i); pParameterCallable.call(item); } } public void call(final IMatcher pMatcher, final ParameterCallable pParameterCallable) { - for(int i = this.size() - 1; i >= 0; i--) { + for (int i = this.size() - 1; i >= 0; i--) { final T item = this.get(i); - if(pMatcher.matches(item)) { + if (pMatcher.matches(item)) { pParameterCallable.call(item); } } diff --git a/src/org/andengine/util/adt/list/SortedList.java b/src/org/andengine/util/adt/list/SortedList.java index 26d2ae740..51db59caa 100644 --- a/src/org/andengine/util/adt/list/SortedList.java +++ b/src/org/andengine/util/adt/list/SortedList.java @@ -5,9 +5,9 @@ /** * This implementation is particular useful/efficient for enter/poll operations of elements that need to be sorted by natural order instead of the order they are queue. * Its {@link java.util.List} like behavior performs better than a plain {@link java.util.ArrayList}, since it automatically shift the contents of its internal Array only when really necessary. - * Besides sparse allocations to increase the size of the internal Array, {@link com.zynga.mobileville.path.SortedList} is allocation free (unlike the {@link java.util.LinkedList} family). + * Besides sparse allocations to increase the size of the internal Array, {@link SortedList} is allocation free (unlike the {@link java.util.LinkedList} family). * - * (c) Zynga 2012 + * (c) 2012 Zynga Inc. * * @author Nicolas Gramlich * @author Greg Haynes @@ -72,7 +72,7 @@ public void add(final int pIndex, final T pItem) { @Override public void add(final T pItem) { final int index = this.binarySearch(pItem, true); - if(index < 0) { + if (index < 0) { this.mList.add(ListUtils.encodeInsertionIndex(index), pItem); } else { this.mList.add(index, pItem); @@ -91,12 +91,12 @@ public T removeLast() { @Override public boolean remove(final T pItem) { - if(pItem == null) { + if (pItem == null) { return this.mList.remove(pItem); } final int index = this.binarySearch(pItem, false); - if(index >= 0) { + if (index >= 0) { this.mList.remove(index); return true; } else { @@ -119,6 +119,11 @@ public void clear() { this.mList.clear(); } + @Override + public String toString() { + return ListUtils.toString(this); + } + // =========================================================== // Methods // =========================================================== @@ -126,7 +131,7 @@ public void clear() { private int binarySearch(final T pItem, final boolean pReturnSequenceEndIfNoEqualItemFound) { final int size = this.mList.size(); final int guess = this.binarySearch(0, size, pItem); - if(guess >= 0) { + if (guess >= 0) { return this.scanForEqualItem(0, size, guess, pItem, pReturnSequenceEndIfNoEqualItemFound); } else { return guess; @@ -137,14 +142,14 @@ private int binarySearch(final int pStart, final int pEnd, final T pItem) { int low = pStart; int high = pEnd - 1; - while(low <= high) { + while (low <= high) { final int mid = (low + high) >>> 1; final T midVal = this.mList.get(mid); final int diff = pItem.compareTo(midVal); - if(diff > 0) { + if (diff > 0) { low = mid + 1; - } else if(diff < 0) { + } else if (diff < 0) { high = mid - 1; } else { return mid; @@ -166,24 +171,24 @@ private int binarySearch(final int pStart, final int pEnd, final T pItem) { private int scanForEqualItem(final int pStart, final int pEnd, final int pGuess, final T pItem, final boolean pReturnSequenceEndIfNoEqualItemFound) { /* Quickly move to the beginning of the sequence. */ int i = pGuess - 1; - while((i >= pStart) && (pItem.compareTo(this.mList.get(i)) == 0)) { + while ((i >= pStart) && (pItem.compareTo(this.mList.get(i)) == 0)) { i--; } i++; /* From the beginning of the sequence, advance until the first item equals pItem or the end has been reached. */ - while(i < pEnd) { + while (i < pEnd) { final T item = this.mList.get(i); - if(i <= pGuess) { + if (i <= pGuess) { /* Since the compartTo check has already been performed, only equals needs to be checked. */ - if(pItem.equals(item)) { + if (pItem.equals(item)) { /* Item found. */ return i; } } else { /* Check if the sequence is still ongoing. */ - if(pItem.compareTo(item) == 0) { - if(pItem.equals(item)) { + if (pItem.compareTo(item) == 0) { + if (pItem.equals(item)) { /* Item found. */ return i; } @@ -195,7 +200,7 @@ private int scanForEqualItem(final int pStart, final int pEnd, final int pGuess, i++; } - if(pReturnSequenceEndIfNoEqualItemFound) { + if (pReturnSequenceEndIfNoEqualItemFound) { return i; } else { return SortedList.INDEX_INVALID; diff --git a/src/org/andengine/util/adt/list/UniqueList.java b/src/org/andengine/util/adt/list/UniqueList.java index 7249a4d05..ead379ee1 100644 --- a/src/org/andengine/util/adt/list/UniqueList.java +++ b/src/org/andengine/util/adt/list/UniqueList.java @@ -5,9 +5,9 @@ /** * This implementation is particular useful/efficient for enter/poll operations of elements that need to be sorted by natural order instead of the order they are queue. * Its {@link java.util.List} like behavior performs better than a plain {@link java.util.ArrayList}, since it automatically shift the contents of its internal Array only when really necessary. - * Besides sparse allocations to increase the size of the internal Array, {@link com.zynga.mobileville.path.SortedList} is allocation free (unlike the {@link java.util.LinkedList} family). + * Besides sparse allocations to increase the size of the internal Array, {@link SortedList} is allocation free (unlike the {@link java.util.LinkedList} family). * - * (c) Zynga 2012 + * (c) 2012 Zynga Inc. * * @author Nicolas Gramlich * @author Greg Haynes @@ -65,7 +65,7 @@ public int indexOf(final T pItem) { @Deprecated public void add(final int pIndex, final T pItem) { final int index = this.indexOf(pItem); - if(index < 0) { + if (index < 0) { this.mList.add(pItem); } } @@ -73,7 +73,7 @@ public void add(final int pIndex, final T pItem) { @Override public void add(final T pItem) { final int index = this.indexOf(pItem); - if(index < 0) { + if (index < 0) { this.mList.add(ListUtils.encodeInsertionIndex(index), pItem); } } @@ -108,6 +108,11 @@ public void clear() { this.mList.clear(); } + @Override + public String toString() { + return ListUtils.toString(this); + } + // =========================================================== // Methods // =========================================================== diff --git a/src/org/andengine/util/adt/list/concurrent/SynchronizedList.java b/src/org/andengine/util/adt/list/concurrent/SynchronizedList.java index b38576b54..932276708 100644 --- a/src/org/andengine/util/adt/list/concurrent/SynchronizedList.java +++ b/src/org/andengine/util/adt/list/concurrent/SynchronizedList.java @@ -1,9 +1,10 @@ package org.andengine.util.adt.list.concurrent; import org.andengine.util.adt.list.IList; +import org.andengine.util.adt.list.ListUtils; /** - * (c) Zynga 2012 + * (c) 2012 Zynga Inc. * * @author Nicolas Gramlich * @since 14:23:50 - 01.02.2012 @@ -23,8 +24,8 @@ public class SynchronizedList implements IList { // Constructors // =========================================================== - public SynchronizedList(final IList mList) { - this.mList = mList; + public SynchronizedList(final IList pList) { + this.mList = pList; } // =========================================================== @@ -95,6 +96,11 @@ public synchronized void clear() { this.mList.clear(); } + @Override + public synchronized String toString() { + return ListUtils.toString(this); + } + // =========================================================== // Methods // =========================================================== diff --git a/src/org/andengine/util/adt/map/IIntLookupMap.java b/src/org/andengine/util/adt/map/IIntLookupMap.java new file mode 100644 index 000000000..626488c36 --- /dev/null +++ b/src/org/andengine/util/adt/map/IIntLookupMap.java @@ -0,0 +1,21 @@ +package org.andengine.util.adt.map; + +/** + * (c) 2012 Zynga Inc. + * + * @author Nicolas Gramlich + * @since 15:31:34 - 26.04.2012 + */ +public interface IIntLookupMap { + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + public void add(final T pItem, final int pValue); + public T item(final int pValue); + public int value(final T pItem); +} diff --git a/src/org/andengine/util/adt/map/IntLookupMap.java b/src/org/andengine/util/adt/map/IntLookupMap.java new file mode 100644 index 000000000..fc1d841df --- /dev/null +++ b/src/org/andengine/util/adt/map/IntLookupMap.java @@ -0,0 +1,65 @@ +package org.andengine.util.adt.map; + +import java.util.HashMap; + +import android.util.SparseArray; + +/** + * (c) 2012 Zynga Inc. + * + * @author Nicolas Gramlich + * @since 15:30:35 - 26.04.2012 + */ +public class IntLookupMap implements IIntLookupMap { + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + private final HashMap mItemToValueMapping = new HashMap(); + private final SparseArray mValueToItemMapping = new SparseArray(); + + // =========================================================== + // Constructors + // =========================================================== + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + public void add(final T pName, final int pValue) { + this.mItemToValueMapping.put(pName, Integer.valueOf(pValue)); + this.mValueToItemMapping.put(pValue, pName); + } + + @Override + public T item(final int pValue) { + return this.mValueToItemMapping.get(pValue); + } + + @Override + public int value(final T pName) { + final Integer value = this.mItemToValueMapping.get(pName); + if (value == null) { + return -1; + } else { + return value.intValue(); + } + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== +} \ No newline at end of file diff --git a/src/org/andengine/util/adt/map/Library.java b/src/org/andengine/util/adt/map/Library.java index 970b7f9cb..986a28cf2 100644 --- a/src/org/andengine/util/adt/map/Library.java +++ b/src/org/andengine/util/adt/map/Library.java @@ -3,9 +3,9 @@ import android.util.SparseArray; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 11:51:29 - 20.08.2010 * @param @@ -37,12 +37,16 @@ public Library(final int pInitialCapacity) { // Getter & Setter // =========================================================== + public T get(final int pID) { + return this.mItems.get(pID); + } + public void put(final int pID, final T pItem) { - final T existingItem = this.mItems.get(pID); - if(existingItem == null) { + final T item = this.mItems.get(pID); + if (item == null) { this.mItems.put(pID, pItem); } else { - throw new IllegalArgumentException("ID: '" + pID + "' is already associated with item: '" + existingItem.toString() + "'."); + throw new IllegalArgumentException("ID: '" + pID + "' is already associated with item: '" + item.toString() + "'."); } } @@ -50,8 +54,8 @@ public void remove(final int pID) { this.mItems.remove(pID); } - public T get(final int pID) { - return this.mItems.get(pID); + public void clear() { + this.mItems.clear(); } // =========================================================== diff --git a/src/org/andengine/util/adt/map/LongSparseArray.java b/src/org/andengine/util/adt/map/LongSparseArray.java index ca54a8d32..2f13f61f0 100644 --- a/src/org/andengine/util/adt/map/LongSparseArray.java +++ b/src/org/andengine/util/adt/map/LongSparseArray.java @@ -50,7 +50,7 @@ public LongSparseArray(int initialCapacity) { mValues = new Object[initialCapacity]; mSize = 0; } - + /** * @return A copy of all keys contained in the sparse array. */ @@ -60,7 +60,7 @@ public long[] getKeys() { System.arraycopy(mKeys, 0, result, 0, length); return result; } - + /** * Sets all supplied keys to the given unique value. * @param keys Keys to set diff --git a/src/org/andengine/util/adt/map/MultiKey.java b/src/org/andengine/util/adt/map/MultiKey.java index 4e4a8717d..0cd7edd0a 100644 --- a/src/org/andengine/util/adt/map/MultiKey.java +++ b/src/org/andengine/util/adt/map/MultiKey.java @@ -3,9 +3,9 @@ import java.util.Arrays; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 16:54:24 - 07.11.2010 */ @@ -45,10 +45,10 @@ public K[] getKeys() { @Override public boolean equals(final Object pOther) { - if(pOther == this) { + if (pOther == this) { return true; } - if(pOther instanceof MultiKey) { + if (pOther instanceof MultiKey) { final MultiKey otherMultiKey = (MultiKey) pOther; return Arrays.equals(this.mKeys, otherMultiKey.mKeys); } @@ -57,8 +57,8 @@ public boolean equals(final Object pOther) { public static int hash(final Object ... pKeys) { int hashCode = 0; - for(final Object key : pKeys) { - if(key != null) { + for (final Object key : pKeys) { + if (key != null) { hashCode ^= key.hashCode(); } } diff --git a/src/org/andengine/util/adt/map/MultiKeyHashMap.java b/src/org/andengine/util/adt/map/MultiKeyHashMap.java index 06ad365ba..7a5bb517f 100644 --- a/src/org/andengine/util/adt/map/MultiKeyHashMap.java +++ b/src/org/andengine/util/adt/map/MultiKeyHashMap.java @@ -5,9 +5,9 @@ import java.util.Map; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 16:54:24 - 07.11.2010 */ @@ -34,7 +34,7 @@ public V get(final K ... pKeys) { final int hashCode = MultiKey.hash(pKeys); final Iterator, V>> it = this.entrySet().iterator(); - while(it.hasNext()) { + while (it.hasNext()) { final Map.Entry, V> entry = it.next(); final MultiKey entryKey = entry.getKey(); if (entryKey.hashCode() == hashCode && this.isEqualKey(entryKey.getKeys(), pKeys)) { @@ -59,12 +59,12 @@ private boolean isEqualKey(final K[] pKeysA, final K[] pKeysB) { for (int i = 0; i < pKeysA.length; i++) { final K keyA = pKeysA[i]; final K keyB = pKeysB[i]; - if(keyA == null) { - if(keyB != null) { + if (keyA == null) { + if (keyB != null) { return false; } } else { - if(!keyA.equals(keyB)) { + if (!keyA.equals(keyB)) { return false; } } diff --git a/src/org/andengine/util/adt/map/SparseArrayUtils.java b/src/org/andengine/util/adt/map/SparseArrayUtils.java index e6d80e20f..05afddfd8 100644 --- a/src/org/andengine/util/adt/map/SparseArrayUtils.java +++ b/src/org/andengine/util/adt/map/SparseArrayUtils.java @@ -1,11 +1,21 @@ package org.andengine.util.adt.map; +import java.util.ArrayList; + +import org.andengine.util.adt.list.BooleanArrayList; +import org.andengine.util.adt.list.ByteArrayList; +import org.andengine.util.adt.list.CharArrayList; +import org.andengine.util.adt.list.DoubleArrayList; +import org.andengine.util.adt.list.FloatArrayList; +import org.andengine.util.adt.list.IntArrayList; +import org.andengine.util.adt.list.LongArrayList; + import android.util.SparseArray; import android.util.SparseBooleanArray; import android.util.SparseIntArray; /** - * (c) Zynga 2012 + * (c) 2012 Zynga Inc. * * @author Nicolas Gramlich * @since 16:16:35 - 12.04.2012 @@ -35,18 +45,50 @@ public final class SparseArrayUtils { // Methods // =========================================================== - public static final String toString(final SparseArray pSparseArray) { + public static final String toString(final SparseBooleanArray pSparseBooleanArray) { final StringBuilder stringBuilder = new StringBuilder(); - final int size = pSparseArray.size(); - stringBuilder.append("{"); - for(int i = 0; i < size; i++) { - stringBuilder.append(pSparseArray.keyAt(i)).append("=").append(pSparseArray.valueAt(i)); - if(i < (size - 1)) { + final int size = pSparseBooleanArray.size(); + stringBuilder.append('{'); + for (int i = 0; i < size; i++) { + stringBuilder.append(pSparseBooleanArray.keyAt(i)).append('=').append(pSparseBooleanArray.valueAt(i)); + if (i < (size - 1)) { + stringBuilder.append(", "); + } + } + stringBuilder.append('}'); + + return stringBuilder.toString(); + } + + public static final String toString(final SparseByteArray pSparseByteArray) { + final StringBuilder stringBuilder = new StringBuilder(); + + final int size = pSparseByteArray.size(); + stringBuilder.append('{'); + for (int i = 0; i < size; i++) { + stringBuilder.append(pSparseByteArray.keyAt(i)).append('=').append(pSparseByteArray.valueAt(i)); + if (i < (size - 1)) { stringBuilder.append(", "); } } - stringBuilder.append("}"); + stringBuilder.append('}'); + + return stringBuilder.toString(); + } + + public static final String toString(final SparseCharArray pSparseCharArray) { + final StringBuilder stringBuilder = new StringBuilder(); + + final int size = pSparseCharArray.size(); + stringBuilder.append('{'); + for (int i = 0; i < size; i++) { + stringBuilder.append(pSparseCharArray.keyAt(i)).append('=').append(pSparseCharArray.valueAt(i)); + if (i < (size - 1)) { + stringBuilder.append(", "); + } + } + stringBuilder.append('}'); return stringBuilder.toString(); } @@ -55,30 +97,78 @@ public static final String toString(final SparseIntArray pSparseIntArray) { final StringBuilder stringBuilder = new StringBuilder(); final int size = pSparseIntArray.size(); - stringBuilder.append("{"); - for(int i = 0; i < size; i++) { - stringBuilder.append(pSparseIntArray.keyAt(i)).append("=").append(pSparseIntArray.valueAt(i)); - if(i < (size - 1)) { + stringBuilder.append('{'); + for (int i = 0; i < size; i++) { + stringBuilder.append(pSparseIntArray.keyAt(i)).append('=').append(pSparseIntArray.valueAt(i)); + if (i < (size - 1)) { stringBuilder.append(", "); } } - stringBuilder.append("}"); + stringBuilder.append('}'); return stringBuilder.toString(); } - public static final String toString(final SparseBooleanArray pSparseBooleanArray) { + public static final String toString(final SparseLongArray pSparseLongArray) { final StringBuilder stringBuilder = new StringBuilder(); - final int size = pSparseBooleanArray.size(); - stringBuilder.append("{"); - for(int i = 0; i < size; i++) { - stringBuilder.append(pSparseBooleanArray.keyAt(i)).append("=").append(pSparseBooleanArray.valueAt(i)); - if(i < (size - 1)) { + final int size = pSparseLongArray.size(); + stringBuilder.append('{'); + for (int i = 0; i < size; i++) { + stringBuilder.append(pSparseLongArray.keyAt(i)).append('=').append(pSparseLongArray.valueAt(i)); + if (i < (size - 1)) { stringBuilder.append(", "); } } - stringBuilder.append("}"); + stringBuilder.append('}'); + + return stringBuilder.toString(); + } + + public static final String toString(final SparseFloatArray pSparseFloatArray) { + final StringBuilder stringBuilder = new StringBuilder(); + + final int size = pSparseFloatArray.size(); + stringBuilder.append('{'); + for (int i = 0; i < size; i++) { + stringBuilder.append(pSparseFloatArray.keyAt(i)).append('=').append(pSparseFloatArray.valueAt(i)); + if (i < (size - 1)) { + stringBuilder.append(", "); + } + } + stringBuilder.append('}'); + + return stringBuilder.toString(); + } + + public static final String toString(final SparseDoubleArray pSparseDoubleArray) { + final StringBuilder stringBuilder = new StringBuilder(); + + final int size = pSparseDoubleArray.size(); + stringBuilder.append('{'); + for (int i = 0; i < size; i++) { + stringBuilder.append(pSparseDoubleArray.keyAt(i)).append('=').append(pSparseDoubleArray.valueAt(i)); + if (i < (size - 1)) { + stringBuilder.append(", "); + } + } + stringBuilder.append('}'); + + return stringBuilder.toString(); + } + + public static final String toString(final SparseArray pSparseArray) { + final StringBuilder stringBuilder = new StringBuilder(); + + final int size = pSparseArray.size(); + stringBuilder.append('{'); + for (int i = 0; i < size; i++) { + stringBuilder.append(pSparseArray.keyAt(i)).append('=').append(pSparseArray.valueAt(i)); + if (i < (size - 1)) { + stringBuilder.append(", "); + } + } + stringBuilder.append('}'); return stringBuilder.toString(); } @@ -87,18 +177,117 @@ public static final String toString(final LongSparseArray pLongSparseArray) { final StringBuilder stringBuilder = new StringBuilder(); final int size = pLongSparseArray.size(); - stringBuilder.append("{"); - for(int i = 0; i < size; i++) { - stringBuilder.append(pLongSparseArray.keyAt(i)).append("=").append(pLongSparseArray.valueAt(i)); - if(i < (size - 1)) { + stringBuilder.append('{'); + for (int i = 0; i < size; i++) { + stringBuilder.append(pLongSparseArray.keyAt(i)).append('=').append(pLongSparseArray.valueAt(i)); + if (i < (size - 1)) { stringBuilder.append(", "); } } - stringBuilder.append("}"); + stringBuilder.append('}'); return stringBuilder.toString(); } + public static final BooleanArrayList valuesToList(final SparseBooleanArray pSparseBooleanArray) { + final int size = pSparseBooleanArray.size(); + final BooleanArrayList result = new BooleanArrayList(size); + + for (int i = 0; i < size; i++) { + result.add(pSparseBooleanArray.valueAt(i)); + } + + return result; + } + + public static final ByteArrayList valuesToList(final SparseByteArray pSparseByteArray) { + final int size = pSparseByteArray.size(); + final ByteArrayList result = new ByteArrayList(size); + + for (int i = 0; i < size; i++) { + result.add(pSparseByteArray.valueAt(i)); + } + + return result; + } + + public static final CharArrayList valuesToList(final SparseCharArray pSparseCharArray) { + final int size = pSparseCharArray.size(); + final CharArrayList result = new CharArrayList(size); + + for (int i = 0; i < size; i++) { + result.add(pSparseCharArray.valueAt(i)); + } + + return result; + } + + public static final IntArrayList valuesToList(final SparseIntArray pSparseIntArray) { + final int size = pSparseIntArray.size(); + final IntArrayList result = new IntArrayList(size); + + for (int i = 0; i < size; i++) { + result.add(pSparseIntArray.valueAt(i)); + } + + return result; + } + + public static final LongArrayList valuesToList(final SparseLongArray pSparseLongArray) { + final int size = pSparseLongArray.size(); + final LongArrayList result = new LongArrayList(size); + + for (int i = 0; i < size; i++) { + result.add(pSparseLongArray.valueAt(i)); + } + + return result; + } + + public static final FloatArrayList valuesToList(final SparseFloatArray pSparseFloatArray) { + final int size = pSparseFloatArray.size(); + final FloatArrayList result = new FloatArrayList(size); + + for (int i = 0; i < size; i++) { + result.add(pSparseFloatArray.valueAt(i)); + } + + return result; + } + + public static final DoubleArrayList valuesToList(final SparseDoubleArray pSparseDoubleArray) { + final int size = pSparseDoubleArray.size(); + final DoubleArrayList result = new DoubleArrayList(size); + + for (int i = 0; i < size; i++) { + result.add(pSparseDoubleArray.valueAt(i)); + } + + return result; + } + + public static final ArrayList valuesToList(final SparseArray pSparseArray) { + final int size = pSparseArray.size(); + final ArrayList result = new ArrayList(size); + + for (int i = 0; i < size; i++) { + result.add(pSparseArray.valueAt(i)); + } + + return result; + } + + public static final ArrayList valuesToList(final LongSparseArray pSparseLongArray) { + final int size = pSparseLongArray.size(); + final ArrayList result = new ArrayList(size); + + for (int i = 0; i < size; i++) { + result.add(pSparseLongArray.valueAt(i)); + } + + return result; + } + // =========================================================== // Inner and Anonymous Classes // =========================================================== diff --git a/src/org/andengine/util/adt/map/SparseByteArray.java b/src/org/andengine/util/adt/map/SparseByteArray.java new file mode 100644 index 000000000..b78c4c430 --- /dev/null +++ b/src/org/andengine/util/adt/map/SparseByteArray.java @@ -0,0 +1,246 @@ +/* + * Copyright (C) 2006 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. + */ + +package org.andengine.util.adt.map; + +import org.andengine.util.adt.array.ArrayUtils; + +/** + * SparseByteArrays map integers to bytes. + * Unlike a normal array of bytes + * there can be gaps in the indices. It is intended to be more efficient + * than using a HashMap to map Integers to Booleans. + */ +public class SparseByteArray implements Cloneable { + /** + * Creates a new SparseByteArray containing no mappings. + */ + public SparseByteArray() { + this(10); + } + + /** + * Creates a new SparseByteArray containing no mappings that will not + * require any additional memory allocation to store the specified + * number of mappings. + */ + public SparseByteArray(int initialCapacity) { + initialCapacity = ArrayUtils.idealIntArraySize(initialCapacity); + + mKeys = new int[initialCapacity]; + mValues = new byte[initialCapacity]; + mSize = 0; + } + + @Override + public SparseByteArray clone() { + SparseByteArray clone = null; + try { + clone = (SparseByteArray) super.clone(); + clone.mKeys = mKeys.clone(); + clone.mValues = mValues.clone(); + } catch (CloneNotSupportedException cnse) { + /* ignore */ + } + return clone; + } + + /** + * Gets the byte mapped from the specified key, or 0 + * if no such mapping has been made. + */ + public byte get(int key) { + return get(key, (byte)0); + } + + /** + * Gets the byte mapped from the specified key, or the specified value + * if no such mapping has been made. + */ + public byte get(int key, byte valueIfKeyNotFound) { + int i = binarySearch(mKeys, 0, mSize, key); + + if (i < 0) { + return valueIfKeyNotFound; + } else { + return mValues[i]; + } + } + + /** + * Removes the mapping from the specified key, if there was any. + */ + public void delete(int key) { + int i = binarySearch(mKeys, 0, mSize, key); + + if (i >= 0) { + System.arraycopy(mKeys, i + 1, mKeys, i, mSize - (i + 1)); + System.arraycopy(mValues, i + 1, mValues, i, mSize - (i + 1)); + mSize--; + } + } + + /** + * Adds a mapping from the specified key to the specified value, + * replacing the previous mapping from the specified key if there + * was one. + */ + public void put(int key, byte value) { + int i = binarySearch(mKeys, 0, mSize, key); + + if (i >= 0) { + mValues[i] = value; + } else { + i = ~i; + + if (mSize >= mKeys.length) { + int n = ArrayUtils.idealIntArraySize(mSize + 1); + + int[] nkeys = new int[n]; + byte[] nvalues = new byte[n]; + + // Log.e("SparseByteArray", "grow " + mKeys.length + " to " + n); + System.arraycopy(mKeys, 0, nkeys, 0, mKeys.length); + System.arraycopy(mValues, 0, nvalues, 0, mValues.length); + + mKeys = nkeys; + mValues = nvalues; + } + + if (mSize - i != 0) { + // Log.e("SparseByteArray", "move " + (mSize - i)); + System.arraycopy(mKeys, i, mKeys, i + 1, mSize - i); + System.arraycopy(mValues, i, mValues, i + 1, mSize - i); + } + + mKeys[i] = key; + mValues[i] = value; + mSize++; + } + } + + /** + * Returns the number of key-value mappings that this SparseByteArray + * currently stores. + */ + public int size() { + return mSize; + } + + /** + * Given an index in the range 0...size()-1, returns + * the key from the indexth key-value mapping that this + * SparseByteArray stores. + */ + public int keyAt(int index) { + return mKeys[index]; + } + + /** + * Given an index in the range 0...size()-1, returns + * the value from the indexth key-value mapping that this + * SparseByteArray stores. + */ + public byte valueAt(int index) { + return mValues[index]; + } + + /** + * Returns the index for which {@link #keyAt} would return the + * specified key, or a negative number if the specified + * key is not mapped. + */ + public int indexOfKey(int key) { + return binarySearch(mKeys, 0, mSize, key); + } + + /** + * Returns an index for which {@link #valueAt} would return the + * specified key, or a negative number if no keys map to the + * specified value. + * Beware that this is a linear search, unlike lookups by key, + * and that multiple keys can map to the same value and this will + * find only one of them. + */ + public int indexOfValue(byte value) { + for (int i = 0; i < mSize; i++) + if (mValues[i] == value) + return i; + + return -1; + } + + /** + * Removes all key-value mappings from this SparseByteArray. + */ + public void clear() { + mSize = 0; + } + + /** + * Puts a key/value pair into the array, optimizing for the case where + * the key is greater than all existing keys in the array. + */ + public void append(int key, byte value) { + if (mSize != 0 && key <= mKeys[mSize - 1]) { + put(key, value); + return; + } + + int pos = mSize; + if (pos >= mKeys.length) { + int n = ArrayUtils.idealIntArraySize(pos + 1); + + int[] nkeys = new int[n]; + byte[] nvalues = new byte[n]; + + // Log.e("SparseByteArray", "grow " + mKeys.length + " to " + n); + System.arraycopy(mKeys, 0, nkeys, 0, mKeys.length); + System.arraycopy(mValues, 0, nvalues, 0, mValues.length); + + mKeys = nkeys; + mValues = nvalues; + } + + mKeys[pos] = key; + mValues[pos] = value; + mSize = pos + 1; + } + + private static int binarySearch(int[] a, int start, int len, int key) { + int high = start + len, low = start - 1, guess; + + while (high - low > 1) { + guess = (high + low) / 2; + + if (a[guess] < key) + low = guess; + else + high = guess; + } + + if (high == start + len) + return ~(start + len); + else if (a[high] == key) + return high; + else + return ~high; + } + + private int[] mKeys; + private byte[] mValues; + private int mSize; +} \ No newline at end of file diff --git a/src/org/andengine/util/adt/map/SparseCharArray.java b/src/org/andengine/util/adt/map/SparseCharArray.java new file mode 100644 index 000000000..20cac5f81 --- /dev/null +++ b/src/org/andengine/util/adt/map/SparseCharArray.java @@ -0,0 +1,246 @@ +/* + * Copyright (C) 2006 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. + */ + +package org.andengine.util.adt.map; + +import org.andengine.util.adt.array.ArrayUtils; + +/** + * SparseCharArrays map integers to chars. + * Unlike a normal array of chars + * there can be gaps in the indices. It is intended to be more efficient + * than using a HashMap to map Integers to Booleans. + */ +public class SparseCharArray implements Cloneable { + /** + * Creates a new SparseCharArray containing no mappings. + */ + public SparseCharArray() { + this(10); + } + + /** + * Creates a new SparseCharArray containing no mappings that will not + * require any additional memory allocation to store the specified + * number of mappings. + */ + public SparseCharArray(int initialCapacity) { + initialCapacity = ArrayUtils.idealIntArraySize(initialCapacity); + + mKeys = new int[initialCapacity]; + mValues = new char[initialCapacity]; + mSize = 0; + } + + @Override + public SparseCharArray clone() { + SparseCharArray clone = null; + try { + clone = (SparseCharArray) super.clone(); + clone.mKeys = mKeys.clone(); + clone.mValues = mValues.clone(); + } catch (CloneNotSupportedException cnse) { + /* ignore */ + } + return clone; + } + + /** + * Gets the char mapped from the specified key, or '\0' + * if no such mapping has been made. + */ + public char get(int key) { + return get(key, '\0'); + } + + /** + * Gets the char mapped from the specified key, or the specified value + * if no such mapping has been made. + */ + public char get(int key, char valueIfKeyNotFound) { + int i = binarySearch(mKeys, 0, mSize, key); + + if (i < 0) { + return valueIfKeyNotFound; + } else { + return mValues[i]; + } + } + + /** + * Removes the mapping from the specified key, if there was any. + */ + public void delete(int key) { + int i = binarySearch(mKeys, 0, mSize, key); + + if (i >= 0) { + System.arraycopy(mKeys, i + 1, mKeys, i, mSize - (i + 1)); + System.arraycopy(mValues, i + 1, mValues, i, mSize - (i + 1)); + mSize--; + } + } + + /** + * Adds a mapping from the specified key to the specified value, + * replacing the previous mapping from the specified key if there + * was one. + */ + public void put(int key, char value) { + int i = binarySearch(mKeys, 0, mSize, key); + + if (i >= 0) { + mValues[i] = value; + } else { + i = ~i; + + if (mSize >= mKeys.length) { + int n = ArrayUtils.idealIntArraySize(mSize + 1); + + int[] nkeys = new int[n]; + char[] nvalues = new char[n]; + + // Log.e("SparseCharArray", "grow " + mKeys.length + " to " + n); + System.arraycopy(mKeys, 0, nkeys, 0, mKeys.length); + System.arraycopy(mValues, 0, nvalues, 0, mValues.length); + + mKeys = nkeys; + mValues = nvalues; + } + + if (mSize - i != 0) { + // Log.e("SparseCharArray", "move " + (mSize - i)); + System.arraycopy(mKeys, i, mKeys, i + 1, mSize - i); + System.arraycopy(mValues, i, mValues, i + 1, mSize - i); + } + + mKeys[i] = key; + mValues[i] = value; + mSize++; + } + } + + /** + * Returns the number of key-value mappings that this SparseCharArray + * currently stores. + */ + public int size() { + return mSize; + } + + /** + * Given an index in the range 0...size()-1, returns + * the key from the indexth key-value mapping that this + * SparseCharArray stores. + */ + public int keyAt(int index) { + return mKeys[index]; + } + + /** + * Given an index in the range 0...size()-1, returns + * the value from the indexth key-value mapping that this + * SparseCharArray stores. + */ + public char valueAt(int index) { + return mValues[index]; + } + + /** + * Returns the index for which {@link #keyAt} would return the + * specified key, or a negative number if the specified + * key is not mapped. + */ + public int indexOfKey(int key) { + return binarySearch(mKeys, 0, mSize, key); + } + + /** + * Returns an index for which {@link #valueAt} would return the + * specified key, or a negative number if no keys map to the + * specified value. + * Beware that this is a linear search, unlike lookups by key, + * and that multiple keys can map to the same value and this will + * find only one of them. + */ + public int indexOfValue(char value) { + for (int i = 0; i < mSize; i++) + if (mValues[i] == value) + return i; + + return -1; + } + + /** + * Removes all key-value mappings from this SparseCharArray. + */ + public void clear() { + mSize = 0; + } + + /** + * Puts a key/value pair into the array, optimizing for the case where + * the key is greater than all existing keys in the array. + */ + public void append(int key, char value) { + if (mSize != 0 && key <= mKeys[mSize - 1]) { + put(key, value); + return; + } + + int pos = mSize; + if (pos >= mKeys.length) { + int n = ArrayUtils.idealIntArraySize(pos + 1); + + int[] nkeys = new int[n]; + char[] nvalues = new char[n]; + + // Log.e("SparseCharArray", "grow " + mKeys.length + " to " + n); + System.arraycopy(mKeys, 0, nkeys, 0, mKeys.length); + System.arraycopy(mValues, 0, nvalues, 0, mValues.length); + + mKeys = nkeys; + mValues = nvalues; + } + + mKeys[pos] = key; + mValues[pos] = value; + mSize = pos + 1; + } + + private static int binarySearch(int[] a, int start, int len, int key) { + int high = start + len, low = start - 1, guess; + + while (high - low > 1) { + guess = (high + low) / 2; + + if (a[guess] < key) + low = guess; + else + high = guess; + } + + if (high == start + len) + return ~(start + len); + else if (a[high] == key) + return high; + else + return ~high; + } + + private int[] mKeys; + private char[] mValues; + private int mSize; +} \ No newline at end of file diff --git a/src/org/andengine/util/adt/map/SparseDoubleArray.java b/src/org/andengine/util/adt/map/SparseDoubleArray.java new file mode 100644 index 000000000..c1e2e540a --- /dev/null +++ b/src/org/andengine/util/adt/map/SparseDoubleArray.java @@ -0,0 +1,246 @@ +/* + * Copyright (C) 2006 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. + */ + +package org.andengine.util.adt.map; + +import org.andengine.util.adt.array.ArrayUtils; + +/** + * SparseDoubleArrays map integers to doubles. + * Unlike a normal array of doubles + * there can be gaps in the indices. It is intended to be more efficient + * than using a HashMap to map Integers to Booleans. + */ +public class SparseDoubleArray implements Cloneable { + /** + * Creates a new SparseDoubleArray containing no mappings. + */ + public SparseDoubleArray() { + this(10); + } + + /** + * Creates a new SparseDoubleArray containing no mappings that will not + * require any additional memory allocation to store the specified + * number of mappings. + */ + public SparseDoubleArray(int initialCapacity) { + initialCapacity = ArrayUtils.idealIntArraySize(initialCapacity); + + mKeys = new int[initialCapacity]; + mValues = new double[initialCapacity]; + mSize = 0; + } + + @Override + public SparseDoubleArray clone() { + SparseDoubleArray clone = null; + try { + clone = (SparseDoubleArray) super.clone(); + clone.mKeys = mKeys.clone(); + clone.mValues = mValues.clone(); + } catch (CloneNotSupportedException cnse) { + /* ignore */ + } + return clone; + } + + /** + * Gets the double mapped from the specified key, or 0 + * if no such mapping has been made. + */ + public double get(int key) { + return get(key, 0); + } + + /** + * Gets the double mapped from the specified key, or the specified value + * if no such mapping has been made. + */ + public double get(int key, double valueIfKeyNotFound) { + int i = binarySearch(mKeys, 0, mSize, key); + + if (i < 0) { + return valueIfKeyNotFound; + } else { + return mValues[i]; + } + } + + /** + * Removes the mapping from the specified key, if there was any. + */ + public void delete(int key) { + int i = binarySearch(mKeys, 0, mSize, key); + + if (i >= 0) { + System.arraycopy(mKeys, i + 1, mKeys, i, mSize - (i + 1)); + System.arraycopy(mValues, i + 1, mValues, i, mSize - (i + 1)); + mSize--; + } + } + + /** + * Adds a mapping from the specified key to the specified value, + * replacing the previous mapping from the specified key if there + * was one. + */ + public void put(int key, double value) { + int i = binarySearch(mKeys, 0, mSize, key); + + if (i >= 0) { + mValues[i] = value; + } else { + i = ~i; + + if (mSize >= mKeys.length) { + int n = ArrayUtils.idealIntArraySize(mSize + 1); + + int[] nkeys = new int[n]; + double[] nvalues = new double[n]; + + // Log.e("SparseDoubleArray", "grow " + mKeys.length + " to " + n); + System.arraycopy(mKeys, 0, nkeys, 0, mKeys.length); + System.arraycopy(mValues, 0, nvalues, 0, mValues.length); + + mKeys = nkeys; + mValues = nvalues; + } + + if (mSize - i != 0) { + // Log.e("SparseDoubleArray", "move " + (mSize - i)); + System.arraycopy(mKeys, i, mKeys, i + 1, mSize - i); + System.arraycopy(mValues, i, mValues, i + 1, mSize - i); + } + + mKeys[i] = key; + mValues[i] = value; + mSize++; + } + } + + /** + * Returns the number of key-value mappings that this SparseDoubleArray + * currently stores. + */ + public int size() { + return mSize; + } + + /** + * Given an index in the range 0...size()-1, returns + * the key from the indexth key-value mapping that this + * SparseDoubleArray stores. + */ + public int keyAt(int index) { + return mKeys[index]; + } + + /** + * Given an index in the range 0...size()-1, returns + * the value from the indexth key-value mapping that this + * SparseDoubleArray stores. + */ + public double valueAt(int index) { + return mValues[index]; + } + + /** + * Returns the index for which {@link #keyAt} would return the + * specified key, or a negative number if the specified + * key is not mapped. + */ + public int indexOfKey(int key) { + return binarySearch(mKeys, 0, mSize, key); + } + + /** + * Returns an index for which {@link #valueAt} would return the + * specified key, or a negative number if no keys map to the + * specified value. + * Beware that this is a linear search, unlike lookups by key, + * and that multiple keys can map to the same value and this will + * find only one of them. + */ + public int indexOfValue(double value) { + for (int i = 0; i < mSize; i++) + if (mValues[i] == value) + return i; + + return -1; + } + + /** + * Removes all key-value mappings from this SparseDoubleArray. + */ + public void clear() { + mSize = 0; + } + + /** + * Puts a key/value pair into the array, optimizing for the case where + * the key is greater than all existing keys in the array. + */ + public void append(int key, double value) { + if (mSize != 0 && key <= mKeys[mSize - 1]) { + put(key, value); + return; + } + + int pos = mSize; + if (pos >= mKeys.length) { + int n = ArrayUtils.idealIntArraySize(pos + 1); + + int[] nkeys = new int[n]; + double[] nvalues = new double[n]; + + // Log.e("SparseDoubleArray", "grow " + mKeys.length + " to " + n); + System.arraycopy(mKeys, 0, nkeys, 0, mKeys.length); + System.arraycopy(mValues, 0, nvalues, 0, mValues.length); + + mKeys = nkeys; + mValues = nvalues; + } + + mKeys[pos] = key; + mValues[pos] = value; + mSize = pos + 1; + } + + private static int binarySearch(int[] a, int start, int len, int key) { + int high = start + len, low = start - 1, guess; + + while (high - low > 1) { + guess = (high + low) / 2; + + if (a[guess] < key) + low = guess; + else + high = guess; + } + + if (high == start + len) + return ~(start + len); + else if (a[high] == key) + return high; + else + return ~high; + } + + private int[] mKeys; + private double[] mValues; + private int mSize; +} \ No newline at end of file diff --git a/src/org/andengine/util/adt/map/SparseFloatArray.java b/src/org/andengine/util/adt/map/SparseFloatArray.java new file mode 100644 index 000000000..ffa6eb304 --- /dev/null +++ b/src/org/andengine/util/adt/map/SparseFloatArray.java @@ -0,0 +1,246 @@ +/* + * Copyright (C) 2006 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. + */ + +package org.andengine.util.adt.map; + +import org.andengine.util.adt.array.ArrayUtils; + +/** + * SparseFloatArrays map integers to floats. + * Unlike a normal array of floats + * there can be gaps in the indices. It is intended to be more efficient + * than using a HashMap to map Integers to Booleans. + */ +public class SparseFloatArray implements Cloneable { + /** + * Creates a new SparseFloatArray containing no mappings. + */ + public SparseFloatArray() { + this(10); + } + + /** + * Creates a new SparseFloatArray containing no mappings that will not + * require any additional memory allocation to store the specified + * number of mappings. + */ + public SparseFloatArray(int initialCapacity) { + initialCapacity = ArrayUtils.idealIntArraySize(initialCapacity); + + mKeys = new int[initialCapacity]; + mValues = new float[initialCapacity]; + mSize = 0; + } + + @Override + public SparseFloatArray clone() { + SparseFloatArray clone = null; + try { + clone = (SparseFloatArray) super.clone(); + clone.mKeys = mKeys.clone(); + clone.mValues = mValues.clone(); + } catch (CloneNotSupportedException cnse) { + /* ignore */ + } + return clone; + } + + /** + * Gets the float mapped from the specified key, or 0 + * if no such mapping has been made. + */ + public float get(int key) { + return get(key, 0); + } + + /** + * Gets the float mapped from the specified key, or the specified value + * if no such mapping has been made. + */ + public float get(int key, float valueIfKeyNotFound) { + int i = binarySearch(mKeys, 0, mSize, key); + + if (i < 0) { + return valueIfKeyNotFound; + } else { + return mValues[i]; + } + } + + /** + * Removes the mapping from the specified key, if there was any. + */ + public void delete(int key) { + int i = binarySearch(mKeys, 0, mSize, key); + + if (i >= 0) { + System.arraycopy(mKeys, i + 1, mKeys, i, mSize - (i + 1)); + System.arraycopy(mValues, i + 1, mValues, i, mSize - (i + 1)); + mSize--; + } + } + + /** + * Adds a mapping from the specified key to the specified value, + * replacing the previous mapping from the specified key if there + * was one. + */ + public void put(int key, float value) { + int i = binarySearch(mKeys, 0, mSize, key); + + if (i >= 0) { + mValues[i] = value; + } else { + i = ~i; + + if (mSize >= mKeys.length) { + int n = ArrayUtils.idealIntArraySize(mSize + 1); + + int[] nkeys = new int[n]; + float[] nvalues = new float[n]; + + // Log.e("SparseFloatArray", "grow " + mKeys.length + " to " + n); + System.arraycopy(mKeys, 0, nkeys, 0, mKeys.length); + System.arraycopy(mValues, 0, nvalues, 0, mValues.length); + + mKeys = nkeys; + mValues = nvalues; + } + + if (mSize - i != 0) { + // Log.e("SparseFloatArray", "move " + (mSize - i)); + System.arraycopy(mKeys, i, mKeys, i + 1, mSize - i); + System.arraycopy(mValues, i, mValues, i + 1, mSize - i); + } + + mKeys[i] = key; + mValues[i] = value; + mSize++; + } + } + + /** + * Returns the number of key-value mappings that this SparseFloatArray + * currently stores. + */ + public int size() { + return mSize; + } + + /** + * Given an index in the range 0...size()-1, returns + * the key from the indexth key-value mapping that this + * SparseFloatArray stores. + */ + public int keyAt(int index) { + return mKeys[index]; + } + + /** + * Given an index in the range 0...size()-1, returns + * the value from the indexth key-value mapping that this + * SparseFloatArray stores. + */ + public float valueAt(int index) { + return mValues[index]; + } + + /** + * Returns the index for which {@link #keyAt} would return the + * specified key, or a negative number if the specified + * key is not mapped. + */ + public int indexOfKey(int key) { + return binarySearch(mKeys, 0, mSize, key); + } + + /** + * Returns an index for which {@link #valueAt} would return the + * specified key, or a negative number if no keys map to the + * specified value. + * Beware that this is a linear search, unlike lookups by key, + * and that multiple keys can map to the same value and this will + * find only one of them. + */ + public int indexOfValue(float value) { + for (int i = 0; i < mSize; i++) + if (mValues[i] == value) + return i; + + return -1; + } + + /** + * Removes all key-value mappings from this SparseFloatArray. + */ + public void clear() { + mSize = 0; + } + + /** + * Puts a key/value pair into the array, optimizing for the case where + * the key is greater than all existing keys in the array. + */ + public void append(int key, float value) { + if (mSize != 0 && key <= mKeys[mSize - 1]) { + put(key, value); + return; + } + + int pos = mSize; + if (pos >= mKeys.length) { + int n = ArrayUtils.idealIntArraySize(pos + 1); + + int[] nkeys = new int[n]; + float[] nvalues = new float[n]; + + // Log.e("SparseFloatArray", "grow " + mKeys.length + " to " + n); + System.arraycopy(mKeys, 0, nkeys, 0, mKeys.length); + System.arraycopy(mValues, 0, nvalues, 0, mValues.length); + + mKeys = nkeys; + mValues = nvalues; + } + + mKeys[pos] = key; + mValues[pos] = value; + mSize = pos + 1; + } + + private static int binarySearch(int[] a, int start, int len, int key) { + int high = start + len, low = start - 1, guess; + + while (high - low > 1) { + guess = (high + low) / 2; + + if (a[guess] < key) + low = guess; + else + high = guess; + } + + if (high == start + len) + return ~(start + len); + else if (a[high] == key) + return high; + else + return ~high; + } + + private int[] mKeys; + private float[] mValues; + private int mSize; +} \ No newline at end of file diff --git a/src/org/andengine/util/adt/map/SparseLongArray.java b/src/org/andengine/util/adt/map/SparseLongArray.java new file mode 100644 index 000000000..99ef55fe9 --- /dev/null +++ b/src/org/andengine/util/adt/map/SparseLongArray.java @@ -0,0 +1,246 @@ +/* + * Copyright (C) 2006 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. + */ + +package org.andengine.util.adt.map; + +import org.andengine.util.adt.array.ArrayUtils; + +/** + * SparseLongArrays map integers to longs. + * Unlike a normal array of longs + * there can be gaps in the indices. It is intended to be more efficient + * than using a HashMap to map Integers to Booleans. + */ +public class SparseLongArray implements Cloneable { + /** + * Creates a new SparseLongArray containing no mappings. + */ + public SparseLongArray() { + this(10); + } + + /** + * Creates a new SparseLongArray containing no mappings that will not + * require any additional memory allocation to store the specified + * number of mappings. + */ + public SparseLongArray(int initialCapacity) { + initialCapacity = ArrayUtils.idealIntArraySize(initialCapacity); + + mKeys = new int[initialCapacity]; + mValues = new long[initialCapacity]; + mSize = 0; + } + + @Override + public SparseLongArray clone() { + SparseLongArray clone = null; + try { + clone = (SparseLongArray) super.clone(); + clone.mKeys = mKeys.clone(); + clone.mValues = mValues.clone(); + } catch (CloneNotSupportedException cnse) { + /* ignore */ + } + return clone; + } + + /** + * Gets the long mapped from the specified key, or 0 + * if no such mapping has been made. + */ + public long get(int key) { + return get(key, 0); + } + + /** + * Gets the long mapped from the specified key, or the specified value + * if no such mapping has been made. + */ + public long get(int key, long valueIfKeyNotFound) { + int i = binarySearch(mKeys, 0, mSize, key); + + if (i < 0) { + return valueIfKeyNotFound; + } else { + return mValues[i]; + } + } + + /** + * Removes the mapping from the specified key, if there was any. + */ + public void delete(int key) { + int i = binarySearch(mKeys, 0, mSize, key); + + if (i >= 0) { + System.arraycopy(mKeys, i + 1, mKeys, i, mSize - (i + 1)); + System.arraycopy(mValues, i + 1, mValues, i, mSize - (i + 1)); + mSize--; + } + } + + /** + * Adds a mapping from the specified key to the specified value, + * replacing the previous mapping from the specified key if there + * was one. + */ + public void put(int key, long value) { + int i = binarySearch(mKeys, 0, mSize, key); + + if (i >= 0) { + mValues[i] = value; + } else { + i = ~i; + + if (mSize >= mKeys.length) { + int n = ArrayUtils.idealIntArraySize(mSize + 1); + + int[] nkeys = new int[n]; + long[] nvalues = new long[n]; + + // Log.e("SparseLongArray", "grow " + mKeys.length + " to " + n); + System.arraycopy(mKeys, 0, nkeys, 0, mKeys.length); + System.arraycopy(mValues, 0, nvalues, 0, mValues.length); + + mKeys = nkeys; + mValues = nvalues; + } + + if (mSize - i != 0) { + // Log.e("SparseLongArray", "move " + (mSize - i)); + System.arraycopy(mKeys, i, mKeys, i + 1, mSize - i); + System.arraycopy(mValues, i, mValues, i + 1, mSize - i); + } + + mKeys[i] = key; + mValues[i] = value; + mSize++; + } + } + + /** + * Returns the number of key-value mappings that this SparseLongArray + * currently stores. + */ + public int size() { + return mSize; + } + + /** + * Given an index in the range 0...size()-1, returns + * the key from the indexth key-value mapping that this + * SparseLongArray stores. + */ + public int keyAt(int index) { + return mKeys[index]; + } + + /** + * Given an index in the range 0...size()-1, returns + * the value from the indexth key-value mapping that this + * SparseLongArray stores. + */ + public long valueAt(int index) { + return mValues[index]; + } + + /** + * Returns the index for which {@link #keyAt} would return the + * specified key, or a negative number if the specified + * key is not mapped. + */ + public int indexOfKey(int key) { + return binarySearch(mKeys, 0, mSize, key); + } + + /** + * Returns an index for which {@link #valueAt} would return the + * specified key, or a negative number if no keys map to the + * specified value. + * Beware that this is a linear search, unlike lookups by key, + * and that multiple keys can map to the same value and this will + * find only one of them. + */ + public int indexOfValue(long value) { + for (int i = 0; i < mSize; i++) + if (mValues[i] == value) + return i; + + return -1; + } + + /** + * Removes all key-value mappings from this SparseLongArray. + */ + public void clear() { + mSize = 0; + } + + /** + * Puts a key/value pair into the array, optimizing for the case where + * the key is greater than all existing keys in the array. + */ + public void append(int key, long value) { + if (mSize != 0 && key <= mKeys[mSize - 1]) { + put(key, value); + return; + } + + int pos = mSize; + if (pos >= mKeys.length) { + int n = ArrayUtils.idealIntArraySize(pos + 1); + + int[] nkeys = new int[n]; + long[] nvalues = new long[n]; + + // Log.e("SparseLongArray", "grow " + mKeys.length + " to " + n); + System.arraycopy(mKeys, 0, nkeys, 0, mKeys.length); + System.arraycopy(mValues, 0, nvalues, 0, mValues.length); + + mKeys = nkeys; + mValues = nvalues; + } + + mKeys[pos] = key; + mValues[pos] = value; + mSize = pos + 1; + } + + private static int binarySearch(int[] a, int start, int len, int key) { + int high = start + len, low = start - 1, guess; + + while (high - low > 1) { + guess = (high + low) / 2; + + if (a[guess] < key) + low = guess; + else + high = guess; + } + + if (high == start + len) + return ~(start + len); + else if (a[high] == key) + return high; + else + return ~high; + } + + private int[] mKeys; + private long[] mValues; + private int mSize; +} \ No newline at end of file diff --git a/src/org/andengine/util/adt/pool/EntityDetachRunnablePoolItem.java b/src/org/andengine/util/adt/pool/EntityDetachRunnablePoolItem.java index 4e00bcb5f..0e4e02530 100644 --- a/src/org/andengine/util/adt/pool/EntityDetachRunnablePoolItem.java +++ b/src/org/andengine/util/adt/pool/EntityDetachRunnablePoolItem.java @@ -4,9 +4,9 @@ import org.andengine.util.call.Callback; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 00:53:22 - 28.08.2010 */ @@ -50,7 +50,7 @@ public void setCallback(final Callback pCallback) { public void run() { this.mEntity.detachSelf(); - if(this.mCallback != null) { + if (this.mCallback != null) { this.mCallback.onCallback(this.mEntity); } } diff --git a/src/org/andengine/util/adt/pool/EntityDetachRunnablePoolUpdateHandler.java b/src/org/andengine/util/adt/pool/EntityDetachRunnablePoolUpdateHandler.java index 8d6b388a3..8df8c9342 100644 --- a/src/org/andengine/util/adt/pool/EntityDetachRunnablePoolUpdateHandler.java +++ b/src/org/andengine/util/adt/pool/EntityDetachRunnablePoolUpdateHandler.java @@ -6,7 +6,7 @@ /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 23:16:25 - 31.08.2010 */ diff --git a/src/org/andengine/util/adt/pool/GenericPool.java b/src/org/andengine/util/adt/pool/GenericPool.java index a03420648..0cc241897 100644 --- a/src/org/andengine/util/adt/pool/GenericPool.java +++ b/src/org/andengine/util/adt/pool/GenericPool.java @@ -9,10 +9,10 @@ /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Valentin Milea * @author Nicolas Gramlich - * + * * @since 22:19:55 - 31.08.2010 */ public abstract class GenericPool { @@ -47,10 +47,10 @@ public GenericPool(final int pInitialSize, final int pGrowth) { } public GenericPool(final int pInitialSize, final int pGrowth, final int pAvailableItemsMaximum) { - if(pGrowth <= 0) { + if (pGrowth <= 0) { throw new IllegalArgumentException("pGrowth must be greater than 0!"); } - if(pAvailableItemsMaximum < 0) { + if (pAvailableItemsMaximum < 0) { throw new IllegalArgumentException("pAvailableItemsMaximum must be at least 0!"); } @@ -58,7 +58,7 @@ public GenericPool(final int pInitialSize, final int pGrowth, final int pAvailab this.mAvailableItemCountMaximum = pAvailableItemsMaximum; this.mAvailableItems = new ArrayList(pInitialSize); - if(pInitialSize > 0) { + if (pInitialSize > 0) { this.batchAllocatePoolItems(pInitialSize); } } @@ -111,11 +111,11 @@ public synchronized void batchAllocatePoolItems(final int pCount) { final ArrayList availableItems = this.mAvailableItems; int allocationCount = this.mAvailableItemCountMaximum - availableItems.size(); - if(pCount < allocationCount) { + if (pCount < allocationCount) { allocationCount = pCount; } - for(int i = allocationCount - 1; i >= 0; i--) { + for (int i = allocationCount - 1; i >= 0; i--) { availableItems.add(this.onHandleAllocatePoolItem()); } } @@ -123,16 +123,16 @@ public synchronized void batchAllocatePoolItems(final int pCount) { public synchronized T obtainPoolItem() { final T item; - if(this.mAvailableItems.size() > 0) { + if (this.mAvailableItems.size() > 0) { item = this.mAvailableItems.remove(this.mAvailableItems.size() - 1); } else { - if(this.mGrowth == 1 || this.mAvailableItemCountMaximum == 0) { + if (this.mGrowth == 1 || this.mAvailableItemCountMaximum == 0) { item = this.onHandleAllocatePoolItem(); } else { this.batchAllocatePoolItems(this.mGrowth); item = this.mAvailableItems.remove(this.mAvailableItems.size() - 1); } - if(BuildConfig.DEBUG) { + if (BuildConfig.DEBUG) { Debug.v(this.getClass().getName() + "<" + item.getClass().getSimpleName() +"> was exhausted, with " + this.mUnrecycledItemCount + " item not yet recycled. Allocated " + this.mGrowth + " more."); } } @@ -143,19 +143,19 @@ public synchronized T obtainPoolItem() { } public synchronized void recyclePoolItem(final T pItem) { - if(pItem == null) { + if (pItem == null) { throw new IllegalArgumentException("Cannot recycle null item!"); } this.onHandleRecycleItem(pItem); - if(this.mAvailableItems.size() < this.mAvailableItemCountMaximum) { + if (this.mAvailableItems.size() < this.mAvailableItemCountMaximum) { this.mAvailableItems.add(pItem); } this.mUnrecycledItemCount--; - if(this.mUnrecycledItemCount < 0) { + if (this.mUnrecycledItemCount < 0) { Debug.e("More items recycled than obtained!"); } } diff --git a/src/org/andengine/util/adt/pool/MultiPool.java b/src/org/andengine/util/adt/pool/MultiPool.java index 7da1a94d1..a5d873058 100644 --- a/src/org/andengine/util/adt/pool/MultiPool.java +++ b/src/org/andengine/util/adt/pool/MultiPool.java @@ -3,9 +3,9 @@ import android.util.SparseArray; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 10:13:26 - 02.03.2011 */ @@ -42,7 +42,7 @@ public void registerPool(final int pID, final GenericPool pPool) { public T obtainPoolItem(final int pID) { final GenericPool pool = this.mPools.get(pID); - if(pool == null) { + if (pool == null) { return null; } else { return pool.obtainPoolItem(); @@ -51,7 +51,7 @@ public T obtainPoolItem(final int pID) { public void recyclePoolItem(final int pID, final T pItem) { final GenericPool pool = this.mPools.get(pID); - if(pool != null) { + if (pool != null) { pool.recyclePoolItem(pItem); } } diff --git a/src/org/andengine/util/adt/pool/Pool.java b/src/org/andengine/util/adt/pool/Pool.java index aae137b3e..4186614ed 100644 --- a/src/org/andengine/util/adt/pool/Pool.java +++ b/src/org/andengine/util/adt/pool/Pool.java @@ -4,10 +4,10 @@ /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Valentin Milea * @author Nicolas Gramlich - * + * * @since 23:00:21 - 21.08.2010 */ public abstract class Pool extends GenericPool { @@ -68,11 +68,11 @@ protected void onHandleRecycleItem(final T pPoolItem) { @Override public synchronized void recyclePoolItem(final T pPoolItem) { - if(pPoolItem.mParent == null) { + if (pPoolItem.mParent == null) { throw new IllegalArgumentException("PoolItem not assigned to a pool!"); - } else if(!pPoolItem.isFromPool(this)) { + } else if (!pPoolItem.isFromPool(this)) { throw new IllegalArgumentException("PoolItem from another pool!"); - } else if(pPoolItem.isRecycled()) { + } else if (pPoolItem.isRecycled()) { throw new IllegalArgumentException("PoolItem already recycled!"); } diff --git a/src/org/andengine/util/adt/pool/PoolItem.java b/src/org/andengine/util/adt/pool/PoolItem.java index 95e209df2..139b09d32 100644 --- a/src/org/andengine/util/adt/pool/PoolItem.java +++ b/src/org/andengine/util/adt/pool/PoolItem.java @@ -1,12 +1,12 @@ package org.andengine.util.adt.pool; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Valentin Milea * @author Nicolas Gramlich - * + * * @since 23:02:47 - 21.08.2010 */ public abstract class PoolItem { @@ -58,7 +58,7 @@ protected void onObtain() { } public void recycle() { - if(this.mParent == null) { + if (this.mParent == null) { throw new IllegalStateException("Item already recycled!"); } diff --git a/src/org/andengine/util/adt/pool/PoolUpdateHandler.java b/src/org/andengine/util/adt/pool/PoolUpdateHandler.java index 9bb277543..ddfa44606 100644 --- a/src/org/andengine/util/adt/pool/PoolUpdateHandler.java +++ b/src/org/andengine/util/adt/pool/PoolUpdateHandler.java @@ -8,10 +8,10 @@ /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Valentin Milea * @author Nicolas Gramlich - * + * * @since 23:02:58 - 21.08.2010 */ public abstract class PoolUpdateHandler implements IUpdateHandler { @@ -84,7 +84,7 @@ public void onUpdate(final float pSecondsElapsed) { final Pool pool = this.mPool; T item; - while((item = scheduledPoolItemQueue.poll()) != null) { + while ((item = scheduledPoolItemQueue.poll()) != null) { this.onHandlePoolItem(item); pool.recyclePoolItem(item); } @@ -96,7 +96,7 @@ public void reset() { final Pool pool = this.mPool; T item; - while((item = scheduledPoolItemQueue.poll()) != null) { + while ((item = scheduledPoolItemQueue.poll()) != null) { pool.recyclePoolItem(item); } } @@ -110,9 +110,9 @@ public T obtainPoolItem() { } public void postPoolItem(final T pPoolItem) { - if(pPoolItem == null) { + if (pPoolItem == null) { throw new IllegalArgumentException("PoolItem already recycled!"); - } else if(!this.mPool.ownsPoolItem(pPoolItem)) { + } else if (!this.mPool.ownsPoolItem(pPoolItem)) { throw new IllegalArgumentException("PoolItem from another pool!"); } diff --git a/src/org/andengine/util/adt/pool/RunnablePoolItem.java b/src/org/andengine/util/adt/pool/RunnablePoolItem.java index 2928a7c31..19e24df40 100644 --- a/src/org/andengine/util/adt/pool/RunnablePoolItem.java +++ b/src/org/andengine/util/adt/pool/RunnablePoolItem.java @@ -1,9 +1,9 @@ package org.andengine.util.adt.pool; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 23:46:50 - 27.08.2010 */ diff --git a/src/org/andengine/util/adt/pool/RunnablePoolUpdateHandler.java b/src/org/andengine/util/adt/pool/RunnablePoolUpdateHandler.java index f389ff7de..0b7845fd2 100644 --- a/src/org/andengine/util/adt/pool/RunnablePoolUpdateHandler.java +++ b/src/org/andengine/util/adt/pool/RunnablePoolUpdateHandler.java @@ -3,10 +3,10 @@ /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Valentin Milea * @author Nicolas Gramlich - * + * * @since 23:03:58 - 21.08.2010 */ public abstract class RunnablePoolUpdateHandler extends PoolUpdateHandler { diff --git a/src/org/andengine/util/adt/queue/CircularQueue.java b/src/org/andengine/util/adt/queue/CircularQueue.java index 5cec43b16..6410c995b 100644 --- a/src/org/andengine/util/adt/queue/CircularQueue.java +++ b/src/org/andengine/util/adt/queue/CircularQueue.java @@ -3,7 +3,7 @@ import org.andengine.util.adt.list.CircularList; /** - * (c) Zynga 2012 + * (c) 2012 Zynga Inc. * * @author Nicolas Gramlich * @since 17:06:49 - 03.01.2012 @@ -39,7 +39,7 @@ public CircularQueue(final int pInitialCapacity) { @Override public T peek() { - if(this.isEmpty()) { + if (this.isEmpty()) { return null; } else { return this.get(0); @@ -48,7 +48,7 @@ public T peek() { @Override public T poll() { - if(this.isEmpty()) { + if (this.isEmpty()) { return null; } else { return this.remove(0); diff --git a/src/org/andengine/util/adt/queue/IQueue.java b/src/org/andengine/util/adt/queue/IQueue.java index d9f8923c1..5d44b94c2 100644 --- a/src/org/andengine/util/adt/queue/IQueue.java +++ b/src/org/andengine/util/adt/queue/IQueue.java @@ -3,7 +3,7 @@ import org.andengine.util.adt.list.IList; /** - * (c) Zynga 2012 + * (c) 2012 Zynga Inc. * * @author Nicolas Gramlich * @since 15:00:30 - 24.01.2012 diff --git a/src/org/andengine/util/adt/queue/ISortedQueue.java b/src/org/andengine/util/adt/queue/ISortedQueue.java index b0ae3c355..b51ced792 100644 --- a/src/org/andengine/util/adt/queue/ISortedQueue.java +++ b/src/org/andengine/util/adt/queue/ISortedQueue.java @@ -4,7 +4,7 @@ /** - * (c) Zynga 2012 + * (c) 2012 Zynga Inc. * * @author Nicolas Gramlich * @since 15:37:19 - 01.02.2012 diff --git a/src/org/andengine/util/adt/queue/IUniqueQueue.java b/src/org/andengine/util/adt/queue/IUniqueQueue.java index a0aaba91a..b7716545f 100644 --- a/src/org/andengine/util/adt/queue/IUniqueQueue.java +++ b/src/org/andengine/util/adt/queue/IUniqueQueue.java @@ -4,7 +4,7 @@ /** - * (c) Zynga 2012 + * (c) 2012 Zynga Inc. * * @author Nicolas Gramlich * @since 15:37:19 - 01.02.2012 diff --git a/src/org/andengine/util/adt/queue/ShiftQueue.java b/src/org/andengine/util/adt/queue/ShiftQueue.java index f0e038778..cebc0f2d6 100644 --- a/src/org/andengine/util/adt/queue/ShiftQueue.java +++ b/src/org/andengine/util/adt/queue/ShiftQueue.java @@ -3,7 +3,7 @@ import org.andengine.util.adt.list.ShiftList; /** - * (c) Zynga 2012 + * (c) 2012 Zynga Inc. * * @author Nicolas Gramlich * @since 17:06:49 - 03.01.2012 @@ -39,7 +39,7 @@ public ShiftQueue(final int pInitialCapacity) { @Override public T peek() { - if(this.isEmpty()) { + if (this.isEmpty()) { return null; } else { return this.get(0); @@ -48,7 +48,7 @@ public T peek() { @Override public T poll() { - if(this.isEmpty()) { + if (this.isEmpty()) { return null; } else { return this.remove(0); diff --git a/src/org/andengine/util/adt/queue/SortedQueue.java b/src/org/andengine/util/adt/queue/SortedQueue.java index 23d9e6396..f3450c807 100644 --- a/src/org/andengine/util/adt/queue/SortedQueue.java +++ b/src/org/andengine/util/adt/queue/SortedQueue.java @@ -3,12 +3,12 @@ import org.andengine.util.adt.list.SortedList; /** - * (c) Zynga 2012 + * (c) 2012 Zynga Inc. * * @author Nicolas Gramlich * @since 17:17:33 PM - 03.022012 */ -public class SortedQueue> extends SortedList implements ISortedQueue{ +public class SortedQueue> extends SortedList implements ISortedQueue { // =========================================================== // Constants // =========================================================== @@ -35,7 +35,7 @@ public SortedQueue(final IQueue pQueue) { @Override public T peek() { - if(this.isEmpty()) { + if (this.isEmpty()) { return null; } else { return this.get(0); @@ -44,7 +44,7 @@ public T peek() { @Override public T poll() { - if(this.isEmpty()) { + if (this.isEmpty()) { return null; } else { return this.remove(0); diff --git a/src/org/andengine/util/adt/queue/UniqueQueue.java b/src/org/andengine/util/adt/queue/UniqueQueue.java index 94ebfd300..0a5613efb 100644 --- a/src/org/andengine/util/adt/queue/UniqueQueue.java +++ b/src/org/andengine/util/adt/queue/UniqueQueue.java @@ -3,12 +3,12 @@ import org.andengine.util.adt.list.UniqueList; /** - * (c) Zynga 2012 + * (c) 2012 Zynga Inc. * * @author Nicolas Gramlich * @since 17:17:33 PM - 03.022012 */ -public class UniqueQueue> extends UniqueList implements IUniqueQueue{ +public class UniqueQueue> extends UniqueList implements IUniqueQueue { // =========================================================== // Constants // =========================================================== @@ -35,7 +35,7 @@ public UniqueQueue(final IQueue pQueue) { @Override public T peek() { - if(this.isEmpty()) { + if (this.isEmpty()) { return null; } else { return this.get(0); @@ -44,7 +44,7 @@ public T peek() { @Override public T poll() { - if(this.isEmpty()) { + if (this.isEmpty()) { return null; } else { return this.remove(0); diff --git a/src/org/andengine/util/adt/queue/concurrent/PriorityBlockingAggregatorQueue.java b/src/org/andengine/util/adt/queue/concurrent/PriorityBlockingAggregatorQueue.java new file mode 100644 index 000000000..6ad0d773b --- /dev/null +++ b/src/org/andengine/util/adt/queue/concurrent/PriorityBlockingAggregatorQueue.java @@ -0,0 +1,439 @@ +package org.andengine.util.adt.queue.concurrent; + +import java.util.concurrent.locks.Condition; +import java.util.concurrent.locks.ReentrantLock; + +import org.andengine.util.adt.list.CircularList; +import org.andengine.util.adt.list.IList; + +import android.util.SparseArray; +import android.util.SparseIntArray; + +/** + * The {@link PriorityBlockingAggregatorQueue} is a thread-safe queue that internally holds multiple queues each having their own priority. + * {@link #peek()}, {@link #poll()} and {@link #take()} always return the head of the highest priority internal queue. + * The {@link PriorityBlockingAggregatorQueue} is i.e. useful in networking situations where different {@link Thread}s (producers) put different messages of different priority and the network {@link Thread} (consumer) should always send the highest priority message first. + * + * (c) 2013 Nicolas Gramlich + * + * @author Nicolas Gramlich + * @since 21:55:23 - 08.05.2013 + */ +public class PriorityBlockingAggregatorQueue { + // =========================================================== + // Constants + // =========================================================== + + private static final int QUEUE_INITIAL_CAPACITY_DEFAULT = 10; + + // =========================================================== + // Fields + // =========================================================== + + private final ReentrantLock mLock; + + private final SparseArray> mQueues = new SparseArray>(); + private final SparseIntArray mQueueCapacities = new SparseIntArray(); + private final SparseArray mNotFullConditions = new SparseArray(); + + private final Condition mNotEmptyCondition; + + private int mSize; + + // =========================================================== + // Constructors + // =========================================================== + + public PriorityBlockingAggregatorQueue(final boolean pFair) { + this.mLock = new ReentrantLock(pFair); + this.mNotEmptyCondition = this.mLock.newCondition(); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + public int size() { + final ReentrantLock lock = this.mLock; + lock.lock(); + + try { + return this.mSize; + } finally { + lock.unlock(); + } + } + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + public String toString() { + final ReentrantLock lock = this.mLock; + lock.lock(); + + try { + final StringBuilder stringBuilder = new StringBuilder(); + + if (this.mQueues.size() > 0) { + final SparseArray> queues = this.mQueues; + final SparseIntArray queueCapacities = this.mQueueCapacities; + + stringBuilder.append(" [\n"); + + final int queueCount = queues.size(); + for (int i = 0; i < queueCount; i++) { + final int priority = queues.keyAt(i); + final IList queue = queues.valueAt(i); + final int queueCapacity = queueCapacities.valueAt(i); + final int queueSize = queue.size(); + + stringBuilder.append("\tPriority: ").append(priority).append(" (Capacity: ").append(queueSize).append('/').append(queueCapacity).append("): "); + stringBuilder.append(queue.toString()); + + if (i < (queueCount - 1)) { + stringBuilder.append(','); + } + stringBuilder.append('\n'); + } + + stringBuilder.append(']'); + } + + return stringBuilder.toString(); + } finally { + lock.unlock(); + } + } + + + // =========================================================== + // Methods + // =========================================================== + + private void insert(final int pPrority, final T pItem) { // TODO Causes another (potentially unnecessary) lookup for the queue + final IList queue = this.mQueues.get(pPrority); + queue.add(pItem); + this.mSize++; + + this.mNotEmptyCondition.signal(); + } + + private T extract() { + final SparseArray> queues = this.mQueues; + final int queueCount = queues.size(); + for (int i = 0; i < queueCount; i++) { + final IList queue = this.mQueues.valueAt(i); + if (queue.size() > 0) { + final int priority = this.mQueues.keyAt(i); + return this.extract(priority); + } + } + return null; + } + + private T extract(final int pPriority) { // TODO Causes another (potentially unnecessary) lookup for the queue and the condition + final Condition notFullCondition = this.mNotFullConditions.get(pPriority); + + final IList queue = this.mQueues.get(pPriority); + final T item = queue.remove(0); + this.mSize--; + + notFullCondition.signal(); + + return item; + } + + public void addQueue(final int pPriority) { + this.addQueue(pPriority, Integer.MAX_VALUE); + } + + public void addQueue(final int pPriority, final int pCapacity) { + this.addQueue(pPriority, pCapacity, QUEUE_INITIAL_CAPACITY_DEFAULT); + } + + public void addQueue(final int pPriority, final int pCapacity, final int pInitialCapacity) { + if (pCapacity <= 0) { + throw new IllegalArgumentException("pCapacity must be greater than 0."); + } + + if (pInitialCapacity <= 0) { + throw new IllegalArgumentException("pInitialCapacity must be greater than 0."); + } + + final ReentrantLock lock = this.mLock; + lock.lock(); + + try { + this.mQueues.put(pPriority, new CircularList(pInitialCapacity)); + this.mQueueCapacities.put(pPriority, pCapacity); + this.mNotFullConditions.put(pPriority, this.mLock.newCondition()); + } finally { + lock.unlock(); + } + } + + public T peek() { + final ReentrantLock lock = this.mLock; + lock.lock(); + + try { + if (this.mSize == 0) { + return null; + } else { + final SparseArray> queues = this.mQueues; + final int queueCount = queues.size(); + for (int i = 0; i < queueCount; i++) { + final IList queue = this.mQueues.valueAt(i); + if (queue.size() > 0) { + return queue.get(0); + } + } + return null; + } + } finally { + lock.unlock(); + } + } + +// public T peek(final int pPriority) { +// final ReentrantLock lock = this.mLock; +// lock.lock(); +// +// try { +// final IList queue = this.mQueues.get(pPriority); +// if (queue == null) { +// throw new IllegalArgumentException("No queue found for pPriority: '" + pPriority + "'."); +// } +// final int queueCapacity = this.mQueueCapacities.get(pPriority); +// +// if (queueCapacity == 0) { +// return null; +// } else { +// return queue.get(0); +// } +// } finally { +// lock.unlock(); +// } +// } + + public T poll() { + final ReentrantLock lock = this.mLock; + lock.lock(); + + try { + if (this.mSize == 0) { + return null; + } else { + return extract(); + } + } finally { + lock.unlock(); + } + } + +// public T poll(final int pPriority) { +// final ReentrantLock lock = this.mLock; +// lock.lock(); +// +// try { +// final int queueCapacity = this.mQueueCapacities.get(pPriority, -1); +// if (queueCapacity == 0) { +// return null; +// } else { +// return this.extract(pPriority); +// } +// } finally { +// lock.unlock(); +// } +// } + + public T take() throws InterruptedException { + final ReentrantLock lock = this.mLock; + lock.lockInterruptibly(); + + try { + try { + while (this.mSize == 0) { + this.mNotEmptyCondition.await(); + } + } catch (final InterruptedException e) { + /* Propagate to non-interrupted thread. */ + this.mNotEmptyCondition.signal(); + throw e; + } + return this.extract(); + } finally { + lock.unlock(); + } + } + +// public T take(final int pPriority) throws InterruptedException { +// final ReentrantLock lock = this.mLock; +// lock.lockInterruptibly(); +// +// try { +// final IList queue = this.mQueues.get(pPriority); +// if (queue == null) { +// throw new IllegalArgumentException("No queue found for pPriority: '" + pPriority + "'."); +// } +// +// try { +// while (queue.size() == 0) { +// this.mNotEmptyCondition.await(); +// } +// } catch (final InterruptedException e) { +// /* Propagate to non-interrupted thread. */ +// this.mNotEmptyCondition.signal(); +// throw e; +// } +// return this.extract(pPriority); +// } finally { +// lock.unlock(); +// } +// } + + /** + * Inserts the specified element at the tail of this queue with the given priority, waiting for space to become available if the queue is full. + * + * @throws IllegalArgumentException if pItem is null + * @throws InterruptedException + */ + public void put(final int pPriority, final T pItem) throws IllegalArgumentException, InterruptedException { + if (pItem == null) { + throw new IllegalArgumentException("pItem must not be null."); + } + + final ReentrantLock lock = this.mLock; + final Condition notFullCondition = this.mNotFullConditions.get(pPriority); + lock.lockInterruptibly(); + + try { + final IList queue = this.mQueues.get(pPriority); + if (queue == null) { + throw new IllegalArgumentException("No queue found for pPriority: '" + pPriority + "'."); + } + + final int queueCapacity = this.mQueueCapacities.get(pPriority); + try { + while (queue.size() == queueCapacity) { + notFullCondition.await(); + } + } catch (final InterruptedException e) { + /* Propagate to non-interrupted thread. */ + notFullCondition.signal(); + throw e; + } + insert(pPriority, pItem); + } finally { + lock.unlock(); + } + } + + /** + * Inserts the specified element at the tail of this queue with the given priority, if it is possible without exceeding the capacity of the queue with the given priority. + * + * @throws IllegalArgumentException if pItem is null + * @return true if the + */ + public boolean offer(final int pPriority, final T pItem) throws IllegalArgumentException { + if (pItem == null) { + throw new IllegalArgumentException("pItem must not be null."); + } + + final ReentrantLock lock = this.mLock; + lock.lock(); + + try { + final IList queue = this.mQueues.get(pPriority); + if (queue == null) { + throw new IllegalArgumentException("No queue found for pPriority: '" + pPriority + "'."); + } + + final int queueCapacity = this.mQueueCapacities.get(pPriority); + if (queue.size() == queueCapacity) { + return false; + } else { + insert(pPriority, pItem); + return true; + } + } finally { + lock.unlock(); + } + } + + public void clear() { + final ReentrantLock lock = this.mLock; + lock.lock(); + + try { + if (this.mSize > 0) { + final SparseArray> queues = this.mQueues; + final int queueCount = queues.size(); + for (int i = 0; i < queueCount; i++) { + final int priority = this.mQueues.keyAt(i); + + final IList queue = this.mQueues.valueAt(i); + queue.clear(); + + final Condition notFullCondition = this.mNotFullConditions.get(priority); + notFullCondition.signal(); + } + this.mSize = 0; + } + } finally { + lock.unlock(); + } + } + + public void clear(final int pPriority) { + final ReentrantLock lock = this.mLock; + lock.lock(); + + try { + final IList queue = this.mQueues.get(pPriority); + if (queue == null) { + throw new IllegalArgumentException("No queue found for pPriority: '" + pPriority + "'."); + } + final int queueSize = queue.size(); + + queue.clear(); + + final Condition notFullCondition = this.mNotFullConditions.get(pPriority); + notFullCondition.signal(); + + this.mSize -= queueSize; + } finally { + lock.unlock(); + } + } + + public void clearAndPut(final int pPriority, final T pItem) throws IllegalArgumentException, InterruptedException { + final ReentrantLock lock = this.mLock; + lock.lock(); + + try { + this.clear(pPriority); + this.put(pPriority, pItem); + } finally { + lock.unlock(); + } + } + + public boolean clearAndOffer(final int pPriority, final T pItem) { + final ReentrantLock lock = this.mLock; + lock.lock(); + + try { + this.clear(pPriority); + return this.offer(pPriority, pItem); + } finally { + lock.unlock(); + } + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== +} diff --git a/src/org/andengine/util/adt/queue/concurrent/SynchronizedQueue.java b/src/org/andengine/util/adt/queue/concurrent/SynchronizedQueue.java index da83575f4..66ce918b5 100644 --- a/src/org/andengine/util/adt/queue/concurrent/SynchronizedQueue.java +++ b/src/org/andengine/util/adt/queue/concurrent/SynchronizedQueue.java @@ -1,9 +1,10 @@ package org.andengine.util.adt.queue.concurrent; +import org.andengine.util.adt.list.ListUtils; import org.andengine.util.adt.queue.IQueue; /** - * (c) Zynga 2012 + * (c) 2012 Zynga Inc. * * @author Nicolas Gramlich * @since 14:23:50 - 01.02.2012 @@ -46,7 +47,7 @@ public synchronized T get(final int pIndex) throws IndexOutOfBoundsException { } @Override - public synchronized void set(int pIndex, T pItem) throws IndexOutOfBoundsException { + public synchronized void set(final int pIndex, final T pItem) throws IndexOutOfBoundsException { this.mQueue.set(pIndex, pItem); } @@ -81,7 +82,7 @@ public synchronized void enter(final T pItem) { } @Override - public synchronized void enter(final int pIndex, final T pItem) throws IndexOutOfBoundsException{ + public synchronized void enter(final int pIndex, final T pItem) throws IndexOutOfBoundsException { this.mQueue.enter(pIndex, pItem); } @@ -101,7 +102,7 @@ public synchronized boolean remove(final T pItem) { } @Override - public synchronized T remove(final int pIndex) throws IndexOutOfBoundsException{ + public synchronized T remove(final int pIndex) throws IndexOutOfBoundsException { return this.mQueue.remove(pIndex); } @@ -115,6 +116,11 @@ public synchronized void clear() { this.mQueue.clear(); } + @Override + public synchronized String toString() { + return ListUtils.toString(this); + } + // =========================================================== // Methods // =========================================================== diff --git a/src/org/andengine/util/algorithm/path/Direction.java b/src/org/andengine/util/adt/spatial/Direction.java similarity index 92% rename from src/org/andengine/util/algorithm/path/Direction.java rename to src/org/andengine/util/adt/spatial/Direction.java index 488fb153f..deea9bae0 100644 --- a/src/org/andengine/util/algorithm/path/Direction.java +++ b/src/org/andengine/util/adt/spatial/Direction.java @@ -1,9 +1,9 @@ -package org.andengine.util.algorithm.path; +package org.andengine.util.adt.spatial; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 15:19:11 - 17.08.2010 */ @@ -12,14 +12,14 @@ public enum Direction { // Elements // =========================================================== - UP(0, -1), - DOWN(0, 1), + UP(0, 1), + DOWN(0, -1), LEFT(-1, 0), RIGHT(1, 0), - UP_LEFT(-1, -1), - UP_RIGHT(1, -1), - DOWN_LEFT(-1, 1), - DOWN_RIGHT(1, 1); + UP_LEFT(-1, 1), + UP_RIGHT(1, 1), + DOWN_LEFT(-1, -1), + DOWN_RIGHT(1, -1); // =========================================================== // Constants @@ -42,32 +42,32 @@ private Direction(final int pDeltaX, final int pDeltaY) { } public static Direction fromDelta(final int pDeltaX, final int pDeltaY) { - switch(pDeltaX) { + switch (pDeltaX) { case -1: - switch(pDeltaY) { - case -1: + switch (pDeltaY) { + case 1: return UP_LEFT; case 0: return LEFT; - case 1: + case -1: return DOWN_LEFT; } break; case 0: - switch(pDeltaY) { - case -1: - return UP; + switch (pDeltaY) { case 1: + return UP; + case -1: return DOWN; } break; case 1: - switch(pDeltaY) { - case -1: + switch (pDeltaY) { + case 1: return UP_RIGHT; case 0: return RIGHT; - case 1: + case -1: return DOWN_RIGHT; } break; @@ -96,7 +96,7 @@ public int getDeltaY() { } public Direction rotateLeft() { - switch(this) { + switch (this) { case UP: return LEFT; case UP_RIGHT: @@ -118,7 +118,7 @@ public Direction rotateLeft() { } public Direction rotateRight() { - switch(this) { + switch (this) { case UP: return RIGHT; case UP_RIGHT: @@ -140,7 +140,7 @@ public Direction rotateRight() { } public Direction opposite() { - switch(this) { + switch (this) { case UP: return DOWN; case UP_RIGHT: diff --git a/src/org/andengine/util/adt/spatial/ISpatialItem.java b/src/org/andengine/util/adt/spatial/ISpatialItem.java index 79be2f9d8..8f7441dcc 100644 --- a/src/org/andengine/util/adt/spatial/ISpatialItem.java +++ b/src/org/andengine/util/adt/spatial/ISpatialItem.java @@ -4,7 +4,7 @@ /** - * (c) Zynga 2011 + * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 20:23:12 - 07.10.2011 diff --git a/src/org/andengine/util/adt/spatial/bounds/util/FloatBoundsUtils.java b/src/org/andengine/util/adt/spatial/bounds/util/FloatBoundsUtils.java index 377008824..a553aef1e 100644 --- a/src/org/andengine/util/adt/spatial/bounds/util/FloatBoundsUtils.java +++ b/src/org/andengine/util/adt/spatial/bounds/util/FloatBoundsUtils.java @@ -4,7 +4,7 @@ /** - * (c) Zynga 2011 + * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 23:12:02 - 07.10.2011 @@ -22,6 +22,10 @@ public final class FloatBoundsUtils { // Constructors // =========================================================== + private FloatBoundsUtils() { + + } + // =========================================================== // Getter & Setter // =========================================================== @@ -33,7 +37,7 @@ public final class FloatBoundsUtils { // =========================================================== // Methods // =========================================================== - + public static final boolean intersects(final IFloatBounds pFloatBoundsA, final IFloatBounds pFloatBoundsB) { return FloatBoundsUtils.intersects(pFloatBoundsA.getXMin(), pFloatBoundsA.getYMin(), pFloatBoundsA.getXMax(), pFloatBoundsA.getYMax(), pFloatBoundsB.getXMin(), pFloatBoundsB.getYMin(), pFloatBoundsB.getXMax(), pFloatBoundsB.getYMax()); } @@ -47,7 +51,7 @@ public static final boolean intersects(final float pXMinA, final float pYMinA, f public static final boolean contains(final IFloatBounds pFloatBounds, final float pX, final float pY) { return FloatBoundsUtils.contains(pFloatBounds.getXMin(), pFloatBounds.getYMin(), pFloatBounds.getXMax(), pFloatBounds.getYMax(), pX, pY); } - + public static final boolean contains(final IFloatBounds pFloatBoundsA, final IFloatBounds pFloatBoundsB) { return FloatBoundsUtils.contains(pFloatBoundsA.getXMin(), pFloatBoundsA.getYMin(), pFloatBoundsA.getXMax(), pFloatBoundsA.getYMax(), pFloatBoundsB.getXMin(), pFloatBoundsB.getYMin(), pFloatBoundsB.getXMax(), pFloatBoundsB.getYMax()); } diff --git a/src/org/andengine/util/adt/spatial/bounds/util/IntBoundsUtils.java b/src/org/andengine/util/adt/spatial/bounds/util/IntBoundsUtils.java index 4845d14e8..e5299f0d8 100644 --- a/src/org/andengine/util/adt/spatial/bounds/util/IntBoundsUtils.java +++ b/src/org/andengine/util/adt/spatial/bounds/util/IntBoundsUtils.java @@ -4,7 +4,7 @@ /** - * (c) Zynga 2011 + * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 17:05:32 - 08.10.2011 @@ -22,6 +22,10 @@ public final class IntBoundsUtils { // Constructors // =========================================================== + private IntBoundsUtils() { + + } + // =========================================================== // Getter & Setter // =========================================================== @@ -33,7 +37,7 @@ public final class IntBoundsUtils { // =========================================================== // Methods // =========================================================== - + public static final boolean intersects(final IIntBounds pIntBoundsA, final IIntBounds pIntBoundsB) { return IntBoundsUtils.intersects(pIntBoundsA.getXMin(), pIntBoundsA.getYMin(), pIntBoundsA.getXMax(), pIntBoundsA.getYMax(), pIntBoundsB.getXMin(), pIntBoundsB.getYMin(), pIntBoundsB.getXMax(), pIntBoundsB.getYMax()); } @@ -43,15 +47,15 @@ public static final boolean intersects(final int pXMinA, final int pYMinA, final || IntBoundsUtils.contains(pXMinA, pYMinA, pXMaxA, pYMaxA, pXMinB, pYMinB, pXMaxB, pYMaxB) || IntBoundsUtils.contains(pXMinB, pYMinB, pXMaxB, pYMaxB, pXMinA, pYMinA, pXMaxA, pYMaxA); } - + public static final boolean contains(final IIntBounds pIntBoundsA, final IIntBounds pIntBoundsB) { return IntBoundsUtils.contains(pIntBoundsA.getXMin(), pIntBoundsA.getYMin(), pIntBoundsA.getXMax(), pIntBoundsA.getYMax(), pIntBoundsB.getXMin(), pIntBoundsB.getYMin(), pIntBoundsB.getXMax(), pIntBoundsB.getYMax()); } - + public static final boolean contains(final IIntBounds pIntBounds, final int pX, final int pY) { return IntBoundsUtils.contains(pIntBounds.getXMin(), pIntBounds.getYMin(), pIntBounds.getXMax(), pIntBounds.getYMax(), pX, pY); } - + public static final boolean contains(final IIntBounds pIntBounds, final int pXMin, final int pYMin, final int pXMax, final int pYMax) { return IntBoundsUtils.contains(pIntBounds.getXMin(), pIntBounds.getYMin(), pIntBounds.getXMax(), pIntBounds.getYMax(), pXMin, pYMin, pXMax, pYMax); } diff --git a/src/org/andengine/util/adt/spatial/quadtree/FloatQuadTree.java b/src/org/andengine/util/adt/spatial/quadtree/FloatQuadTree.java index bc8c6fef5..546eb9c71 100644 --- a/src/org/andengine/util/adt/spatial/quadtree/FloatQuadTree.java +++ b/src/org/andengine/util/adt/spatial/quadtree/FloatQuadTree.java @@ -12,7 +12,7 @@ /** - * (c) Zynga 2011 + * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 20:15:21 - 10.10.2011 @@ -195,10 +195,10 @@ public FloatQuadTreeNode(final int pLevel, final float pXMin, final float pYMin, this.mXMax = pXMax; this.mYMax = pYMax; - if(pXMin > pXMax) { + if (pXMin > pXMax) { throw new IllegalArgumentException("pXMin must be smaller or equal to pXMax."); } - if(pYMin > pYMax) { + if (pYMin > pYMax) { throw new IllegalArgumentException("pYMin must be smaller or equal to pYMax."); } } @@ -285,7 +285,7 @@ protected void appendBoundsToString(final StringBuilder pStringBuilder) { .append(this.mXMax) .append(", YMax: ") .append(this.mYMax) - .append("]"); + .append(']'); } // =========================================================== @@ -295,7 +295,7 @@ protected void appendBoundsToString(final StringBuilder pStringBuilder) { private float getXMin(final BoundsSplit pBoundsSplit) { final float halfWidth = this.getWidth() / 2; - switch(pBoundsSplit) { + switch (pBoundsSplit) { case TOP_LEFT: return this.mXMin; case TOP_RIGHT: @@ -312,7 +312,7 @@ private float getXMin(final BoundsSplit pBoundsSplit) { private float getYMin(final BoundsSplit pBoundsSplit) { final float halfHeight = this.getHeight() / 2; - switch(pBoundsSplit) { + switch (pBoundsSplit) { case TOP_LEFT: return this.mYMin; case TOP_RIGHT: @@ -325,11 +325,11 @@ private float getYMin(final BoundsSplit pBoundsSplit) { throw new IllegalArgumentException("Unexpected " + BoundsSplit.class.getSimpleName() + ": '" + pBoundsSplit + "'."); } } - + private float getXMax(final BoundsSplit pBoundsSplit) { final float halfWidth = this.getWidth() / 2; - - switch(pBoundsSplit) { + + switch (pBoundsSplit) { case TOP_LEFT: return this.mXMin + halfWidth; case TOP_RIGHT: @@ -346,7 +346,7 @@ private float getXMax(final BoundsSplit pBoundsSplit) { private float getYMax(final BoundsSplit pBoundsSplit) { final float halfHeight = this.getHeight() / 2; - switch(pBoundsSplit) { + switch (pBoundsSplit) { case TOP_LEFT: return this.mYMin + halfHeight; case TOP_RIGHT: diff --git a/src/org/andengine/util/adt/spatial/quadtree/IntQuadTree.java b/src/org/andengine/util/adt/spatial/quadtree/IntQuadTree.java index 5504c8e62..d6316050c 100644 --- a/src/org/andengine/util/adt/spatial/quadtree/IntQuadTree.java +++ b/src/org/andengine/util/adt/spatial/quadtree/IntQuadTree.java @@ -13,7 +13,7 @@ /** - * (c) Zynga 2011 + * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 20:22:18 - 10.10.2011 @@ -196,10 +196,10 @@ public IntQuadTreeNode(final int pLevel, final int pXMin, final int pYMin, final this.mXMax = pXMax; this.mYMax = pYMax; - if(pXMin > pXMax) { + if (pXMin > pXMax) { throw new IllegalArgumentException("pXMin must be smaller or equal to pXMax."); } - if(pYMin > pYMax) { + if (pYMin > pYMax) { throw new IllegalArgumentException("pYMin must be smaller or equal to pYMax."); } } @@ -212,7 +212,7 @@ public IntQuadTreeNode(final int pLevel, final int pXMin, final int pYMin, final public int getXMin() { return this.mXMin; } - + @Override public int getYMin() { return this.mYMin; @@ -245,7 +245,7 @@ protected IntQuadTreeNode split(final BoundsSplit pBoundsSplit) { final int width = this.getWidth(); final int height = this.getHeight(); - if(width <= 2 && height <= 2) { + if (width <= 2 && height <= 2) { throw new BoundsSplitException(); } @@ -293,7 +293,7 @@ protected void appendBoundsToString(final StringBuilder pStringBuilder) { .append(this.mXMax) .append(", YMax: ") .append(this.mYMax) - .append("]"); + .append(']'); } // =========================================================== @@ -304,8 +304,8 @@ private int getXMin(final BoundsSplit pBoundsSplit) { final int width = this.getWidth(); final int halfWidth = width / 2; - if(width <= 2) { - switch(pBoundsSplit) { + if (width <= 2) { + switch (pBoundsSplit) { case TOP_LEFT: case BOTTOM_LEFT: return this.mXMin; @@ -316,7 +316,7 @@ private int getXMin(final BoundsSplit pBoundsSplit) { throw new IllegalArgumentException("Unexpected " + BoundsSplit.class.getSimpleName() + ": '" + pBoundsSplit + "'."); } } else { - switch(pBoundsSplit) { + switch (pBoundsSplit) { case TOP_LEFT: return this.mXMin; case TOP_RIGHT: @@ -330,16 +330,16 @@ private int getXMin(final BoundsSplit pBoundsSplit) { } } } - + private int getYMin(final BoundsSplit pBoundsSplit) { final int height = this.getHeight(); final int halfHeight = height / 2; - - if(height <= 2) { - switch(pBoundsSplit) { + + if (height <= 2) { + switch (pBoundsSplit) { case TOP_LEFT: case TOP_RIGHT: - return this.mYMin; + return this.mYMin; case BOTTOM_LEFT: case BOTTOM_RIGHT: throw new BoundsSplitException(); @@ -347,9 +347,9 @@ private int getYMin(final BoundsSplit pBoundsSplit) { throw new IllegalArgumentException("Unexpected " + BoundsSplit.class.getSimpleName() + ": '" + pBoundsSplit + "'."); } } else { - switch(pBoundsSplit) { + switch (pBoundsSplit) { case TOP_LEFT: - return this.mYMin; + return this.mYMin; case TOP_RIGHT: return this.mYMin; case BOTTOM_LEFT: @@ -366,8 +366,8 @@ private int getXMax(final BoundsSplit pBoundsSplit) { final int width = this.getWidth(); final int halfWidth = width / 2; - if(width <= 2) { - switch(pBoundsSplit) { + if (width <= 2) { + switch (pBoundsSplit) { case TOP_LEFT: case BOTTOM_LEFT: return this.mXMax; @@ -378,7 +378,7 @@ private int getXMax(final BoundsSplit pBoundsSplit) { throw new IllegalArgumentException("Unexpected " + BoundsSplit.class.getSimpleName() + ": '" + pBoundsSplit + "'."); } } else { - switch(pBoundsSplit) { + switch (pBoundsSplit) { case TOP_LEFT: return this.mXMin + halfWidth; case TOP_RIGHT: @@ -397,8 +397,8 @@ private int getYMax(final BoundsSplit pBoundsSplit) { final int height = this.getHeight(); final int halfHeight = height / 2; - if(height <= 2) { - switch(pBoundsSplit) { + if (height <= 2) { + switch (pBoundsSplit) { case TOP_LEFT: case TOP_RIGHT: return this.mYMax; @@ -409,7 +409,7 @@ private int getYMax(final BoundsSplit pBoundsSplit) { throw new IllegalArgumentException("Unexpected " + BoundsSplit.class.getSimpleName() + ": '" + pBoundsSplit + "'."); } } else { - switch(pBoundsSplit) { + switch (pBoundsSplit) { case TOP_LEFT: return this.mYMin + halfHeight; case TOP_RIGHT: diff --git a/src/org/andengine/util/adt/spatial/quadtree/QuadTree.java b/src/org/andengine/util/adt/spatial/quadtree/QuadTree.java index e5a632082..1acd9de35 100644 --- a/src/org/andengine/util/adt/spatial/quadtree/QuadTree.java +++ b/src/org/andengine/util/adt/spatial/quadtree/QuadTree.java @@ -15,9 +15,9 @@ import org.andengine.util.exception.AndEngineRuntimeException; /** - * TODO Make all methods non-synchronized and add a SynchronizedXZYQuadTree subclasses. + * TODO Make all methods non-synchronized and add a SynchronizedXZYQuadTree subclasses. * - * (c) Zynga 2011 + * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 20:16:01 - 07.10.2011 @@ -120,27 +120,27 @@ public synchronized void add(final T pItem) { } public synchronized void addAll(final T ... pItems) { - for(final T item : pItems) { + for (final T item : pItems) { this.add(item); } } public synchronized void addAll(final ArrayList pItems) { final int itemCount = pItems.size(); - for(int i = 0; i < itemCount; i++) { + for (int i = 0; i < itemCount; i++) { this.add(pItems.get(i)); } } public synchronized void addAll(final Collection pItems) { - for(final T item : pItems) { + for (final T item : pItems) { this.add(item); } } @Deprecated public synchronized void add(final T pItem, final B pBounds) { - if(!this.mRoot.contains(pBounds)) { + if (!this.mRoot.contains(pBounds)) { Debug.w("pBounds are out of the bounds of this " + this.getClass().getSimpleName() + "."); this.mRoot.addItemSafe(pItem); return; @@ -156,7 +156,7 @@ public synchronized void add(final T pItem, final B pBounds) { */ public synchronized void move(final T pItem, final B pBounds) throws AndEngineRuntimeException { final boolean success = this.remove(pItem, pBounds); - if(!success) { + if (!success) { throw new AndEngineRuntimeException("Failed to remove item: '" + pItem.toString() + " from old bounds: '" + pBounds.toString() + "'."); } this.add(pItem); @@ -172,7 +172,7 @@ public synchronized void move(final T pItem, final B pBounds) throws AndEngineRu @Deprecated public synchronized void move(final T pItem, final B pOldBounds, final B pNewBounds) throws AndEngineRuntimeException { final boolean success = this.remove(pItem, pOldBounds); - if(!success) { + if (!success) { throw new AndEngineRuntimeException("Failed to remove item: '" + pItem.toString() + " from old bounds: '" + pOldBounds.toString() + "'."); } this.add(pItem, pNewBounds); @@ -308,7 +308,7 @@ public String toString(final int pIndent) { .append('\t') .append("Level: ") .append(this.mLevel) - .append(',' ) + .append(',') .append('\n') .append(indents) .append('\t') @@ -316,12 +316,12 @@ public String toString(final int pIndent) { this.appendBoundsToString(sb); - sb.append(',' ) + sb.append(',') .append('\n') .append(indents) .append("\tItems: "); - if(this.mItems != null) { + if (this.mItems != null) { sb.append(this.mItems.toString()); } else { sb.append("[]"); @@ -333,31 +333,31 @@ public String toString(final int pIndent) { .append("Children: ["); /* Children */ - if(this.mTopLeftChild == null && this.mTopRightChild == null && this.mBottomLeftChild == null && this.mBottomRightChild == null) { + if (this.mTopLeftChild == null && this.mTopRightChild == null && this.mBottomLeftChild == null && this.mBottomRightChild == null) { sb.append(']'); } else { - if(this.mTopLeftChild != null) { + if (this.mTopLeftChild != null) { sb.append('\n'); sb.append(this.mTopLeftChild.toString(pIndent + 2)); - if(this.mTopRightChild != null || this.mBottomLeftChild != null || this.mBottomRightChild != null) { + if (this.mTopRightChild != null || this.mBottomLeftChild != null || this.mBottomRightChild != null) { sb.append(','); } } - if(this.mTopRightChild != null) { + if (this.mTopRightChild != null) { sb.append('\n'); sb.append(this.mTopRightChild.toString(pIndent + 2)); - if(this.mBottomLeftChild != null || this.mBottomRightChild != null) { + if (this.mBottomLeftChild != null || this.mBottomRightChild != null) { sb.append(','); } } - if(this.mBottomLeftChild != null) { + if (this.mBottomLeftChild != null) { sb.append('\n'); sb.append(this.mBottomLeftChild.toString(pIndent + 2)); - if(this.mBottomRightChild != null) { + if (this.mBottomRightChild != null) { sb.append(','); } } - if(this.mBottomRightChild != null) { + if (this.mBottomRightChild != null) { sb.append('\n'); sb.append(this.mBottomRightChild.toString(pIndent + 2)); } @@ -380,22 +380,22 @@ public String toString(final int pIndent) { public int getItemCount() { int count; - if(this.mItems == null) { + if (this.mItems == null) { count = 0; } else { count = this.mItems.size(); } - if(this.mTopLeftChild != null) { + if (this.mTopLeftChild != null) { count += this.mTopLeftChild.getItemCount(); } - if(this.mTopRightChild != null) { + if (this.mTopRightChild != null) { count += this.mTopRightChild.getItemCount(); } - if(this.mBottomLeftChild != null) { + if (this.mBottomLeftChild != null) { count += this.mBottomLeftChild.getItemCount(); } - if(this.mBottomRightChild != null) { + if (this.mBottomRightChild != null) { count += this.mBottomRightChild.getItemCount(); } @@ -403,24 +403,24 @@ public int getItemCount() { } public void callItems(final ParameterCallable pParameterCallable) { - if(this.mItems != null) { + if (this.mItems != null) { final int itemCount = this.mItems.size(); - for(int i = 0; i < itemCount; i++) { + for (int i = 0; i < itemCount; i++) { final T item = this.mItems.get(i); pParameterCallable.call(item); } } - if(this.mTopLeftChild != null) { + if (this.mTopLeftChild != null) { this.mTopLeftChild.callItems(pParameterCallable); } - if(this.mTopRightChild != null) { + if (this.mTopRightChild != null) { this.mTopRightChild.callItems(pParameterCallable); } - if(this.mBottomLeftChild != null) { + if (this.mBottomLeftChild != null) { this.mBottomLeftChild.callItems(pParameterCallable); } - if(this.mBottomRightChild != null) { + if (this.mBottomRightChild != null) { this.mBottomRightChild.callItems(pParameterCallable); } } @@ -428,16 +428,16 @@ public void callItems(final ParameterCallable pParameterCallable) { public void callNodes(final ParameterCallable pParameterCallable) { pParameterCallable.call(this); - if(this.mTopLeftChild != null) { + if (this.mTopLeftChild != null) { this.mTopLeftChild.callNodes(pParameterCallable); } - if(this.mTopRightChild != null) { + if (this.mTopRightChild != null) { this.mTopRightChild.callNodes(pParameterCallable); } - if(this.mBottomLeftChild != null) { + if (this.mBottomLeftChild != null) { this.mBottomLeftChild.callNodes(pParameterCallable); } - if(this.mBottomRightChild != null) { + if (this.mBottomRightChild != null) { this.mBottomRightChild.callNodes(pParameterCallable); } } @@ -450,20 +450,20 @@ public ArrayList getItemsAndItemsBelow() { * @return the items of this {@link QuadTreeNode} and all children (recursively). */ public > L getItemsAndItemsBelow(final L pResult) { - if(this.mItems != null) { + if (this.mItems != null) { pResult.addAll(this.mItems); // TODO Does addAll use an iterator internally? } - if(this.mTopLeftChild != null) { + if (this.mTopLeftChild != null) { this.mTopLeftChild.getItemsAndItemsBelow(pResult); } - if(this.mTopRightChild != null) { + if (this.mTopRightChild != null) { this.mTopRightChild.getItemsAndItemsBelow(pResult); } - if(this.mBottomLeftChild != null) { + if (this.mBottomLeftChild != null) { this.mBottomLeftChild.getItemsAndItemsBelow(pResult); } - if(this.mBottomRightChild != null) { + if (this.mBottomRightChild != null) { this.mBottomRightChild.getItemsAndItemsBelow(pResult); } @@ -475,24 +475,24 @@ public ArrayList getItemsAndItemsBelow(final IMatcher pMatcher) { } public > L getItemsAndItemsBelow(final IMatcher pMatcher, final L pResult) { - if(this.mItems != null) { - for(final T item : this.mItems) { // TODO Check if iteration is allocation free. - if(pMatcher.matches(item)) { + if (this.mItems != null) { + for (final T item : this.mItems) { // TODO Check if iteration is allocation free. + if (pMatcher.matches(item)) { pResult.add(item); } } } - if(this.mTopLeftChild != null) { + if (this.mTopLeftChild != null) { this.mTopLeftChild.getItemsAndItemsBelow(pMatcher, pResult); } - if(this.mTopRightChild != null) { + if (this.mTopRightChild != null) { this.mTopRightChild.getItemsAndItemsBelow(pMatcher, pResult); } - if(this.mBottomLeftChild != null) { + if (this.mBottomLeftChild != null) { this.mBottomLeftChild.getItemsAndItemsBelow(pMatcher, pResult); } - if(this.mBottomRightChild != null) { + if (this.mBottomRightChild != null) { this.mBottomRightChild.getItemsAndItemsBelow(pMatcher, pResult); } @@ -501,26 +501,26 @@ public > L getItemsAndItemsBelow(final IMatcher pMatcher, f @SuppressWarnings("unchecked") public , S extends T> L getItemsAndItemsBelowForSubclass(final IMatcher pMatcher, final L pResult) throws ClassCastException { - if(this.mItems != null) { + if (this.mItems != null) { final int itemCount = this.mItems.size(); - for(int i = 0; i < itemCount; i++) { + for (int i = 0; i < itemCount; i++) { final T item = this.mItems.get(i); - if(pMatcher.matches(item)) { - pResult.add((S)item); + if (pMatcher.matches(item)) { + pResult.add((S) item); } } } - if(this.mTopLeftChild != null) { + if (this.mTopLeftChild != null) { this.mTopLeftChild.getItemsAndItemsBelowForSubclass(pMatcher, pResult); } - if(this.mTopRightChild != null) { + if (this.mTopRightChild != null) { this.mTopRightChild.getItemsAndItemsBelowForSubclass(pMatcher, pResult); } - if(this.mBottomLeftChild != null) { + if (this.mBottomLeftChild != null) { this.mBottomLeftChild.getItemsAndItemsBelowForSubclass(pMatcher, pResult); } - if(this.mBottomRightChild != null) { + if (this.mBottomRightChild != null) { this.mBottomRightChild.getItemsAndItemsBelowForSubclass(pMatcher, pResult); } @@ -533,24 +533,24 @@ public ArrayList query(final B pBounds) { public > L query(final B pBounds, final L pResult) { /* Test against all items in this node. */ - if(this.mItems != null) { + if (this.mItems != null) { final int itemCount = this.mItems.size(); - for(int i = 0; i < itemCount; i++) { + for (int i = 0; i < itemCount; i++) { final T item = this.mItems.get(i); - if(this.intersects(pBounds, item.getBounds())) { + if (this.intersects(pBounds, item.getBounds())) { pResult.add(item); } } } /* Check children. */ - if(this.queryChild(pBounds, pResult, this.mTopLeftChild)) { + if (this.queryChild(pBounds, pResult, this.mTopLeftChild)) { return pResult; - } else if(this.queryChild(pBounds, pResult, this.mTopRightChild)) { + } else if (this.queryChild(pBounds, pResult, this.mTopRightChild)) { return pResult; - } else if(this.queryChild(pBounds, pResult, this.mBottomLeftChild)) { + } else if (this.queryChild(pBounds, pResult, this.mBottomLeftChild)) { return pResult; - } else if(this.queryChild(pBounds, pResult, this.mBottomRightChild)) { + } else if (this.queryChild(pBounds, pResult, this.mBottomRightChild)) { return pResult; } else { return pResult; @@ -559,22 +559,22 @@ public > L query(final B pBounds, final L pResult) { public > L query(final B pBounds, final IMatcher pMatcher, final L pResult) { /* Test against all items in this node. */ - if(this.mItems != null) { - for(final T item : this.mItems) { - if(this.intersects(pBounds, item.getBounds()) && pMatcher.matches(item)) { + if (this.mItems != null) { + for (final T item : this.mItems) { + if (this.intersects(pBounds, item.getBounds()) && pMatcher.matches(item)) { pResult.add(item); } } } /* Check children. */ - if(this.queryChild(pBounds, pMatcher, pResult, this.mTopLeftChild)) { + if (this.queryChild(pBounds, pMatcher, pResult, this.mTopLeftChild)) { return pResult; - } else if(this.queryChild(pBounds, pMatcher, pResult, this.mTopRightChild)) { + } else if (this.queryChild(pBounds, pMatcher, pResult, this.mTopRightChild)) { return pResult; - } else if(this.queryChild(pBounds, pMatcher, pResult, this.mBottomLeftChild)) { + } else if (this.queryChild(pBounds, pMatcher, pResult, this.mBottomLeftChild)) { return pResult; - } else if(this.queryChild(pBounds, pMatcher, pResult, this.mBottomRightChild)) { + } else if (this.queryChild(pBounds, pMatcher, pResult, this.mBottomRightChild)) { return pResult; } else { return pResult; @@ -584,22 +584,22 @@ public > L query(final B pBounds, final IMatcher pMatcher, @SuppressWarnings("unchecked") public , S extends T> L queryForSubclass(final B pBounds, final IMatcher pMatcher, final L pResult) throws ClassCastException { /* Test against all items in this node. */ - if(this.mItems != null) { - for(final T item : this.mItems) { - if(this.intersects(pBounds, item.getBounds()) && pMatcher.matches(item)) { - pResult.add((S)item); + if (this.mItems != null) { + for (final T item : this.mItems) { + if (this.intersects(pBounds, item.getBounds()) && pMatcher.matches(item)) { + pResult.add((S) item); } } } /* Check children. */ - if(this.queryChildForSubclass(pBounds, pMatcher, pResult, this.mTopLeftChild)) { + if (this.queryChildForSubclass(pBounds, pMatcher, pResult, this.mTopLeftChild)) { return pResult; - } else if(this.queryChildForSubclass(pBounds, pMatcher, pResult, this.mTopRightChild)) { + } else if (this.queryChildForSubclass(pBounds, pMatcher, pResult, this.mTopRightChild)) { return pResult; - } else if(this.queryChildForSubclass(pBounds, pMatcher, pResult, this.mBottomLeftChild)) { + } else if (this.queryChildForSubclass(pBounds, pMatcher, pResult, this.mBottomLeftChild)) { return pResult; - } else if(this.queryChildForSubclass(pBounds, pMatcher, pResult, this.mBottomRightChild)) { + } else if (this.queryChildForSubclass(pBounds, pMatcher, pResult, this.mBottomRightChild)) { return pResult; } else { return pResult; @@ -613,18 +613,18 @@ public , S extends T> L queryForSubclass(final B pBounds, fina * @return true when the child contains pBounds, false otherwise. */ private > boolean queryChild(final B pBounds, final L pResult, final QuadTreeNode pChild) { - if(pChild == null) { + if (pChild == null) { return false; } - if(pChild.contains(pBounds)) { + if (pChild.contains(pBounds)) { pChild.query(pBounds, pResult); return true; } - if(pChild.containedBy(pBounds)) { + if (pChild.containedBy(pBounds)) { pChild.getItemsAndItemsBelow(pResult); - } else if(pChild.intersects(pBounds)) { + } else if (pChild.intersects(pBounds)) { pChild.query(pBounds, pResult); } @@ -639,18 +639,18 @@ private > boolean queryChild(final B pBounds, final L pResult, * @return true when the child contains pBounds, false otherwise. */ private > boolean queryChild(final B pBounds, final IMatcher pMatcher, final L pResult, final QuadTreeNode pChild) { - if(pChild == null) { + if (pChild == null) { return false; } - if(pChild.contains(pBounds)) { + if (pChild.contains(pBounds)) { pChild.query(pBounds, pMatcher, pResult); return true; } - if(pChild.containedBy(pBounds)) { + if (pChild.containedBy(pBounds)) { pChild.getItemsAndItemsBelow(pMatcher, pResult); - } else if(pChild.intersects(pBounds)) { + } else if (pChild.intersects(pBounds)) { pChild.query(pBounds, pMatcher, pResult); } @@ -665,18 +665,18 @@ private > boolean queryChild(final B pBounds, final IMatchertrue when the child contains pBounds, false otherwise. */ private , S extends T> boolean queryChildForSubclass(final B pBounds, final IMatcher pMatcher, final L pResult, final QuadTreeNode pChild) throws ClassCastException { - if(pChild == null) { + if (pChild == null) { return false; } - if(pChild.contains(pBounds)) { + if (pChild.contains(pBounds)) { pChild.queryForSubclass(pBounds, pMatcher, pResult); return true; } - if(pChild.containedBy(pBounds)) { + if (pChild.containedBy(pBounds)) { pChild.getItemsAndItemsBelowForSubclass(pMatcher, pResult); - } else if(pChild.intersects(pBounds)) { + } else if (pChild.intersects(pBounds)) { pChild.queryForSubclass(pBounds, pMatcher, pResult); } @@ -685,24 +685,24 @@ private , S extends T> boolean queryChildForSubclass(final B p public boolean containsAny(final B pBounds, final IMatcher pMatcher) { /* Test against all items in this node. */ - if(this.mItems != null) { + if (this.mItems != null) { final int itemCount = this.mItems.size(); - for(int i = 0; i < itemCount; i++) { + for (int i = 0; i < itemCount; i++) { final T item = this.mItems.get(i); - if(this.intersects(pBounds, item.getBounds()) && pMatcher.matches(item)) { + if (this.intersects(pBounds, item.getBounds()) && pMatcher.matches(item)) { return true; } } } /* Check children. */ - if(this.containsAnyChild(pBounds, pMatcher, this.mTopLeftChild)) { + if (this.containsAnyChild(pBounds, pMatcher, this.mTopLeftChild)) { return true; - } else if(this.containsAnyChild(pBounds, pMatcher, this.mTopRightChild)) { + } else if (this.containsAnyChild(pBounds, pMatcher, this.mTopRightChild)) { return true; - } else if(this.containsAnyChild(pBounds, pMatcher, this.mBottomLeftChild)) { + } else if (this.containsAnyChild(pBounds, pMatcher, this.mBottomLeftChild)) { return true; - } else if(this.containsAnyChild(pBounds, pMatcher, this.mBottomRightChild)) { + } else if (this.containsAnyChild(pBounds, pMatcher, this.mBottomRightChild)) { return true; } else { return false; @@ -711,24 +711,24 @@ public boolean containsAny(final B pBounds, final IMatcher pMatcher) { public boolean containsAny(final B pBounds) { /* Test against all items in this node. */ - if(this.mItems != null) { + if (this.mItems != null) { final int itemCount = this.mItems.size(); - for(int i = 0; i < itemCount; i++) { + for (int i = 0; i < itemCount; i++) { final T item = this.mItems.get(i); - if(this.intersects(pBounds, item.getBounds())) { + if (this.intersects(pBounds, item.getBounds())) { return true; } } } /* Check children. */ - if(this.containsAnyChild(pBounds, this.mTopLeftChild)) { + if (this.containsAnyChild(pBounds, this.mTopLeftChild)) { return true; - } else if(this.containsAnyChild(pBounds, this.mTopRightChild)) { + } else if (this.containsAnyChild(pBounds, this.mTopRightChild)) { return true; - } else if(this.containsAnyChild(pBounds, this.mBottomLeftChild)) { + } else if (this.containsAnyChild(pBounds, this.mBottomLeftChild)) { return true; - } else if(this.containsAnyChild(pBounds, this.mBottomRightChild)) { + } else if (this.containsAnyChild(pBounds, this.mBottomRightChild)) { return true; } else { return false; @@ -736,11 +736,11 @@ public boolean containsAny(final B pBounds) { } private boolean containsAnyChild(final B pBounds, final IMatcher pMatcher, final QuadTreeNode pChild) { - if(pChild == null) { + if (pChild == null) { return false; } - if(pChild.intersects(pBounds) && pChild.containsAny(pBounds, pMatcher)) { + if (pChild.intersects(pBounds) && pChild.containsAny(pBounds, pMatcher)) { return true; } @@ -748,11 +748,11 @@ private boolean containsAnyChild(final B pBounds, final IMatcher pMatcher, fi } private boolean containsAnyChild(final B pBounds, final QuadTreeNode pChild) { - if(pChild == null) { + if (pChild == null) { return false; } - if(pChild.intersects(pBounds) && pChild.containsAny(pBounds)) { + if (pChild.intersects(pBounds) && pChild.containsAny(pBounds)) { return true; } @@ -761,18 +761,18 @@ private boolean containsAnyChild(final B pBounds, final QuadTreeNode pChild) { public void add(final T pItem, final B pBounds) throws IllegalArgumentException { /* Check if this node is in the maximum level. */ - if(this.mLevel >= QuadTree.this.mMaxLevel) { + if (this.mLevel >= QuadTree.this.mMaxLevel) { /* No more levels allowed, so this node has to take the item. */ this.addItemSafe(pItem); return; } /* If the node contains the item, add the item to that node. */ - if(this.mTopLeftChild != null && this.mTopLeftChild.contains(pBounds)) { + if (this.mTopLeftChild != null && this.mTopLeftChild.contains(pBounds)) { this.mTopLeftChild.add(pItem, pBounds); return; - } else if(this.contains(BoundsSplit.TOP_LEFT, pBounds)) { - if(this.mTopLeftChild == null) { + } else if (this.contains(BoundsSplit.TOP_LEFT, pBounds)) { + if (this.mTopLeftChild == null) { try { this.mTopLeftChild = this.split(BoundsSplit.TOP_LEFT); this.mTopLeftChild.add(pItem, pBounds); @@ -783,11 +783,11 @@ public void add(final T pItem, final B pBounds) throws IllegalArgumentException } } - if(this.mTopRightChild != null && this.mTopRightChild.contains(pBounds)) { + if (this.mTopRightChild != null && this.mTopRightChild.contains(pBounds)) { this.mTopRightChild.add(pItem, pBounds); return; - } else if(this.contains(BoundsSplit.TOP_RIGHT, pBounds)) { - if(this.mTopRightChild == null) { + } else if (this.contains(BoundsSplit.TOP_RIGHT, pBounds)) { + if (this.mTopRightChild == null) { try { this.mTopRightChild = this.split(BoundsSplit.TOP_RIGHT); this.mTopRightChild.add(pItem, pBounds); @@ -798,11 +798,11 @@ public void add(final T pItem, final B pBounds) throws IllegalArgumentException } } - if(this.mBottomLeftChild != null && this.mBottomLeftChild.contains(pBounds)) { + if (this.mBottomLeftChild != null && this.mBottomLeftChild.contains(pBounds)) { this.mBottomLeftChild.add(pItem, pBounds); return; - } else if(this.contains(BoundsSplit.BOTTOM_LEFT, pBounds)) { - if(this.mBottomLeftChild == null) { + } else if (this.contains(BoundsSplit.BOTTOM_LEFT, pBounds)) { + if (this.mBottomLeftChild == null) { try { this.mBottomLeftChild = this.split(BoundsSplit.BOTTOM_LEFT); this.mBottomLeftChild.add(pItem, pBounds); @@ -813,11 +813,11 @@ public void add(final T pItem, final B pBounds) throws IllegalArgumentException } } - if(this.mBottomRightChild != null && this.mBottomRightChild.contains(pBounds)) { + if (this.mBottomRightChild != null && this.mBottomRightChild.contains(pBounds)) { this.mBottomRightChild.add(pItem, pBounds); return; - } else if(this.contains(BoundsSplit.BOTTOM_RIGHT, pBounds)) { - if(this.mBottomRightChild == null) { + } else if (this.contains(BoundsSplit.BOTTOM_RIGHT, pBounds)) { + if (this.mBottomRightChild == null) { try { this.mBottomRightChild = this.split(BoundsSplit.BOTTOM_RIGHT); this.mBottomRightChild.add(pItem, pBounds); @@ -837,22 +837,22 @@ public boolean remove(final T pItem) throws IllegalArgumentException { } public boolean remove(final T pItem, final B pBounds) throws IllegalArgumentException { - if(!this.contains(pBounds)) { // TODO Perform this check only for the root? + if (!this.contains(pBounds)) { // TODO Perform this check only for the root? throw new IllegalArgumentException("pItem (" + pItem.toString() + ") is out of the bounds of this " + this.getClass().getSimpleName() + "."); } /* If there are no children, try to remove from self. */ - if(this.mTopLeftChild != null && this.mTopLeftChild.contains(pBounds)) { + if (this.mTopLeftChild != null && this.mTopLeftChild.contains(pBounds)) { return this.mTopLeftChild.remove(pItem, pBounds); - } else if(this.mTopRightChild != null && this.mTopRightChild.contains(pBounds)) { + } else if (this.mTopRightChild != null && this.mTopRightChild.contains(pBounds)) { return this.mTopRightChild.remove(pItem, pBounds); - } else if(this.mBottomLeftChild != null && this.mBottomLeftChild.contains(pBounds)) { + } else if (this.mBottomLeftChild != null && this.mBottomLeftChild.contains(pBounds)) { return this.mBottomLeftChild.remove(pItem, pBounds); - } else if(this.mBottomRightChild != null && this.mBottomRightChild.contains(pBounds)) { + } else if (this.mBottomRightChild != null && this.mBottomRightChild.contains(pBounds)) { return this.mBottomRightChild.remove(pItem, pBounds); } else { /* None of the children completely contained the item. */ - if(this.mItems == null) { + if (this.mItems == null) { return false; } else { // TODO Potentially mItems could be set to null when its size is 0. @@ -862,31 +862,31 @@ public boolean remove(final T pItem, final B pBounds) throws IllegalArgumentExce } private void addItemSafe(final T pItem) { - if(this.mItems == null) { + if (this.mItems == null) { this.mItems = new ArrayList(1); } this.mItems.add(pItem); } protected void clear() { - if(this.mBottomLeftChild != null) { + if (this.mBottomLeftChild != null) { this.mBottomLeftChild.clear(); this.mBottomLeftChild = null; } - if(this.mBottomRightChild != null) { + if (this.mBottomRightChild != null) { this.mBottomRightChild.clear(); this.mBottomRightChild = null; } - if(this.mTopLeftChild != null) { + if (this.mTopLeftChild != null) { this.mTopLeftChild.clear(); this.mTopLeftChild = null; } - if(this.mTopRightChild != null) { + if (this.mTopRightChild != null) { this.mTopRightChild.clear(); this.mTopRightChild = null; } - if(this.mItems != null) { + if (this.mItems != null) { this.mItems.clear(); this.mItems = null; } diff --git a/src/org/andengine/util/adt/transformation/Transformation.java b/src/org/andengine/util/adt/transformation/Transformation.java index 8e1f0b36c..9ad1761f9 100644 --- a/src/org/andengine/util/adt/transformation/Transformation.java +++ b/src/org/andengine/util/adt/transformation/Transformation.java @@ -2,14 +2,12 @@ import org.andengine.util.math.MathConstants; -import android.util.FloatMath; - /** *

    This class is basically a java-space replacement for the native {@link android.graphics.Matrix} class.

    - * + * *

    Math taken from senocular.com.

    - * + * * This class represents an affine transformation with the following matrix: *
     [ a , b , 0 ]
      * [ c , d , 0 ]
    @@ -26,7 +24,7 @@
      *
      * (c) 2010 Nicolas Gramlich
      * (c) 2011 Zynga Inc.
    - * 
    + *
      * @author Nicolas Gramlich
      * @since 15:47:18 - 23.12.2010
      */
    @@ -119,8 +117,8 @@ public final Transformation setToTranslate(final float pX, final float pY) {
     	public final void preRotate(final float pAngle) {
     		final float angleRad = MathConstants.DEG_TO_RAD * pAngle;
     
    -		final float sin = FloatMath.sin(angleRad);
    -		final float cos = FloatMath.cos(angleRad);
    +		final float sin = (float) Math.sin(angleRad);
    +		final float cos = (float) Math.cos(angleRad);
     
     		final float a = this.a;
     		final float b = this.b;
    @@ -136,8 +134,8 @@ public final void preRotate(final float pAngle) {
     	public final void postRotate(final float pAngle) {
     		final float angleRad = MathConstants.DEG_TO_RAD * pAngle;
     
    -		final float sin = FloatMath.sin(angleRad);
    -		final float cos = FloatMath.cos(angleRad);
    +		final float sin = (float) Math.sin(angleRad);
    +		final float cos = (float) Math.cos(angleRad);
     
     		final float a = this.a;
     		final float b = this.b;
    @@ -157,8 +155,8 @@ public final void postRotate(final float pAngle) {
     	public final Transformation setToRotate(final float pAngle) {
     		final float angleRad = MathConstants.DEG_TO_RAD * pAngle;
     
    -		final float sin = FloatMath.sin(angleRad);
    -		final float cos = FloatMath.cos(angleRad);
    +		final float sin = (float) Math.sin(angleRad);
    +		final float cos = (float) Math.cos(angleRad);
     
     		this.a = cos;
     		this.b = sin;
    @@ -290,7 +288,7 @@ public final void transform(final float[] pVertices) {
     		int count = pVertices.length >> 1;
     		int i = 0;
     		int j = 0;
    -		while(--count >= 0) {
    +		while (--count >= 0) {
     			final float x = pVertices[i++];
     			final float y = pVertices[i++];
     			pVertices[j++] = x * this.a + y * this.c + this.tx;
    diff --git a/src/org/andengine/util/adt/transformation/TransformationPool.java b/src/org/andengine/util/adt/transformation/TransformationPool.java
    index b7a0ba982..6f245c44a 100644
    --- a/src/org/andengine/util/adt/transformation/TransformationPool.java
    +++ b/src/org/andengine/util/adt/transformation/TransformationPool.java
    @@ -3,9 +3,9 @@
     import org.andengine.util.adt.pool.GenericPool;
     
     /**
    - * (c) 2010 Nicolas Gramlich 
    + * (c) 2010 Nicolas Gramlich
      * (c) 2011 Zynga Inc.
    - * 
    + *
      * @author Nicolas Gramlich
      * @since 23:07:53 - 23.02.2011
      */
    @@ -17,7 +17,7 @@ public class TransformationPool {
     	// ===========================================================
     	// Fields
     	// ===========================================================
    -	
    +
     	private static final GenericPool POOL = new GenericPool() {
     		@Override
     		protected Transformation onAllocatePoolItem() {
    @@ -36,11 +36,11 @@ protected Transformation onAllocatePoolItem() {
     	// ===========================================================
     	// Methods for/from SuperClass/Interfaces
     	// ===========================================================
    -	
    +
     	public static Transformation obtain() {
     		return POOL.obtainPoolItem();
     	}
    -	
    +
     	public static void recycle(final Transformation pTransformation) {
     		pTransformation.setToIdentity();
     		POOL.recyclePoolItem(pTransformation);
    diff --git a/src/org/andengine/util/adt/trie/ITrie.java b/src/org/andengine/util/adt/trie/ITrie.java
    index bc30f94f6..2b7538242 100644
    --- a/src/org/andengine/util/adt/trie/ITrie.java
    +++ b/src/org/andengine/util/adt/trie/ITrie.java
    @@ -1,7 +1,7 @@
     package org.andengine.util.adt.trie;
     
     /**
    - * (c) Zynga 2012
    + * (c) 2012 Zynga Inc.
      *
      * @author Nicolas Gramlich 
      * @since 12:18:44 - 30.01.2012
    diff --git a/src/org/andengine/util/adt/trie/Trie.java b/src/org/andengine/util/adt/trie/Trie.java
    index 67e0aeefc..acc4d117e 100644
    --- a/src/org/andengine/util/adt/trie/Trie.java
    +++ b/src/org/andengine/util/adt/trie/Trie.java
    @@ -3,7 +3,7 @@
     import android.util.SparseArray;
     
     /**
    - * (c) Zynga 2012
    + * (c) 2012 Zynga Inc.
      *
      * @author Nicolas Gramlich 
      * @since 12:25:47 - 30.01.2012
    @@ -101,7 +101,7 @@ public TrieNode(final boolean pWordEndFlag) {
     		@Override
     		public void add(final CharSequence pCharSequence) {
     			final int length = pCharSequence.length();
    -			if(length == 0) {
    +			if (length == 0) {
     				return;
     			}
     
    @@ -110,18 +110,18 @@ public void add(final CharSequence pCharSequence) {
     
     		@Override
     		public void add(final CharSequence pCharSequence, final int pStart, final int pEnd) {
    -			if(this.mChildren == null) {
    +			if (this.mChildren == null) {
     				this.mChildren = new SparseArray(Trie.CHILDREN_SIZE_DEFAULT);
     			}
     			final char character = pCharSequence.charAt(pStart);
     
     			TrieNode child = this.mChildren.get(character);
    -			if(child == null) {
    +			if (child == null) {
     				child = new TrieNode();
     				this.mChildren.put(character, child);
     			}
     
    -			if(pStart < pEnd - 1) {
    +			if (pStart < pEnd - 1) {
     				child.add(pCharSequence, pStart + 1, pEnd);
     			} else {
     				child.mWordEndFlag = true;
    @@ -131,7 +131,7 @@ public void add(final CharSequence pCharSequence, final int pStart, final int pE
     		@Override
     		public boolean contains(final CharSequence pCharSequence) {
     			final int length = pCharSequence.length();
    -			if(length == 0) {
    +			if (length == 0) {
     				throw new IllegalArgumentException();
     			}
     			return this.contains(pCharSequence, 0, length);
    @@ -139,16 +139,16 @@ public boolean contains(final CharSequence pCharSequence) {
     
     		@Override
     		public boolean contains(final CharSequence pCharSequence, final int pStart, final int pEnd) {
    -			if(this.mChildren == null) {
    +			if (this.mChildren == null) {
     				return false;
     			}
     
     			final char character = pCharSequence.charAt(pStart);
     			final TrieNode child = this.mChildren.get(character);
    -			if(child == null) {
    +			if (child == null) {
     				return false;
     			} else {
    -				if(pStart < pEnd - 1) {
    +				if (pStart < pEnd - 1) {
     					return child.contains(pCharSequence, pStart + 1, pEnd);
     				} else {
     					return child.mWordEndFlag;
    diff --git a/src/org/andengine/util/algorithm/Spiral.java b/src/org/andengine/util/algorithm/Spiral.java
    index 33550e7da..708248d09 100644
    --- a/src/org/andengine/util/algorithm/Spiral.java
    +++ b/src/org/andengine/util/algorithm/Spiral.java
    @@ -1,9 +1,9 @@
     package org.andengine.util.algorithm;
     
    -import org.andengine.util.algorithm.path.Direction;
    +import org.andengine.util.adt.spatial.Direction;
     
     /**
    - * (c) Zynga 2011
    + * (c) 2011 Zynga Inc.
      *
      * @author Nicolas Gramlich 
      * @since 22:40:53 - 10.11.2011
    diff --git a/src/org/andengine/util/algorithm/collision/BaseCollisionChecker.java b/src/org/andengine/util/algorithm/collision/BaseCollisionChecker.java
    index f3e03e490..4220a2f41 100644
    --- a/src/org/andengine/util/algorithm/collision/BaseCollisionChecker.java
    +++ b/src/org/andengine/util/algorithm/collision/BaseCollisionChecker.java
    @@ -1,13 +1,16 @@
     package org.andengine.util.algorithm.collision;
     
    +import org.andengine.opengl.util.VertexUtils;
    +import org.andengine.util.Constants;
    +
     /**
      * (c) 2010 Nicolas Gramlich
      * (c) 2011 Zynga Inc.
    - * 
    + *
      * @author Nicolas Gramlich
      * @since 11:50:19 - 11.03.2010
      */
    -public class BaseCollisionChecker {
    +public final class BaseCollisionChecker {
     	// ===========================================================
     	// Constants
     	// ===========================================================
    @@ -20,6 +23,10 @@ public class BaseCollisionChecker {
     	// Constructors
     	// ===========================================================
     
    +	private BaseCollisionChecker() {
    +
    +	}
    +
     	// ===========================================================
     	// Getter & Setter
     	// ===========================================================
    @@ -33,25 +40,25 @@ public class BaseCollisionChecker {
     	// ===========================================================
     
     	public static boolean checkAxisAlignedRectangleCollision(final float pLeftA, final float pTopA, final float pRightA, final float pBottomA, final float pLeftB, final float pTopB, final float pRightB, final float pBottomB) {
    -		return pLeftA < pRightB &&
    -				pLeftB < pRightA &&
    -				pTopA < pBottomB &&
    -				pTopB < pBottomA;
    +		return (pLeftA < pRightB) &&
    +				(pLeftB < pRightA) &&
    +				(pTopA < pBottomB) &&
    +				(pTopB < pBottomA);
     	}
     
     	public static boolean checkAxisAlignedRectangleContains(final float pLeft, final float pTop, final float pRight, final float pBottom, final float pX, final float pY) {
    -		return pX > pLeft &&
    -				pX < pRight &&
    -				pY > pTop &&
    -				pY < pBottom;
    +		return (pX > pLeft) &&
    +				(pX < pRight) &&
    +				(pY > pTop) &&
    +				(pY < pBottom);
     	}
     
     	/**
    -	 * Returns an indicator of where the specified point (PX, PY) lies with
    -	 * respect to the line segment from (X1, Y1) to (X2, Y2). The
    +	 * Returns an indicator of where the specified point (PX, PY) lies with
    +	 * respect to the line segment from (X1, Y1) to (X2, Y2). The
     	 * return value can be either 1, -1, or 0 and indicates in which direction
    -	 * the specified line must pivot around its first endpoint, (X1, Y1),
    -	 * in order to point at the specified point (PX, PY).
    +	 * the specified line must pivot around its first endpoint, (X1, Y1),
    +	 * in order to point at the specified point (PX, PY).
     	 * 

    * A return value of 1 indicates that the line segment must turn in the * direction that takes the positive X axis towards the negative Y axis. In @@ -68,16 +75,16 @@ public static boolean checkAxisAlignedRectangleContains(final float pLeft, final *

    * If the point is colinear with the line segment, but not between the * endpoints, then the value will be -1 if the point lies - * "beyond (X1, Y1)" or 1 if the point lies "beyond (X2, Y2)". - * - * @param pX1 - * , Y1 the coordinates of the beginning of the specified + * "beyond (X1, Y1)" or 1 if the point lies "beyond (X2, Y2)". + * + * @param pX1 , + * @param pY1 the coordinates of the beginning of the specified * line segment - * @param pX2 - * , Y2 the coordinates of the end of the specified line + * @param pX2 , + * @param pY2 the coordinates of the end of the specified line * segment - * @param pPX - * , PY the coordinates of the specified point to be + * @param pPX , + * @param pPY the coordinates of the specified point to be * compared with the specified line segment * @return an integer that indicates the position of the third specified * coordinates with respect to the line segment formed by the first @@ -88,7 +95,7 @@ public static int relativeCCW(final float pX1, final float pY1, float pX2, float pY2 -= pY1; pPX -= pX1; pPY -= pY1; - float ccw = pPX * pY2 - pPY * pX2; + float ccw = (pPX * pY2) - (pPY * pX2); if (ccw == 0.0f) { // The point is colinear, classify based on which side of // the segment the point falls on. We can calculate a @@ -96,7 +103,7 @@ public static int relativeCCW(final float pX1, final float pY1, float pX2, float // segment - a negative value indicates the point projects // outside of the segment in the direction of the particular // endpoint used as the origin for the projection. - ccw = pPX * pX2 + pPY * pY2; + ccw = (pPX * pX2) + (pPY * pY2); if (ccw > 0.0f) { // Reverse the projection to be relative to the original X2,Y2 // X2 and Y2 are simply negated. @@ -107,7 +114,7 @@ public static int relativeCCW(final float pX1, final float pY1, float pX2, float // the inverse anyway - thus we leave X2 & Y2 negated. pPX -= pX2; pPY -= pY2; - ccw = pPX * pX2 + pPY * pY2; + ccw = (pPX * pX2) + (pPY * pY2); if (ccw < 0.0f) { ccw = 0.0f; } @@ -116,6 +123,144 @@ public static int relativeCCW(final float pX1, final float pY1, float pX2, float return (ccw < 0.0f) ? -1 : ((ccw > 0.0f) ? 1 : 0); } + /** + * Calls through to {@link #checkCollisionSub(float[], int, int, int, int, int, float[], int, int, int, int)} with the default parameters internally used by different AndEngine primitives. + * @param pVerticesA + * @param pVertexCountA the number of vertices in pVerticesA + * @param pVerticesB + * @param pVertexCountB the number of vertices in pVerticesB + * @return + */ + public static boolean checkCollision(final float[] pVerticesA, final int pVertexCountA, final float[] pVerticesB, final int pVertexCountB) { + return BaseCollisionChecker.checkCollision(pVerticesA, pVertexCountA, Constants.VERTEX_INDEX_X, Constants.VERTEX_INDEX_Y, 2, pVerticesB, pVertexCountB, Constants.VERTEX_INDEX_X, Constants.VERTEX_INDEX_Y, 2); + } + + /** + * @param pVerticesA + * @param pVertexCountA the number of vertices in pVerticesA + * @param pVertexOffsetXA + * @param pVertexOffsetYA + * @param pVertexStrideA + * @param pVerticesB + * @param pVertexCountB the number of vertices in pVerticesB + * @param pVertexOffsetXB + * @param pVertexOffsetYB + * @param pVertexStrideB + * @return + */ + public static boolean checkCollision(final float[] pVerticesA, final int pVertexCountA, final int pVertexOffsetXA, final int pVertexOffsetYA, final int pVertexStrideA, final float[] pVerticesB, final int pVertexCountB, final int pVertexOffsetXB, final int pVertexOffsetYB, final int pVertexStrideB) { + /* Check all the lines of A ... */ + for (int a = pVertexCountA - 2; a >= 0; a--) { + /* ... against all lines in B. */ + if (BaseCollisionChecker.checkCollisionSub(pVerticesA, pVertexOffsetXA, pVertexOffsetYA, pVertexStrideA, a, a + 1, pVerticesB, pVertexCountB, pVertexOffsetXB, pVertexOffsetYB, pVertexStrideB)) { + return true; + } + } + /* Also check the 'around the corner of the array' line of A against all lines in B. */ + if (BaseCollisionChecker.checkCollisionSub(pVerticesA, pVertexOffsetXA, pVertexOffsetYA, pVertexStrideA, pVertexCountA - 1, 0, pVerticesB, pVertexCountB, pVertexOffsetXB, pVertexOffsetYB, pVertexStrideB)) { + return true; + } else { + /* At last check if one polygon 'contains' the other one by checking + * if one vertex of the one vertices is contained by all of the other vertices. */ + if (BaseCollisionChecker.checkContains(pVerticesA, pVertexCountA, VertexUtils.getVertex(pVerticesB, pVertexOffsetXB, pVertexStrideB, 0), VertexUtils.getVertex(pVerticesB, pVertexOffsetYB, pVertexStrideB, 0))) { + return true; + } else if (BaseCollisionChecker.checkContains(pVerticesB, pVertexCountB, VertexUtils.getVertex(pVerticesA, pVertexOffsetXA, pVertexStrideA, 0), VertexUtils.getVertex(pVerticesA, pVertexOffsetYA, pVertexStrideA, 0))) { + return true; + } else { + return false; + } + } + } + + /** + * Checks line specified by pVertexIndexA1 and pVertexIndexA2 in pVerticesA against all lines in pVerticesB. + * + * @param pVerticesA + * @param pVertexOffsetXA + * @param pVertexOffsetYA + * @param pVertexStrideA + * @param pVertexIndexA1 the first point of the line in pVerticesA + * @param pVertexIndexA2 the second point of the line in pVerticesA + * @param pVerticesB + * @param pVertexCountB the number of vertices in pVerticesB + * @param pVertexOffsetXB + * @param pVertexOffsetYB + * @param pVertexStrideB + * @return + */ + static boolean checkCollisionSub(final float[] pVerticesA, final int pVertexOffsetXA, final int pVertexOffsetYA, final int pVertexStrideA, final int pVertexIndexA1, final int pVertexIndexA2, final float[] pVerticesB, final int pVertexCountB, final int pVertexOffsetXB, final int pVertexOffsetYB, final int pVertexStrideB) { + /* Check against all the lines of B. */ + final float vertexA1X = VertexUtils.getVertex(pVerticesA, pVertexOffsetXA, pVertexStrideA, pVertexIndexA1); + final float vertexA1Y = VertexUtils.getVertex(pVerticesA, pVertexOffsetYA, pVertexStrideA, pVertexIndexA1); + final float vertexA2X = VertexUtils.getVertex(pVerticesA, pVertexOffsetXA, pVertexStrideA, pVertexIndexA2); + final float vertexA2Y = VertexUtils.getVertex(pVerticesA, pVertexOffsetYA, pVertexStrideA, pVertexIndexA2); + + for (int b = pVertexCountB - 2; b >= 0; b--) { + final float vertexB1X = VertexUtils.getVertex(pVerticesB, pVertexOffsetXB, pVertexStrideB, b); + final float vertexB1Y = VertexUtils.getVertex(pVerticesB, pVertexOffsetYB, pVertexStrideB, b); + final float vertexB2X = VertexUtils.getVertex(pVerticesB, pVertexOffsetXB, pVertexStrideB, b + 1); + final float vertexB2Y = VertexUtils.getVertex(pVerticesB, pVertexOffsetYB, pVertexStrideB, b + 1); + if (LineCollisionChecker.checkLineCollision(vertexA1X, vertexA1Y, vertexA2X, vertexA2Y, vertexB1X, vertexB1Y, vertexB2X, vertexB2Y)) { + return true; + } + } + /* Also check the 'around the corner of the array' line of B. */ + final float vertexB1X = VertexUtils.getVertex(pVerticesB, pVertexOffsetXB, pVertexStrideB, pVertexCountB - 1); + final float vertexB1Y = VertexUtils.getVertex(pVerticesB, pVertexOffsetYB, pVertexStrideB, pVertexCountB - 1); + final float vertexB2X = VertexUtils.getVertex(pVerticesB, pVertexOffsetXB, pVertexStrideB, 0); + final float vertexB2Y = VertexUtils.getVertex(pVerticesB, pVertexOffsetYB, pVertexStrideB, 0); + if (LineCollisionChecker.checkLineCollision(vertexA1X, vertexA1Y, vertexA2X, vertexA2Y, vertexB1X, vertexB1Y, vertexB2X, vertexB2Y)) { + return true; + } + return false; + } + + /** + * Calls through to {@link #checkContains(float[], int, int, int, int, float, float)} with the default parameters internally used by different AndEngine primitives. + * + * @param pVertices + * @param pVertexCount the number of vertices in pVertices + * @param pX + * @param pY + * @return + */ + public static boolean checkContains(final float[] pVertices, final int pVertexCount, final float pX, final float pY) { + return BaseCollisionChecker.checkContains(pVertices, pVertexCount, Constants.VERTEX_INDEX_X, Constants.VERTEX_INDEX_Y, 2, pX, pY); + } + + /** + * Works with complex polygons! + * + * @see alienryderflex.com/polygon/ + * + * @param pVertices + * @param pVertexCount the number of vertices in pVertices + * @param pVertexOffsetX + * @param pVertexOffsetY + * @param pVertexStride + * @param pX + * @param pY + * @return true when the point defined by (pX, pY) is inside the polygon defined by pVertices, false. If the point is exactly on the edge of the polygon, the result can be true or false. + */ + public static boolean checkContains(final float[] pVertices, final int pVertexCount, final int pVertexOffsetX, final int pVertexOffsetY, final int pVertexStride, final float pX, final float pY) { + boolean odd = false; + + int j = pVertexCount - 1; + for (int i = 0; i < pVertexCount; i++) { + final float vertexXI = VertexUtils.getVertex(pVertices, pVertexOffsetX, pVertexStride, i); + final float vertexYI = VertexUtils.getVertex(pVertices, pVertexOffsetY, pVertexStride, i); + final float vertexXJ = VertexUtils.getVertex(pVertices, pVertexOffsetX, pVertexStride, j); + final float vertexYJ = VertexUtils.getVertex(pVertices, pVertexOffsetY, pVertexStride, j); + + if ((((vertexYI < pY) && (vertexYJ >= pY)) || ((vertexYJ < pY) && (vertexYI >= pY))) && ((vertexXI <= pX) || (vertexXJ <= pX))) { + odd ^= ((vertexXI + (((pY - vertexYI) / (vertexYJ - vertexYI)) * (vertexXJ - vertexXI))) < pX); + } + j = i; + } + + return odd; + } + // =========================================================== // Inner and Anonymous Classes // =========================================================== diff --git a/src/org/andengine/util/algorithm/collision/EntityCollisionChecker.java b/src/org/andengine/util/algorithm/collision/EntityCollisionChecker.java new file mode 100644 index 000000000..83498bf82 --- /dev/null +++ b/src/org/andengine/util/algorithm/collision/EntityCollisionChecker.java @@ -0,0 +1,146 @@ +package org.andengine.util.algorithm.collision; + +import org.andengine.engine.camera.Camera; +import org.andengine.entity.IEntity; +import org.andengine.entity.primitive.Line; +import org.andengine.util.Constants; +import org.andengine.util.adt.transformation.Transformation; +import org.andengine.util.math.MathUtils; + +/** + * (c) 2010 Nicolas Gramlich + * (c) 2011 Zynga Inc. + * + * @author Nicolas Gramlich + * @since 11:50:19 - 11.03.2010 + */ +public final class EntityCollisionChecker { + // =========================================================== + // Constants + // =========================================================== + + public static final int RECTANGULARSHAPE_VERTEX_COUNT = 4; + + private static final float[] VERTICES_CONTAINS_TMP = new float[2 * EntityCollisionChecker.RECTANGULARSHAPE_VERTEX_COUNT]; + private static final float[] VERTICES_COLLISION_TMP_A = new float[2 * EntityCollisionChecker.RECTANGULARSHAPE_VERTEX_COUNT]; + private static final float[] VERTICES_COLLISION_TMP_B = new float[2 * EntityCollisionChecker.RECTANGULARSHAPE_VERTEX_COUNT]; + + // =========================================================== + // Fields + // =========================================================== + + // =========================================================== + // Constructors + // =========================================================== + + private EntityCollisionChecker() { + + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + public static boolean checkContains(final float pLocalX, final float pLocalY, final float pLocalWidth, final float pLocalHeight, final Transformation pLocalToSceneTransformation, final float pX, final float pY) { + EntityCollisionChecker.fillVertices(pLocalX, pLocalY, pLocalWidth, pLocalHeight, pLocalToSceneTransformation, EntityCollisionChecker.VERTICES_CONTAINS_TMP); + return BaseCollisionChecker.checkContains(EntityCollisionChecker.VERTICES_CONTAINS_TMP, EntityCollisionChecker.RECTANGULARSHAPE_VERTEX_COUNT, pX, pY); + } + + public static boolean checkContains(final IEntity pEntity, final float pLocalWidth, final float pLocalHeight, final float pX, final float pY) { + EntityCollisionChecker.fillVertices(pEntity.getX(), pEntity.getY(), pLocalWidth, pLocalHeight, pEntity.getLocalToSceneTransformation(), EntityCollisionChecker.VERTICES_CONTAINS_TMP); + return BaseCollisionChecker.checkContains(EntityCollisionChecker.VERTICES_CONTAINS_TMP, EntityCollisionChecker.RECTANGULARSHAPE_VERTEX_COUNT, pX, pY); + } + + public static boolean checkContains(final IEntity pEntity, final float pX, final float pY) { + EntityCollisionChecker.fillVertices(pEntity, EntityCollisionChecker.VERTICES_CONTAINS_TMP); + return BaseCollisionChecker.checkContains(EntityCollisionChecker.VERTICES_CONTAINS_TMP, EntityCollisionChecker.RECTANGULARSHAPE_VERTEX_COUNT, pX, pY); + } + + public static boolean isVisible(final Camera pCamera, final IEntity pEntity) { + EntityCollisionChecker.fillVertices(pCamera, EntityCollisionChecker.VERTICES_COLLISION_TMP_A); + EntityCollisionChecker.fillVertices(pEntity, EntityCollisionChecker.VERTICES_COLLISION_TMP_B); + + return BaseCollisionChecker.checkCollision(EntityCollisionChecker.VERTICES_COLLISION_TMP_A, EntityCollisionChecker.RECTANGULARSHAPE_VERTEX_COUNT, EntityCollisionChecker.VERTICES_COLLISION_TMP_B, EntityCollisionChecker.RECTANGULARSHAPE_VERTEX_COUNT); + } + + public static boolean isVisible(final Camera pCamera, final float pX, final float pY, final float pWidth, final float pHeight, final Transformation pLocalToSceneTransformation) { + EntityCollisionChecker.fillVertices(pCamera, EntityCollisionChecker.VERTICES_COLLISION_TMP_A); + EntityCollisionChecker.fillVertices(pX, pY, pWidth, pHeight, pLocalToSceneTransformation, EntityCollisionChecker.VERTICES_COLLISION_TMP_B); + + return BaseCollisionChecker.checkCollision(EntityCollisionChecker.VERTICES_COLLISION_TMP_A, EntityCollisionChecker.RECTANGULARSHAPE_VERTEX_COUNT, EntityCollisionChecker.VERTICES_COLLISION_TMP_B, EntityCollisionChecker.RECTANGULARSHAPE_VERTEX_COUNT); + } + + public static boolean isVisible(final Camera pCamera, final Line pLine) { + EntityCollisionChecker.fillVertices(pCamera, EntityCollisionChecker.VERTICES_COLLISION_TMP_A); + LineCollisionChecker.fillVertices(pLine, EntityCollisionChecker.VERTICES_COLLISION_TMP_B); + + return BaseCollisionChecker.checkCollision(EntityCollisionChecker.VERTICES_COLLISION_TMP_A, EntityCollisionChecker.RECTANGULARSHAPE_VERTEX_COUNT, EntityCollisionChecker.VERTICES_COLLISION_TMP_B, LineCollisionChecker.LINE_VERTEX_COUNT); + } + + public static boolean checkCollision(final IEntity pEntityA, final IEntity pEntityB) { + EntityCollisionChecker.fillVertices(pEntityA, EntityCollisionChecker.VERTICES_COLLISION_TMP_A); + EntityCollisionChecker.fillVertices(pEntityB, EntityCollisionChecker.VERTICES_COLLISION_TMP_B); + + return BaseCollisionChecker.checkCollision(EntityCollisionChecker.VERTICES_COLLISION_TMP_A, EntityCollisionChecker.RECTANGULARSHAPE_VERTEX_COUNT, EntityCollisionChecker.VERTICES_COLLISION_TMP_B, EntityCollisionChecker.RECTANGULARSHAPE_VERTEX_COUNT); + } + + public static boolean checkCollision(final IEntity pEntity, final Line pLine) { + EntityCollisionChecker.fillVertices(pEntity, EntityCollisionChecker.VERTICES_COLLISION_TMP_A); + LineCollisionChecker.fillVertices(pLine, EntityCollisionChecker.VERTICES_COLLISION_TMP_B); + + return BaseCollisionChecker.checkCollision(EntityCollisionChecker.VERTICES_COLLISION_TMP_A, EntityCollisionChecker.RECTANGULARSHAPE_VERTEX_COUNT, EntityCollisionChecker.VERTICES_COLLISION_TMP_B, LineCollisionChecker.LINE_VERTEX_COUNT); + } + + public static void fillVertices(final IEntity pEntity, final float[] pVertices) { + EntityCollisionChecker.fillVertices(0, 0, pEntity.getWidth(), pEntity.getHeight(), pEntity.getLocalToSceneTransformation(), pVertices); + } + + public static void fillVertices(final float pLocalX, final float pLocalY, final float pLocalWidth, final float pLocalHeight, final Transformation pLocalToSceneTransformation, final float[] pVertices) { + final float localXMin = pLocalX; + final float localXMax = pLocalX + pLocalWidth; + final float localYMin = pLocalY; + final float localYMax = pLocalY + pLocalHeight; + + pVertices[0 + Constants.VERTEX_INDEX_X] = localXMin; + pVertices[0 + Constants.VERTEX_INDEX_Y] = localYMin; + + pVertices[2 + Constants.VERTEX_INDEX_X] = localXMax; + pVertices[2 + Constants.VERTEX_INDEX_Y] = localYMin; + + pVertices[4 + Constants.VERTEX_INDEX_X] = localXMax; + pVertices[4 + Constants.VERTEX_INDEX_Y] = localYMax; + + pVertices[6 + Constants.VERTEX_INDEX_X] = localXMin; + pVertices[6 + Constants.VERTEX_INDEX_Y] = localYMax; + + pLocalToSceneTransformation.transform(pVertices); + } + + private static void fillVertices(final Camera pCamera, final float[] pVertices) { + pVertices[0 + Constants.VERTEX_INDEX_X] = pCamera.getXMin(); + pVertices[0 + Constants.VERTEX_INDEX_Y] = pCamera.getYMin(); + + pVertices[2 + Constants.VERTEX_INDEX_X] = pCamera.getXMax(); + pVertices[2 + Constants.VERTEX_INDEX_Y] = pCamera.getYMin(); + + pVertices[4 + Constants.VERTEX_INDEX_X] = pCamera.getXMax(); + pVertices[4 + Constants.VERTEX_INDEX_Y] = pCamera.getYMax(); + + pVertices[6 + Constants.VERTEX_INDEX_X] = pCamera.getXMin(); + pVertices[6 + Constants.VERTEX_INDEX_Y] = pCamera.getYMax(); + + MathUtils.rotateAroundCenter(pVertices, pCamera.getRotation(), pCamera.getCenterX(), pCamera.getCenterY()); + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== +} diff --git a/src/org/andengine/util/algorithm/collision/LineCollisionChecker.java b/src/org/andengine/util/algorithm/collision/LineCollisionChecker.java index 4c80902e7..f174c4703 100644 --- a/src/org/andengine/util/algorithm/collision/LineCollisionChecker.java +++ b/src/org/andengine/util/algorithm/collision/LineCollisionChecker.java @@ -6,13 +6,13 @@ import org.andengine.entity.primitive.Line; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 19:27:22 - 17.07.2010 */ -public class LineCollisionChecker extends ShapeCollisionChecker { +public final class LineCollisionChecker { // =========================================================== // Constants // =========================================================== @@ -27,6 +27,10 @@ public class LineCollisionChecker extends ShapeCollisionChecker { // Constructors // =========================================================== + private LineCollisionChecker() { + + } + // =========================================================== // Getter & Setter // =========================================================== diff --git a/src/org/andengine/util/algorithm/collision/RectangularShapeCollisionChecker.java b/src/org/andengine/util/algorithm/collision/RectangularShapeCollisionChecker.java deleted file mode 100644 index b6751240d..000000000 --- a/src/org/andengine/util/algorithm/collision/RectangularShapeCollisionChecker.java +++ /dev/null @@ -1,143 +0,0 @@ -package org.andengine.util.algorithm.collision; - -import org.andengine.engine.camera.Camera; -import org.andengine.entity.Entity; -import org.andengine.entity.primitive.Line; -import org.andengine.entity.shape.RectangularShape; -import org.andengine.util.Constants; -import org.andengine.util.adt.transformation.Transformation; -import org.andengine.util.math.MathUtils; - -/** - * (c) 2010 Nicolas Gramlich - * (c) 2011 Zynga Inc. - * - * @author Nicolas Gramlich - * @since 11:50:19 - 11.03.2010 - */ -public class RectangularShapeCollisionChecker extends ShapeCollisionChecker { - // =========================================================== - // Constants - // =========================================================== - - public static final int RECTANGULARSHAPE_VERTEX_COUNT = 4; - - private static final float[] VERTICES_CONTAINS_TMP = new float[2 * RectangularShapeCollisionChecker.RECTANGULARSHAPE_VERTEX_COUNT]; - private static final float[] VERTICES_COLLISION_TMP_A = new float[2 * RectangularShapeCollisionChecker.RECTANGULARSHAPE_VERTEX_COUNT]; - private static final float[] VERTICES_COLLISION_TMP_B = new float[2 * RectangularShapeCollisionChecker.RECTANGULARSHAPE_VERTEX_COUNT]; - - // =========================================================== - // Fields - // =========================================================== - - // =========================================================== - // Constructors - // =========================================================== - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - // =========================================================== - // Methods - // =========================================================== - - public static boolean checkContains(final float pLocalX, final float pLocalY, final float pLocalWidth, final float pLocalHeight, final Transformation pLocalToSceneTransformation, final float pX, final float pY) { - RectangularShapeCollisionChecker.fillVertices(pLocalX, pLocalY, pLocalWidth, pLocalHeight, pLocalToSceneTransformation, RectangularShapeCollisionChecker.VERTICES_CONTAINS_TMP); - return ShapeCollisionChecker.checkContains(RectangularShapeCollisionChecker.VERTICES_CONTAINS_TMP, RectangularShapeCollisionChecker.RECTANGULARSHAPE_VERTEX_COUNT, pX, pY); - } - - public static boolean checkContains(final Entity pEntity, final float pLocalWidth, final float pLocalHeight, final float pX, final float pY) { - RectangularShapeCollisionChecker.fillVertices(pEntity.getX(), pEntity.getY(), pLocalWidth, pLocalHeight, pEntity.getLocalToSceneTransformation(), RectangularShapeCollisionChecker.VERTICES_CONTAINS_TMP); - return ShapeCollisionChecker.checkContains(RectangularShapeCollisionChecker.VERTICES_CONTAINS_TMP, RectangularShapeCollisionChecker.RECTANGULARSHAPE_VERTEX_COUNT, pX, pY); - } - - public static boolean checkContains(final RectangularShape pRectangularShape, final float pX, final float pY) { - RectangularShapeCollisionChecker.fillVertices(pRectangularShape, RectangularShapeCollisionChecker.VERTICES_CONTAINS_TMP); - return ShapeCollisionChecker.checkContains(RectangularShapeCollisionChecker.VERTICES_CONTAINS_TMP, RectangularShapeCollisionChecker.RECTANGULARSHAPE_VERTEX_COUNT, pX, pY); - } - - public static boolean isVisible(final Camera pCamera, final RectangularShape pRectangularShape) { - RectangularShapeCollisionChecker.fillVertices(pCamera, RectangularShapeCollisionChecker.VERTICES_COLLISION_TMP_A); - RectangularShapeCollisionChecker.fillVertices(pRectangularShape, RectangularShapeCollisionChecker.VERTICES_COLLISION_TMP_B); - - return ShapeCollisionChecker.checkCollision(RectangularShapeCollisionChecker.VERTICES_COLLISION_TMP_A, RectangularShapeCollisionChecker.RECTANGULARSHAPE_VERTEX_COUNT, RectangularShapeCollisionChecker.VERTICES_COLLISION_TMP_B, RectangularShapeCollisionChecker.RECTANGULARSHAPE_VERTEX_COUNT); - } - - public static boolean isVisible(final Camera pCamera, final float pX, final float pY, final float pWidth, final float pHeight, final Transformation pLocalToSceneTransformation) { - RectangularShapeCollisionChecker.fillVertices(pCamera, RectangularShapeCollisionChecker.VERTICES_COLLISION_TMP_A); - RectangularShapeCollisionChecker.fillVertices(pX, pY, pWidth, pHeight, pLocalToSceneTransformation, RectangularShapeCollisionChecker.VERTICES_COLLISION_TMP_B); - - return ShapeCollisionChecker.checkCollision(RectangularShapeCollisionChecker.VERTICES_COLLISION_TMP_A, RectangularShapeCollisionChecker.RECTANGULARSHAPE_VERTEX_COUNT, RectangularShapeCollisionChecker.VERTICES_COLLISION_TMP_B, RectangularShapeCollisionChecker.RECTANGULARSHAPE_VERTEX_COUNT); - } - - public static boolean isVisible(final Camera pCamera, final Line pLine) { - RectangularShapeCollisionChecker.fillVertices(pCamera, RectangularShapeCollisionChecker.VERTICES_COLLISION_TMP_A); - LineCollisionChecker.fillVertices(pLine, RectangularShapeCollisionChecker.VERTICES_COLLISION_TMP_B); - - return ShapeCollisionChecker.checkCollision(RectangularShapeCollisionChecker.VERTICES_COLLISION_TMP_A, RectangularShapeCollisionChecker.RECTANGULARSHAPE_VERTEX_COUNT, RectangularShapeCollisionChecker.VERTICES_COLLISION_TMP_B, LineCollisionChecker.LINE_VERTEX_COUNT); - } - - public static boolean checkCollision(final RectangularShape pRectangularShapeA, final RectangularShape pRectangularShapeB) { - RectangularShapeCollisionChecker.fillVertices(pRectangularShapeA, RectangularShapeCollisionChecker.VERTICES_COLLISION_TMP_A); - RectangularShapeCollisionChecker.fillVertices(pRectangularShapeB, RectangularShapeCollisionChecker.VERTICES_COLLISION_TMP_B); - - return ShapeCollisionChecker.checkCollision(RectangularShapeCollisionChecker.VERTICES_COLLISION_TMP_A, RectangularShapeCollisionChecker.RECTANGULARSHAPE_VERTEX_COUNT, RectangularShapeCollisionChecker.VERTICES_COLLISION_TMP_B, RectangularShapeCollisionChecker.RECTANGULARSHAPE_VERTEX_COUNT); - } - - public static boolean checkCollision(final RectangularShape pRectangularShape, final Line pLine) { - RectangularShapeCollisionChecker.fillVertices(pRectangularShape, RectangularShapeCollisionChecker.VERTICES_COLLISION_TMP_A); - LineCollisionChecker.fillVertices(pLine, RectangularShapeCollisionChecker.VERTICES_COLLISION_TMP_B); - - return ShapeCollisionChecker.checkCollision(RectangularShapeCollisionChecker.VERTICES_COLLISION_TMP_A, RectangularShapeCollisionChecker.RECTANGULARSHAPE_VERTEX_COUNT, RectangularShapeCollisionChecker.VERTICES_COLLISION_TMP_B, LineCollisionChecker.LINE_VERTEX_COUNT); - } - - public static void fillVertices(final RectangularShape pRectangularShape, final float[] pVertices) { - RectangularShapeCollisionChecker.fillVertices(0, 0, pRectangularShape.getWidth(), pRectangularShape.getHeight(), pRectangularShape.getLocalToSceneTransformation(), pVertices); - } - - public static void fillVertices(final float pLocalX, final float pLocalY, final float pLocalWidth, final float pLocalHeight, final Transformation pLocalToSceneTransformation, final float[] pVertices) { - final float localXMin = pLocalX; - final float localXMax = pLocalX + pLocalWidth; - final float localYMin = pLocalY; - final float localYMax = pLocalY + pLocalHeight; - - pVertices[0 + Constants.VERTEX_INDEX_X] = localXMin; - pVertices[0 + Constants.VERTEX_INDEX_Y] = localYMin; - - pVertices[2 + Constants.VERTEX_INDEX_X] = localXMax; - pVertices[2 + Constants.VERTEX_INDEX_Y] = localYMin; - - pVertices[4 + Constants.VERTEX_INDEX_X] = localXMax; - pVertices[4 + Constants.VERTEX_INDEX_Y] = localYMax; - - pVertices[6 + Constants.VERTEX_INDEX_X] = localXMin; - pVertices[6 + Constants.VERTEX_INDEX_Y] = localYMax; - - pLocalToSceneTransformation.transform(pVertices); - } - - private static void fillVertices(final Camera pCamera, final float[] pVertices) { - pVertices[0 + Constants.VERTEX_INDEX_X] = pCamera.getXMin(); - pVertices[0 + Constants.VERTEX_INDEX_Y] = pCamera.getYMin(); - - pVertices[2 + Constants.VERTEX_INDEX_X] = pCamera.getXMax(); - pVertices[2 + Constants.VERTEX_INDEX_Y] = pCamera.getYMin(); - - pVertices[4 + Constants.VERTEX_INDEX_X] = pCamera.getXMax(); - pVertices[4 + Constants.VERTEX_INDEX_Y] = pCamera.getYMax(); - - pVertices[6 + Constants.VERTEX_INDEX_X] = pCamera.getXMin(); - pVertices[6 + Constants.VERTEX_INDEX_Y] = pCamera.getYMax(); - - MathUtils.rotateAroundCenter(pVertices, pCamera.getRotation(), pCamera.getCenterX(), pCamera.getCenterY()); - } - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== -} diff --git a/src/org/andengine/util/algorithm/collision/ShapeCollisionChecker.java b/src/org/andengine/util/algorithm/collision/ShapeCollisionChecker.java deleted file mode 100644 index 02e468cac..000000000 --- a/src/org/andengine/util/algorithm/collision/ShapeCollisionChecker.java +++ /dev/null @@ -1,180 +0,0 @@ -package org.andengine.util.algorithm.collision; - -import org.andengine.opengl.util.VertexUtils; -import org.andengine.util.Constants; - - -/** - * (c) 2010 Nicolas Gramlich - * (c) 2011 Zynga Inc. - * - * @author Nicolas Gramlich - * @since 11:50:19 - 11.03.2010 - */ -public class ShapeCollisionChecker extends BaseCollisionChecker { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - // =========================================================== - // Constructors - // =========================================================== - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - // =========================================================== - // Methods - // =========================================================== - - /** - * Calls through to {@link ShapeCollisionChecker#checkCollisionSub(float[], int, int, int, int, int, float[], int, int, int, int)} with the default parameters internally used by different AndEngine primitives. - * @param pVerticesA - * @param pVertexCountA the number of vertices in pVerticesA - * @param pVerticesB - * @param pVertexCountB the number of vertices in pVerticesB - * @return - */ - public static boolean checkCollision(final float[] pVerticesA, final int pVertexCountA, final float[] pVerticesB, final int pVertexCountB) { - return ShapeCollisionChecker.checkCollision(pVerticesA, pVertexCountA, Constants.VERTEX_INDEX_X, Constants.VERTEX_INDEX_Y, 2, pVerticesB, pVertexCountB, Constants.VERTEX_INDEX_X, Constants.VERTEX_INDEX_Y, 2); - } - - /** - * @param pVerticesA - * @param pVertexCountA the number of vertices in pVerticesA - * @param pVertexOffsetXA - * @param pVertexOffsetYA - * @param pVertexStrideA - * @param pVerticesB - * @param pVertexCountB the number of vertices in pVerticesB - * @param pVertexOffsetXB - * @param pVertexOffsetYB - * @param pVertexStrideB - * @return - */ - public static boolean checkCollision(final float[] pVerticesA, final int pVertexCountA, final int pVertexOffsetXA, final int pVertexOffsetYA, final int pVertexStrideA, final float[] pVerticesB, final int pVertexCountB, final int pVertexOffsetXB, final int pVertexOffsetYB, final int pVertexStrideB) { - /* Check all the lines of A ... */ - for(int a = pVertexCountA - 2; a >= 0; a--) { - /* ... against all lines in B. */ - if(ShapeCollisionChecker.checkCollisionSub(pVerticesA, pVertexOffsetXA, pVertexOffsetYA, pVertexStrideA, a, a + 1, pVerticesB, pVertexCountB, pVertexOffsetXB, pVertexOffsetYB, pVertexStrideB)){ - return true; - } - } - /* Also check the 'around the corner of the array' line of A against all lines in B. */ - if(ShapeCollisionChecker.checkCollisionSub(pVerticesA, pVertexOffsetXA, pVertexOffsetYA, pVertexStrideA, pVertexCountA - 1, 0, pVerticesB, pVertexCountB, pVertexOffsetXB, pVertexOffsetYB, pVertexStrideB)){ - return true; - } else { - /* At last check if one polygon 'contains' the other one by checking - * if one vertex of the one vertices is contained by all of the other vertices. */ - if(ShapeCollisionChecker.checkContains(pVerticesA, pVertexCountA, VertexUtils.getVertex(pVerticesB, pVertexOffsetXB, pVertexStrideB, 0), VertexUtils.getVertex(pVerticesB, pVertexOffsetYB, pVertexStrideB, 0))) { - return true; - } else if(ShapeCollisionChecker.checkContains(pVerticesB, pVertexCountB, VertexUtils.getVertex(pVerticesA, pVertexOffsetXA, pVertexStrideA, 0), VertexUtils.getVertex(pVerticesA, pVertexOffsetYA, pVertexStrideA, 0))) { - return true; - } else { - return false; - } - } - } - - /** - * Checks line specified by pVertexIndexA1 and pVertexIndexA2 in pVerticesA against all lines in pVerticesB. - * - * @param pVerticesA - * @param pVertexOffsetXA - * @param pVertexOffsetYA - * @param pVertexStrideA - * @param pVertexIndexA1 the first point of the line in pVerticesA - * @param pVertexIndexA2 the second point of the line in pVerticesA - * @param pVerticesB - * @param pVertexCountB the number of vertices in pVerticesB - * @param pVertexOffsetXB - * @param pVertexOffsetYB - * @param pVertexStrideB - * @return - */ - private static boolean checkCollisionSub(final float[] pVerticesA, final int pVertexOffsetXA, final int pVertexOffsetYA, final int pVertexStrideA, final int pVertexIndexA1, final int pVertexIndexA2, final float[] pVerticesB, final int pVertexCountB, final int pVertexOffsetXB, final int pVertexOffsetYB, final int pVertexStrideB) { - /* Check against all the lines of B. */ - final float vertexA1X = VertexUtils.getVertex(pVerticesA, pVertexOffsetXA, pVertexStrideA, pVertexIndexA1); - final float vertexA1Y = VertexUtils.getVertex(pVerticesA, pVertexOffsetYA, pVertexStrideA, pVertexIndexA1); - final float vertexA2X = VertexUtils.getVertex(pVerticesA, pVertexOffsetXA, pVertexStrideA, pVertexIndexA2); - final float vertexA2Y = VertexUtils.getVertex(pVerticesA, pVertexOffsetYA, pVertexStrideA, pVertexIndexA2); - - for(int b = pVertexCountB - 2; b >= 0; b--) { - final float vertexB1X = VertexUtils.getVertex(pVerticesB, pVertexOffsetXB, pVertexStrideB, b); - final float vertexB1Y = VertexUtils.getVertex(pVerticesB, pVertexOffsetYB, pVertexStrideB, b); - final float vertexB2X = VertexUtils.getVertex(pVerticesB, pVertexOffsetXB, pVertexStrideB, b + 1); - final float vertexB2Y = VertexUtils.getVertex(pVerticesB, pVertexOffsetYB, pVertexStrideB, b + 1); - if(LineCollisionChecker.checkLineCollision(vertexA1X, vertexA1Y, vertexA2X, vertexA2Y, vertexB1X, vertexB1Y, vertexB2X, vertexB2Y)){ - return true; - } - } - /* Also check the 'around the corner of the array' line of B. */ - final float vertexB1X = VertexUtils.getVertex(pVerticesB, pVertexOffsetXB, pVertexStrideB, pVertexCountB - 1); - final float vertexB1Y = VertexUtils.getVertex(pVerticesB, pVertexOffsetYB, pVertexStrideB, pVertexCountB - 1); - final float vertexB2X = VertexUtils.getVertex(pVerticesB, pVertexOffsetXB, pVertexStrideB, 0); - final float vertexB2Y = VertexUtils.getVertex(pVerticesB, pVertexOffsetYB, pVertexStrideB, 0); - if(LineCollisionChecker.checkLineCollision(vertexA1X, vertexA1Y, vertexA2X, vertexA2Y, vertexB1X, vertexB1Y, vertexB2X, vertexB2Y)){ - return true; - } - return false; - } - - /** - * Calls through to {@link ShapeCollisionChecker#checkContains(float[], int, int, int, int, float, float)} with the default parameters internally used by different AndEngine primitives. - * - * @param pVertices - * @param pVertexCount the number of vertices in pVertices - * @param pX - * @param pY - * @return - */ - public static boolean checkContains(final float[] pVertices, final int pVertexCount, final float pX, final float pY) { - return ShapeCollisionChecker.checkContains(pVertices, pVertexCount, Constants.VERTEX_INDEX_X, Constants.VERTEX_INDEX_Y, 2, pX, pY); - } - - /** - * Works with complex polygons! - * - * @see http://alienryderflex.com/polygon/ - * - * @param pVertices - * @param pVertexCount the number of vertices in pVertices - * @param pVertexOffsetX - * @param pVertexOffsetY - * @param pVertexStride - * @param pX - * @param pY - * @return true when the point defined by (pX, pY) is inside the polygon defined by pVertices, false. If the point is exactly on the edge of the polygon, the result can be true or false. - */ - public static boolean checkContains(final float[] pVertices, final int pVertexCount, final int pVertexOffsetX, final int pVertexOffsetY, final int pVertexStride, final float pX, final float pY) { - boolean odd = false; - - int j = pVertexCount - 1; - for(int i = 0; i < pVertexCount; i++) { - final float vertexXI = VertexUtils.getVertex(pVertices, pVertexOffsetX, pVertexStride, i); - final float vertexYI = VertexUtils.getVertex(pVertices, pVertexOffsetY, pVertexStride, i); - final float vertexXJ = VertexUtils.getVertex(pVertices, pVertexOffsetX, pVertexStride, j); - final float vertexYJ = VertexUtils.getVertex(pVertices, pVertexOffsetY, pVertexStride, j); - - if((((vertexYI < pY) && (vertexYJ >= pY)) || ((vertexYJ < pY) && (vertexYI >= pY))) && ((vertexXI <= pX) || (vertexXJ <= pX))) { - odd ^= ((vertexXI + (((pY - vertexYI) / (vertexYJ - vertexYI)) * (vertexXJ - vertexXI))) < pX); - } - j = i; - } - - return odd; - } - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== -} diff --git a/src/org/andengine/util/algorithm/collision/TriangleCollisionChecker.java b/src/org/andengine/util/algorithm/collision/TriangleCollisionChecker.java index 85c51820c..303b33d1d 100644 --- a/src/org/andengine/util/algorithm/collision/TriangleCollisionChecker.java +++ b/src/org/andengine/util/algorithm/collision/TriangleCollisionChecker.java @@ -4,12 +4,12 @@ import org.andengine.util.adt.transformation.Transformation; /** - * (c) Zynga 2011 + * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 17:47:42 - 30.08.2011 */ -public class TriangleCollisionChecker { +public final class TriangleCollisionChecker { // =========================================================== // Constants // =========================================================== @@ -26,6 +26,10 @@ public class TriangleCollisionChecker { // Constructors // =========================================================== + private TriangleCollisionChecker() { + + } + // =========================================================== // Getter & Setter // =========================================================== diff --git a/src/org/andengine/util/algorithm/hull/HullUtils.java b/src/org/andengine/util/algorithm/hull/HullUtils.java index 7b1fc44f1..1d8880131 100644 --- a/src/org/andengine/util/algorithm/hull/HullUtils.java +++ b/src/org/andengine/util/algorithm/hull/HullUtils.java @@ -2,12 +2,12 @@ /** - * (c) Zynga 2012 + * (c) 2012 Zynga Inc. * * @author Nicolas Gramlich * @since 14:52:48 - 08.02.2012 */ -public class HullUtils { +public final class HullUtils { // =========================================================== // Constants // =========================================================== @@ -20,6 +20,10 @@ public class HullUtils { // Constructors // =========================================================== + private HullUtils() { + + } + // =========================================================== // Getter & Setter // =========================================================== @@ -38,17 +42,17 @@ public static int indexOfLowestVertex(final float[] pVertices, final int pVertex float lowestVertexY = pVertices[pVertexOffsetY]; final int lastVertexOffset = pVertexCount * pVertexStride; - + /* Starting at one since, since we chose 0 as a the first candidate. */ - int currentVertexIndex = 1; + int currentVertexIndex = 1; int currentVertexOffsetY = pVertexStride + pVertexOffsetY; - + /* Loop to the end. */ - while(currentVertexOffsetY < lastVertexOffset) { + while (currentVertexOffsetY < lastVertexOffset) { final float currentVertexY = pVertices[currentVertexOffsetY]; /* Check if the current candidate is lower and if so, assign it. */ - if(currentVertexY < lowestVertexY) { + if (currentVertexY < lowestVertexY) { lowestVertexIndex = currentVertexIndex; lowestVertexY = currentVertexY; } @@ -62,7 +66,7 @@ public static void swap(final float[] pVertices, final int pVertexStride, final final int vertexOffsetA = pVertexIndexA * pVertexStride; final int vertexOffsetB = pVertexIndexB * pVertexStride; - for(int i = pVertexStride - 1; i >= 0; i--) { + for (int i = pVertexStride - 1; i >= 0; i--) { final float tmp = pVertices[vertexOffsetA + i]; pVertices[vertexOffsetA + i] = pVertices[vertexOffsetB + i]; pVertices[vertexOffsetB + i] = tmp; diff --git a/src/org/andengine/util/algorithm/hull/IHullAlgorithm.java b/src/org/andengine/util/algorithm/hull/IHullAlgorithm.java index 846d1dab4..e5b880754 100644 --- a/src/org/andengine/util/algorithm/hull/IHullAlgorithm.java +++ b/src/org/andengine/util/algorithm/hull/IHullAlgorithm.java @@ -2,9 +2,9 @@ /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 13:46:22 - 14.09.2010 */ diff --git a/src/org/andengine/util/algorithm/hull/JarvisMarch.java b/src/org/andengine/util/algorithm/hull/JarvisMarch.java index 3800a4b5f..ba0e3ddf7 100644 --- a/src/org/andengine/util/algorithm/hull/JarvisMarch.java +++ b/src/org/andengine/util/algorithm/hull/JarvisMarch.java @@ -10,13 +10,14 @@ * The Jarvis March algorithm marches around the hull, * like a ribbon wrapping itself around the points, * this algorithm also called the gift-wrapping algorithm. - * + * * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 14:01:18 - 14.09.2010 - * @see http://www.iti.fh-flensburg.de/lang/algorithmen/geo/ + * + * @see iti.fh-flensburg.de/lang/algorithmen/geo/ */ public class JarvisMarch implements IHullAlgorithm { // =========================================================== @@ -71,20 +72,20 @@ private int jarvisMarch(final float[] pVertices, final int pVertexCount, final i float nextHullVertexAngle = MathConstants.PI_TWICE; /* 360 degrees. */ /* Start searching one behind the already found hull vertices. */ - for(int j = hullVertexCount; j < pVertexCount; j++) { + for (int j = hullVertexCount; j < pVertexCount; j++) { final float possibleNextHullVertexX = VertexUtils.getVertex(pVertices, pVertexOffsetX, pVertexStride, j); final float possibleNextHullVertexY = VertexUtils.getVertex(pVertices, pVertexOffsetY, pVertexStride, j); /* Ignore identical vertices. */ - if(currentHullPointVertexX != possibleNextHullVertexX || currentHullPointVertexY != possibleNextHullVertexY) { + if (currentHullPointVertexX != possibleNextHullVertexX || currentHullPointVertexY != possibleNextHullVertexY) { final float dX = possibleNextHullVertexX - currentHullPointVertexX; final float dY = possibleNextHullVertexY - currentHullPointVertexY; - + float possibleNextHullVertexAngle = MathUtils.atan2(dY, dX); - if(possibleNextHullVertexAngle < 0) { + if (possibleNextHullVertexAngle < 0) { possibleNextHullVertexAngle += MathConstants.PI_TWICE; /* 360 degrees. */ } - if((possibleNextHullVertexAngle >= currentHullVertexAngle) && (possibleNextHullVertexAngle <= nextHullVertexAngle)) { + if ((possibleNextHullVertexAngle >= currentHullVertexAngle) && (possibleNextHullVertexAngle <= nextHullVertexAngle)) { nextHullVertexIndex = j; nextHullVertexAngle = possibleNextHullVertexAngle; } @@ -92,22 +93,22 @@ private int jarvisMarch(final float[] pVertices, final int pVertexCount, final i } /* Compare against first hull vertex. */ - if(hullVertexCount > 1) { + if (hullVertexCount > 1) { final float dX = firstHullVertexX - currentHullPointVertexX; final float dY = firstHullVertexY - currentHullPointVertexY; float possibleNextHullVertexAngle = MathUtils.atan2(dY, dX); - if(possibleNextHullVertexAngle < 0) { + if (possibleNextHullVertexAngle < 0) { possibleNextHullVertexAngle += MathConstants.PI_TWICE; /* 360 degrees. */ } - if((possibleNextHullVertexAngle >= currentHullVertexAngle) && (possibleNextHullVertexAngle <= nextHullVertexAngle)) { + if ((possibleNextHullVertexAngle >= currentHullVertexAngle) && (possibleNextHullVertexAngle <= nextHullVertexAngle)) { break; } } currentHullVertexAngle = nextHullVertexAngle; currentHullVertexIndex = nextHullVertexIndex; - } while(currentHullVertexIndex > 0); + } while (currentHullVertexIndex > 0); return hullVertexCount; } diff --git a/src/org/andengine/util/algorithm/path/ICostFunction.java b/src/org/andengine/util/algorithm/path/ICostFunction.java index 5631430a2..0f705cf0d 100644 --- a/src/org/andengine/util/algorithm/path/ICostFunction.java +++ b/src/org/andengine/util/algorithm/path/ICostFunction.java @@ -1,9 +1,9 @@ package org.andengine.util.algorithm.path; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 23:00:24 - 16.08.2010 */ diff --git a/src/org/andengine/util/algorithm/path/IPathFinder.java b/src/org/andengine/util/algorithm/path/IPathFinder.java index 5e1e9321d..c55ca11c2 100644 --- a/src/org/andengine/util/algorithm/path/IPathFinder.java +++ b/src/org/andengine/util/algorithm/path/IPathFinder.java @@ -3,9 +3,9 @@ import org.andengine.util.algorithm.path.astar.IAStarHeuristic; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 22:57:13 - 16.08.2010 */ @@ -22,19 +22,19 @@ public interface IPathFinder { public Path findPath(final IPathFinderMap pPathFinderMap, final int pXMin, final int pYMin, final int pXMax, final int pYMax, final T pEntity, final int pFromX, final int pFromY, final int pToX, final int pToY, final boolean pAllowDiagonal, final IAStarHeuristic pAStarHeuristic, final ICostFunction pCostFunction, final float pMaxCost); public Path findPath(final IPathFinderMap pPathFinderMap, final int pXMin, final int pYMin, final int pXMax, final int pYMax, final T pEntity, final int pFromX, final int pFromY, final int pToX, final int pToY, final boolean pAllowDiagonal, final IAStarHeuristic pAStarHeuristic, final ICostFunction pCostFunction, final float pMaxCost, final IPathFinderListener pPathFinderListener); - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== - + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== + public interface IPathFinderListener { // =========================================================== // Constants // =========================================================== - + // =========================================================== // Fields // =========================================================== - + public void onVisited(final T pEntity, final int pX, final int pY); } } diff --git a/src/org/andengine/util/algorithm/path/IPathFinderMap.java b/src/org/andengine/util/algorithm/path/IPathFinderMap.java index 782e5bd7f..d7c9f7e65 100644 --- a/src/org/andengine/util/algorithm/path/IPathFinderMap.java +++ b/src/org/andengine/util/algorithm/path/IPathFinderMap.java @@ -2,9 +2,9 @@ /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 23:00:24 - 16.08.2010 */ diff --git a/src/org/andengine/util/algorithm/path/Path.java b/src/org/andengine/util/algorithm/path/Path.java index e4da8eb7e..dada81257 100644 --- a/src/org/andengine/util/algorithm/path/Path.java +++ b/src/org/andengine/util/algorithm/path/Path.java @@ -1,10 +1,12 @@ package org.andengine.util.algorithm.path; +import org.andengine.util.adt.spatial.Direction; + /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 23:00:24 - 16.08.2010 */ @@ -77,8 +79,8 @@ public void set(final int pIndex, final int pX, final int pY) { public boolean contains(final int pX, final int pY) { final int[] xs = this.mXs; final int[] ys = this.mYs; - for(int i = this.getLength() - 1; i >= 0; i--) { - if(xs[i] == pX && ys[i] == pY) { + for (int i = this.getLength() - 1; i >= 0; i--) { + if (xs[i] == pX && ys[i] == pY) { return true; } } @@ -86,7 +88,7 @@ public boolean contains(final int pX, final int pY) { } public Direction getDirectionToPreviousStep(final int pIndex) { - if(pIndex == 0) { + if (pIndex == 0) { return null; } else { final int dX = this.getX(pIndex - 1) - this.getX(pIndex); @@ -96,7 +98,7 @@ public Direction getDirectionToPreviousStep(final int pIndex) { } public Direction getDirectionToNextStep(final int pIndex) { - if(pIndex == this.getLength() - 1) { + if (pIndex == this.getLength() - 1) { return null; } else { final int dX = this.getX(pIndex + 1) - this.getX(pIndex); diff --git a/src/org/andengine/util/algorithm/path/astar/AStarPathFinder.java b/src/org/andengine/util/algorithm/path/astar/AStarPathFinder.java index 534fc785e..13be0af1e 100644 --- a/src/org/andengine/util/algorithm/path/astar/AStarPathFinder.java +++ b/src/org/andengine/util/algorithm/path/astar/AStarPathFinder.java @@ -4,7 +4,6 @@ import org.andengine.util.adt.map.LongSparseArray; import org.andengine.util.adt.queue.IQueue; import org.andengine.util.adt.queue.SortedQueue; -import org.andengine.util.adt.queue.UniqueQueue; import org.andengine.util.adt.spatial.bounds.util.IntBoundsUtils; import org.andengine.util.algorithm.path.ICostFunction; import org.andengine.util.algorithm.path.IPathFinder; @@ -16,7 +15,7 @@ * * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @author Greg Haynes * @since 23:16:17 - 16.08.2010 @@ -54,7 +53,7 @@ public Path findPath(final IPathFinderMap pPathFinderMap, final int pXMin, fi @Override public Path findPath(final IPathFinderMap pPathFinderMap, final int pXMin, final int pYMin, final int pXMax, final int pYMax, final T pEntity, final int pFromX, final int pFromY, final int pToX, final int pToY, final boolean pAllowDiagonal, final IAStarHeuristic pAStarHeuristic, final ICostFunction pCostFunction, final float pMaxCost, final IPathFinderListener pPathFinderListener) { - if(((pFromX == pToX) && (pFromY == pToY)) || pPathFinderMap.isBlocked(pFromX, pFromY, pEntity) || pPathFinderMap.isBlocked(pToX, pToY, pEntity)) { + if (((pFromX == pToX) && (pFromY == pToY)) || pPathFinderMap.isBlocked(pFromX, pFromY, pEntity) || pPathFinderMap.isBlocked(pToX, pToY, pEntity)) { return null; } @@ -75,24 +74,24 @@ public Path findPath(final IPathFinderMap pPathFinderMap, final int pXMin, fi sortedOpenNodes.enter(fromNode); Node currentNode = null; - while(openNodes.size() > 0) { + while (openNodes.size() > 0) { /* The first Node in the open list is the one with the lowest cost. */ currentNode = sortedOpenNodes.poll(); final long currentNodeID = currentNode.mID; - if(currentNodeID == toNodeID) { + if (currentNodeID == toNodeID) { break; } visitedNodes.put(currentNodeID, currentNode); /* Loop over all neighbors of this position. */ - for(int dX = -1; dX <= 1; dX++) { - for(int dY = -1; dY <= 1; dY++) { - if((dX == 0) && (dY == 0)) { + for (int dX = -1; dX <= 1; dX++) { + for (int dY = -1; dY <= 1; dY++) { + if ((dX == 0) && (dY == 0)) { continue; } - if(!allowDiagonalMovement && (dX != 0) && (dY != 0)) { + if (!allowDiagonalMovement && (dX != 0) && (dY != 0)) { continue; } @@ -100,18 +99,18 @@ public Path findPath(final IPathFinderMap pPathFinderMap, final int pXMin, fi final int neighborNodeY = dY + currentNode.mY; final long neighborNodeID = Node.calculateID(neighborNodeX, neighborNodeY); - if(!IntBoundsUtils.contains(pXMin, pYMin, pXMax, pYMax, neighborNodeX, neighborNodeY) || pPathFinderMap.isBlocked(neighborNodeX, neighborNodeY, pEntity)) { + if (!IntBoundsUtils.contains(pXMin, pYMin, pXMax, pYMax, neighborNodeX, neighborNodeY) || pPathFinderMap.isBlocked(neighborNodeX, neighborNodeY, pEntity)) { continue; } - if(visitedNodes.indexOfKey(neighborNodeID) >= 0) { + if (visitedNodes.indexOfKey(neighborNodeID) >= 0) { continue; } Node neighborNode = openNodes.get(neighborNodeID); final boolean neighborNodeIsNew; /* Check if neighbor exists. */ - if(neighborNode == null) { + if (neighborNode == null) { neighborNodeIsNew = true; neighborNode = new Node(neighborNodeX, neighborNodeY, pAStarHeuristic.getExpectedRestCost(pPathFinderMap, pEntity, neighborNodeX, neighborNodeY, pToX, pToY)); } else { @@ -121,14 +120,14 @@ public Path findPath(final IPathFinderMap pPathFinderMap, final int pXMin, fi /* Update cost of neighbor as cost of current plus step from current to neighbor. */ final float costFromCurrentToNeigbor = pCostFunction.getCost(pPathFinderMap, currentNode.mX, currentNode.mY, neighborNodeX, neighborNodeY, pEntity); final float neighborNodeCost = currentNode.mCost + costFromCurrentToNeigbor; - if(neighborNodeCost > pMaxCost) { + if (neighborNodeCost > pMaxCost) { /* Too expensive -> remove if isn't a new node. */ - if(!neighborNodeIsNew) { + if (!neighborNodeIsNew) { openNodes.remove(neighborNodeID); } } else { neighborNode.setParent(currentNode, costFromCurrentToNeigbor); - if(neighborNodeIsNew) { + if (neighborNodeIsNew) { openNodes.put(neighborNodeID, neighborNode); } else { /* Remove so that re-insertion puts it to the correct spot. */ @@ -137,7 +136,7 @@ public Path findPath(final IPathFinderMap pPathFinderMap, final int pXMin, fi sortedOpenNodes.enter(neighborNode); - if(pPathFinderListener != null) { + if (pPathFinderListener != null) { pPathFinderListener.onVisited(pEntity, neighborNodeX, neighborNodeY); } } @@ -152,14 +151,14 @@ public Path findPath(final IPathFinderMap pPathFinderMap, final int pXMin, fi sortedOpenNodes.clear(); /* Check if a path was found. */ - if(currentNode.mID != toNodeID) { + if (currentNode.mID != toNodeID) { return null; } /* Calculate path length. */ int length = 1; Node tmp = currentNode; - while(tmp.mID != fromNodeID) { + while (tmp.mID != fromNodeID) { tmp = tmp.mParent; length++; } @@ -168,7 +167,7 @@ public Path findPath(final IPathFinderMap pPathFinderMap, final int pXMin, fi final Path path = new Path(length); int index = length - 1; tmp = currentNode; - while(tmp.mID != fromNodeID) { + while (tmp.mID != fromNodeID) { path.set(index, tmp.mX, tmp.mY); tmp = tmp.mParent; index--; @@ -186,7 +185,7 @@ public Path findPath(final IPathFinderMap pPathFinderMap, final int pXMin, fi // Inner and Anonymous Classes // =========================================================== - private static final class Node implements Comparable { + /* package */ static final class Node implements Comparable { // =========================================================== // Constants // =========================================================== @@ -234,9 +233,9 @@ public void setParent(final Node pParent, final float pCost) { @Override public int compareTo(final Node pNode) { final float diff = this.mTotalCost - pNode.mTotalCost; - if(diff > 0) { + if (diff > 0) { return 1; - } else if(diff < 0) { + } else if (diff < 0) { return -1; } else { return 0; @@ -245,14 +244,14 @@ public int compareTo(final Node pNode) { @Override public boolean equals(final Object pOther) { - if(this == pOther) { + if (this == pOther) { return true; - } else if(pOther == null) { + } else if (pOther == null) { return false; - } else if(this.getClass() != pOther.getClass()) { + } else if (this.getClass() != pOther.getClass()) { return false; } - return this.equals((Node)pOther); + return this.equals((Node) pOther); } @Override @@ -265,7 +264,7 @@ public String toString() { // =========================================================== public static long calculateID(final int pX, final int pY) { - return (((long)pX) << 32) | pY; + return (((long) pX) << 32) | (((long) pY) & 0xFFFFFFFFL); } public boolean equals(final Node pNode) { diff --git a/src/org/andengine/util/algorithm/path/astar/EuclideanHeuristic.java b/src/org/andengine/util/algorithm/path/astar/EuclideanHeuristic.java index 8e3a934a4..0bef540c5 100644 --- a/src/org/andengine/util/algorithm/path/astar/EuclideanHeuristic.java +++ b/src/org/andengine/util/algorithm/path/astar/EuclideanHeuristic.java @@ -2,12 +2,10 @@ import org.andengine.util.algorithm.path.IPathFinderMap; -import android.util.FloatMath; - /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 22:58:01 - 16.08.2010 */ @@ -37,7 +35,7 @@ public float getExpectedRestCost(final IPathFinderMap pPathFinderMap, final T final float dX = pToX - pFromX; final float dY = pToY - pFromY; - return FloatMath.sqrt(dX * dX + dY * dY); + return (float) Math.sqrt(dX * dX + dY * dY); } // =========================================================== diff --git a/src/org/andengine/util/algorithm/path/astar/IAStarHeuristic.java b/src/org/andengine/util/algorithm/path/astar/IAStarHeuristic.java index 2471588da..03432e429 100644 --- a/src/org/andengine/util/algorithm/path/astar/IAStarHeuristic.java +++ b/src/org/andengine/util/algorithm/path/astar/IAStarHeuristic.java @@ -3,9 +3,9 @@ import org.andengine.util.algorithm.path.IPathFinderMap; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 22:59:20 - 16.08.2010 */ diff --git a/src/org/andengine/util/algorithm/path/astar/ManhattanHeuristic.java b/src/org/andengine/util/algorithm/path/astar/ManhattanHeuristic.java index 2e8fe85be..dc35a857b 100644 --- a/src/org/andengine/util/algorithm/path/astar/ManhattanHeuristic.java +++ b/src/org/andengine/util/algorithm/path/astar/ManhattanHeuristic.java @@ -3,9 +3,9 @@ import org.andengine.util.algorithm.path.IPathFinderMap; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 22:58:01 - 16.08.2010 */ @@ -32,7 +32,7 @@ public class ManhattanHeuristic implements IAStarHeuristic { @Override public float getExpectedRestCost(final IPathFinderMap pPathFinderMap, final T pEntity, final int pFromX, final int pFromY, final int pToX, final int pToY) { - return Math.abs(pFromX - pToX) + Math.abs(pToX - pToY); + return Math.abs(pFromX - pToX) + Math.abs(pFromY - pToY); } // =========================================================== diff --git a/src/org/andengine/util/algorithm/path/astar/NullHeuristic.java b/src/org/andengine/util/algorithm/path/astar/NullHeuristic.java index 3418aef95..5ceab683a 100644 --- a/src/org/andengine/util/algorithm/path/astar/NullHeuristic.java +++ b/src/org/andengine/util/algorithm/path/astar/NullHeuristic.java @@ -3,9 +3,9 @@ import org.andengine.util.algorithm.path.IPathFinderMap; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 22:58:01 - 16.08.2010 */ diff --git a/src/org/andengine/util/algorithm/sort/InsertionSorter.java b/src/org/andengine/util/algorithm/sort/InsertionSorter.java index 2904ec692..f60427e48 100644 --- a/src/org/andengine/util/algorithm/sort/InsertionSorter.java +++ b/src/org/andengine/util/algorithm/sort/InsertionSorter.java @@ -6,9 +6,9 @@ import org.andengine.util.adt.list.IList; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 14:14:31 - 06.08.2010 * @param @@ -36,14 +36,14 @@ public class InsertionSorter extends Sorter { @Override public void sort(final T[] pArray, final int pStart, final int pEnd, final Comparator pComparator) { - for(int i = pStart + 1; i < pEnd; i++) { + for (int i = pStart + 1; i < pEnd; i++) { final T current = pArray[i]; T prev = pArray[i - 1]; - if(pComparator.compare(current, prev) < 0) { + if (pComparator.compare(current, prev) < 0) { int j = i; do { pArray[j--] = prev; - } while(j > pStart && pComparator.compare(current, prev = pArray[j - 1]) < 0); + } while (j > pStart && pComparator.compare(current, prev = pArray[j - 1]) < 0); pArray[j] = current; } } @@ -52,14 +52,14 @@ public void sort(final T[] pArray, final int pStart, final int pEnd, final Compa @Override public void sort(final List pList, final int pStart, final int pEnd, final Comparator pComparator) { - for(int i = pStart + 1; i < pEnd; i++) { + for (int i = pStart + 1; i < pEnd; i++) { final T current = pList.get(i); T prev = pList.get(i - 1); - if(pComparator.compare(current, prev) < 0) { + if (pComparator.compare(current, prev) < 0) { int j = i; do { pList.set(j--, prev); - } while(j > pStart && pComparator.compare(current, prev = pList.get(j - 1)) < 0); + } while (j > pStart && pComparator.compare(current, prev = pList.get(j - 1)) < 0); pList.set(j, current); } } @@ -68,14 +68,14 @@ public void sort(final List pList, final int pStart, final int pEnd, final Co @Override public void sort(final IList pList, final int pStart, final int pEnd, final Comparator pComparator) { - for(int i = pStart + 1; i < pEnd; i++) { + for (int i = pStart + 1; i < pEnd; i++) { final T current = pList.get(i); T prev = pList.get(i - 1); - if(pComparator.compare(current, prev) < 0) { + if (pComparator.compare(current, prev) < 0) { int j = i; do { pList.set(j--, prev); - } while(j > pStart && pComparator.compare(current, prev = pList.get(j - 1)) < 0); + } while (j > pStart && pComparator.compare(current, prev = pList.get(j - 1)) < 0); pList.set(j, current); } } diff --git a/src/org/andengine/util/algorithm/sort/Sorter.java b/src/org/andengine/util/algorithm/sort/Sorter.java index 4704122d5..249d83c04 100644 --- a/src/org/andengine/util/algorithm/sort/Sorter.java +++ b/src/org/andengine/util/algorithm/sort/Sorter.java @@ -6,9 +6,9 @@ import org.andengine.util.adt.list.IList; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 14:14:39 - 06.08.2010 * @param @@ -42,15 +42,15 @@ public abstract class Sorter { // Methods // =========================================================== - public final void sort(final T[] pArray, final Comparator pComparator){ + public final void sort(final T[] pArray, final Comparator pComparator) { this.sort(pArray, 0, pArray.length, pComparator); } - public final void sort(final List pList, final Comparator pComparator){ + public final void sort(final List pList, final Comparator pComparator) { this.sort(pList, 0, pList.size(), pComparator); } - public final void sort(final IList pList, final Comparator pComparator){ + public final void sort(final IList pList, final Comparator pComparator) { this.sort(pList, 0, pList.size(), pComparator); } diff --git a/src/org/andengine/util/animationpack/AnimationPack.java b/src/org/andengine/util/animationpack/AnimationPack.java index de98b176b..4b61bd42e 100644 --- a/src/org/andengine/util/animationpack/AnimationPack.java +++ b/src/org/andengine/util/animationpack/AnimationPack.java @@ -4,7 +4,7 @@ /** - * (c) Zynga 2012 + * (c) 2012 Zynga Inc. * * @author Nicolas Gramlich * @since 16:58:15 - 03.05.2012 diff --git a/src/org/andengine/util/animationpack/AnimationPackLoader.java b/src/org/andengine/util/animationpack/AnimationPackLoader.java index af090df00..f04b0627b 100644 --- a/src/org/andengine/util/animationpack/AnimationPackLoader.java +++ b/src/org/andengine/util/animationpack/AnimationPackLoader.java @@ -18,7 +18,7 @@ import android.content.res.AssetManager; /** - * (c) Zynga 2011 + * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 17:05:15 - 29.07.2011 @@ -65,7 +65,7 @@ public AnimationPack loadFromAsset(final String pAssetPath, final String pAssetB } public AnimationPack load(final InputStream pInputStream, final String pAssetBasePath) throws AnimationPackParseException { - try{ + try { final SAXParserFactory spf = SAXParserFactory.newInstance(); final SAXParser sp = spf.newSAXParser(); diff --git a/src/org/andengine/util/animationpack/AnimationPackParser.java b/src/org/andengine/util/animationpack/AnimationPackParser.java index 6e4dc49d8..48c826146 100644 --- a/src/org/andengine/util/animationpack/AnimationPackParser.java +++ b/src/org/andengine/util/animationpack/AnimationPackParser.java @@ -18,7 +18,7 @@ import android.content.res.AssetManager; /** - * (c) Zynga 2011 + * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 17:19:26 - 29.07.2011 @@ -88,9 +88,9 @@ public AnimationPack getAnimationPack() { @Override public void startElement(final String pUri, final String pLocalName, final String pQualifiedName, final Attributes pAttributes) throws SAXException { - if(pLocalName.equals(AnimationPackParser.TAG_ANIMATIONPACK)) { + if (pLocalName.equals(AnimationPackParser.TAG_ANIMATIONPACK)) { final int version = SAXUtils.getIntAttributeOrThrow(pAttributes, AnimationPackParser.TAG_ANIMATIONPACK_ATTRIBUTE_VERSION); - if(version != 1) { + if (version != 1) { throw new AnimationPackParseException("Unexpected version: '" + version + "'."); } @@ -98,21 +98,21 @@ public void startElement(final String pUri, final String pLocalName, final Strin this.mTexturePackLibrary = new TexturePackLibrary(); this.mAnimationPackTiledTextureRegionLibrary = new AnimationPackTiledTextureRegionLibrary(); this.mAnimationPack = new AnimationPack(this.mTexturePackLibrary, this.mAnimationPackTiledTextureRegionLibrary); - } else if(pLocalName.equals(AnimationPackParser.TAG_TEXTUREPACKS)) { + } else if (pLocalName.equals(AnimationPackParser.TAG_TEXTUREPACKS)) { /* Nothing. */ - } else if(pLocalName.equals(AnimationPackParser.TAG_TEXTUREPACK)) { + } else if (pLocalName.equals(AnimationPackParser.TAG_TEXTUREPACK)) { final String texturePackName = SAXUtils.getAttributeOrThrow(pAttributes, AnimationPackParser.TAG_TEXTUREPACK_ATTRIBUTE_FILENAME); final String texturePackPath = this.mAssetBasePath + texturePackName; final TexturePack texturePack = this.mTexturePackLoader.loadFromAsset(texturePackPath, this.mAssetBasePath); this.mTexturePackLibrary.put(texturePackName, texturePack); texturePack.loadTexture(); - } else if(pLocalName.equals(AnimationPackParser.TAG_ANIMATIONS)) { + } else if (pLocalName.equals(AnimationPackParser.TAG_ANIMATIONS)) { /* Nothing. */ - } else if(pLocalName.equals(AnimationPackParser.TAG_ANIMATION)) { + } else if (pLocalName.equals(AnimationPackParser.TAG_ANIMATION)) { this.mCurrentAnimationName = SAXUtils.getAttributeOrThrow(pAttributes, AnimationPackParser.TAG_ANIMATION_ATTRIBUTE_NAME); this.mCurrentAnimationLoopCount = SAXUtils.getIntAttribute(pAttributes, AnimationPackParser.TAG_ANIMATION_ATTRIBUTE_LOOPCOUNT, IAnimationData.LOOP_CONTINUOUS); - } else if(pLocalName.equals(AnimationPackParser.TAG_ANIMATIONFRAME)) { + } else if (pLocalName.equals(AnimationPackParser.TAG_ANIMATIONFRAME)) { final int duration = SAXUtils.getIntAttributeOrThrow(pAttributes, AnimationPackParser.TAG_ANIMATIONFRAME_ATTRIBUTE_DURATION); this.mCurrentAnimationFrameDurations.add(duration); @@ -126,15 +126,15 @@ public void startElement(final String pUri, final String pLocalName, final Strin @Override public void endElement(final String pUri, final String pLocalName, final String pQualifiedName) throws SAXException { - if(pLocalName.equals(AnimationPackParser.TAG_ANIMATIONPACK)) { + if (pLocalName.equals(AnimationPackParser.TAG_ANIMATIONPACK)) { /* Nothing. */ - } else if(pLocalName.equals(AnimationPackParser.TAG_TEXTUREPACKS)) { + } else if (pLocalName.equals(AnimationPackParser.TAG_TEXTUREPACKS)) { /* Nothing. */ - } else if(pLocalName.equals(AnimationPackParser.TAG_TEXTUREPACK)) { + } else if (pLocalName.equals(AnimationPackParser.TAG_TEXTUREPACK)) { /* Nothing. */ - } else if(pLocalName.equals(AnimationPackParser.TAG_ANIMATIONS)) { + } else if (pLocalName.equals(AnimationPackParser.TAG_ANIMATIONS)) { /* Nothing. */ - } else if(pLocalName.equals(AnimationPackParser.TAG_ANIMATION)) { + } else if (pLocalName.equals(AnimationPackParser.TAG_ANIMATION)) { final int currentAnimationFrameFrameCount = this.mCurrentAnimationFrameDurations.size(); final long[] frameDurations = this.mCurrentAnimationFrameDurations.toArray(); final TexturePackTextureRegion[] textureRegions = new TexturePackTextureRegion[currentAnimationFrameFrameCount]; @@ -147,7 +147,7 @@ public void endElement(final String pUri, final String pLocalName, final String this.mCurrentAnimationLoopCount = IAnimationData.LOOP_CONTINUOUS; this.mCurrentAnimationFrameDurations.clear(); this.mCurrentAnimationFrameTexturePackTextureRegions.clear(); - } else if(pLocalName.equals(AnimationPackParser.TAG_ANIMATIONFRAME)) { + } else if (pLocalName.equals(AnimationPackParser.TAG_ANIMATIONFRAME)) { /* Nothing. */ } else { throw new AnimationPackParseException("Unexpected end tag: '" + pLocalName + "'."); diff --git a/src/org/andengine/util/animationpack/AnimationPackTiledTextureRegion.java b/src/org/andengine/util/animationpack/AnimationPackTiledTextureRegion.java index e726c6249..f3d1fad6c 100644 --- a/src/org/andengine/util/animationpack/AnimationPackTiledTextureRegion.java +++ b/src/org/andengine/util/animationpack/AnimationPackTiledTextureRegion.java @@ -6,7 +6,7 @@ import org.andengine.opengl.texture.region.TiledTextureRegion; /** - * (c) Zynga 2012 + * (c) 2012 Zynga Inc. * * @author Nicolas Gramlich * @since 17:17:17 - 03.05.2012 @@ -33,8 +33,8 @@ public AnimationPackTiledTextureRegion(final String pAnimationName, final long[] this.mAnimationName = pAnimationName; final int frameCount = pFrameDurations.length; - final int[] frames= new int[frameCount]; - for(int i = 0; i < frameCount; i++) { + final int[] frames = new int[frameCount]; + for (int i = 0; i < frameCount; i++) { frames[i] = i; } diff --git a/src/org/andengine/util/animationpack/AnimationPackTiledTextureRegionLibrary.java b/src/org/andengine/util/animationpack/AnimationPackTiledTextureRegionLibrary.java index dc536126f..4b44cb0fb 100644 --- a/src/org/andengine/util/animationpack/AnimationPackTiledTextureRegionLibrary.java +++ b/src/org/andengine/util/animationpack/AnimationPackTiledTextureRegionLibrary.java @@ -3,7 +3,7 @@ import java.util.HashMap; /** - * (c) Zynga 2012 + * (c) 2012 Zynga Inc. * * @author Nicolas Gramlich * @since 17:17:37 - 03.05.2012 diff --git a/src/org/andengine/util/animationpack/exception/AnimationPackParseException.java b/src/org/andengine/util/animationpack/exception/AnimationPackParseException.java index d69ef60e9..6d2cc174d 100644 --- a/src/org/andengine/util/animationpack/exception/AnimationPackParseException.java +++ b/src/org/andengine/util/animationpack/exception/AnimationPackParseException.java @@ -3,7 +3,7 @@ import org.xml.sax.SAXException; /** - * (c) Zynga 2012 + * (c) 2012 Zynga Inc. * * @author Nicolas Gramlich * @since 18:03:45 - 03.06.2012 diff --git a/src/org/andengine/util/base64/Base64.java b/src/org/andengine/util/base64/Base64.java deleted file mode 100644 index 9e4a40b43..000000000 --- a/src/org/andengine/util/base64/Base64.java +++ /dev/null @@ -1,761 +0,0 @@ -/* - * 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. - */ - -package org.andengine.util.base64; - -import java.io.UnsupportedEncodingException; - -import android.util.Base64OutputStream; - -/** - * Utilities for encoding and decoding the Base64 representation of - * binary data. See RFCs 2045 and 3548. - */ -public class Base64 { - /** - * Default values for encoder/decoder flags. - */ - public static final int DEFAULT = 0; - - /** - * Encoder flag bit to omit the padding '=' characters at the end - * of the output (if any). - */ - public static final int NO_PADDING = 1; - - /** - * Encoder flag bit to omit all line terminators (i.e., the output - * will be on one long line). - */ - public static final int NO_WRAP = 2; - - /** - * Encoder flag bit to indicate lines should be terminated with a - * CRLF pair instead of just an LF. Has no effect if {@code - * NO_WRAP} is specified as well. - */ - public static final int CRLF = 4; - - /** - * Encoder/decoder flag bit to indicate using the "URL and - * filename safe" variant of Base64 (see RFC 3548 section 4) where - * {@code -} and {@code _} are used in place of {@code +} and - * {@code /}. - */ - public static final int URL_SAFE = 8; - - /** - * Flag to pass to {@link Base64OutputStream} to indicate that it - * should not close the output stream it is wrapping when it - * itself is closed. - */ - public static final int NO_CLOSE = 16; - - // -------------------------------------------------------- - // shared code - // -------------------------------------------------------- - - /* package */ static abstract class Coder { - public byte[] output; - public int op; - - /** - * Encode/decode another block of input data. this.output is - * provided by the caller, and must be big enough to hold all - * the coded data. On exit, this.opwill be set to the length - * of the coded data. - * - * @param finish true if this is the final call to process for - * this object. Will finalize the coder state and - * include any final bytes in the output. - * - * @return true if the input so far is good; false if some - * error has been detected in the input stream.. - */ - public abstract boolean process(byte[] input, int offset, int len, boolean finish); - - /** - * @return the maximum number of bytes a call to process() - * could produce for the given number of input bytes. This may - * be an overestimate. - */ - public abstract int maxOutputSize(int len); - } - - // -------------------------------------------------------- - // decoding - // -------------------------------------------------------- - - /** - * Decode the Base64-encoded data in input and return the data in - * a new byte array. - * - *

    The padding '=' characters at the end are considered optional, but - * if any are present, there must be the correct number of them. - * - * @param str the input String to decode, which is converted to - * bytes using the default charset - * @param flags controls certain features of the decoded output. - * Pass {@code DEFAULT} to decode standard Base64. - * - * @throws IllegalArgumentException if the input contains - * incorrect padding - */ - public static byte[] decode(final String str, final int flags) { - return Base64.decode(str.getBytes(), flags); - } - - /** - * Decode the Base64-encoded data in input and return the data in - * a new byte array. - * - *

    The padding '=' characters at the end are considered optional, but - * if any are present, there must be the correct number of them. - * - * @param input the input array to decode - * @param flags controls certain features of the decoded output. - * Pass {@code DEFAULT} to decode standard Base64. - * - * @throws IllegalArgumentException if the input contains - * incorrect padding - */ - public static byte[] decode(final byte[] input, final int flags) { - return Base64.decode(input, 0, input.length, flags); - } - - /** - * Decode the Base64-encoded data in input and return the data in - * a new byte array. - * - *

    The padding '=' characters at the end are considered optional, but - * if any are present, there must be the correct number of them. - * - * @param input the data to decode - * @param offset the position within the input array at which to start - * @param len the number of bytes of input to decode - * @param flags controls certain features of the decoded output. - * Pass {@code DEFAULT} to decode standard Base64. - * - * @throws IllegalArgumentException if the input contains - * incorrect padding - */ - public static byte[] decode(final byte[] input, final int offset, final int len, final int flags) { - // Allocate space for the most data the input could represent. - // (It could contain less if it contains whitespace, etc.) - final Decoder decoder = new Decoder(flags, new byte[len*3/4]); - - if (!decoder.process(input, offset, len, true)) { - throw new IllegalArgumentException("bad base-64"); - } - - // Maybe we got lucky and allocated exactly enough output space. - if (decoder.op == decoder.output.length) { - return decoder.output; - } - - // Need to shorten the array, so allocate a new one of the - // right size and copy. - final byte[] temp = new byte[decoder.op]; - System.arraycopy(decoder.output, 0, temp, 0, decoder.op); - return temp; - } - - /* package */ static class Decoder extends Coder { - /** - * Lookup table for turning bytes into their position in the - * Base64 alphabet. - */ - private static final int DECODE[] = { - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, - 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -2, -1, -1, - -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, - 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, - -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, - 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - }; - - /** - * Decode lookup table for the "web safe" variant (RFC 3548 - * sec. 4) where - and _ replace + and /. - */ - private static final int DECODE_WEBSAFE[] = { - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, - 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -2, -1, -1, - -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, - 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, 63, - -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, - 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - }; - - /** Non-data values in the DECODE arrays. */ - private static final int SKIP = -1; - private static final int EQUALS = -2; - - /** - * States 0-3 are reading through the next input tuple. - * State 4 is having read one '=' and expecting exactly - * one more. - * State 5 is expecting no more data or padding characters - * in the input. - * State 6 is the error state; an error has been detected - * in the input and no future input can "fix" it. - */ - private int state; // state number (0 to 6) - private int value; - - final private int[] alphabet; - - public Decoder(final int flags, final byte[] output) { - this.output = output; - - this.alphabet = ((flags & URL_SAFE) == 0) ? DECODE : DECODE_WEBSAFE; - this.state = 0; - this.value = 0; - } - - /** - * @return an overestimate for the number of bytes {@code - * len} bytes could decode to. - */ - @Override - public int maxOutputSize(final int len) { - return len * 3/4 + 10; - } - - /** - * Decode another block of input data. - * - * @return true if the state machine is still healthy. false if - * bad base-64 data has been detected in the input stream. - */ - @Override - public boolean process(final byte[] input, final int offset, int len, final boolean finish) { - if (this.state == 6) { - return false; - } - - int p = offset; - len += offset; - - // Using local variables makes the decoder about 12% - // faster than if we manipulate the member variables in - // the loop. (Even alphabet makes a measurable - // difference, which is somewhat surprising to me since - // the member variable is final.) - int state = this.state; - int value = this.value; - int op = 0; - final byte[] output = this.output; - final int[] alphabet = this.alphabet; - - while (p < len) { - // Try the fast path: we're starting a new tuple and the - // next four bytes of the input stream are all data - // bytes. This corresponds to going through states - // 0-1-2-3-0. We expect to use this method for most of - // the data. - // - // If any of the next four bytes of input are non-data - // (whitespace, etc.), value will end up negative. (All - // the non-data values in decode are small negative - // numbers, so shifting any of them up and or'ing them - // together will result in a value with its top bit set.) - // - // You can remove this whole block and the output should - // be the same, just slower. - if (state == 0) { - while (p+4 <= len && - (value = ((alphabet[input[p] & 0xff] << 18) | - (alphabet[input[p+1] & 0xff] << 12) | - (alphabet[input[p+2] & 0xff] << 6) | - (alphabet[input[p+3] & 0xff]))) >= 0) { - output[op+2] = (byte) value; - output[op+1] = (byte) (value >> 8); - output[op] = (byte) (value >> 16); - op += 3; - p += 4; - } - if (p >= len) { - break; - } - } - - // The fast path isn't available -- either we've read a - // partial tuple, or the next four input bytes aren't all - // data, or whatever. Fall back to the slower state - // machine implementation. - - final int d = alphabet[input[p++] & 0xff]; - - switch (state) { - case 0: - if (d >= 0) { - value = d; - ++state; - } else if (d != SKIP) { - this.state = 6; - return false; - } - break; - - case 1: - if (d >= 0) { - value = (value << 6) | d; - ++state; - } else if (d != SKIP) { - this.state = 6; - return false; - } - break; - - case 2: - if (d >= 0) { - value = (value << 6) | d; - ++state; - } else if (d == EQUALS) { - // Emit the last (partial) output tuple; - // expect exactly one more padding character. - output[op++] = (byte) (value >> 4); - state = 4; - } else if (d != SKIP) { - this.state = 6; - return false; - } - break; - - case 3: - if (d >= 0) { - // Emit the output triple and return to state 0. - value = (value << 6) | d; - output[op+2] = (byte) value; - output[op+1] = (byte) (value >> 8); - output[op] = (byte) (value >> 16); - op += 3; - state = 0; - } else if (d == EQUALS) { - // Emit the last (partial) output tuple; - // expect no further data or padding characters. - output[op+1] = (byte) (value >> 2); - output[op] = (byte) (value >> 10); - op += 2; - state = 5; - } else if (d != SKIP) { - this.state = 6; - return false; - } - break; - - case 4: - if (d == EQUALS) { - ++state; - } else if (d != SKIP) { - this.state = 6; - return false; - } - break; - - case 5: - if (d != SKIP) { - this.state = 6; - return false; - } - break; - } - } - - if (!finish) { - // We're out of input, but a future call could provide - // more. - this.state = state; - this.value = value; - this.op = op; - return true; - } - - // Done reading input. Now figure out where we are left in - // the state machine and finish up. - - switch (state) { - case 0: - // Output length is a multiple of three. Fine. - break; - case 1: - // Read one extra input byte, which isn't enough to - // make another output byte. Illegal. - this.state = 6; - return false; - case 2: - // Read two extra input bytes, enough to emit 1 more - // output byte. Fine. - output[op++] = (byte) (value >> 4); - break; - case 3: - // Read three extra input bytes, enough to emit 2 more - // output bytes. Fine. - output[op++] = (byte) (value >> 10); - output[op++] = (byte) (value >> 2); - break; - case 4: - // Read one padding '=' when we expected 2. Illegal. - this.state = 6; - return false; - case 5: - // Read all the padding '='s we expected and no more. - // Fine. - break; - } - - this.state = state; - this.op = op; - return true; - } - } - - // -------------------------------------------------------- - // encoding - // -------------------------------------------------------- - - /** - * Base64-encode the given data and return a newly allocated - * String with the result. - * - * @param input the data to encode - * @param flags controls certain features of the encoded output. - * Passing {@code DEFAULT} results in output that - * adheres to RFC 2045. - */ - public static String encodeToString(final byte[] input, final int flags) { - try { - return new String(Base64.encode(input, flags), "US-ASCII"); - } catch (final UnsupportedEncodingException e) { - // US-ASCII is guaranteed to be available. - throw new AssertionError(e); - } - } - - /** - * Base64-encode the given data and return a newly allocated - * String with the result. - * - * @param input the data to encode - * @param offset the position within the input array at which to - * start - * @param len the number of bytes of input to encode - * @param flags controls certain features of the encoded output. - * Passing {@code DEFAULT} results in output that - * adheres to RFC 2045. - */ - public static String encodeToString(final byte[] input, final int offset, final int len, final int flags) { - try { - return new String(Base64.encode(input, offset, len, flags), "US-ASCII"); - } catch (final UnsupportedEncodingException e) { - // US-ASCII is guaranteed to be available. - throw new AssertionError(e); - } - } - - /** - * Base64-encode the given data and return a newly allocated - * byte[] with the result. - * - * @param input the data to encode - * @param flags controls certain features of the encoded output. - * Passing {@code DEFAULT} results in output that - * adheres to RFC 2045. - */ - public static byte[] encode(final byte[] input, final int flags) { - return Base64.encode(input, 0, input.length, flags); - } - - /** - * Base64-encode the given data and return a newly allocated - * byte[] with the result. - * - * @param input the data to encode - * @param offset the position within the input array at which to - * start - * @param len the number of bytes of input to encode - * @param flags controls certain features of the encoded output. - * Passing {@code DEFAULT} results in output that - * adheres to RFC 2045. - */ - public static byte[] encode(final byte[] input, final int offset, final int len, final int flags) { - final Encoder encoder = new Encoder(flags, null); - - // Compute the exact length of the array we will produce. - int output_len = len / 3 * 4; - - // Account for the tail of the data and the padding bytes, if any. - if (encoder.do_padding) { - if (len % 3 > 0) { - output_len += 4; - } - } else { - switch (len % 3) { - case 0: break; - case 1: output_len += 2; break; - case 2: output_len += 3; break; - } - } - - // Account for the newlines, if any. - if (encoder.do_newline && len > 0) { - output_len += (((len-1) / (3 * Encoder.LINE_GROUPS)) + 1) * - (encoder.do_cr ? 2 : 1); - } - - encoder.output = new byte[output_len]; - encoder.process(input, offset, len, true); - - assert encoder.op == output_len; - - return encoder.output; - } - - /* package */ static class Encoder extends Coder { - /** - * Emit a new line every this many output tuples. Corresponds to - * a 76-character line length (the maximum allowable according to - * RFC 2045). - */ - public static final int LINE_GROUPS = 19; - - /** - * Lookup table for turning Base64 alphabet positions (6 bits) - * into output bytes. - */ - private static final byte ENCODE[] = { - 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', - 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', - 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', - 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/', - }; - - /** - * Lookup table for turning Base64 alphabet positions (6 bits) - * into output bytes. - */ - private static final byte ENCODE_WEBSAFE[] = { - 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', - 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', - 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', - 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-', '_', - }; - - final private byte[] tail; - /* package */ int tailLen; - private int count; - - final public boolean do_padding; - final public boolean do_newline; - final public boolean do_cr; - final private byte[] alphabet; - - public Encoder(final int flags, final byte[] output) { - this.output = output; - - this.do_padding = (flags & NO_PADDING) == 0; - this.do_newline = (flags & NO_WRAP) == 0; - this.do_cr = (flags & CRLF) != 0; - this.alphabet = ((flags & URL_SAFE) == 0) ? ENCODE : ENCODE_WEBSAFE; - - this.tail = new byte[2]; - this.tailLen = 0; - - this.count = this.do_newline ? LINE_GROUPS : -1; - } - - /** - * @return an overestimate for the number of bytes {@code - * len} bytes could encode to. - */ - @Override - public int maxOutputSize(final int len) { - return len * 8/5 + 10; - } - - @Override - public boolean process(final byte[] input, final int offset, int len, final boolean finish) { - // Using local variables makes the encoder about 9% faster. - final byte[] alphabet = this.alphabet; - final byte[] output = this.output; - int op = 0; - int count = this.count; - - int p = offset; - len += offset; - int v = -1; - - // First we need to concatenate the tail of the previous call - // with any input bytes available now and see if we can empty - // the tail. - - switch (this.tailLen) { - case 0: - // There was no tail. - break; - - case 1: - if (p+2 <= len) { - // A 1-byte tail with at least 2 bytes of - // input available now. - v = ((this.tail[0] & 0xff) << 16) | - ((input[p++] & 0xff) << 8) | - (input[p++] & 0xff); - this.tailLen = 0; - } - break; - - case 2: - if (p+1 <= len) { - // A 2-byte tail with at least 1 byte of input. - v = ((this.tail[0] & 0xff) << 16) | - ((this.tail[1] & 0xff) << 8) | - (input[p++] & 0xff); - this.tailLen = 0; - } - break; - } - - if (v != -1) { - output[op++] = alphabet[(v >> 18) & 0x3f]; - output[op++] = alphabet[(v >> 12) & 0x3f]; - output[op++] = alphabet[(v >> 6) & 0x3f]; - output[op++] = alphabet[v & 0x3f]; - if (--count == 0) { - if (this.do_cr) { - output[op++] = '\r'; - } - output[op++] = '\n'; - count = LINE_GROUPS; - } - } - - // At this point either there is no tail, or there are fewer - // than 3 bytes of input available. - - // The main loop, turning 3 input bytes into 4 output bytes on - // each iteration. - while (p+3 <= len) { - v = ((input[p] & 0xff) << 16) | - ((input[p+1] & 0xff) << 8) | - (input[p+2] & 0xff); - output[op] = alphabet[(v >> 18) & 0x3f]; - output[op+1] = alphabet[(v >> 12) & 0x3f]; - output[op+2] = alphabet[(v >> 6) & 0x3f]; - output[op+3] = alphabet[v & 0x3f]; - p += 3; - op += 4; - if (--count == 0) { - if (this.do_cr) { - output[op++] = '\r'; - } - output[op++] = '\n'; - count = LINE_GROUPS; - } - } - - if (finish) { - // Finish up the tail of the input. Note that we need to - // consume any bytes in tail before any bytes - // remaining in input; there should be at most two bytes - // total. - - if (p-this.tailLen == len-1) { - int t = 0; - v = ((this.tailLen > 0 ? this.tail[t++] : input[p++]) & 0xff) << 4; - this.tailLen -= t; - output[op++] = alphabet[(v >> 6) & 0x3f]; - output[op++] = alphabet[v & 0x3f]; - if (this.do_padding) { - output[op++] = '='; - output[op++] = '='; - } - if (this.do_newline) { - if (this.do_cr) { - output[op++] = '\r'; - } - output[op++] = '\n'; - } - } else if (p-this.tailLen == len-2) { - int t = 0; - v = (((this.tailLen > 1 ? this.tail[t++] : input[p++]) & 0xff) << 10) | - (((this.tailLen > 0 ? this.tail[t++] : input[p++]) & 0xff) << 2); - this.tailLen -= t; - output[op++] = alphabet[(v >> 12) & 0x3f]; - output[op++] = alphabet[(v >> 6) & 0x3f]; - output[op++] = alphabet[v & 0x3f]; - if (this.do_padding) { - output[op++] = '='; - } - if (this.do_newline) { - if (this.do_cr) { - output[op++] = '\r'; - } - output[op++] = '\n'; - } - } else if (this.do_newline && op > 0 && count != LINE_GROUPS) { - if (this.do_cr) { - output[op++] = '\r'; - } - output[op++] = '\n'; - } - - assert this.tailLen == 0; - assert p == len; - } else { - // Save the leftovers in tail to be consumed on the next - // call to encodeInternal. - - if (p == len-1) { - this.tail[this.tailLen++] = input[p]; - } else if (p == len-2) { - this.tail[this.tailLen++] = input[p]; - this.tail[this.tailLen++] = input[p+1]; - } - } - - this.op = op; - this.count = count; - - return true; - } - } - - private Base64() { } // don't instantiate -} diff --git a/src/org/andengine/util/base64/Base64InputStream.java b/src/org/andengine/util/base64/Base64InputStream.java deleted file mode 100644 index e1d58c244..000000000 --- a/src/org/andengine/util/base64/Base64InputStream.java +++ /dev/null @@ -1,163 +0,0 @@ -/* - * 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. - */ - -package org.andengine.util.base64; - -import java.io.FilterInputStream; -import java.io.IOException; -import java.io.InputStream; - -/** - * An InputStream that does Base64 decoding on the data read through - * it. - */ -public class Base64InputStream extends FilterInputStream { - private final Base64.Coder coder; - - private static byte[] EMPTY = new byte[0]; - - private static final int BUFFER_SIZE = 2048; - private boolean eof; - private byte[] inputBuffer; - private int outputStart; - private int outputEnd; - - /** - * An InputStream that performs Base64 decoding on the data read - * from the wrapped stream. - * - * @param in the InputStream to read the source data from - * @param flags bit flags for controlling the decoder; see the - * constants in {@link Base64} - */ - public Base64InputStream(final InputStream in, final int flags) { - this(in, flags, false); - } - - /** - * Performs Base64 encoding or decoding on the data read from the - * wrapped InputStream. - * - * @param in the InputStream to read the source data from - * @param flags bit flags for controlling the decoder; see the - * constants in {@link Base64} - * @param encode true to encode, false to decode - * - * @hide - */ - public Base64InputStream(final InputStream in, final int flags, final boolean encode) { - super(in); - this.eof = false; - this.inputBuffer = new byte[BUFFER_SIZE]; - if (encode) { - this.coder = new Base64.Encoder(flags, null); - } else { - this.coder = new Base64.Decoder(flags, null); - } - this.coder.output = new byte[this.coder.maxOutputSize(BUFFER_SIZE)]; - this.outputStart = 0; - this.outputEnd = 0; - } - - @Override - public boolean markSupported() { - return false; - } - - @Override - public void mark(final int readlimit) { - throw new UnsupportedOperationException(); - } - - @Override - public void reset() { - throw new UnsupportedOperationException(); - } - - @Override - public void close() throws IOException { - this.in.close(); - this.inputBuffer = null; - } - - @Override - public int available() { - return this.outputEnd - this.outputStart; - } - - @Override - public long skip(final long n) throws IOException { - if (this.outputStart >= this.outputEnd) { - this.refill(); - } - if (this.outputStart >= this.outputEnd) { - return 0; - } - final long bytes = Math.min(n, this.outputEnd-this.outputStart); - this.outputStart += bytes; - return bytes; - } - - @Override - public int read() throws IOException { - if (this.outputStart >= this.outputEnd) { - this.refill(); - } - if (this.outputStart >= this.outputEnd) { - return -1; - } else { - return this.coder.output[this.outputStart++]; - } - } - - @Override - public int read(final byte[] b, final int off, final int len) throws IOException { - if (this.outputStart >= this.outputEnd) { - this.refill(); - } - if (this.outputStart >= this.outputEnd) { - return -1; - } - final int bytes = Math.min(len, this.outputEnd-this.outputStart); - System.arraycopy(this.coder.output, this.outputStart, b, off, bytes); - this.outputStart += bytes; - return bytes; - } - - /** - * Read data from the input stream into inputBuffer, then - * decode/encode it into the empty coder.output, and reset the - * outputStart and outputEnd pointers. - */ - private void refill() throws IOException { - if (this.eof) { - return; - } - final int bytesRead = this.in.read(this.inputBuffer); - boolean success; - if (bytesRead == -1) { - this.eof = true; - success = this.coder.process(EMPTY, 0, 0, true); - } else { - success = this.coder.process(this.inputBuffer, 0, bytesRead, false); - } - if (!success) { - throw new IOException("bad base-64"); - } - this.outputEnd = this.coder.op; - this.outputStart = 0; - } -} diff --git a/src/org/andengine/util/call/AsyncCallable.java b/src/org/andengine/util/call/AsyncCallable.java index db9e47339..e4a829497 100644 --- a/src/org/andengine/util/call/AsyncCallable.java +++ b/src/org/andengine/util/call/AsyncCallable.java @@ -1,9 +1,9 @@ package org.andengine.util.call; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 15:00:30 - 14.05.2010 * @param diff --git a/src/org/andengine/util/call/Callable.java b/src/org/andengine/util/call/Callable.java index 2d73ecdbb..b707618a2 100644 --- a/src/org/andengine/util/call/Callable.java +++ b/src/org/andengine/util/call/Callable.java @@ -1,9 +1,9 @@ package org.andengine.util.call; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 20:52:44 - 03.01.2010 */ diff --git a/src/org/andengine/util/call/Callback.java b/src/org/andengine/util/call/Callback.java index 11feb98a6..e7c357dc4 100644 --- a/src/org/andengine/util/call/Callback.java +++ b/src/org/andengine/util/call/Callback.java @@ -1,9 +1,9 @@ package org.andengine.util.call; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 09:40:55 - 14.12.2009 */ diff --git a/src/org/andengine/util/call/ParameterCallable.java b/src/org/andengine/util/call/ParameterCallable.java index a57dee24f..3bf37c5ca 100644 --- a/src/org/andengine/util/call/ParameterCallable.java +++ b/src/org/andengine/util/call/ParameterCallable.java @@ -1,9 +1,9 @@ package org.andengine.util.call; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 23:40:42 - 27.12.2010 */ diff --git a/src/org/andengine/util/debug/Debug.java b/src/org/andengine/util/debug/Debug.java index a9fa397ff..dd6fd8216 100644 --- a/src/org/andengine/util/debug/Debug.java +++ b/src/org/andengine/util/debug/Debug.java @@ -7,11 +7,11 @@ /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 13:29:16 - 08.03.2010 */ -public class Debug { +public final class Debug { // =========================================================== // Constants // =========================================================== @@ -28,6 +28,10 @@ public class Debug { // Constructors // =========================================================== + private Debug() { + + } + // =========================================================== // Getter & Setter // =========================================================== @@ -45,14 +49,14 @@ public static DebugLevel getDebugLevel() { } public static void setDebugLevel(final DebugLevel pDebugLevel) { - if(pDebugLevel == null) { + if (pDebugLevel == null) { throw new IllegalArgumentException("pDebugLevel must not be null!"); } Debug.sDebugLevel = pDebugLevel; } public static void setDebugUser(final String pDebugUser) { - if(pDebugUser == null) { + if (pDebugUser == null) { throw new IllegalArgumentException("pDebugUser must not be null!"); } Debug.sDebugUser = pDebugUser; @@ -67,7 +71,7 @@ public static void setDebugUser(final String pDebugUser) { // =========================================================== public static void log(final DebugLevel pDebugLevel, final String pMessage) { - switch(pDebugLevel) { + switch (pDebugLevel) { case NONE: return; case VERBOSE: @@ -89,7 +93,7 @@ public static void log(final DebugLevel pDebugLevel, final String pMessage) { } public static void log(final DebugLevel pDebugLevel, final String pMessage, final Throwable pThrowable) { - switch(pDebugLevel) { + switch (pDebugLevel) { case NONE: return; case VERBOSE: @@ -111,7 +115,7 @@ public static void log(final DebugLevel pDebugLevel, final String pMessage, fina } public static void log(final DebugLevel pDebugLevel, final String pTag, final String pMessage) { - switch(pDebugLevel) { + switch (pDebugLevel) { case NONE: return; case VERBOSE: @@ -133,7 +137,7 @@ public static void log(final DebugLevel pDebugLevel, final String pTag, final St } public static void log(final DebugLevel pDebugLevel, final String pTag, final String pMessage, final Throwable pThrowable) { - switch(pDebugLevel) { + switch (pDebugLevel) { case NONE: return; case VERBOSE: @@ -167,8 +171,8 @@ public static void v(final String pTag, final String pMessage) { } public static void v(final String pTag, final String pMessage, final Throwable pThrowable) { - if(Debug.sDebugLevel.isSameOrLessThan(DebugLevel.VERBOSE)) { - if(pThrowable == null) { + if (Debug.sDebugLevel.isSameOrLessThan(DebugLevel.VERBOSE)) { + if (pThrowable == null) { Log.v(pTag, pMessage); } else { Log.v(pTag, pMessage, pThrowable); @@ -177,25 +181,25 @@ public static void v(final String pTag, final String pMessage, final Throwable p } public static void vUser(final String pMessage, final String pDebugUser) { - if(Debug.sDebugUser.equals(pDebugUser)) { + if (Debug.sDebugUser.equals(pDebugUser)) { Debug.v(pMessage); } } public static void vUser(final String pMessage, final Throwable pThrowable, final String pDebugUser) { - if(Debug.sDebugUser.equals(pDebugUser)) { + if (Debug.sDebugUser.equals(pDebugUser)) { Debug.v(pMessage, pThrowable); } } public static void vUser(final String pTag, final String pMessage, final String pDebugUser) { - if(Debug.sDebugUser.equals(pDebugUser)) { + if (Debug.sDebugUser.equals(pDebugUser)) { Debug.v(pTag, pMessage); } } public static void vUser(final String pTag, final String pMessage, final Throwable pThrowable, final String pDebugUser) { - if(Debug.sDebugUser.equals(pDebugUser)) { + if (Debug.sDebugUser.equals(pDebugUser)) { Debug.v(pTag, pMessage, pThrowable); } } @@ -213,8 +217,8 @@ public static void d(final String pTag, final String pMessage) { } public static void d(final String pTag, final String pMessage, final Throwable pThrowable) { - if(Debug.sDebugLevel.isSameOrLessThan(DebugLevel.DEBUG)) { - if(pThrowable == null) { + if (Debug.sDebugLevel.isSameOrLessThan(DebugLevel.DEBUG)) { + if (pThrowable == null) { Log.d(pTag, pMessage); } else { Log.d(pTag, pMessage, pThrowable); @@ -223,25 +227,25 @@ public static void d(final String pTag, final String pMessage, final Throwable p } public static void dUser(final String pMessage, final String pDebugUser) { - if(Debug.sDebugUser.equals(pDebugUser)) { + if (Debug.sDebugUser.equals(pDebugUser)) { Debug.d(pMessage); } } public static void dUser(final String pMessage, final Throwable pThrowable, final String pDebugUser) { - if(Debug.sDebugUser.equals(pDebugUser)) { + if (Debug.sDebugUser.equals(pDebugUser)) { Debug.d(pMessage, pThrowable); } } public static void dUser(final String pTag, final String pMessage, final String pDebugUser) { - if(Debug.sDebugUser.equals(pDebugUser)) { + if (Debug.sDebugUser.equals(pDebugUser)) { Debug.d(pTag, pMessage); } } public static void dUser(final String pTag, final String pMessage, final Throwable pThrowable, final String pDebugUser) { - if(Debug.sDebugUser.equals(pDebugUser)) { + if (Debug.sDebugUser.equals(pDebugUser)) { Debug.d(pTag, pMessage, pThrowable); } } @@ -259,8 +263,8 @@ public static void i(final String pTag, final String pMessage) { } public static void i(final String pTag, final String pMessage, final Throwable pThrowable) { - if(Debug.sDebugLevel.isSameOrLessThan(DebugLevel.INFO)) { - if(pThrowable == null) { + if (Debug.sDebugLevel.isSameOrLessThan(DebugLevel.INFO)) { + if (pThrowable == null) { Log.i(pTag, pMessage); } else { Log.i(pTag, pMessage, pThrowable); @@ -269,25 +273,25 @@ public static void i(final String pTag, final String pMessage, final Throwable p } public static void iUser(final String pMessage, final String pDebugUser) { - if(Debug.sDebugUser.equals(pDebugUser)) { + if (Debug.sDebugUser.equals(pDebugUser)) { Debug.i(pMessage); } } public static void iUser(final String pMessage, final Throwable pThrowable, final String pDebugUser) { - if(Debug.sDebugUser.equals(pDebugUser)) { + if (Debug.sDebugUser.equals(pDebugUser)) { Debug.i(pMessage, pThrowable); } } public static void iUser(final String pTag, final String pMessage, final String pDebugUser) { - if(Debug.sDebugUser.equals(pDebugUser)) { + if (Debug.sDebugUser.equals(pDebugUser)) { Debug.i(pTag, pMessage); } } public static void iUser(final String pTag, final String pMessage, final Throwable pThrowable, final String pDebugUser) { - if(Debug.sDebugUser.equals(pDebugUser)) { + if (Debug.sDebugUser.equals(pDebugUser)) { Debug.i(pTag, pMessage, pThrowable); } } @@ -309,8 +313,8 @@ public static void w(final String pTag, final String pMessage) { } public static void w(final String pTag, final String pMessage, final Throwable pThrowable) { - if(Debug.sDebugLevel.isSameOrLessThan(DebugLevel.WARNING)) { - if(pThrowable == null) { + if (Debug.sDebugLevel.isSameOrLessThan(DebugLevel.WARNING)) { + if (pThrowable == null) { Log.w(pTag, pMessage); } else { Log.w(pTag, pMessage, pThrowable); @@ -319,31 +323,31 @@ public static void w(final String pTag, final String pMessage, final Throwable p } public static void wUser(final String pMessage, final String pDebugUser) { - if(Debug.sDebugUser.equals(pDebugUser)) { + if (Debug.sDebugUser.equals(pDebugUser)) { Debug.w(pMessage); } } public static void wUser(final Throwable pThrowable, final String pDebugUser) { - if(Debug.sDebugUser.equals(pDebugUser)) { + if (Debug.sDebugUser.equals(pDebugUser)) { Debug.w(pThrowable); } } public static void wUser(final String pMessage, final Throwable pThrowable, final String pDebugUser) { - if(Debug.sDebugUser.equals(pDebugUser)) { + if (Debug.sDebugUser.equals(pDebugUser)) { Debug.w(pMessage, pThrowable); } } public static void wUser(final String pTag, final String pMessage, final String pDebugUser) { - if(Debug.sDebugUser.equals(pDebugUser)) { + if (Debug.sDebugUser.equals(pDebugUser)) { Debug.w(pTag, pMessage); } } public static void wUser(final String pTag, final String pMessage, final Throwable pThrowable, final String pDebugUser) { - if(Debug.sDebugUser.equals(pDebugUser)) { + if (Debug.sDebugUser.equals(pDebugUser)) { Debug.w(pTag, pMessage, pThrowable); } } @@ -365,8 +369,8 @@ public static void e(final String pTag, final String pMessage) { } public static void e(final String pTag, final String pMessage, final Throwable pThrowable) { - if(Debug.sDebugLevel.isSameOrLessThan(DebugLevel.ERROR)) { - if(pThrowable == null) { + if (Debug.sDebugLevel.isSameOrLessThan(DebugLevel.ERROR)) { + if (pThrowable == null) { Log.e(pTag, pMessage); } else { Log.e(pTag, pMessage, pThrowable); @@ -375,31 +379,31 @@ public static void e(final String pTag, final String pMessage, final Throwable p } public static void eUser(final String pMessage, final String pDebugUser) { - if(Debug.sDebugUser.equals(pDebugUser)) { + if (Debug.sDebugUser.equals(pDebugUser)) { Debug.e(pMessage); } } public static void eUser(final Throwable pThrowable, final String pDebugUser) { - if(Debug.sDebugUser.equals(pDebugUser)) { + if (Debug.sDebugUser.equals(pDebugUser)) { Debug.e(pThrowable); } } public static void eUser(final String pMessage, final Throwable pThrowable, final String pDebugUser) { - if(Debug.sDebugUser.equals(pDebugUser)) { + if (Debug.sDebugUser.equals(pDebugUser)) { Debug.e(pMessage, pThrowable); } } public static void eUser(final String pTag, final String pMessage, final String pDebugUser) { - if(Debug.sDebugUser.equals(pDebugUser)) { + if (Debug.sDebugUser.equals(pDebugUser)) { Debug.e(pTag, pMessage); } } public static void eUser(final String pTag, final String pMessage, final Throwable pThrowable, final String pDebugUser) { - if(Debug.sDebugUser.equals(pDebugUser)) { + if (Debug.sDebugUser.equals(pDebugUser)) { Debug.e(pTag, pMessage, pThrowable); } } @@ -411,7 +415,7 @@ public static void eUser(final String pTag, final String pMessage, final Throwab public static enum DebugLevel implements Comparable { NONE, ERROR, WARNING, INFO, DEBUG, VERBOSE; - public static DebugLevel ALL = DebugLevel.VERBOSE; + public static final DebugLevel ALL = DebugLevel.VERBOSE; public boolean isSameOrLessThan(final DebugLevel pDebugLevel) { return this.compareTo(pDebugLevel) >= 0; diff --git a/src/org/andengine/util/debug/DebugTimer.java b/src/org/andengine/util/debug/DebugTimer.java index c68a1caef..b16103e9d 100644 --- a/src/org/andengine/util/debug/DebugTimer.java +++ b/src/org/andengine/util/debug/DebugTimer.java @@ -7,7 +7,7 @@ import org.andengine.util.debug.Debug.DebugLevel; /** - * (c) Zynga 2011 + * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 13:52:42 - 02.11.2011 @@ -71,7 +71,7 @@ public void split(final String pLabel) { public void end() { final long now = System.currentTimeMillis(); - if(this.mDebugTimes.size() == 1) { + if (this.mDebugTimes.size() == 1) { throw new IllegalStateException("Cannot end the root of this " + this.getClass().getSimpleName()); } else { this.mDebugTimes.pop().end(now); @@ -84,7 +84,7 @@ public void dump() { public void dump(final boolean pClear) { final long now = System.currentTimeMillis(); - if(this.mDebugTimes.size() > 1) { + if (this.mDebugTimes.size() > 1) { Debug.w(this.getClass().getSimpleName() + " not all ended!"); } @@ -92,7 +92,7 @@ public void dump(final boolean pClear) { root.end(now); root.dump(0); - if(pClear) { + if (pClear) { this.clear(); } } @@ -159,7 +159,7 @@ public void split(final String pLabel) { final long now = System.currentTimeMillis(); final DebugTime split; - if(this.mLastSplit == null) { + if (this.mLastSplit == null) { split = new DebugTime(this.mStartTime, pLabel, true); } else { split = new DebugTime(this.mLastSplit.mEndTime, pLabel, true); @@ -181,21 +181,21 @@ public void dump(final int pIndent) { } public void dump(final int pIndent, final String pPostfix) { - if(this.mSplit) { + if (this.mSplit) { final char[] indent = new char[(pIndent - 1) * INDENT_SPACES]; Arrays.fill(indent, ' '); Debug.log(DebugTimer.this.mDebugLevel, new String(indent) + SPLIT_STRING + "'" + this.mLabel + "'" + " @( " + (this.mEndTime - this.mStartTime) + "ms )" + pPostfix); } else { final char[] indent = new char[pIndent * INDENT_SPACES]; Arrays.fill(indent, ' '); - if(this.mChildren == null) { + if (this.mChildren == null) { Debug.log(DebugTimer.this.mDebugLevel, new String(indent) + "'" + this.mLabel + "' @( " + (this.mEndTime - this.mStartTime) + "ms )" + pPostfix); } else { final ArrayList children = this.mChildren; final int childCount = children.size(); - + Debug.log(DebugTimer.this.mDebugLevel, new String(indent) + "'" + this.mLabel + "' {"); - for(int i = 0; i < childCount - 1; i++) { + for (int i = 0; i < childCount - 1; i++) { children.get(i).dump(pIndent + 1, ","); } children.get(childCount - 1).dump(pIndent + 1); @@ -205,7 +205,7 @@ public void dump(final int pIndent, final String pPostfix) { } private void ensureChildrenAllocated() { - if(this.mChildren == null) { + if (this.mChildren == null) { this.mChildren = new ArrayList(); } } diff --git a/src/org/andengine/util/escape/Unescaper.java b/src/org/andengine/util/escape/Unescaper.java new file mode 100644 index 000000000..ddcb406c7 --- /dev/null +++ b/src/org/andengine/util/escape/Unescaper.java @@ -0,0 +1,96 @@ +package org.andengine.util.escape; + +import org.andengine.util.adt.map.IIntLookupMap; + +import android.text.TextUtils; + +/** + * (c) 2012 Zynga Inc. + * + * @author Nicolas Gramlich + * @since 15:20:25 - 26.04.2012 + */ +public final class Unescaper { + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + // =========================================================== + // Constructors + // =========================================================== + + private Unescaper() { + + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + /** + *

    Unescapes the entities in a {@link String}.

    + * + *

    For example, if you have called addEntity("foo", 0xA1), + * unescape("&foo;") will return "\u00A1"

    + * + * @param pString The {@link String} to escape. + * @param pIntLookupMap the {@link IIntLookupMap} to look up entities. + * @return A new escaped {@link String}. + */ + public static String unescape(final CharSequence pCharSequence, final IIntLookupMap pIntLookupMap) { + final int stringLength = pCharSequence.length(); + final StringBuilder stringBuilder = new StringBuilder(stringLength); + + int i; + for (i = 0; i < stringLength; ++i) { + final char ch = pCharSequence.charAt(i); + if (ch == '&') { + final int semi = TextUtils.indexOf(pCharSequence, ';', i + 1); + if (semi == -1) { + stringBuilder.append(ch); + continue; + } + final CharSequence entityName = pCharSequence.subSequence(i + 1, semi); + int entityValue; + if (entityName.charAt(0) == '#') { + final char charAt1 = entityName.charAt(1); + if ((charAt1 == 'x') || (charAt1 == 'X')) { + entityValue = Integer.valueOf(entityName.subSequence(2, entityName.length()).toString(), 16).intValue(); + } else { + entityValue = Integer.parseInt(entityName.subSequence(1, entityName.length()).toString()); + } + } else { + entityValue = pIntLookupMap.value(entityName); + } + if (entityValue == -1) { + stringBuilder.append('&'); + stringBuilder.append(entityName); + stringBuilder.append(';'); + } else { + stringBuilder.append((char) (entityValue)); + } + i = semi; + } else { + stringBuilder.append(ch); + } + } + + return stringBuilder.toString(); + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== +} diff --git a/src/org/andengine/util/escape/UnescaperEntityMap.java b/src/org/andengine/util/escape/UnescaperEntityMap.java new file mode 100644 index 000000000..13fe895b7 --- /dev/null +++ b/src/org/andengine/util/escape/UnescaperEntityMap.java @@ -0,0 +1,57 @@ +package org.andengine.util.escape; + +import org.andengine.util.adt.map.IntLookupMap; + +/** + * (c) 2012 Zynga Inc. + * + * @author Nicolas Gramlich + * @since 15:31:08 - 26.04.2012 + */ +public class UnescaperEntityMap extends IntLookupMap { + // =========================================================== + // Constants + // =========================================================== + + private static final int LOOKUP_TABLE_SIZE = 256; + + // =========================================================== + // Fields + // =========================================================== + + private final CharSequence[] mLookupTable = new CharSequence[UnescaperEntityMap.LOOKUP_TABLE_SIZE]; + + // =========================================================== + // Constructors + // =========================================================== + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + @Override + public CharSequence item(final int pValue) { + if (pValue < UnescaperEntityMap.LOOKUP_TABLE_SIZE) { + return this.mLookupTable[pValue]; + } + return super.item(pValue); + } + + public void init() { + for (int i = 0; i < UnescaperEntityMap.LOOKUP_TABLE_SIZE; ++i) { + this.mLookupTable[i] = super.item(i); + } + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== +} \ No newline at end of file diff --git a/src/org/andengine/util/escape/XMLUnescaper.java b/src/org/andengine/util/escape/XMLUnescaper.java new file mode 100644 index 000000000..13521ff82 --- /dev/null +++ b/src/org/andengine/util/escape/XMLUnescaper.java @@ -0,0 +1,60 @@ +package org.andengine.util.escape; + +/** + * (c) 2012 Zynga Inc. + * + * @author Nicolas Gramlich + * @since 3:27:44 PM - Apr 26, 2012 + */ +public final class XMLUnescaper { + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + private static final UnescaperEntityMap XMLUNESCAPER_ENTITYMAP = new UnescaperEntityMap() { + { + /* BASIC */ + this.add("quot", 34); // " - double-quote + this.add("amp", 38); // & - ampersand + this.add("lt", 60); // < - less-than + this.add("gt", 62); // > - greater-than + + /* XML */ + this.add("apos", 39); // XML apostrophe + + this.init(); + } + }; + + // =========================================================== + // Constructors + // =========================================================== + + private XMLUnescaper() { + + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + public static String unescape(final CharSequence pCharSequence) { + return Unescaper.unescape(pCharSequence, XMLUnescaper.XMLUNESCAPER_ENTITYMAP); + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== +} diff --git a/src/org/andengine/util/exception/AndEngineException.java b/src/org/andengine/util/exception/AndEngineException.java index ea79cce46..d099b4cb7 100644 --- a/src/org/andengine/util/exception/AndEngineException.java +++ b/src/org/andengine/util/exception/AndEngineException.java @@ -1,7 +1,7 @@ package org.andengine.util.exception; /** - * (c) Zynga 2011 + * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 02:40:26 - 07.08.2011 diff --git a/src/org/andengine/util/exception/AndEngineRuntimeException.java b/src/org/andengine/util/exception/AndEngineRuntimeException.java index 70f4dbd18..35b149384 100644 --- a/src/org/andengine/util/exception/AndEngineRuntimeException.java +++ b/src/org/andengine/util/exception/AndEngineRuntimeException.java @@ -1,7 +1,7 @@ package org.andengine.util.exception; /** - * (c) Zynga 2011 + * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 02:40:26 - 07.08.2011 @@ -21,7 +21,6 @@ public class AndEngineRuntimeException extends RuntimeException { // Constructors // =========================================================== - public AndEngineRuntimeException() { super(); } diff --git a/src/org/andengine/util/exception/BluetoothException.java b/src/org/andengine/util/exception/BluetoothException.java new file mode 100644 index 000000000..1697449e4 --- /dev/null +++ b/src/org/andengine/util/exception/BluetoothException.java @@ -0,0 +1,56 @@ +package org.andengine.util.exception; + +/** + * (c) 2010 Nicolas Gramlich + * (c) 2011 Zynga Inc. + * + * @author Nicolas Gramlich + * @since 20:17:14 - 04.03.2011 + */ +public class BluetoothException extends AndEngineException { + // =========================================================== + // Constants + // =========================================================== + + private static final long serialVersionUID = -8552336984977745238L; + + // =========================================================== + // Fields + // =========================================================== + + // =========================================================== + // Constructors + // =========================================================== + + public BluetoothException() { + + } + + public BluetoothException(final String pMessage) { + super(pMessage); + } + + public BluetoothException(final Throwable pThrowable) { + super(pThrowable); + } + + public BluetoothException(final String pMessage, final Throwable pThrowable) { + super(pMessage, pThrowable); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== +} diff --git a/src/org/andengine/util/exception/CancelledException.java b/src/org/andengine/util/exception/CancelledException.java index 0668c6c0a..6f0652f3c 100644 --- a/src/org/andengine/util/exception/CancelledException.java +++ b/src/org/andengine/util/exception/CancelledException.java @@ -1,7 +1,7 @@ package org.andengine.util.exception; /** - * (c) Zynga 2012 + * (c) 2012 Zynga Inc. * * @author Nicolas Gramlich * @since 16:33:53 - 23.04.2012 @@ -21,6 +21,22 @@ public class CancelledException extends AndEngineException { // Constructors // =========================================================== + public CancelledException() { + super(); + } + + public CancelledException(String pMessage) { + super(pMessage); + } + + public CancelledException(Throwable pThrowable) { + super(pThrowable); + } + + public CancelledException(String pMessage, Throwable pThrowable) { + super(pMessage, pThrowable); + } + // =========================================================== // Getter & Setter // =========================================================== diff --git a/src/org/andengine/util/exception/DeviceNotSupportedException.java b/src/org/andengine/util/exception/DeviceNotSupportedException.java index 1eb60725d..e6175e5a8 100644 --- a/src/org/andengine/util/exception/DeviceNotSupportedException.java +++ b/src/org/andengine/util/exception/DeviceNotSupportedException.java @@ -1,7 +1,7 @@ package org.andengine.util.exception; /** - * (c) Zynga 2012 + * (c) 2012 Zynga Inc. * * @author Nicolas Gramlich * @since 14:05:09 - 19.03.2012 @@ -60,6 +60,7 @@ public static enum DeviceNotSupportedCause { // Elements // =========================================================== + GLES2_UNSUPPORTED, CODEPATH_INCOMPLETE, EGLCONFIG_NOT_FOUND; diff --git a/src/org/andengine/util/exception/IllegalClassNameException.java b/src/org/andengine/util/exception/IllegalClassNameException.java new file mode 100644 index 000000000..95921aa32 --- /dev/null +++ b/src/org/andengine/util/exception/IllegalClassNameException.java @@ -0,0 +1,57 @@ +package org.andengine.util.exception; + +import org.andengine.util.exception.AndEngineRuntimeException; + +/** + * (c) 2013 Nicolas Gramlich + * + * @author Nicolas Gramlich + * @since 21:33:53 - 01.05.2013 + */ +public class IllegalClassNameException extends AndEngineRuntimeException { + // =========================================================== + // Constants + // =========================================================== + + private static final long serialVersionUID = 5615299668631505188L; + + // =========================================================== + // Fields + // =========================================================== + + // =========================================================== + // Constructors + // =========================================================== + + public IllegalClassNameException() { + super(); + } + + public IllegalClassNameException(final String pMessage) { + super(pMessage); + } + + public IllegalClassNameException(final Throwable pThrowable) { + super(pThrowable); + } + + public IllegalClassNameException(final String pMessage, final Throwable pThrowable) { + super(pMessage, pThrowable); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== +} diff --git a/src/org/andengine/util/exception/MethodNotFoundException.java b/src/org/andengine/util/exception/MethodNotFoundException.java new file mode 100644 index 000000000..e9410477f --- /dev/null +++ b/src/org/andengine/util/exception/MethodNotFoundException.java @@ -0,0 +1,55 @@ +package org.andengine.util.exception; + +/** + * (c) 2013 Nicolas Gramlich + * + * @author Nicolas Gramlich + * @since 18:13:32 - 26.12.2011 + */ +public class MethodNotFoundException extends AndEngineRuntimeException { + // =========================================================== + // Constants + // =========================================================== + + private static final long serialVersionUID = -6878670836555401945L; + + // =========================================================== + // Fields + // =========================================================== + + // =========================================================== + // Constructors + // =========================================================== + + public MethodNotFoundException() { + + } + + public MethodNotFoundException(final String pMessage) { + super(pMessage); + } + + public MethodNotFoundException(final Throwable pThrowable) { + super(pThrowable); + } + + public MethodNotFoundException(final String pMessage, final Throwable pThrowable) { + super(pMessage, pThrowable); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== +} diff --git a/src/org/andengine/util/exception/MethodNotSupportedException.java b/src/org/andengine/util/exception/MethodNotSupportedException.java index 4bece8cb8..3e4d95e1d 100644 --- a/src/org/andengine/util/exception/MethodNotSupportedException.java +++ b/src/org/andengine/util/exception/MethodNotSupportedException.java @@ -1,7 +1,7 @@ package org.andengine.util.exception; /** - * (c) Zynga 2011 + * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 18:13:32 - 26.12.2011 diff --git a/src/org/andengine/util/exception/MethodNotYetImplementedException.java b/src/org/andengine/util/exception/MethodNotYetImplementedException.java index 2f2ce48c4..23c222fc1 100644 --- a/src/org/andengine/util/exception/MethodNotYetImplementedException.java +++ b/src/org/andengine/util/exception/MethodNotYetImplementedException.java @@ -1,7 +1,7 @@ package org.andengine.util.exception; /** - * (c) Zynga 2011 + * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 12:25:52 - 03.11.2011 diff --git a/src/org/andengine/util/exception/NullBitmapException.java b/src/org/andengine/util/exception/NullBitmapException.java index becbd0734..a3c85b53a 100644 --- a/src/org/andengine/util/exception/NullBitmapException.java +++ b/src/org/andengine/util/exception/NullBitmapException.java @@ -1,7 +1,7 @@ package org.andengine.util.exception; /** - * (c) Zynga 2011 + * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 14:52:38 - 16.09.2011 diff --git a/src/org/andengine/util/level/EntityLoader.java b/src/org/andengine/util/level/EntityLoader.java new file mode 100644 index 000000000..2771e5e9b --- /dev/null +++ b/src/org/andengine/util/level/EntityLoader.java @@ -0,0 +1,49 @@ +package org.andengine.util.level; + + +/** + * (c) 2012 Zynga Inc. + * + * @author Nicolas Gramlich + * @since 14:05:31 - 19.04.2012 + */ +public abstract class EntityLoader implements IEntityLoader { + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + private final String[] mEntityNames; + + // =========================================================== + // Constructors + // =========================================================== + + public EntityLoader(final String ... pEntityNames) { + this.mEntityNames = pEntityNames; + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + public String[] getEntityNames() { + return this.mEntityNames; + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== +} diff --git a/src/org/andengine/util/level/IEntityLoader.java b/src/org/andengine/util/level/IEntityLoader.java index 716b47447..3188baac4 100644 --- a/src/org/andengine/util/level/IEntityLoader.java +++ b/src/org/andengine/util/level/IEntityLoader.java @@ -1,15 +1,17 @@ package org.andengine.util.level; +import java.io.IOException; + import org.andengine.entity.IEntity; import org.xml.sax.Attributes; /** - * (c) Zynga 2012 + * (c) 2012 Zynga Inc. * * @author Nicolas Gramlich * @since 18:38:40 - 18.04.2012 */ -public interface IEntityLoader { +public interface IEntityLoader { // =========================================================== // Constants // =========================================================== @@ -18,5 +20,15 @@ public interface IEntityLoader { // Methods // =========================================================== - public IEntity onLoadEntity(final String pEntityName, final Attributes pAttributes); + public String[] getEntityNames(); + + /** + * @param pEntityName + * @param pParent can be null, i.e. for the root {@link IEntity}. + * @param pAttributes + * @param pEntityLoaderData + * @return + * @throws IOException + */ + public IEntity onLoadEntity(final String pEntityName, final IEntity pParent, final Attributes pAttributes, final T pEntityLoaderData) throws IOException; } \ No newline at end of file diff --git a/src/org/andengine/util/level/IEntityLoaderData.java b/src/org/andengine/util/level/IEntityLoaderData.java new file mode 100644 index 000000000..5a7c2c1c2 --- /dev/null +++ b/src/org/andengine/util/level/IEntityLoaderData.java @@ -0,0 +1,17 @@ +package org.andengine.util.level; + +/** + * (c) 2012 Zynga Inc. + * + * @author Nicolas Gramlich + * @since 2:21:46 PM - Apr 19, 2012 + */ +public interface IEntityLoaderData { + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== +} diff --git a/src/org/andengine/util/level/IEntityLoaderListener.java b/src/org/andengine/util/level/IEntityLoaderListener.java new file mode 100644 index 000000000..950d56162 --- /dev/null +++ b/src/org/andengine/util/level/IEntityLoaderListener.java @@ -0,0 +1,22 @@ +package org.andengine.util.level; + +import org.andengine.entity.IEntity; +import org.xml.sax.Attributes; + +/** + * (c) 2012 Zynga Inc. + * + * @author Nicolas Gramlich + * @since 14:52:39 - 02.05.2012 + */ +public interface IEntityLoaderListener { + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + public void onEntityLoaded(final IEntity pEntity, final Attributes pAttributes); +} diff --git a/src/org/andengine/util/level/ILevelLoaderResult.java b/src/org/andengine/util/level/ILevelLoaderResult.java new file mode 100644 index 000000000..80970d699 --- /dev/null +++ b/src/org/andengine/util/level/ILevelLoaderResult.java @@ -0,0 +1,17 @@ +package org.andengine.util.level; + +/** + * (c) 2012 Zynga Inc. + * + * @author Nicolas Gramlich + * @since 15:08:08 - 19.04.2012 + */ +public interface ILevelLoaderResult { + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== +} diff --git a/src/org/andengine/util/level/LevelLoader.java b/src/org/andengine/util/level/LevelLoader.java index e6f6e6681..1d7db3c04 100644 --- a/src/org/andengine/util/level/LevelLoader.java +++ b/src/org/andengine/util/level/LevelLoader.java @@ -5,29 +5,25 @@ import java.io.InputStream; import java.util.HashMap; -import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; -import org.andengine.entity.IEntity; import org.andengine.util.StreamUtils; -import org.andengine.util.debug.Debug; -import org.xml.sax.Attributes; +import org.andengine.util.level.exception.LevelLoaderException; import org.xml.sax.InputSource; -import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import android.content.res.AssetManager; -import android.content.res.Resources; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich + * @param * @since 14:16:19 - 11.10.2010 */ -public class LevelLoader { +public abstract class LevelLoader { // =========================================================== // Constants // =========================================================== @@ -36,103 +32,99 @@ public class LevelLoader { // Fields // =========================================================== - private String mAssetBasePath; - - private IEntityLoader mDefaultEntityLoader; - private final HashMap mEntityLoaders = new HashMap(); + private final HashMap> mEntityLoaders = new HashMap>(); + private IEntityLoader mDefaultEntityLoader; // =========================================================== // Constructors // =========================================================== public LevelLoader() { - this(""); + } - public LevelLoader(final String pAssetBasePath) { - this.setAssetBasePath(pAssetBasePath); + public LevelLoader(final IEntityLoader pDefaultEntityLoader) { + this.mDefaultEntityLoader = pDefaultEntityLoader; } // =========================================================== // Getter & Setter // =========================================================== - public IEntityLoader getDefaultEntityLoader() { - return this.mDefaultEntityLoader; - } - - public void setDefaultEntityLoader(final IEntityLoader pDefaultEntityLoader) { + public void setDefaultEntityLoader(final IEntityLoader pDefaultEntityLoader) { this.mDefaultEntityLoader = pDefaultEntityLoader; } - /** - * @param pAssetBasePath must end with '/' or have .length() == 0. - */ - public void setAssetBasePath(final String pAssetBasePath) { - if(pAssetBasePath.endsWith("/") || (pAssetBasePath.length() == 0)) { - this.mAssetBasePath = pAssetBasePath; - } else { - throw new IllegalStateException("pAssetBasePath must end with '/' or be lenght zero."); - } - } - // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== - protected void onAfterLoadLevel() { + // =========================================================== + // Methods + // =========================================================== + + protected abstract T onCreateEntityLoaderData(); + protected abstract LevelLoaderContentHandler onCreateLevelLoaderContentHandler(final HashMap> pEntityLoaders, final IEntityLoader pDefaultEntityLoader, final T pEntityLoaderData, final L pEntityLoaderListener); + public void registerEntityLoader(final IEntityLoader pEntityLoader) { + final String[] entityNames = pEntityLoader.getEntityNames(); + for (int i = 0; i < entityNames.length; i++) { + final String entityName = entityNames[i]; + this.mEntityLoaders.put(entityName, pEntityLoader); + } } - protected void onBeforeLoadLevel() { + public void clearEntityLoaders() { + this.mEntityLoaders.clear(); + } + public R loadLevelFromAsset(final AssetManager pAssetManager, final String pAssetPath) throws LevelLoaderException { + return this.loadLevelFromAsset(pAssetManager, pAssetPath, (L) null); } - // =========================================================== - // Methods - // =========================================================== + public R loadLevelFromAsset(final AssetManager pAssetManager, final String pAssetPath, final L pEntityLoaderListener) throws LevelLoaderException { + final T entityLoaderData = this.onCreateEntityLoaderData(); - public void registerEntityLoader(final String pEntityName, final IEntityLoader pEntityLoader) { - this.mEntityLoaders.put(pEntityName, pEntityLoader); + return this.loadLevelFromAsset(pAssetManager, pAssetPath, entityLoaderData, pEntityLoaderListener); } - public void registerEntityLoader(final String[] pEntityNames, final IEntityLoader pEntityLoader) { - final HashMap entityLoaders = this.mEntityLoaders; + public R loadLevelFromAsset(final AssetManager pAssetManager, final String pAssetPath, final T pEntityLoaderData) throws LevelLoaderException { + return this.loadLevelFromAsset(pAssetManager, pAssetPath, pEntityLoaderData, null); + } - for(int i = pEntityNames.length - 1; i >= 0; i--) { - entityLoaders.put(pEntityNames[i], pEntityLoader); + public R loadLevelFromAsset(final AssetManager pAssetManager, final String pAssetPath, final T pEntityLoaderData, final L pEntityLoaderListener) throws LevelLoaderException { + try { + return this.loadLevelFromStream(pAssetManager.open(pAssetPath), pEntityLoaderData, pEntityLoaderListener); + } catch (final IOException e) { + throw new LevelLoaderException(e); } } - public void loadLevelFromAsset(final AssetManager pAssetManager, final String pAssetPath) throws IOException { - this.loadLevelFromStream(pAssetManager.open(this.mAssetBasePath + pAssetPath)); + public R loadLevelFromStream(final InputStream pInputStream) throws LevelLoaderException { + return this.loadLevelFromStream(pInputStream, null); } - public void loadLevelFromResource(final Resources pResources, final int pRawResourceID) throws IOException { - this.loadLevelFromStream(pResources.openRawResource(pRawResourceID)); + public R loadLevelFromStream(final InputStream pInputStream, final L pEntityLoaderListener) throws LevelLoaderException { + final T entityLoaderData = this.onCreateEntityLoaderData(); + + return this.loadLevelFromStream(pInputStream, entityLoaderData, pEntityLoaderListener); } - public void loadLevelFromStream(final InputStream pInputStream) throws IOException { - try{ + public R loadLevelFromStream(final InputStream pInputStream, final T pEntityLoaderData, final L pEntityLoaderListener) throws LevelLoaderException { + try { final SAXParserFactory spf = SAXParserFactory.newInstance(); final SAXParser sp = spf.newSAXParser(); final XMLReader xr = sp.getXMLReader(); - this.onBeforeLoadLevel(); - - final LevelParser levelParser = new LevelParser(this.mDefaultEntityLoader, this.mEntityLoaders); - xr.setContentHandler(levelParser); + final LevelLoaderContentHandler levelContentHandler = this.onCreateLevelLoaderContentHandler(this.mEntityLoaders, this.mDefaultEntityLoader, pEntityLoaderData, pEntityLoaderListener); + xr.setContentHandler(levelContentHandler); xr.parse(new InputSource(new BufferedInputStream(pInputStream))); - this.onAfterLoadLevel(); - } catch (final SAXException se) { - Debug.e(se); - /* Doesn't happen. */ - } catch (final ParserConfigurationException pe) { - Debug.e(pe); - /* Doesn't happen. */ + return levelContentHandler.getLevelLoaderResult(); + } catch (final Exception e) { + throw new LevelLoaderException(e); } finally { StreamUtils.close(pInputStream); } diff --git a/src/org/andengine/util/level/LevelLoaderContentHandler.java b/src/org/andengine/util/level/LevelLoaderContentHandler.java new file mode 100644 index 000000000..2c5e16f2c --- /dev/null +++ b/src/org/andengine/util/level/LevelLoaderContentHandler.java @@ -0,0 +1,120 @@ +package org.andengine.util.level; + +import java.io.IOException; +import java.util.HashMap; + +import org.andengine.BuildConfig; +import org.andengine.entity.IEntity; +import org.andengine.util.adt.list.SmartList; +import org.andengine.util.debug.Debug; +import org.andengine.util.level.exception.LevelLoaderException; +import org.xml.sax.Attributes; +import org.xml.sax.SAXException; +import org.xml.sax.helpers.DefaultHandler; + +/** + * (c) 2010 Nicolas Gramlich + * (c) 2011 Zynga Inc. + * + * @author Nicolas Gramlich + * @since 14:35:32 - 11.10.2010 + */ +public abstract class LevelLoaderContentHandler extends DefaultHandler { + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + protected final IEntityLoader mDefaultEntityLoader; + protected final HashMap> mEntityLoaders; + protected final T mEntityLoaderData; + + private final SmartList mParentEntityStack = new SmartList(); + + protected IEntity mRootEntity; + protected L mEntityLoaderListener; + + // =========================================================== + // Constructors + // =========================================================== + + public LevelLoaderContentHandler(final IEntityLoader pDefaultEntityLoader, final HashMap> pEntityLoaders, final T pEntityLoaderData) { + this(pDefaultEntityLoader, pEntityLoaders, pEntityLoaderData, null); + } + + public LevelLoaderContentHandler(final IEntityLoader pDefaultEntityLoader, final HashMap> pEntityLoaders, final T pEntityLoaderData, final L pEntityLoaderListener) { + this.mDefaultEntityLoader = pDefaultEntityLoader; + this.mEntityLoaders = pEntityLoaders; + this.mEntityLoaderData = pEntityLoaderData; + this.mEntityLoaderListener = pEntityLoaderListener; + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + public abstract R getLevelLoaderResult(); + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + public void startElement(final String pUri, final String pLocalName, final String pQualifiedName, final Attributes pAttributes) throws SAXException, LevelLoaderException { + final String entityName = pLocalName; + + final IEntity parent = (this.mParentEntityStack.isEmpty()) ? null : this.mParentEntityStack.getLast(); + + IEntityLoader entityLoader = this.mEntityLoaders.get(entityName); + if (entityLoader == null) { + if (this.mDefaultEntityLoader == null) { + throw new LevelLoaderException("Unexpected tag: '" + entityName + "'."); + } else { + entityLoader = this.mDefaultEntityLoader; + } + } + + final IEntity entity; + try { + entity = entityLoader.onLoadEntity(entityName, parent, pAttributes, this.mEntityLoaderData); + } catch (final IOException e) { + throw new LevelLoaderException("Exception when loading entity: '" + entityName + "'.", e); + } + + if (entity == null) { + if (BuildConfig.DEBUG) { + Debug.w("No '" + IEntity.class.getSimpleName() + "' created for entity name: '" + entityName + "'."); + } + } else { + if (parent == null) { + if (this.mRootEntity == null) { + this.mRootEntity = entity; + } + } else { + parent.attachChild(entity); + } + + if (this.mEntityLoaderListener != null) { + this.mEntityLoaderListener.onEntityLoaded(entity, pAttributes); + } + } + + this.mParentEntityStack.addLast(entity); + } + + @Override + public void endElement(final String pUri, final String pLocalName, final String pQualifiedName) throws SAXException { + this.mParentEntityStack.removeLast(); + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== +} diff --git a/src/org/andengine/util/level/LevelParser.java b/src/org/andengine/util/level/LevelParser.java deleted file mode 100644 index 05800e4d6..000000000 --- a/src/org/andengine/util/level/LevelParser.java +++ /dev/null @@ -1,85 +0,0 @@ -package org.andengine.util.level; - -import java.util.HashMap; - -import org.andengine.entity.IEntity; -import org.andengine.util.adt.list.SmartList; -import org.xml.sax.Attributes; -import org.xml.sax.SAXException; -import org.xml.sax.helpers.DefaultHandler; - -/** - * (c) 2010 Nicolas Gramlich - * (c) 2011 Zynga Inc. - * - * @author Nicolas Gramlich - * @since 14:35:32 - 11.10.2010 - */ -public class LevelParser extends DefaultHandler { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - private final IEntityLoader mDefaultEntityLoader; - private final HashMap mEntityLoaders; - - private SmartList mParentEntityStack = new SmartList(); - - // =========================================================== - // Constructors - // =========================================================== - - public LevelParser(final IEntityLoader pDefaultEntityLoader, final HashMap pEntityLoaders) { - this.mDefaultEntityLoader = pDefaultEntityLoader; - this.mEntityLoaders = pEntityLoaders; - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - public void startElement(final String pUri, final String pLocalName, final String pQualifiedName, final Attributes pAttributes) throws SAXException { - final String entityName = pLocalName; - - final IEntity parent = (this.mParentEntityStack.isEmpty()) ? null : this.mParentEntityStack.getLast(); - - final IEntityLoader entityLoader = this.mEntityLoaders.get(entityName); - - final IEntity entity; - if(entityLoader != null) { - entity = entityLoader.onLoadEntity(entityName, pAttributes); - } else if(this.mDefaultEntityLoader != null) { - entity = this.mDefaultEntityLoader.onLoadEntity(entityName, pAttributes); - } else { - throw new IllegalArgumentException("Unexpected tag: '" + entityName + "'."); - } - - if(parent != null && entity != null) { - parent.attachChild(entity); - } - - this.mParentEntityStack.addLast(entity); - } - - @Override - public void endElement(final String pUri, final String pLocalName, final String pQualifiedName) throws SAXException { - this.mParentEntityStack.removeLast(); - } - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== -} diff --git a/src/org/andengine/util/level/constants/LevelConstants.java b/src/org/andengine/util/level/constants/LevelConstants.java index ac244e9e6..edcb8bc35 100644 --- a/src/org/andengine/util/level/constants/LevelConstants.java +++ b/src/org/andengine/util/level/constants/LevelConstants.java @@ -2,9 +2,9 @@ /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 14:23:27 - 11.10.2010 */ diff --git a/src/org/andengine/util/level/exception/LevelLoaderException.java b/src/org/andengine/util/level/exception/LevelLoaderException.java new file mode 100644 index 000000000..135da9bbe --- /dev/null +++ b/src/org/andengine/util/level/exception/LevelLoaderException.java @@ -0,0 +1,57 @@ +package org.andengine.util.level.exception; + +import org.andengine.util.exception.AndEngineRuntimeException; + +/** + * (c) 2012 Zynga Inc. + * + * @author Nicolas Gramlich + * @since 14:59:01 - 19.04.2012 + */ +public class LevelLoaderException extends AndEngineRuntimeException { + // =========================================================== + // Constants + // =========================================================== + + private static final long serialVersionUID = 1027781104016235328L; + + // =========================================================== + // Fields + // =========================================================== + + // =========================================================== + // Constructors + // =========================================================== + + public LevelLoaderException() { + + } + + public LevelLoaderException(final String pMessage) { + super(pMessage); + } + + public LevelLoaderException(final Throwable pThrowable) { + super(pThrowable); + } + + public LevelLoaderException(final String pMessage, final Throwable pThrowable) { + super(pMessage, pThrowable); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== +} diff --git a/src/org/andengine/util/level/simple/SimpleLevelEntityLoaderData.java b/src/org/andengine/util/level/simple/SimpleLevelEntityLoaderData.java new file mode 100644 index 000000000..14cb50d17 --- /dev/null +++ b/src/org/andengine/util/level/simple/SimpleLevelEntityLoaderData.java @@ -0,0 +1,50 @@ +package org.andengine.util.level.simple; + +import org.andengine.opengl.vbo.VertexBufferObjectManager; +import org.andengine.util.level.IEntityLoaderData; + +/** + * (c) 2012 Zynga Inc. + * + * @author Nicolas Gramlich + * @since 16:13:09 - 19.04.2012 + */ +public class SimpleLevelEntityLoaderData implements IEntityLoaderData { + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + private final VertexBufferObjectManager mVertexBufferObjectManager; + + // =========================================================== + // Constructors + // =========================================================== + + public SimpleLevelEntityLoaderData(final VertexBufferObjectManager pVertexBufferObjectManager) { + this.mVertexBufferObjectManager = pVertexBufferObjectManager; + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + public VertexBufferObjectManager getVertexBufferObjectManager() { + return this.mVertexBufferObjectManager; + } + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== +} diff --git a/src/org/andengine/util/level/simple/SimpleLevelLoader.java b/src/org/andengine/util/level/simple/SimpleLevelLoader.java new file mode 100644 index 000000000..a15ec58c1 --- /dev/null +++ b/src/org/andengine/util/level/simple/SimpleLevelLoader.java @@ -0,0 +1,60 @@ +package org.andengine.util.level.simple; + +import java.util.HashMap; + +import org.andengine.opengl.vbo.VertexBufferObjectManager; +import org.andengine.util.level.IEntityLoader; +import org.andengine.util.level.IEntityLoaderListener; +import org.andengine.util.level.LevelLoader; + +/** + * (c) 2012 Zynga Inc. + * + * @author Nicolas Gramlich + * @since 4:11:17 - 19.04.2012 + */ +public class SimpleLevelLoader extends LevelLoader { + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + private final VertexBufferObjectManager mVertexBufferObjectManager; + + // =========================================================== + // Constructors + // =========================================================== + + public SimpleLevelLoader(final VertexBufferObjectManager pVertexBufferObjectManager) { + this.mVertexBufferObjectManager = pVertexBufferObjectManager; + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + protected SimpleLevelEntityLoaderData onCreateEntityLoaderData() { + return new SimpleLevelEntityLoaderData(this.mVertexBufferObjectManager); + } + + @Override + protected SimpleLevelLoaderContentHandler onCreateLevelLoaderContentHandler(final HashMap> pEntityLoaders, final IEntityLoader pDefaultEntityLoader, final SimpleLevelEntityLoaderData pEntityLoaderData, final IEntityLoaderListener pEntityLoaderListener) { + return new SimpleLevelLoaderContentHandler(pDefaultEntityLoader, pEntityLoaders, pEntityLoaderData); + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== +} diff --git a/src/org/andengine/util/level/simple/SimpleLevelLoaderContentHandler.java b/src/org/andengine/util/level/simple/SimpleLevelLoaderContentHandler.java new file mode 100644 index 000000000..60cf5e2c0 --- /dev/null +++ b/src/org/andengine/util/level/simple/SimpleLevelLoaderContentHandler.java @@ -0,0 +1,53 @@ +package org.andengine.util.level.simple; + +import java.util.HashMap; + +import org.andengine.entity.scene.Scene; +import org.andengine.util.level.IEntityLoader; +import org.andengine.util.level.IEntityLoaderListener; +import org.andengine.util.level.LevelLoaderContentHandler; + +/** + * (c) 2012 Zynga Inc. + * + * @author Nicolas Gramlich + * @since 16:12:23 - 19.04.2012 + */ +public class SimpleLevelLoaderContentHandler extends LevelLoaderContentHandler { + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + // =========================================================== + // Constructors + // =========================================================== + + public SimpleLevelLoaderContentHandler(final IEntityLoader pDefaultEntityLoader, final HashMap> pEntityLoaders, final SimpleLevelEntityLoaderData pEntityLoaderData) { + super(pDefaultEntityLoader, pEntityLoaders, pEntityLoaderData); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + public SimpleLevelLoaderResult getLevelLoaderResult() { + return new SimpleLevelLoaderResult((Scene) this.mRootEntity); + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== +} diff --git a/src/org/andengine/util/level/simple/SimpleLevelLoaderResult.java b/src/org/andengine/util/level/simple/SimpleLevelLoaderResult.java new file mode 100644 index 000000000..07249f2e2 --- /dev/null +++ b/src/org/andengine/util/level/simple/SimpleLevelLoaderResult.java @@ -0,0 +1,50 @@ +package org.andengine.util.level.simple; + +import org.andengine.entity.scene.Scene; +import org.andengine.util.level.ILevelLoaderResult; + +/** + * (c) 2012 Zynga Inc. + * + * @author Nicolas Gramlich + * @since 16:13:38 - 19.04.2012 + */ +public class SimpleLevelLoaderResult implements ILevelLoaderResult { + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + private final Scene mScene; + + // =========================================================== + // Constructors + // =========================================================== + + public SimpleLevelLoaderResult(final Scene pScene) { + this.mScene = pScene; + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + public Scene getScene() { + return this.mScene; + } + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== +} diff --git a/src/org/andengine/util/levelstats/LevelStatsDBConnector.java b/src/org/andengine/util/levelstats/LevelStatsDBConnector.java index dc0af6c29..f6108ed20 100644 --- a/src/org/andengine/util/levelstats/LevelStatsDBConnector.java +++ b/src/org/andengine/util/levelstats/LevelStatsDBConnector.java @@ -22,9 +22,9 @@ import android.content.SharedPreferences; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 21:13:55 - 18.10.2010 */ @@ -33,7 +33,7 @@ public class LevelStatsDBConnector { // Constants // =========================================================== - private static final String PREFERENCES_LEVELSTATSDBCONNECTOR_PLAYERID_ID = "preferences.levelstatsdbconnector.playerid"; + private static final String PREFERENCES_LEVELSTATSDBCONNECTOR_PLAYERID_KEY = "preferences.levelstatsdbconnector.playerid"; // =========================================================== // Fields @@ -52,12 +52,12 @@ public LevelStatsDBConnector(final Context pContext, final String pSecret, final this.mSubmitURL = pSubmitURL; final SharedPreferences simplePreferences = SimplePreferences.getInstance(pContext); - final int playerID = simplePreferences.getInt(PREFERENCES_LEVELSTATSDBCONNECTOR_PLAYERID_ID, -1); - if(playerID != -1) { + final int playerID = simplePreferences.getInt(PREFERENCES_LEVELSTATSDBCONNECTOR_PLAYERID_KEY, -1); + if (playerID != -1) { this.mPlayerID = playerID; } else { this.mPlayerID = MathUtils.random(1000000000, Integer.MAX_VALUE); - SimplePreferences.getEditorInstance(pContext).putInt(PREFERENCES_LEVELSTATSDBCONNECTOR_PLAYERID_ID, this.mPlayerID).commit(); + SimplePreferences.getEditorInstance(pContext).putInt(PREFERENCES_LEVELSTATSDBCONNECTOR_PLAYERID_KEY, this.mPlayerID).commit(); } } @@ -77,7 +77,7 @@ public void submitAsync(final int pLevelID, final boolean pSolved, final int pSe new Thread(new Runnable() { @Override public void run() { - try{ + try { /* Create a new HttpClient and Post Header. */ final HttpClient httpClient = new DefaultHttpClient(); final HttpPost httpPost = new HttpPost(LevelStatsDBConnector.this.mSubmitURL); @@ -97,26 +97,26 @@ public void run() { final HttpResponse httpResponse = httpClient.execute(httpPost); final int statusCode = httpResponse.getStatusLine().getStatusCode(); - if(statusCode == HttpStatus.SC_OK) { + if (statusCode == HttpStatus.SC_OK) { final String response = StreamUtils.readFully(httpResponse.getEntity().getContent()); - if(response.equals("")) { - if(pCallback != null) { + if (response.equals("")) { + if (pCallback != null) { pCallback.onCallback(true); } } else { - if(pCallback != null) { + if (pCallback != null) { pCallback.onCallback(false); } } } else { - if(pCallback != null) { + if (pCallback != null) { pCallback.onCallback(false); } } - }catch(final IOException e) { + } catch(final IOException e) { Debug.e(e); - if(pCallback != null) { + if (pCallback != null) { pCallback.onCallback(false); } } diff --git a/src/org/andengine/util/math/MathConstants.java b/src/org/andengine/util/math/MathConstants.java index d839498f1..d9220e8cc 100644 --- a/src/org/andengine/util/math/MathConstants.java +++ b/src/org/andengine/util/math/MathConstants.java @@ -1,9 +1,10 @@ package org.andengine.util.math; + /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 16:49:25 - 26.07.2010 */ @@ -20,6 +21,8 @@ public interface MathConstants { public static final float DEG_TO_RAD = PI / 180.0f; public static final float RAD_TO_DEG = 180.0f / PI; + public static final float SQRT_2 = (float) Math.sqrt(2); + // =========================================================== // Methods // =========================================================== diff --git a/src/org/andengine/util/math/MathUtils.java b/src/org/andengine/util/math/MathUtils.java index f98afe166..fe7cf4818 100644 --- a/src/org/andengine/util/math/MathUtils.java +++ b/src/org/andengine/util/math/MathUtils.java @@ -2,12 +2,10 @@ import java.util.Random; -import android.util.FloatMath; - /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 20:42:15 - 17.12.2009 */ @@ -26,6 +24,10 @@ public final class MathUtils { // Constructors // =========================================================== + private MathUtils() { + + } + // =========================================================== // Getter & Setter // =========================================================== @@ -38,8 +40,152 @@ public final class MathUtils { // Methods // =========================================================== + public static byte min(final byte pA, final byte pB, final byte pC) { + return (byte) Math.min(Math.min(pA, pB), pC); + } + + public static byte min(final byte pA, final byte pB, final byte pC, final byte pD) { + return (byte) Math.min(Math.min(Math.min(pA, pB), pC), pD); + } + + public static byte min(final byte pA, final byte pB, final byte pC, final byte pD, final byte pE) { + return (byte) Math.min(Math.min(Math.min(Math.min(pA, pB), pC), pD), pE); + } + + public static short min(final short pA, final short pB, final short pC) { + return (short) Math.min(Math.min(pA, pB), pC); + } + + public static short min(final short pA, final short pB, final short pC, final short pD) { + return (short) Math.min(Math.min(Math.min(pA, pB), pC), pD); + } + + public static short min(final short pA, final short pB, final short pC, final short pD, final short pE) { + return (short) Math.min(Math.min(Math.min(Math.min(pA, pB), pC), pD), pE); + } + + public static int min(final int pA, final int pB, final int pC) { + return Math.min(Math.min(pA, pB), pC); + } + + public static int min(final int pA, final int pB, final int pC, final int pD) { + return Math.min(Math.min(Math.min(pA, pB), pC), pD); + } + + public static int min(final int pA, final int pB, final int pC, final int pD, final int pE) { + return Math.min(Math.min(Math.min(Math.min(pA, pB), pC), pD), pE); + } + + public static long min(final long pA, final long pB, final long pC) { + return Math.min(Math.min(pA, pB), pC); + } + + public static long min(final long pA, final long pB, final long pC, final long pD) { + return Math.min(Math.min(Math.min(pA, pB), pC), pD); + } + + public static long min(final long pA, final long pB, final long pC, final long pD, final long pE) { + return Math.min(Math.min(Math.min(Math.min(pA, pB), pC), pD), pE); + } + + public static float min(final float pA, final float pB, final float pC) { + return Math.min(Math.min(pA, pB), pC); + } + + public static float min(final float pA, final float pB, final float pC, final float pD) { + return Math.min(Math.min(Math.min(pA, pB), pC), pD); + } + + public static float min(final float pA, final float pB, final float pC, final float pD, final float pE) { + return Math.min(Math.min(Math.min(Math.min(pA, pB), pC), pD), pE); + } + + public static double min(final double pA, final double pB, final double pC) { + return Math.min(Math.min(pA, pB), pC); + } + + public static double min(final double pA, final double pB, final double pC, final double pD) { + return Math.min(Math.min(Math.min(pA, pB), pC), pD); + } + + public static double min(final double pA, final double pB, final double pC, final double pD, final double pE) { + return Math.min(Math.min(Math.min(Math.min(pA, pB), pC), pD), pE); + } + + public static byte max(final byte pA, final byte pB, final byte pC) { + return (byte) Math.max(Math.max(pA, pB), pC); + } + + public static byte max(final byte pA, final byte pB, final byte pC, final byte pD) { + return (byte) Math.max(Math.max(Math.max(pA, pB), pC), pD); + } + + public static byte max(final byte pA, final byte pB, final byte pC, final byte pD, final byte pE) { + return (byte) Math.max(Math.max(Math.max(Math.max(pA, pB), pC), pD), pE); + } + + public static short max(final short pA, final short pB, final short pC) { + return (short) Math.max(Math.max(pA, pB), pC); + } + + public static short max(final short pA, final short pB, final short pC, final short pD) { + return (short) Math.max(Math.max(Math.max(pA, pB), pC), pD); + } + + public static short max(final short pA, final short pB, final short pC, final short pD, final short pE) { + return (short) Math.max(Math.max(Math.max(Math.max(pA, pB), pC), pD), pE); + } + + public static int max(final int pA, final int pB, final int pC) { + return Math.max(Math.max(pA, pB), pC); + } + + public static int max(final int pA, final int pB, final int pC, final int pD) { + return Math.max(Math.max(Math.max(pA, pB), pC), pD); + } + + public static int max(final int pA, final int pB, final int pC, final int pD, final int pE) { + return Math.max(Math.max(Math.max(Math.max(pA, pB), pC), pD), pE); + } + + public static long max(final long pA, final long pB, final long pC) { + return Math.max(Math.max(pA, pB), pC); + } + + public static long max(final long pA, final long pB, final long pC, final long pD) { + return Math.max(Math.max(Math.max(pA, pB), pC), pD); + } + + public static long max(final long pA, final long pB, final long pC, final long pD, final long pE) { + return Math.max(Math.max(Math.max(Math.max(pA, pB), pC), pD), pE); + } + + public static float max(final float pA, final float pB, final float pC) { + return Math.max(Math.max(pA, pB), pC); + } + + public static float max(final float pA, final float pB, final float pC, final float pD) { + return Math.max(Math.max(Math.max(pA, pB), pC), pD); + } + + public static float max(final float pA, final float pB, final float pC, final float pD, final float pE) { + return Math.max(Math.max(Math.max(Math.max(pA, pB), pC), pD), pE); + } + + public static double max(final double pA, final double pB, final double pC) { + return Math.max(Math.max(pA, pB), pC); + } + + public static double max(final double pA, final double pB, final double pC, final double pD) { + return Math.max(Math.max(Math.max(pA, pB), pC), pD); + } + + public static double max(final double pA, final double pB, final double pC, final double pD, final double pE) { + return Math.max(Math.max(Math.max(Math.max(pA, pB), pC), pD), pE); + } + public static final float atan2(final float dY, final float dX) { - return (float)Math.atan2(dY, dX); + return (float) Math.atan2(dY, dX); } public static final float radToDeg(final float pRad) { @@ -51,9 +197,9 @@ public static final float degToRad(final float pDegree) { } public static final int signum(final int n) { - if(n == 0) { + if (n == 0) { return 0; - } else if(n > 0) { + } else if (n > 0) { return 1; } else { return -1; @@ -61,7 +207,7 @@ public static final int signum(final int n) { } public static final int randomSign() { - if(RANDOM.nextBoolean()) { + if (MathUtils.RANDOM.nextBoolean()) { return 1; } else { return -1; @@ -69,24 +215,36 @@ public static final int randomSign() { } public static final float random(final float pMin, final float pMax) { - return pMin + RANDOM.nextFloat() * (pMax - pMin); + return pMin + (MathUtils.RANDOM.nextFloat() * (pMax - pMin)); } /** + * Interval: [pMin, pMax] + * * @param pMin inclusive! * @param pMax inclusive! * @return */ public static final int random(final int pMin, final int pMax) { - return pMin + RANDOM.nextInt(pMax - pMin + 1); + return pMin + MathUtils.RANDOM.nextInt((pMax - pMin) + 1); + } + + /** + * Interval: [0, pMax) + * + * @param pMax exclusive! + * @return + */ + public static final int random(final int pMax) { + return MathUtils.RANDOM.nextInt(pMax); } public static final boolean isPowerOfTwo(final int n) { - return ((n != 0) && (n & (n - 1)) == 0); + return ((n != 0) && ((n & (n - 1)) == 0)); } public static final int nextPowerOfTwo(final float f) { - return MathUtils.nextPowerOfTwo((int)(FloatMath.ceil(f))); + return MathUtils.nextPowerOfTwo((int)(Math.ceil(f))); } public static final int nextPowerOfTwo(final int n) { @@ -99,7 +257,7 @@ public static final int nextPowerOfTwo(final int n) { k--; for (int i = 1; i < 32; i <<= 1) { - k = k | k >> i; + k = k | (k >> i); } return k + 1; @@ -107,77 +265,34 @@ public static final int nextPowerOfTwo(final int n) { public static final int sum(final int[] pValues) { int sum = 0; - for(int i = pValues.length - 1; i >= 0; i--) { + for (int i = pValues.length - 1; i >= 0; i--) { sum += pValues[i]; } return sum; } - public static final void arraySumInternal(final int[] pValues) { - final int valueCount = pValues.length; - for(int i = 1; i < valueCount; i++) { - pValues[i] = pValues[i-1] + pValues[i]; - } - } - - public static final void arraySumInternal(final long[] pValues) { - final int valueCount = pValues.length; - for(int i = 1; i < valueCount; i++) { - pValues[i] = pValues[i-1] + pValues[i]; - } - } - - public static final void arraySumInternal(final long[] pValues, final long pFactor) { - pValues[0] = pValues[0] * pFactor; - final int valueCount = pValues.length; - for(int i = 1; i < valueCount; i++) { - pValues[i] = pValues[i-1] + pValues[i] * pFactor; - } - } - - public static final void arraySumInto(final long[] pValues, final long[] pTargetValues, final long pFactor) { - pTargetValues[0] = pValues[0] * pFactor; - final int valueCount = pValues.length; - for(int i = 1; i < valueCount; i++) { - pTargetValues[i] = pTargetValues[i-1] + pValues[i] * pFactor; - } - } - - public static final float arraySum(final float[] pValues) { - float sum = 0; - final int valueCount = pValues.length; - for(int i = 0; i < valueCount; i++) { - sum += pValues[i]; - } - return sum; - } - - public static final float arrayAverage(final float[] pValues) { - return MathUtils.arraySum(pValues) / pValues.length; - } - public static float[] rotateAroundCenter(final float[] pVertices, final float pRotation, final float pRotationCenterX, final float pRotationCenterY) { - if(pRotation != 0) { + if (pRotation != 0) { final float rotationRad = MathUtils.degToRad(pRotation); - final float sinRotationRad = FloatMath.sin(rotationRad); - final float cosRotationInRad = FloatMath.cos(rotationRad); + final float sinRotationRad = (float) Math.sin(rotationRad); + final float cosRotationInRad = (float) Math.cos(rotationRad); - for(int i = pVertices.length - 2; i >= 0; i -= 2) { + for (int i = pVertices.length - 2; i >= 0; i -= 2) { final float pX = pVertices[i]; final float pY = pVertices[i + 1]; - pVertices[i] = pRotationCenterX + (cosRotationInRad * (pX - pRotationCenterX) - sinRotationRad * (pY - pRotationCenterY)); - pVertices[i + 1] = pRotationCenterY + (sinRotationRad * (pX - pRotationCenterX) + cosRotationInRad * (pY - pRotationCenterY)); + pVertices[i] = pRotationCenterX + ((cosRotationInRad * (pX - pRotationCenterX)) - (sinRotationRad * (pY - pRotationCenterY))); + pVertices[i + 1] = pRotationCenterY + ((sinRotationRad * (pX - pRotationCenterX)) + (cosRotationInRad * (pY - pRotationCenterY))); } } return pVertices; } public static float[] scaleAroundCenter(final float[] pVertices, final float pScaleX, final float pScaleY, final float pScaleCenterX, final float pScaleCenterY) { - if(pScaleX != 1 || pScaleY != 1) { - for(int i = pVertices.length - 2; i >= 0; i -= 2) { - pVertices[i] = pScaleCenterX + (pVertices[i] - pScaleCenterX) * pScaleX; - pVertices[i + 1] = pScaleCenterY + (pVertices[i + 1] - pScaleCenterY) * pScaleY; + if ((pScaleX != 1) || (pScaleY != 1)) { + for (int i = pVertices.length - 2; i >= 0; i -= 2) { + pVertices[i] = pScaleCenterX + ((pVertices[i] - pScaleCenterX) * pScaleX); + pVertices[i + 1] = pScaleCenterY + ((pVertices[i + 1] - pScaleCenterY) * pScaleY); } } @@ -203,11 +318,11 @@ public static float[] revertRotateAndScaleAroundCenter(final float[] pVertices, } public static final boolean isInBounds(final int pMinValue, final int pMaxValue, final int pValue) { - return pValue >= pMinValue && pValue <= pMaxValue; + return (pValue >= pMinValue) && (pValue <= pMaxValue); } public static final boolean isInBounds(final float pMinValue, final float pMaxValue, final float pValue) { - return pValue >= pMinValue && pValue <= pMaxValue; + return (pValue >= pMinValue) && (pValue <= pMaxValue); } /** @@ -233,17 +348,17 @@ public static final float bringToBounds(final float pMinValue, final float pMaxV /** * @return the euclidean distance between the points (pX1, pY1) and (pX2, pY2). */ - public static final float distance(final float pX1, final float pY1, final float pX2, final float pY2){ + public static final float distance(final float pX1, final float pY1, final float pX2, final float pY2) { final float dX = pX2 - pX1; final float dY = pY2 - pY1; - return FloatMath.sqrt((dX * dX) + (dY * dY)); + return (float) Math.sqrt((dX * dX) + (dY * dY)); } /** * @return the euclidean distance between the origin (0, 0) and (pX, pY). */ - public static final float length(final float pX, final float pY){ - return FloatMath.sqrt((pX * pX) + (pY * pY)); + public static final float length(final float pX, final float pY) { + return (float) Math.sqrt((pX * pX) + (pY * pY)); } /** @@ -253,7 +368,7 @@ public static final float length(final float pX, final float pY){ * @return pX * (1 - pMix) + pY * pMix */ public static final float mix(final float pX, final float pY, final float pMix) { - return pX * (1 - pMix) + pY * pMix; + return (pX * (1 - pMix)) + (pY * pMix); } /** @@ -263,23 +378,31 @@ public static final float mix(final float pX, final float pY, final float pMix) * @return (int)Math.round(pX * (1 - pMix) + pY * pMix) */ public static final int mix(final int pX, final int pY, final float pMix) { - return (int)Math.round(pX * (1 - pMix) + pY * pMix); + return Math.round((pX * (1 - pMix)) + (pY * pMix)); } public static final boolean isEven(final int n) { - return n % 2 == 0; + return (n % 2) == 0; } public static final boolean isOdd(final int n) { - return n % 2 == 1; + return (n % 2) == 1; } - public static float dot(final float pXA, final float pYA, final float pXB, final float pYB) { - return pXA * pXB + pYA * pYB; + public static float dot(final float pXA, final float pYA, final float pXB, final float pYB) { + return (pXA * pXB) + (pYA * pYB); } - public static float cross(final float pXA, final float pYA, final float pXB, final float pYB) { - return pXA * pYB - pXB * pYA; + public static float cross(final float pXA, final float pYA, final float pXB, final float pYB) { + return (pXA * pYB) - (pXB * pYA); + } + + public static final int factorial(final int n) { + int result = 1; + for (int i = 1; i <= n; i++) { + result *= i; + } + return result; } // =========================================================== diff --git a/src/org/andengine/util/math/factorioal/DenseFactorialCache.java b/src/org/andengine/util/math/factorioal/DenseFactorialCache.java new file mode 100644 index 000000000..ca2c2ce2e --- /dev/null +++ b/src/org/andengine/util/math/factorioal/DenseFactorialCache.java @@ -0,0 +1,70 @@ +package org.andengine.util.math.factorioal; + +import android.util.SparseIntArray; + +/** + * (c) 2013 Nicolas Gramlich + * + * @author Nicolas Gramlich + * @since 21:37:15 - 09.06.2013 + */ +public class DenseFactorialCache implements IFactorialProvider { + // =========================================================== + // Constants + // =========================================================== + + private static DenseFactorialCache INSTANCE; + + private final SparseIntArray mCache = new SparseIntArray(); + + // =========================================================== + // Fields + // =========================================================== + + // =========================================================== + // Constructors + // =========================================================== + + private DenseFactorialCache() { + + } + + public static DenseFactorialCache getInstance() { + if (INSTANCE == null) { + INSTANCE = new DenseFactorialCache(); + } + return INSTANCE; + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + @Override + public int factorial(final int n) { + if (n == 0 || n == 1) { + return 1; + } else { + int result = this.mCache.get(n); + if (result != 0) { + return result; + } else { + result = n * this.factorial(n - 1); + this.mCache.put(n, result); + return result; + } + } + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== +} \ No newline at end of file diff --git a/src/org/andengine/util/math/factorioal/IFactorialProvider.java b/src/org/andengine/util/math/factorioal/IFactorialProvider.java new file mode 100644 index 000000000..7c03e4c44 --- /dev/null +++ b/src/org/andengine/util/math/factorioal/IFactorialProvider.java @@ -0,0 +1,23 @@ +package org.andengine.util.math.factorioal; + +/** + * (c) 2013 Nicolas Gramlich + * + * @author Nicolas Gramlich + * @since 21:37:15 - 09.06.2013 + */ +public interface IFactorialProvider { + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + public int factorial(final int n); + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== +} diff --git a/src/org/andengine/util/math/factorioal/IterativeFactorialProvider.java b/src/org/andengine/util/math/factorioal/IterativeFactorialProvider.java new file mode 100644 index 000000000..ac0777e25 --- /dev/null +++ b/src/org/andengine/util/math/factorioal/IterativeFactorialProvider.java @@ -0,0 +1,60 @@ +package org.andengine.util.math.factorioal; + + +/** + * (c) 2013 Nicolas Gramlich + * + * @author Nicolas Gramlich + * @since 21:37:15 - 09.06.2013 + */ +public class IterativeFactorialProvider implements IFactorialProvider { + // =========================================================== + // Constants + // =========================================================== + + private static IterativeFactorialProvider INSTANCE; + + // =========================================================== + // Fields + // =========================================================== + + // =========================================================== + // Constructors + // =========================================================== + + private IterativeFactorialProvider() { + + } + + public static IterativeFactorialProvider getInstance() { + if (INSTANCE == null) { + INSTANCE = new IterativeFactorialProvider(); + } + return INSTANCE; + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + @Override + public int factorial(final int n) { + int result = 1; + for (int i = 1; i <= n; i++) { + result *= i; + } + return result; + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== +} \ No newline at end of file diff --git a/src/org/andengine/util/math/factorioal/RecursiveFactorialProvider.java b/src/org/andengine/util/math/factorioal/RecursiveFactorialProvider.java new file mode 100644 index 000000000..7656a6cb2 --- /dev/null +++ b/src/org/andengine/util/math/factorioal/RecursiveFactorialProvider.java @@ -0,0 +1,60 @@ +package org.andengine.util.math.factorioal; + + +/** + * (c) 2013 Nicolas Gramlich + * + * @author Nicolas Gramlich + * @since 21:37:15 - 09.06.2013 + */ +public class RecursiveFactorialProvider implements IFactorialProvider { + // =========================================================== + // Constants + // =========================================================== + + private static RecursiveFactorialProvider INSTANCE; + + // =========================================================== + // Fields + // =========================================================== + + // =========================================================== + // Constructors + // =========================================================== + + private RecursiveFactorialProvider() { + + } + + public static RecursiveFactorialProvider getInstance() { + if (INSTANCE == null) { + INSTANCE = new RecursiveFactorialProvider(); + } + return INSTANCE; + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + @Override + public int factorial(final int n) { + if (n == 0 || n == 1) { + return 1; + } else { + return n * this.factorial(n - 1); + } + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== +} \ No newline at end of file diff --git a/src/org/andengine/util/math/factorioal/SparseFactorialCache.java b/src/org/andengine/util/math/factorioal/SparseFactorialCache.java new file mode 100644 index 000000000..f57a5f5ae --- /dev/null +++ b/src/org/andengine/util/math/factorioal/SparseFactorialCache.java @@ -0,0 +1,66 @@ +package org.andengine.util.math.factorioal; + +import android.util.SparseIntArray; + +/** + * (c) 2013 Nicolas Gramlich + * + * @author Nicolas Gramlich + * @since 21:37:15 - 09.06.2013 + */ +public class SparseFactorialCache implements IFactorialProvider { + // =========================================================== + // Constants + // =========================================================== + + private static SparseFactorialCache INSTANCE; + + private final SparseIntArray mCache = new SparseIntArray(); + + // =========================================================== + // Fields + // =========================================================== + + // =========================================================== + // Constructors + // =========================================================== + + private SparseFactorialCache() { + + } + + public static SparseFactorialCache getInstance() { + if (INSTANCE == null) { + INSTANCE = new SparseFactorialCache(); + } + return INSTANCE; + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + @Override + public int factorial(final int n) { + int result = this.mCache.get(n); + if (result != 0) { + return result; + } else { + result = IterativeFactorialProvider.getInstance().factorial(n); + this.mCache.put(n, result); + return result; + } + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== +} \ No newline at end of file diff --git a/src/org/andengine/util/mime/MIMEType.java b/src/org/andengine/util/mime/MIMEType.java index 3e0d065f7..ba824a805 100644 --- a/src/org/andengine/util/mime/MIMEType.java +++ b/src/org/andengine/util/mime/MIMEType.java @@ -1,9 +1,9 @@ package org.andengine.util.mime; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 14:58:20 - 10.01.2011 */ @@ -13,8 +13,9 @@ public enum MIMEType { // =========================================================== JPEG("image/jpeg"), - GIF("image/gif"), - PNG("image/png"); + Gif ("image/gif"), + PNG("image/png"), + TEXT("text/plain"); // =========================================================== // Constants @@ -23,7 +24,7 @@ public enum MIMEType { // =========================================================== // Fields // =========================================================== - + private final String mTypeString; // =========================================================== diff --git a/src/org/andengine/util/modifier/BaseDoubleValueChangeModifier.java b/src/org/andengine/util/modifier/BaseDoubleValueChangeModifier.java index 5604f821b..28783e809 100644 --- a/src/org/andengine/util/modifier/BaseDoubleValueChangeModifier.java +++ b/src/org/andengine/util/modifier/BaseDoubleValueChangeModifier.java @@ -2,7 +2,7 @@ /** - * (c) Zynga 2011 + * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 14:17:30 - 10.08.2011 diff --git a/src/org/andengine/util/modifier/BaseDoubleValueSpanModifier.java b/src/org/andengine/util/modifier/BaseDoubleValueSpanModifier.java index c7a008994..6b4deb12f 100644 --- a/src/org/andengine/util/modifier/BaseDoubleValueSpanModifier.java +++ b/src/org/andengine/util/modifier/BaseDoubleValueSpanModifier.java @@ -4,9 +4,9 @@ import org.andengine.util.modifier.ease.IEaseFunction; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 10:51:46 - 03.09.2010 * @param @@ -109,7 +109,7 @@ public void reset(final float pDuration, final float pFromValue, final float pTo // =========================================================== // Methods // =========================================================== - + public void reset(final float pDuration, final float pFromValueA, final float pToValueA, final float pFromValueB, final float pToValueB) { super.reset(pDuration, pFromValueA, pToValueA); diff --git a/src/org/andengine/util/modifier/BaseDurationModifier.java b/src/org/andengine/util/modifier/BaseDurationModifier.java index 6ba287f6c..3d2d27bcd 100644 --- a/src/org/andengine/util/modifier/BaseDurationModifier.java +++ b/src/org/andengine/util/modifier/BaseDurationModifier.java @@ -1,9 +1,9 @@ package org.andengine.util.modifier; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 10:48:13 - 03.09.2010 * @param @@ -62,16 +62,16 @@ public float getDuration() { @Override public final float onUpdate(final float pSecondsElapsed, final T pItem) { - if(this.mFinished){ + if (this.mFinished) { return 0; } else { - if(this.mSecondsElapsed == 0) { + if (this.mSecondsElapsed == 0) { this.onManagedInitialize(pItem); this.onModifierStarted(pItem); } final float secondsElapsedUsed; - if(this.mSecondsElapsed + pSecondsElapsed < this.mDuration) { + if (this.mSecondsElapsed + pSecondsElapsed < this.mDuration) { secondsElapsedUsed = pSecondsElapsed; } else { secondsElapsedUsed = this.mDuration - this.mSecondsElapsed; @@ -80,7 +80,7 @@ public final float onUpdate(final float pSecondsElapsed, final T pItem) { this.mSecondsElapsed += secondsElapsedUsed; this.onManagedUpdate(secondsElapsedUsed, pItem); - if(this.mDuration != -1 && this.mSecondsElapsed >= this.mDuration) { + if (this.mDuration != -1 && this.mSecondsElapsed >= this.mDuration) { this.mSecondsElapsed = this.mDuration; this.mFinished = true; this.onModifierFinished(pItem); diff --git a/src/org/andengine/util/modifier/BaseModifier.java b/src/org/andengine/util/modifier/BaseModifier.java index a18ec6334..9c1322790 100644 --- a/src/org/andengine/util/modifier/BaseModifier.java +++ b/src/org/andengine/util/modifier/BaseModifier.java @@ -4,9 +4,9 @@ /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 10:47:23 - 03.09.2010 * @param @@ -61,14 +61,14 @@ public final void setAutoUnregisterWhenFinished(final boolean pAutoUnregisterWhe @Override public void addModifierListener(final IModifierListener pModifierListener) { - if(pModifierListener != null) { + if (pModifierListener != null) { this.mModifierListeners.add(pModifierListener); } } @Override public boolean removeModifierListener(final IModifierListener pModifierListener) { - if(pModifierListener == null) { + if (pModifierListener == null) { return false; } else { return this.mModifierListeners.remove(pModifierListener); @@ -85,7 +85,7 @@ public boolean removeModifierListener(final IModifierListener pModifierListen protected void onModifierStarted(final T pItem) { final SmartList> modifierListeners = this.mModifierListeners; final int modifierListenerCount = modifierListeners.size(); - for(int i = modifierListenerCount - 1; i >= 0; i--) { + for (int i = modifierListenerCount - 1; i >= 0; i--) { modifierListeners.get(i).onModifierStarted(this, pItem); } } @@ -93,21 +93,21 @@ protected void onModifierStarted(final T pItem) { protected void onModifierFinished(final T pItem) { final SmartList> modifierListeners = this.mModifierListeners; final int modifierListenerCount = modifierListeners.size(); - for(int i = modifierListenerCount - 1; i >= 0; i--) { + for (int i = modifierListenerCount - 1; i >= 0; i--) { modifierListeners.get(i).onModifierFinished(this, pItem); } } protected final void assertNoNullModifier(final IModifier pModifier) { - if(pModifier == null) { + if (pModifier == null) { throw new IllegalArgumentException("Illegal 'null' " + IModifier.class.getSimpleName() + " detected!"); } } protected final void assertNoNullModifier(final IModifier ... pModifiers) { final int modifierCount = pModifiers.length; - for(int i = 0; i < modifierCount; i++) { - if(pModifiers[i] == null) { + for (int i = 0; i < modifierCount; i++) { + if (pModifiers[i] == null) { throw new IllegalArgumentException("Illegal 'null' " + IModifier.class.getSimpleName() + " detected at position: '" + i + "'!"); } } diff --git a/src/org/andengine/util/modifier/BaseQuadrupelValueSpanModifier.java b/src/org/andengine/util/modifier/BaseQuadrupelValueSpanModifier.java index 1df2ce05e..5fca40e07 100644 --- a/src/org/andengine/util/modifier/BaseQuadrupelValueSpanModifier.java +++ b/src/org/andengine/util/modifier/BaseQuadrupelValueSpanModifier.java @@ -4,7 +4,7 @@ /** * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 10:58:32 - 02.08.2011 * @param diff --git a/src/org/andengine/util/modifier/BaseSingleValueChangeModifier.java b/src/org/andengine/util/modifier/BaseSingleValueChangeModifier.java index 5959528f8..cbc3d8634 100644 --- a/src/org/andengine/util/modifier/BaseSingleValueChangeModifier.java +++ b/src/org/andengine/util/modifier/BaseSingleValueChangeModifier.java @@ -4,7 +4,7 @@ /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 10:49:51 - 03.09.2010 * @param diff --git a/src/org/andengine/util/modifier/BaseSingleValueSpanModifier.java b/src/org/andengine/util/modifier/BaseSingleValueSpanModifier.java index 8ef1eecf5..92aeedb95 100644 --- a/src/org/andengine/util/modifier/BaseSingleValueSpanModifier.java +++ b/src/org/andengine/util/modifier/BaseSingleValueSpanModifier.java @@ -4,9 +4,9 @@ import org.andengine.util.modifier.ease.IEaseFunction; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 23:29:22 - 19.03.2010 */ @@ -90,10 +90,10 @@ protected void onManagedUpdate(final float pSecondsElapsed, final T pItem) { // =========================================================== // Methods // =========================================================== - + public void reset(final float pDuration, final float pFromValue, final float pToValue) { super.reset(); - + this.mDuration = pDuration; this.mFromValue = pFromValue; this.mValueSpan = pToValue - pFromValue; diff --git a/src/org/andengine/util/modifier/BaseTripleValueSpanModifier.java b/src/org/andengine/util/modifier/BaseTripleValueSpanModifier.java index 7868528ca..3ec29edb9 100644 --- a/src/org/andengine/util/modifier/BaseTripleValueSpanModifier.java +++ b/src/org/andengine/util/modifier/BaseTripleValueSpanModifier.java @@ -3,9 +3,9 @@ import org.andengine.util.modifier.ease.IEaseFunction; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 10:52:31 - 03.09.2010 * @param diff --git a/src/org/andengine/util/modifier/IModifier.java b/src/org/andengine/util/modifier/IModifier.java index f85f87ea1..0606a3f90 100644 --- a/src/org/andengine/util/modifier/IModifier.java +++ b/src/org/andengine/util/modifier/IModifier.java @@ -8,7 +8,7 @@ /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 11:17:50 - 19.03.2010 */ diff --git a/src/org/andengine/util/modifier/LoopModifier.java b/src/org/andengine/util/modifier/LoopModifier.java index bc90815d8..20acc550d 100644 --- a/src/org/andengine/util/modifier/LoopModifier.java +++ b/src/org/andengine/util/modifier/LoopModifier.java @@ -6,7 +6,7 @@ /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 11:18:37 - 03.09.2010 * @param @@ -44,7 +44,7 @@ public LoopModifier(final IModifier pModifier) { } public LoopModifier(final IModifier pModifier, final int pLoopCount) { - this(pModifier, pLoopCount, null, (IModifierListener)null); + this(pModifier, pLoopCount, null, (IModifierListener) null); } public LoopModifier(final IModifier pModifier, final int pLoopCount, final IModifierListener pModifierListener) { @@ -52,7 +52,7 @@ public LoopModifier(final IModifier pModifier, final int pLoopCount, final IM } public LoopModifier(final IModifier pModifier, final int pLoopCount, final ILoopModifierListener pLoopModifierListener) { - this(pModifier, pLoopCount, pLoopModifierListener, (IModifierListener)null); + this(pModifier, pLoopCount, pLoopModifierListener, (IModifierListener) null); } public LoopModifier(final IModifier pModifier, final int pLoopCount, final ILoopModifierListener pLoopModifierListener, final IModifierListener pModifierListener) { @@ -107,13 +107,13 @@ public float getDuration() { @Override public float onUpdate(final float pSecondsElapsed, final T pItem) { - if(this.mFinished){ + if (this.mFinished) { return 0; } else { float secondsElapsedRemaining = pSecondsElapsed; this.mFinishedCached = false; - while((secondsElapsedRemaining > 0) && !this.mFinishedCached) { + while ((secondsElapsedRemaining > 0) && !this.mFinishedCached) { secondsElapsedRemaining -= this.mModifier.onUpdate(secondsElapsedRemaining, pItem); } this.mFinishedCached = false; @@ -140,27 +140,27 @@ public void reset() { @Override public void onModifierStarted(final IModifier pModifier, final T pItem) { - if(!this.mModifierStartedCalled) { + if (!this.mModifierStartedCalled) { this.mModifierStartedCalled = true; this.onModifierStarted(pItem); } - if(this.mLoopModifierListener != null) { + if (this.mLoopModifierListener != null) { this.mLoopModifierListener.onLoopStarted(this, this.mLoop, this.mLoopCount); } } @Override public void onModifierFinished(final IModifier pModifier, final T pItem) { - if(this.mLoopModifierListener != null) { + if (this.mLoopModifierListener != null) { this.mLoopModifierListener.onLoopFinished(this, this.mLoop, this.mLoopCount); } - if(this.mLoopCount == LoopModifier.LOOP_CONTINUOUS) { + if (this.mLoopCount == LoopModifier.LOOP_CONTINUOUS) { this.mSecondsElapsed = 0; this.mModifier.reset(); } else { this.mLoop++; - if(this.mLoop >= this.mLoopCount) { + if (this.mLoop >= this.mLoopCount) { this.mFinished = true; this.mFinishedCached = true; this.onModifierFinished(pItem); diff --git a/src/org/andengine/util/modifier/ModifierList.java b/src/org/andengine/util/modifier/ModifierList.java index 5558aa109..035573ac7 100644 --- a/src/org/andengine/util/modifier/ModifierList.java +++ b/src/org/andengine/util/modifier/ModifierList.java @@ -4,9 +4,9 @@ import org.andengine.util.adt.list.SmartList; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 14:34:57 - 03.09.2010 */ @@ -31,7 +31,7 @@ public ModifierList(final T pTarget) { this.mTarget = pTarget; } - public ModifierList(final T pTarget, final int pCapacity){ + public ModifierList(final T pTarget, final int pCapacity) { super(pCapacity); this.mTarget = pTarget; } @@ -50,7 +50,7 @@ public T getTarget() { @Override public boolean add(final IModifier pModifier) { - if(pModifier == null) { + if (pModifier == null) { throw new IllegalArgumentException("Supplied " + IModifier.class.getSimpleName() + " must not be null."); } else { return super.add(pModifier); @@ -60,11 +60,11 @@ public boolean add(final IModifier pModifier) { @Override public void onUpdate(final float pSecondsElapsed) { final int modifierCount = this.size(); - if(modifierCount > 0) { - for(int i = modifierCount - 1; i >= 0; i--) { + if (modifierCount > 0) { + for (int i = modifierCount - 1; i >= 0; i--) { final IModifier modifier = this.get(i); modifier.onUpdate(pSecondsElapsed, this.mTarget); - if(modifier.isFinished() && modifier.isAutoUnregisterWhenFinished()) { + if (modifier.isFinished() && modifier.isAutoUnregisterWhenFinished()) { this.remove(i); } } @@ -73,7 +73,7 @@ public void onUpdate(final float pSecondsElapsed) { @Override public void reset() { - for(int i = this.size() - 1; i >= 0; i--) { + for (int i = this.size() - 1; i >= 0; i--) { this.get(i).reset(); } } diff --git a/src/org/andengine/util/modifier/ParallelModifier.java b/src/org/andengine/util/modifier/ParallelModifier.java index 335cd869c..d33e0f3c0 100644 --- a/src/org/andengine/util/modifier/ParallelModifier.java +++ b/src/org/andengine/util/modifier/ParallelModifier.java @@ -5,9 +5,9 @@ import org.andengine.util.modifier.IModifier.IModifierListener; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 11:21:22 - 03.09.2010 * @param @@ -38,7 +38,7 @@ public ParallelModifier(final IModifier ... pModifiers) throws IllegalArgumen public ParallelModifier(final IModifierListener pModifierListener, final IModifier ... pModifiers) throws IllegalArgumentException { super(pModifierListener); - if(pModifiers.length == 0) { + if (pModifiers.length == 0) { throw new IllegalArgumentException("pModifiers must not be empty!"); } @@ -58,7 +58,7 @@ protected ParallelModifier(final ParallelModifier pParallelModifier) throws D this.mModifiers = new IModifier[otherModifiers.length]; final IModifier[] modifiers = this.mModifiers; - for(int i = modifiers.length - 1; i >= 0; i--) { + for (int i = modifiers.length - 1; i >= 0; i--) { modifiers[i] = otherModifiers[i].deepCopy(); } @@ -68,7 +68,7 @@ protected ParallelModifier(final ParallelModifier pParallelModifier) throws D } @Override - public ParallelModifier deepCopy() throws DeepCopyNotSupportedException{ + public ParallelModifier deepCopy() throws DeepCopyNotSupportedException { return new ParallelModifier(this); } @@ -92,7 +92,7 @@ public float getDuration() { @Override public float onUpdate(final float pSecondsElapsed, final T pItem) { - if(this.mFinished){ + if (this.mFinished) { return 0; } else { float secondsElapsedRemaining = pSecondsElapsed; @@ -100,9 +100,9 @@ public float onUpdate(final float pSecondsElapsed, final T pItem) { final IModifier[] shapeModifiers = this.mModifiers; this.mFinishedCached = false; - while(secondsElapsedRemaining > 0 && !this.mFinishedCached) { + while (secondsElapsedRemaining > 0 && !this.mFinishedCached) { float secondsElapsedUsed = 0; - for(int i = shapeModifiers.length - 1; i >= 0; i--) { + for (int i = shapeModifiers.length - 1; i >= 0; i--) { secondsElapsedUsed = Math.max(secondsElapsedUsed, shapeModifiers[i].onUpdate(pSecondsElapsed, pItem)); } secondsElapsedRemaining -= secondsElapsedUsed; @@ -121,7 +121,7 @@ public void reset() { this.mSecondsElapsed = 0; final IModifier[] shapeModifiers = this.mModifiers; - for(int i = shapeModifiers.length - 1; i >= 0; i--) { + for (int i = shapeModifiers.length - 1; i >= 0; i--) { shapeModifiers[i].reset(); } } diff --git a/src/org/andengine/util/modifier/SequenceModifier.java b/src/org/andengine/util/modifier/SequenceModifier.java index 224e9e9e1..4fe245b40 100644 --- a/src/org/andengine/util/modifier/SequenceModifier.java +++ b/src/org/andengine/util/modifier/SequenceModifier.java @@ -5,9 +5,9 @@ /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 19:39:25 - 19.03.2010 */ @@ -49,7 +49,7 @@ public SequenceModifier(final IModifierListener pModifierListener, final IMod public SequenceModifier(final ISubSequenceModifierListener pSubSequenceModifierListener, final IModifierListener pModifierListener, final IModifier ... pModifiers) throws IllegalArgumentException { super(pModifierListener); - if(pModifiers.length == 0) { + if (pModifiers.length == 0) { throw new IllegalArgumentException("pModifiers must not be empty!"); } @@ -71,7 +71,7 @@ protected SequenceModifier(final SequenceModifier pSequenceModifier) throws D this.mSubSequenceModifiers = new IModifier[otherModifiers.length]; final IModifier[] subSequenceModifiers = this.mSubSequenceModifiers; - for(int i = subSequenceModifiers.length - 1; i >= 0; i--) { + for (int i = subSequenceModifiers.length - 1; i >= 0; i--) { subSequenceModifiers[i] = otherModifiers[i].deepCopy(); } @@ -79,7 +79,7 @@ protected SequenceModifier(final SequenceModifier pSequenceModifier) throws D } @Override - public SequenceModifier deepCopy() throws DeepCopyNotSupportedException{ + public SequenceModifier deepCopy() throws DeepCopyNotSupportedException { return new SequenceModifier(this); } @@ -111,12 +111,12 @@ public float getDuration() { @Override public float onUpdate(final float pSecondsElapsed, final T pItem) { - if(this.mFinished){ + if (this.mFinished) { return 0; } else { float secondsElapsedRemaining = pSecondsElapsed; this.mFinishedCached = false; - while(secondsElapsedRemaining > 0 && !this.mFinishedCached) { + while (secondsElapsedRemaining > 0 && !this.mFinishedCached) { secondsElapsedRemaining -= this.mSubSequenceModifiers[this.mCurrentSubSequenceModifierIndex].onUpdate(secondsElapsedRemaining, pItem); } this.mFinishedCached = false; @@ -129,7 +129,7 @@ public float onUpdate(final float pSecondsElapsed, final T pItem) { @Override public void reset() { - if(this.isFinished()) { + if (this.isFinished()) { this.mSubSequenceModifiers[this.mSubSequenceModifiers.length - 1].removeModifierListener(this); } else { this.mSubSequenceModifiers[this.mCurrentSubSequenceModifierIndex].removeModifierListener(this); @@ -142,32 +142,32 @@ public void reset() { this.mSubSequenceModifiers[0].addModifierListener(this); final IModifier[] subSequenceModifiers = this.mSubSequenceModifiers; - for(int i = subSequenceModifiers.length - 1; i >= 0; i--) { + for (int i = subSequenceModifiers.length - 1; i >= 0; i--) { subSequenceModifiers[i].reset(); } } @Override public void onModifierStarted(final IModifier pModifier, final T pItem) { - if(this.mCurrentSubSequenceModifierIndex == 0) { + if (this.mCurrentSubSequenceModifierIndex == 0) { this.onModifierStarted(pItem); } - if(this.mSubSequenceModifierListener != null) { + if (this.mSubSequenceModifierListener != null) { this.mSubSequenceModifierListener.onSubSequenceStarted(pModifier, pItem, this.mCurrentSubSequenceModifierIndex); } } @Override public void onModifierFinished(final IModifier pModifier, final T pItem) { - if(this.mSubSequenceModifierListener != null) { + if (this.mSubSequenceModifierListener != null) { this.mSubSequenceModifierListener.onSubSequenceFinished(pModifier, pItem, this.mCurrentSubSequenceModifierIndex); } pModifier.removeModifierListener(this); this.mCurrentSubSequenceModifierIndex++; - if(this.mCurrentSubSequenceModifierIndex < this.mSubSequenceModifiers.length) { + if (this.mCurrentSubSequenceModifierIndex < this.mSubSequenceModifiers.length) { final IModifier nextSubSequenceModifier = this.mSubSequenceModifiers[this.mCurrentSubSequenceModifierIndex]; nextSubSequenceModifier.addModifierListener(this); } else { diff --git a/src/org/andengine/util/modifier/ease/EaseBackIn.java b/src/org/andengine/util/modifier/ease/EaseBackIn.java index ee0282b85..a0296aa92 100644 --- a/src/org/andengine/util/modifier/ease/EaseBackIn.java +++ b/src/org/andengine/util/modifier/ease/EaseBackIn.java @@ -30,7 +30,7 @@ private EaseBackIn() { } public static EaseBackIn getInstance() { - if(null == INSTANCE) { + if (null == INSTANCE) { INSTANCE = new EaseBackIn(); } return INSTANCE; diff --git a/src/org/andengine/util/modifier/ease/EaseBackInOut.java b/src/org/andengine/util/modifier/ease/EaseBackInOut.java index c3e68fd70..69170bb0e 100644 --- a/src/org/andengine/util/modifier/ease/EaseBackInOut.java +++ b/src/org/andengine/util/modifier/ease/EaseBackInOut.java @@ -28,7 +28,7 @@ private EaseBackInOut() { } public static EaseBackInOut getInstance() { - if(INSTANCE == null) { + if (INSTANCE == null) { INSTANCE = new EaseBackInOut(); } return INSTANCE; @@ -46,7 +46,7 @@ public static EaseBackInOut getInstance() { public float getPercentage(final float pSecondsElapsed, final float pDuration) { final float percentage = pSecondsElapsed / pDuration; - if(percentage < 0.5f) { + if (percentage < 0.5f) { return 0.5f * EaseBackIn.getValue(2 * percentage); } else { return 0.5f + 0.5f * EaseBackOut.getValue(percentage * 2 - 1); diff --git a/src/org/andengine/util/modifier/ease/EaseBackOut.java b/src/org/andengine/util/modifier/ease/EaseBackOut.java index 71e302e0d..f7a24ad0c 100644 --- a/src/org/andengine/util/modifier/ease/EaseBackOut.java +++ b/src/org/andengine/util/modifier/ease/EaseBackOut.java @@ -28,7 +28,7 @@ private EaseBackOut() { } public static EaseBackOut getInstance() { - if(INSTANCE == null) { + if (INSTANCE == null) { INSTANCE = new EaseBackOut(); } return INSTANCE; diff --git a/src/org/andengine/util/modifier/ease/EaseBounceIn.java b/src/org/andengine/util/modifier/ease/EaseBounceIn.java index ef2e25995..3008aba00 100644 --- a/src/org/andengine/util/modifier/ease/EaseBounceIn.java +++ b/src/org/andengine/util/modifier/ease/EaseBounceIn.java @@ -28,7 +28,7 @@ private EaseBounceIn() { } public static EaseBounceIn getInstance() { - if(INSTANCE == null) { + if (INSTANCE == null) { INSTANCE = new EaseBounceIn(); } return INSTANCE; diff --git a/src/org/andengine/util/modifier/ease/EaseBounceInOut.java b/src/org/andengine/util/modifier/ease/EaseBounceInOut.java index fec86ba0b..0ad71b2f2 100644 --- a/src/org/andengine/util/modifier/ease/EaseBounceInOut.java +++ b/src/org/andengine/util/modifier/ease/EaseBounceInOut.java @@ -28,7 +28,7 @@ private EaseBounceInOut() { } public static EaseBounceInOut getInstance() { - if(INSTANCE == null) { + if (INSTANCE == null) { INSTANCE = new EaseBounceInOut(); } return INSTANCE; @@ -46,7 +46,7 @@ public static EaseBounceInOut getInstance() { public float getPercentage(final float pSecondsElapsed, final float pDuration) { final float percentage = pSecondsElapsed / pDuration; - if(percentage < 0.5f) { + if (percentage < 0.5f) { return 0.5f * EaseBounceIn.getValue(2 * percentage); } else { return 0.5f + 0.5f * EaseBounceOut.getValue(percentage * 2 - 1); diff --git a/src/org/andengine/util/modifier/ease/EaseBounceOut.java b/src/org/andengine/util/modifier/ease/EaseBounceOut.java index 13d058598..ca52cb753 100644 --- a/src/org/andengine/util/modifier/ease/EaseBounceOut.java +++ b/src/org/andengine/util/modifier/ease/EaseBounceOut.java @@ -28,7 +28,7 @@ private EaseBounceOut() { } public static EaseBounceOut getInstance() { - if(INSTANCE == null) { + if (INSTANCE == null) { INSTANCE = new EaseBounceOut(); } return INSTANCE; @@ -52,12 +52,12 @@ public float getPercentage(final float pSecondsElapsed, final float pDuration) { // =========================================================== public static float getValue(final float pPercentage) { - if(pPercentage < (1f / 2.75f)) { + if (pPercentage < (1f / 2.75f)) { return 7.5625f * pPercentage * pPercentage; - } else if(pPercentage < (2f / 2.75f)) { + } else if (pPercentage < (2f / 2.75f)) { final float t = pPercentage - (1.5f / 2.75f); return 7.5625f * t * t + 0.75f; - } else if(pPercentage < (2.5f / 2.75f)) { + } else if (pPercentage < (2.5f / 2.75f)) { final float t = pPercentage - (2.25f / 2.75f); return 7.5625f * t * t + 0.9375f; } else { diff --git a/src/org/andengine/util/modifier/ease/EaseCircularIn.java b/src/org/andengine/util/modifier/ease/EaseCircularIn.java index bd707d8d1..b04c27287 100644 --- a/src/org/andengine/util/modifier/ease/EaseCircularIn.java +++ b/src/org/andengine/util/modifier/ease/EaseCircularIn.java @@ -1,6 +1,5 @@ package org.andengine.util.modifier.ease; -import android.util.FloatMath; /** * (c) 2010 Nicolas Gramlich @@ -30,7 +29,7 @@ private EaseCircularIn() { } public static EaseCircularIn getInstance() { - if(INSTANCE == null) { + if (INSTANCE == null) { INSTANCE = new EaseCircularIn(); } return INSTANCE; @@ -54,7 +53,7 @@ public float getPercentage(final float pSecondsElapsed, final float pDuration) { // =========================================================== public static float getValue(final float pPercentage) { - return -(FloatMath.sqrt(1 - pPercentage * pPercentage) - 1.0f); + return -((float) Math.sqrt(1 - pPercentage * pPercentage) - 1.0f); } // =========================================================== diff --git a/src/org/andengine/util/modifier/ease/EaseCircularInOut.java b/src/org/andengine/util/modifier/ease/EaseCircularInOut.java index 53058ba2a..0be0f0862 100644 --- a/src/org/andengine/util/modifier/ease/EaseCircularInOut.java +++ b/src/org/andengine/util/modifier/ease/EaseCircularInOut.java @@ -28,7 +28,7 @@ private EaseCircularInOut() { } public static EaseCircularInOut getInstance() { - if(INSTANCE == null) { + if (INSTANCE == null) { INSTANCE = new EaseCircularInOut(); } return INSTANCE; @@ -46,7 +46,7 @@ public static EaseCircularInOut getInstance() { public float getPercentage(final float pSecondsElapsed, final float pDuration) { final float percentage = pSecondsElapsed / pDuration; - if(percentage < 0.5f) { + if (percentage < 0.5f) { return 0.5f * EaseCircularIn.getValue(2 * percentage); } else { return 0.5f + 0.5f * EaseCircularOut.getValue(percentage * 2 - 1); diff --git a/src/org/andengine/util/modifier/ease/EaseCircularOut.java b/src/org/andengine/util/modifier/ease/EaseCircularOut.java index cad80942c..d1662c15f 100644 --- a/src/org/andengine/util/modifier/ease/EaseCircularOut.java +++ b/src/org/andengine/util/modifier/ease/EaseCircularOut.java @@ -1,6 +1,5 @@ package org.andengine.util.modifier.ease; -import android.util.FloatMath; /** * (c) 2010 Nicolas Gramlich @@ -30,7 +29,7 @@ private EaseCircularOut() { } public static EaseCircularOut getInstance() { - if(INSTANCE == null) { + if (INSTANCE == null) { INSTANCE = new EaseCircularOut(); } return INSTANCE; @@ -55,7 +54,7 @@ public float getPercentage(final float pSecondsElapsed, final float pDuration) { public static float getValue(final float pPercentage) { final float t = pPercentage - 1; - return FloatMath.sqrt(1 - t * t); + return (float) Math.sqrt(1 - t * t); } // =========================================================== diff --git a/src/org/andengine/util/modifier/ease/EaseCubicIn.java b/src/org/andengine/util/modifier/ease/EaseCubicIn.java index 526515a7c..15f8a0004 100644 --- a/src/org/andengine/util/modifier/ease/EaseCubicIn.java +++ b/src/org/andengine/util/modifier/ease/EaseCubicIn.java @@ -28,7 +28,7 @@ private EaseCubicIn() { } public static EaseCubicIn getInstance() { - if(INSTANCE == null) { + if (INSTANCE == null) { INSTANCE = new EaseCubicIn(); } return INSTANCE; diff --git a/src/org/andengine/util/modifier/ease/EaseCubicInOut.java b/src/org/andengine/util/modifier/ease/EaseCubicInOut.java index 50cae7a23..dd948c170 100644 --- a/src/org/andengine/util/modifier/ease/EaseCubicInOut.java +++ b/src/org/andengine/util/modifier/ease/EaseCubicInOut.java @@ -28,7 +28,7 @@ private EaseCubicInOut() { } public static EaseCubicInOut getInstance() { - if(INSTANCE == null) { + if (INSTANCE == null) { INSTANCE = new EaseCubicInOut(); } return INSTANCE; @@ -46,7 +46,7 @@ public static EaseCubicInOut getInstance() { public float getPercentage(final float pSecondsElapsed, final float pDuration) { final float percentage = pSecondsElapsed / pDuration; - if(percentage < 0.5f) { + if (percentage < 0.5f) { return 0.5f * EaseCubicIn.getValue(2 * percentage); } else { return 0.5f + 0.5f * EaseCubicOut.getValue(percentage * 2 - 1); diff --git a/src/org/andengine/util/modifier/ease/EaseCubicOut.java b/src/org/andengine/util/modifier/ease/EaseCubicOut.java index 315eb16c3..ba24db6f5 100644 --- a/src/org/andengine/util/modifier/ease/EaseCubicOut.java +++ b/src/org/andengine/util/modifier/ease/EaseCubicOut.java @@ -28,7 +28,7 @@ private EaseCubicOut() { } public static EaseCubicOut getInstance() { - if(INSTANCE == null) { + if (INSTANCE == null) { INSTANCE = new EaseCubicOut(); } return INSTANCE; diff --git a/src/org/andengine/util/modifier/ease/EaseElasticIn.java b/src/org/andengine/util/modifier/ease/EaseElasticIn.java index 8de385399..bf4aa6f25 100644 --- a/src/org/andengine/util/modifier/ease/EaseElasticIn.java +++ b/src/org/andengine/util/modifier/ease/EaseElasticIn.java @@ -2,8 +2,6 @@ import org.andengine.util.math.MathConstants; -import android.util.FloatMath; - /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. @@ -32,7 +30,7 @@ private EaseElasticIn() { } public static EaseElasticIn getInstance() { - if(INSTANCE == null) { + if (INSTANCE == null) { INSTANCE = new EaseElasticIn(); } return INSTANCE; @@ -56,10 +54,10 @@ public float getPercentage(final float pSecondsElapsed, final float pDuration) { // =========================================================== public static float getValue(final float pSecondsElapsed, final float pDuration, final float pPercentage) { - if(pSecondsElapsed == 0) { + if (pSecondsElapsed == 0) { return 0; } - if(pSecondsElapsed == pDuration) { + if (pSecondsElapsed == pDuration) { return 1; } @@ -67,7 +65,7 @@ public static float getValue(final float pSecondsElapsed, final float pDuration, final float s = p / 4; final float t = pPercentage - 1; - return -(float)Math.pow(2, 10 * t) * FloatMath.sin((t * pDuration - s) * MathConstants.PI_TWICE / p); + return -(float) Math.pow(2, 10 * t) * (float) Math.sin((t * pDuration - s) * MathConstants.PI_TWICE / p); } // =========================================================== diff --git a/src/org/andengine/util/modifier/ease/EaseElasticInOut.java b/src/org/andengine/util/modifier/ease/EaseElasticInOut.java index afb13dc56..dc40f0b08 100644 --- a/src/org/andengine/util/modifier/ease/EaseElasticInOut.java +++ b/src/org/andengine/util/modifier/ease/EaseElasticInOut.java @@ -29,7 +29,7 @@ private EaseElasticInOut() { } public static EaseElasticInOut getInstance() { - if(INSTANCE == null) { + if (INSTANCE == null) { INSTANCE = new EaseElasticInOut(); } return INSTANCE; @@ -47,7 +47,7 @@ public static EaseElasticInOut getInstance() { public float getPercentage(final float pSecondsElapsed, final float pDuration) { final float percentage = pSecondsElapsed / pDuration; - if(percentage < 0.5f) { + if (percentage < 0.5f) { return 0.5f * EaseElasticIn.getValue(2 * pSecondsElapsed, pDuration, 2 * percentage); } else { return 0.5f + 0.5f * EaseElasticOut.getValue(pSecondsElapsed * 2 - pDuration, pDuration, percentage * 2 - 1); diff --git a/src/org/andengine/util/modifier/ease/EaseElasticOut.java b/src/org/andengine/util/modifier/ease/EaseElasticOut.java index 3ae923f50..c773ee769 100644 --- a/src/org/andengine/util/modifier/ease/EaseElasticOut.java +++ b/src/org/andengine/util/modifier/ease/EaseElasticOut.java @@ -2,8 +2,6 @@ import org.andengine.util.math.MathConstants; -import android.util.FloatMath; - /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. @@ -32,7 +30,7 @@ private EaseElasticOut() { } public static EaseElasticOut getInstance() { - if(INSTANCE == null) { + if (INSTANCE == null) { INSTANCE = new EaseElasticOut(); } return INSTANCE; @@ -56,17 +54,17 @@ public float getPercentage(final float pSecondsElapsed, final float pDuration) { // =========================================================== public static float getValue(final float pSecondsElapsed, final float pDuration, final float pPercentageDone) { - if(pSecondsElapsed == 0) { + if (pSecondsElapsed == 0) { return 0; } - if(pSecondsElapsed == pDuration) { + if (pSecondsElapsed == pDuration) { return 1; } final float p = pDuration * 0.3f; final float s = p / 4; - return 1 + (float)Math.pow(2, -10 * pPercentageDone) * FloatMath.sin((pPercentageDone * pDuration - s) * MathConstants.PI_TWICE / p); + return 1 + (float) Math.pow(2, -10 * pPercentageDone) * (float) Math.sin((pPercentageDone * pDuration - s) * MathConstants.PI_TWICE / p); } // =========================================================== diff --git a/src/org/andengine/util/modifier/ease/EaseExponentialIn.java b/src/org/andengine/util/modifier/ease/EaseExponentialIn.java index 4553f64c7..73a95dfd8 100644 --- a/src/org/andengine/util/modifier/ease/EaseExponentialIn.java +++ b/src/org/andengine/util/modifier/ease/EaseExponentialIn.java @@ -28,7 +28,7 @@ private EaseExponentialIn() { } public static EaseExponentialIn getInstance() { - if(INSTANCE == null) { + if (INSTANCE == null) { INSTANCE = new EaseExponentialIn(); } return INSTANCE; diff --git a/src/org/andengine/util/modifier/ease/EaseExponentialInOut.java b/src/org/andengine/util/modifier/ease/EaseExponentialInOut.java index 7d1eb296b..3817550f6 100644 --- a/src/org/andengine/util/modifier/ease/EaseExponentialInOut.java +++ b/src/org/andengine/util/modifier/ease/EaseExponentialInOut.java @@ -28,7 +28,7 @@ private EaseExponentialInOut() { } public static EaseExponentialInOut getInstance() { - if(INSTANCE == null) { + if (INSTANCE == null) { INSTANCE = new EaseExponentialInOut(); } return INSTANCE; @@ -46,7 +46,7 @@ public static EaseExponentialInOut getInstance() { public float getPercentage(final float pSecondsElapsed, final float pDuration) { final float percentage = pSecondsElapsed / pDuration; - if(percentage < 0.5f) { + if (percentage < 0.5f) { return 0.5f * EaseExponentialIn.getValue(2 * percentage); } else { return 0.5f + 0.5f * EaseExponentialOut.getValue(percentage * 2 - 1); diff --git a/src/org/andengine/util/modifier/ease/EaseExponentialOut.java b/src/org/andengine/util/modifier/ease/EaseExponentialOut.java index cd56c467f..d2ac43b34 100644 --- a/src/org/andengine/util/modifier/ease/EaseExponentialOut.java +++ b/src/org/andengine/util/modifier/ease/EaseExponentialOut.java @@ -28,7 +28,7 @@ private EaseExponentialOut() { } public static EaseExponentialOut getInstance() { - if(INSTANCE == null) { + if (INSTANCE == null) { INSTANCE = new EaseExponentialOut(); } return INSTANCE; @@ -52,7 +52,7 @@ public float getPercentage(final float pSecondsElapsed, final float pDuration) { // =========================================================== public static float getValue(final float pPercentage) { - return (pPercentage == 1) ? 1 : (-(float)Math.pow(2, -10 * pPercentage) + 1); + return (pPercentage == 1) ? 1 : (-(float) Math.pow(2, -10 * pPercentage) + 1); } // =========================================================== diff --git a/src/org/andengine/util/modifier/ease/EaseLinear.java b/src/org/andengine/util/modifier/ease/EaseLinear.java index c81879128..f9c7cc6a2 100644 --- a/src/org/andengine/util/modifier/ease/EaseLinear.java +++ b/src/org/andengine/util/modifier/ease/EaseLinear.java @@ -28,7 +28,7 @@ private EaseLinear() { } public static EaseLinear getInstance() { - if(INSTANCE == null) { + if (INSTANCE == null) { INSTANCE = new EaseLinear(); } return INSTANCE; diff --git a/src/org/andengine/util/modifier/ease/EaseQuadIn.java b/src/org/andengine/util/modifier/ease/EaseQuadIn.java index 443c5a2d7..245516068 100644 --- a/src/org/andengine/util/modifier/ease/EaseQuadIn.java +++ b/src/org/andengine/util/modifier/ease/EaseQuadIn.java @@ -28,7 +28,7 @@ private EaseQuadIn() { } public static EaseQuadIn getInstance() { - if(INSTANCE == null) { + if (INSTANCE == null) { INSTANCE = new EaseQuadIn(); } return INSTANCE; diff --git a/src/org/andengine/util/modifier/ease/EaseQuadInOut.java b/src/org/andengine/util/modifier/ease/EaseQuadInOut.java index ca3780c32..67aae9154 100644 --- a/src/org/andengine/util/modifier/ease/EaseQuadInOut.java +++ b/src/org/andengine/util/modifier/ease/EaseQuadInOut.java @@ -28,7 +28,7 @@ private EaseQuadInOut() { } public static EaseQuadInOut getInstance() { - if(INSTANCE == null) { + if (INSTANCE == null) { INSTANCE = new EaseQuadInOut(); } return INSTANCE; @@ -46,7 +46,7 @@ public static EaseQuadInOut getInstance() { public float getPercentage(final float pSecondsElapsed, final float pDuration) { final float percentage = pSecondsElapsed / pDuration; - if(percentage < 0.5f) { + if (percentage < 0.5f) { return 0.5f * EaseQuadIn.getValue(2 * percentage); } else { return 0.5f + 0.5f * EaseQuadOut.getValue(percentage * 2 - 1); diff --git a/src/org/andengine/util/modifier/ease/EaseQuadOut.java b/src/org/andengine/util/modifier/ease/EaseQuadOut.java index 706382d2d..02d985c69 100644 --- a/src/org/andengine/util/modifier/ease/EaseQuadOut.java +++ b/src/org/andengine/util/modifier/ease/EaseQuadOut.java @@ -28,7 +28,7 @@ private EaseQuadOut() { } public static EaseQuadOut getInstance() { - if(INSTANCE == null) { + if (INSTANCE == null) { INSTANCE = new EaseQuadOut(); } return INSTANCE; diff --git a/src/org/andengine/util/modifier/ease/EaseQuartIn.java b/src/org/andengine/util/modifier/ease/EaseQuartIn.java index b8a1d861c..c2e09f7ba 100644 --- a/src/org/andengine/util/modifier/ease/EaseQuartIn.java +++ b/src/org/andengine/util/modifier/ease/EaseQuartIn.java @@ -28,7 +28,7 @@ private EaseQuartIn() { } public static EaseQuartIn getInstance() { - if(INSTANCE == null) { + if (INSTANCE == null) { INSTANCE = new EaseQuartIn(); } return INSTANCE; diff --git a/src/org/andengine/util/modifier/ease/EaseQuartInOut.java b/src/org/andengine/util/modifier/ease/EaseQuartInOut.java index c93b7bfa1..a8b9bbc98 100644 --- a/src/org/andengine/util/modifier/ease/EaseQuartInOut.java +++ b/src/org/andengine/util/modifier/ease/EaseQuartInOut.java @@ -28,7 +28,7 @@ private EaseQuartInOut() { } public static EaseQuartInOut getInstance() { - if(INSTANCE == null) { + if (INSTANCE == null) { INSTANCE = new EaseQuartInOut(); } return INSTANCE; @@ -46,7 +46,7 @@ public static EaseQuartInOut getInstance() { public float getPercentage(final float pSecondsElapsed, final float pDuration) { final float percentage = pSecondsElapsed / pDuration; - if(percentage < 0.5f) { + if (percentage < 0.5f) { return 0.5f * EaseQuartIn.getValue(2 * percentage); } else { return 0.5f + 0.5f * EaseQuartOut.getValue(percentage * 2 - 1); diff --git a/src/org/andengine/util/modifier/ease/EaseQuartOut.java b/src/org/andengine/util/modifier/ease/EaseQuartOut.java index bd5bf3f7d..a0aac2714 100644 --- a/src/org/andengine/util/modifier/ease/EaseQuartOut.java +++ b/src/org/andengine/util/modifier/ease/EaseQuartOut.java @@ -28,7 +28,7 @@ private EaseQuartOut() { } public static EaseQuartOut getInstance() { - if(INSTANCE == null) { + if (INSTANCE == null) { INSTANCE = new EaseQuartOut(); } return INSTANCE; diff --git a/src/org/andengine/util/modifier/ease/EaseQuintIn.java b/src/org/andengine/util/modifier/ease/EaseQuintIn.java index 296be6aef..2517650bf 100644 --- a/src/org/andengine/util/modifier/ease/EaseQuintIn.java +++ b/src/org/andengine/util/modifier/ease/EaseQuintIn.java @@ -28,7 +28,7 @@ private EaseQuintIn() { } public static EaseQuintIn getInstance() { - if(INSTANCE == null) { + if (INSTANCE == null) { INSTANCE = new EaseQuintIn(); } return INSTANCE; diff --git a/src/org/andengine/util/modifier/ease/EaseQuintInOut.java b/src/org/andengine/util/modifier/ease/EaseQuintInOut.java index 46905b107..e795d0090 100644 --- a/src/org/andengine/util/modifier/ease/EaseQuintInOut.java +++ b/src/org/andengine/util/modifier/ease/EaseQuintInOut.java @@ -28,7 +28,7 @@ private EaseQuintInOut() { } public static EaseQuintInOut getInstance() { - if(INSTANCE == null) { + if (INSTANCE == null) { INSTANCE = new EaseQuintInOut(); } return INSTANCE; @@ -46,7 +46,7 @@ public static EaseQuintInOut getInstance() { public float getPercentage(final float pSecondsElapsed, final float pDuration) { final float percentage = pSecondsElapsed / pDuration; - if(percentage < 0.5f) { + if (percentage < 0.5f) { return 0.5f * EaseQuintIn.getValue(2 * percentage); } else { return 0.5f + 0.5f * EaseQuintOut.getValue(percentage * 2 - 1); diff --git a/src/org/andengine/util/modifier/ease/EaseQuintOut.java b/src/org/andengine/util/modifier/ease/EaseQuintOut.java index 1ff5e9017..be4e479d5 100644 --- a/src/org/andengine/util/modifier/ease/EaseQuintOut.java +++ b/src/org/andengine/util/modifier/ease/EaseQuintOut.java @@ -28,7 +28,7 @@ private EaseQuintOut() { } public static EaseQuintOut getInstance() { - if(INSTANCE == null) { + if (INSTANCE == null) { INSTANCE = new EaseQuintOut(); } return INSTANCE; diff --git a/src/org/andengine/util/modifier/ease/EaseSineIn.java b/src/org/andengine/util/modifier/ease/EaseSineIn.java index 23e629cb3..0894b41d4 100644 --- a/src/org/andengine/util/modifier/ease/EaseSineIn.java +++ b/src/org/andengine/util/modifier/ease/EaseSineIn.java @@ -2,8 +2,6 @@ import org.andengine.util.math.MathConstants; -import android.util.FloatMath; - /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. @@ -32,7 +30,7 @@ private EaseSineIn() { } public static EaseSineIn getInstance() { - if(INSTANCE == null) { + if (INSTANCE == null) { INSTANCE = new EaseSineIn(); } return INSTANCE; @@ -56,7 +54,7 @@ public float getPercentage(final float pSecondsElapsed, final float pDuration) { // =========================================================== public static float getValue(final float pPercentage) { - return -FloatMath.cos(pPercentage * MathConstants.PI_HALF) + 1; + return -(float) Math.cos(pPercentage * MathConstants.PI_HALF) + 1; } // =========================================================== diff --git a/src/org/andengine/util/modifier/ease/EaseSineInOut.java b/src/org/andengine/util/modifier/ease/EaseSineInOut.java index 98dcd4113..36613596e 100644 --- a/src/org/andengine/util/modifier/ease/EaseSineInOut.java +++ b/src/org/andengine/util/modifier/ease/EaseSineInOut.java @@ -1,7 +1,6 @@ package org.andengine.util.modifier.ease; import static org.andengine.util.math.MathConstants.PI; -import android.util.FloatMath; /** * (c) 2010 Nicolas Gramlich @@ -31,7 +30,7 @@ private EaseSineInOut() { } public static EaseSineInOut getInstance() { - if(INSTANCE == null) { + if (INSTANCE == null) { INSTANCE = new EaseSineInOut(); } return INSTANCE; @@ -49,7 +48,7 @@ public static EaseSineInOut getInstance() { public float getPercentage(final float pSecondsElapsed, final float pDuration) { final float percentage = pSecondsElapsed / pDuration; - return -0.5f * (FloatMath.cos(percentage * PI) - 1); + return -0.5f * ((float) Math.cos(percentage * PI) - 1); } // =========================================================== diff --git a/src/org/andengine/util/modifier/ease/EaseSineOut.java b/src/org/andengine/util/modifier/ease/EaseSineOut.java index 46bf096ff..b4434d46c 100644 --- a/src/org/andengine/util/modifier/ease/EaseSineOut.java +++ b/src/org/andengine/util/modifier/ease/EaseSineOut.java @@ -2,8 +2,6 @@ import org.andengine.util.math.MathConstants; -import android.util.FloatMath; - /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. @@ -32,7 +30,7 @@ private EaseSineOut() { } public static EaseSineOut getInstance() { - if(INSTANCE == null) { + if (INSTANCE == null) { INSTANCE = new EaseSineOut(); } return INSTANCE; @@ -56,7 +54,7 @@ public float getPercentage(final float pSecondsElapsed, final float pDuration) { // =========================================================== public static float getValue(final float pPercentage) { - return FloatMath.sin(pPercentage * MathConstants.PI_HALF); + return (float) Math.sin(pPercentage * MathConstants.PI_HALF); } // =========================================================== diff --git a/src/org/andengine/util/modifier/ease/EaseStrongIn.java b/src/org/andengine/util/modifier/ease/EaseStrongIn.java index 1393781e4..f8f462d7d 100644 --- a/src/org/andengine/util/modifier/ease/EaseStrongIn.java +++ b/src/org/andengine/util/modifier/ease/EaseStrongIn.java @@ -28,7 +28,7 @@ private EaseStrongIn() { } public static EaseStrongIn getInstance() { - if(INSTANCE == null) { + if (INSTANCE == null) { INSTANCE = new EaseStrongIn(); } return INSTANCE; diff --git a/src/org/andengine/util/modifier/ease/EaseStrongInOut.java b/src/org/andengine/util/modifier/ease/EaseStrongInOut.java index 0d6ca61f6..3b2dd4157 100644 --- a/src/org/andengine/util/modifier/ease/EaseStrongInOut.java +++ b/src/org/andengine/util/modifier/ease/EaseStrongInOut.java @@ -28,7 +28,7 @@ private EaseStrongInOut() { } public static EaseStrongInOut getInstance() { - if(INSTANCE == null) { + if (INSTANCE == null) { INSTANCE = new EaseStrongInOut(); } return INSTANCE; @@ -46,7 +46,7 @@ public static EaseStrongInOut getInstance() { public float getPercentage(final float pSecondsElapsed, final float pDuration) { final float percentage = pSecondsElapsed / pDuration; - if(percentage < 0.5f) { + if (percentage < 0.5f) { return 0.5f * EaseStrongIn.getValue(2 * percentage); } else { return 0.5f + 0.5f * EaseStrongOut.getValue(percentage * 2 - 1); diff --git a/src/org/andengine/util/modifier/ease/EaseStrongOut.java b/src/org/andengine/util/modifier/ease/EaseStrongOut.java index cae57dd0e..5cad9f608 100644 --- a/src/org/andengine/util/modifier/ease/EaseStrongOut.java +++ b/src/org/andengine/util/modifier/ease/EaseStrongOut.java @@ -28,7 +28,7 @@ private EaseStrongOut() { } public static EaseStrongOut getInstance() { - if(INSTANCE == null) { + if (INSTANCE == null) { INSTANCE = new EaseStrongOut(); } return INSTANCE; diff --git a/src/org/andengine/util/modifier/util/ModifierUtils.java b/src/org/andengine/util/modifier/util/ModifierUtils.java index f426f80bd..83bc156f3 100644 --- a/src/org/andengine/util/modifier/util/ModifierUtils.java +++ b/src/org/andengine/util/modifier/util/ModifierUtils.java @@ -3,13 +3,13 @@ import org.andengine.util.modifier.IModifier; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 11:16:36 - 03.09.2010 */ -public class ModifierUtils { +public final class ModifierUtils { // =========================================================== // Constants // =========================================================== @@ -22,6 +22,10 @@ public class ModifierUtils { // Constructors // =========================================================== + private ModifierUtils() { + + } + // =========================================================== // Getter & Setter // =========================================================== @@ -34,10 +38,10 @@ public class ModifierUtils { // Methods // =========================================================== - public static float getSequenceDurationOfModifier(final IModifier[] pModifiers){ + public static float getSequenceDurationOfModifier(final IModifier[] pModifiers) { float duration = Float.MIN_VALUE; - for(int i = pModifiers.length - 1; i >= 0; i--) { + for (int i = pModifiers.length - 1; i >= 0; i--) { duration += pModifiers[i].getDuration(); } diff --git a/src/org/andengine/util/net/HttpClientUtils.java b/src/org/andengine/util/net/HttpClientUtils.java new file mode 100644 index 000000000..bac352524 --- /dev/null +++ b/src/org/andengine/util/net/HttpClientUtils.java @@ -0,0 +1,61 @@ +package org.andengine.util.net; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; + +import org.apache.http.NameValuePair; +import org.apache.http.message.BasicNameValuePair; + + +/** + * (c) 2013 Nicolas Gramlich + * + * @author Nicolas Gramlich + * @since 19:20:32 - 03.05.2013 + */ +public final class HttpClientUtils { + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + // =========================================================== + // Constructors + // =========================================================== + + private HttpClientUtils() { + + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods from SuperClass/Interfaces + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + public static List convertParametersToNameValuePairs(final Map pParameters) { + final List result = new ArrayList(); + + for (final Entry entry : pParameters.entrySet()) { + result.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); + } + + return result; + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== + +} diff --git a/src/org/andengine/util/net/HttpUtils.java b/src/org/andengine/util/net/HttpUtils.java new file mode 100644 index 000000000..aea8cc87f --- /dev/null +++ b/src/org/andengine/util/net/HttpUtils.java @@ -0,0 +1,66 @@ +package org.andengine.util.net; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; + +import org.apache.http.HttpStatus; +import org.apache.http.NameValuePair; +import org.apache.http.message.BasicNameValuePair; + + +/** + * (c) 2013 Nicolas Gramlich + * + * @author Nicolas Gramlich + * @since 19:20:32 - 03.05.2013 + */ +public final class HttpUtils { + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + // =========================================================== + // Constructors + // =========================================================== + + private HttpUtils() { + + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods from SuperClass/Interfaces + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + public static List convertParametersToNameValuePairs(final Map pParameters) { + final List result = new ArrayList(); + + for (final Entry entry : pParameters.entrySet()) { + result.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); + } + + return result; + } + + public static boolean isHttpStatusCodeSuccess(final int pHttpStatusCode) { + return pHttpStatusCode >= HttpStatus.SC_OK && pHttpStatusCode < HttpStatus.SC_MULTIPLE_CHOICES; + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== + +} diff --git a/src/org/andengine/util/preferences/SecureSharedPreferences.java b/src/org/andengine/util/preferences/SecureSharedPreferences.java new file mode 100644 index 000000000..6bf60dc23 --- /dev/null +++ b/src/org/andengine/util/preferences/SecureSharedPreferences.java @@ -0,0 +1,380 @@ +package org.andengine.util.preferences; + +import java.io.UnsupportedEncodingException; +import java.security.GeneralSecurityException; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReadWriteLock; +import java.util.concurrent.locks.ReentrantReadWriteLock; + +import javax.crypto.Cipher; +import javax.crypto.spec.IvParameterSpec; +import javax.crypto.spec.SecretKeySpec; + +import org.andengine.util.exception.MethodNotYetImplementedException; +import org.andengine.util.preferences.exception.SecureSharedPreferencesException; + +import android.annotation.TargetApi; +import android.content.SharedPreferences; +import android.os.Build; +import android.util.Base64; + +/** + * (c) 2013 Nicolas Gramlich + * + * @author Nicolas Gramlich + * @since 20:09:38 - 13.04.2013 + */ +public class SecureSharedPreferences implements SharedPreferences { + // =========================================================== + // Constants + // =========================================================== + + protected static final String CIPHER_TRANSFORMATION = "AES/CBC/PKCS5Padding"; + protected static final String KEY_HASH_TRANSFORMATION = "SHA-256"; + protected static final String CHARSET = "UTF-8"; + + // =========================================================== + // Fields + // =========================================================== + + protected final SharedPreferences mDelegate; + + protected final boolean mEncryptKeys; + protected final boolean mEncryptValues; + + protected final Cipher mEncryptCipher; + protected final Cipher mDecryptCipher; + + protected final ReadWriteLock mReadWriteLock = new ReentrantReadWriteLock(true); + + // =========================================================== + // Constructors + // =========================================================== + + public SecureSharedPreferences(final SharedPreferences pDelegate, final String pSecureKey) throws SecureSharedPreferencesException { + this(pDelegate, pSecureKey, true, true); + } + + public SecureSharedPreferences(final SharedPreferences pDelegate, final String pSecureKey, final boolean pEncryptKeys, final boolean pEncryptValues) throws SecureSharedPreferencesException { + this.mDelegate = pDelegate; + this.mEncryptKeys = pEncryptKeys; + this.mEncryptValues = pEncryptValues; + try { + this.mEncryptCipher = Cipher.getInstance(SecureSharedPreferences.CIPHER_TRANSFORMATION); + this.mDecryptCipher = Cipher.getInstance(SecureSharedPreferences.CIPHER_TRANSFORMATION); + + final IvParameterSpec ivSpec = this.getIvParameterSpec(); + final SecretKeySpec secretKey = this.getSecretKeySpec(pSecureKey); + + this.mEncryptCipher.init(Cipher.ENCRYPT_MODE, secretKey, ivSpec); + this.mDecryptCipher.init(Cipher.DECRYPT_MODE, secretKey, ivSpec); + } catch (final GeneralSecurityException e) { + throw new SecureSharedPreferencesException(e); + } catch (final UnsupportedEncodingException e) { + throw new SecureSharedPreferencesException(e); + } + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + public Lock getReadLock() { + return this.mReadWriteLock.readLock(); + } + + public Lock getWriteLock() { + return this.mReadWriteLock.writeLock(); + } + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + public Editor edit() { + return new Editor(); + } + + @Override + public Map getAll() { + throw new MethodNotYetImplementedException(); + } + + @Override + public boolean getBoolean(final String pKey, final boolean pDefaultValue) { + final String encryptedKey = this.encryptKey(pKey); + final String value = this.mDelegate.getString(encryptedKey, null); + if (value == null) { + return pDefaultValue; + } else { + final String decryptedValue = this.decryptValue(value); + return Boolean.parseBoolean(decryptedValue); + } + } + + @Override + public int getInt(final String pKey, final int pDefaultValue) { + final String encryptedKey = this.encryptKey(pKey); + final String value = this.mDelegate.getString(encryptedKey, null); + if (value == null) { + return pDefaultValue; + } else { + final String decryptedValue = this.decryptValue(value); + return Integer.parseInt(decryptedValue); + } + } + + @Override + public long getLong(final String pKey, final long pDefaultValue) { + final String encryptedKey = this.encryptKey(pKey); + final String value = this.mDelegate.getString(encryptedKey, null); + if (value == null) { + return pDefaultValue; + } else { + final String decryptedValue = this.decryptValue(value); + return Long.parseLong(decryptedValue); + } + } + + @Override + public float getFloat(final String pKey, final float pDefaultValue) { + final String encryptedKey = this.encryptKey(pKey); + final String value = this.mDelegate.getString(encryptedKey, null); + if (value == null) { + return pDefaultValue; + } else { + final String decryptedValue = this.decryptValue(value); + return Float.parseFloat(decryptedValue); + } + } + + @Override + public String getString(final String pKey, final String pDefaultValue) { + final String encryptedKey = this.encryptKey(pKey); + final String value = this.mDelegate.getString(encryptedKey, null); + if (value == null) { + return pDefaultValue; + } else { + final String decryptedValue = this.decryptValue(value); + return decryptedValue; + } + } + + @Override + public boolean contains(final String pKey) { + return this.mDelegate.contains(pKey); + } + + @Override + public void registerOnSharedPreferenceChangeListener(final OnSharedPreferenceChangeListener pOnSharedPreferenceChangeListener) { + this.mDelegate.registerOnSharedPreferenceChangeListener(pOnSharedPreferenceChangeListener); + } + + @Override + public void unregisterOnSharedPreferenceChangeListener(final OnSharedPreferenceChangeListener pOnSharedPreferenceChangeListener) { + this.mDelegate.unregisterOnSharedPreferenceChangeListener(pOnSharedPreferenceChangeListener); + } + + @Override + public Set getStringSet(final String pKey, final Set pStringSet) { + throw new MethodNotYetImplementedException(); + } + + // =========================================================== + // Methods + // =========================================================== + + protected String encryptKey(final String pKey) { + if (this.mEncryptKeys) { + return this.encrypt(pKey); + } else { + return pKey; + } + } + + protected String encryptValue(final String pValue) { + if (this.mEncryptValues) { + return this.encrypt(pValue); + } else { + return pValue; + } + } + + protected String decryptKey(final String pKey) { + if (this.mEncryptKeys) { + return this.decrypt(pKey); + } else { + return pKey; + } + } + + protected String decryptValue(final String pValue) { + if (this.mEncryptValues) { + return this.decrypt(pValue); + } else { + return pValue; + } + } + + protected IvParameterSpec getIvParameterSpec() { + final int blockSize = this.mEncryptCipher.getBlockSize(); + final byte[] iv = new byte[blockSize]; + System.arraycopy("abcdefghijklmnopqrstuvwxzyABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".getBytes(), 0, iv, 0, blockSize); + return new IvParameterSpec(iv); + } + + protected SecretKeySpec getSecretKeySpec(final String pKey) throws UnsupportedEncodingException, NoSuchAlgorithmException { + final byte[] keyBytes = this.createKeyBytes(pKey); + return new SecretKeySpec(keyBytes, SecureSharedPreferences.CIPHER_TRANSFORMATION); + } + + protected byte[] createKeyBytes(final String pKey) throws UnsupportedEncodingException, NoSuchAlgorithmException { + final MessageDigest md = MessageDigest.getInstance(SecureSharedPreferences.KEY_HASH_TRANSFORMATION); + md.reset(); + final byte[] keyBytes = md.digest(pKey.getBytes(SecureSharedPreferences.CHARSET)); + return keyBytes; + } + + protected String encrypt(final String pPlainText) throws SecureSharedPreferencesException { + byte[] secureValue; + try { + secureValue = SecureSharedPreferences.crypt(this.mEncryptCipher, pPlainText.getBytes(SecureSharedPreferences.CHARSET)); + } catch (final UnsupportedEncodingException e) { + throw new SecureSharedPreferencesException(e); + } + final String secureValueEncoded = Base64.encodeToString(secureValue, Base64.NO_WRAP); + return secureValueEncoded; + } + + protected String decrypt(final String pCipherText) { + final byte[] securedValue = Base64.decode(pCipherText, Base64.NO_WRAP); + final byte[] pValue = SecureSharedPreferences.crypt(this.mDecryptCipher, securedValue); + try { + return new String(pValue, SecureSharedPreferences.CHARSET); + } catch (final UnsupportedEncodingException e) { + throw new SecureSharedPreferencesException(e); + } + } + + protected static byte[] crypt(final Cipher pCipher, final byte[] pBytes) throws SecureSharedPreferencesException { + try { + return pCipher.doFinal(pBytes); + } catch (final Exception e) { + throw new SecureSharedPreferencesException(e); + } + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== + + public class Editor implements SharedPreferences.Editor { + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + protected final SharedPreferences.Editor mDelegate; + + // =========================================================== + // Constructors + // =========================================================== + + public Editor() { + this.mDelegate = SecureSharedPreferences.this.mDelegate.edit(); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + public Editor putBoolean(final String pKey, final boolean pValue) { + final String encryptedKey = SecureSharedPreferences.this.encryptKey(pKey); + final String encryptedValue = SecureSharedPreferences.this.encryptValue(Boolean.toString(pValue)); + this.mDelegate.putString(encryptedKey, encryptedValue); + return this; + } + + @Override + public Editor putInt(final String pKey, final int pValue) { + final String encryptedKey = SecureSharedPreferences.this.encrypt(pKey); + final String encryptValue = SecureSharedPreferences.this.encryptValue(Integer.toString(pValue)); + this.mDelegate.putString(encryptedKey, encryptValue); + return this; + } + + @Override + public Editor putLong(final String pKey, final long pValue) { + final String encryptedKey = SecureSharedPreferences.this.encrypt(pKey); + final String encryptValue = SecureSharedPreferences.this.encryptValue(Long.toString(pValue)); + this.mDelegate.putString(encryptedKey, encryptValue); + return this; + } + + @Override + public Editor putFloat(final String pKey, final float pValue) { + final String encryptedKey = SecureSharedPreferences.this.encrypt(pKey); + final String encryptedVaue = SecureSharedPreferences.this.encryptValue(Float.toString(pValue)); + this.mDelegate.putString(encryptedKey, encryptedVaue); + return this; + } + + @Override + public Editor putString(final String pKey, final String pValue) { + final String encryptedKey = SecureSharedPreferences.this.encrypt(pKey); + final String encryptValue = SecureSharedPreferences.this.encryptValue(pValue); + this.mDelegate.putString(encryptedKey, encryptValue); + return this; + } + + @Override + public Editor putStringSet(final String pKey, final Set pStringSet) { + throw new MethodNotYetImplementedException(); + } + + @Override + public Editor remove(final String pKey) { + final String encryptedKey = SecureSharedPreferences.this.encrypt(pKey); + this.mDelegate.remove(encryptedKey); + return this; + } + + @Override + public Editor clear() { + this.mDelegate.clear(); + return this; + } + + @Override + public boolean commit() { + return this.mDelegate.commit(); + } + + @TargetApi(Build.VERSION_CODES.GINGERBREAD) + @Override + public void apply() { + this.mDelegate.apply(); + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== + } +} \ No newline at end of file diff --git a/src/org/andengine/util/preferences/SharedPreferencesCompat.java b/src/org/andengine/util/preferences/SharedPreferencesCompat.java new file mode 100644 index 000000000..bb387f134 --- /dev/null +++ b/src/org/andengine/util/preferences/SharedPreferencesCompat.java @@ -0,0 +1,70 @@ +package org.andengine.util.preferences; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; + +import android.content.SharedPreferences.Editor; + +/** + * (c) 2013 Nicolas Gramlich + * + * @author Nicolas Gramlich + * @since 20:41:56 - 07.04.2013 + */ +public class SharedPreferencesCompat { + // =========================================================== + // Constants + // =========================================================== + + private static final Method WORKAROUND_APPLY_METHOD; + + static { + Method applyMethod; + try { + final Class cls = Editor.class; + applyMethod = cls.getMethod("apply"); + } catch (final NoSuchMethodException unused) { + applyMethod = null; + } + + WORKAROUND_APPLY_METHOD = applyMethod; + } + + // =========================================================== + // Fields + // =========================================================== + + // =========================================================== + // Constructors + // =========================================================== + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + public static void apply(final Editor pEditor) { + if (SharedPreferencesCompat.WORKAROUND_APPLY_METHOD != null) { + try { + SharedPreferencesCompat.WORKAROUND_APPLY_METHOD.invoke(pEditor); + return; + } catch (final InvocationTargetException e) { + /* Nothing. */ + } catch (final IllegalAccessException e) { + /* Nothing. */ + } + } + pEditor.commit(); + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== +} diff --git a/src/org/andengine/util/preferences/SimplePreferences.java b/src/org/andengine/util/preferences/SimplePreferences.java index 6ab383ec6..4c0cc7bde 100644 --- a/src/org/andengine/util/preferences/SimplePreferences.java +++ b/src/org/andengine/util/preferences/SimplePreferences.java @@ -7,9 +7,9 @@ import android.preference.PreferenceManager; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 18:55:12 - 02.08.2010 */ @@ -30,14 +30,14 @@ public class SimplePreferences { // =========================================================== public static SharedPreferences getInstance(final Context pContext) { - if(SimplePreferences.INSTANCE == null) { + if (SimplePreferences.INSTANCE == null) { SimplePreferences.INSTANCE = PreferenceManager.getDefaultSharedPreferences(pContext); } return SimplePreferences.INSTANCE; } public static Editor getEditorInstance(final Context pContext) { - if(SimplePreferences.EDITORINSTANCE == null) { + if (SimplePreferences.EDITORINSTANCE == null) { SimplePreferences.EDITORINSTANCE = SimplePreferences.getInstance(pContext).edit(); } return SimplePreferences.EDITORINSTANCE; diff --git a/src/org/andengine/util/preferences/exception/SecureSharedPreferencesException.java b/src/org/andengine/util/preferences/exception/SecureSharedPreferencesException.java new file mode 100644 index 000000000..7aa792176 --- /dev/null +++ b/src/org/andengine/util/preferences/exception/SecureSharedPreferencesException.java @@ -0,0 +1,57 @@ +package org.andengine.util.preferences.exception; + +import org.andengine.util.exception.AndEngineRuntimeException; + +/** + * (c) 2013 Nicolas Gramlich + * + * @author Nicolas Gramlich + * @since 20:09:38 - 13.04.2013 + */ +public class SecureSharedPreferencesException extends AndEngineRuntimeException { + // =========================================================== + // Constants + // =========================================================== + + private static final long serialVersionUID = 5683854473467471982L; + + // =========================================================== + // Fields + // =========================================================== + + // =========================================================== + // Constructors + // =========================================================== + + public SecureSharedPreferencesException() { + + } + + public SecureSharedPreferencesException(final String pMessage) { + super(pMessage); + } + + public SecureSharedPreferencesException(final Throwable pThrowable) { + super(pThrowable); + } + + public SecureSharedPreferencesException(final String pMessage, final Throwable pThrowable) { + super(pMessage, pThrowable); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== +} diff --git a/src/org/andengine/util/progress/IProgressListener.java b/src/org/andengine/util/progress/IProgressListener.java index 8dc3c4952..f16d01b50 100644 --- a/src/org/andengine/util/progress/IProgressListener.java +++ b/src/org/andengine/util/progress/IProgressListener.java @@ -2,9 +2,9 @@ /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 18:07:35 - 09.07.2009 */ diff --git a/src/org/andengine/util/progress/ProgressCallable.java b/src/org/andengine/util/progress/ProgressCallable.java index 4c51c5775..edd9dd279 100644 --- a/src/org/andengine/util/progress/ProgressCallable.java +++ b/src/org/andengine/util/progress/ProgressCallable.java @@ -2,9 +2,9 @@ /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 20:52:44 - 03.01.2010 */ diff --git a/src/org/andengine/util/progress/ProgressMonitor.java b/src/org/andengine/util/progress/ProgressMonitor.java index 2d84cc578..64ea5b1e4 100644 --- a/src/org/andengine/util/progress/ProgressMonitor.java +++ b/src/org/andengine/util/progress/ProgressMonitor.java @@ -8,7 +8,7 @@ /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 18:07:35 - 09.07.2009 */ @@ -47,7 +47,7 @@ public ProgressMonitor(final IProgressListener pProgressListener) { @Override public void onProgressChanged(final int pProgress) { final int progressListenerCount = this.mProgressListeners.size(); - for(int i = 0; i < progressListenerCount; i++) { + for (int i = 0; i < progressListenerCount; i++) { this.mProgressListeners.get(i).onProgressChanged(pProgress); } } diff --git a/src/org/andengine/util/system/CPUUsage.java b/src/org/andengine/util/system/CPUUsage.java index d153f51da..d8c826862 100644 --- a/src/org/andengine/util/system/CPUUsage.java +++ b/src/org/andengine/util/system/CPUUsage.java @@ -10,7 +10,7 @@ import org.andengine.util.debug.Debug; /** - * (c) Zynga 2011 + * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 21:48:14 - 22.10.2011 diff --git a/src/org/andengine/util/system/SystemUtils.java b/src/org/andengine/util/system/SystemUtils.java index d50d38ff0..b35ef99c0 100644 --- a/src/org/andengine/util/system/SystemUtils.java +++ b/src/org/andengine/util/system/SystemUtils.java @@ -7,22 +7,29 @@ import java.util.regex.MatchResult; import org.andengine.util.StreamUtils; -import org.andengine.util.debug.Debug; +import org.andengine.util.adt.data.constants.DataConstants; +import org.andengine.util.exception.AndEngineException; +import org.andengine.util.exception.MethodNotFoundException; import android.content.Context; +import android.content.pm.ApplicationInfo; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; +import android.graphics.Color; import android.os.Build; +import android.os.Bundle; +import android.os.Debug; +import android.os.Debug.MemoryInfo; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 15:50:31 - 14.07.2010 */ -public class SystemUtils { +public final class SystemUtils { // =========================================================== // Constants // =========================================================== @@ -41,10 +48,16 @@ public class SystemUtils { // Fields // =========================================================== + private static MemoryInfo sMemoryInfo; + // =========================================================== // Constructors // =========================================================== + private SystemUtils() { + + } + // =========================================================== // Getter & Setter // =========================================================== @@ -57,15 +70,81 @@ public class SystemUtils { // Methods // =========================================================== - public static boolean isGoogleTV(final Context pContext) { + public static boolean isEmulator() { + if (Build.PRODUCT != null && Build.PRODUCT.equals("google_sdk")) { + return true; + } else if (Build.MODEL != null && Build.MODEL.equals("google_sdk")) { + return true; + } else if (Build.BRAND != null && Build.BRAND.startsWith("generic")){ + return true; + } else if (Build.DEVICE != null && Build.DEVICE.startsWith("generic")) { + return true; + } else { + return false; + } + } + + public static MemoryInfo getMemoryInfo() { + /* Lazy allocation. */ + if (SystemUtils.sMemoryInfo == null) { + SystemUtils.sMemoryInfo = new MemoryInfo(); + } + + Debug.getMemoryInfo(SystemUtils.sMemoryInfo); + + return SystemUtils.sMemoryInfo; + } + + public static boolean isGoogleTV(final Context pContext) throws SystemUtilsException { return SystemUtils.hasSystemFeature(pContext, "com.google.android.tv"); } - public static int getPackageVersionCode(final Context pContext) { + public static boolean isGoogleTV(final Context pContext, final boolean pDefault) { + try { + return SystemUtils.isGoogleTV(pContext); + } catch (final SystemUtilsException e) { + return pDefault; + } + } + + public static boolean hasCamera(final Context pContext) throws SystemUtilsException { + return SystemUtils.hasSystemFeature(pContext, PackageManager.FEATURE_CAMERA); + } + + public static boolean hasCamera(final Context pContext, final boolean pDefault) { + try { + return SystemUtils.hasCamera(pContext); + } catch (final SystemUtilsException e) { + return pDefault; + } + } + + public static boolean isNDKSupported(final Context pContext, final boolean pDefault) { + try { + if (SystemUtils.isGoogleTV(pContext)) { + if (SystemUtils.isAndroidVersionOrHigher(Build.VERSION_CODES.JELLY_BEAN_MR1)) { + return true; + } else { + return false; + } + } else { + return true; + } + } catch (final SystemUtilsException e) { + return pDefault; + } + } + + public static String getApplicationLabel(final Context pContext) throws SystemUtilsException { + final int labelResID = SystemUtils.getApplicationInfo(pContext).labelRes; + return pContext.getString(labelResID); + } + + public static int getPackageVersionCode(final Context pContext) throws SystemUtilsException { return SystemUtils.getPackageInfo(pContext).versionCode; } - public static String getPackageVersionName(final Context pContext) { + public static String getPackageVersionName(final Context pContext) throws SystemUtilsException { return SystemUtils.getPackageInfo(pContext).versionName; } @@ -73,26 +152,174 @@ public static String getPackageName(final Context pContext) { return pContext.getPackageName(); } - public static String getApkFilePath(final Context pContext) throws NameNotFoundException { - final PackageManager packMgmr = pContext.getPackageManager(); - return packMgmr.getApplicationInfo(SystemUtils.getPackageName(pContext), 0).sourceDir; + public static String getApkFilePath(final Context pContext) throws SystemUtilsException { + return SystemUtils.getApplicationInfo(pContext, 0).sourceDir; } - private static PackageInfo getPackageInfo(final Context pContext) { + public static ApplicationInfo getApplicationInfo(final Context pContext) throws SystemUtilsException { + return SystemUtils.getApplicationInfo(pContext, 0); + } + + public static ApplicationInfo getApplicationInfo(final Context pContext, final int pFlags) throws SystemUtilsException { try { - return pContext.getPackageManager().getPackageInfo(pContext.getPackageName(), 0); + return pContext.getPackageManager().getApplicationInfo(pContext.getPackageName(), pFlags); } catch (final NameNotFoundException e) { - Debug.e(e); - return null; + throw new SystemUtilsException(e); } } - public static boolean hasSystemFeature(final Context pContext, final String pFeature) { + public static PackageInfo getPackageInfo(final Context pContext) throws SystemUtilsException { + return SystemUtils.getPackageInfo(pContext, 0); + } + + public static PackageInfo getPackageInfo(final Context pContext, final int pFlags) throws SystemUtilsException { try { - final Method PackageManager_hasSystemFeatures = PackageManager.class.getMethod("hasSystemFeature", new Class[] { String.class }); - return (PackageManager_hasSystemFeatures == null) ? false : (Boolean) PackageManager_hasSystemFeatures.invoke(pContext.getPackageManager(), pFeature); + return pContext.getPackageManager().getPackageInfo(pContext.getPackageName(), pFlags); + } catch (final NameNotFoundException e) { + throw new SystemUtilsException(e); + } + } + + public static int getTargetSDKVersion(final Context pContext) throws SystemUtilsException { + return SystemUtils.getApplicationInfo(pContext).targetSdkVersion; + } + + public static boolean hasSystemFeature(final Context pContext, final String pFeature) throws SystemUtilsException { + final PackageManager packageManager = pContext.getPackageManager(); + try { + try { + return packageManager.hasSystemFeature(pFeature); + } catch (final Throwable t) { + final Method PackageManager_hasSystemFeatures = PackageManager.class.getMethod("hasSystemFeature", String.class); + if (PackageManager_hasSystemFeatures == null) { + throw new SystemUtilsException(new MethodNotFoundException(PackageManager.class.getSimpleName() + ".hasSystemFeature(String)")); + } else { + final boolean result = (Boolean) PackageManager_hasSystemFeatures.invoke(packageManager, pFeature); + return result; + } + } } catch (final Throwable t) { - return false; + throw new SystemUtilsException(t); + } + } + + public static boolean hasSystemFeature(final Context pContext, final String pFeature, final boolean pDefault) { + try { + return SystemUtils.hasSystemFeature(pContext, pFeature); + } catch (final SystemUtilsException e) { + return pDefault; + } + } + + public static boolean optMetaDataBoolean(final Context pContext, final String pKey) throws SystemUtilsException { + final Bundle bundle = SystemUtils.getMetaData(pContext); + return bundle.getBoolean(pKey); + } + + public static boolean optMetaDataBoolean(final Context pContext, final String pKey, final boolean pDefaultValue) throws SystemUtilsException { + final Bundle bundle = SystemUtils.getMetaData(pContext); + return bundle.getBoolean(pKey, pDefaultValue); + } + + public static int optMetaDataInt(final Context pContext, final String pKey) throws SystemUtilsException { + final Bundle bundle = SystemUtils.getMetaData(pContext); + return bundle.getInt(pKey); + } + + public static int optMetaDataInt(final Context pContext, final String pKey, final int pDefaultValue) throws SystemUtilsException { + final Bundle bundle = SystemUtils.getMetaData(pContext); + return bundle.getInt(pKey, pDefaultValue); + } + + public static float optMetaDataFloat(final Context pContext, final String pKey) throws SystemUtilsException { + final Bundle bundle = SystemUtils.getMetaData(pContext); + return bundle.getFloat(pKey); + } + + public static float optMetaDataFloat(final Context pContext, final String pKey, final float pDefaultValue) throws SystemUtilsException { + final Bundle bundle = SystemUtils.getMetaData(pContext); + return bundle.getFloat(pKey, pDefaultValue); + } + + public static String optMetaDataString(final Context pContext, final String pKey) throws SystemUtilsException { + final Bundle bundle = SystemUtils.getMetaData(pContext); + return bundle.getString(pKey); + } + + public static String optMetaDataString(final Context pContext, final String pKey, final String pDefaultValue) throws SystemUtilsException { + final Bundle bundle = SystemUtils.getMetaData(pContext); + if (bundle.containsKey(pKey)) { + return bundle.getString(pKey); + } else { + return pDefaultValue; + } + } + + public static int optMetaDataColor(final Context pContext, final String pKey) throws SystemUtilsException { + final Bundle bundle = SystemUtils.getMetaData(pContext); + return Color.parseColor(bundle.getString(pKey)); + } + + public static int optMetaDataColor(final Context pContext, final String pKey, final int pDefaultValue) throws SystemUtilsException { + final Bundle bundle = SystemUtils.getMetaData(pContext); + if (bundle.containsKey(pKey)) { + return Color.parseColor(bundle.getString(pKey)); + } else { + return pDefaultValue; + } + } + + public static boolean getMetaDataBoolean(final Context pContext, final String pKey) throws SystemUtilsException { + final Bundle bundle = SystemUtils.getMetaData(pContext); + if (bundle.containsKey(pKey)) { + return bundle.getBoolean(pKey); + } else { + throw new SystemUtilsException(new IllegalArgumentException("Could not find meta data with key: '" + pKey + "'.")); + } + } + + public static int getMetaDataInt(final Context pContext, final String pKey) throws SystemUtilsException { + final Bundle bundle = SystemUtils.getMetaData(pContext); + if (bundle.containsKey(pKey)) { + return bundle.getInt(pKey); + } else { + throw new SystemUtilsException(new IllegalArgumentException("Could not find meta data with key: '" + pKey + "'.")); + } + } + + public static float getMetaDataFloat(final Context pContext, final String pKey) throws SystemUtilsException { + final Bundle bundle = SystemUtils.getMetaData(pContext); + if (bundle.containsKey(pKey)) { + return bundle.getFloat(pKey); + } else { + throw new SystemUtilsException(new IllegalArgumentException("Could not find meta data with key: '" + pKey + "'.")); + } + } + + public static String getMetaDataString(final Context pContext, final String pKey) throws SystemUtilsException { + final Bundle bundle = SystemUtils.getMetaData(pContext); + if (bundle.containsKey(pKey)) { + return bundle.getString(pKey); + } else { + throw new SystemUtilsException(new IllegalArgumentException("Could not find meta data with key: '" + pKey + "'.")); + } + } + + public static int getMetaDataColor(final Context pContext, final String pKey) throws SystemUtilsException { + final Bundle bundle = SystemUtils.getMetaData(pContext); + if (bundle.containsKey(pKey)) { + return Color.parseColor(bundle.getString(pKey)); + } else { + throw new SystemUtilsException(new IllegalArgumentException("Could not find meta data with key: '" + pKey + "'.")); + } + } + + public static Bundle getMetaData(final Context pContext) throws SystemUtilsException { + try { + final ApplicationInfo applicationInfo = SystemUtils.getApplicationInfo(pContext, PackageManager.GET_META_DATA); + return applicationInfo.metaData; + } catch (final Throwable t) { + throw new SystemUtilsException(t); } } @@ -122,7 +349,7 @@ public static float getCPUBogoMips() throws SystemUtilsException { final MatchResult matchResult = SystemUtils.matchSystemFile("/proc/cpuinfo", SystemUtils.BOGOMIPS_PATTERN, 1000); try { - if(matchResult.groupCount() > 0) { + if (matchResult.groupCount() > 0) { return Float.parseFloat(matchResult.group(1)); } else { throw new SystemUtilsException(); @@ -136,12 +363,12 @@ public static float getCPUBogoMips() throws SystemUtilsException { * @return in kiloBytes. * @throws SystemUtilsException */ - public static int getMemoryTotal() throws SystemUtilsException { + public static long getSystemMemorySize() throws SystemUtilsException { final MatchResult matchResult = SystemUtils.matchSystemFile("/proc/meminfo", SystemUtils.MEMTOTAL_PATTERN, 1000); try { - if(matchResult.groupCount() > 0) { - return Integer.parseInt(matchResult.group(1)); + if (matchResult.groupCount() > 0) { + return Long.parseLong(matchResult.group(1)); } else { throw new SystemUtilsException(); } @@ -154,12 +381,12 @@ public static int getMemoryTotal() throws SystemUtilsException { * @return in kiloBytes. * @throws SystemUtilsException */ - public static int getMemoryFree() throws SystemUtilsException { + public static long getSystemMemoryFreeSize() throws SystemUtilsException { final MatchResult matchResult = SystemUtils.matchSystemFile("/proc/meminfo", SystemUtils.MEMFREE_PATTERN, 1000); try { - if(matchResult.groupCount() > 0) { - return Integer.parseInt(matchResult.group(1)); + if (matchResult.groupCount() > 0) { + return Long.parseLong(matchResult.group(1)); } else { throw new SystemUtilsException(); } @@ -172,52 +399,52 @@ public static int getMemoryFree() throws SystemUtilsException { * @return in kiloHertz. * @throws SystemUtilsException */ - public static int getCPUFrequencyCurrent() throws SystemUtilsException { - return SystemUtils.readSystemFileAsInt("/sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq"); + public static long getCPUFrequencyCurrent() throws SystemUtilsException { + return SystemUtils.readSystemFileAsLong("/sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq"); } /** * @return in kiloHertz. * @throws SystemUtilsException */ - public static int getCPUFrequencyMin() throws SystemUtilsException { - return SystemUtils.readSystemFileAsInt("/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_min_freq"); + public static long getCPUFrequencyMin() throws SystemUtilsException { + return SystemUtils.readSystemFileAsLong("/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_min_freq"); } /** * @return in kiloHertz. * @throws SystemUtilsException */ - public static int getCPUFrequencyMax() throws SystemUtilsException { - return SystemUtils.readSystemFileAsInt("/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq"); + public static long getCPUFrequencyMax() throws SystemUtilsException { + return SystemUtils.readSystemFileAsLong("/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq"); } /** * @return in kiloHertz. * @throws SystemUtilsException */ - public static int getCPUFrequencyMinScaling() throws SystemUtilsException { - return SystemUtils.readSystemFileAsInt("/sys/devices/system/cpu/cpu0/cpufreq/scaling_min_freq"); + public static long getCPUFrequencyMinScaling() throws SystemUtilsException { + return SystemUtils.readSystemFileAsLong("/sys/devices/system/cpu/cpu0/cpufreq/scaling_min_freq"); } /** * @return in kiloHertz. * @throws SystemUtilsException */ - public static int getCPUFrequencyMaxScaling() throws SystemUtilsException { - return SystemUtils.readSystemFileAsInt("/sys/devices/system/cpu/cpu0/cpufreq/scaling_max_freq"); + public static long getCPUFrequencyMaxScaling() throws SystemUtilsException { + return SystemUtils.readSystemFileAsLong("/sys/devices/system/cpu/cpu0/cpufreq/scaling_max_freq"); } private static MatchResult matchSystemFile(final String pSystemFile, final String pPattern, final int pHorizon) throws SystemUtilsException { InputStream in = null; try { - final Process process = new ProcessBuilder(new String[] { "/system/bin/cat", pSystemFile }).start(); + final Process process = new ProcessBuilder(new String[] {"/system/bin/cat", pSystemFile}).start(); in = process.getInputStream(); final Scanner scanner = new Scanner(in); final boolean matchFound = scanner.findWithinHorizon(pPattern, pHorizon) != null; - if(matchFound) { + if (matchFound) { return scanner.match(); } else { throw new SystemUtilsException(); @@ -229,14 +456,14 @@ private static MatchResult matchSystemFile(final String pSystemFile, final Strin } } - private static int readSystemFileAsInt(final String pSystemFile) throws SystemUtilsException { + private static long readSystemFileAsLong(final String pSystemFile) throws SystemUtilsException { InputStream in = null; try { - final Process process = new ProcessBuilder(new String[] { "/system/bin/cat", pSystemFile }).start(); + final Process process = new ProcessBuilder(new String[] {"/system/bin/cat", pSystemFile}).start(); in = process.getInputStream(); final String content = StreamUtils.readFully(in); - return Integer.parseInt(content); + return Long.parseLong(content); } catch (final IOException e) { throw new SystemUtilsException(e); } catch (final NumberFormatException e) { @@ -246,11 +473,71 @@ private static int readSystemFileAsInt(final String pSystemFile) throws SystemUt } } + public static long getNativeHeapSize() { + return Debug.getNativeHeapSize() / DataConstants.BYTES_PER_KILOBYTE; + } + + public static long getNativeHeapFreeSize() { + return Debug.getNativeHeapFreeSize() / DataConstants.BYTES_PER_KILOBYTE; + } + + public static long getNativeHeapAllocatedSize() { + return Debug.getNativeHeapAllocatedSize() / DataConstants.BYTES_PER_KILOBYTE; + } + + public static long getDalvikHeapSize() { + return Runtime.getRuntime().totalMemory() / DataConstants.BYTES_PER_KILOBYTE; + } + + public static long getDalvikHeapFreeSize() { + return Runtime.getRuntime().freeMemory() / DataConstants.BYTES_PER_KILOBYTE; + } + + public static long getDalvikHeapAllocatedSize() { + return SystemUtils.getDalvikHeapSize() - SystemUtils.getDalvikHeapFreeSize(); + } + + public static long getNativeProportionalSetSize() { + return SystemUtils.getMemoryInfo().nativePss; + } + + public static long getNativePrivateDirtyPages() { + return SystemUtils.getMemoryInfo().nativePrivateDirty; + } + + public static long getNativeSharedDirtyPages() { + return SystemUtils.getMemoryInfo().nativeSharedDirty; + } + + public static long getDalvikProportionalSetSize() { + return SystemUtils.getMemoryInfo().dalvikPss; + } + + public static long getDalvikPrivateDirtyPages() { + return SystemUtils.getMemoryInfo().dalvikPrivateDirty; + } + + public static long getDalvikSharedDirtyPages() { + return SystemUtils.getMemoryInfo().dalvikSharedDirty; + } + + public static long getOtherProportionalSetSize() { + return SystemUtils.getMemoryInfo().otherPss; + } + + public static long getOtherPrivateDirtyPages() { + return SystemUtils.getMemoryInfo().otherPrivateDirty; + } + + public static long getOtherSharedDirtyPages() { + return SystemUtils.getMemoryInfo().otherSharedDirty; + } + // =========================================================== // Inner and Anonymous Classes // =========================================================== - public static class SystemUtilsException extends Exception { + public static class SystemUtilsException extends AndEngineException { // =========================================================== // Constants // =========================================================== @@ -258,7 +545,7 @@ public static class SystemUtilsException extends Exception { private static final long serialVersionUID = -7256483361095147596L; // =========================================================== - // Methods + // Constructors // =========================================================== public SystemUtilsException() { diff --git a/src/org/andengine/util/texturepack/TexturePack.java b/src/org/andengine/util/texturepack/TexturePack.java index 42a27cdfd..3be18961f 100644 --- a/src/org/andengine/util/texturepack/TexturePack.java +++ b/src/org/andengine/util/texturepack/TexturePack.java @@ -3,7 +3,7 @@ import org.andengine.opengl.texture.ITexture; /** - * (c) Zynga 2011 + * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 23:23:47 - 30.07.2011 diff --git a/src/org/andengine/util/texturepack/TexturePackLibrary.java b/src/org/andengine/util/texturepack/TexturePackLibrary.java index 70ed7003c..249b09709 100644 --- a/src/org/andengine/util/texturepack/TexturePackLibrary.java +++ b/src/org/andengine/util/texturepack/TexturePackLibrary.java @@ -3,7 +3,7 @@ import java.util.HashMap; /** - * (c) Zynga 2012 + * (c) 2012 Zynga Inc. * * @author Nicolas Gramlich * @since 17:29:37 - 03.05.2012 diff --git a/src/org/andengine/util/texturepack/TexturePackLoader.java b/src/org/andengine/util/texturepack/TexturePackLoader.java index 3c33c667f..bdeae70c4 100644 --- a/src/org/andengine/util/texturepack/TexturePackLoader.java +++ b/src/org/andengine/util/texturepack/TexturePackLoader.java @@ -18,7 +18,7 @@ import android.content.res.AssetManager; /** - * (c) Zynga 2011 + * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 17:05:15 - 29.07.2011 @@ -65,7 +65,7 @@ public TexturePack loadFromAsset(final String pAssetPath, final String pAssetBas } public TexturePack load(final InputStream pInputStream, final String pAssetBasePath) throws TexturePackParseException { - try{ + try { final SAXParserFactory spf = SAXParserFactory.newInstance(); final SAXParser sp = spf.newSAXParser(); diff --git a/src/org/andengine/util/texturepack/TexturePackParser.java b/src/org/andengine/util/texturepack/TexturePackParser.java index bfb105264..a8e53c4f5 100644 --- a/src/org/andengine/util/texturepack/TexturePackParser.java +++ b/src/org/andengine/util/texturepack/TexturePackParser.java @@ -11,13 +11,14 @@ import org.andengine.opengl.texture.TextureOptions; import org.andengine.opengl.texture.bitmap.BitmapTexture; import org.andengine.opengl.texture.bitmap.BitmapTextureFormat; +import org.andengine.opengl.texture.compressed.etc1.ETC1Texture; import org.andengine.opengl.texture.compressed.pvr.PVRCCZTexture; import org.andengine.opengl.texture.compressed.pvr.PVRGZTexture; import org.andengine.opengl.texture.compressed.pvr.PVRTexture; import org.andengine.opengl.texture.compressed.pvr.PVRTexture.PVRTextureFormat; import org.andengine.opengl.texture.compressed.pvr.pixelbufferstrategy.SmartPVRTexturePixelBufferStrategy; import org.andengine.util.SAXUtils; -import org.andengine.util.adt.DataConstants; +import org.andengine.util.adt.data.constants.DataConstants; import org.andengine.util.adt.io.in.IInputStreamOpener; import org.andengine.util.texturepack.exception.TexturePackParseException; import org.xml.sax.Attributes; @@ -27,7 +28,7 @@ import android.content.res.AssetManager; /** - * (c) Zynga 2011 + * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 17:19:26 - 29.07.2011 @@ -63,6 +64,7 @@ public class TexturePackParser extends DefaultHandler { private static final String TAG_TEXTURE_ATTRIBUTE_TYPE_VALUE_PVRGZ = "pvrgz"; private static final String TAG_TEXTURE_ATTRIBUTE_TYPE_VALUE_PVR = "pvr"; private static final String TAG_TEXTURE_ATTRIBUTE_TYPE_VALUE_BITMAP = "bitmap"; + private static final String TAG_TEXTURE_ATTRIBUTE_TYPE_VALUE_ETC1 = "etc1"; private static final String TAG_TEXTURE_ATTRIBUTE_PIXELFORMAT = "pixelformat"; private static final String TAG_TEXTUREREGION = "textureregion"; @@ -116,19 +118,19 @@ public TexturePack getTexturePack() { @Override public void startElement(final String pUri, final String pLocalName, final String pQualifiedName, final Attributes pAttributes) throws SAXException { - if(pLocalName.equals(TexturePackParser.TAG_TEXTURE)) { + if (pLocalName.equals(TexturePackParser.TAG_TEXTURE)) { this.mVersion = SAXUtils.getIntAttributeOrThrow(pAttributes, TexturePackParser.TAG_TEXTURE_ATTRIBUTE_VERSION); this.mTexture = this.parseTexture(pAttributes); this.mTextureRegionLibrary = new TexturePackTextureRegionLibrary(10); this.mTexturePack = new TexturePack(this.mTexture, this.mTextureRegionLibrary); - } else if(pLocalName.equals(TexturePackParser.TAG_TEXTUREREGION)) { + } else if (pLocalName.equals(TexturePackParser.TAG_TEXTUREREGION)) { final int id = SAXUtils.getIntAttributeOrThrow(pAttributes, TexturePackParser.TAG_TEXTUREREGION_ATTRIBUTE_ID); final int x = SAXUtils.getIntAttributeOrThrow(pAttributes, TexturePackParser.TAG_TEXTUREREGION_ATTRIBUTE_X); final int y = SAXUtils.getIntAttributeOrThrow(pAttributes, TexturePackParser.TAG_TEXTUREREGION_ATTRIBUTE_Y); final int width = SAXUtils.getIntAttributeOrThrow(pAttributes, TexturePackParser.TAG_TEXTUREREGION_ATTRIBUTE_WIDTH); final int height = SAXUtils.getIntAttributeOrThrow(pAttributes, TexturePackParser.TAG_TEXTUREREGION_ATTRIBUTE_HEIGHT); - + final String source = SAXUtils.getAttributeOrThrow(pAttributes, TAG_TEXTUREREGION_ATTRIBUTE_SOURCE); // TODO Not sure how trimming could be transparently supported... @@ -148,7 +150,7 @@ public void startElement(final String pUri, final String pLocalName, final Strin // =========================================================== // Methods // =========================================================== - + protected InputStream onGetInputStream(final String pFilename) throws IOException { return this.mAssetManager.open(this.mAssetBasePath + pFilename); } @@ -156,7 +158,7 @@ protected InputStream onGetInputStream(final String pFilename) throws IOExceptio private ITexture parseTexture(final Attributes pAttributes) throws TexturePackParseException { final String file = SAXUtils.getAttributeOrThrow(pAttributes, TexturePackParser.TAG_TEXTURE_ATTRIBUTE_FILE); - if(this.mTextureManager.hasMappedTexture(file)) { + if (this.mTextureManager.hasMappedTexture(file)) { return this.mTextureManager.getMappedTexture(file); } @@ -166,7 +168,7 @@ private ITexture parseTexture(final Attributes pAttributes) throws TexturePackPa final TextureOptions textureOptions = this.parseTextureOptions(pAttributes); final ITexture texture; - if(type.equals(TexturePackParser.TAG_TEXTURE_ATTRIBUTE_TYPE_VALUE_BITMAP)) { + if (type.equals(TexturePackParser.TAG_TEXTURE_ATTRIBUTE_TYPE_VALUE_BITMAP)) { try { texture = new BitmapTexture(this.mTextureManager, new IInputStreamOpener() { @Override @@ -177,7 +179,7 @@ public InputStream open() throws IOException { } catch (final IOException e) { throw new TexturePackParseException(e); } - } else if(type.equals(TexturePackParser.TAG_TEXTURE_ATTRIBUTE_TYPE_VALUE_PVR)) { + } else if (type.equals(TexturePackParser.TAG_TEXTURE_ATTRIBUTE_TYPE_VALUE_PVR)) { try { texture = new PVRTexture(this.mTextureManager, PVRTextureFormat.fromPixelFormat(pixelFormat), new SmartPVRTexturePixelBufferStrategy(DataConstants.BYTES_PER_MEGABYTE / 8), textureOptions) { @Override @@ -188,7 +190,7 @@ protected InputStream onGetInputStream() throws IOException { } catch (final IOException e) { throw new TexturePackParseException(e); } - } else if(type.equals(TexturePackParser.TAG_TEXTURE_ATTRIBUTE_TYPE_VALUE_PVRGZ)) { + } else if (type.equals(TexturePackParser.TAG_TEXTURE_ATTRIBUTE_TYPE_VALUE_PVRGZ)) { try { texture = new PVRGZTexture(this.mTextureManager, PVRTextureFormat.fromPixelFormat(pixelFormat), new SmartPVRTexturePixelBufferStrategy(DataConstants.BYTES_PER_MEGABYTE / 8), textureOptions) { @Override @@ -199,7 +201,7 @@ protected InputStream onGetInputStream() throws IOException { } catch (final IOException e) { throw new TexturePackParseException(e); } - } else if(type.equals(TexturePackParser.TAG_TEXTURE_ATTRIBUTE_TYPE_VALUE_PVRCCZ)) { + } else if (type.equals(TexturePackParser.TAG_TEXTURE_ATTRIBUTE_TYPE_VALUE_PVRCCZ)) { try { texture = new PVRCCZTexture(this.mTextureManager, PVRTextureFormat.fromPixelFormat(pixelFormat), new SmartPVRTexturePixelBufferStrategy(DataConstants.BYTES_PER_MEGABYTE / 8), textureOptions) { @Override @@ -210,6 +212,17 @@ protected InputStream onGetInputStream() throws IOException { } catch (final IOException e) { throw new TexturePackParseException(e); } + } else if (type.equals(TexturePackParser.TAG_TEXTURE_ATTRIBUTE_TYPE_VALUE_ETC1)) { + try { + return new ETC1Texture(this.mTextureManager, textureOptions) { + @Override + protected InputStream getInputStream() throws IOException { + return TexturePackParser.this.onGetInputStream(file); + } + }; + } catch (final IOException e) { + throw new TexturePackParseException(e); + } } else { throw new TexturePackParseException(new IllegalArgumentException("Unsupported pTextureFormat: '" + type + "'.")); } @@ -235,17 +248,17 @@ private TextureOptions parseTextureOptions(final Attributes pAttributes) { private static int parseMinFilter(final Attributes pAttributes) { final String minFilter = SAXUtils.getAttributeOrThrow(pAttributes, TexturePackParser.TAG_TEXTURE_ATTRIBUTE_MINFILTER); - if(minFilter.equals(TexturePackParser.TAG_TEXTURE_ATTRIBUTE_MINFILTER_VALUE_NEAREST)) { + if (minFilter.equals(TexturePackParser.TAG_TEXTURE_ATTRIBUTE_MINFILTER_VALUE_NEAREST)) { return GL10.GL_NEAREST; - } else if(minFilter.equals(TexturePackParser.TAG_TEXTURE_ATTRIBUTE_MINFILTER_VALUE_LINEAR)) { + } else if (minFilter.equals(TexturePackParser.TAG_TEXTURE_ATTRIBUTE_MINFILTER_VALUE_LINEAR)) { return GL10.GL_LINEAR; - } else if(minFilter.equals(TexturePackParser.TAG_TEXTURE_ATTRIBUTE_MINFILTER_VALUE_LINEAR_MIPMAP_LINEAR)) { + } else if (minFilter.equals(TexturePackParser.TAG_TEXTURE_ATTRIBUTE_MINFILTER_VALUE_LINEAR_MIPMAP_LINEAR)) { return GL10.GL_LINEAR_MIPMAP_LINEAR; - } else if(minFilter.equals(TexturePackParser.TAG_TEXTURE_ATTRIBUTE_MINFILTER_VALUE_LINEAR_MIPMAP_NEAREST)) { + } else if (minFilter.equals(TexturePackParser.TAG_TEXTURE_ATTRIBUTE_MINFILTER_VALUE_LINEAR_MIPMAP_NEAREST)) { return GL10.GL_LINEAR_MIPMAP_NEAREST; - } else if(minFilter.equals(TexturePackParser.TAG_TEXTURE_ATTRIBUTE_MINFILTER_VALUE_NEAREST_MIPMAP_LINEAR)) { + } else if (minFilter.equals(TexturePackParser.TAG_TEXTURE_ATTRIBUTE_MINFILTER_VALUE_NEAREST_MIPMAP_LINEAR)) { return GL10.GL_NEAREST_MIPMAP_LINEAR; - } else if(minFilter.equals(TexturePackParser.TAG_TEXTURE_ATTRIBUTE_MINFILTER_VALUE_NEAREST_MIPMAP_NEAREST)) { + } else if (minFilter.equals(TexturePackParser.TAG_TEXTURE_ATTRIBUTE_MINFILTER_VALUE_NEAREST_MIPMAP_NEAREST)) { return GL10.GL_NEAREST_MIPMAP_NEAREST; } else { throw new IllegalArgumentException("Unexpected " + TexturePackParser.TAG_TEXTURE_ATTRIBUTE_MINFILTER + " attribute: '" + minFilter + "'."); @@ -254,9 +267,9 @@ private static int parseMinFilter(final Attributes pAttributes) { private static int parseMagFilter(final Attributes pAttributes) { final String magFilter = SAXUtils.getAttributeOrThrow(pAttributes, TexturePackParser.TAG_TEXTURE_ATTRIBUTE_MAGFILTER); - if(magFilter.equals(TexturePackParser.TAG_TEXTURE_ATTRIBUTE_MAGFILTER_VALUE_NEAREST)) { + if (magFilter.equals(TexturePackParser.TAG_TEXTURE_ATTRIBUTE_MAGFILTER_VALUE_NEAREST)) { return GL10.GL_NEAREST; - } else if(magFilter.equals(TexturePackParser.TAG_TEXTURE_ATTRIBUTE_MAGFILTER_VALUE_LINEAR)) { + } else if (magFilter.equals(TexturePackParser.TAG_TEXTURE_ATTRIBUTE_MAGFILTER_VALUE_LINEAR)) { return GL10.GL_LINEAR; } else { throw new IllegalArgumentException("Unexpected " + TexturePackParser.TAG_TEXTURE_ATTRIBUTE_MAGFILTER + " attribute: '" + magFilter + "'."); @@ -273,11 +286,11 @@ private int parseWrapS(final Attributes pAttributes) { private int parseWrap(final Attributes pAttributes, final String pWrapAttributeName) { final String wrapAttribute = SAXUtils.getAttributeOrThrow(pAttributes, pWrapAttributeName); - if(this.mVersion == 1 && wrapAttribute.equals(TexturePackParser.TAG_TEXTURE_ATTRIBUTE_WRAP_VALUE_CLAMP)) { + if (this.mVersion == 1 && wrapAttribute.equals(TexturePackParser.TAG_TEXTURE_ATTRIBUTE_WRAP_VALUE_CLAMP)) { return GL10.GL_CLAMP_TO_EDGE; - } else if(wrapAttribute.equals(TexturePackParser.TAG_TEXTURE_ATTRIBUTE_WRAP_VALUE_CLAMP_TO_EDGE)) { + } else if (wrapAttribute.equals(TexturePackParser.TAG_TEXTURE_ATTRIBUTE_WRAP_VALUE_CLAMP_TO_EDGE)) { return GL10.GL_CLAMP_TO_EDGE; - } else if(wrapAttribute.equals(TexturePackParser.TAG_TEXTURE_ATTRIBUTE_WRAP_VALUE_REPEAT)) { + } else if (wrapAttribute.equals(TexturePackParser.TAG_TEXTURE_ATTRIBUTE_WRAP_VALUE_REPEAT)) { return GL10.GL_REPEAT; } else { throw new IllegalArgumentException("Unexpected " + pWrapAttributeName + " attribute: '" + wrapAttribute + "'."); diff --git a/src/org/andengine/util/texturepack/TexturePackTextureRegion.java b/src/org/andengine/util/texturepack/TexturePackTextureRegion.java index 5d0b6835d..0d3276f10 100644 --- a/src/org/andengine/util/texturepack/TexturePackTextureRegion.java +++ b/src/org/andengine/util/texturepack/TexturePackTextureRegion.java @@ -4,8 +4,8 @@ import org.andengine.opengl.texture.region.TextureRegion; /** - * - * (c) Zynga 2011 + * + * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 16:28:48 - 15.08.2011 diff --git a/src/org/andengine/util/texturepack/TexturePackTextureRegionLibrary.java b/src/org/andengine/util/texturepack/TexturePackTextureRegionLibrary.java index 65d1cc55f..bc1a84cde 100644 --- a/src/org/andengine/util/texturepack/TexturePackTextureRegionLibrary.java +++ b/src/org/andengine/util/texturepack/TexturePackTextureRegionLibrary.java @@ -5,7 +5,7 @@ import android.util.SparseArray; /** - * (c) Zynga 2011 + * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 16:34:23 - 15.08.2011 @@ -71,9 +71,9 @@ public TexturePackTextureRegion get(final String pSource) { } public TexturePackTextureRegion get(final String pSource, final boolean pStripExtension) { - if(pStripExtension) { + if (pStripExtension) { final int indexOfExtension = pSource.lastIndexOf('.'); - if(indexOfExtension == -1) { + if (indexOfExtension == -1) { return this.get(pSource); } else { final String stripped = pSource.substring(0, indexOfExtension); @@ -85,9 +85,9 @@ public TexturePackTextureRegion get(final String pSource, final boolean pStripEx } private void throwOnCollision(final TexturePackTextureRegion pTexturePackTextureRegion) throws IllegalArgumentException { - if(this.mIDMapping.get(pTexturePackTextureRegion.getID()) != null) { + if (this.mIDMapping.get(pTexturePackTextureRegion.getID()) != null) { throw new IllegalArgumentException("Collision with ID: '" + pTexturePackTextureRegion.getID() + "'."); - } else if(this.mSourceMapping.get(pTexturePackTextureRegion.getSource()) != null) { + } else if (this.mSourceMapping.get(pTexturePackTextureRegion.getSource()) != null) { throw new IllegalArgumentException("Collision with Source: '" + pTexturePackTextureRegion.getSource() + "'."); } } diff --git a/src/org/andengine/util/texturepack/exception/TexturePackParseException.java b/src/org/andengine/util/texturepack/exception/TexturePackParseException.java index 2f387af37..fb0df5bcf 100644 --- a/src/org/andengine/util/texturepack/exception/TexturePackParseException.java +++ b/src/org/andengine/util/texturepack/exception/TexturePackParseException.java @@ -3,7 +3,7 @@ import org.xml.sax.SAXException; /** - * (c) Zynga 2011 + * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 17:29:20 - 29.07.2011 diff --git a/src/org/andengine/util/time/TimeConstants.java b/src/org/andengine/util/time/TimeConstants.java index fd54f7705..e82cd457b 100644 --- a/src/org/andengine/util/time/TimeConstants.java +++ b/src/org/andengine/util/time/TimeConstants.java @@ -1,9 +1,9 @@ package org.andengine.util.time; /** - * (c) 2010 Nicolas Gramlich + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. - * + * * @author Nicolas Gramlich * @since 16:49:25 - 26.07.2010 */ @@ -22,8 +22,8 @@ public interface TimeConstants { public static final int MINUTES_PER_HOUR = 60; - public static final int MILLISECONDS_PER_SECOND = 1000; - public static final int MICROSECONDS_PER_SECOND = 1000 * 1000; + public static final long MILLISECONDS_PER_SECOND = 1000; + public static final long MICROSECONDS_PER_SECOND = 1000 * 1000; public static final long NANOSECONDS_PER_SECOND = 1000 * 1000 * 1000; public static final long MICROSECONDS_PER_MILLISECOND = MICROSECONDS_PER_SECOND / MILLISECONDS_PER_SECOND; @@ -47,6 +47,27 @@ public interface TimeConstants { public static final int SECONDS_PER_MONTH = SECONDS_PER_DAY * DAYS_PER_MONTH; public static final int SECONDS_PER_YEAR = SECONDS_PER_MONTH * MONTHS_PER_YEAR; + public static final long MILLISECONDS_PER_MINUTE = MILLISECONDS_PER_SECOND * SECONDS_PER_MINUTE; + public static final long MILLISECONDS_PER_HOUR = MILLISECONDS_PER_SECOND * SECONDS_PER_HOUR; + public static final long MILLISECONDS_PER_DAY = MILLISECONDS_PER_SECOND * SECONDS_PER_DAY; + public static final long MILLISECONDS_PER_WEEK = MILLISECONDS_PER_SECOND * SECONDS_PER_WEEK; + public static final long MILLISECONDS_PER_MONTH = MILLISECONDS_PER_SECOND * SECONDS_PER_MONTH; + public static final long MILLISECONDS_PER_YEAR = MILLISECONDS_PER_SECOND * SECONDS_PER_YEAR; + + public static final long MICROSECONDS_PER_MINUTE = MICROSECONDS_PER_SECOND * SECONDS_PER_MINUTE; + public static final long MICROSECONDS_PER_HOUR = MICROSECONDS_PER_SECOND * SECONDS_PER_HOUR; + public static final long MICROSECONDS_PER_DAY = MICROSECONDS_PER_SECOND * SECONDS_PER_DAY; + public static final long MICROSECONDS_PER_WEEK = MICROSECONDS_PER_SECOND * SECONDS_PER_WEEK; + public static final long MICROSECONDS_PER_MONTH = MICROSECONDS_PER_SECOND * SECONDS_PER_MONTH; + public static final long MICROSECONDS_PER_YEAR = MICROSECONDS_PER_SECOND * SECONDS_PER_YEAR; + + public static final long NANOSECONDS_PER_MINUTE = NANOSECONDS_PER_SECOND * SECONDS_PER_MINUTE; + public static final long NANOSECONDS_PER_HOUR = NANOSECONDS_PER_SECOND * SECONDS_PER_HOUR; + public static final long NANOSECONDS_PER_DAY = NANOSECONDS_PER_SECOND * SECONDS_PER_DAY; + public static final long NANOSECONDS_PER_WEEK = NANOSECONDS_PER_SECOND * SECONDS_PER_WEEK; + public static final long NANOSECONDS_PER_MONTH = NANOSECONDS_PER_SECOND * SECONDS_PER_MONTH; + public static final long NANOSECONDS_PER_YEAR = NANOSECONDS_PER_SECOND * SECONDS_PER_YEAR; + // =========================================================== // Methods // =========================================================== diff --git a/src/org/andengine/util/uuid/UUIDManager.java b/src/org/andengine/util/uuid/UUIDManager.java new file mode 100644 index 000000000..b61e4a299 --- /dev/null +++ b/src/org/andengine/util/uuid/UUIDManager.java @@ -0,0 +1,68 @@ +package org.andengine.util.uuid; + +import java.util.UUID; + +import org.andengine.util.preferences.SimplePreferences; + +import android.content.Context; +import android.content.SharedPreferences; +import android.content.SharedPreferences.Editor; + +/** + * (c) 2013 Nicolas Gramlich + * + * @author Nicolas Gramlich + * @since 01:15:12 - 22.03.2013 + */ +public class UUIDManager { + // =========================================================== + // Constants + // =========================================================== + + private static final String PREFERENCES_UUIDMANAGER_UUID_KEY = "preferences.uuidmanager.uuid"; + + // =========================================================== + // Fields + // =========================================================== + + // =========================================================== + // Constructors + // =========================================================== + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + public static synchronized UUID getUUID(final Context pContext) { + final SharedPreferences preferences = SimplePreferences.getInstance(pContext); + return UUIDManager.getUUID(preferences); + } + + public static UUID getUUID(final SharedPreferences pSharedPreferences) { + final String uuidPreference = pSharedPreferences.getString(UUIDManager.PREFERENCES_UUIDMANAGER_UUID_KEY, null); + + if (uuidPreference != null) { + return UUID.fromString(uuidPreference); + } else { + final UUID uuid = UUID.randomUUID(); + + final Editor editor = pSharedPreferences.edit(); + editor.putString(UUIDManager.PREFERENCES_UUIDMANAGER_UUID_KEY, uuid.toString()); + editor.commit(); + + return uuid; + } + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== +}