diff --git a/AndEngine/src/org/anddev/andengine/audio/BaseAudioEntity.java b/AndEngine/src/org/anddev/andengine/audio/BaseAudioEntity.java index 7ddb466a..a6e453b3 100644 --- a/AndEngine/src/org/anddev/andengine/audio/BaseAudioEntity.java +++ b/AndEngine/src/org/anddev/andengine/audio/BaseAudioEntity.java @@ -8,82 +8,82 @@ * @since 16:35:37 - 13.06.2010 */ public abstract class BaseAudioEntity implements IAudioEntity { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - private final IAudioManager mAudioManager; - - protected float mLeftVolume = 1.0f; - protected float mRightVolume = 1.0f; - - // =========================================================== - // Constructors - // =========================================================== - - public BaseAudioEntity(final IAudioManager pAudioManager) { - this.mAudioManager = pAudioManager; - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - protected IAudioManager getAudioManager() { - return this.mAudioManager; - } - - public float getActualLeftVolume() { - return this.mLeftVolume * this.getMasterVolume(); - } - - public float getActualRightVolume() { - return this.mRightVolume * this.getMasterVolume(); - } - - protected float getMasterVolume() { - return this.mAudioManager.getMasterVolume(); - } - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - public float getVolume() { - return (this.mLeftVolume + this.mRightVolume) * 0.5f; - } - - @Override - public float getLeftVolume() { - return this.mLeftVolume; - } - - @Override - public float getRightVolume() { - return this.mRightVolume; - } - - @Override - public final void setVolume(final float pVolume) { - this.setVolume(pVolume, pVolume); - } - - @Override - public void setVolume(final float pLeftVolume, final float pRightVolume) { - this.mLeftVolume = pLeftVolume; - this.mRightVolume = pRightVolume; - } - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + private final IAudioManager mAudioManager; + + protected float mLeftVolume = 1.0f; + protected float mRightVolume = 1.0f; + + // =========================================================== + // Constructors + // =========================================================== + + public BaseAudioEntity(final IAudioManager pAudioManager) { + this.mAudioManager = pAudioManager; + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + protected IAudioManager getAudioManager() { + return this.mAudioManager; + } + + public float getActualLeftVolume() { + return this.mLeftVolume * this.getMasterVolume(); + } + + public float getActualRightVolume() { + return this.mRightVolume * this.getMasterVolume(); + } + + protected float getMasterVolume() { + return this.mAudioManager.getMasterVolume(); + } + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + public float getVolume() { + return (this.mLeftVolume + this.mRightVolume) * 0.5f; + } + + @Override + public float getLeftVolume() { + return this.mLeftVolume; + } + + @Override + public float getRightVolume() { + return this.mRightVolume; + } + + @Override + public final void setVolume(final float pVolume) { + this.setVolume(pVolume, pVolume); + } + + @Override + public void setVolume(final float pLeftVolume, final float pRightVolume) { + this.mLeftVolume = pLeftVolume; + this.mRightVolume = pRightVolume; + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/audio/BaseAudioManager.java b/AndEngine/src/org/anddev/andengine/audio/BaseAudioManager.java index b3d9ee29..dac4598c 100644 --- a/AndEngine/src/org/anddev/andengine/audio/BaseAudioManager.java +++ b/AndEngine/src/org/anddev/andengine/audio/BaseAudioManager.java @@ -10,68 +10,68 @@ * @since 18:07:02 - 13.06.2010 */ public abstract class BaseAudioManager implements IAudioManager { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - protected final ArrayList mAudioEntities = new ArrayList(); - - protected float mMasterVolume = 1.0f; - - // =========================================================== - // Constructors - // =========================================================== - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - public float getMasterVolume() { - return this.mMasterVolume; - } - - @Override - public void setMasterVolume(final float pMasterVolume) { - this.mMasterVolume = pMasterVolume; - - final ArrayList audioEntities = this.mAudioEntities; - for(int i = audioEntities.size() - 1; i >= 0; i--) { - final T audioEntity = audioEntities.get(i); - - audioEntity.onMasterVolumeChanged(pMasterVolume); - } - } - - @Override - public void add(final T pAudioEntity) { - this.mAudioEntities.add(pAudioEntity); - } - - @Override - public void releaseAll() { - final ArrayList audioEntities = this.mAudioEntities; - for(int i = audioEntities.size() - 1; i >= 0; i--) { - final T audioEntity = audioEntities.get(i); - - audioEntity.stop(); - audioEntity.release(); - } - } - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + protected final ArrayList mAudioEntities = new ArrayList(); + + protected float mMasterVolume = 1.0f; + + // =========================================================== + // Constructors + // =========================================================== + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + public float getMasterVolume() { + return this.mMasterVolume; + } + + @Override + public void setMasterVolume(final float pMasterVolume) { + this.mMasterVolume = pMasterVolume; + + final ArrayList audioEntities = this.mAudioEntities; + for(int i = audioEntities.size() - 1; i >= 0; i--) { + final T audioEntity = audioEntities.get(i); + + audioEntity.onMasterVolumeChanged(pMasterVolume); + } + } + + @Override + public void add(final T pAudioEntity) { + this.mAudioEntities.add(pAudioEntity); + } + + @Override + public void releaseAll() { + final ArrayList audioEntities = this.mAudioEntities; + for(int i = audioEntities.size() - 1; i >= 0; i--) { + final T audioEntity = audioEntities.get(i); + + audioEntity.stop(); + audioEntity.release(); + } + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/audio/IAudioEntity.java b/AndEngine/src/org/anddev/andengine/audio/IAudioEntity.java index 8a1e0bb0..2b81cb25 100644 --- a/AndEngine/src/org/anddev/andengine/audio/IAudioEntity.java +++ b/AndEngine/src/org/anddev/andengine/audio/IAudioEntity.java @@ -8,29 +8,29 @@ * @since 14:53:29 - 13.06.2010 */ public interface IAudioEntity { - // =========================================================== - // Final Fields - // =========================================================== + // =========================================================== + // Final Fields + // =========================================================== - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - public void play(); - public void pause(); - public void resume(); - public void stop(); + public void play(); + public void pause(); + public void resume(); + public void stop(); - public float getVolume(); - public void setVolume(final float pVolume); + public float getVolume(); + public void setVolume(final float pVolume); - public float getLeftVolume(); - public float getRightVolume(); - public void setVolume(final float pLeftVolume, final float pRightVolume); + public float getLeftVolume(); + public float getRightVolume(); + public void setVolume(final float pLeftVolume, final float pRightVolume); - public void onMasterVolumeChanged(final float pMasterVolume); + public void onMasterVolumeChanged(final float pMasterVolume); - public void setLooping(final boolean pLooping); + public void setLooping(final boolean pLooping); - public void release(); + public void release(); } diff --git a/AndEngine/src/org/anddev/andengine/audio/IAudioManager.java b/AndEngine/src/org/anddev/andengine/audio/IAudioManager.java index 45dbad03..c0b6f568 100644 --- a/AndEngine/src/org/anddev/andengine/audio/IAudioManager.java +++ b/AndEngine/src/org/anddev/andengine/audio/IAudioManager.java @@ -8,18 +8,18 @@ * @since 15:02:06 - 13.06.2010 */ public interface IAudioManager { - // =========================================================== - // Final Fields - // =========================================================== + // =========================================================== + // Final Fields + // =========================================================== - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - public float getMasterVolume(); - public void setMasterVolume(final float pMasterVolume); + public float getMasterVolume(); + public void setMasterVolume(final float pMasterVolume); - public void add(final T pAudioEntity); + public void add(final T pAudioEntity); - public void releaseAll(); + public void releaseAll(); } diff --git a/AndEngine/src/org/anddev/andengine/audio/music/Music.java b/AndEngine/src/org/anddev/andengine/audio/music/Music.java index 74ab3617..50d3bc49 100644 --- a/AndEngine/src/org/anddev/andengine/audio/music/Music.java +++ b/AndEngine/src/org/anddev/andengine/audio/music/Music.java @@ -13,105 +13,105 @@ * @since 14:53:12 - 13.06.2010 */ public class Music extends BaseAudioEntity { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - private final MediaPlayer mMediaPlayer; - - // =========================================================== - // Constructors - // =========================================================== - - Music(final MusicManager pMusicManager, final MediaPlayer pMediaPlayer) { - super(pMusicManager); - this.mMediaPlayer = pMediaPlayer; - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - public boolean isPlaying() { - return this.mMediaPlayer.isPlaying(); - } - - public MediaPlayer getMediaPlayer() { - return this.mMediaPlayer; - } - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - protected MusicManager getAudioManager() { - return (MusicManager)super.getAudioManager(); - } - - @Override - public void play() { - this.mMediaPlayer.start(); - } - - @Override - public void stop() { - this.mMediaPlayer.stop(); - } - - @Override - public void resume() { - this.mMediaPlayer.start(); - } - - @Override - public void pause() { - this.mMediaPlayer.pause(); - } - - @Override - public void release() { - this.mMediaPlayer.release(); - } - - @Override - public void setLooping(final boolean pLooping) { - this.mMediaPlayer.setLooping(pLooping); - } - - @Override - public void setVolume(final float pLeftVolume, final float pRightVolume) { - super.setVolume(pLeftVolume, pRightVolume); - - final float masterVolume = this.getAudioManager().getMasterVolume(); - final float actualLeftVolume = pLeftVolume * masterVolume; - final float actualRightVolume = pRightVolume * masterVolume; - - this.mMediaPlayer.setVolume(actualLeftVolume, actualRightVolume); - } - - @Override - public void onMasterVolumeChanged(final float pMasterVolume) { - this.setVolume(this.mLeftVolume, this.mRightVolume); - } - - // =========================================================== - // Methods - // =========================================================== - - public void seekTo(final int pMilliseconds) { - this.mMediaPlayer.seekTo(pMilliseconds); - } - - public void setOnCompletionListener(final OnCompletionListener pOnCompletionListener) { - this.mMediaPlayer.setOnCompletionListener(pOnCompletionListener); - } - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + private final MediaPlayer mMediaPlayer; + + // =========================================================== + // Constructors + // =========================================================== + + Music(final MusicManager pMusicManager, final MediaPlayer pMediaPlayer) { + super(pMusicManager); + this.mMediaPlayer = pMediaPlayer; + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + public boolean isPlaying() { + return this.mMediaPlayer.isPlaying(); + } + + public MediaPlayer getMediaPlayer() { + return this.mMediaPlayer; + } + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + protected MusicManager getAudioManager() { + return (MusicManager)super.getAudioManager(); + } + + @Override + public void play() { + this.mMediaPlayer.start(); + } + + @Override + public void stop() { + this.mMediaPlayer.stop(); + } + + @Override + public void resume() { + this.mMediaPlayer.start(); + } + + @Override + public void pause() { + this.mMediaPlayer.pause(); + } + + @Override + public void release() { + this.mMediaPlayer.release(); + } + + @Override + public void setLooping(final boolean pLooping) { + this.mMediaPlayer.setLooping(pLooping); + } + + @Override + public void setVolume(final float pLeftVolume, final float pRightVolume) { + super.setVolume(pLeftVolume, pRightVolume); + + final float masterVolume = this.getAudioManager().getMasterVolume(); + final float actualLeftVolume = pLeftVolume * masterVolume; + final float actualRightVolume = pRightVolume * masterVolume; + + this.mMediaPlayer.setVolume(actualLeftVolume, actualRightVolume); + } + + @Override + public void onMasterVolumeChanged(final float pMasterVolume) { + this.setVolume(this.mLeftVolume, this.mRightVolume); + } + + // =========================================================== + // Methods + // =========================================================== + + public void seekTo(final int pMilliseconds) { + this.mMediaPlayer.seekTo(pMilliseconds); + } + + public void setOnCompletionListener(final OnCompletionListener pOnCompletionListener) { + this.mMediaPlayer.setOnCompletionListener(pOnCompletionListener); + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/audio/music/MusicFactory.java b/AndEngine/src/org/anddev/andengine/audio/music/MusicFactory.java index 86066b3a..1c5b9c74 100644 --- a/AndEngine/src/org/anddev/andengine/audio/music/MusicFactory.java +++ b/AndEngine/src/org/anddev/andengine/audio/music/MusicFactory.java @@ -16,83 +16,83 @@ * @since 15:05:49 - 13.06.2010 */ public class MusicFactory { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - private static String sAssetBasePath = ""; + private static String sAssetBasePath = ""; - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - /** - * @param pAssetBasePath must end with '/' or have .length() == 0. - */ - public static void setAssetBasePath(final String pAssetBasePath) { - if(pAssetBasePath.endsWith("/") || pAssetBasePath.length() == 0) { - MusicFactory.sAssetBasePath = pAssetBasePath; - } else { - throw new IllegalStateException("pAssetBasePath must end with '/' or be lenght zero."); - } - } + /** + * @param pAssetBasePath must end with '/' or have .length() == 0. + */ + public static void setAssetBasePath(final String pAssetBasePath) { + if(pAssetBasePath.endsWith("/") || pAssetBasePath.length() == 0) { + MusicFactory.sAssetBasePath = pAssetBasePath; + } else { + throw new IllegalStateException("pAssetBasePath must end with '/' or be lenght zero."); + } + } - public static void reset() { - MusicFactory.setAssetBasePath(""); - } + public static void reset() { + MusicFactory.setAssetBasePath(""); + } - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - public static Music createMusicFromFile(final MusicManager pMusicManager, final File pFile) throws IOException { - final MediaPlayer mediaPlayer = new MediaPlayer(); + public static Music createMusicFromFile(final MusicManager pMusicManager, final File pFile) throws IOException { + final MediaPlayer mediaPlayer = new MediaPlayer(); - mediaPlayer.setDataSource(new FileInputStream(pFile).getFD()); - mediaPlayer.prepare(); + mediaPlayer.setDataSource(new FileInputStream(pFile).getFD()); + mediaPlayer.prepare(); - final Music music = new Music(pMusicManager, mediaPlayer); - pMusicManager.add(music); + final Music music = new Music(pMusicManager, mediaPlayer); + pMusicManager.add(music); - return music; - } + return music; + } - public static Music createMusicFromAsset(final MusicManager pMusicManager, final Context pContext, final String pAssetPath) throws IOException { - final MediaPlayer mediaPlayer = new MediaPlayer(); + public static Music createMusicFromAsset(final MusicManager pMusicManager, final Context pContext, final String pAssetPath) throws IOException { + final MediaPlayer mediaPlayer = new MediaPlayer(); - final AssetFileDescriptor assetFileDescritor = pContext.getAssets().openFd(MusicFactory.sAssetBasePath + pAssetPath); - mediaPlayer.setDataSource(assetFileDescritor.getFileDescriptor(), assetFileDescritor.getStartOffset(), assetFileDescritor.getLength()); - mediaPlayer.prepare(); + final AssetFileDescriptor assetFileDescritor = pContext.getAssets().openFd(MusicFactory.sAssetBasePath + pAssetPath); + mediaPlayer.setDataSource(assetFileDescritor.getFileDescriptor(), assetFileDescritor.getStartOffset(), assetFileDescritor.getLength()); + mediaPlayer.prepare(); - final Music music = new Music(pMusicManager, mediaPlayer); - pMusicManager.add(music); + final Music music = new Music(pMusicManager, mediaPlayer); + pMusicManager.add(music); - return music; - } + return music; + } - public static Music createMusicFromResource(final MusicManager pMusicManager, final Context pContext, final int pMusicResID) throws IOException { - final MediaPlayer mediaPlayer = MediaPlayer.create(pContext, pMusicResID); - mediaPlayer.prepare(); + public static Music createMusicFromResource(final MusicManager pMusicManager, final Context pContext, final int pMusicResID) throws IOException { + final MediaPlayer mediaPlayer = MediaPlayer.create(pContext, pMusicResID); + mediaPlayer.prepare(); - final Music music = new Music(pMusicManager, mediaPlayer); - pMusicManager.add(music); + final Music music = new Music(pMusicManager, mediaPlayer); + pMusicManager.add(music); - return music; - } + return music; + } - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/audio/music/MusicManager.java b/AndEngine/src/org/anddev/andengine/audio/music/MusicManager.java index 3a402939..c0bfdf8d 100644 --- a/AndEngine/src/org/anddev/andengine/audio/music/MusicManager.java +++ b/AndEngine/src/org/anddev/andengine/audio/music/MusicManager.java @@ -10,35 +10,35 @@ * @since 15:01:23 - 13.06.2010 */ public class MusicManager extends BaseAudioManager { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - public MusicManager() { + public MusicManager() { - } + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/audio/sound/Sound.java b/AndEngine/src/org/anddev/andengine/audio/sound/Sound.java index 17eca807..45a16121 100644 --- a/AndEngine/src/org/anddev/andengine/audio/sound/Sound.java +++ b/AndEngine/src/org/anddev/andengine/audio/sound/Sound.java @@ -10,117 +10,117 @@ * @since 13:22:15 - 11.03.2010 */ public class Sound extends BaseAudioEntity { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - private final int mSoundID; - private int mStreamID = 0; - - private int mLoopCount = 0; - private float mRate = 1.0f; - - // =========================================================== - // Constructors - // =========================================================== - - Sound(final SoundManager pSoundManager, final int pSoundID) { - super(pSoundManager); - this.mSoundID = pSoundID; - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - public void setLoopCount(final int pLoopCount) { - this.mLoopCount = pLoopCount; - if(this.mStreamID != 0) { - this.getAudioManager().getSoundPool().setLoop(this.mStreamID, pLoopCount); - } - } - - public void setRate(final float pRate) { - this.mRate = pRate; - if(this.mStreamID != 0) { - this.getAudioManager().getSoundPool().setRate(this.mStreamID, pRate); - } - } - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - // =========================================================== - // Methods - // =========================================================== - - @Override - protected SoundManager getAudioManager() { - return (SoundManager)super.getAudioManager(); - } - - @Override - public void play() { - final float masterVolume = this.getMasterVolume(); - final float leftVolume = this.mLeftVolume * masterVolume; - final float rightVolume = this.mRightVolume * masterVolume; - this.mStreamID = this.getAudioManager().getSoundPool().play(this.mSoundID, leftVolume, rightVolume, 1, this.mLoopCount, this.mRate); - } - - @Override - public void stop() { - if(this.mStreamID != 0) { - this.getAudioManager().getSoundPool().stop(this.mStreamID); - } - } - - @Override - public void resume() { - if(this.mStreamID != 0) { - this.getAudioManager().getSoundPool().resume(this.mStreamID); - } - } - - @Override - public void pause() { - if(this.mStreamID != 0) { - this.getAudioManager().getSoundPool().pause(this.mStreamID); - } - } - - @Override - public void release() { - - } - - @Override - public void setLooping(final boolean pLooping) { - this.setLoopCount(pLooping ? -1 : 0); - } - - @Override - public void setVolume(final float pLeftVolume, final float pRightVolume) { - super.setVolume(pLeftVolume, pRightVolume); - if(this.mStreamID != 0){ - final float masterVolume = this.getMasterVolume(); - final float leftVolume = this.mLeftVolume * masterVolume; - final float rightVolume = this.mRightVolume * masterVolume; - - this.getAudioManager().getSoundPool().setVolume(this.mStreamID, leftVolume, rightVolume); - } - } - - @Override - public void onMasterVolumeChanged(final float pMasterVolume) { - this.setVolume(this.mLeftVolume, this.mRightVolume); - } - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + private final int mSoundID; + private int mStreamID = 0; + + private int mLoopCount = 0; + private float mRate = 1.0f; + + // =========================================================== + // Constructors + // =========================================================== + + Sound(final SoundManager pSoundManager, final int pSoundID) { + super(pSoundManager); + this.mSoundID = pSoundID; + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + public void setLoopCount(final int pLoopCount) { + this.mLoopCount = pLoopCount; + if(this.mStreamID != 0) { + this.getAudioManager().getSoundPool().setLoop(this.mStreamID, pLoopCount); + } + } + + public void setRate(final float pRate) { + this.mRate = pRate; + if(this.mStreamID != 0) { + this.getAudioManager().getSoundPool().setRate(this.mStreamID, pRate); + } + } + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + @Override + protected SoundManager getAudioManager() { + return (SoundManager)super.getAudioManager(); + } + + @Override + public void play() { + final float masterVolume = this.getMasterVolume(); + final float leftVolume = this.mLeftVolume * masterVolume; + final float rightVolume = this.mRightVolume * masterVolume; + this.mStreamID = this.getAudioManager().getSoundPool().play(this.mSoundID, leftVolume, rightVolume, 1, this.mLoopCount, this.mRate); + } + + @Override + public void stop() { + if(this.mStreamID != 0) { + this.getAudioManager().getSoundPool().stop(this.mStreamID); + } + } + + @Override + public void resume() { + if(this.mStreamID != 0) { + this.getAudioManager().getSoundPool().resume(this.mStreamID); + } + } + + @Override + public void pause() { + if(this.mStreamID != 0) { + this.getAudioManager().getSoundPool().pause(this.mStreamID); + } + } + + @Override + public void release() { + + } + + @Override + public void setLooping(final boolean pLooping) { + this.setLoopCount(pLooping ? -1 : 0); + } + + @Override + public void setVolume(final float pLeftVolume, final float pRightVolume) { + super.setVolume(pLeftVolume, pRightVolume); + if(this.mStreamID != 0){ + final float masterVolume = this.getMasterVolume(); + final float leftVolume = this.mLeftVolume * masterVolume; + final float rightVolume = this.mRightVolume * masterVolume; + + this.getAudioManager().getSoundPool().setVolume(this.mStreamID, leftVolume, rightVolume); + } + } + + @Override + public void onMasterVolumeChanged(final float pMasterVolume) { + this.setVolume(this.mLeftVolume, this.mRightVolume); + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/audio/sound/SoundFactory.java b/AndEngine/src/org/anddev/andengine/audio/sound/SoundFactory.java index 17b7ab7f..39768d96 100644 --- a/AndEngine/src/org/anddev/andengine/audio/sound/SoundFactory.java +++ b/AndEngine/src/org/anddev/andengine/audio/sound/SoundFactory.java @@ -13,76 +13,76 @@ * @since 14:23:03 - 11.03.2010 */ public class SoundFactory { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - private static String sAssetBasePath = ""; - - // =========================================================== - // Constructors - // =========================================================== - - // =========================================================== - // Getter & Setter - // =========================================================== - - /** - * @param pAssetBasePath must end with '/' or have .length() == 0. - */ - public static void setAssetBasePath(final String pAssetBasePath) { - if(pAssetBasePath.endsWith("/") || pAssetBasePath.length() == 0) { - SoundFactory.sAssetBasePath = pAssetBasePath; - } else { - throw new IllegalStateException("pAssetBasePath must end with '/' or be lenght zero."); - } - } - - public static void reset() { - SoundFactory.setAssetBasePath(""); - } - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - // =========================================================== - // Methods - // =========================================================== - - public static Sound createSoundFromPath(final SoundManager pSoundManager, final String pPath) throws IOException { - final int soundID = pSoundManager.getSoundPool().load(pPath, 1); - final Sound sound = new Sound(pSoundManager, soundID); - pSoundManager.add(sound); - return sound; - } - - public static Sound createSoundFromAsset(final SoundManager pSoundManager, final Context pContext, final String pAssetPath) throws IOException { - final int soundID = pSoundManager.getSoundPool().load(pContext.getAssets().openFd(SoundFactory.sAssetBasePath + pAssetPath), 1); - final Sound sound = new Sound(pSoundManager, soundID); - pSoundManager.add(sound); - return sound; - } - - public static Sound createSoundFromResource(final SoundManager pSoundManager, final Context pContext, final int pSoundResID) { - final int soundID = pSoundManager.getSoundPool().load(pContext, pSoundResID, 1); - final Sound sound = new Sound(pSoundManager, soundID); - pSoundManager.add(sound); - return sound; - } - - public static Sound createSoundFromFileDescriptor(final SoundManager pSoundManager, final FileDescriptor pFileDescriptor, final long pOffset, final long pLength) throws IOException { - final int soundID = pSoundManager.getSoundPool().load(pFileDescriptor, pOffset, pLength, 1); - final Sound sound = new Sound(pSoundManager, soundID); - pSoundManager.add(sound); - return sound; - } - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + private static String sAssetBasePath = ""; + + // =========================================================== + // Constructors + // =========================================================== + + // =========================================================== + // Getter & Setter + // =========================================================== + + /** + * @param pAssetBasePath must end with '/' or have .length() == 0. + */ + public static void setAssetBasePath(final String pAssetBasePath) { + if(pAssetBasePath.endsWith("/") || pAssetBasePath.length() == 0) { + SoundFactory.sAssetBasePath = pAssetBasePath; + } else { + throw new IllegalStateException("pAssetBasePath must end with '/' or be lenght zero."); + } + } + + public static void reset() { + SoundFactory.setAssetBasePath(""); + } + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + public static Sound createSoundFromPath(final SoundManager pSoundManager, final String pPath) throws IOException { + final int soundID = pSoundManager.getSoundPool().load(pPath, 1); + final Sound sound = new Sound(pSoundManager, soundID); + pSoundManager.add(sound); + return sound; + } + + public static Sound createSoundFromAsset(final SoundManager pSoundManager, final Context pContext, final String pAssetPath) throws IOException { + final int soundID = pSoundManager.getSoundPool().load(pContext.getAssets().openFd(SoundFactory.sAssetBasePath + pAssetPath), 1); + final Sound sound = new Sound(pSoundManager, soundID); + pSoundManager.add(sound); + return sound; + } + + public static Sound createSoundFromResource(final SoundManager pSoundManager, final Context pContext, final int pSoundResID) { + final int soundID = pSoundManager.getSoundPool().load(pContext, pSoundResID, 1); + final Sound sound = new Sound(pSoundManager, soundID); + pSoundManager.add(sound); + return sound; + } + + public static Sound createSoundFromFileDescriptor(final SoundManager pSoundManager, final FileDescriptor pFileDescriptor, final long pOffset, final long pLength) throws IOException { + final int soundID = pSoundManager.getSoundPool().load(pFileDescriptor, pOffset, pLength, 1); + final Sound sound = new Sound(pSoundManager, soundID); + pSoundManager.add(sound); + return sound; + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/audio/sound/SoundLibrary.java b/AndEngine/src/org/anddev/andengine/audio/sound/SoundLibrary.java index d5231a86..50e7a0ef 100644 --- a/AndEngine/src/org/anddev/andengine/audio/sound/SoundLibrary.java +++ b/AndEngine/src/org/anddev/andengine/audio/sound/SoundLibrary.java @@ -10,31 +10,31 @@ * @since 20:41:56 - 20.08.2010 */ public class SoundLibrary extends Library { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/audio/sound/SoundManager.java b/AndEngine/src/org/anddev/andengine/audio/sound/SoundManager.java index b49f8a8d..16ec8baf 100644 --- a/AndEngine/src/org/anddev/andengine/audio/sound/SoundManager.java +++ b/AndEngine/src/org/anddev/andengine/audio/sound/SoundManager.java @@ -13,54 +13,54 @@ * @since 13:22:59 - 11.03.2010 */ public class SoundManager extends BaseAudioManager { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - private static final int MAX_SIMULTANEOUS_STREAMS_DEFAULT = 5; + private static final int MAX_SIMULTANEOUS_STREAMS_DEFAULT = 5; - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - private final SoundPool mSoundPool; + private final SoundPool mSoundPool; - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - public SoundManager() { - this(MAX_SIMULTANEOUS_STREAMS_DEFAULT); - } + public SoundManager() { + this(MAX_SIMULTANEOUS_STREAMS_DEFAULT); + } - public SoundManager(final int pMaxSimultaneousStreams) { - this.mSoundPool = new SoundPool(pMaxSimultaneousStreams, AudioManager.STREAM_MUSIC, 0); - } + public SoundManager(final int pMaxSimultaneousStreams) { + this.mSoundPool = new SoundPool(pMaxSimultaneousStreams, AudioManager.STREAM_MUSIC, 0); + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - SoundPool getSoundPool() { - return this.mSoundPool; - } + SoundPool getSoundPool() { + return this.mSoundPool; + } - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - @Override - public void releaseAll() { - super.releaseAll(); + @Override + public void releaseAll() { + super.releaseAll(); - this.mSoundPool.release(); - } + this.mSoundPool.release(); + } - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/collision/BaseCollisionChecker.java b/AndEngine/src/org/anddev/andengine/collision/BaseCollisionChecker.java index 792fd9d3..80101ec8 100644 --- a/AndEngine/src/org/anddev/andengine/collision/BaseCollisionChecker.java +++ b/AndEngine/src/org/anddev/andengine/collision/BaseCollisionChecker.java @@ -8,108 +8,108 @@ * @since 11:50:19 - 11.03.2010 */ public class BaseCollisionChecker { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - 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; - } + 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; + } - /** - * 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). - *

- * 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 - * the default coordinate system used by Java 2D, this direction is - * counterclockwise. - *

- * A return value of -1 indicates that the line segment must turn in the - * direction that takes the positive X axis towards the positive Y axis. In - * the default coordinate system, this direction is clockwise. - *

- * A return value of 0 indicates that the point lies exactly on the line - * segment. Note that an indicator value of 0 is rare and not useful for - * determining colinearity because of floating point rounding issues. - *

- * 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 - * line segment - * @param pX2 - * , Y2 the coordinates of the end of the specified line - * segment - * @param pPX - * , PY 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 - * two specified coordinates. - */ - public static int relativeCCW(final float pX1, final float pY1, float pX2, float pY2, float pPX, float pPY) { - pX2 -= pX1; - pY2 -= pY1; - pPX -= pX1; - pPY -= pY1; - 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 - // relative value using the projection of PX,PY onto the - // 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; - if (ccw > 0.0f) { - // Reverse the projection to be relative to the original X2,Y2 - // X2 and Y2 are simply negated. - // PX and PY need to have (X2 - X1) or (Y2 - Y1) subtracted - // from them (based on the original values) - // Since we really want to get a positive answer when the - // point is "beyond (X2,Y2)", then we want to calculate - // the inverse anyway - thus we leave X2 & Y2 negated. - pPX -= pX2; - pPY -= pY2; - ccw = pPX * pX2 + pPY * pY2; - if (ccw < 0.0f) { - ccw = 0.0f; - } - } - } - return (ccw < 0.0f) ? -1 : ((ccw > 0.0f) ? 1 : 0); - } + /** + * 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). + *

+ * 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 + * the default coordinate system used by Java 2D, this direction is + * counterclockwise. + *

+ * A return value of -1 indicates that the line segment must turn in the + * direction that takes the positive X axis towards the positive Y axis. In + * the default coordinate system, this direction is clockwise. + *

+ * A return value of 0 indicates that the point lies exactly on the line + * segment. Note that an indicator value of 0 is rare and not useful for + * determining colinearity because of floating point rounding issues. + *

+ * 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 + * line segment + * @param pX2 + * , Y2 the coordinates of the end of the specified line + * segment + * @param pPX + * , PY 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 + * two specified coordinates. + */ + public static int relativeCCW(final float pX1, final float pY1, float pX2, float pY2, float pPX, float pPY) { + pX2 -= pX1; + pY2 -= pY1; + pPX -= pX1; + pPY -= pY1; + 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 + // relative value using the projection of PX,PY onto the + // 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; + if (ccw > 0.0f) { + // Reverse the projection to be relative to the original X2,Y2 + // X2 and Y2 are simply negated. + // PX and PY need to have (X2 - X1) or (Y2 - Y1) subtracted + // from them (based on the original values) + // Since we really want to get a positive answer when the + // point is "beyond (X2,Y2)", then we want to calculate + // the inverse anyway - thus we leave X2 & Y2 negated. + pPX -= pX2; + pPY -= pY2; + ccw = pPX * pX2 + pPY * pY2; + if (ccw < 0.0f) { + ccw = 0.0f; + } + } + } + return (ccw < 0.0f) ? -1 : ((ccw > 0.0f) ? 1 : 0); + } - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/collision/LineCollisionChecker.java b/AndEngine/src/org/anddev/andengine/collision/LineCollisionChecker.java index 5388ee4d..e56fcaa5 100644 --- a/AndEngine/src/org/anddev/andengine/collision/LineCollisionChecker.java +++ b/AndEngine/src/org/anddev/andengine/collision/LineCollisionChecker.java @@ -13,46 +13,46 @@ * @since 19:27:22 - 17.07.2010 */ public class LineCollisionChecker extends ShapeCollisionChecker { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - public static boolean checkLineCollision(final float pX1, final float pY1, final float pX2, final float pY2, final float pX3, final float pY3, final float pX4, final float pY4) { - return ((BaseCollisionChecker.relativeCCW(pX1, pY1, pX2, pY2, pX3, pY3) * BaseCollisionChecker.relativeCCW(pX1, pY1, pX2, pY2, pX4, pY4) <= 0) - && (BaseCollisionChecker.relativeCCW(pX3, pY3, pX4, pY4, pX1, pY1) * BaseCollisionChecker.relativeCCW(pX3, pY3, pX4, pY4, pX2, pY2) <= 0)); - } + public static boolean checkLineCollision(final float pX1, final float pY1, final float pX2, final float pY2, final float pX3, final float pY3, final float pX4, final float pY4) { + return ((BaseCollisionChecker.relativeCCW(pX1, pY1, pX2, pY2, pX3, pY3) * BaseCollisionChecker.relativeCCW(pX1, pY1, pX2, pY2, pX4, pY4) <= 0) + && (BaseCollisionChecker.relativeCCW(pX3, pY3, pX4, pY4, pX1, pY1) * BaseCollisionChecker.relativeCCW(pX3, pY3, pX4, pY4, pX2, pY2) <= 0)); + } - public static void fillVertices(final Line pLine, final float[] pVertices) { - pVertices[0 + VERTEX_INDEX_X] = 0; - pVertices[0 + VERTEX_INDEX_Y] = 0; + public static void fillVertices(final Line pLine, final float[] pVertices) { + pVertices[0 + VERTEX_INDEX_X] = 0; + pVertices[0 + VERTEX_INDEX_Y] = 0; - pVertices[2 + VERTEX_INDEX_X] = pLine.getX2() - pLine.getX1(); - pVertices[2 + VERTEX_INDEX_Y] = pLine.getY2() - pLine.getY1(); + pVertices[2 + VERTEX_INDEX_X] = pLine.getX2() - pLine.getX1(); + pVertices[2 + VERTEX_INDEX_Y] = pLine.getY2() - pLine.getY1(); - pLine.getLocalToSceneTransformation().transform(pVertices); - } + pLine.getLocalToSceneTransformation().transform(pVertices); + } - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/collision/RectangularShapeCollisionChecker.java b/AndEngine/src/org/anddev/andengine/collision/RectangularShapeCollisionChecker.java index 60833be0..11be27db 100644 --- a/AndEngine/src/org/anddev/andengine/collision/RectangularShapeCollisionChecker.java +++ b/AndEngine/src/org/anddev/andengine/collision/RectangularShapeCollisionChecker.java @@ -16,108 +16,108 @@ * @since 11:50:19 - 11.03.2010 */ public class RectangularShapeCollisionChecker extends ShapeCollisionChecker { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - private static final int RECTANGULARSHAPE_VERTEX_COUNT = 4; - private static final int LINE_VERTEX_COUNT = 2; + private static final int RECTANGULARSHAPE_VERTEX_COUNT = 4; + private static final int LINE_VERTEX_COUNT = 2; - private static final float[] VERTICES_CONTAINS_TMP = new float[2 * RECTANGULARSHAPE_VERTEX_COUNT]; - private static final float[] VERTICES_COLLISION_TMP_A = new float[2 * RECTANGULARSHAPE_VERTEX_COUNT]; - private static final float[] VERTICES_COLLISION_TMP_B = new float[2 * RECTANGULARSHAPE_VERTEX_COUNT]; + private static final float[] VERTICES_CONTAINS_TMP = new float[2 * RECTANGULARSHAPE_VERTEX_COUNT]; + private static final float[] VERTICES_COLLISION_TMP_A = new float[2 * RECTANGULARSHAPE_VERTEX_COUNT]; + private static final float[] VERTICES_COLLISION_TMP_B = new float[2 * RECTANGULARSHAPE_VERTEX_COUNT]; - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - public static boolean checkContains(final RectangularShape pRectangularShape, final float pX, final float pY) { - RectangularShapeCollisionChecker.fillVertices(pRectangularShape, VERTICES_CONTAINS_TMP); - return ShapeCollisionChecker.checkContains(VERTICES_CONTAINS_TMP, 2 * RECTANGULARSHAPE_VERTEX_COUNT, pX, pY); - } + public static boolean checkContains(final RectangularShape pRectangularShape, final float pX, final float pY) { + RectangularShapeCollisionChecker.fillVertices(pRectangularShape, VERTICES_CONTAINS_TMP); + return ShapeCollisionChecker.checkContains(VERTICES_CONTAINS_TMP, 2 * RECTANGULARSHAPE_VERTEX_COUNT, pX, pY); + } - public static boolean isVisible(final Camera pCamera, final RectangularShape pRectangularShape) { - RectangularShapeCollisionChecker.fillVertices(pCamera, VERTICES_COLLISION_TMP_A); - RectangularShapeCollisionChecker.fillVertices(pRectangularShape, VERTICES_COLLISION_TMP_B); + public static boolean isVisible(final Camera pCamera, final RectangularShape pRectangularShape) { + RectangularShapeCollisionChecker.fillVertices(pCamera, VERTICES_COLLISION_TMP_A); + RectangularShapeCollisionChecker.fillVertices(pRectangularShape, VERTICES_COLLISION_TMP_B); - return ShapeCollisionChecker.checkCollision(2 * RECTANGULARSHAPE_VERTEX_COUNT, VERTICES_COLLISION_TMP_A, 2 * RECTANGULARSHAPE_VERTEX_COUNT, VERTICES_COLLISION_TMP_B); - } + return ShapeCollisionChecker.checkCollision(2 * RECTANGULARSHAPE_VERTEX_COUNT, VERTICES_COLLISION_TMP_A, 2 * RECTANGULARSHAPE_VERTEX_COUNT, VERTICES_COLLISION_TMP_B); + } - public static boolean isVisible(final Camera pCamera, final Line pLine) { - RectangularShapeCollisionChecker.fillVertices(pCamera, VERTICES_COLLISION_TMP_A); - LineCollisionChecker.fillVertices(pLine, VERTICES_COLLISION_TMP_B); + public static boolean isVisible(final Camera pCamera, final Line pLine) { + RectangularShapeCollisionChecker.fillVertices(pCamera, VERTICES_COLLISION_TMP_A); + LineCollisionChecker.fillVertices(pLine, VERTICES_COLLISION_TMP_B); - return ShapeCollisionChecker.checkCollision(2 * RECTANGULARSHAPE_VERTEX_COUNT, VERTICES_COLLISION_TMP_A, 2 * LINE_VERTEX_COUNT, VERTICES_COLLISION_TMP_B); - } + return ShapeCollisionChecker.checkCollision(2 * RECTANGULARSHAPE_VERTEX_COUNT, VERTICES_COLLISION_TMP_A, 2 * LINE_VERTEX_COUNT, VERTICES_COLLISION_TMP_B); + } - public static boolean checkCollision(final RectangularShape pRectangularShapeA, final RectangularShape pRectangularShapeB) { - RectangularShapeCollisionChecker.fillVertices(pRectangularShapeA, VERTICES_COLLISION_TMP_A); - RectangularShapeCollisionChecker.fillVertices(pRectangularShapeB, VERTICES_COLLISION_TMP_B); + public static boolean checkCollision(final RectangularShape pRectangularShapeA, final RectangularShape pRectangularShapeB) { + RectangularShapeCollisionChecker.fillVertices(pRectangularShapeA, VERTICES_COLLISION_TMP_A); + RectangularShapeCollisionChecker.fillVertices(pRectangularShapeB, VERTICES_COLLISION_TMP_B); - return ShapeCollisionChecker.checkCollision(2 * RECTANGULARSHAPE_VERTEX_COUNT, VERTICES_COLLISION_TMP_A, 2 * RECTANGULARSHAPE_VERTEX_COUNT, VERTICES_COLLISION_TMP_B); - } + return ShapeCollisionChecker.checkCollision(2 * RECTANGULARSHAPE_VERTEX_COUNT, VERTICES_COLLISION_TMP_A, 2 * RECTANGULARSHAPE_VERTEX_COUNT, VERTICES_COLLISION_TMP_B); + } - public static boolean checkCollision(final RectangularShape pRectangularShape, final Line pLine) { - RectangularShapeCollisionChecker.fillVertices(pRectangularShape, VERTICES_COLLISION_TMP_A); - LineCollisionChecker.fillVertices(pLine, VERTICES_COLLISION_TMP_B); + public static boolean checkCollision(final RectangularShape pRectangularShape, final Line pLine) { + RectangularShapeCollisionChecker.fillVertices(pRectangularShape, VERTICES_COLLISION_TMP_A); + LineCollisionChecker.fillVertices(pLine, VERTICES_COLLISION_TMP_B); - return ShapeCollisionChecker.checkCollision(2 * RECTANGULARSHAPE_VERTEX_COUNT, VERTICES_COLLISION_TMP_A, 2 * LINE_VERTEX_COUNT, VERTICES_COLLISION_TMP_B); - } + return ShapeCollisionChecker.checkCollision(2 * RECTANGULARSHAPE_VERTEX_COUNT, VERTICES_COLLISION_TMP_A, 2 * LINE_VERTEX_COUNT, VERTICES_COLLISION_TMP_B); + } - public static void fillVertices(final RectangularShape pRectangularShape, final float[] pVertices) { - final float left = 0; - final float top = 0; - final float right = pRectangularShape.getWidth(); - final float bottom = pRectangularShape.getHeight(); + public static void fillVertices(final RectangularShape pRectangularShape, final float[] pVertices) { + final float left = 0; + final float top = 0; + final float right = pRectangularShape.getWidth(); + final float bottom = pRectangularShape.getHeight(); - pVertices[0 + VERTEX_INDEX_X] = left; - pVertices[0 + VERTEX_INDEX_Y] = top; + pVertices[0 + VERTEX_INDEX_X] = left; + pVertices[0 + VERTEX_INDEX_Y] = top; - pVertices[2 + VERTEX_INDEX_X] = right; - pVertices[2 + VERTEX_INDEX_Y] = top; + pVertices[2 + VERTEX_INDEX_X] = right; + pVertices[2 + VERTEX_INDEX_Y] = top; - pVertices[4 + VERTEX_INDEX_X] = right; - pVertices[4 + VERTEX_INDEX_Y] = bottom; + pVertices[4 + VERTEX_INDEX_X] = right; + pVertices[4 + VERTEX_INDEX_Y] = bottom; - pVertices[6 + VERTEX_INDEX_X] = left; - pVertices[6 + VERTEX_INDEX_Y] = bottom; + pVertices[6 + VERTEX_INDEX_X] = left; + pVertices[6 + VERTEX_INDEX_Y] = bottom; - pRectangularShape.getLocalToSceneTransformation().transform(pVertices); - } + pRectangularShape.getLocalToSceneTransformation().transform(pVertices); + } - private static void fillVertices(final Camera pCamera, final float[] pVertices) { - pVertices[0 + VERTEX_INDEX_X] = pCamera.getMinX(); - pVertices[0 + VERTEX_INDEX_Y] = pCamera.getMinY(); + private static void fillVertices(final Camera pCamera, final float[] pVertices) { + pVertices[0 + VERTEX_INDEX_X] = pCamera.getMinX(); + pVertices[0 + VERTEX_INDEX_Y] = pCamera.getMinY(); - pVertices[2 + VERTEX_INDEX_X] = pCamera.getMaxX(); - pVertices[2 + VERTEX_INDEX_Y] = pCamera.getMinY(); + pVertices[2 + VERTEX_INDEX_X] = pCamera.getMaxX(); + pVertices[2 + VERTEX_INDEX_Y] = pCamera.getMinY(); - pVertices[4 + VERTEX_INDEX_X] = pCamera.getMaxX(); - pVertices[4 + VERTEX_INDEX_Y] = pCamera.getMaxY(); + pVertices[4 + VERTEX_INDEX_X] = pCamera.getMaxX(); + pVertices[4 + VERTEX_INDEX_Y] = pCamera.getMaxY(); - pVertices[6 + VERTEX_INDEX_X] = pCamera.getMinX(); - pVertices[6 + VERTEX_INDEX_Y] = pCamera.getMaxY(); + pVertices[6 + VERTEX_INDEX_X] = pCamera.getMinX(); + pVertices[6 + VERTEX_INDEX_Y] = pCamera.getMaxY(); - MathUtils.rotateAroundCenter(pVertices, pCamera.getRotation(), pCamera.getCenterX(), pCamera.getCenterY()); - } + MathUtils.rotateAroundCenter(pVertices, pCamera.getRotation(), pCamera.getCenterX(), pCamera.getCenterY()); + } - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/collision/ShapeCollisionChecker.java b/AndEngine/src/org/anddev/andengine/collision/ShapeCollisionChecker.java index 572d0b84..7054d6d1 100644 --- a/AndEngine/src/org/anddev/andengine/collision/ShapeCollisionChecker.java +++ b/AndEngine/src/org/anddev/andengine/collision/ShapeCollisionChecker.java @@ -11,101 +11,101 @@ * @since 11:50:19 - 11.03.2010 */ public class ShapeCollisionChecker extends BaseCollisionChecker { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - public static boolean checkCollision(final int pVerticesALength, final float[] pVerticesA, final int pVerticesBLength, final float[] pVerticesB) { - /* Check all the lines of A ... */ - for(int a = pVerticesALength - 4; a >= 0; a -= 2) { - /* ... against all lines in B. */ - if(ShapeCollisionChecker.checkCollisionSub(a, a + 2, pVerticesA, pVerticesB, pVerticesBLength)){ - return true; - } - } - /* Also check the 'around the corner of the array' line of A against all lines in B. */ - if(ShapeCollisionChecker.checkCollisionSub(pVerticesALength - 2, 0, pVerticesA, pVerticesB, pVerticesBLength)){ - 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, pVerticesALength, pVerticesB[Constants.VERTEX_INDEX_X], pVerticesB[Constants.VERTEX_INDEX_Y])) { - return true; - } else if(ShapeCollisionChecker.checkContains(pVerticesB, pVerticesBLength, pVerticesA[Constants.VERTEX_INDEX_X], pVerticesA[Constants.VERTEX_INDEX_Y])) { - return true; - } else { - return false; - } - } - } + public static boolean checkCollision(final int pVerticesALength, final float[] pVerticesA, final int pVerticesBLength, final float[] pVerticesB) { + /* Check all the lines of A ... */ + for(int a = pVerticesALength - 4; a >= 0; a -= 2) { + /* ... against all lines in B. */ + if(ShapeCollisionChecker.checkCollisionSub(a, a + 2, pVerticesA, pVerticesB, pVerticesBLength)){ + return true; + } + } + /* Also check the 'around the corner of the array' line of A against all lines in B. */ + if(ShapeCollisionChecker.checkCollisionSub(pVerticesALength - 2, 0, pVerticesA, pVerticesB, pVerticesBLength)){ + 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, pVerticesALength, pVerticesB[Constants.VERTEX_INDEX_X], pVerticesB[Constants.VERTEX_INDEX_Y])) { + return true; + } else if(ShapeCollisionChecker.checkContains(pVerticesB, pVerticesBLength, pVerticesA[Constants.VERTEX_INDEX_X], pVerticesA[Constants.VERTEX_INDEX_Y])) { + return true; + } else { + return false; + } + } + } - /** - * Checks line specified by pVerticesA[pVertexIndexA1] and pVerticesA[pVertexIndexA2] against all lines in pVerticesB. - */ - private static boolean checkCollisionSub(final int pVertexIndexA1, final int pVertexIndexA2, final float[] pVerticesA, final float[] pVerticesB, final int pVerticesBLength) { - /* Check against all the lines of B. */ - final float vertexA1X = pVerticesA[pVertexIndexA1 + Constants.VERTEX_INDEX_X]; - final float vertexA1Y = pVerticesA[pVertexIndexA1 + Constants.VERTEX_INDEX_Y]; - final float vertexA2X = pVerticesA[pVertexIndexA2 + Constants.VERTEX_INDEX_X]; - final float vertexA2Y = pVerticesA[pVertexIndexA2 + Constants.VERTEX_INDEX_Y]; + /** + * Checks line specified by pVerticesA[pVertexIndexA1] and pVerticesA[pVertexIndexA2] against all lines in pVerticesB. + */ + private static boolean checkCollisionSub(final int pVertexIndexA1, final int pVertexIndexA2, final float[] pVerticesA, final float[] pVerticesB, final int pVerticesBLength) { + /* Check against all the lines of B. */ + final float vertexA1X = pVerticesA[pVertexIndexA1 + Constants.VERTEX_INDEX_X]; + final float vertexA1Y = pVerticesA[pVertexIndexA1 + Constants.VERTEX_INDEX_Y]; + final float vertexA2X = pVerticesA[pVertexIndexA2 + Constants.VERTEX_INDEX_X]; + final float vertexA2Y = pVerticesA[pVertexIndexA2 + Constants.VERTEX_INDEX_Y]; - for(int b = pVerticesBLength - 4; b >= 0; b -= 2) { - if(LineCollisionChecker.checkLineCollision(vertexA1X, vertexA1Y, vertexA2X, vertexA2Y, pVerticesB[b + Constants.VERTEX_INDEX_X], pVerticesB[b + Constants.VERTEX_INDEX_Y], pVerticesB[b + 2 + Constants.VERTEX_INDEX_X], pVerticesB[b + 2 + Constants.VERTEX_INDEX_Y])){ - return true; - } - } - /* Also check the 'around the corner of the array' line of B. */ - if(LineCollisionChecker.checkLineCollision(vertexA1X, vertexA1Y, vertexA2X, vertexA2Y, pVerticesB[pVerticesBLength - 2], pVerticesB[pVerticesBLength - 1], pVerticesB[Constants.VERTEX_INDEX_X], pVerticesB[Constants.VERTEX_INDEX_Y])){ - return true; - } - return false; - } + for(int b = pVerticesBLength - 4; b >= 0; b -= 2) { + if(LineCollisionChecker.checkLineCollision(vertexA1X, vertexA1Y, vertexA2X, vertexA2Y, pVerticesB[b + Constants.VERTEX_INDEX_X], pVerticesB[b + Constants.VERTEX_INDEX_Y], pVerticesB[b + 2 + Constants.VERTEX_INDEX_X], pVerticesB[b + 2 + Constants.VERTEX_INDEX_Y])){ + return true; + } + } + /* Also check the 'around the corner of the array' line of B. */ + if(LineCollisionChecker.checkLineCollision(vertexA1X, vertexA1Y, vertexA2X, vertexA2Y, pVerticesB[pVerticesBLength - 2], pVerticesB[pVerticesBLength - 1], pVerticesB[Constants.VERTEX_INDEX_X], pVerticesB[Constants.VERTEX_INDEX_Y])){ + return true; + } + return false; + } - public static boolean checkContains(final float[] pVertices, final int pVerticesLength, final float pX, final float pY) { - int edgeResultSum = 0; + public static boolean checkContains(final float[] pVertices, final int pVerticesLength, final float pX, final float pY) { + int edgeResultSum = 0; - for(int i = pVerticesLength - 4; i >= 0; i -= 2) { - final int edgeResult = BaseCollisionChecker.relativeCCW(pVertices[i], pVertices[i + 1], pVertices[i + 2], pVertices[i + 3], pX, pY); - if(edgeResult == 0) { - return true; - } else { - edgeResultSum += edgeResult; - } - } - /* Also check the 'around the corner of the array' line. */ - final int edgeResult = BaseCollisionChecker.relativeCCW(pVertices[pVerticesLength - 2], pVertices[pVerticesLength - 1], pVertices[Constants.VERTEX_INDEX_X], pVertices[Constants.VERTEX_INDEX_Y], pX, pY); - if(edgeResult == 0){ - return true; - } else { - edgeResultSum += edgeResult; - } + for(int i = pVerticesLength - 4; i >= 0; i -= 2) { + final int edgeResult = BaseCollisionChecker.relativeCCW(pVertices[i], pVertices[i + 1], pVertices[i + 2], pVertices[i + 3], pX, pY); + if(edgeResult == 0) { + return true; + } else { + edgeResultSum += edgeResult; + } + } + /* Also check the 'around the corner of the array' line. */ + final int edgeResult = BaseCollisionChecker.relativeCCW(pVertices[pVerticesLength - 2], pVertices[pVerticesLength - 1], pVertices[Constants.VERTEX_INDEX_X], pVertices[Constants.VERTEX_INDEX_Y], pX, pY); + if(edgeResult == 0){ + return true; + } else { + edgeResultSum += edgeResult; + } - final int vertexCount = pVerticesLength / 2; - /* Point is not on the edge, so check if the edge is on the same side(left or right) of all edges. */ - return edgeResultSum == vertexCount || edgeResultSum == -vertexCount ; - } + final int vertexCount = pVerticesLength / 2; + /* Point is not on the edge, so check if the edge is on the same side(left or right) of all edges. */ + return edgeResultSum == vertexCount || edgeResultSum == -vertexCount ; + } - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/engine/DoubleSceneSplitScreenEngine.java b/AndEngine/src/org/anddev/andengine/engine/DoubleSceneSplitScreenEngine.java index 892adb62..0c9bc886 100644 --- a/AndEngine/src/org/anddev/andengine/engine/DoubleSceneSplitScreenEngine.java +++ b/AndEngine/src/org/anddev/andengine/engine/DoubleSceneSplitScreenEngine.java @@ -16,167 +16,167 @@ * @since 22:28:34 - 27.03.2010 */ public class DoubleSceneSplitScreenEngine extends Engine { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - private Scene mSecondScene; - private final Camera mSecondCamera; - - // =========================================================== - // Constructors - // =========================================================== - - public DoubleSceneSplitScreenEngine(final EngineOptions pEngineOptions, final Camera pSecondCamera) { - super(pEngineOptions); - this.mSecondCamera = pSecondCamera; - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - @Deprecated - @Override - public Camera getCamera() { - return super.mCamera; - } - - public Camera getFirstCamera() { - return super.mCamera; - } - - public Camera getSecondCamera() { - return this.mSecondCamera; - } - - @Deprecated - @Override - public Scene getScene() { - return super.getScene(); - } - - public Scene getFirstScene() { - return super.getScene(); - } - - public Scene getSecondScene() { - return this.mSecondScene; - } - - @Deprecated - @Override - public void setScene(final Scene pScene) { - this.setFirstScene(pScene); - } - - public void setFirstScene(final Scene pScene) { - super.setScene(pScene); - } - - public void setSecondScene(final Scene pScene) { - this.mSecondScene = pScene; - } - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - protected void onDrawScene(final GL10 pGL) { - final Camera firstCamera = this.getFirstCamera(); - final Camera secondCamera = this.getSecondCamera(); - - final int surfaceWidth = this.mSurfaceWidth; - final int surfaceWidthHalf = surfaceWidth >> 1; - - final int surfaceHeight = this.mSurfaceHeight; - - GLHelper.enableScissorTest(pGL); - - /* First Screen. With first camera, on the left half of the screens width. */ - { - pGL.glScissor(0, 0, surfaceWidthHalf, surfaceHeight); - pGL.glViewport(0, 0, surfaceWidthHalf, surfaceHeight); - - super.mScene.onDraw(pGL, firstCamera); - firstCamera.onDrawHUD(pGL); - } - - /* Second Screen. With second camera, on the right half of the screens width. */ - { - pGL.glScissor(surfaceWidthHalf, 0, surfaceWidthHalf, surfaceHeight); - pGL.glViewport(surfaceWidthHalf, 0, surfaceWidthHalf, surfaceHeight); - - this.mSecondScene.onDraw(pGL, secondCamera); - secondCamera.onDrawHUD(pGL); - } - - GLHelper.disableScissorTest(pGL); - } - - @Override - protected Camera getCameraFromSurfaceTouchEvent(final TouchEvent pTouchEvent) { - if(pTouchEvent.getX() <= this.mSurfaceWidth >> 1) { - return this.getFirstCamera(); - } else { - return this.getSecondCamera(); - } - } - - @Override - protected Scene getSceneFromSurfaceTouchEvent(final TouchEvent pTouchEvent) { - if(pTouchEvent.getX() <= this.mSurfaceWidth >> 1) { - return this.getFirstScene(); - } else { - return this.getSecondScene(); - } - } - - @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) { - final int surfaceWidthHalf = this.mSurfaceWidth >> 1; - - if(pCamera == this.getFirstCamera()) { - pCamera.convertSurfaceToSceneTouchEvent(pSurfaceTouchEvent, surfaceWidthHalf, this.mSurfaceHeight); - } else { - pSurfaceTouchEvent.offset(-surfaceWidthHalf, 0); - pCamera.convertSurfaceToSceneTouchEvent(pSurfaceTouchEvent, surfaceWidthHalf, this.mSurfaceHeight); - } - } - - @Override - protected void updateUpdateHandlers(final float pSecondsElapsed) { - super.updateUpdateHandlers(pSecondsElapsed); - this.getSecondCamera().onUpdate(pSecondsElapsed); - } - - @Override - protected void onUpdateCameraSurface() { - final int surfaceWidth = this.mSurfaceWidth; - final int surfaceWidthHalf = surfaceWidth >> 1; - - this.getFirstCamera().setSurfaceSize(0, 0, surfaceWidthHalf, this.mSurfaceHeight); - this.getSecondCamera().setSurfaceSize(surfaceWidthHalf, 0, surfaceWidthHalf, this.mSurfaceHeight); - } - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + private Scene mSecondScene; + private final Camera mSecondCamera; + + // =========================================================== + // Constructors + // =========================================================== + + public DoubleSceneSplitScreenEngine(final EngineOptions pEngineOptions, final Camera pSecondCamera) { + super(pEngineOptions); + this.mSecondCamera = pSecondCamera; + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + @Deprecated + @Override + public Camera getCamera() { + return super.mCamera; + } + + public Camera getFirstCamera() { + return super.mCamera; + } + + public Camera getSecondCamera() { + return this.mSecondCamera; + } + + @Deprecated + @Override + public Scene getScene() { + return super.getScene(); + } + + public Scene getFirstScene() { + return super.getScene(); + } + + public Scene getSecondScene() { + return this.mSecondScene; + } + + @Deprecated + @Override + public void setScene(final Scene pScene) { + this.setFirstScene(pScene); + } + + public void setFirstScene(final Scene pScene) { + super.setScene(pScene); + } + + public void setSecondScene(final Scene pScene) { + this.mSecondScene = pScene; + } + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + protected void onDrawScene(final GL10 pGL) { + final Camera firstCamera = this.getFirstCamera(); + final Camera secondCamera = this.getSecondCamera(); + + final int surfaceWidth = this.mSurfaceWidth; + final int surfaceWidthHalf = surfaceWidth >> 1; + + final int surfaceHeight = this.mSurfaceHeight; + + GLHelper.enableScissorTest(pGL); + + /* First Screen. With first camera, on the left half of the screens width. */ + { + pGL.glScissor(0, 0, surfaceWidthHalf, surfaceHeight); + pGL.glViewport(0, 0, surfaceWidthHalf, surfaceHeight); + + super.mScene.onDraw(pGL, firstCamera); + firstCamera.onDrawHUD(pGL); + } + + /* Second Screen. With second camera, on the right half of the screens width. */ + { + pGL.glScissor(surfaceWidthHalf, 0, surfaceWidthHalf, surfaceHeight); + pGL.glViewport(surfaceWidthHalf, 0, surfaceWidthHalf, surfaceHeight); + + this.mSecondScene.onDraw(pGL, secondCamera); + secondCamera.onDrawHUD(pGL); + } + + GLHelper.disableScissorTest(pGL); + } + + @Override + protected Camera getCameraFromSurfaceTouchEvent(final TouchEvent pTouchEvent) { + if(pTouchEvent.getX() <= this.mSurfaceWidth >> 1) { + return this.getFirstCamera(); + } else { + return this.getSecondCamera(); + } + } + + @Override + protected Scene getSceneFromSurfaceTouchEvent(final TouchEvent pTouchEvent) { + if(pTouchEvent.getX() <= this.mSurfaceWidth >> 1) { + return this.getFirstScene(); + } else { + return this.getSecondScene(); + } + } + + @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) { + final int surfaceWidthHalf = this.mSurfaceWidth >> 1; + + if(pCamera == this.getFirstCamera()) { + pCamera.convertSurfaceToSceneTouchEvent(pSurfaceTouchEvent, surfaceWidthHalf, this.mSurfaceHeight); + } else { + pSurfaceTouchEvent.offset(-surfaceWidthHalf, 0); + pCamera.convertSurfaceToSceneTouchEvent(pSurfaceTouchEvent, surfaceWidthHalf, this.mSurfaceHeight); + } + } + + @Override + protected void updateUpdateHandlers(final float pSecondsElapsed) { + super.updateUpdateHandlers(pSecondsElapsed); + this.getSecondCamera().onUpdate(pSecondsElapsed); + } + + @Override + protected void onUpdateCameraSurface() { + final int surfaceWidth = this.mSurfaceWidth; + final int surfaceWidthHalf = surfaceWidth >> 1; + + this.getFirstCamera().setSurfaceSize(0, 0, surfaceWidthHalf, this.mSurfaceHeight); + this.getSecondCamera().setSurfaceSize(surfaceWidthHalf, 0, surfaceWidthHalf, this.mSurfaceHeight); + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/engine/Engine.java b/AndEngine/src/org/anddev/andengine/engine/Engine.java index f6a7985f..14f2cd68 100644 --- a/AndEngine/src/org/anddev/andengine/engine/Engine.java +++ b/AndEngine/src/org/anddev/andengine/engine/Engine.java @@ -62,538 +62,538 @@ * @since 12:21:31 - 08.03.2010 */ public class Engine implements SensorEventListener, OnTouchListener, ITouchEventCallback, TimeConstants, LocationListener { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - private static final SensorDelay SENSORDELAY_DEFAULT = SensorDelay.GAME; - private static final int UPDATEHANDLERS_CAPACITY_DEFAULT = 32; + private static final SensorDelay SENSORDELAY_DEFAULT = SensorDelay.GAME; + private static final int UPDATEHANDLERS_CAPACITY_DEFAULT = 32; - public static int INPUT_PAUSE_DURATION = 0; + public static int INPUT_PAUSE_DURATION = 0; - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - private boolean mRunning = false; + private boolean mRunning = false; - private long mLastTick = -1; - private float mSecondsElapsedTotal = 0; + private long mLastTick = -1; + private float mSecondsElapsedTotal = 0; - private final State mThreadLocker = new State(); + private final State mThreadLocker = new State(); - private final UpdateThread mUpdateThread = new UpdateThread(); + private final UpdateThread mUpdateThread = new UpdateThread(); - private final RunnableHandler mUpdateThreadRunnableHandler = new RunnableHandler(); + private final RunnableHandler mUpdateThreadRunnableHandler = new RunnableHandler(); - private final EngineOptions mEngineOptions; - protected final Camera mCamera; + private final EngineOptions mEngineOptions; + protected final Camera mCamera; - private ITouchController mTouchController; + private ITouchController mTouchController; - private SoundManager mSoundManager; - private MusicManager mMusicManager; - private final TextureManager mTextureManager = new TextureManager(); - private final BufferObjectManager mBufferObjectManager = new BufferObjectManager(); - private final FontManager mFontManager = new FontManager(); + private SoundManager mSoundManager; + private MusicManager mMusicManager; + private final TextureManager mTextureManager = new TextureManager(); + private final BufferObjectManager mBufferObjectManager = new BufferObjectManager(); + private final FontManager mFontManager = new FontManager(); - protected Scene mScene; + protected Scene mScene; - private Vibrator mVibrator; + private Vibrator mVibrator; - private ILocationListener mLocationListener; - private Location mLocation; + private ILocationListener mLocationListener; + private Location mLocation; - private IAccelerometerListener mAccelerometerListener; - private AccelerometerData mAccelerometerData; + private IAccelerometerListener mAccelerometerListener; + private AccelerometerData mAccelerometerData; - private IOrientationListener mOrientationListener; - private OrientationData mOrientationData; + private IOrientationListener mOrientationListener; + private OrientationData mOrientationData; - private final UpdateHandlerList mUpdateHandlers = new UpdateHandlerList(UPDATEHANDLERS_CAPACITY_DEFAULT); + private final UpdateHandlerList mUpdateHandlers = new UpdateHandlerList(UPDATEHANDLERS_CAPACITY_DEFAULT); - protected int mSurfaceWidth = 1; // 1 to prevent accidental DIV/0 - protected int mSurfaceHeight = 1; // 1 to prevent accidental DIV/0 + protected int mSurfaceWidth = 1; // 1 to prevent accidental DIV/0 + protected int mSurfaceHeight = 1; // 1 to prevent accidental DIV/0 - private boolean mIsMethodTracing; + private boolean mIsMethodTracing; - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - public Engine(final EngineOptions pEngineOptions) { - BitmapTextureAtlasTextureRegionFactory.reset(); - SoundFactory.reset(); - MusicFactory.reset(); - FontFactory.reset(); + public Engine(final EngineOptions pEngineOptions) { + BitmapTextureAtlasTextureRegionFactory.reset(); + SoundFactory.reset(); + MusicFactory.reset(); + FontFactory.reset(); - BufferObjectManager.setActiveInstance(this.mBufferObjectManager); + BufferObjectManager.setActiveInstance(this.mBufferObjectManager); - this.mEngineOptions = pEngineOptions; - this.setTouchController(new SingleTouchControler()); - this.mCamera = pEngineOptions.getCamera(); + this.mEngineOptions = pEngineOptions; + this.setTouchController(new SingleTouchControler()); + this.mCamera = pEngineOptions.getCamera(); - if(this.mEngineOptions.needsSound()) { - this.mSoundManager = new SoundManager(); - } + if(this.mEngineOptions.needsSound()) { + this.mSoundManager = new SoundManager(); + } - if(this.mEngineOptions.needsMusic()) { - this.mMusicManager = new MusicManager(); - } + if(this.mEngineOptions.needsMusic()) { + this.mMusicManager = new MusicManager(); + } - this.mUpdateThread.start(); - } + this.mUpdateThread.start(); + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - public boolean isRunning() { - return this.mRunning; - } + public boolean isRunning() { + return this.mRunning; + } - public synchronized void start() { - if(!this.mRunning) { - this.mLastTick = System.nanoTime(); - this.mRunning = true; - } - } + public synchronized void start() { + if(!this.mRunning) { + this.mLastTick = System.nanoTime(); + this.mRunning = true; + } + } - public synchronized void stop() { - if(this.mRunning) { - this.mRunning = false; - } - } + public synchronized void stop() { + if(this.mRunning) { + this.mRunning = false; + } + } - public Scene getScene() { - return this.mScene; - } + public Scene getScene() { + return this.mScene; + } - public void setScene(final Scene pScene) { - this.mScene = pScene; - } + public void setScene(final Scene pScene) { + this.mScene = pScene; + } - public EngineOptions getEngineOptions() { - return this.mEngineOptions; - } + public EngineOptions getEngineOptions() { + return this.mEngineOptions; + } + + public Camera getCamera() { + return this.mCamera; + } + + public float getSecondsElapsedTotal() { + return this.mSecondsElapsedTotal; + } + + public void setSurfaceSize(final int pSurfaceWidth, final int pSurfaceHeight) { + // Debug.w("SurfaceView size changed to (width x height): " + pSurfaceWidth + " x " + pSurfaceHeight, new Exception()); + this.mSurfaceWidth = pSurfaceWidth; + this.mSurfaceHeight = pSurfaceHeight; + this.onUpdateCameraSurface(); + } + + protected void onUpdateCameraSurface() { + this.mCamera.setSurfaceSize(0, 0, this.mSurfaceWidth, this.mSurfaceHeight); + } + + public int getSurfaceWidth() { + return this.mSurfaceWidth; + } + + public int getSurfaceHeight() { + return this.mSurfaceHeight; + } + + public ITouchController getTouchController() { + return this.mTouchController; + } + + public void setTouchController(final ITouchController pTouchController) { + this.mTouchController = pTouchController; + this.mTouchController.applyTouchOptions(this.mEngineOptions.getTouchOptions()); + this.mTouchController.setTouchEventCallback(this); + } + + public AccelerometerData getAccelerometerData() { + return this.mAccelerometerData; + } + + public OrientationData getOrientationData() { + return this.mOrientationData; + } + + public SoundManager getSoundManager() throws IllegalStateException { + if(this.mSoundManager != null) { + return this.mSoundManager; + } else { + throw new IllegalStateException("To enable the SoundManager, check the EngineOptions!"); + } + } + + public MusicManager getMusicManager() throws IllegalStateException { + if(this.mMusicManager != null) { + return this.mMusicManager; + } else { + throw new IllegalStateException("To enable the MusicManager, check the EngineOptions!"); + } + } + + public TextureManager getTextureManager() { + return this.mTextureManager; + } + + public FontManager getFontManager() { + return this.mFontManager; + } + + public void clearUpdateHandlers() { + this.mUpdateHandlers.clear(); + } + + public void registerUpdateHandler(final IUpdateHandler pUpdateHandler) { + this.mUpdateHandlers.add(pUpdateHandler); + } + + public void unregisterUpdateHandler(final IUpdateHandler pUpdateHandler) { + this.mUpdateHandlers.remove(pUpdateHandler); + } + + public boolean isMethodTracing() { + return this.mIsMethodTracing; + } + + public void startMethodTracing(final String pTraceFileName) { + if(!this.mIsMethodTracing) { + this.mIsMethodTracing = true; + android.os.Debug.startMethodTracing(pTraceFileName); + } + } + + public void stopMethodTracing() { + if(this.mIsMethodTracing) { + android.os.Debug.stopMethodTracing(); + this.mIsMethodTracing = false; + } + } + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + public void onAccuracyChanged(final Sensor pSensor, final int pAccuracy) { + if(this.mRunning) { + switch(pSensor.getType()) { + case Sensor.TYPE_ACCELEROMETER: + if(this.mAccelerometerData != null) { + this.mAccelerometerData.setAccuracy(pAccuracy); + this.mAccelerometerListener.onAccelerometerChanged(this.mAccelerometerData); + } else if(this.mOrientationData != null) { + this.mOrientationData.setAccelerometerAccuracy(pAccuracy); + this.mOrientationListener.onOrientationChanged(this.mOrientationData); + } + break; + case Sensor.TYPE_MAGNETIC_FIELD: + this.mOrientationData.setMagneticFieldAccuracy(pAccuracy); + this.mOrientationListener.onOrientationChanged(this.mOrientationData); + break; + } + } + } + + @Override + public void onSensorChanged(final SensorEvent pEvent) { + if(this.mRunning) { + switch(pEvent.sensor.getType()) { + case Sensor.TYPE_ACCELEROMETER: + if(this.mAccelerometerData != null) { + this.mAccelerometerData.setValues(pEvent.values); + this.mAccelerometerListener.onAccelerometerChanged(this.mAccelerometerData); + } else if(this.mOrientationData != null) { + this.mOrientationData.setAccelerometerValues(pEvent.values); + this.mOrientationListener.onOrientationChanged(this.mOrientationData); + } + break; + case Sensor.TYPE_MAGNETIC_FIELD: + this.mOrientationData.setMagneticFieldValues(pEvent.values); + this.mOrientationListener.onOrientationChanged(this.mOrientationData); + break; + } + } + } + + @Override + public void onLocationChanged(final Location pLocation) { + if(this.mLocation == null) { + this.mLocation = pLocation; + } else { + if(pLocation == null) { + this.mLocationListener.onLocationLost(); + } else { + this.mLocation = pLocation; + this.mLocationListener.onLocationChanged(pLocation); + } + } + } + + @Override + public void onProviderDisabled(final String pProvider) { + this.mLocationListener.onLocationProviderDisabled(); + } + + @Override + public void onProviderEnabled(final String pProvider) { + this.mLocationListener.onLocationProviderEnabled(); + } + + @Override + public void onStatusChanged(final String pProvider, final int pStatus, final Bundle pExtras) { + switch(pStatus) { + case LocationProvider.AVAILABLE: + this.mLocationListener.onLocationProviderStatusChanged(LocationProviderStatus.AVAILABLE, pExtras); + break; + case LocationProvider.OUT_OF_SERVICE: + this.mLocationListener.onLocationProviderStatusChanged(LocationProviderStatus.OUT_OF_SERVICE, pExtras); + break; + case LocationProvider.TEMPORARILY_UNAVAILABLE: + this.mLocationListener.onLocationProviderStatusChanged(LocationProviderStatus.TEMPORARILY_UNAVAILABLE, pExtras); + break; + } + } + + @SuppressLint("ClickableViewAccessibility") + @Override + public boolean onTouch(final View pView, final MotionEvent pSurfaceMotionEvent) { + if(this.mRunning) { + final boolean handled = this.mTouchController.onHandleMotionEvent(pSurfaceMotionEvent); + try { + /* + * As a human cannot interact 1000x per second, we pause the + * UI-Thread for a little. + */ + if (INPUT_PAUSE_DURATION != 0) { + Thread.sleep(INPUT_PAUSE_DURATION); + } + // TODO Maybe this can be removed, when TouchEvents are handled on the UpdateThread!} + } catch (final InterruptedException e) { + Debug.e(e); + } + return handled; + } else { + return false; + } + } - public Camera getCamera() { - return this.mCamera; - } - - public float getSecondsElapsedTotal() { - return this.mSecondsElapsedTotal; - } - - public void setSurfaceSize(final int pSurfaceWidth, final int pSurfaceHeight) { - // Debug.w("SurfaceView size changed to (width x height): " + pSurfaceWidth + " x " + pSurfaceHeight, new Exception()); - this.mSurfaceWidth = pSurfaceWidth; - this.mSurfaceHeight = pSurfaceHeight; - this.onUpdateCameraSurface(); - } - - protected void onUpdateCameraSurface() { - this.mCamera.setSurfaceSize(0, 0, this.mSurfaceWidth, this.mSurfaceHeight); - } - - public int getSurfaceWidth() { - return this.mSurfaceWidth; - } - - public int getSurfaceHeight() { - return this.mSurfaceHeight; - } - - public ITouchController getTouchController() { - return this.mTouchController; - } - - public void setTouchController(final ITouchController pTouchController) { - this.mTouchController = pTouchController; - this.mTouchController.applyTouchOptions(this.mEngineOptions.getTouchOptions()); - this.mTouchController.setTouchEventCallback(this); - } - - public AccelerometerData getAccelerometerData() { - return this.mAccelerometerData; - } - - public OrientationData getOrientationData() { - return this.mOrientationData; - } - - public SoundManager getSoundManager() throws IllegalStateException { - if(this.mSoundManager != null) { - return this.mSoundManager; - } else { - throw new IllegalStateException("To enable the SoundManager, check the EngineOptions!"); - } - } - - public MusicManager getMusicManager() throws IllegalStateException { - if(this.mMusicManager != null) { - return this.mMusicManager; - } else { - throw new IllegalStateException("To enable the MusicManager, check the EngineOptions!"); - } - } - - public TextureManager getTextureManager() { - return this.mTextureManager; - } - - public FontManager getFontManager() { - return this.mFontManager; - } - - public void clearUpdateHandlers() { - this.mUpdateHandlers.clear(); - } - - public void registerUpdateHandler(final IUpdateHandler pUpdateHandler) { - this.mUpdateHandlers.add(pUpdateHandler); - } - - public void unregisterUpdateHandler(final IUpdateHandler pUpdateHandler) { - this.mUpdateHandlers.remove(pUpdateHandler); - } - - public boolean isMethodTracing() { - return this.mIsMethodTracing; - } - - public void startMethodTracing(final String pTraceFileName) { - if(!this.mIsMethodTracing) { - this.mIsMethodTracing = true; - android.os.Debug.startMethodTracing(pTraceFileName); - } - } - - public void stopMethodTracing() { - if(this.mIsMethodTracing) { - android.os.Debug.stopMethodTracing(); - this.mIsMethodTracing = false; - } - } - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - public void onAccuracyChanged(final Sensor pSensor, final int pAccuracy) { - if(this.mRunning) { - switch(pSensor.getType()) { - case Sensor.TYPE_ACCELEROMETER: - if(this.mAccelerometerData != null) { - this.mAccelerometerData.setAccuracy(pAccuracy); - this.mAccelerometerListener.onAccelerometerChanged(this.mAccelerometerData); - } else if(this.mOrientationData != null) { - this.mOrientationData.setAccelerometerAccuracy(pAccuracy); - this.mOrientationListener.onOrientationChanged(this.mOrientationData); - } - break; - case Sensor.TYPE_MAGNETIC_FIELD: - this.mOrientationData.setMagneticFieldAccuracy(pAccuracy); - this.mOrientationListener.onOrientationChanged(this.mOrientationData); - break; - } - } - } - - @Override - public void onSensorChanged(final SensorEvent pEvent) { - if(this.mRunning) { - switch(pEvent.sensor.getType()) { - case Sensor.TYPE_ACCELEROMETER: - if(this.mAccelerometerData != null) { - this.mAccelerometerData.setValues(pEvent.values); - this.mAccelerometerListener.onAccelerometerChanged(this.mAccelerometerData); - } else if(this.mOrientationData != null) { - this.mOrientationData.setAccelerometerValues(pEvent.values); - this.mOrientationListener.onOrientationChanged(this.mOrientationData); - } - break; - case Sensor.TYPE_MAGNETIC_FIELD: - this.mOrientationData.setMagneticFieldValues(pEvent.values); - this.mOrientationListener.onOrientationChanged(this.mOrientationData); - break; - } - } - } - - @Override - public void onLocationChanged(final Location pLocation) { - if(this.mLocation == null) { - this.mLocation = pLocation; - } else { - if(pLocation == null) { - this.mLocationListener.onLocationLost(); - } else { - this.mLocation = pLocation; - this.mLocationListener.onLocationChanged(pLocation); - } - } - } - - @Override - public void onProviderDisabled(final String pProvider) { - this.mLocationListener.onLocationProviderDisabled(); - } - - @Override - public void onProviderEnabled(final String pProvider) { - this.mLocationListener.onLocationProviderEnabled(); - } - - @Override - public void onStatusChanged(final String pProvider, final int pStatus, final Bundle pExtras) { - switch(pStatus) { - case LocationProvider.AVAILABLE: - this.mLocationListener.onLocationProviderStatusChanged(LocationProviderStatus.AVAILABLE, pExtras); - break; - case LocationProvider.OUT_OF_SERVICE: - this.mLocationListener.onLocationProviderStatusChanged(LocationProviderStatus.OUT_OF_SERVICE, pExtras); - break; - case LocationProvider.TEMPORARILY_UNAVAILABLE: - this.mLocationListener.onLocationProviderStatusChanged(LocationProviderStatus.TEMPORARILY_UNAVAILABLE, pExtras); - break; - } - } - - @SuppressLint("ClickableViewAccessibility") @Override - public boolean onTouch(final View pView, final MotionEvent pSurfaceMotionEvent) { - if(this.mRunning) { - final boolean handled = this.mTouchController.onHandleMotionEvent(pSurfaceMotionEvent); - try { - /* - * As a human cannot interact 1000x per second, we pause the - * UI-Thread for a little. - */ - if (INPUT_PAUSE_DURATION != 0) { - Thread.sleep(INPUT_PAUSE_DURATION); - } - // TODO Maybe this can be removed, when TouchEvents are handled on the UpdateThread!} - } catch (final InterruptedException e) { - Debug.e(e); - } - return handled; - } else { - return false; - } - } - - @Override - public boolean onTouchEvent(final TouchEvent pSurfaceTouchEvent) { - /* - * 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); - - if(this.onTouchHUD(camera, pSurfaceTouchEvent)) { - return true; - } else { - /* If HUD didn't handle it, Scene may handle it. */ - return this.onTouchScene(scene, pSurfaceTouchEvent); - } - } - - protected boolean onTouchHUD(final Camera pCamera, final TouchEvent pSceneTouchEvent) { - if(pCamera.hasHUD()) { - return pCamera.getHUD().onSceneTouchEvent(pSceneTouchEvent); - } else { - return false; - } - } - - protected boolean onTouchScene(final Scene pScene, final TouchEvent pSceneTouchEvent) { - if(pScene != null) { - return pScene.onSceneTouchEvent(pSceneTouchEvent); - } else { - return false; - } - } - - // =========================================================== - // Methods - // =========================================================== - - public void runOnUpdateThread(final Runnable pRunnable) { - this.mUpdateThreadRunnableHandler.postRunnable(pRunnable); - } - - public void interruptUpdateThread(){ - this.mUpdateThread.interrupt(); - } - - public void onResume() { - // TODO GLHelper.reset(pGL); ? - this.mTextureManager.reloadTextures(); - this.mFontManager.reloadFonts(); - BufferObjectManager.setActiveInstance(this.mBufferObjectManager); - this.mBufferObjectManager.reloadBufferObjects(); - } - - public void onPause() { - - } - - protected Camera getCameraFromSurfaceTouchEvent(@SuppressWarnings("unused") final TouchEvent pTouchEvent) { - return this.getCamera(); - } - - protected Scene getSceneFromSurfaceTouchEvent(@SuppressWarnings("unused") final TouchEvent pTouchEvent) { - return this.mScene; - } - - protected void convertSurfaceToSceneTouchEvent(final Camera pCamera, final TouchEvent pSurfaceTouchEvent) { - pCamera.convertSurfaceToSceneTouchEvent(pSurfaceTouchEvent, this.mSurfaceWidth, this.mSurfaceHeight); - } - - protected void convertSceneToSurfaceTouchEvent(final Camera pCamera, final TouchEvent pSurfaceTouchEvent) { - pCamera.convertSceneToSurfaceTouchEvent(pSurfaceTouchEvent, this.mSurfaceWidth, this.mSurfaceHeight); - } - - public void onLoadComplete(final Scene pScene) { - this.setScene(pScene); - } - - void onTickUpdate() throws InterruptedException { - if(this.mRunning) { - final long secondsElapsed = this.getNanosecondsElapsed(); - - this.onUpdate(secondsElapsed); - - this.yieldDraw(); - } else { - this.yieldDraw(); - - Thread.sleep(16); - } - } - - private void yieldDraw() throws InterruptedException { - final State threadLocker = this.mThreadLocker; - threadLocker.notifyCanDraw(); - threadLocker.waitUntilCanUpdate(); - } - - protected void onUpdate(final long pNanosecondsElapsed) throws InterruptedException { - final float pSecondsElapsed = (float)pNanosecondsElapsed / TimeConstants.NANOSECONDSPERSECOND; - - this.mSecondsElapsedTotal += pSecondsElapsed; - this.mLastTick += pNanosecondsElapsed; - - this.mTouchController.onUpdate(pSecondsElapsed); - this.updateUpdateHandlers(pSecondsElapsed); - this.onUpdateScene(pSecondsElapsed); - } - - protected void onUpdateScene(final float pSecondsElapsed) { - if(this.mScene != null) { - this.mScene.onUpdate(pSecondsElapsed); - } - } - - protected void updateUpdateHandlers(final float pSecondsElapsed) { - this.mUpdateThreadRunnableHandler.onUpdate(pSecondsElapsed); - this.mUpdateHandlers.onUpdate(pSecondsElapsed); - this.getCamera().onUpdate(pSecondsElapsed); - } - - public void onDrawFrame(final GL10 pGL) throws InterruptedException { - final State threadLocker = this.mThreadLocker; - - threadLocker.waitUntilCanDraw(); - - this.mTextureManager.updateTextures(pGL); - this.mFontManager.updateFonts(pGL); - if(GLHelper.EXTENSIONS_VERTEXBUFFEROBJECTS) { - this.mBufferObjectManager.updateBufferObjects((GL11) pGL); - } - - this.onDrawScene(pGL); - - threadLocker.notifyCanUpdate(); - } - - protected void onDrawScene(final GL10 pGL) { - final Camera camera = this.getCamera(); - - this.mScene.onDraw(pGL, camera); - - camera.onDrawHUD(pGL); - } - - private long getNanosecondsElapsed() { - final long now = System.nanoTime(); - - return this.calculateNanosecondsElapsed(now, this.mLastTick); - } - - protected long calculateNanosecondsElapsed(final long pNow, final long pLastTick) { - return pNow - pLastTick; - } - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== - - private class UpdateThread extends Thread { - public UpdateThread() { - super("UpdateThread"); - } - - @Override - public void run() { - android.os.Process.setThreadPriority(Engine.this.mEngineOptions.getUpdateThreadPriority()); - try { - while(true) { - Engine.this.onTickUpdate(); - } - } catch (final InterruptedException e) { - Debug.d("UpdateThread interrupted. Don't worry - this Exception is most likely expected!", e); - this.interrupt(); - } - } - } - - private static class State { - boolean mDrawing = false; - - public synchronized void notifyCanDraw() { - // Debug.d(">>> notifyCanDraw"); - this.mDrawing = true; - this.notifyAll(); - // Debug.d("<<< notifyCanDraw"); - } - - public synchronized void notifyCanUpdate() { - // Debug.d(">>> notifyCanUpdate"); - this.mDrawing = false; - this.notifyAll(); - // Debug.d("<<< notifyCanUpdate"); - } - - public synchronized void waitUntilCanDraw() throws InterruptedException { - // Debug.d(">>> waitUntilCanDraw"); - while(!this.mDrawing) { - this.wait(); - } - // Debug.d("<<< waitUntilCanDraw"); - } - - public synchronized void waitUntilCanUpdate() throws InterruptedException { - // Debug.d(">>> waitUntilCanUpdate"); - while(this.mDrawing) { - this.wait(); - } - // Debug.d("<<< waitUntilCanUpdate"); - } - } + public boolean onTouchEvent(final TouchEvent pSurfaceTouchEvent) { + /* + * 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); + + if(this.onTouchHUD(camera, pSurfaceTouchEvent)) { + return true; + } else { + /* If HUD didn't handle it, Scene may handle it. */ + return this.onTouchScene(scene, pSurfaceTouchEvent); + } + } + + protected boolean onTouchHUD(final Camera pCamera, final TouchEvent pSceneTouchEvent) { + if(pCamera.hasHUD()) { + return pCamera.getHUD().onSceneTouchEvent(pSceneTouchEvent); + } else { + return false; + } + } + + protected boolean onTouchScene(final Scene pScene, final TouchEvent pSceneTouchEvent) { + if(pScene != null) { + return pScene.onSceneTouchEvent(pSceneTouchEvent); + } else { + return false; + } + } + + // =========================================================== + // Methods + // =========================================================== + + public void runOnUpdateThread(final Runnable pRunnable) { + this.mUpdateThreadRunnableHandler.postRunnable(pRunnable); + } + + public void interruptUpdateThread(){ + this.mUpdateThread.interrupt(); + } + + public void onResume() { + // TODO GLHelper.reset(pGL); ? + this.mTextureManager.reloadTextures(); + this.mFontManager.reloadFonts(); + BufferObjectManager.setActiveInstance(this.mBufferObjectManager); + this.mBufferObjectManager.reloadBufferObjects(); + } + + public void onPause() { + + } + + protected Camera getCameraFromSurfaceTouchEvent(@SuppressWarnings("unused") final TouchEvent pTouchEvent) { + return this.getCamera(); + } + + protected Scene getSceneFromSurfaceTouchEvent(@SuppressWarnings("unused") final TouchEvent pTouchEvent) { + return this.mScene; + } + + protected void convertSurfaceToSceneTouchEvent(final Camera pCamera, final TouchEvent pSurfaceTouchEvent) { + pCamera.convertSurfaceToSceneTouchEvent(pSurfaceTouchEvent, this.mSurfaceWidth, this.mSurfaceHeight); + } + + protected void convertSceneToSurfaceTouchEvent(final Camera pCamera, final TouchEvent pSurfaceTouchEvent) { + pCamera.convertSceneToSurfaceTouchEvent(pSurfaceTouchEvent, this.mSurfaceWidth, this.mSurfaceHeight); + } + + public void onLoadComplete(final Scene pScene) { + this.setScene(pScene); + } + + void onTickUpdate() throws InterruptedException { + if(this.mRunning) { + final long secondsElapsed = this.getNanosecondsElapsed(); + + this.onUpdate(secondsElapsed); + + this.yieldDraw(); + } else { + this.yieldDraw(); + + Thread.sleep(16); + } + } + + private void yieldDraw() throws InterruptedException { + final State threadLocker = this.mThreadLocker; + threadLocker.notifyCanDraw(); + threadLocker.waitUntilCanUpdate(); + } + + protected void onUpdate(final long pNanosecondsElapsed) throws InterruptedException { + final float pSecondsElapsed = (float)pNanosecondsElapsed / TimeConstants.NANOSECONDSPERSECOND; + + this.mSecondsElapsedTotal += pSecondsElapsed; + this.mLastTick += pNanosecondsElapsed; + + this.mTouchController.onUpdate(pSecondsElapsed); + this.updateUpdateHandlers(pSecondsElapsed); + this.onUpdateScene(pSecondsElapsed); + } + + protected void onUpdateScene(final float pSecondsElapsed) { + if(this.mScene != null) { + this.mScene.onUpdate(pSecondsElapsed); + } + } + + protected void updateUpdateHandlers(final float pSecondsElapsed) { + this.mUpdateThreadRunnableHandler.onUpdate(pSecondsElapsed); + this.mUpdateHandlers.onUpdate(pSecondsElapsed); + this.getCamera().onUpdate(pSecondsElapsed); + } + + public void onDrawFrame(final GL10 pGL) throws InterruptedException { + final State threadLocker = this.mThreadLocker; + + threadLocker.waitUntilCanDraw(); + + this.mTextureManager.updateTextures(pGL); + this.mFontManager.updateFonts(pGL); + if(GLHelper.EXTENSIONS_VERTEXBUFFEROBJECTS) { + this.mBufferObjectManager.updateBufferObjects((GL11) pGL); + } + + this.onDrawScene(pGL); + + threadLocker.notifyCanUpdate(); + } + + protected void onDrawScene(final GL10 pGL) { + final Camera camera = this.getCamera(); + + this.mScene.onDraw(pGL, camera); + + camera.onDrawHUD(pGL); + } + + private long getNanosecondsElapsed() { + final long now = System.nanoTime(); + + return this.calculateNanosecondsElapsed(now, this.mLastTick); + } + + protected long calculateNanosecondsElapsed(final long pNow, final long pLastTick) { + return pNow - pLastTick; + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== + + private class UpdateThread extends Thread { + public UpdateThread() { + super("UpdateThread"); + } + + @Override + public void run() { + android.os.Process.setThreadPriority(Engine.this.mEngineOptions.getUpdateThreadPriority()); + try { + while(true) { + Engine.this.onTickUpdate(); + } + } catch (final InterruptedException e) { + Debug.d("UpdateThread interrupted. Don't worry - this Exception is most likely expected!", e); + this.interrupt(); + } + } + } + + private static class State { + boolean mDrawing = false; + + public synchronized void notifyCanDraw() { + // Debug.d(">>> notifyCanDraw"); + this.mDrawing = true; + this.notifyAll(); + // Debug.d("<<< notifyCanDraw"); + } + + public synchronized void notifyCanUpdate() { + // Debug.d(">>> notifyCanUpdate"); + this.mDrawing = false; + this.notifyAll(); + // Debug.d("<<< notifyCanUpdate"); + } + + public synchronized void waitUntilCanDraw() throws InterruptedException { + // Debug.d(">>> waitUntilCanDraw"); + while(!this.mDrawing) { + this.wait(); + } + // Debug.d("<<< waitUntilCanDraw"); + } + + public synchronized void waitUntilCanUpdate() throws InterruptedException { + // Debug.d(">>> waitUntilCanUpdate"); + while(this.mDrawing) { + this.wait(); + } + // Debug.d("<<< waitUntilCanUpdate"); + } + } } diff --git a/AndEngine/src/org/anddev/andengine/engine/FixedStepEngine.java b/AndEngine/src/org/anddev/andengine/engine/FixedStepEngine.java index 9b6555a4..81adc421 100644 --- a/AndEngine/src/org/anddev/andengine/engine/FixedStepEngine.java +++ b/AndEngine/src/org/anddev/andengine/engine/FixedStepEngine.java @@ -14,50 +14,50 @@ * @since 10:17:47 - 02.08.2010 */ public class FixedStepEngine extends Engine { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - private final long mStepLength; - private long mSecondsElapsedAccumulator; - - // =========================================================== - // Constructors - // =========================================================== - - public FixedStepEngine(final EngineOptions pEngineOptions, final int pStepsPerSecond) { - super(pEngineOptions); - this.mStepLength = NANOSECONDSPERSECOND / pStepsPerSecond; - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - public void onUpdate(final long pNanosecondsElapsed) throws InterruptedException { - this.mSecondsElapsedAccumulator += pNanosecondsElapsed; - - final long stepLength = this.mStepLength; - while(this.mSecondsElapsedAccumulator >= stepLength) { - super.onUpdate(stepLength); - this.mSecondsElapsedAccumulator -= stepLength; - } - } - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + private final long mStepLength; + private long mSecondsElapsedAccumulator; + + // =========================================================== + // Constructors + // =========================================================== + + public FixedStepEngine(final EngineOptions pEngineOptions, final int pStepsPerSecond) { + super(pEngineOptions); + this.mStepLength = NANOSECONDSPERSECOND / pStepsPerSecond; + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + public void onUpdate(final long pNanosecondsElapsed) throws InterruptedException { + this.mSecondsElapsedAccumulator += pNanosecondsElapsed; + + final long stepLength = this.mStepLength; + while(this.mSecondsElapsedAccumulator >= stepLength) { + super.onUpdate(stepLength); + this.mSecondsElapsedAccumulator -= stepLength; + } + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/engine/LimitedFPSEngine.java b/AndEngine/src/org/anddev/andengine/engine/LimitedFPSEngine.java index e6f8ecfb..31cb5596 100644 --- a/AndEngine/src/org/anddev/andengine/engine/LimitedFPSEngine.java +++ b/AndEngine/src/org/anddev/andengine/engine/LimitedFPSEngine.java @@ -14,53 +14,53 @@ * @since 10:17:47 - 02.08.2010 */ public class LimitedFPSEngine extends Engine { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - private final long mPreferredFrameLengthNanoseconds; + private final long mPreferredFrameLengthNanoseconds; - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - public LimitedFPSEngine(final EngineOptions pEngineOptions, final int pFramesPerSecond) { - super(pEngineOptions); - this.mPreferredFrameLengthNanoseconds = NANOSECONDSPERSECOND / pFramesPerSecond; - } + public LimitedFPSEngine(final EngineOptions pEngineOptions, final int pFramesPerSecond) { + super(pEngineOptions); + this.mPreferredFrameLengthNanoseconds = NANOSECONDSPERSECOND / pFramesPerSecond; + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - @Override - public void onUpdate(final long pNanosecondsElapsed) throws InterruptedException { - final long preferredFrameLengthNanoseconds = this.mPreferredFrameLengthNanoseconds; - final long deltaFrameLengthNanoseconds = preferredFrameLengthNanoseconds - pNanosecondsElapsed; + @Override + public void onUpdate(final long pNanosecondsElapsed) throws InterruptedException { + final long preferredFrameLengthNanoseconds = this.mPreferredFrameLengthNanoseconds; + final long deltaFrameLengthNanoseconds = preferredFrameLengthNanoseconds - pNanosecondsElapsed; - if(deltaFrameLengthNanoseconds <= 0) { - super.onUpdate(pNanosecondsElapsed); - } else { - final int sleepTimeMilliseconds = (int) (deltaFrameLengthNanoseconds / NANOSECONDSPERMILLISECOND); + if(deltaFrameLengthNanoseconds <= 0) { + super.onUpdate(pNanosecondsElapsed); + } else { + final int sleepTimeMilliseconds = (int) (deltaFrameLengthNanoseconds / NANOSECONDSPERMILLISECOND); - Thread.sleep(sleepTimeMilliseconds); - super.onUpdate(pNanosecondsElapsed + deltaFrameLengthNanoseconds); - } - } + Thread.sleep(sleepTimeMilliseconds); + super.onUpdate(pNanosecondsElapsed + deltaFrameLengthNanoseconds); + } + } - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/engine/SingleSceneSplitScreenEngine.java b/AndEngine/src/org/anddev/andengine/engine/SingleSceneSplitScreenEngine.java index 3b84f789..21b0b332 100644 --- a/AndEngine/src/org/anddev/andengine/engine/SingleSceneSplitScreenEngine.java +++ b/AndEngine/src/org/anddev/andengine/engine/SingleSceneSplitScreenEngine.java @@ -15,121 +15,121 @@ * @since 22:28:34 - 27.03.2010 */ public class SingleSceneSplitScreenEngine extends Engine { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - private final Camera mSecondCamera; - - // =========================================================== - // Constructors - // =========================================================== - - public SingleSceneSplitScreenEngine(final EngineOptions pEngineOptions, final Camera pSecondCamera) { - super(pEngineOptions); - this.mSecondCamera = pSecondCamera; - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - @Deprecated - @Override - public Camera getCamera() { - return super.mCamera; - } - - public Camera getFirstCamera() { - return super.mCamera; - } - - public Camera getSecondCamera() { - return this.mSecondCamera; - } - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - protected void onDrawScene(final GL10 pGL) { - final Camera firstCamera = this.getFirstCamera(); - final Camera secondCamera = this.getSecondCamera(); - - final int surfaceWidth = this.mSurfaceWidth; - final int surfaceWidthHalf = surfaceWidth >> 1; - - final int surfaceHeight = this.mSurfaceHeight; - - GLHelper.enableScissorTest(pGL); - - /* First Screen. With first camera, on the left half of the screens width. */ - { - pGL.glScissor(0, 0, surfaceWidthHalf, surfaceHeight); - pGL.glViewport(0, 0, surfaceWidthHalf, surfaceHeight); - - super.mScene.onDraw(pGL, firstCamera); - firstCamera.onDrawHUD(pGL); - } - - /* Second Screen. With second camera, on the right half of the screens width. */ - { - pGL.glScissor(surfaceWidthHalf, 0, surfaceWidthHalf, surfaceHeight); - pGL.glViewport(surfaceWidthHalf, 0, surfaceWidthHalf, surfaceHeight); - - super.mScene.onDraw(pGL, secondCamera); - secondCamera.onDrawHUD(pGL); - } - - GLHelper.disableScissorTest(pGL); - } - - @Override - protected Camera getCameraFromSurfaceTouchEvent(final TouchEvent pTouchEvent) { - if(pTouchEvent.getX() <= this.mSurfaceWidth >> 1) { - return this.getFirstCamera(); - } else { - return this.getSecondCamera(); - } - } - - @Override - protected void convertSurfaceToSceneTouchEvent(final Camera pCamera, final TouchEvent pSurfaceTouchEvent) { - final int surfaceWidthHalf = this.mSurfaceWidth >> 1; - - if(pCamera == this.getFirstCamera()) { - pCamera.convertSurfaceToSceneTouchEvent(pSurfaceTouchEvent, surfaceWidthHalf, this.mSurfaceHeight); - } else { - pSurfaceTouchEvent.offset(-surfaceWidthHalf, 0); - pCamera.convertSurfaceToSceneTouchEvent(pSurfaceTouchEvent, surfaceWidthHalf, this.mSurfaceHeight); - } - } - - @Override - protected void updateUpdateHandlers(final float pSecondsElapsed) { - super.updateUpdateHandlers(pSecondsElapsed); - this.getSecondCamera().onUpdate(pSecondsElapsed); - } - - @Override - protected void onUpdateCameraSurface() { - final int surfaceWidth = this.mSurfaceWidth; - final int surfaceWidthHalf = surfaceWidth >> 1; - - this.getFirstCamera().setSurfaceSize(0, 0, surfaceWidthHalf, this.mSurfaceHeight); - this.getSecondCamera().setSurfaceSize(surfaceWidthHalf, 0, surfaceWidthHalf, this.mSurfaceHeight); - } - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + private final Camera mSecondCamera; + + // =========================================================== + // Constructors + // =========================================================== + + public SingleSceneSplitScreenEngine(final EngineOptions pEngineOptions, final Camera pSecondCamera) { + super(pEngineOptions); + this.mSecondCamera = pSecondCamera; + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + @Deprecated + @Override + public Camera getCamera() { + return super.mCamera; + } + + public Camera getFirstCamera() { + return super.mCamera; + } + + public Camera getSecondCamera() { + return this.mSecondCamera; + } + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + protected void onDrawScene(final GL10 pGL) { + final Camera firstCamera = this.getFirstCamera(); + final Camera secondCamera = this.getSecondCamera(); + + final int surfaceWidth = this.mSurfaceWidth; + final int surfaceWidthHalf = surfaceWidth >> 1; + + final int surfaceHeight = this.mSurfaceHeight; + + GLHelper.enableScissorTest(pGL); + + /* First Screen. With first camera, on the left half of the screens width. */ + { + pGL.glScissor(0, 0, surfaceWidthHalf, surfaceHeight); + pGL.glViewport(0, 0, surfaceWidthHalf, surfaceHeight); + + super.mScene.onDraw(pGL, firstCamera); + firstCamera.onDrawHUD(pGL); + } + + /* Second Screen. With second camera, on the right half of the screens width. */ + { + pGL.glScissor(surfaceWidthHalf, 0, surfaceWidthHalf, surfaceHeight); + pGL.glViewport(surfaceWidthHalf, 0, surfaceWidthHalf, surfaceHeight); + + super.mScene.onDraw(pGL, secondCamera); + secondCamera.onDrawHUD(pGL); + } + + GLHelper.disableScissorTest(pGL); + } + + @Override + protected Camera getCameraFromSurfaceTouchEvent(final TouchEvent pTouchEvent) { + if(pTouchEvent.getX() <= this.mSurfaceWidth >> 1) { + return this.getFirstCamera(); + } else { + return this.getSecondCamera(); + } + } + + @Override + protected void convertSurfaceToSceneTouchEvent(final Camera pCamera, final TouchEvent pSurfaceTouchEvent) { + final int surfaceWidthHalf = this.mSurfaceWidth >> 1; + + if(pCamera == this.getFirstCamera()) { + pCamera.convertSurfaceToSceneTouchEvent(pSurfaceTouchEvent, surfaceWidthHalf, this.mSurfaceHeight); + } else { + pSurfaceTouchEvent.offset(-surfaceWidthHalf, 0); + pCamera.convertSurfaceToSceneTouchEvent(pSurfaceTouchEvent, surfaceWidthHalf, this.mSurfaceHeight); + } + } + + @Override + protected void updateUpdateHandlers(final float pSecondsElapsed) { + super.updateUpdateHandlers(pSecondsElapsed); + this.getSecondCamera().onUpdate(pSecondsElapsed); + } + + @Override + protected void onUpdateCameraSurface() { + final int surfaceWidth = this.mSurfaceWidth; + final int surfaceWidthHalf = surfaceWidth >> 1; + + this.getFirstCamera().setSurfaceSize(0, 0, surfaceWidthHalf, this.mSurfaceHeight); + this.getSecondCamera().setSurfaceSize(surfaceWidthHalf, 0, surfaceWidthHalf, this.mSurfaceHeight); + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/engine/camera/BoundCamera.java b/AndEngine/src/org/anddev/andengine/engine/camera/BoundCamera.java index 28d3f73e..c080028a 100644 --- a/AndEngine/src/org/anddev/andengine/engine/camera/BoundCamera.java +++ b/AndEngine/src/org/anddev/andengine/engine/camera/BoundCamera.java @@ -8,160 +8,160 @@ * @since 15:55:54 - 27.07.2010 */ public class BoundCamera extends Camera { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - protected boolean mBoundsEnabled; - - private float mBoundsMinX; - private float mBoundsMaxX; - private float mBoundsMinY; - private float mBoundsMaxY; - - private float mBoundsCenterX; - private float mBoundsCenterY; - - private float mBoundsWidth; - private float mBoundsHeight; - - // =========================================================== - // Constructors - // =========================================================== - - public BoundCamera(final float pX, final float pY, final float pWidth, final float pHeight) { - super(pX, pY, pWidth, pHeight); - } - - public BoundCamera(final float pX, final float pY, final float pWidth, final float pHeight, final float pBoundMinX, final float pBoundMaxX, final float pBoundMinY, final float pBoundMaxY) { - super(pX, pY, pWidth, pHeight); - this.setBounds(pBoundMinX, pBoundMaxX, pBoundMinY, pBoundMaxY); - this.mBoundsEnabled = true; - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - public boolean isBoundsEnabled() { - return this.mBoundsEnabled; - } - - public void setBoundsEnabled(final boolean pBoundsEnabled) { - this.mBoundsEnabled = pBoundsEnabled; - } - - public void setBounds(final float pBoundMinX, final float pBoundMaxX, final float pBoundMinY, final float pBoundMaxY) { - this.mBoundsMinX = pBoundMinX; - this.mBoundsMaxX = pBoundMaxX; - this.mBoundsMinY = pBoundMinY; - this.mBoundsMaxY = pBoundMaxY; - - this.mBoundsWidth = this.mBoundsMaxX - this.mBoundsMinX; - this.mBoundsHeight = this.mBoundsMaxY - this.mBoundsMinY; - - this.mBoundsCenterX = this.mBoundsMinX + this.mBoundsWidth * 0.5f; - this.mBoundsCenterY = this.mBoundsMinY + this.mBoundsHeight * 0.5f; - } - - public float getBoundsWidth() { - return this.mBoundsWidth; - } - - public float getBoundsHeight() { - return this.mBoundsHeight; - } - - @Override - public void setCenter(final float pCenterX, final float pCenterY) { - super.setCenter(pCenterX, pCenterY); - - if(this.mBoundsEnabled) { - this.ensureInBounds(); - } - } - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - // =========================================================== - // Methods - // =========================================================== - - protected void ensureInBounds() { - super.setCenter(this.determineBoundedX(), this.determineBoundedY()); - } - - private float determineBoundedX() { - if(this.mBoundsWidth < this.getWidth()) { - return this.mBoundsCenterX; - } else { - final float currentCenterX = this.getCenterX(); - - final float minXBoundExceededAmount = this.mBoundsMinX - this.getMinX(); - final boolean minXBoundExceeded = minXBoundExceededAmount > 0; - - final float maxXBoundExceededAmount = this.getMaxX() - this.mBoundsMaxX; - final boolean maxXBoundExceeded = maxXBoundExceededAmount > 0; - - if(minXBoundExceeded) { - if(maxXBoundExceeded) { - /* Min and max X exceeded. */ - return currentCenterX - maxXBoundExceededAmount + minXBoundExceededAmount; - } else { - /* Only min X exceeded. */ - return currentCenterX + minXBoundExceededAmount; - } - } else { - if(maxXBoundExceeded) { - /* Only max X exceeded. */ - return currentCenterX - maxXBoundExceededAmount; - } else { - /* Nothing exceeded. */ - return currentCenterX; - } - } - } - } - - private float determineBoundedY() { - if(this.mBoundsHeight < this.getHeight()) { - return this.mBoundsCenterY; - } else { - final float currentCenterY = this.getCenterY(); - - final float minYBoundExceededAmount = this.mBoundsMinY - this.getMinY(); - final boolean minYBoundExceeded = minYBoundExceededAmount > 0; - - final float maxYBoundExceededAmount = this.getMaxY() - this.mBoundsMaxY; - final boolean maxYBoundExceeded = maxYBoundExceededAmount > 0; - - if(minYBoundExceeded) { - if(maxYBoundExceeded) { - /* Min and max Y exceeded. */ - return currentCenterY - maxYBoundExceededAmount + minYBoundExceededAmount; - } else { - /* Only min Y exceeded. */ - return currentCenterY + minYBoundExceededAmount; - } - } else { - if(maxYBoundExceeded) { - /* Only max Y exceeded. */ - return currentCenterY - maxYBoundExceededAmount; - } else { - /* Nothing exceeded. */ - return currentCenterY; - } - } - } - } - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + protected boolean mBoundsEnabled; + + private float mBoundsMinX; + private float mBoundsMaxX; + private float mBoundsMinY; + private float mBoundsMaxY; + + private float mBoundsCenterX; + private float mBoundsCenterY; + + private float mBoundsWidth; + private float mBoundsHeight; + + // =========================================================== + // Constructors + // =========================================================== + + public BoundCamera(final float pX, final float pY, final float pWidth, final float pHeight) { + super(pX, pY, pWidth, pHeight); + } + + public BoundCamera(final float pX, final float pY, final float pWidth, final float pHeight, final float pBoundMinX, final float pBoundMaxX, final float pBoundMinY, final float pBoundMaxY) { + super(pX, pY, pWidth, pHeight); + this.setBounds(pBoundMinX, pBoundMaxX, pBoundMinY, pBoundMaxY); + this.mBoundsEnabled = true; + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + public boolean isBoundsEnabled() { + return this.mBoundsEnabled; + } + + public void setBoundsEnabled(final boolean pBoundsEnabled) { + this.mBoundsEnabled = pBoundsEnabled; + } + + public void setBounds(final float pBoundMinX, final float pBoundMaxX, final float pBoundMinY, final float pBoundMaxY) { + this.mBoundsMinX = pBoundMinX; + this.mBoundsMaxX = pBoundMaxX; + this.mBoundsMinY = pBoundMinY; + this.mBoundsMaxY = pBoundMaxY; + + this.mBoundsWidth = this.mBoundsMaxX - this.mBoundsMinX; + this.mBoundsHeight = this.mBoundsMaxY - this.mBoundsMinY; + + this.mBoundsCenterX = this.mBoundsMinX + this.mBoundsWidth * 0.5f; + this.mBoundsCenterY = this.mBoundsMinY + this.mBoundsHeight * 0.5f; + } + + public float getBoundsWidth() { + return this.mBoundsWidth; + } + + public float getBoundsHeight() { + return this.mBoundsHeight; + } + + @Override + public void setCenter(final float pCenterX, final float pCenterY) { + super.setCenter(pCenterX, pCenterY); + + if(this.mBoundsEnabled) { + this.ensureInBounds(); + } + } + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + protected void ensureInBounds() { + super.setCenter(this.determineBoundedX(), this.determineBoundedY()); + } + + private float determineBoundedX() { + if(this.mBoundsWidth < this.getWidth()) { + return this.mBoundsCenterX; + } else { + final float currentCenterX = this.getCenterX(); + + final float minXBoundExceededAmount = this.mBoundsMinX - this.getMinX(); + final boolean minXBoundExceeded = minXBoundExceededAmount > 0; + + final float maxXBoundExceededAmount = this.getMaxX() - this.mBoundsMaxX; + final boolean maxXBoundExceeded = maxXBoundExceededAmount > 0; + + if(minXBoundExceeded) { + if(maxXBoundExceeded) { + /* Min and max X exceeded. */ + return currentCenterX - maxXBoundExceededAmount + minXBoundExceededAmount; + } else { + /* Only min X exceeded. */ + return currentCenterX + minXBoundExceededAmount; + } + } else { + if(maxXBoundExceeded) { + /* Only max X exceeded. */ + return currentCenterX - maxXBoundExceededAmount; + } else { + /* Nothing exceeded. */ + return currentCenterX; + } + } + } + } + + private float determineBoundedY() { + if(this.mBoundsHeight < this.getHeight()) { + return this.mBoundsCenterY; + } else { + final float currentCenterY = this.getCenterY(); + + final float minYBoundExceededAmount = this.mBoundsMinY - this.getMinY(); + final boolean minYBoundExceeded = minYBoundExceededAmount > 0; + + final float maxYBoundExceededAmount = this.getMaxY() - this.mBoundsMaxY; + final boolean maxYBoundExceeded = maxYBoundExceededAmount > 0; + + if(minYBoundExceeded) { + if(maxYBoundExceeded) { + /* Min and max Y exceeded. */ + return currentCenterY - maxYBoundExceededAmount + minYBoundExceededAmount; + } else { + /* Only min Y exceeded. */ + return currentCenterY + minYBoundExceededAmount; + } + } else { + if(maxYBoundExceeded) { + /* Only max Y exceeded. */ + return currentCenterY - maxYBoundExceededAmount; + } else { + /* Nothing exceeded. */ + return currentCenterY; + } + } + } + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/engine/camera/Camera.java b/AndEngine/src/org/anddev/andengine/engine/camera/Camera.java index f72f195a..62c8b4df 100644 --- a/AndEngine/src/org/anddev/andengine/engine/camera/Camera.java +++ b/AndEngine/src/org/anddev/andengine/engine/camera/Camera.java @@ -23,421 +23,421 @@ * @since 10:24:18 - 25.03.2010 */ public class Camera implements IUpdateHandler { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - protected static final float[] VERTICES_TOUCH_TMP = new float[2]; + protected static final float[] VERTICES_TOUCH_TMP = new float[2]; - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - private float mMinX; - private float mMaxX; - private float mMinY; - private float mMaxY; + private float mMinX; + private float mMaxX; + private float mMinY; + private float mMaxY; - private float mNearZ = -1.0f; - private float mFarZ = 1.0f; + private float mNearZ = -1.0f; + private float mFarZ = 1.0f; - private HUD mHUD; - - private IEntity mChaseEntity; + private HUD mHUD; + + private IEntity mChaseEntity; - protected float mRotation = 0; - protected float mCameraSceneRotation = 0; - - protected int mSurfaceX; - protected int mSurfaceY; - protected int mSurfaceWidth; - protected int mSurfaceHeight; - - // =========================================================== - // Constructors - // =========================================================== - - public Camera(final float pX, final float pY, final float pWidth, final float pHeight) { - this.mMinX = pX; - this.mMaxX = pX + pWidth; - this.mMinY = pY; - this.mMaxY = pY + pHeight; - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - public float getMinX() { - return this.mMinX; - } - - public float getMaxX() { - return this.mMaxX; - } - - public float getMinY() { - return this.mMinY; - } - - public float getMaxY() { - return this.mMaxY; - } - - public float getNearZClippingPlane() { - return this.mNearZ; - } - - public float getFarZClippingPlane() { - return this.mFarZ; - } - - public void setNearZClippingPlane(final float pNearZClippingPlane) { - this.mNearZ = pNearZClippingPlane; - } - - public void setFarZClippingPlane(final float pFarZClippingPlane) { - this.mFarZ = pFarZClippingPlane; - } - - public void setZClippingPlanes(final float pNearZClippingPlane, final float pFarZClippingPlane) { - this.mNearZ = pNearZClippingPlane; - this.mFarZ = pFarZClippingPlane; - } - - public float getWidth() { - return this.mMaxX - this.mMinX; - } - - public float getHeight() { - return this.mMaxY - this.mMinY; - } - - public float getWidthRaw() { - return this.mMaxX - this.mMinX; - } - - public float getHeightRaw() { - return this.mMaxY - this.mMinY; - } - - public float getCenterX() { - final float minX = this.mMinX; - return minX + (this.mMaxX - minX) * 0.5f; - } - - public float getCenterY() { - final float minY = this.mMinY; - return minY + (this.mMaxY - minY) * 0.5f; - } - - public void setCenter(final float pCenterX, final float pCenterY) { - final float dX = pCenterX - this.getCenterX(); - final float dY = pCenterY - this.getCenterY(); - - this.mMinX += dX; - this.mMaxX += dX; - this.mMinY += dY; - this.mMaxY += dY; - } - - public void offsetCenter(final float pX, final float pY) { - this.setCenter(this.getCenterX() + pX, this.getCenterY() + pY); - } - - public HUD getHUD() { - return this.mHUD; - } - - public void setHUD(final HUD pHUD) { - this.mHUD = pHUD; - pHUD.setCamera(this); - } - - public boolean hasHUD() { - return this.mHUD != null; - } - - public void setChaseEntity(final IEntity pChaseEntity) { - this.mChaseEntity = pChaseEntity; - } - - public float getRotation() { - return this.mRotation; - } - - public void setRotation(final float pRotation) { - this.mRotation = pRotation; - } - - public float getCameraSceneRotation() { - return this.mCameraSceneRotation; - } - - public void setCameraSceneRotation(final float pCameraSceneRotation) { - this.mCameraSceneRotation = pCameraSceneRotation; - } - - public int getSurfaceX() { - return this.mSurfaceX; - } - - public int getSurfaceY() { - return this.mSurfaceY; - } - - public int getSurfaceWidth() { - return this.mSurfaceWidth; - } - - public int getSurfaceHeight() { - return this.mSurfaceHeight; - } - - public void setSurfaceSize(final int pSurfaceX, final int pSurfaceY, final int pSurfaceWidth, final int pSurfaceHeight) { - this.mSurfaceX = pSurfaceX; - this.mSurfaceY = pSurfaceY; - this.mSurfaceWidth = pSurfaceWidth; - this.mSurfaceHeight = pSurfaceHeight; - } - - public boolean isRotated() { - return this.mRotation != 0; - } + protected float mRotation = 0; + protected float mCameraSceneRotation = 0; + + protected int mSurfaceX; + protected int mSurfaceY; + protected int mSurfaceWidth; + protected int mSurfaceHeight; + + // =========================================================== + // Constructors + // =========================================================== + + public Camera(final float pX, final float pY, final float pWidth, final float pHeight) { + this.mMinX = pX; + this.mMaxX = pX + pWidth; + this.mMinY = pY; + this.mMaxY = pY + pHeight; + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + public float getMinX() { + return this.mMinX; + } + + public float getMaxX() { + return this.mMaxX; + } + + public float getMinY() { + return this.mMinY; + } + + public float getMaxY() { + return this.mMaxY; + } + + public float getNearZClippingPlane() { + return this.mNearZ; + } + + public float getFarZClippingPlane() { + return this.mFarZ; + } + + public void setNearZClippingPlane(final float pNearZClippingPlane) { + this.mNearZ = pNearZClippingPlane; + } + + public void setFarZClippingPlane(final float pFarZClippingPlane) { + this.mFarZ = pFarZClippingPlane; + } + + public void setZClippingPlanes(final float pNearZClippingPlane, final float pFarZClippingPlane) { + this.mNearZ = pNearZClippingPlane; + this.mFarZ = pFarZClippingPlane; + } + + public float getWidth() { + return this.mMaxX - this.mMinX; + } + + public float getHeight() { + return this.mMaxY - this.mMinY; + } + + public float getWidthRaw() { + return this.mMaxX - this.mMinX; + } + + public float getHeightRaw() { + return this.mMaxY - this.mMinY; + } + + public float getCenterX() { + final float minX = this.mMinX; + return minX + (this.mMaxX - minX) * 0.5f; + } + + public float getCenterY() { + final float minY = this.mMinY; + return minY + (this.mMaxY - minY) * 0.5f; + } + + public void setCenter(final float pCenterX, final float pCenterY) { + final float dX = pCenterX - this.getCenterX(); + final float dY = pCenterY - this.getCenterY(); + + this.mMinX += dX; + this.mMaxX += dX; + this.mMinY += dY; + this.mMaxY += dY; + } + + public void offsetCenter(final float pX, final float pY) { + this.setCenter(this.getCenterX() + pX, this.getCenterY() + pY); + } + + public HUD getHUD() { + return this.mHUD; + } + + public void setHUD(final HUD pHUD) { + this.mHUD = pHUD; + pHUD.setCamera(this); + } + + public boolean hasHUD() { + return this.mHUD != null; + } + + public void setChaseEntity(final IEntity pChaseEntity) { + this.mChaseEntity = pChaseEntity; + } + + public float getRotation() { + return this.mRotation; + } + + public void setRotation(final float pRotation) { + this.mRotation = pRotation; + } + + public float getCameraSceneRotation() { + return this.mCameraSceneRotation; + } + + public void setCameraSceneRotation(final float pCameraSceneRotation) { + this.mCameraSceneRotation = pCameraSceneRotation; + } + + public int getSurfaceX() { + return this.mSurfaceX; + } + + public int getSurfaceY() { + return this.mSurfaceY; + } + + public int getSurfaceWidth() { + return this.mSurfaceWidth; + } + + public int getSurfaceHeight() { + return this.mSurfaceHeight; + } + + public void setSurfaceSize(final int pSurfaceX, final int pSurfaceY, final int pSurfaceWidth, final int pSurfaceHeight) { + this.mSurfaceX = pSurfaceX; + this.mSurfaceY = pSurfaceY; + this.mSurfaceWidth = pSurfaceWidth; + this.mSurfaceHeight = pSurfaceHeight; + } + + public boolean isRotated() { + return this.mRotation != 0; + } - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - @Override - public void onUpdate(final float pSecondsElapsed) { - if(this.mHUD != null) { - this.mHUD.onUpdate(pSecondsElapsed); - } + @Override + public void onUpdate(final float pSecondsElapsed) { + if(this.mHUD != null) { + this.mHUD.onUpdate(pSecondsElapsed); + } - this.updateChaseEntity(); - } + this.updateChaseEntity(); + } - @Override - public void reset() { + @Override + public void reset() { - } + } - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - public void onDrawHUD(final GL10 pGL) { - if(this.mHUD != null) { - this.mHUD.onDraw(pGL, this); - } - } + public void onDrawHUD(final GL10 pGL) { + if(this.mHUD != null) { + this.mHUD.onDraw(pGL, this); + } + } - public void updateChaseEntity() { - if(this.mChaseEntity != null) { - final float[] centerCoordinates = this.mChaseEntity.getSceneCenterCoordinates(); - this.setCenter(centerCoordinates[VERTEX_INDEX_X], centerCoordinates[VERTEX_INDEX_Y]); - } - } + public void updateChaseEntity() { + if(this.mChaseEntity != null) { + final float[] centerCoordinates = this.mChaseEntity.getSceneCenterCoordinates(); + this.setCenter(centerCoordinates[VERTEX_INDEX_X], centerCoordinates[VERTEX_INDEX_Y]); + } + } - public boolean isLineVisible(final Line pLine) { - return RectangularShapeCollisionChecker.isVisible(this, pLine); - } + public boolean isLineVisible(final Line pLine) { + return RectangularShapeCollisionChecker.isVisible(this, pLine); + } - public boolean isRectangularShapeVisible(final RectangularShape pRectangularShape) { - return RectangularShapeCollisionChecker.isVisible(this, pRectangularShape); - } + public boolean isRectangularShapeVisible(final RectangularShape pRectangularShape) { + return RectangularShapeCollisionChecker.isVisible(this, pRectangularShape); + } - public void onApplySceneMatrix(final GL10 pGL) { - GLHelper.setProjectionIdentityMatrix(pGL); + public void onApplySceneMatrix(final GL10 pGL) { + GLHelper.setProjectionIdentityMatrix(pGL); - pGL.glOrthof(this.getMinX(), this.getMaxX(), this.getMaxY(), this.getMinY(), this.mNearZ, this.mFarZ); + pGL.glOrthof(this.getMinX(), this.getMaxX(), this.getMaxY(), this.getMinY(), this.mNearZ, this.mFarZ); - final float rotation = this.mRotation; - if(rotation != 0) { - this.applyRotation(pGL, this.getCenterX(), this.getCenterY(), rotation); - } - } + final float rotation = this.mRotation; + if(rotation != 0) { + this.applyRotation(pGL, this.getCenterX(), this.getCenterY(), rotation); + } + } - public void onApplySceneBackgroundMatrix(final GL10 pGL) { - GLHelper.setProjectionIdentityMatrix(pGL); + public void onApplySceneBackgroundMatrix(final GL10 pGL) { + GLHelper.setProjectionIdentityMatrix(pGL); - final float widthRaw = this.getWidthRaw(); - final float heightRaw = this.getHeightRaw(); + final float widthRaw = this.getWidthRaw(); + final float heightRaw = this.getHeightRaw(); - pGL.glOrthof(0, widthRaw, heightRaw, 0, this.mNearZ, this.mFarZ); + pGL.glOrthof(0, widthRaw, heightRaw, 0, this.mNearZ, this.mFarZ); - final float rotation = this.mRotation; - if(rotation != 0) { - this.applyRotation(pGL, widthRaw * 0.5f, heightRaw * 0.5f, rotation); - } - } + final float rotation = this.mRotation; + if(rotation != 0) { + this.applyRotation(pGL, widthRaw * 0.5f, heightRaw * 0.5f, rotation); + } + } - public void onApplyCameraSceneMatrix(final GL10 pGL) { - GLHelper.setProjectionIdentityMatrix(pGL); + public void onApplyCameraSceneMatrix(final GL10 pGL) { + GLHelper.setProjectionIdentityMatrix(pGL); - final float widthRaw = this.getWidthRaw(); - final float heightRaw = this.getHeightRaw(); + final float widthRaw = this.getWidthRaw(); + final float heightRaw = this.getHeightRaw(); - pGL.glOrthof(0, widthRaw, heightRaw, 0, this.mNearZ, this.mFarZ); + pGL.glOrthof(0, widthRaw, heightRaw, 0, this.mNearZ, this.mFarZ); - final float cameraSceneRotation = this.mCameraSceneRotation; - if(cameraSceneRotation != 0) { - this.applyRotation(pGL, widthRaw * 0.5f, heightRaw * 0.5f, cameraSceneRotation); - } - } + final float cameraSceneRotation = this.mCameraSceneRotation; + if(cameraSceneRotation != 0) { + this.applyRotation(pGL, widthRaw * 0.5f, heightRaw * 0.5f, cameraSceneRotation); + } + } - private void applyRotation(final GL10 pGL, final float pRotationCenterX, final float pRotationCenterY, final float pAngle) { - pGL.glTranslatef(pRotationCenterX, pRotationCenterY, 0); - pGL.glRotatef(pAngle, 0, 0, 1); - pGL.glTranslatef(-pRotationCenterX, -pRotationCenterY, 0); - } + private void applyRotation(final GL10 pGL, final float pRotationCenterX, final float pRotationCenterY, final float pAngle) { + pGL.glTranslatef(pRotationCenterX, pRotationCenterY, 0); + pGL.glRotatef(pAngle, 0, 0, 1); + pGL.glTranslatef(-pRotationCenterX, -pRotationCenterY, 0); + } - public void convertSceneToCameraSceneTouchEvent(final TouchEvent pSceneTouchEvent) { - this.unapplySceneRotation(pSceneTouchEvent); + public void convertSceneToCameraSceneTouchEvent(final TouchEvent pSceneTouchEvent) { + this.unapplySceneRotation(pSceneTouchEvent); - this.applySceneToCameraSceneOffset(pSceneTouchEvent); + this.applySceneToCameraSceneOffset(pSceneTouchEvent); - this.applyCameraSceneRotation(pSceneTouchEvent); - } + this.applyCameraSceneRotation(pSceneTouchEvent); + } - public void convertCameraSceneToSceneTouchEvent(final TouchEvent pCameraSceneTouchEvent) { - this.unapplyCameraSceneRotation(pCameraSceneTouchEvent); + public void convertCameraSceneToSceneTouchEvent(final TouchEvent pCameraSceneTouchEvent) { + this.unapplyCameraSceneRotation(pCameraSceneTouchEvent); - this.unapplySceneToCameraSceneOffset(pCameraSceneTouchEvent); + this.unapplySceneToCameraSceneOffset(pCameraSceneTouchEvent); - this.applySceneRotation(pCameraSceneTouchEvent); - } + this.applySceneRotation(pCameraSceneTouchEvent); + } - protected void applySceneToCameraSceneOffset(final TouchEvent pSceneTouchEvent) { - pSceneTouchEvent.offset(-this.mMinX, -this.mMinY); - } + protected void applySceneToCameraSceneOffset(final TouchEvent pSceneTouchEvent) { + pSceneTouchEvent.offset(-this.mMinX, -this.mMinY); + } - protected void unapplySceneToCameraSceneOffset(final TouchEvent pCameraSceneTouchEvent) { - pCameraSceneTouchEvent.offset(this.mMinX, this.mMinY); - } + protected void unapplySceneToCameraSceneOffset(final TouchEvent pCameraSceneTouchEvent) { + pCameraSceneTouchEvent.offset(this.mMinX, this.mMinY); + } - private void applySceneRotation(final TouchEvent pCameraSceneTouchEvent) { - final float rotation = -this.mRotation; - if(rotation != 0) { - VERTICES_TOUCH_TMP[VERTEX_INDEX_X] = pCameraSceneTouchEvent.getX(); - VERTICES_TOUCH_TMP[VERTEX_INDEX_Y] = pCameraSceneTouchEvent.getY(); + private void applySceneRotation(final TouchEvent pCameraSceneTouchEvent) { + final float rotation = -this.mRotation; + if(rotation != 0) { + VERTICES_TOUCH_TMP[VERTEX_INDEX_X] = pCameraSceneTouchEvent.getX(); + VERTICES_TOUCH_TMP[VERTEX_INDEX_Y] = pCameraSceneTouchEvent.getY(); - MathUtils.rotateAroundCenter(VERTICES_TOUCH_TMP, rotation, this.getCenterX(), this.getCenterY()); + MathUtils.rotateAroundCenter(VERTICES_TOUCH_TMP, rotation, this.getCenterX(), this.getCenterY()); - pCameraSceneTouchEvent.set(VERTICES_TOUCH_TMP[VERTEX_INDEX_X], VERTICES_TOUCH_TMP[VERTEX_INDEX_Y]); - } - } + pCameraSceneTouchEvent.set(VERTICES_TOUCH_TMP[VERTEX_INDEX_X], VERTICES_TOUCH_TMP[VERTEX_INDEX_Y]); + } + } - private void unapplySceneRotation(final TouchEvent pSceneTouchEvent) { - final float rotation = this.mRotation; + private void unapplySceneRotation(final TouchEvent pSceneTouchEvent) { + final float rotation = this.mRotation; - if(rotation != 0) { - VERTICES_TOUCH_TMP[VERTEX_INDEX_X] = pSceneTouchEvent.getX(); - VERTICES_TOUCH_TMP[VERTEX_INDEX_Y] = pSceneTouchEvent.getY(); + if(rotation != 0) { + VERTICES_TOUCH_TMP[VERTEX_INDEX_X] = pSceneTouchEvent.getX(); + VERTICES_TOUCH_TMP[VERTEX_INDEX_Y] = pSceneTouchEvent.getY(); - MathUtils.revertRotateAroundCenter(VERTICES_TOUCH_TMP, rotation, this.getCenterX(), this.getCenterY()); + MathUtils.revertRotateAroundCenter(VERTICES_TOUCH_TMP, rotation, this.getCenterX(), this.getCenterY()); - pSceneTouchEvent.set(VERTICES_TOUCH_TMP[VERTEX_INDEX_X], VERTICES_TOUCH_TMP[VERTEX_INDEX_Y]); - } - } + pSceneTouchEvent.set(VERTICES_TOUCH_TMP[VERTEX_INDEX_X], VERTICES_TOUCH_TMP[VERTEX_INDEX_Y]); + } + } - private void applyCameraSceneRotation(final TouchEvent pSceneTouchEvent) { - final float cameraSceneRotation = -this.mCameraSceneRotation; + private void applyCameraSceneRotation(final TouchEvent pSceneTouchEvent) { + final float cameraSceneRotation = -this.mCameraSceneRotation; - if(cameraSceneRotation != 0) { - VERTICES_TOUCH_TMP[VERTEX_INDEX_X] = pSceneTouchEvent.getX(); - VERTICES_TOUCH_TMP[VERTEX_INDEX_Y] = pSceneTouchEvent.getY(); + if(cameraSceneRotation != 0) { + VERTICES_TOUCH_TMP[VERTEX_INDEX_X] = pSceneTouchEvent.getX(); + VERTICES_TOUCH_TMP[VERTEX_INDEX_Y] = pSceneTouchEvent.getY(); - MathUtils.rotateAroundCenter(VERTICES_TOUCH_TMP, cameraSceneRotation, (this.mMaxX - this.mMinX) * 0.5f, (this.mMaxY - this.mMinY) * 0.5f); + MathUtils.rotateAroundCenter(VERTICES_TOUCH_TMP, cameraSceneRotation, (this.mMaxX - this.mMinX) * 0.5f, (this.mMaxY - this.mMinY) * 0.5f); - pSceneTouchEvent.set(VERTICES_TOUCH_TMP[VERTEX_INDEX_X], VERTICES_TOUCH_TMP[VERTEX_INDEX_Y]); - } - } + pSceneTouchEvent.set(VERTICES_TOUCH_TMP[VERTEX_INDEX_X], VERTICES_TOUCH_TMP[VERTEX_INDEX_Y]); + } + } - private void unapplyCameraSceneRotation(final TouchEvent pCameraSceneTouchEvent) { - final float cameraSceneRotation = -this.mCameraSceneRotation; + private void unapplyCameraSceneRotation(final TouchEvent pCameraSceneTouchEvent) { + final float cameraSceneRotation = -this.mCameraSceneRotation; - if(cameraSceneRotation != 0) { - VERTICES_TOUCH_TMP[VERTEX_INDEX_X] = pCameraSceneTouchEvent.getX(); - VERTICES_TOUCH_TMP[VERTEX_INDEX_Y] = pCameraSceneTouchEvent.getY(); + if(cameraSceneRotation != 0) { + VERTICES_TOUCH_TMP[VERTEX_INDEX_X] = pCameraSceneTouchEvent.getX(); + VERTICES_TOUCH_TMP[VERTEX_INDEX_Y] = pCameraSceneTouchEvent.getY(); - MathUtils.revertRotateAroundCenter(VERTICES_TOUCH_TMP, cameraSceneRotation, (this.mMaxX - this.mMinX) * 0.5f, (this.mMaxY - this.mMinY) * 0.5f); + MathUtils.revertRotateAroundCenter(VERTICES_TOUCH_TMP, cameraSceneRotation, (this.mMaxX - this.mMinX) * 0.5f, (this.mMaxY - this.mMinY) * 0.5f); - pCameraSceneTouchEvent.set(VERTICES_TOUCH_TMP[VERTEX_INDEX_X], VERTICES_TOUCH_TMP[VERTEX_INDEX_Y]); - } - } + pCameraSceneTouchEvent.set(VERTICES_TOUCH_TMP[VERTEX_INDEX_X], VERTICES_TOUCH_TMP[VERTEX_INDEX_Y]); + } + } - public void convertSurfaceToSceneTouchEvent(final TouchEvent pSurfaceTouchEvent, final int pSurfaceWidth, final int pSurfaceHeight) { - final float relativeX; - final float relativeY; + public void convertSurfaceToSceneTouchEvent(final TouchEvent pSurfaceTouchEvent, final int pSurfaceWidth, final int pSurfaceHeight) { + final float relativeX; + final float relativeY; - final float surfaceTouchEventX = pSurfaceTouchEvent.getX(); - final float surfaceTouchEventY = pSurfaceTouchEvent.getY(); + final float surfaceTouchEventX = pSurfaceTouchEvent.getX(); + final float surfaceTouchEventY = pSurfaceTouchEvent.getY(); - final float rotation = this.mRotation; - if(rotation == 0) { - relativeX = surfaceTouchEventX / pSurfaceWidth; - relativeY = surfaceTouchEventY / pSurfaceHeight; - } else if(rotation == 180) { - relativeX = 1 - (surfaceTouchEventX / pSurfaceWidth); - relativeY = 1 - (surfaceTouchEventY / pSurfaceHeight); - } else { - VERTICES_TOUCH_TMP[VERTEX_INDEX_X] = surfaceTouchEventX; - VERTICES_TOUCH_TMP[VERTEX_INDEX_Y] = surfaceTouchEventY; + final float rotation = this.mRotation; + if(rotation == 0) { + relativeX = surfaceTouchEventX / pSurfaceWidth; + relativeY = surfaceTouchEventY / pSurfaceHeight; + } else if(rotation == 180) { + relativeX = 1 - (surfaceTouchEventX / pSurfaceWidth); + relativeY = 1 - (surfaceTouchEventY / pSurfaceHeight); + } else { + VERTICES_TOUCH_TMP[VERTEX_INDEX_X] = surfaceTouchEventX; + VERTICES_TOUCH_TMP[VERTEX_INDEX_Y] = surfaceTouchEventY; - MathUtils.rotateAroundCenter(VERTICES_TOUCH_TMP, rotation, pSurfaceWidth / 2, pSurfaceHeight / 2); + MathUtils.rotateAroundCenter(VERTICES_TOUCH_TMP, rotation, pSurfaceWidth / 2, pSurfaceHeight / 2); - relativeX = VERTICES_TOUCH_TMP[VERTEX_INDEX_X] / pSurfaceWidth; - relativeY = VERTICES_TOUCH_TMP[VERTEX_INDEX_Y] / pSurfaceHeight; - } + relativeX = VERTICES_TOUCH_TMP[VERTEX_INDEX_X] / pSurfaceWidth; + relativeY = VERTICES_TOUCH_TMP[VERTEX_INDEX_Y] / pSurfaceHeight; + } - this.convertAxisAlignedSurfaceToSceneTouchEvent(pSurfaceTouchEvent, relativeX, relativeY); - } + this.convertAxisAlignedSurfaceToSceneTouchEvent(pSurfaceTouchEvent, relativeX, relativeY); + } - private void convertAxisAlignedSurfaceToSceneTouchEvent(final TouchEvent pSurfaceTouchEvent, final float pRelativeX, final float pRelativeY) { - final float minX = this.getMinX(); - final float maxX = this.getMaxX(); - final float minY = this.getMinY(); - final float maxY = this.getMaxY(); + private void convertAxisAlignedSurfaceToSceneTouchEvent(final TouchEvent pSurfaceTouchEvent, final float pRelativeX, final float pRelativeY) { + final float minX = this.getMinX(); + final float maxX = this.getMaxX(); + final float minY = this.getMinY(); + final float maxY = this.getMaxY(); - final float x = minX + pRelativeX * (maxX - minX); - final float y = minY + pRelativeY * (maxY - minY); + final float x = minX + pRelativeX * (maxX - minX); + final float y = minY + pRelativeY * (maxY - minY); - pSurfaceTouchEvent.set(x, y); - } + pSurfaceTouchEvent.set(x, y); + } - public void convertSceneToSurfaceTouchEvent(final TouchEvent pSceneTouchEvent, final int pSurfaceWidth, final int pSurfaceHeight) { - this.convertAxisAlignedSceneToSurfaceTouchEvent(pSceneTouchEvent, pSurfaceWidth, pSurfaceHeight); + public void convertSceneToSurfaceTouchEvent(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()); - } else { - VERTICES_TOUCH_TMP[VERTEX_INDEX_X] = pSceneTouchEvent.getX(); - VERTICES_TOUCH_TMP[VERTEX_INDEX_Y] = pSceneTouchEvent.getY(); + final float rotation = this.mRotation; + if(rotation == 0) { + /* Nothing to do. */ + } else if(rotation == 180) { + pSceneTouchEvent.set(pSurfaceWidth - pSceneTouchEvent.getX(), pSurfaceHeight - pSceneTouchEvent.getY()); + } else { + VERTICES_TOUCH_TMP[VERTEX_INDEX_X] = pSceneTouchEvent.getX(); + VERTICES_TOUCH_TMP[VERTEX_INDEX_Y] = pSceneTouchEvent.getY(); - MathUtils.revertRotateAroundCenter(VERTICES_TOUCH_TMP, rotation, pSurfaceWidth >> 1, pSurfaceHeight >> 1); + MathUtils.revertRotateAroundCenter(VERTICES_TOUCH_TMP, rotation, pSurfaceWidth >> 1, pSurfaceHeight >> 1); - pSceneTouchEvent.set(VERTICES_TOUCH_TMP[VERTEX_INDEX_X], VERTICES_TOUCH_TMP[VERTEX_INDEX_Y]); - } - } + pSceneTouchEvent.set(VERTICES_TOUCH_TMP[VERTEX_INDEX_X], VERTICES_TOUCH_TMP[VERTEX_INDEX_Y]); + } + } - private void convertAxisAlignedSceneToSurfaceTouchEvent(final TouchEvent pSceneTouchEvent, final int pSurfaceWidth, final int pSurfaceHeight) { - final float minX = this.getMinX(); - final float maxX = this.getMaxX(); - final float minY = this.getMinY(); - final float maxY = this.getMaxY(); + private void convertAxisAlignedSceneToSurfaceTouchEvent(final TouchEvent pSceneTouchEvent, final int pSurfaceWidth, final int pSurfaceHeight) { + final float minX = this.getMinX(); + final float maxX = this.getMaxX(); + final float minY = this.getMinY(); + final float maxY = this.getMaxY(); - final float relativeX = (pSceneTouchEvent.getX() - minX) / (maxX - minX); - final float relativeY = (pSceneTouchEvent.getY() - minY) / (maxY - minY); + final float relativeX = (pSceneTouchEvent.getX() - minX) / (maxX - minX); + final float relativeY = (pSceneTouchEvent.getY() - minY) / (maxY - minY); - pSceneTouchEvent.set(relativeX * pSurfaceWidth, relativeY * pSurfaceHeight); - } + pSceneTouchEvent.set(relativeX * pSurfaceWidth, relativeY * pSurfaceHeight); + } - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/engine/camera/CameraFactory.java b/AndEngine/src/org/anddev/andengine/engine/camera/CameraFactory.java index 7147d2a9..95aab955 100644 --- a/AndEngine/src/org/anddev/andengine/engine/camera/CameraFactory.java +++ b/AndEngine/src/org/anddev/andengine/engine/camera/CameraFactory.java @@ -11,43 +11,43 @@ * @since 13:50:42 - 03.07.2010 */ public class CameraFactory { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - public static Camera createPixelPerfectCamera(final Context pContext, final float pCenterX, final float pCenterY) { - final DisplayMetrics displayMetrics = CameraFactory.getDisplayMetrics(pContext); + public static Camera createPixelPerfectCamera(final Context pContext, final float pCenterX, final float pCenterY) { + final DisplayMetrics displayMetrics = CameraFactory.getDisplayMetrics(pContext); - final float width = displayMetrics.widthPixels; - final float height = displayMetrics.heightPixels; - return new Camera(pCenterX - width * 0.5f, pCenterY - height * 0.5f, width, height); - } + final float width = displayMetrics.widthPixels; + final float height = displayMetrics.heightPixels; + return new Camera(pCenterX - width * 0.5f, pCenterY - height * 0.5f, width, height); + } - private static DisplayMetrics getDisplayMetrics(final Context pContext) { - return pContext.getResources().getDisplayMetrics(); - } + private static DisplayMetrics getDisplayMetrics(final Context pContext) { + return pContext.getResources().getDisplayMetrics(); + } - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/engine/camera/SmoothCamera.java b/AndEngine/src/org/anddev/andengine/engine/camera/SmoothCamera.java index a8e201c4..27a63486 100644 --- a/AndEngine/src/org/anddev/andengine/engine/camera/SmoothCamera.java +++ b/AndEngine/src/org/anddev/andengine/engine/camera/SmoothCamera.java @@ -9,174 +9,174 @@ * @since 22:11:17 - 25.03.2010 */ public class SmoothCamera extends ZoomCamera { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - private float mMaxVelocityX; - private float mMaxVelocityY; - private float mMaxZoomFactorChange; - - private float mTargetCenterX; - private float mTargetCenterY; - - private float mTargetZoomFactor; - - // =========================================================== - // Constructors - // =========================================================== - - public SmoothCamera(final float pX, final float pY, final float pWidth, final float pHeight, final float pMaxVelocityX, final float pMaxVelocityY, final float pMaxZoomFactorChange) { - super(pX, pY, pWidth, pHeight); - this.mMaxVelocityX = pMaxVelocityX; - this.mMaxVelocityY = pMaxVelocityY; - this.mMaxZoomFactorChange = pMaxZoomFactorChange; + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + private float mMaxVelocityX; + private float mMaxVelocityY; + private float mMaxZoomFactorChange; + + private float mTargetCenterX; + private float mTargetCenterY; + + private float mTargetZoomFactor; + + // =========================================================== + // Constructors + // =========================================================== + + public SmoothCamera(final float pX, final float pY, final float pWidth, final float pHeight, final float pMaxVelocityX, final float pMaxVelocityY, final float pMaxZoomFactorChange) { + super(pX, pY, pWidth, pHeight); + this.mMaxVelocityX = pMaxVelocityX; + this.mMaxVelocityY = pMaxVelocityY; + this.mMaxZoomFactorChange = pMaxZoomFactorChange; - this.mTargetCenterX = this.getCenterX(); - this.mTargetCenterY = this.getCenterY(); + this.mTargetCenterX = this.getCenterX(); + this.mTargetCenterY = this.getCenterY(); - this.mTargetZoomFactor = 1.0f; - } + this.mTargetZoomFactor = 1.0f; + } - // =========================================================== - // Getter & Setter - // =========================================================== - - @Override - public void setCenter(final float pCenterX, final float pCenterY) { - this.mTargetCenterX = pCenterX; - this.mTargetCenterY = pCenterY; - } - - public void setCenterDirect(final float pCenterX, final float pCenterY) { - super.setCenter(pCenterX, pCenterY); - this.mTargetCenterX = pCenterX; - this.mTargetCenterY = pCenterY; - } - - @Override - public void setZoomFactor(final float pZoomFactor) { - if(this.mTargetZoomFactor != pZoomFactor) { - if(this.mTargetZoomFactor == this.mZoomFactor) { - this.mTargetZoomFactor = pZoomFactor; - - this.onSmoothZoomStarted(); - } else { - this.mTargetZoomFactor = pZoomFactor; - } - } - } - - public void setZoomFactorDirect(final float pZoomFactor) { - if(this.mTargetZoomFactor != this.mZoomFactor) { - this.mTargetZoomFactor = pZoomFactor; - super.setZoomFactor(pZoomFactor); - - this.onSmoothZoomFinished(); - } else { - this.mTargetZoomFactor = pZoomFactor; - super.setZoomFactor(pZoomFactor); - } - } - - public void setMaxVelocityX(final float pMaxVelocityX) { - this.mMaxVelocityX = pMaxVelocityX; - } - - public void setMaxVelocityY(final float pMaxVelocityY) { - this.mMaxVelocityY = pMaxVelocityY; - } - - public void setMaxVelocity(final float pMaxVelocityX, final float pMaxVelocityY) { - this.mMaxVelocityX = pMaxVelocityX; - this.mMaxVelocityY = pMaxVelocityY; - } - - public void setMaxZoomFactorChange(final float pMaxZoomFactorChange) { - this.mMaxZoomFactorChange = pMaxZoomFactorChange; - } - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - protected void onSmoothZoomStarted() { - - } - - protected void onSmoothZoomFinished() { - - } - - @Override - public void onUpdate(final float pSecondsElapsed) { - super.onUpdate(pSecondsElapsed); - /* Update center. */ - final float currentCenterX = this.getCenterX(); - final float currentCenterY = this.getCenterY(); - - final float targetCenterX = this.mTargetCenterX; - final float targetCenterY = this.mTargetCenterY; - - if(currentCenterX != targetCenterX || currentCenterY != targetCenterY) { - final float diffX = targetCenterX - currentCenterX; - final float dX = this.limitToMaxVelocityX(diffX, pSecondsElapsed); - - final float diffY = targetCenterY - currentCenterY; - final float dY = this.limitToMaxVelocityY(diffY, pSecondsElapsed); - - super.setCenter(currentCenterX + dX, currentCenterY + dY); - } - - /* Update zoom. */ - final float currentZoom = this.getZoomFactor(); - - final float targetZoomFactor = this.mTargetZoomFactor; - - if(currentZoom != targetZoomFactor) { - final float absoluteZoomDifference = targetZoomFactor - currentZoom; - final float zoomChange = this.limitToMaxZoomFactorChange(absoluteZoomDifference, pSecondsElapsed); - super.setZoomFactor(currentZoom + zoomChange); - - if(this.mZoomFactor == this.mTargetZoomFactor) { - this.onSmoothZoomFinished(); - } - } - } - - private float limitToMaxVelocityX(final float pValue, final float pSecondsElapsed) { - if(pValue > 0) { - return Math.min(pValue, this.mMaxVelocityX * pSecondsElapsed); - } else { - return Math.max(pValue, -this.mMaxVelocityX * pSecondsElapsed); - } - } - - private float limitToMaxVelocityY(final float pValue, final float pSecondsElapsed) { - if(pValue > 0) { - return Math.min(pValue, this.mMaxVelocityY * pSecondsElapsed); - } else { - return Math.max(pValue, -this.mMaxVelocityY * pSecondsElapsed); - } - } - - private float limitToMaxZoomFactorChange(final float pValue, final float pSecondsElapsed) { - if(pValue > 0) { - return Math.min(pValue, this.mMaxZoomFactorChange * pSecondsElapsed); - } else { - return Math.max(pValue, -this.mMaxZoomFactorChange * pSecondsElapsed); - } - } - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== + + @Override + public void setCenter(final float pCenterX, final float pCenterY) { + this.mTargetCenterX = pCenterX; + this.mTargetCenterY = pCenterY; + } + + public void setCenterDirect(final float pCenterX, final float pCenterY) { + super.setCenter(pCenterX, pCenterY); + this.mTargetCenterX = pCenterX; + this.mTargetCenterY = pCenterY; + } + + @Override + public void setZoomFactor(final float pZoomFactor) { + if(this.mTargetZoomFactor != pZoomFactor) { + if(this.mTargetZoomFactor == this.mZoomFactor) { + this.mTargetZoomFactor = pZoomFactor; + + this.onSmoothZoomStarted(); + } else { + this.mTargetZoomFactor = pZoomFactor; + } + } + } + + public void setZoomFactorDirect(final float pZoomFactor) { + if(this.mTargetZoomFactor != this.mZoomFactor) { + this.mTargetZoomFactor = pZoomFactor; + super.setZoomFactor(pZoomFactor); + + this.onSmoothZoomFinished(); + } else { + this.mTargetZoomFactor = pZoomFactor; + super.setZoomFactor(pZoomFactor); + } + } + + public void setMaxVelocityX(final float pMaxVelocityX) { + this.mMaxVelocityX = pMaxVelocityX; + } + + public void setMaxVelocityY(final float pMaxVelocityY) { + this.mMaxVelocityY = pMaxVelocityY; + } + + public void setMaxVelocity(final float pMaxVelocityX, final float pMaxVelocityY) { + this.mMaxVelocityX = pMaxVelocityX; + this.mMaxVelocityY = pMaxVelocityY; + } + + public void setMaxZoomFactorChange(final float pMaxZoomFactorChange) { + this.mMaxZoomFactorChange = pMaxZoomFactorChange; + } + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + protected void onSmoothZoomStarted() { + + } + + protected void onSmoothZoomFinished() { + + } + + @Override + public void onUpdate(final float pSecondsElapsed) { + super.onUpdate(pSecondsElapsed); + /* Update center. */ + final float currentCenterX = this.getCenterX(); + final float currentCenterY = this.getCenterY(); + + final float targetCenterX = this.mTargetCenterX; + final float targetCenterY = this.mTargetCenterY; + + if(currentCenterX != targetCenterX || currentCenterY != targetCenterY) { + final float diffX = targetCenterX - currentCenterX; + final float dX = this.limitToMaxVelocityX(diffX, pSecondsElapsed); + + final float diffY = targetCenterY - currentCenterY; + final float dY = this.limitToMaxVelocityY(diffY, pSecondsElapsed); + + super.setCenter(currentCenterX + dX, currentCenterY + dY); + } + + /* Update zoom. */ + final float currentZoom = this.getZoomFactor(); + + final float targetZoomFactor = this.mTargetZoomFactor; + + if(currentZoom != targetZoomFactor) { + final float absoluteZoomDifference = targetZoomFactor - currentZoom; + final float zoomChange = this.limitToMaxZoomFactorChange(absoluteZoomDifference, pSecondsElapsed); + super.setZoomFactor(currentZoom + zoomChange); + + if(this.mZoomFactor == this.mTargetZoomFactor) { + this.onSmoothZoomFinished(); + } + } + } + + private float limitToMaxVelocityX(final float pValue, final float pSecondsElapsed) { + if(pValue > 0) { + return Math.min(pValue, this.mMaxVelocityX * pSecondsElapsed); + } else { + return Math.max(pValue, -this.mMaxVelocityX * pSecondsElapsed); + } + } + + private float limitToMaxVelocityY(final float pValue, final float pSecondsElapsed) { + if(pValue > 0) { + return Math.min(pValue, this.mMaxVelocityY * pSecondsElapsed); + } else { + return Math.max(pValue, -this.mMaxVelocityY * pSecondsElapsed); + } + } + + private float limitToMaxZoomFactorChange(final float pValue, final float pSecondsElapsed) { + if(pValue > 0) { + return Math.min(pValue, this.mMaxZoomFactorChange * pSecondsElapsed); + } else { + return Math.max(pValue, -this.mMaxZoomFactorChange * pSecondsElapsed); + } + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/engine/camera/ZoomCamera.java b/AndEngine/src/org/anddev/andengine/engine/camera/ZoomCamera.java index e172d6d4..d2eb32f3 100644 --- a/AndEngine/src/org/anddev/andengine/engine/camera/ZoomCamera.java +++ b/AndEngine/src/org/anddev/andengine/engine/camera/ZoomCamera.java @@ -17,134 +17,134 @@ * TODO min/max(X/Y) values could be cached and only updated once the zoomfactor/center changed. */ public class ZoomCamera extends BoundCamera { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - protected float mZoomFactor = 1.0f; - - // =========================================================== - // Constructors - // =========================================================== - - public ZoomCamera(final float pX, final float pY, final float pWidth, final float pHeight) { - super(pX, pY, pWidth, pHeight); - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - public float getZoomFactor() { - return this.mZoomFactor; - } - - public void setZoomFactor(final float pZoomFactor) { - this.mZoomFactor = pZoomFactor; - - if(this.mBoundsEnabled) { - this.ensureInBounds(); - } - } - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - public float getMinX() { - if(this.mZoomFactor == 1.0f) { - return super.getMinX(); - } else { - final float centerX = this.getCenterX(); - return centerX - (centerX - super.getMinX()) / this.mZoomFactor; - } - } - - @Override - public float getMaxX() { - if(this.mZoomFactor == 1.0f) { - return super.getMaxX(); - } else { - final float centerX = this.getCenterX(); - return centerX + (super.getMaxX() - centerX) / this.mZoomFactor; - } - } - - @Override - public float getMinY() { - if(this.mZoomFactor == 1.0f) { - return super.getMinY(); - } else { - final float centerY = this.getCenterY(); - return centerY - (centerY - super.getMinY()) / this.mZoomFactor; - } - } - - @Override - public float getMaxY() { - if(this.mZoomFactor == 1.0f) { - return super.getMaxY(); - } else { - final float centerY = this.getCenterY(); - return centerY + (super.getMaxY() - centerY) / this.mZoomFactor; - } - } - - @Override - public float getWidth() { - return super.getWidth() / this.mZoomFactor; - } - - @Override - public float getHeight() { - return super.getHeight() / this.mZoomFactor; - } - - @Override - protected void applySceneToCameraSceneOffset(final TouchEvent pSceneTouchEvent) { - final float zoomFactor = this.mZoomFactor; - if(zoomFactor != 1) { - final float scaleCenterX = this.getCenterX(); - final float scaleCenterY = this.getCenterY(); - - VERTICES_TOUCH_TMP[VERTEX_INDEX_X] = pSceneTouchEvent.getX(); - VERTICES_TOUCH_TMP[VERTEX_INDEX_Y] = pSceneTouchEvent.getY(); - - MathUtils.scaleAroundCenter(VERTICES_TOUCH_TMP, zoomFactor, zoomFactor, scaleCenterX, scaleCenterY); // TODO Use a Transformation object instead!?! - - pSceneTouchEvent.set(VERTICES_TOUCH_TMP[VERTEX_INDEX_X], VERTICES_TOUCH_TMP[VERTEX_INDEX_Y]); - } - super.applySceneToCameraSceneOffset(pSceneTouchEvent); - } - - @Override - protected void unapplySceneToCameraSceneOffset(final TouchEvent pCameraSceneTouchEvent) { - super.unapplySceneToCameraSceneOffset(pCameraSceneTouchEvent); - - final float zoomFactor = this.mZoomFactor; - if(zoomFactor != 1) { - final float scaleCenterX = this.getCenterX(); - final float scaleCenterY = this.getCenterY(); - - VERTICES_TOUCH_TMP[VERTEX_INDEX_X] = pCameraSceneTouchEvent.getX(); - VERTICES_TOUCH_TMP[VERTEX_INDEX_Y] = pCameraSceneTouchEvent.getY(); - - MathUtils.revertScaleAroundCenter(VERTICES_TOUCH_TMP, zoomFactor, zoomFactor, scaleCenterX, scaleCenterY); - - pCameraSceneTouchEvent.set(VERTICES_TOUCH_TMP[VERTEX_INDEX_X], VERTICES_TOUCH_TMP[VERTEX_INDEX_Y]); - } - } - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + protected float mZoomFactor = 1.0f; + + // =========================================================== + // Constructors + // =========================================================== + + public ZoomCamera(final float pX, final float pY, final float pWidth, final float pHeight) { + super(pX, pY, pWidth, pHeight); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + public float getZoomFactor() { + return this.mZoomFactor; + } + + public void setZoomFactor(final float pZoomFactor) { + this.mZoomFactor = pZoomFactor; + + if(this.mBoundsEnabled) { + this.ensureInBounds(); + } + } + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + public float getMinX() { + if(this.mZoomFactor == 1.0f) { + return super.getMinX(); + } else { + final float centerX = this.getCenterX(); + return centerX - (centerX - super.getMinX()) / this.mZoomFactor; + } + } + + @Override + public float getMaxX() { + if(this.mZoomFactor == 1.0f) { + return super.getMaxX(); + } else { + final float centerX = this.getCenterX(); + return centerX + (super.getMaxX() - centerX) / this.mZoomFactor; + } + } + + @Override + public float getMinY() { + if(this.mZoomFactor == 1.0f) { + return super.getMinY(); + } else { + final float centerY = this.getCenterY(); + return centerY - (centerY - super.getMinY()) / this.mZoomFactor; + } + } + + @Override + public float getMaxY() { + if(this.mZoomFactor == 1.0f) { + return super.getMaxY(); + } else { + final float centerY = this.getCenterY(); + return centerY + (super.getMaxY() - centerY) / this.mZoomFactor; + } + } + + @Override + public float getWidth() { + return super.getWidth() / this.mZoomFactor; + } + + @Override + public float getHeight() { + return super.getHeight() / this.mZoomFactor; + } + + @Override + protected void applySceneToCameraSceneOffset(final TouchEvent pSceneTouchEvent) { + final float zoomFactor = this.mZoomFactor; + if(zoomFactor != 1) { + final float scaleCenterX = this.getCenterX(); + final float scaleCenterY = this.getCenterY(); + + VERTICES_TOUCH_TMP[VERTEX_INDEX_X] = pSceneTouchEvent.getX(); + VERTICES_TOUCH_TMP[VERTEX_INDEX_Y] = pSceneTouchEvent.getY(); + + MathUtils.scaleAroundCenter(VERTICES_TOUCH_TMP, zoomFactor, zoomFactor, scaleCenterX, scaleCenterY); // TODO Use a Transformation object instead!?! + + pSceneTouchEvent.set(VERTICES_TOUCH_TMP[VERTEX_INDEX_X], VERTICES_TOUCH_TMP[VERTEX_INDEX_Y]); + } + super.applySceneToCameraSceneOffset(pSceneTouchEvent); + } + + @Override + protected void unapplySceneToCameraSceneOffset(final TouchEvent pCameraSceneTouchEvent) { + super.unapplySceneToCameraSceneOffset(pCameraSceneTouchEvent); + + final float zoomFactor = this.mZoomFactor; + if(zoomFactor != 1) { + final float scaleCenterX = this.getCenterX(); + final float scaleCenterY = this.getCenterY(); + + VERTICES_TOUCH_TMP[VERTEX_INDEX_X] = pCameraSceneTouchEvent.getX(); + VERTICES_TOUCH_TMP[VERTEX_INDEX_Y] = pCameraSceneTouchEvent.getY(); + + MathUtils.revertScaleAroundCenter(VERTICES_TOUCH_TMP, zoomFactor, zoomFactor, scaleCenterX, scaleCenterY); + + pCameraSceneTouchEvent.set(VERTICES_TOUCH_TMP[VERTEX_INDEX_X], VERTICES_TOUCH_TMP[VERTEX_INDEX_Y]); + } + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/engine/camera/hud/HUD.java b/AndEngine/src/org/anddev/andengine/engine/camera/hud/HUD.java index 1db017df..b153c0a1 100644 --- a/AndEngine/src/org/anddev/andengine/engine/camera/hud/HUD.java +++ b/AndEngine/src/org/anddev/andengine/engine/camera/hud/HUD.java @@ -15,37 +15,37 @@ * @since 14:13:13 - 01.04.2010 */ public class HUD extends CameraScene { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - public HUD() { - super(); + public HUD() { + super(); - this.setBackgroundEnabled(false); - } + this.setBackgroundEnabled(false); + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/engine/camera/hud/controls/AnalogOnScreenControl.java b/AndEngine/src/org/anddev/andengine/engine/camera/hud/controls/AnalogOnScreenControl.java index bea04c95..acb5c47f 100644 --- a/AndEngine/src/org/anddev/andengine/engine/camera/hud/controls/AnalogOnScreenControl.java +++ b/AndEngine/src/org/anddev/andengine/engine/camera/hud/controls/AnalogOnScreenControl.java @@ -16,89 +16,89 @@ * @since 00:21:55 - 11.07.2010 */ public class AnalogOnScreenControl extends BaseOnScreenControl implements TimeConstants, IClickDetectorListener { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - private final ClickDetector mClickDetector = new ClickDetector(this); - - // =========================================================== - // Constructors - // =========================================================== - - public AnalogOnScreenControl(final float pX, final float pY, final Camera pCamera, final TextureRegion pControlBaseTextureRegion, final TextureRegion pControlKnobTextureRegion, final float pTimeBetweenUpdates, final IAnalogOnScreenControlListener pAnalogOnScreenControlListener) { - super(pX, pY, pCamera, pControlBaseTextureRegion, pControlKnobTextureRegion, pTimeBetweenUpdates, pAnalogOnScreenControlListener); - this.mClickDetector.setEnabled(false); - } - - public AnalogOnScreenControl(final float pX, final float pY, final Camera pCamera, final TextureRegion pControlBaseTextureRegion, final TextureRegion pControlKnobTextureRegion, final float pTimeBetweenUpdates, final long pOnControlClickMaximumMilliseconds, final IAnalogOnScreenControlListener pAnalogOnScreenControlListener) { - super(pX, pY, pCamera, pControlBaseTextureRegion, pControlKnobTextureRegion, pTimeBetweenUpdates, pAnalogOnScreenControlListener); - this.mClickDetector.setTriggerClickMaximumMilliseconds(pOnControlClickMaximumMilliseconds); - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - @Override - public IAnalogOnScreenControlListener getOnScreenControlListener() { - return (IAnalogOnScreenControlListener)super.getOnScreenControlListener(); - } - - public void setOnControlClickEnabled(final boolean pOnControlClickEnabled) { - this.mClickDetector.setEnabled(pOnControlClickEnabled); - } - - public void setOnControlClickMaximumMilliseconds(final long pOnControlClickMaximumMilliseconds) { - this.mClickDetector.setTriggerClickMaximumMilliseconds(pOnControlClickMaximumMilliseconds); - } - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - public void onClick(final ClickDetector pClickDetector, final TouchEvent pTouchEvent) { - this.getOnScreenControlListener().onControlClick(this); - } - - @Override - protected boolean onHandleControlBaseTouched(final TouchEvent pSceneTouchEvent, final float pTouchAreaLocalX, final float pTouchAreaLocalY) { - this.mClickDetector.onSceneTouchEvent(null, pSceneTouchEvent); - return super.onHandleControlBaseTouched(pSceneTouchEvent, pTouchAreaLocalX, pTouchAreaLocalY); - } - - @Override - protected void onUpdateControlKnob(final float pRelativeX, final float pRelativeY) { - if(pRelativeX * pRelativeX + pRelativeY * pRelativeY <= 0.25f) { - super.onUpdateControlKnob(pRelativeX, pRelativeY); - } else { - final float angleRad = MathUtils.atan2(pRelativeY, pRelativeX); - super.onUpdateControlKnob((float) Math.cos(angleRad) * 0.5f, (float) Math.sin(angleRad) * 0.5f); - } - } - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== - - public interface IAnalogOnScreenControlListener extends IOnScreenControlListener { - // =========================================================== - // Final Fields - // =========================================================== - - // =========================================================== - // Methods - // =========================================================== - - public void onControlClick(final AnalogOnScreenControl pAnalogOnScreenControl); - } + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + private final ClickDetector mClickDetector = new ClickDetector(this); + + // =========================================================== + // Constructors + // =========================================================== + + public AnalogOnScreenControl(final float pX, final float pY, final Camera pCamera, final TextureRegion pControlBaseTextureRegion, final TextureRegion pControlKnobTextureRegion, final float pTimeBetweenUpdates, final IAnalogOnScreenControlListener pAnalogOnScreenControlListener) { + super(pX, pY, pCamera, pControlBaseTextureRegion, pControlKnobTextureRegion, pTimeBetweenUpdates, pAnalogOnScreenControlListener); + this.mClickDetector.setEnabled(false); + } + + public AnalogOnScreenControl(final float pX, final float pY, final Camera pCamera, final TextureRegion pControlBaseTextureRegion, final TextureRegion pControlKnobTextureRegion, final float pTimeBetweenUpdates, final long pOnControlClickMaximumMilliseconds, final IAnalogOnScreenControlListener pAnalogOnScreenControlListener) { + super(pX, pY, pCamera, pControlBaseTextureRegion, pControlKnobTextureRegion, pTimeBetweenUpdates, pAnalogOnScreenControlListener); + this.mClickDetector.setTriggerClickMaximumMilliseconds(pOnControlClickMaximumMilliseconds); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + @Override + public IAnalogOnScreenControlListener getOnScreenControlListener() { + return (IAnalogOnScreenControlListener)super.getOnScreenControlListener(); + } + + public void setOnControlClickEnabled(final boolean pOnControlClickEnabled) { + this.mClickDetector.setEnabled(pOnControlClickEnabled); + } + + public void setOnControlClickMaximumMilliseconds(final long pOnControlClickMaximumMilliseconds) { + this.mClickDetector.setTriggerClickMaximumMilliseconds(pOnControlClickMaximumMilliseconds); + } + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + public void onClick(final ClickDetector pClickDetector, final TouchEvent pTouchEvent) { + this.getOnScreenControlListener().onControlClick(this); + } + + @Override + protected boolean onHandleControlBaseTouched(final TouchEvent pSceneTouchEvent, final float pTouchAreaLocalX, final float pTouchAreaLocalY) { + this.mClickDetector.onSceneTouchEvent(null, pSceneTouchEvent); + return super.onHandleControlBaseTouched(pSceneTouchEvent, pTouchAreaLocalX, pTouchAreaLocalY); + } + + @Override + protected void onUpdateControlKnob(final float pRelativeX, final float pRelativeY) { + if(pRelativeX * pRelativeX + pRelativeY * pRelativeY <= 0.25f) { + super.onUpdateControlKnob(pRelativeX, pRelativeY); + } else { + final float angleRad = MathUtils.atan2(pRelativeY, pRelativeX); + super.onUpdateControlKnob((float) Math.cos(angleRad) * 0.5f, (float) Math.sin(angleRad) * 0.5f); + } + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== + + public interface IAnalogOnScreenControlListener extends IOnScreenControlListener { + // =========================================================== + // Final Fields + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + public void onControlClick(final AnalogOnScreenControl pAnalogOnScreenControl); + } } diff --git a/AndEngine/src/org/anddev/andengine/engine/camera/hud/controls/BaseOnScreenControl.java b/AndEngine/src/org/anddev/andengine/engine/camera/hud/controls/BaseOnScreenControl.java index 01725c6b..4cb1df3e 100644 --- a/AndEngine/src/org/anddev/andengine/engine/camera/hud/controls/BaseOnScreenControl.java +++ b/AndEngine/src/org/anddev/andengine/engine/camera/hud/controls/BaseOnScreenControl.java @@ -24,193 +24,193 @@ * @since 10:43:09 - 11.07.2010 */ public abstract class BaseOnScreenControl extends HUD implements IOnSceneTouchListener { - // =========================================================== - // Constants - // =========================================================== - - private static final int INVALID_POINTER_ID = -1; - - // =========================================================== - // Fields - // =========================================================== - - private final Sprite mControlBase; - private final Sprite mControlKnob; - - private float mControlValueX; - private float mControlValueY; - - private final IOnScreenControlListener mOnScreenControlListener; - - private int mActivePointerID = INVALID_POINTER_ID; - - // =========================================================== - // Constructors - // =========================================================== - - public BaseOnScreenControl(final float pX, final float pY, final Camera pCamera, final TextureRegion pControlBaseTextureRegion, final TextureRegion pControlKnobTextureRegion, final float pTimeBetweenUpdates, final IOnScreenControlListener pOnScreenControlListener) { - this.setCamera(pCamera); - - this.mOnScreenControlListener = pOnScreenControlListener; - /* Create the control base. */ - this.mControlBase = new Sprite(pX, pY, pControlBaseTextureRegion) { - @Override - public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final float pTouchAreaLocalX, final float pTouchAreaLocalY) { - return BaseOnScreenControl.this.onHandleControlBaseTouched(pSceneTouchEvent, pTouchAreaLocalX, pTouchAreaLocalY); - } - }; - - /* Create the control knob. */ - this.mControlKnob = new Sprite(0, 0, pControlKnobTextureRegion); - this.onHandleControlKnobReleased(); - - /* Register listeners and add objects to this HUD. */ - this.setOnSceneTouchListener(this); - this.registerTouchArea(this.mControlBase); - this.registerUpdateHandler(new TimerHandler(pTimeBetweenUpdates, true, new ITimerCallback() { - @Override - public void onTimePassed(final TimerHandler pTimerHandler) { - BaseOnScreenControl.this.mOnScreenControlListener.onControlChange(BaseOnScreenControl.this, BaseOnScreenControl.this.mControlValueX, BaseOnScreenControl.this.mControlValueY); - } - })); - - this.attachChild(this.mControlBase); - this.attachChild(this.mControlKnob); - - this.setTouchAreaBindingEnabled(true); - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - public Sprite getControlBase() { - return this.mControlBase; - } - - public Sprite getControlKnob() { - return this.mControlKnob; - } - - public IOnScreenControlListener getOnScreenControlListener() { - return this.mOnScreenControlListener; - } - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) { - final int pointerID = pSceneTouchEvent.getPointerID(); - if(pointerID == this.mActivePointerID) { - this.onHandleControlBaseLeft(); - - switch(pSceneTouchEvent.getAction()) { - case MotionEvent.ACTION_UP: - case MotionEvent.ACTION_CANCEL: - this.mActivePointerID = INVALID_POINTER_ID; - } - } - return false; - } - - // =========================================================== - // Methods - // =========================================================== - - public void refreshControlKnobPosition() { - this.onUpdateControlKnob(this.mControlValueX * 0.5f, this.mControlValueY * 0.5f); - } - - /** - * When the touch happened outside of the bounds of this OnScreenControl. - * */ - protected void onHandleControlBaseLeft() { - this.onUpdateControlKnob(0, 0); - } - - /** - * When the OnScreenControl was released. - */ - protected void onHandleControlKnobReleased() { - this.onUpdateControlKnob(0, 0); - } - - protected boolean onHandleControlBaseTouched(final TouchEvent pSceneTouchEvent, final float pTouchAreaLocalX, final float pTouchAreaLocalY) { - final int pointerID = pSceneTouchEvent.getPointerID(); - - switch(pSceneTouchEvent.getAction()) { - case MotionEvent.ACTION_DOWN: - if(this.mActivePointerID == INVALID_POINTER_ID) { - this.mActivePointerID = pointerID; - this.updateControlKnob(pTouchAreaLocalX, pTouchAreaLocalY); - return true; - } - break; - case MotionEvent.ACTION_UP: - case MotionEvent.ACTION_CANCEL: - if(this.mActivePointerID == pointerID) { - this.mActivePointerID = INVALID_POINTER_ID; - this.onHandleControlKnobReleased(); - return true; - } - break; - default: - if(this.mActivePointerID == pointerID) { - this.updateControlKnob(pTouchAreaLocalX, pTouchAreaLocalY); - return true; - } - break; - } - return true; - } - - 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; - - this.onUpdateControlKnob(relativeX, relativeY); - } - - /** - * @param pRelativeX from -0.5 (left) to 0.5 (right). - * @param pRelativeY from -0.5 (top) to 0.5 (bottom). - */ - protected void onUpdateControlKnob(final float pRelativeX, final float pRelativeY) { - final Sprite controlBase = this.mControlBase; - final Sprite controlKnob = this.mControlKnob; - - 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(); - - controlKnob.setPosition(x, y); - } - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== - - public static interface IOnScreenControlListener { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Methods - // =========================================================== - - /** - * @param pBaseOnScreenControl - * @param pValueX between -1 (left) to 1 (right). - * @param pValueY between -1 (up) to 1 (down). - */ - public void onControlChange(final BaseOnScreenControl pBaseOnScreenControl, final float pValueX, final float pValueY); - } + // =========================================================== + // Constants + // =========================================================== + + private static final int INVALID_POINTER_ID = -1; + + // =========================================================== + // Fields + // =========================================================== + + private final Sprite mControlBase; + private final Sprite mControlKnob; + + private float mControlValueX; + private float mControlValueY; + + private final IOnScreenControlListener mOnScreenControlListener; + + private int mActivePointerID = INVALID_POINTER_ID; + + // =========================================================== + // Constructors + // =========================================================== + + public BaseOnScreenControl(final float pX, final float pY, final Camera pCamera, final TextureRegion pControlBaseTextureRegion, final TextureRegion pControlKnobTextureRegion, final float pTimeBetweenUpdates, final IOnScreenControlListener pOnScreenControlListener) { + this.setCamera(pCamera); + + this.mOnScreenControlListener = pOnScreenControlListener; + /* Create the control base. */ + this.mControlBase = new Sprite(pX, pY, pControlBaseTextureRegion) { + @Override + public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final float pTouchAreaLocalX, final float pTouchAreaLocalY) { + return BaseOnScreenControl.this.onHandleControlBaseTouched(pSceneTouchEvent, pTouchAreaLocalX, pTouchAreaLocalY); + } + }; + + /* Create the control knob. */ + this.mControlKnob = new Sprite(0, 0, pControlKnobTextureRegion); + this.onHandleControlKnobReleased(); + + /* Register listeners and add objects to this HUD. */ + this.setOnSceneTouchListener(this); + this.registerTouchArea(this.mControlBase); + this.registerUpdateHandler(new TimerHandler(pTimeBetweenUpdates, true, new ITimerCallback() { + @Override + public void onTimePassed(final TimerHandler pTimerHandler) { + BaseOnScreenControl.this.mOnScreenControlListener.onControlChange(BaseOnScreenControl.this, BaseOnScreenControl.this.mControlValueX, BaseOnScreenControl.this.mControlValueY); + } + })); + + this.attachChild(this.mControlBase); + this.attachChild(this.mControlKnob); + + this.setTouchAreaBindingEnabled(true); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + public Sprite getControlBase() { + return this.mControlBase; + } + + public Sprite getControlKnob() { + return this.mControlKnob; + } + + public IOnScreenControlListener getOnScreenControlListener() { + return this.mOnScreenControlListener; + } + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) { + final int pointerID = pSceneTouchEvent.getPointerID(); + if(pointerID == this.mActivePointerID) { + this.onHandleControlBaseLeft(); + + switch(pSceneTouchEvent.getAction()) { + case MotionEvent.ACTION_UP: + case MotionEvent.ACTION_CANCEL: + this.mActivePointerID = INVALID_POINTER_ID; + } + } + return false; + } + + // =========================================================== + // Methods + // =========================================================== + + public void refreshControlKnobPosition() { + this.onUpdateControlKnob(this.mControlValueX * 0.5f, this.mControlValueY * 0.5f); + } + + /** + * When the touch happened outside of the bounds of this OnScreenControl. + * */ + protected void onHandleControlBaseLeft() { + this.onUpdateControlKnob(0, 0); + } + + /** + * When the OnScreenControl was released. + */ + protected void onHandleControlKnobReleased() { + this.onUpdateControlKnob(0, 0); + } + + protected boolean onHandleControlBaseTouched(final TouchEvent pSceneTouchEvent, final float pTouchAreaLocalX, final float pTouchAreaLocalY) { + final int pointerID = pSceneTouchEvent.getPointerID(); + + switch(pSceneTouchEvent.getAction()) { + case MotionEvent.ACTION_DOWN: + if(this.mActivePointerID == INVALID_POINTER_ID) { + this.mActivePointerID = pointerID; + this.updateControlKnob(pTouchAreaLocalX, pTouchAreaLocalY); + return true; + } + break; + case MotionEvent.ACTION_UP: + case MotionEvent.ACTION_CANCEL: + if(this.mActivePointerID == pointerID) { + this.mActivePointerID = INVALID_POINTER_ID; + this.onHandleControlKnobReleased(); + return true; + } + break; + default: + if(this.mActivePointerID == pointerID) { + this.updateControlKnob(pTouchAreaLocalX, pTouchAreaLocalY); + return true; + } + break; + } + return true; + } + + 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; + + this.onUpdateControlKnob(relativeX, relativeY); + } + + /** + * @param pRelativeX from -0.5 (left) to 0.5 (right). + * @param pRelativeY from -0.5 (top) to 0.5 (bottom). + */ + protected void onUpdateControlKnob(final float pRelativeX, final float pRelativeY) { + final Sprite controlBase = this.mControlBase; + final Sprite controlKnob = this.mControlKnob; + + 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(); + + controlKnob.setPosition(x, y); + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== + + public static interface IOnScreenControlListener { + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + /** + * @param pBaseOnScreenControl + * @param pValueX between -1 (left) to 1 (right). + * @param pValueY between -1 (up) to 1 (down). + */ + public void onControlChange(final BaseOnScreenControl pBaseOnScreenControl, final float pValueX, final float pValueY); + } } diff --git a/AndEngine/src/org/anddev/andengine/engine/camera/hud/controls/DigitalOnScreenControl.java b/AndEngine/src/org/anddev/andengine/engine/camera/hud/controls/DigitalOnScreenControl.java index 7edb3ac3..0f0c6823 100644 --- a/AndEngine/src/org/anddev/andengine/engine/camera/hud/controls/DigitalOnScreenControl.java +++ b/AndEngine/src/org/anddev/andengine/engine/camera/hud/controls/DigitalOnScreenControl.java @@ -13,108 +13,108 @@ */ public class DigitalOnScreenControl extends BaseOnScreenControl { - // =========================================================== - // Constants - // =========================================================== - - private static final float EXTENT_SIDE = 0.5f; - private static final float EXTENT_DIAGONAL = 0.354f; - - private static final float ANGLE_DELTA = 22.5f; - - // =========================================================== - // Fields - // =========================================================== - - private boolean mAllowDiagonal; - - // =========================================================== - // Constructors - // =========================================================== - - public DigitalOnScreenControl(final float pX, final float pY, final Camera pCamera, final TextureRegion pControlBaseTextureRegion, final TextureRegion pControlKnobTextureRegion, final float pTimeBetweenUpdates, final IOnScreenControlListener pOnScreenControlListener) { - this(pX, pY, pCamera, pControlBaseTextureRegion, pControlKnobTextureRegion, pTimeBetweenUpdates, false, pOnScreenControlListener); - } - - public DigitalOnScreenControl(final float pX, final float pY, final Camera pCamera, final TextureRegion pControlBaseTextureRegion, final TextureRegion pControlKnobTextureRegion, final float pTimeBetweenUpdates, final boolean pAllowDiagonal, final IOnScreenControlListener pOnScreenControlListener) { - super(pX, pY, pCamera, pControlBaseTextureRegion, pControlKnobTextureRegion, pTimeBetweenUpdates, pOnScreenControlListener); - this.mAllowDiagonal = pAllowDiagonal; - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - public boolean isAllowDiagonal() { - return this.mAllowDiagonal; - } - - public void setAllowDiagonal(final boolean pAllowDiagonal) { - this.mAllowDiagonal = pAllowDiagonal; - } - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - protected void onUpdateControlKnob(final float pRelativeX, final float pRelativeY) { - if(pRelativeX == 0 && pRelativeY == 0) { - super.onUpdateControlKnob(0, 0); - return; - } - - if(this.mAllowDiagonal) { - final float angle = MathUtils.radToDeg(MathUtils.atan2(pRelativeY, pRelativeX)) + 180; - if(this.testDiagonalAngle(0, angle) || this.testDiagonalAngle(360, angle)) { - super.onUpdateControlKnob(-EXTENT_SIDE, 0); - } else if(this.testDiagonalAngle(45, angle)) { - super.onUpdateControlKnob(-EXTENT_DIAGONAL, -EXTENT_DIAGONAL); - } else if(this.testDiagonalAngle(90, angle)) { - super.onUpdateControlKnob(0, -EXTENT_SIDE); - } else if(this.testDiagonalAngle(135, angle)) { - super.onUpdateControlKnob(EXTENT_DIAGONAL, -EXTENT_DIAGONAL); - } else if(this.testDiagonalAngle(180, angle)) { - super.onUpdateControlKnob(EXTENT_SIDE, 0); - } else if(this.testDiagonalAngle(225, angle)) { - super.onUpdateControlKnob(EXTENT_DIAGONAL, EXTENT_DIAGONAL); - } else if(this.testDiagonalAngle(270, angle)) { - super.onUpdateControlKnob(0, EXTENT_SIDE); - } 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) { - super.onUpdateControlKnob(EXTENT_SIDE, 0); - } else if(pRelativeX < 0) { - super.onUpdateControlKnob(-EXTENT_SIDE, 0); - } else if(pRelativeX == 0) { - super.onUpdateControlKnob(0, 0); - } - } else { - if(pRelativeY > 0) { - super.onUpdateControlKnob(0, EXTENT_SIDE); - } else if(pRelativeY < 0) { - super.onUpdateControlKnob(0, -EXTENT_SIDE); - } else if(pRelativeY == 0) { - super.onUpdateControlKnob(0, 0); - } - } - } - } - - private boolean testDiagonalAngle(final float pTestAngle, final float pActualAngle) { - return pActualAngle > pTestAngle - ANGLE_DELTA && pActualAngle < pTestAngle + ANGLE_DELTA; - } - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + private static final float EXTENT_SIDE = 0.5f; + private static final float EXTENT_DIAGONAL = 0.354f; + + private static final float ANGLE_DELTA = 22.5f; + + // =========================================================== + // Fields + // =========================================================== + + private boolean mAllowDiagonal; + + // =========================================================== + // Constructors + // =========================================================== + + public DigitalOnScreenControl(final float pX, final float pY, final Camera pCamera, final TextureRegion pControlBaseTextureRegion, final TextureRegion pControlKnobTextureRegion, final float pTimeBetweenUpdates, final IOnScreenControlListener pOnScreenControlListener) { + this(pX, pY, pCamera, pControlBaseTextureRegion, pControlKnobTextureRegion, pTimeBetweenUpdates, false, pOnScreenControlListener); + } + + public DigitalOnScreenControl(final float pX, final float pY, final Camera pCamera, final TextureRegion pControlBaseTextureRegion, final TextureRegion pControlKnobTextureRegion, final float pTimeBetweenUpdates, final boolean pAllowDiagonal, final IOnScreenControlListener pOnScreenControlListener) { + super(pX, pY, pCamera, pControlBaseTextureRegion, pControlKnobTextureRegion, pTimeBetweenUpdates, pOnScreenControlListener); + this.mAllowDiagonal = pAllowDiagonal; + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + public boolean isAllowDiagonal() { + return this.mAllowDiagonal; + } + + public void setAllowDiagonal(final boolean pAllowDiagonal) { + this.mAllowDiagonal = pAllowDiagonal; + } + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + protected void onUpdateControlKnob(final float pRelativeX, final float pRelativeY) { + if(pRelativeX == 0 && pRelativeY == 0) { + super.onUpdateControlKnob(0, 0); + return; + } + + if(this.mAllowDiagonal) { + final float angle = MathUtils.radToDeg(MathUtils.atan2(pRelativeY, pRelativeX)) + 180; + if(this.testDiagonalAngle(0, angle) || this.testDiagonalAngle(360, angle)) { + super.onUpdateControlKnob(-EXTENT_SIDE, 0); + } else if(this.testDiagonalAngle(45, angle)) { + super.onUpdateControlKnob(-EXTENT_DIAGONAL, -EXTENT_DIAGONAL); + } else if(this.testDiagonalAngle(90, angle)) { + super.onUpdateControlKnob(0, -EXTENT_SIDE); + } else if(this.testDiagonalAngle(135, angle)) { + super.onUpdateControlKnob(EXTENT_DIAGONAL, -EXTENT_DIAGONAL); + } else if(this.testDiagonalAngle(180, angle)) { + super.onUpdateControlKnob(EXTENT_SIDE, 0); + } else if(this.testDiagonalAngle(225, angle)) { + super.onUpdateControlKnob(EXTENT_DIAGONAL, EXTENT_DIAGONAL); + } else if(this.testDiagonalAngle(270, angle)) { + super.onUpdateControlKnob(0, EXTENT_SIDE); + } 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) { + super.onUpdateControlKnob(EXTENT_SIDE, 0); + } else if(pRelativeX < 0) { + super.onUpdateControlKnob(-EXTENT_SIDE, 0); + } else if(pRelativeX == 0) { + super.onUpdateControlKnob(0, 0); + } + } else { + if(pRelativeY > 0) { + super.onUpdateControlKnob(0, EXTENT_SIDE); + } else if(pRelativeY < 0) { + super.onUpdateControlKnob(0, -EXTENT_SIDE); + } else if(pRelativeY == 0) { + super.onUpdateControlKnob(0, 0); + } + } + } + } + + private boolean testDiagonalAngle(final float pTestAngle, final float pActualAngle) { + return pActualAngle > pTestAngle - ANGLE_DELTA && pActualAngle < pTestAngle + ANGLE_DELTA; + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/engine/handler/BaseEntityUpdateHandler.java b/AndEngine/src/org/anddev/andengine/engine/handler/BaseEntityUpdateHandler.java index a723997a..85ff6f25 100644 --- a/AndEngine/src/org/anddev/andengine/engine/handler/BaseEntityUpdateHandler.java +++ b/AndEngine/src/org/anddev/andengine/engine/handler/BaseEntityUpdateHandler.java @@ -10,49 +10,49 @@ * @since 14:00:25 - 24.12.2010 */ public abstract class BaseEntityUpdateHandler implements IUpdateHandler { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - private final IEntity mEntity; + private final IEntity mEntity; - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - public BaseEntityUpdateHandler(final IEntity pEntity) { - this.mEntity = pEntity; - } + public BaseEntityUpdateHandler(final IEntity pEntity) { + this.mEntity = pEntity; + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - protected abstract void onUpdate(final float pSecondsElapsed, final IEntity pEntity); + protected abstract void onUpdate(final float pSecondsElapsed, final IEntity pEntity); - @Override - public final void onUpdate(final float pSecondsElapsed) { - this.onUpdate(pSecondsElapsed, this.mEntity); - } + @Override + public final void onUpdate(final float pSecondsElapsed) { + this.onUpdate(pSecondsElapsed, this.mEntity); + } - @Override - public void reset() { + @Override + public void reset() { - } + } - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/engine/handler/IUpdateHandler.java b/AndEngine/src/org/anddev/andengine/engine/handler/IUpdateHandler.java index cefc5cbd..c9f129de 100644 --- a/AndEngine/src/org/anddev/andengine/engine/handler/IUpdateHandler.java +++ b/AndEngine/src/org/anddev/andengine/engine/handler/IUpdateHandler.java @@ -10,30 +10,30 @@ * @since 12:24:09 - 11.03.2010 */ public interface IUpdateHandler { - // =========================================================== - // Final Fields - // =========================================================== + // =========================================================== + // Final Fields + // =========================================================== - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - public void onUpdate(final float pSecondsElapsed); - public void reset(); - - // TODO Maybe add onRegister and onUnregister. (Maybe add SimpleUpdateHandler that implements all methods, but onUpdate) + 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 - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== + + public interface IUpdateHandlerMatcher extends IMatcher { + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Methods - // =========================================================== - } + // =========================================================== + // Methods + // =========================================================== + } } diff --git a/AndEngine/src/org/anddev/andengine/engine/handler/UpdateHandlerList.java b/AndEngine/src/org/anddev/andengine/engine/handler/UpdateHandlerList.java index e4f01a5d..05e6074f 100644 --- a/AndEngine/src/org/anddev/andengine/engine/handler/UpdateHandlerList.java +++ b/AndEngine/src/org/anddev/andengine/engine/handler/UpdateHandlerList.java @@ -10,57 +10,57 @@ * @since 09:45:22 - 31.03.2010 */ public class UpdateHandlerList extends SmartList implements IUpdateHandler { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - private static final long serialVersionUID = -8842562717687229277L; + private static final long serialVersionUID = -8842562717687229277L; - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - public UpdateHandlerList() { + public UpdateHandlerList() { - } + } - public UpdateHandlerList(final int pCapacity) { - super(pCapacity); - } + public UpdateHandlerList(final int pCapacity) { + super(pCapacity); + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - @Override - public void onUpdate(final float pSecondsElapsed) { - final int handlerCount = this.size(); - for(int i = handlerCount - 1; i >= 0; i--) { - this.get(i).onUpdate(pSecondsElapsed); - } - } + @Override + public void onUpdate(final float pSecondsElapsed) { + final int handlerCount = this.size(); + for(int i = handlerCount - 1; i >= 0; i--) { + this.get(i).onUpdate(pSecondsElapsed); + } + } - @Override - public void reset() { - final int handlerCount = this.size(); - for(int i = handlerCount - 1; i >= 0; i--) { - this.get(i).reset(); - } - } + @Override + public void reset() { + final int handlerCount = this.size(); + for(int i = handlerCount - 1; i >= 0; i--) { + this.get(i).reset(); + } + } - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/engine/handler/collision/CollisionHandler.java b/AndEngine/src/org/anddev/andengine/engine/handler/collision/CollisionHandler.java index 6d95d480..eeffe6b1 100644 --- a/AndEngine/src/org/anddev/andengine/engine/handler/collision/CollisionHandler.java +++ b/AndEngine/src/org/anddev/andengine/engine/handler/collision/CollisionHandler.java @@ -14,76 +14,76 @@ * @since 12:19:35 - 11.03.2010 */ public class CollisionHandler implements IUpdateHandler { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - private final ICollisionCallback mCollisionCallback; - private final IShape mCheckShape; - private final ArrayList mTargetStaticEntities; - - // =========================================================== - // Constructors - // =========================================================== - - public CollisionHandler(final ICollisionCallback pCollisionCallback, final IShape pCheckShape, final IShape pTargetShape) throws IllegalArgumentException { - this(pCollisionCallback, pCheckShape, ListUtils.toList(pTargetShape)); - } - - public CollisionHandler(final ICollisionCallback pCollisionCallback, final IShape pCheckShape, final ArrayList pTargetStaticEntities) throws IllegalArgumentException { - if (pCollisionCallback == null) { - throw new IllegalArgumentException( "pCollisionCallback must not be null!"); - } - if (pCheckShape == null) { - throw new IllegalArgumentException( "pCheckShape must not be null!"); - } - if (pTargetStaticEntities == null) { - throw new IllegalArgumentException( "pTargetStaticEntities must not be null!"); - } - - this.mCollisionCallback = pCollisionCallback; - this.mCheckShape = pCheckShape; - this.mTargetStaticEntities = pTargetStaticEntities; - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - public void onUpdate(final float pSecondsElapsed) { - final IShape checkShape = this.mCheckShape; - final ArrayList staticEntities = this.mTargetStaticEntities; - final int staticEntityCount = staticEntities.size(); - - 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) { - return; - } - } - } - } - - @Override - public void reset() { - - } - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + private final ICollisionCallback mCollisionCallback; + private final IShape mCheckShape; + private final ArrayList mTargetStaticEntities; + + // =========================================================== + // Constructors + // =========================================================== + + public CollisionHandler(final ICollisionCallback pCollisionCallback, final IShape pCheckShape, final IShape pTargetShape) throws IllegalArgumentException { + this(pCollisionCallback, pCheckShape, ListUtils.toList(pTargetShape)); + } + + public CollisionHandler(final ICollisionCallback pCollisionCallback, final IShape pCheckShape, final ArrayList pTargetStaticEntities) throws IllegalArgumentException { + if (pCollisionCallback == null) { + throw new IllegalArgumentException( "pCollisionCallback must not be null!"); + } + if (pCheckShape == null) { + throw new IllegalArgumentException( "pCheckShape must not be null!"); + } + if (pTargetStaticEntities == null) { + throw new IllegalArgumentException( "pTargetStaticEntities must not be null!"); + } + + this.mCollisionCallback = pCollisionCallback; + this.mCheckShape = pCheckShape; + this.mTargetStaticEntities = pTargetStaticEntities; + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + public void onUpdate(final float pSecondsElapsed) { + final IShape checkShape = this.mCheckShape; + final ArrayList staticEntities = this.mTargetStaticEntities; + final int staticEntityCount = staticEntities.size(); + + 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) { + return; + } + } + } + } + + @Override + public void reset() { + + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/engine/handler/collision/ICollisionCallback.java b/AndEngine/src/org/anddev/andengine/engine/handler/collision/ICollisionCallback.java index 95be4371..c8f177c3 100644 --- a/AndEngine/src/org/anddev/andengine/engine/handler/collision/ICollisionCallback.java +++ b/AndEngine/src/org/anddev/andengine/engine/handler/collision/ICollisionCallback.java @@ -10,18 +10,18 @@ * @since 12:05:39 - 11.03.2010 */ public interface ICollisionCallback { - // =========================================================== - // Final Fields - // =========================================================== + // =========================================================== + // Final Fields + // =========================================================== - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - /** - * @param pCheckShape - * @param pTargetShape - * @return true to proceed, false to stop further collosion-checks. - */ - public boolean onCollision(final IShape pCheckShape, final IShape pTargetShape); + /** + * @param pCheckShape + * @param pTargetShape + * @return true to proceed, false to stop further collosion-checks. + */ + public boolean onCollision(final IShape pCheckShape, final IShape pTargetShape); } diff --git a/AndEngine/src/org/anddev/andengine/engine/handler/physics/PhysicsHandler.java b/AndEngine/src/org/anddev/andengine/engine/handler/physics/PhysicsHandler.java index 9033df68..a3fb7c68 100644 --- a/AndEngine/src/org/anddev/andengine/engine/handler/physics/PhysicsHandler.java +++ b/AndEngine/src/org/anddev/andengine/engine/handler/physics/PhysicsHandler.java @@ -11,153 +11,153 @@ * @since 13:53:07 - 24.12.2010 */ public class PhysicsHandler extends BaseEntityUpdateHandler { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - private boolean mEnabled = true; + private boolean mEnabled = true; - protected float mAccelerationX = 0; - protected float mAccelerationY = 0; - - protected float mVelocityX = 0; - protected float mVelocityY = 0; - - protected float mAngularVelocity = 0; - - // =========================================================== - // Constructors - // =========================================================== - - public PhysicsHandler(final IEntity pEntity) { - super(pEntity); - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - public boolean isEnabled() { - return this.mEnabled; - } - - public void setEnabled(final boolean pEnabled) { - this.mEnabled = pEnabled; - } - - public float getVelocityX() { - return this.mVelocityX; - } - - public float getVelocityY() { - return this.mVelocityY; - } - - public void setVelocityX(final float pVelocityX) { - this.mVelocityX = pVelocityX; - } - - public void setVelocityY(final float pVelocityY) { - this.mVelocityY = pVelocityY; - } - - public void setVelocity(final float pVelocity) { - this.mVelocityX = pVelocity; - this.mVelocityY = pVelocity; - } - - public void setVelocity(final float pVelocityX, final float pVelocityY) { - this.mVelocityX = pVelocityX; - this.mVelocityY = pVelocityY; - } - - public float getAccelerationX() { - return this.mAccelerationX; - } - - public float getAccelerationY() { - return this.mAccelerationY; - } - - public void setAccelerationX(final float pAccelerationX) { - this.mAccelerationX = pAccelerationX; - } - - public void setAccelerationY(final float pAccelerationY) { - this.mAccelerationY = pAccelerationY; - } - - public void setAcceleration(final float pAccelerationX, final float pAccelerationY) { - this.mAccelerationX = pAccelerationX; - this.mAccelerationY = pAccelerationY; - } - - public void setAcceleration(final float pAcceleration) { - this.mAccelerationX = pAcceleration; - this.mAccelerationY = pAcceleration; - } - - public void accelerate(final float pAccelerationX, final float pAccelerationY) { - this.mAccelerationX += pAccelerationX; - this.mAccelerationY += pAccelerationY; - } - - public float getAngularVelocity() { - return this.mAngularVelocity; - } - - public void setAngularVelocity(final float pAngularVelocity) { - this.mAngularVelocity = pAngularVelocity; - } - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - protected void onUpdate(final float pSecondsElapsed, final IEntity pEntity) { - if(this.mEnabled) { - /* Apply linear acceleration. */ - final float accelerationX = this.mAccelerationX; - final float accelerationY = this.mAccelerationY; - if(accelerationX != 0 || accelerationY != 0) { - this.mVelocityX += accelerationX * pSecondsElapsed; - this.mVelocityY += accelerationY * pSecondsElapsed; - } - - /* Apply angular velocity. */ - final float angularVelocity = this.mAngularVelocity; - 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) { - pEntity.setPosition(pEntity.getX() + velocityX * pSecondsElapsed, pEntity.getY() + velocityY * pSecondsElapsed); - } - } - } - - @Override - public void reset() { - this.mAccelerationX = 0; - this.mAccelerationY = 0; - this.mVelocityX = 0; - this.mVelocityY = 0; - this.mAngularVelocity = 0; - } - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + protected float mAccelerationX = 0; + protected float mAccelerationY = 0; + + protected float mVelocityX = 0; + protected float mVelocityY = 0; + + protected float mAngularVelocity = 0; + + // =========================================================== + // Constructors + // =========================================================== + + public PhysicsHandler(final IEntity pEntity) { + super(pEntity); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + public boolean isEnabled() { + return this.mEnabled; + } + + public void setEnabled(final boolean pEnabled) { + this.mEnabled = pEnabled; + } + + public float getVelocityX() { + return this.mVelocityX; + } + + public float getVelocityY() { + return this.mVelocityY; + } + + public void setVelocityX(final float pVelocityX) { + this.mVelocityX = pVelocityX; + } + + public void setVelocityY(final float pVelocityY) { + this.mVelocityY = pVelocityY; + } + + public void setVelocity(final float pVelocity) { + this.mVelocityX = pVelocity; + this.mVelocityY = pVelocity; + } + + public void setVelocity(final float pVelocityX, final float pVelocityY) { + this.mVelocityX = pVelocityX; + this.mVelocityY = pVelocityY; + } + + public float getAccelerationX() { + return this.mAccelerationX; + } + + public float getAccelerationY() { + return this.mAccelerationY; + } + + public void setAccelerationX(final float pAccelerationX) { + this.mAccelerationX = pAccelerationX; + } + + public void setAccelerationY(final float pAccelerationY) { + this.mAccelerationY = pAccelerationY; + } + + public void setAcceleration(final float pAccelerationX, final float pAccelerationY) { + this.mAccelerationX = pAccelerationX; + this.mAccelerationY = pAccelerationY; + } + + public void setAcceleration(final float pAcceleration) { + this.mAccelerationX = pAcceleration; + this.mAccelerationY = pAcceleration; + } + + public void accelerate(final float pAccelerationX, final float pAccelerationY) { + this.mAccelerationX += pAccelerationX; + this.mAccelerationY += pAccelerationY; + } + + public float getAngularVelocity() { + return this.mAngularVelocity; + } + + public void setAngularVelocity(final float pAngularVelocity) { + this.mAngularVelocity = pAngularVelocity; + } + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + protected void onUpdate(final float pSecondsElapsed, final IEntity pEntity) { + if(this.mEnabled) { + /* Apply linear acceleration. */ + final float accelerationX = this.mAccelerationX; + final float accelerationY = this.mAccelerationY; + if(accelerationX != 0 || accelerationY != 0) { + this.mVelocityX += accelerationX * pSecondsElapsed; + this.mVelocityY += accelerationY * pSecondsElapsed; + } + + /* Apply angular velocity. */ + final float angularVelocity = this.mAngularVelocity; + 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) { + pEntity.setPosition(pEntity.getX() + velocityX * pSecondsElapsed, pEntity.getY() + velocityY * pSecondsElapsed); + } + } + } + + @Override + public void reset() { + this.mAccelerationX = 0; + this.mAccelerationY = 0; + this.mVelocityX = 0; + this.mVelocityY = 0; + this.mAngularVelocity = 0; + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/engine/handler/runnable/RunnableHandler.java b/AndEngine/src/org/anddev/andengine/engine/handler/runnable/RunnableHandler.java index 91567f89..fe792b10 100644 --- a/AndEngine/src/org/anddev/andengine/engine/handler/runnable/RunnableHandler.java +++ b/AndEngine/src/org/anddev/andengine/engine/handler/runnable/RunnableHandler.java @@ -12,52 +12,52 @@ * @since 10:24:39 - 18.06.2010 */ public class RunnableHandler implements IUpdateHandler { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - private final ArrayList mRunnables = new ArrayList(); - - // =========================================================== - // Constructors - // =========================================================== - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - 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--) { - runnables.get(i).run(); - } - runnables.clear(); - } - - @Override - public void reset() { - this.mRunnables.clear(); - } - - // =========================================================== - // Methods - // =========================================================== - - public synchronized void postRunnable(final Runnable pRunnable) { - this.mRunnables.add(pRunnable); - } - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + private final ArrayList mRunnables = new ArrayList(); + + // =========================================================== + // Constructors + // =========================================================== + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + 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--) { + runnables.get(i).run(); + } + runnables.clear(); + } + + @Override + public void reset() { + this.mRunnables.clear(); + } + + // =========================================================== + // Methods + // =========================================================== + + public synchronized void postRunnable(final Runnable pRunnable) { + this.mRunnables.add(pRunnable); + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/engine/handler/timer/ITimerCallback.java b/AndEngine/src/org/anddev/andengine/engine/handler/timer/ITimerCallback.java index 85ba5962..f009f222 100644 --- a/AndEngine/src/org/anddev/andengine/engine/handler/timer/ITimerCallback.java +++ b/AndEngine/src/org/anddev/andengine/engine/handler/timer/ITimerCallback.java @@ -8,13 +8,13 @@ * @since 16:23:25 - 12.03.2010 */ public interface ITimerCallback { - // =========================================================== - // Final Fields - // =========================================================== + // =========================================================== + // Final Fields + // =========================================================== - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - public void onTimePassed(final TimerHandler pTimerHandler); + public void onTimePassed(final TimerHandler pTimerHandler); } diff --git a/AndEngine/src/org/anddev/andengine/engine/handler/timer/TimerHandler.java b/AndEngine/src/org/anddev/andengine/engine/handler/timer/TimerHandler.java index 930ccdb1..401319c6 100644 --- a/AndEngine/src/org/anddev/andengine/engine/handler/timer/TimerHandler.java +++ b/AndEngine/src/org/anddev/andengine/engine/handler/timer/TimerHandler.java @@ -10,100 +10,100 @@ * @since 16:23:58 - 12.03.2010 */ public class TimerHandler implements IUpdateHandler { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - private float mTimerSeconds; - private float mTimerSecondsElapsed; - private boolean mTimerCallbackTriggered; - protected final ITimerCallback mTimerCallback; - private boolean mAutoReset; - - // =========================================================== - // Constructors - // =========================================================== - - public TimerHandler(final float pTimerSeconds, final ITimerCallback pTimerCallback) { - this(pTimerSeconds, false, pTimerCallback); - } - - public TimerHandler(final float pTimerSeconds, final boolean pAutoReset, final ITimerCallback pTimerCallback) { - this.mTimerSeconds = pTimerSeconds; - this.mAutoReset = pAutoReset; - this.mTimerCallback = pTimerCallback; - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - public boolean isAutoReset() { - return this.mAutoReset; - } - - public void setAutoReset(final boolean pAutoReset) { - this.mAutoReset = pAutoReset; - } - - public void setTimerSeconds(final float pTimerSeconds) { - this.mTimerSeconds = pTimerSeconds; - } - - public float getTimerSeconds() { - return this.mTimerSeconds; - } - - public float getTimerSecondsElapsed() { - return this.mTimerSecondsElapsed; - } - - public boolean isTimerCallbackTriggered() { - return this.mTimerCallbackTriggered; - } - - public void setTimerCallbackTriggered(boolean pTimerCallbackTriggered) { - this.mTimerCallbackTriggered = pTimerCallbackTriggered; - } - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - public void onUpdate(final float pSecondsElapsed) { - if(this.mAutoReset) { - this.mTimerSecondsElapsed += pSecondsElapsed; - while(this.mTimerSecondsElapsed >= this.mTimerSeconds) { - this.mTimerSecondsElapsed -= this.mTimerSeconds; - this.mTimerCallback.onTimePassed(this); - } - } else { - if(!this.mTimerCallbackTriggered) { - this.mTimerSecondsElapsed += pSecondsElapsed; - if(this.mTimerSecondsElapsed >= this.mTimerSeconds) { - this.mTimerCallbackTriggered = true; - this.mTimerCallback.onTimePassed(this); - } - } - } - } - - @Override - public void reset() { - this.mTimerCallbackTriggered = false; - this.mTimerSecondsElapsed = 0; - } - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + private float mTimerSeconds; + private float mTimerSecondsElapsed; + private boolean mTimerCallbackTriggered; + protected final ITimerCallback mTimerCallback; + private boolean mAutoReset; + + // =========================================================== + // Constructors + // =========================================================== + + public TimerHandler(final float pTimerSeconds, final ITimerCallback pTimerCallback) { + this(pTimerSeconds, false, pTimerCallback); + } + + public TimerHandler(final float pTimerSeconds, final boolean pAutoReset, final ITimerCallback pTimerCallback) { + this.mTimerSeconds = pTimerSeconds; + this.mAutoReset = pAutoReset; + this.mTimerCallback = pTimerCallback; + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + public boolean isAutoReset() { + return this.mAutoReset; + } + + public void setAutoReset(final boolean pAutoReset) { + this.mAutoReset = pAutoReset; + } + + public void setTimerSeconds(final float pTimerSeconds) { + this.mTimerSeconds = pTimerSeconds; + } + + public float getTimerSeconds() { + return this.mTimerSeconds; + } + + public float getTimerSecondsElapsed() { + return this.mTimerSecondsElapsed; + } + + public boolean isTimerCallbackTriggered() { + return this.mTimerCallbackTriggered; + } + + public void setTimerCallbackTriggered(boolean pTimerCallbackTriggered) { + this.mTimerCallbackTriggered = pTimerCallbackTriggered; + } + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + public void onUpdate(final float pSecondsElapsed) { + if(this.mAutoReset) { + this.mTimerSecondsElapsed += pSecondsElapsed; + while(this.mTimerSecondsElapsed >= this.mTimerSeconds) { + this.mTimerSecondsElapsed -= this.mTimerSeconds; + this.mTimerCallback.onTimePassed(this); + } + } else { + if(!this.mTimerCallbackTriggered) { + this.mTimerSecondsElapsed += pSecondsElapsed; + if(this.mTimerSecondsElapsed >= this.mTimerSeconds) { + this.mTimerCallbackTriggered = true; + this.mTimerCallback.onTimePassed(this); + } + } + } + } + + @Override + public void reset() { + this.mTimerCallbackTriggered = false; + this.mTimerSecondsElapsed = 0; + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/engine/options/EngineOptions.java b/AndEngine/src/org/anddev/andengine/engine/options/EngineOptions.java index 7d070e12..f5b71908 100644 --- a/AndEngine/src/org/anddev/andengine/engine/options/EngineOptions.java +++ b/AndEngine/src/org/anddev/andengine/engine/options/EngineOptions.java @@ -11,122 +11,122 @@ * @since 15:59:52 - 09.03.2010 */ public class EngineOptions { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - private final boolean mFullscreen; - private final ScreenOrientation mScreenOrientation; - private final IResolutionPolicy mResolutionPolicy; - private final Camera mCamera; - - private final TouchOptions mTouchOptions = new TouchOptions(); - private final RenderOptions mRenderOptions = new RenderOptions(); - - private boolean mNeedsSound; - private boolean mNeedsMusic; - private WakeLockOptions mWakeLockOptions = WakeLockOptions.SCREEN_BRIGHT; - private int mUpdateThreadPriority = android.os.Process.THREAD_PRIORITY_DEFAULT;; - - // =========================================================== - // Constructors - // =========================================================== - - public EngineOptions(final boolean pFullscreen, final ScreenOrientation pScreenOrientation, final IResolutionPolicy pResolutionPolicy, final Camera pCamera) { - this.mFullscreen = pFullscreen; - this.mScreenOrientation = pScreenOrientation; - this.mResolutionPolicy = pResolutionPolicy; - this.mCamera = pCamera; - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - public TouchOptions getTouchOptions() { - return this.mTouchOptions; - } - - public RenderOptions getRenderOptions() { - return this.mRenderOptions; - } - - public boolean isFullscreen() { - return this.mFullscreen; - } - - public ScreenOrientation getScreenOrientation() { - return this.mScreenOrientation; - } - - public IResolutionPolicy getResolutionPolicy() { - return this.mResolutionPolicy; - } - - public Camera getCamera() { - return this.mCamera; - } - - public int getUpdateThreadPriority() { - return this.mUpdateThreadPriority; - } - - /** - * @param pUpdateThreadPriority Use constants from: {@link android.os.Process}. - */ - public void setUpdateThreadPriority(final int pUpdateThreadPriority) { - this.mUpdateThreadPriority = pUpdateThreadPriority; - } - - public boolean needsSound() { - return this.mNeedsSound; - } - - public EngineOptions setNeedsSound(final boolean pNeedsSound) { - this.mNeedsSound = pNeedsSound; - return this; - } - - public boolean needsMusic() { - return this.mNeedsMusic; - } - - public EngineOptions setNeedsMusic(final boolean pNeedsMusic) { - this.mNeedsMusic = pNeedsMusic; - return this; - } - - public WakeLockOptions getWakeLockOptions() { - return this.mWakeLockOptions; - } - - public EngineOptions setWakeLockOptions(final WakeLockOptions pWakeLockOptions) { - this.mWakeLockOptions = pWakeLockOptions; - return this; - } - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== - - public static enum ScreenOrientation { - // =========================================================== - // Elements - // =========================================================== - - LANDSCAPE, - PORTRAIT; - } -} \ No newline at end of file + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + private final boolean mFullscreen; + private final ScreenOrientation mScreenOrientation; + private final IResolutionPolicy mResolutionPolicy; + private final Camera mCamera; + + private final TouchOptions mTouchOptions = new TouchOptions(); + private final RenderOptions mRenderOptions = new RenderOptions(); + + private boolean mNeedsSound; + private boolean mNeedsMusic; + private WakeLockOptions mWakeLockOptions = WakeLockOptions.SCREEN_BRIGHT; + private int mUpdateThreadPriority = android.os.Process.THREAD_PRIORITY_DEFAULT;; + + // =========================================================== + // Constructors + // =========================================================== + + public EngineOptions(final boolean pFullscreen, final ScreenOrientation pScreenOrientation, final IResolutionPolicy pResolutionPolicy, final Camera pCamera) { + this.mFullscreen = pFullscreen; + this.mScreenOrientation = pScreenOrientation; + this.mResolutionPolicy = pResolutionPolicy; + this.mCamera = pCamera; + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + public TouchOptions getTouchOptions() { + return this.mTouchOptions; + } + + public RenderOptions getRenderOptions() { + return this.mRenderOptions; + } + + public boolean isFullscreen() { + return this.mFullscreen; + } + + public ScreenOrientation getScreenOrientation() { + return this.mScreenOrientation; + } + + public IResolutionPolicy getResolutionPolicy() { + return this.mResolutionPolicy; + } + + public Camera getCamera() { + return this.mCamera; + } + + public int getUpdateThreadPriority() { + return this.mUpdateThreadPriority; + } + + /** + * @param pUpdateThreadPriority Use constants from: {@link android.os.Process}. + */ + public void setUpdateThreadPriority(final int pUpdateThreadPriority) { + this.mUpdateThreadPriority = pUpdateThreadPriority; + } + + public boolean needsSound() { + return this.mNeedsSound; + } + + public EngineOptions setNeedsSound(final boolean pNeedsSound) { + this.mNeedsSound = pNeedsSound; + return this; + } + + public boolean needsMusic() { + return this.mNeedsMusic; + } + + public EngineOptions setNeedsMusic(final boolean pNeedsMusic) { + this.mNeedsMusic = pNeedsMusic; + return this; + } + + public WakeLockOptions getWakeLockOptions() { + return this.mWakeLockOptions; + } + + public EngineOptions setWakeLockOptions(final WakeLockOptions pWakeLockOptions) { + this.mWakeLockOptions = pWakeLockOptions; + return this; + } + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== + + public static enum ScreenOrientation { + // =========================================================== + // Elements + // =========================================================== + + LANDSCAPE, + PORTRAIT; + } +} diff --git a/AndEngine/src/org/anddev/andengine/engine/options/RenderOptions.java b/AndEngine/src/org/anddev/andengine/engine/options/RenderOptions.java index 34e0e8ce..b839e340 100644 --- a/AndEngine/src/org/anddev/andengine/engine/options/RenderOptions.java +++ b/AndEngine/src/org/anddev/andengine/engine/options/RenderOptions.java @@ -8,74 +8,74 @@ * @since 13:01:40 - 02.07.2010 */ public class RenderOptions { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - private boolean mDisableExtensionVertexBufferObjects = false; - private boolean mDisableExtensionDrawTexture = false; - - // =========================================================== - // Constructors - // =========================================================== - - // =========================================================== - // Getter & Setter - // =========================================================== - - /** - * Default: false - */ - public boolean isDisableExtensionVertexBufferObjects() { - return this.mDisableExtensionVertexBufferObjects; - } - - public RenderOptions enableExtensionVertexBufferObjects() { - return this.setDisableExtensionVertexBufferObjects(false); - } - - public RenderOptions disableExtensionVertexBufferObjects() { - return this.setDisableExtensionVertexBufferObjects(true); - } - - public RenderOptions setDisableExtensionVertexBufferObjects(final boolean pDisableExtensionVertexBufferObjects) { - this.mDisableExtensionVertexBufferObjects = pDisableExtensionVertexBufferObjects; - return this; - } - - /** - * Default: false - */ - public boolean isDisableExtensionDrawTexture() { - return this.mDisableExtensionDrawTexture; - } - - public RenderOptions enableExtensionDrawTexture() { - return this.setDisableExtensionDrawTexture(false); - } - - public RenderOptions disableExtensionDrawTexture() { - return this.setDisableExtensionDrawTexture(true); - } - - public RenderOptions setDisableExtensionDrawTexture(final boolean pDisableExtensionDrawTexture) { - this.mDisableExtensionDrawTexture = pDisableExtensionDrawTexture; - return this; - } - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + private boolean mDisableExtensionVertexBufferObjects = false; + private boolean mDisableExtensionDrawTexture = false; + + // =========================================================== + // Constructors + // =========================================================== + + // =========================================================== + // Getter & Setter + // =========================================================== + + /** + * Default: false + */ + public boolean isDisableExtensionVertexBufferObjects() { + return this.mDisableExtensionVertexBufferObjects; + } + + public RenderOptions enableExtensionVertexBufferObjects() { + return this.setDisableExtensionVertexBufferObjects(false); + } + + public RenderOptions disableExtensionVertexBufferObjects() { + return this.setDisableExtensionVertexBufferObjects(true); + } + + public RenderOptions setDisableExtensionVertexBufferObjects(final boolean pDisableExtensionVertexBufferObjects) { + this.mDisableExtensionVertexBufferObjects = pDisableExtensionVertexBufferObjects; + return this; + } + + /** + * Default: false + */ + public boolean isDisableExtensionDrawTexture() { + return this.mDisableExtensionDrawTexture; + } + + public RenderOptions enableExtensionDrawTexture() { + return this.setDisableExtensionDrawTexture(false); + } + + public RenderOptions disableExtensionDrawTexture() { + return this.setDisableExtensionDrawTexture(true); + } + + public RenderOptions setDisableExtensionDrawTexture(final boolean pDisableExtensionDrawTexture) { + this.mDisableExtensionDrawTexture = pDisableExtensionDrawTexture; + return this; + } + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/engine/options/TouchOptions.java b/AndEngine/src/org/anddev/andengine/engine/options/TouchOptions.java index fc39e363..8649be59 100644 --- a/AndEngine/src/org/anddev/andengine/engine/options/TouchOptions.java +++ b/AndEngine/src/org/anddev/andengine/engine/options/TouchOptions.java @@ -8,53 +8,53 @@ * @since 16:03:09 - 08.09.2010 */ public class TouchOptions { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - private boolean mRunOnUpdateThread; - - // =========================================================== - // Constructors - // =========================================================== - - // =========================================================== - // Getter & Setter - // =========================================================== - - public TouchOptions enableRunOnUpdateThread() { - return this.setRunOnUpdateThread(true); - } - - public TouchOptions disableRunOnUpdateThread() { - return this.setRunOnUpdateThread(false); - } - - public TouchOptions setRunOnUpdateThread(final boolean pRunOnUpdateThread) { - this.mRunOnUpdateThread = pRunOnUpdateThread; - return this; - } - - /** - * Default: true - */ - public boolean isRunOnUpdateThread() { - return this.mRunOnUpdateThread; - } - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + private boolean mRunOnUpdateThread; + + // =========================================================== + // Constructors + // =========================================================== + + // =========================================================== + // Getter & Setter + // =========================================================== + + public TouchOptions enableRunOnUpdateThread() { + return this.setRunOnUpdateThread(true); + } + + public TouchOptions disableRunOnUpdateThread() { + return this.setRunOnUpdateThread(false); + } + + public TouchOptions setRunOnUpdateThread(final boolean pRunOnUpdateThread) { + this.mRunOnUpdateThread = pRunOnUpdateThread; + return this; + } + + /** + * Default: true + */ + public boolean isRunOnUpdateThread() { + return this.mRunOnUpdateThread; + } + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/engine/options/WakeLockOptions.java b/AndEngine/src/org/anddev/andengine/engine/options/WakeLockOptions.java index 2870917b..999c5a7b 100644 --- a/AndEngine/src/org/anddev/andengine/engine/options/WakeLockOptions.java +++ b/AndEngine/src/org/anddev/andengine/engine/options/WakeLockOptions.java @@ -10,54 +10,54 @@ * @since 19:45:23 - 10.07.2010 */ public enum WakeLockOptions { - // =========================================================== - // Elements - // =========================================================== - - /** Screen is on at full brightness. Keyboard backlight is on at full brightness. Requires WAKE_LOCK permission! */ - BRIGHT(PowerManager.FULL_WAKE_LOCK), - /** Screen is on at full brightness. Keyboard backlight will be allowed to go off. Requires WAKE_LOCK permission!*/ - SCREEN_BRIGHT(PowerManager.SCREEN_BRIGHT_WAKE_LOCK), - /** Screen is on but may be dimmed. Keyboard backlight will be allowed to go off. Requires WAKE_LOCK permission!*/ - SCREEN_DIM(PowerManager.SCREEN_DIM_WAKE_LOCK), - /** Screen is on at full brightness. Does not require WAKE_LOCK permission! */ - SCREEN_ON(-1); - - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - private final int mFlag; - - // =========================================================== - // Constructors - // =========================================================== - - private WakeLockOptions(final int pFlag) { - this.mFlag = pFlag; - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - public int getFlag() { - return this.mFlag; - } - - // =========================================================== - // Methods from SuperClass/Interfaces - // =========================================================== - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Elements + // =========================================================== + + /** Screen is on at full brightness. Keyboard backlight is on at full brightness. Requires WAKE_LOCK permission! */ + BRIGHT(PowerManager.FULL_WAKE_LOCK), + /** Screen is on at full brightness. Keyboard backlight will be allowed to go off. Requires WAKE_LOCK permission!*/ + SCREEN_BRIGHT(PowerManager.SCREEN_BRIGHT_WAKE_LOCK), + /** Screen is on but may be dimmed. Keyboard backlight will be allowed to go off. Requires WAKE_LOCK permission!*/ + SCREEN_DIM(PowerManager.SCREEN_DIM_WAKE_LOCK), + /** Screen is on at full brightness. Does not require WAKE_LOCK permission! */ + SCREEN_ON(-1); + + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + private final int mFlag; + + // =========================================================== + // Constructors + // =========================================================== + + private WakeLockOptions(final int pFlag) { + this.mFlag = pFlag; + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + public int getFlag() { + return this.mFlag; + } + + // =========================================================== + // Methods from SuperClass/Interfaces + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/engine/options/resolutionpolicy/BaseResolutionPolicy.java b/AndEngine/src/org/anddev/andengine/engine/options/resolutionpolicy/BaseResolutionPolicy.java index 479f68bb..035c533b 100644 --- a/AndEngine/src/org/anddev/andengine/engine/options/resolutionpolicy/BaseResolutionPolicy.java +++ b/AndEngine/src/org/anddev/andengine/engine/options/resolutionpolicy/BaseResolutionPolicy.java @@ -10,40 +10,40 @@ * @since 22:46:43 - 06.10.2010 */ public abstract class BaseResolutionPolicy implements IResolutionPolicy { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - // =========================================================== - // Constructors - // =========================================================== - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - protected static void throwOnNotMeasureSpecEXACTLY(final int pWidthMeasureSpec, final int pHeightMeasureSpec) { - final int specWidthMode = MeasureSpec.getMode(pWidthMeasureSpec); - final int specHeightMode = MeasureSpec.getMode(pHeightMeasureSpec); - - if (specWidthMode != MeasureSpec.EXACTLY || specHeightMode != MeasureSpec.EXACTLY) { - //throw new IllegalStateException("This IResolutionPolicy requires MeasureSpec.EXACTLY ! That means "); - } - } - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + // =========================================================== + // Constructors + // =========================================================== + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + protected static void throwOnNotMeasureSpecEXACTLY(final int pWidthMeasureSpec, final int pHeightMeasureSpec) { + final int specWidthMode = MeasureSpec.getMode(pWidthMeasureSpec); + final int specHeightMode = MeasureSpec.getMode(pHeightMeasureSpec); + + if (specWidthMode != MeasureSpec.EXACTLY || specHeightMode != MeasureSpec.EXACTLY) { + //throw new IllegalStateException("This IResolutionPolicy requires MeasureSpec.EXACTLY ! That means "); + } + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/engine/options/resolutionpolicy/FillResolutionPolicy.java b/AndEngine/src/org/anddev/andengine/engine/options/resolutionpolicy/FillResolutionPolicy.java index 81fde19a..159ae3fa 100644 --- a/AndEngine/src/org/anddev/andengine/engine/options/resolutionpolicy/FillResolutionPolicy.java +++ b/AndEngine/src/org/anddev/andengine/engine/options/resolutionpolicy/FillResolutionPolicy.java @@ -12,41 +12,41 @@ * @since 11:22:48 - 29.03.2010 */ public class FillResolutionPolicy extends BaseResolutionPolicy { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - @Override - public void onMeasure(final RenderSurfaceView pRenderSurfaceView, final int pWidthMeasureSpec, final int pHeightMeasureSpec) { - BaseResolutionPolicy.throwOnNotMeasureSpecEXACTLY(pWidthMeasureSpec, pHeightMeasureSpec); + @Override + public void onMeasure(final RenderSurfaceView pRenderSurfaceView, final int pWidthMeasureSpec, final int pHeightMeasureSpec) { + BaseResolutionPolicy.throwOnNotMeasureSpecEXACTLY(pWidthMeasureSpec, pHeightMeasureSpec); - final int measuredWidth = MeasureSpec.getSize(pWidthMeasureSpec); - final int measuredHeight = MeasureSpec.getSize(pHeightMeasureSpec); + final int measuredWidth = MeasureSpec.getSize(pWidthMeasureSpec); + final int measuredHeight = MeasureSpec.getSize(pHeightMeasureSpec); - pRenderSurfaceView.setMeasuredDimensionProxy(measuredWidth, measuredHeight); - } + pRenderSurfaceView.setMeasuredDimensionProxy(measuredWidth, measuredHeight); + } - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/engine/options/resolutionpolicy/FixedResolutionPolicy.java b/AndEngine/src/org/anddev/andengine/engine/options/resolutionpolicy/FixedResolutionPolicy.java index aea45fce..277e5065 100644 --- a/AndEngine/src/org/anddev/andengine/engine/options/resolutionpolicy/FixedResolutionPolicy.java +++ b/AndEngine/src/org/anddev/andengine/engine/options/resolutionpolicy/FixedResolutionPolicy.java @@ -10,44 +10,44 @@ * @since 11:23:00 - 29.03.2010 */ public class FixedResolutionPolicy extends BaseResolutionPolicy { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - private final int mWidth; - private final int mHeight; - - // =========================================================== - // Constructors - // =========================================================== - - public FixedResolutionPolicy(final int pWidth, final int pHeight) { - this.mWidth = pWidth; - this.mHeight = pHeight; - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - public void onMeasure(final RenderSurfaceView pRenderSurfaceView, final int pWidthMeasureSpec, final int pHeightMeasureSpec) { - pRenderSurfaceView.setMeasuredDimensionProxy(this.mWidth, this.mHeight); - } - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + private final int mWidth; + private final int mHeight; + + // =========================================================== + // Constructors + // =========================================================== + + public FixedResolutionPolicy(final int pWidth, final int pHeight) { + this.mWidth = pWidth; + this.mHeight = pHeight; + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + public void onMeasure(final RenderSurfaceView pRenderSurfaceView, final int pWidthMeasureSpec, final int pHeightMeasureSpec) { + pRenderSurfaceView.setMeasuredDimensionProxy(this.mWidth, this.mHeight); + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/engine/options/resolutionpolicy/IResolutionPolicy.java b/AndEngine/src/org/anddev/andengine/engine/options/resolutionpolicy/IResolutionPolicy.java index 67a2ca9f..f7c2ab3c 100644 --- a/AndEngine/src/org/anddev/andengine/engine/options/resolutionpolicy/IResolutionPolicy.java +++ b/AndEngine/src/org/anddev/andengine/engine/options/resolutionpolicy/IResolutionPolicy.java @@ -10,13 +10,13 @@ * @since 11:02:35 - 29.03.2010 */ public interface IResolutionPolicy { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - public void onMeasure(final RenderSurfaceView pRenderSurfaceView, final int pWidthMeasureSpec, final int pHeightMeasureSpec); + public void onMeasure(final RenderSurfaceView pRenderSurfaceView, final int pWidthMeasureSpec, final int pHeightMeasureSpec); } diff --git a/AndEngine/src/org/anddev/andengine/engine/options/resolutionpolicy/RatioResolutionPolicy.java b/AndEngine/src/org/anddev/andengine/engine/options/resolutionpolicy/RatioResolutionPolicy.java index 635ad9e3..f9baf08a 100644 --- a/AndEngine/src/org/anddev/andengine/engine/options/resolutionpolicy/RatioResolutionPolicy.java +++ b/AndEngine/src/org/anddev/andengine/engine/options/resolutionpolicy/RatioResolutionPolicy.java @@ -12,64 +12,64 @@ * @since 11:23:00 - 29.03.2010 */ public class RatioResolutionPolicy extends BaseResolutionPolicy { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - private final float mRatio; - - // =========================================================== - // Constructors - // =========================================================== - - public RatioResolutionPolicy(final float pRatio) { - this.mRatio = pRatio; - } - - public RatioResolutionPolicy(final float pWidthRatio, final float pHeightRatio) { - this.mRatio = pWidthRatio / pHeightRatio; - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - public void onMeasure(final RenderSurfaceView pRenderSurfaceView, 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; - - int measuredWidth; - int measuredHeight; - if(realRatio < desiredRatio) { - measuredWidth = specWidth; - measuredHeight = Math.round(measuredWidth / desiredRatio); - } else { - measuredHeight = specHeight; - measuredWidth = Math.round(measuredHeight * desiredRatio); - } - - pRenderSurfaceView.setMeasuredDimensionProxy(measuredWidth, measuredHeight); - } - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + private final float mRatio; + + // =========================================================== + // Constructors + // =========================================================== + + public RatioResolutionPolicy(final float pRatio) { + this.mRatio = pRatio; + } + + public RatioResolutionPolicy(final float pWidthRatio, final float pHeightRatio) { + this.mRatio = pWidthRatio / pHeightRatio; + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + public void onMeasure(final RenderSurfaceView pRenderSurfaceView, 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; + + int measuredWidth; + int measuredHeight; + if(realRatio < desiredRatio) { + measuredWidth = specWidth; + measuredHeight = Math.round(measuredWidth / desiredRatio); + } else { + measuredHeight = specHeight; + measuredWidth = Math.round(measuredHeight * desiredRatio); + } + + pRenderSurfaceView.setMeasuredDimensionProxy(measuredWidth, measuredHeight); + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/engine/options/resolutionpolicy/RelativeResolutionPolicy.java b/AndEngine/src/org/anddev/andengine/engine/options/resolutionpolicy/RelativeResolutionPolicy.java index 3136e2cc..8d2bd424 100644 --- a/AndEngine/src/org/anddev/andengine/engine/options/resolutionpolicy/RelativeResolutionPolicy.java +++ b/AndEngine/src/org/anddev/andengine/engine/options/resolutionpolicy/RelativeResolutionPolicy.java @@ -12,52 +12,52 @@ * @since 11:23:00 - 29.03.2010 */ public class RelativeResolutionPolicy extends BaseResolutionPolicy { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - private final float mWidthScale; - private final float mHeightScale; - - // =========================================================== - // Constructors - // =========================================================== - - public RelativeResolutionPolicy(final float pScale) { - this(pScale, pScale); - } - - public RelativeResolutionPolicy(final float pWidthScale, final float pHeightScale) { - this.mWidthScale = pWidthScale; - this.mHeightScale = pHeightScale; - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - @Override - public void onMeasure(final RenderSurfaceView pRenderSurfaceView, 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); - - pRenderSurfaceView.setMeasuredDimensionProxy(measuredWidth, measuredHeight); - } - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + private final float mWidthScale; + private final float mHeightScale; + + // =========================================================== + // Constructors + // =========================================================== + + public RelativeResolutionPolicy(final float pScale) { + this(pScale, pScale); + } + + public RelativeResolutionPolicy(final float pWidthScale, final float pHeightScale) { + this.mWidthScale = pWidthScale; + this.mHeightScale = pHeightScale; + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + @Override + public void onMeasure(final RenderSurfaceView pRenderSurfaceView, 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); + + pRenderSurfaceView.setMeasuredDimensionProxy(measuredWidth, measuredHeight); + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/entity/Entity.java b/AndEngine/src/org/anddev/andengine/entity/Entity.java index 580af3e0..1268667b 100644 --- a/AndEngine/src/org/anddev/andengine/entity/Entity.java +++ b/AndEngine/src/org/anddev/andengine/entity/Entity.java @@ -27,1049 +27,1049 @@ * @since 12:00:48 - 08.03.2010 */ public class Entity implements IEntity { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - private static final int CHILDREN_CAPACITY_DEFAULT = 4; - private static final int ENTITYMODIFIERS_CAPACITY_DEFAULT = 4; - private static final int UPDATEHANDLERS_CAPACITY_DEFAULT = 4; + private static final int CHILDREN_CAPACITY_DEFAULT = 4; + private static final int ENTITYMODIFIERS_CAPACITY_DEFAULT = 4; + private static final int UPDATEHANDLERS_CAPACITY_DEFAULT = 4; - 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_SCENE_TO_LOCAL_TMP = new float[2]; + private static final float[] VERTICES_LOCAL_TO_SCENE_TMP = new float[2]; - private static final ParameterCallable PARAMETERCALLABLE_DETACHCHILD = new ParameterCallable() { - @Override - public void call(final IEntity pEntity) { - pEntity.setParent(null); - pEntity.onDetached(); - } - }; + private static final ParameterCallable PARAMETERCALLABLE_DETACHCHILD = new ParameterCallable() { + @Override + public void call(final IEntity pEntity) { + pEntity.setParent(null); + pEntity.onDetached(); + } + }; - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - protected boolean mVisible = true; - protected boolean mIgnoreUpdate = false; - protected boolean mChildrenVisible = true; - protected boolean mChildrenIgnoreUpdate = false; + protected boolean mVisible = true; + protected boolean mIgnoreUpdate = false; + protected boolean mChildrenVisible = true; + protected boolean mChildrenIgnoreUpdate = false; - protected int mZIndex = 0; + protected int mZIndex = 0; - private IEntity mParent; + private IEntity mParent; - protected SmartList mChildren; - private EntityModifierList mEntityModifiers; - private UpdateHandlerList mUpdateHandlers; + protected SmartList mChildren; + private EntityModifierList mEntityModifiers; + private UpdateHandlerList mUpdateHandlers; - protected float mRed = 1f; - protected float mGreen = 1f; - protected float mBlue = 1f; - protected float mAlpha = 1f; + protected float mRed = 1f; + protected float mGreen = 1f; + protected float mBlue = 1f; + protected float mAlpha = 1f; - protected float mX; - protected float mY; + protected float mX; + protected float mY; - private final float mInitialX; - private final float mInitialY; + private final float mInitialX; + private final float mInitialY; - protected float mRotation = 0; + protected float mRotation = 0; - protected float mRotationCenterX = 0; - protected float mRotationCenterY = 0; - - protected float mScaleX = 1f; - protected float mScaleY = 1f; + protected float mRotationCenterX = 0; + protected float mRotationCenterY = 0; + + protected float mScaleX = 1f; + protected float mScaleY = 1f; - protected float mScaleCenterX = 0; - protected float mScaleCenterY = 0; + protected float mScaleCenterX = 0; + protected float mScaleCenterY = 0; - private boolean mLocalToParentTransformationDirty = true; - private boolean mParentToLocalTransformationDirty = true; - - private final Transformation mLocalToParentTransformation = new Transformation(); - private final Transformation mParentToLocalTransformation = new Transformation(); - - private final Transformation mLocalToSceneTransformation = new Transformation(); - private final Transformation mSceneToLocalTransformation = new Transformation(); - - private Object mUserData; - - // =========================================================== - // Constructors - // =========================================================== - - public Entity() { - this(0, 0); - } - - public Entity(final float pX, final float pY) { - this.mInitialX = pX; - this.mInitialY = pY; - - this.mX = pX; - this.mY = pY; - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - public boolean isVisible() { - return this.mVisible; - } - - @Override - public void setVisible(final boolean pVisible) { - this.mVisible = pVisible; - } - - @Override - public boolean isChildrenVisible() { - return this.mChildrenVisible; - } - - @Override - public void setChildrenVisible(final boolean pChildrenVisible) { - this.mChildrenVisible = pChildrenVisible; - } - - @Override - public boolean isIgnoreUpdate() { - return this.mIgnoreUpdate; - } - - @Override - public void setIgnoreUpdate(final boolean pIgnoreUpdate) { - this.mIgnoreUpdate = pIgnoreUpdate; - } - - @Override - public boolean isChildrenIgnoreUpdate() { - return this.mChildrenIgnoreUpdate; - } - - @Override - public void setChildrenIgnoreUpdate(final boolean pChildrenIgnoreUpdate) { - this.mChildrenIgnoreUpdate = pChildrenIgnoreUpdate; - } - - @Override - public boolean hasParent() { - return this.mParent != null; - } - - @Override - public IEntity getParent() { - return this.mParent; - } - - @Override - public void setParent(final IEntity pEntity) { - this.mParent = pEntity; - } - - @Override - public int getZIndex() { - return this.mZIndex; - } - - @Override - public void setZIndex(final int pZIndex) { - this.mZIndex = pZIndex; - } - - @Override - public float getX() { - return this.mX; - } - - @Override - public float getY() { - return this.mY; - } - - @Override - public float getInitialX() { - return this.mInitialX; - } - - @Override - public float getInitialY() { - return this.mInitialY; - } - - @Override - public void setPosition(final IEntity pOtherEntity) { - this.setPosition(pOtherEntity.getX(), pOtherEntity.getY()); - } - - @Override - public void setPosition(final float pX, final float pY) { - this.mX = pX; - this.mY = pY; - this.mLocalToParentTransformationDirty = true; - this.mParentToLocalTransformationDirty = true; - } - - @Override - public void setInitialPosition() { - this.mX = this.mInitialX; - this.mY = this.mInitialY; - this.mLocalToParentTransformationDirty = true; - this.mParentToLocalTransformationDirty = true; - } - - @Override - public float getRotation() { - return this.mRotation; - } - - @Override - public boolean isRotated() { - return this.mRotation != 0; - } - - @Override - public void setRotation(final float pRotation) { - this.mRotation = pRotation; - this.mLocalToParentTransformationDirty = true; - this.mParentToLocalTransformationDirty = true; - } - - @Override - public float getRotationCenterX() { - return this.mRotationCenterX; - } - - @Override - public float getRotationCenterY() { - return this.mRotationCenterY; - } - - @Override - public void setRotationCenterX(final float pRotationCenterX) { - this.mRotationCenterX = pRotationCenterX; - this.mLocalToParentTransformationDirty = true; - this.mParentToLocalTransformationDirty = true; - } - - @Override - public void setRotationCenterY(final float pRotationCenterY) { - this.mRotationCenterY = pRotationCenterY; - this.mLocalToParentTransformationDirty = true; - this.mParentToLocalTransformationDirty = true; - } - - @Override - public void setRotationCenter(final float pRotationCenterX, final float pRotationCenterY) { - this.mRotationCenterX = pRotationCenterX; - this.mRotationCenterY = pRotationCenterY; - this.mLocalToParentTransformationDirty = true; - this.mParentToLocalTransformationDirty = true; - } - - @Override - public boolean isScaled() { - return this.mScaleX != 1 || this.mScaleY != 1; - } - - @Override - public float getScaleX() { - return this.mScaleX; - } - - @Override - public float getScaleY() { - return this.mScaleY; - } - - @Override - public void setScaleX(final float pScaleX) { - this.mScaleX = pScaleX; - this.mLocalToParentTransformationDirty = true; - this.mParentToLocalTransformationDirty = true; - } - - @Override - public void setScaleY(final float pScaleY) { - this.mScaleY = pScaleY; - this.mLocalToParentTransformationDirty = true; - this.mParentToLocalTransformationDirty = true; - } - - @Override - public void setScale(final float pScale) { - this.mScaleX = pScale; - this.mScaleY = pScale; - this.mLocalToParentTransformationDirty = true; - this.mParentToLocalTransformationDirty = true; - } - - @Override - public void setScale(final float pScaleX, final float pScaleY) { - this.mScaleX = pScaleX; - this.mScaleY = pScaleY; - this.mLocalToParentTransformationDirty = true; - this.mParentToLocalTransformationDirty = true; - } - - @Override - public float getScaleCenterX() { - return this.mScaleCenterX; - } - - @Override - public float getScaleCenterY() { - return this.mScaleCenterY; - } - - @Override - public void setScaleCenterX(final float pScaleCenterX) { - this.mScaleCenterX = pScaleCenterX; - this.mLocalToParentTransformationDirty = true; - this.mParentToLocalTransformationDirty = true; - } - - @Override - public void setScaleCenterY(final float pScaleCenterY) { - this.mScaleCenterY = pScaleCenterY; - this.mLocalToParentTransformationDirty = true; - this.mParentToLocalTransformationDirty = true; - } - - @Override - public void setScaleCenter(final float pScaleCenterX, final float pScaleCenterY) { - this.mScaleCenterX = pScaleCenterX; - this.mScaleCenterY = pScaleCenterY; - this.mLocalToParentTransformationDirty = true; - this.mParentToLocalTransformationDirty = true; - } - - @Override - public float getRed() { - return this.mRed; - } - - @Override - public float getGreen() { - return this.mGreen; - } - - @Override - public float getBlue() { - return this.mBlue; - } - - @Override - public float getAlpha() { - return this.mAlpha; - } - - /** - * @param pAlpha from 0.0f (transparent) to 1.0f (opaque) - */ - @Override - public void setAlpha(final float pAlpha) { - this.mAlpha = 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 - */ - @Override - public void setColor(final float pRed, final float pGreen, final float pBlue) { - this.mRed = pRed; - this.mGreen = pGreen; - this.mBlue = 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) - */ - @Override - public void setColor(final float pRed, final float pGreen, final float pBlue, final float pAlpha) { - this.mRed = pRed; - this.mGreen = pGreen; - this.mBlue = pBlue; - this.mAlpha = pAlpha; - } - - @Override - public int getChildCount() { - if(this.mChildren == null) { - return 0; - } - return this.mChildren.size(); - } - - @Override - public IEntity getChild(final int pIndex) { - if(this.mChildren == null) { - return null; - } - return this.mChildren.get(pIndex); - } - - @Override - public int getChildIndex(final IEntity pEntity) { - if (this.mChildren == null || pEntity.getParent() != this) { - return -1; - } - return this.mChildren.indexOf(pEntity); - } - - @Override - public boolean setChildIndex(final IEntity pEntity, final int pIndex) { - if (this.mChildren == null || pEntity.getParent() != this) { - return false; - } - try { - this.mChildren.remove(pEntity); - this.mChildren.add(pIndex, pEntity); - return true; - } catch (final IndexOutOfBoundsException e) { - return false; - } - } - - @Override - public IEntity getFirstChild() { - if(this.mChildren == null) { - return null; - } - return this.mChildren.get(0); - } - - @Override - public IEntity getLastChild() { - if(this.mChildren == null) { - return null; - } - return this.mChildren.get(this.mChildren.size() - 1); - } - - @Override - public boolean detachSelf() { - final IEntity parent = this.mParent; - if(parent != null) { - return parent.detachChild(this); - } else { - return false; - } - } - - @Override - public void detachChildren() { - if(this.mChildren == null) { - return; - } - this.mChildren.clear(PARAMETERCALLABLE_DETACHCHILD); - } - - @Override - public void attachChild(final IEntity pEntity) throws IllegalStateException { - if(pEntity.hasParent()) { - throw new IllegalStateException("pEntity already has a parent!"); - } - if(this.mChildren == null) { - this.allocateChildren(); - } - this.mChildren.add(pEntity); - pEntity.setParent(this); - pEntity.onAttached(); - } - - @Override - public boolean attachChild(final IEntity pEntity, final int pIndex) throws IllegalStateException { - if(pEntity.hasParent()) { - throw new IllegalStateException("pEntity already has a parent!"); - } - if (this.mChildren == null) { - this.allocateChildren(); - } - try { - this.mChildren.add(pIndex, pEntity); - pEntity.setParent(this); - pEntity.onAttached(); - return true; - } catch (final IndexOutOfBoundsException e) { - return false; - } - } - - @Override - public IEntity findChild(final IEntityMatcher pEntityMatcher) { - if(this.mChildren == null) { - return null; - } - return this.mChildren.find(pEntityMatcher); - } - - - @Override - public ArrayList query(final IEntityMatcher pEntityMatcher) { - return this.query(pEntityMatcher, new ArrayList()); - } - - @Override - public > L query(final IEntityMatcher pEntityMatcher, final L pResult) { - final int childCount = this.getChildCount(); - for(int i = 0; i < childCount; i++) { - final IEntity item = this.mChildren.get(i); - if(pEntityMatcher.matches(item)) { - pResult.add(item); - } - - item.query(pEntityMatcher, pResult); - } - - return pResult; - } - - @Override - public ArrayList queryForSubclass(final IEntityMatcher pEntityMatcher) throws ClassCastException { - return this.queryForSubclass(pEntityMatcher, new ArrayList()); - } - - @SuppressWarnings("unchecked") - @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++) { - final IEntity item = this.mChildren.get(i); - if(pEntityMatcher.matches(item)) { - pResult.add((S)item); - } - - item.queryForSubclass(pEntityMatcher, pResult); - } - - return pResult; - } - - @Override - public boolean swapChildren(final IEntity pEntityA, final IEntity pEntityB) { - return this.swapChildren(this.getChildIndex(pEntityA), this.getChildIndex(pEntityB)); - } - - @Override - public boolean swapChildren(final int pIndexA, final int pIndexB) { - try { - Collections.swap(this.mChildren, pIndexA, pIndexB); - return true; - } catch (final IndexOutOfBoundsException e) { - return false; - } - } - - @Override - public void sortChildren() { - if(this.mChildren == null) { - return; - } - ZIndexSorter.getInstance().sort(this.mChildren); - } - - @Override - public void sortChildren(final Comparator pEntityComparator) { - if(this.mChildren == null) { - return; - } - ZIndexSorter.getInstance().sort(this.mChildren, pEntityComparator); - } - - @Override - public boolean detachChild(final IEntity pEntity) { - if(this.mChildren == null) { - return false; - } - return this.mChildren.remove(pEntity, PARAMETERCALLABLE_DETACHCHILD); - } - - @Override - public IEntity detachChild(final IEntityMatcher pEntityMatcher) { - if(this.mChildren == null) { - return null; - } - return this.mChildren.remove(pEntityMatcher, Entity.PARAMETERCALLABLE_DETACHCHILD); - } - - @Override - public boolean detachChildren(final IEntityMatcher pEntityMatcher) { - if(this.mChildren == null) { - return false; - } - return this.mChildren.removeAll(pEntityMatcher, Entity.PARAMETERCALLABLE_DETACHCHILD); - } - - @Override - public void callOnChildren(final IEntityCallable pEntityCallable) { - if(this.mChildren == null) { - return; - } - this.mChildren.call(pEntityCallable); - } - - @Override - public void callOnChildren(final IEntityMatcher pEntityMatcher, final IEntityCallable pEntityCallable) { - if(this.mChildren == null) { - return; - } - this.mChildren.call(pEntityMatcher, pEntityCallable); - } - - @Override - public void registerUpdateHandler(final IUpdateHandler pUpdateHandler) { - if(this.mUpdateHandlers == null) { - this.allocateUpdateHandlers(); - } - this.mUpdateHandlers.add(pUpdateHandler); - } - - @Override - public boolean unregisterUpdateHandler(final IUpdateHandler pUpdateHandler) { - if(this.mUpdateHandlers == null) { - return false; - } - return this.mUpdateHandlers.remove(pUpdateHandler); - } - - @Override - public boolean unregisterUpdateHandlers(final IUpdateHandlerMatcher pUpdateHandlerMatcher) { - if(this.mUpdateHandlers == null) { - return false; - } - return this.mUpdateHandlers.removeAll(pUpdateHandlerMatcher); - } - - @Override - public void clearUpdateHandlers() { - if(this.mUpdateHandlers == null) { - return; - } - this.mUpdateHandlers.clear(); - } - - @Override - public void registerEntityModifier(final IEntityModifier pEntityModifier) { - if(this.mEntityModifiers == null) { - this.allocateEntityModifiers(); - } - this.mEntityModifiers.add(pEntityModifier); - } - - @Override - public boolean unregisterEntityModifier(final IEntityModifier pEntityModifier) { - if(this.mEntityModifiers == null) { - return false; - } - return this.mEntityModifiers.remove(pEntityModifier); - } - - @Override - public boolean unregisterEntityModifiers(final IEntityModifierMatcher pEntityModifierMatcher) { - if(this.mEntityModifiers == null) { - return false; - } - return this.mEntityModifiers.removeAll(pEntityModifierMatcher); - } - - @Override - public void clearEntityModifiers() { - if(this.mEntityModifiers == null) { - return; - } - this.mEntityModifiers.clear(); - } - - @Override - public float[] getSceneCenterCoordinates() { - return this.convertLocalToSceneCoordinates(0, 0); - } - - public Transformation getLocalToParentTransformation() { - final Transformation localToParentTransformation = this.mLocalToParentTransformation; - 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; - - /* 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. */ - - localToParentTransformation.postTranslate(-scaleCenterX, -scaleCenterY); - localToParentTransformation.postScale(scaleX, scaleY); - localToParentTransformation.postTranslate(scaleCenterX, scaleCenterY); - } - - /* TODO There is a special, but very likely case when mRotationCenter and mScaleCenter are the same. - * In that case the last postTranslate of the scale and the first postTranslate of the rotation is superfluous. */ - - /* Rotation. */ - final float rotation = this.mRotation; - if(rotation != 0) { - final float rotationCenterX = this.mRotationCenterX; - final float rotationCenterY = this.mRotationCenterY; - - localToParentTransformation.postTranslate(-rotationCenterX, -rotationCenterY); - localToParentTransformation.postRotate(rotation); - localToParentTransformation.postTranslate(rotationCenterX, rotationCenterY); - } - - /* Translation. */ - localToParentTransformation.postTranslate(this.mX, this.mY); - - this.mLocalToParentTransformationDirty = false; - } - return localToParentTransformation; - } - - public Transformation getParentToLocalTransformation() { - final Transformation parentToLocalTransformation = this.mParentToLocalTransformation; - if(this.mParentToLocalTransformationDirty) { - parentToLocalTransformation.setToIdentity(); - - /* 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; - - parentToLocalTransformation.postTranslate(-rotationCenterX, -rotationCenterY); - parentToLocalTransformation.postRotate(-rotation); - parentToLocalTransformation.postTranslate(rotationCenterX, rotationCenterY); - } - - /* TODO There is a special, but very likely case when mRotationCenter and mScaleCenter are the same. - * In that case the last postTranslate of the rotation and the first postTranslate of the scale is superfluous. */ - - /* 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; - - parentToLocalTransformation.postTranslate(-scaleCenterX, -scaleCenterY); - parentToLocalTransformation.postScale(1 / scaleX, 1 / scaleY); - parentToLocalTransformation.postTranslate(scaleCenterX, scaleCenterY); - } - - this.mParentToLocalTransformationDirty = false; - } - return parentToLocalTransformation; - } - - @Override - public Transformation getLocalToSceneTransformation() { - // TODO Cache if parent(recursive) not dirty. - final Transformation localToSceneTransformation = this.mLocalToSceneTransformation; - localToSceneTransformation.setTo(this.getLocalToParentTransformation()); - - final IEntity parent = this.mParent; - if(parent != null) { - localToSceneTransformation.postConcat(parent.getLocalToSceneTransformation()); - } - - return localToSceneTransformation; - } - - @Override - public Transformation getSceneToLocalTransformation() { - // TODO Cache if parent(recursive) not dirty. - final Transformation sceneToLocalTransformation = this.mSceneToLocalTransformation; - sceneToLocalTransformation.setTo(this.getParentToLocalTransformation()); - - final IEntity parent = this.mParent; - if(parent != null) { - sceneToLocalTransformation.postConcat(parent.getSceneToLocalTransformation()); - } - - return sceneToLocalTransformation; - } - - /* (non-Javadoc) - * @see org.anddev.andengine.entity.IEntity#convertLocalToSceneCoordinates(float, float) - */ - @Override - public float[] convertLocalToSceneCoordinates(final float pX, final float pY) { - return this.convertLocalToSceneCoordinates(pX, pY, VERTICES_LOCAL_TO_SCENE_TMP); - } - - /* (non-Javadoc) - * @see org.anddev.andengine.entity.IEntity#convertLocalToSceneCoordinates(float, float, float[]) - */ - @Override - public float[] convertLocalToSceneCoordinates(final float pX, final float pY, final float[] pReuse) { - pReuse[Constants.VERTEX_INDEX_X] = pX; - pReuse[Constants.VERTEX_INDEX_Y] = pY; - - this.getLocalToSceneTransformation().transform(pReuse); - - return pReuse; - } - - /* (non-Javadoc) - * @see org.anddev.andengine.entity.IEntity#convertLocalToSceneCoordinates(float[]) - */ - @Override - public float[] convertLocalToSceneCoordinates(final float[] pCoordinates) { - return this.convertSceneToLocalCoordinates(pCoordinates, VERTICES_LOCAL_TO_SCENE_TMP); - } - - /* (non-Javadoc) - * @see org.anddev.andengine.entity.IEntity#convertLocalToSceneCoordinates(float[], float[]) - */ - @Override - public float[] convertLocalToSceneCoordinates(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.getLocalToSceneTransformation().transform(pReuse); - - return pReuse; - } - - /* (non-Javadoc) - * @see org.anddev.andengine.entity.IEntity#convertSceneToLocalCoordinates(float, float) - */ - @Override - public float[] convertSceneToLocalCoordinates(final float pX, final float pY) { - return this.convertSceneToLocalCoordinates(pX, pY, VERTICES_SCENE_TO_LOCAL_TMP); - } - - /* (non-Javadoc) - * @see org.anddev.andengine.entity.IEntity#convertSceneToLocalCoordinates(float, float, float[]) - */ - @Override - public float[] convertSceneToLocalCoordinates(final float pX, final float pY, final float[] pReuse) { - pReuse[Constants.VERTEX_INDEX_X] = pX; - pReuse[Constants.VERTEX_INDEX_Y] = pY; - - this.getSceneToLocalTransformation().transform(pReuse); - - return pReuse; - } - - /* (non-Javadoc) - * @see org.anddev.andengine.entity.IEntity#convertSceneToLocalCoordinates(float[]) - */ - @Override - public float[] convertSceneToLocalCoordinates(final float[] pCoordinates) { - return this.convertSceneToLocalCoordinates(pCoordinates, VERTICES_SCENE_TO_LOCAL_TMP); - } - - /* (non-Javadoc) - * @see org.anddev.andengine.entity.IEntity#convertSceneToLocalCoordinates(float[], float[]) - */ - @Override - public float[] convertSceneToLocalCoordinates(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.getSceneToLocalTransformation().transform(pReuse); - - return pReuse; - } - - @Override - public void onAttached() { - - } - - @Override - public void onDetached() { - - } - - @Override - public Object getUserData() { - return this.mUserData; - } - - @Override - public void setUserData(final Object pUserData) { - this.mUserData = pUserData; - } - - @Override - public final void onDraw(final GL10 pGL, final Camera pCamera) { - if(this.mVisible) { - this.onManagedDraw(pGL, pCamera); - } - } - - @Override - public final void onUpdate(final float pSecondsElapsed) { - if(!this.mIgnoreUpdate) { - this.onManagedUpdate(pSecondsElapsed); - } - } - - @Override - public void reset() { - this.mVisible = true; - this.mIgnoreUpdate = false; - this.mChildrenVisible = true; - this.mChildrenIgnoreUpdate = false; - - this.mX = this.mInitialX; - this.mY = this.mInitialY; - this.mRotation = 0; - this.mScaleX = 1; - this.mScaleY = 1; - - this.mRed = 1.0f; - this.mGreen = 1.0f; - this.mBlue = 1.0f; - this.mAlpha = 1.0f; - - if(this.mEntityModifiers != null) { - this.mEntityModifiers.reset(); - } - - if(this.mChildren != null) { - final ArrayList entities = this.mChildren; - for(int i = entities.size() - 1; i >= 0; i--) { - entities.get(i).reset(); - } - } - } - - // =========================================================== - // Methods - // =========================================================== - - /** - * @param pGL the OpenGL GL1.0 Context (potentially higher than 1.0) to use for drawing. - * @param pCamera the currently active {@link Camera} i.e. to be used for culling. - */ - protected void doDraw(final GL10 pGL, final Camera pCamera) { - - } - - private void allocateEntityModifiers() { - this.mEntityModifiers = new EntityModifierList(this, Entity.ENTITYMODIFIERS_CAPACITY_DEFAULT); - } - - private void allocateChildren() { - this.mChildren = new SmartList(Entity.CHILDREN_CAPACITY_DEFAULT); - } - - private void allocateUpdateHandlers() { - this.mUpdateHandlers = new UpdateHandlerList(Entity.UPDATEHANDLERS_CAPACITY_DEFAULT); - } - - protected void onApplyTransformations(final GL10 pGL) { - /* Translation. */ - this.applyTranslation(pGL); - - /* Rotation. */ - this.applyRotation(pGL); - - /* Scale. */ - this.applyScale(pGL); - } - - protected void applyTranslation(final GL10 pGL) { - pGL.glTranslatef(this.mX, this.mY, 0); - } - - protected void applyRotation(final GL10 pGL) { - final float rotation = this.mRotation; - - if(rotation != 0) { - final float rotationCenterX = this.mRotationCenterX; - final float rotationCenterY = this.mRotationCenterY; - - pGL.glTranslatef(rotationCenterX, rotationCenterY, 0); - pGL.glRotatef(rotation, 0, 0, 1); - pGL.glTranslatef(-rotationCenterX, -rotationCenterY, 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. - * The problem is that applyRotation and applyScale would need to be "merged" in order to efficiently check for that condition. */ - } - } - - protected void applyScale(final GL10 pGL) { - 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; - - pGL.glTranslatef(scaleCenterX, scaleCenterY, 0); - pGL.glScalef(scaleX, scaleY, 1); - pGL.glTranslatef(-scaleCenterX, -scaleCenterY, 0); - } - } - - protected void onManagedDraw(final GL10 pGL, final Camera pCamera) { - pGL.glPushMatrix(); - { - this.onApplyTransformations(pGL); - - this.doDraw(pGL, pCamera); - - this.onDrawChildren(pGL, pCamera); - } - pGL.glPopMatrix(); - } - - protected void onDrawChildren(final GL10 pGL, final Camera pCamera) { - if(this.mChildren != null && this.mChildrenVisible) { - this.onManagedDrawChildren(pGL, pCamera); - } - } - - public void onManagedDrawChildren(final GL10 pGL, final Camera pCamera) { - final ArrayList children = this.mChildren; - final int childCount = children.size(); - for(int i = 0; i < childCount; i++) { - children.get(i).onDraw(pGL, pCamera); - } - } - - protected void onManagedUpdate(final float pSecondsElapsed) { - if(this.mEntityModifiers != null) { - this.mEntityModifiers.onUpdate(pSecondsElapsed); - } - if(this.mUpdateHandlers != null) { - this.mUpdateHandlers.onUpdate(pSecondsElapsed); - } - - if(this.mChildren != null && !this.mChildrenIgnoreUpdate) { - final ArrayList entities = this.mChildren; - final int entityCount = entities.size(); - for(int i = 0; i < entityCount; i++) { - entities.get(i).onUpdate(pSecondsElapsed); - } - } - } - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + private boolean mLocalToParentTransformationDirty = true; + private boolean mParentToLocalTransformationDirty = true; + + private final Transformation mLocalToParentTransformation = new Transformation(); + private final Transformation mParentToLocalTransformation = new Transformation(); + + private final Transformation mLocalToSceneTransformation = new Transformation(); + private final Transformation mSceneToLocalTransformation = new Transformation(); + + private Object mUserData; + + // =========================================================== + // Constructors + // =========================================================== + + public Entity() { + this(0, 0); + } + + public Entity(final float pX, final float pY) { + this.mInitialX = pX; + this.mInitialY = pY; + + this.mX = pX; + this.mY = pY; + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + public boolean isVisible() { + return this.mVisible; + } + + @Override + public void setVisible(final boolean pVisible) { + this.mVisible = pVisible; + } + + @Override + public boolean isChildrenVisible() { + return this.mChildrenVisible; + } + + @Override + public void setChildrenVisible(final boolean pChildrenVisible) { + this.mChildrenVisible = pChildrenVisible; + } + + @Override + public boolean isIgnoreUpdate() { + return this.mIgnoreUpdate; + } + + @Override + public void setIgnoreUpdate(final boolean pIgnoreUpdate) { + this.mIgnoreUpdate = pIgnoreUpdate; + } + + @Override + public boolean isChildrenIgnoreUpdate() { + return this.mChildrenIgnoreUpdate; + } + + @Override + public void setChildrenIgnoreUpdate(final boolean pChildrenIgnoreUpdate) { + this.mChildrenIgnoreUpdate = pChildrenIgnoreUpdate; + } + + @Override + public boolean hasParent() { + return this.mParent != null; + } + + @Override + public IEntity getParent() { + return this.mParent; + } + + @Override + public void setParent(final IEntity pEntity) { + this.mParent = pEntity; + } + + @Override + public int getZIndex() { + return this.mZIndex; + } + + @Override + public void setZIndex(final int pZIndex) { + this.mZIndex = pZIndex; + } + + @Override + public float getX() { + return this.mX; + } + + @Override + public float getY() { + return this.mY; + } + + @Override + public float getInitialX() { + return this.mInitialX; + } + + @Override + public float getInitialY() { + return this.mInitialY; + } + + @Override + public void setPosition(final IEntity pOtherEntity) { + this.setPosition(pOtherEntity.getX(), pOtherEntity.getY()); + } + + @Override + public void setPosition(final float pX, final float pY) { + this.mX = pX; + this.mY = pY; + this.mLocalToParentTransformationDirty = true; + this.mParentToLocalTransformationDirty = true; + } + + @Override + public void setInitialPosition() { + this.mX = this.mInitialX; + this.mY = this.mInitialY; + this.mLocalToParentTransformationDirty = true; + this.mParentToLocalTransformationDirty = true; + } + + @Override + public float getRotation() { + return this.mRotation; + } + + @Override + public boolean isRotated() { + return this.mRotation != 0; + } + + @Override + public void setRotation(final float pRotation) { + this.mRotation = pRotation; + this.mLocalToParentTransformationDirty = true; + this.mParentToLocalTransformationDirty = true; + } + + @Override + public float getRotationCenterX() { + return this.mRotationCenterX; + } + + @Override + public float getRotationCenterY() { + return this.mRotationCenterY; + } + + @Override + public void setRotationCenterX(final float pRotationCenterX) { + this.mRotationCenterX = pRotationCenterX; + this.mLocalToParentTransformationDirty = true; + this.mParentToLocalTransformationDirty = true; + } + + @Override + public void setRotationCenterY(final float pRotationCenterY) { + this.mRotationCenterY = pRotationCenterY; + this.mLocalToParentTransformationDirty = true; + this.mParentToLocalTransformationDirty = true; + } + + @Override + public void setRotationCenter(final float pRotationCenterX, final float pRotationCenterY) { + this.mRotationCenterX = pRotationCenterX; + this.mRotationCenterY = pRotationCenterY; + this.mLocalToParentTransformationDirty = true; + this.mParentToLocalTransformationDirty = true; + } + + @Override + public boolean isScaled() { + return this.mScaleX != 1 || this.mScaleY != 1; + } + + @Override + public float getScaleX() { + return this.mScaleX; + } + + @Override + public float getScaleY() { + return this.mScaleY; + } + + @Override + public void setScaleX(final float pScaleX) { + this.mScaleX = pScaleX; + this.mLocalToParentTransformationDirty = true; + this.mParentToLocalTransformationDirty = true; + } + + @Override + public void setScaleY(final float pScaleY) { + this.mScaleY = pScaleY; + this.mLocalToParentTransformationDirty = true; + this.mParentToLocalTransformationDirty = true; + } + + @Override + public void setScale(final float pScale) { + this.mScaleX = pScale; + this.mScaleY = pScale; + this.mLocalToParentTransformationDirty = true; + this.mParentToLocalTransformationDirty = true; + } + + @Override + public void setScale(final float pScaleX, final float pScaleY) { + this.mScaleX = pScaleX; + this.mScaleY = pScaleY; + this.mLocalToParentTransformationDirty = true; + this.mParentToLocalTransformationDirty = true; + } + + @Override + public float getScaleCenterX() { + return this.mScaleCenterX; + } + + @Override + public float getScaleCenterY() { + return this.mScaleCenterY; + } + + @Override + public void setScaleCenterX(final float pScaleCenterX) { + this.mScaleCenterX = pScaleCenterX; + this.mLocalToParentTransformationDirty = true; + this.mParentToLocalTransformationDirty = true; + } + + @Override + public void setScaleCenterY(final float pScaleCenterY) { + this.mScaleCenterY = pScaleCenterY; + this.mLocalToParentTransformationDirty = true; + this.mParentToLocalTransformationDirty = true; + } + + @Override + public void setScaleCenter(final float pScaleCenterX, final float pScaleCenterY) { + this.mScaleCenterX = pScaleCenterX; + this.mScaleCenterY = pScaleCenterY; + this.mLocalToParentTransformationDirty = true; + this.mParentToLocalTransformationDirty = true; + } + + @Override + public float getRed() { + return this.mRed; + } + + @Override + public float getGreen() { + return this.mGreen; + } + + @Override + public float getBlue() { + return this.mBlue; + } + + @Override + public float getAlpha() { + return this.mAlpha; + } + + /** + * @param pAlpha from 0.0f (transparent) to 1.0f (opaque) + */ + @Override + public void setAlpha(final float pAlpha) { + this.mAlpha = 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 + */ + @Override + public void setColor(final float pRed, final float pGreen, final float pBlue) { + this.mRed = pRed; + this.mGreen = pGreen; + this.mBlue = 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) + */ + @Override + public void setColor(final float pRed, final float pGreen, final float pBlue, final float pAlpha) { + this.mRed = pRed; + this.mGreen = pGreen; + this.mBlue = pBlue; + this.mAlpha = pAlpha; + } + + @Override + public int getChildCount() { + if(this.mChildren == null) { + return 0; + } + return this.mChildren.size(); + } + + @Override + public IEntity getChild(final int pIndex) { + if(this.mChildren == null) { + return null; + } + return this.mChildren.get(pIndex); + } + + @Override + public int getChildIndex(final IEntity pEntity) { + if (this.mChildren == null || pEntity.getParent() != this) { + return -1; + } + return this.mChildren.indexOf(pEntity); + } + + @Override + public boolean setChildIndex(final IEntity pEntity, final int pIndex) { + if (this.mChildren == null || pEntity.getParent() != this) { + return false; + } + try { + this.mChildren.remove(pEntity); + this.mChildren.add(pIndex, pEntity); + return true; + } catch (final IndexOutOfBoundsException e) { + return false; + } + } + + @Override + public IEntity getFirstChild() { + if(this.mChildren == null) { + return null; + } + return this.mChildren.get(0); + } + + @Override + public IEntity getLastChild() { + if(this.mChildren == null) { + return null; + } + return this.mChildren.get(this.mChildren.size() - 1); + } + + @Override + public boolean detachSelf() { + final IEntity parent = this.mParent; + if(parent != null) { + return parent.detachChild(this); + } else { + return false; + } + } + + @Override + public void detachChildren() { + if(this.mChildren == null) { + return; + } + this.mChildren.clear(PARAMETERCALLABLE_DETACHCHILD); + } + + @Override + public void attachChild(final IEntity pEntity) throws IllegalStateException { + if(pEntity.hasParent()) { + throw new IllegalStateException("pEntity already has a parent!"); + } + if(this.mChildren == null) { + this.allocateChildren(); + } + this.mChildren.add(pEntity); + pEntity.setParent(this); + pEntity.onAttached(); + } + + @Override + public boolean attachChild(final IEntity pEntity, final int pIndex) throws IllegalStateException { + if(pEntity.hasParent()) { + throw new IllegalStateException("pEntity already has a parent!"); + } + if (this.mChildren == null) { + this.allocateChildren(); + } + try { + this.mChildren.add(pIndex, pEntity); + pEntity.setParent(this); + pEntity.onAttached(); + return true; + } catch (final IndexOutOfBoundsException e) { + return false; + } + } + + @Override + public IEntity findChild(final IEntityMatcher pEntityMatcher) { + if(this.mChildren == null) { + return null; + } + return this.mChildren.find(pEntityMatcher); + } + + + @Override + public ArrayList query(final IEntityMatcher pEntityMatcher) { + return this.query(pEntityMatcher, new ArrayList()); + } + + @Override + public > L query(final IEntityMatcher pEntityMatcher, final L pResult) { + final int childCount = this.getChildCount(); + for(int i = 0; i < childCount; i++) { + final IEntity item = this.mChildren.get(i); + if(pEntityMatcher.matches(item)) { + pResult.add(item); + } + + item.query(pEntityMatcher, pResult); + } + + return pResult; + } + + @Override + public ArrayList queryForSubclass(final IEntityMatcher pEntityMatcher) throws ClassCastException { + return this.queryForSubclass(pEntityMatcher, new ArrayList()); + } + + @SuppressWarnings("unchecked") + @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++) { + final IEntity item = this.mChildren.get(i); + if(pEntityMatcher.matches(item)) { + pResult.add((S)item); + } + + item.queryForSubclass(pEntityMatcher, pResult); + } + + return pResult; + } + + @Override + public boolean swapChildren(final IEntity pEntityA, final IEntity pEntityB) { + return this.swapChildren(this.getChildIndex(pEntityA), this.getChildIndex(pEntityB)); + } + + @Override + public boolean swapChildren(final int pIndexA, final int pIndexB) { + try { + Collections.swap(this.mChildren, pIndexA, pIndexB); + return true; + } catch (final IndexOutOfBoundsException e) { + return false; + } + } + + @Override + public void sortChildren() { + if(this.mChildren == null) { + return; + } + ZIndexSorter.getInstance().sort(this.mChildren); + } + + @Override + public void sortChildren(final Comparator pEntityComparator) { + if(this.mChildren == null) { + return; + } + ZIndexSorter.getInstance().sort(this.mChildren, pEntityComparator); + } + + @Override + public boolean detachChild(final IEntity pEntity) { + if(this.mChildren == null) { + return false; + } + return this.mChildren.remove(pEntity, PARAMETERCALLABLE_DETACHCHILD); + } + + @Override + public IEntity detachChild(final IEntityMatcher pEntityMatcher) { + if(this.mChildren == null) { + return null; + } + return this.mChildren.remove(pEntityMatcher, Entity.PARAMETERCALLABLE_DETACHCHILD); + } + + @Override + public boolean detachChildren(final IEntityMatcher pEntityMatcher) { + if(this.mChildren == null) { + return false; + } + return this.mChildren.removeAll(pEntityMatcher, Entity.PARAMETERCALLABLE_DETACHCHILD); + } + + @Override + public void callOnChildren(final IEntityCallable pEntityCallable) { + if(this.mChildren == null) { + return; + } + this.mChildren.call(pEntityCallable); + } + + @Override + public void callOnChildren(final IEntityMatcher pEntityMatcher, final IEntityCallable pEntityCallable) { + if(this.mChildren == null) { + return; + } + this.mChildren.call(pEntityMatcher, pEntityCallable); + } + + @Override + public void registerUpdateHandler(final IUpdateHandler pUpdateHandler) { + if(this.mUpdateHandlers == null) { + this.allocateUpdateHandlers(); + } + this.mUpdateHandlers.add(pUpdateHandler); + } + + @Override + public boolean unregisterUpdateHandler(final IUpdateHandler pUpdateHandler) { + if(this.mUpdateHandlers == null) { + return false; + } + return this.mUpdateHandlers.remove(pUpdateHandler); + } + + @Override + public boolean unregisterUpdateHandlers(final IUpdateHandlerMatcher pUpdateHandlerMatcher) { + if(this.mUpdateHandlers == null) { + return false; + } + return this.mUpdateHandlers.removeAll(pUpdateHandlerMatcher); + } + + @Override + public void clearUpdateHandlers() { + if(this.mUpdateHandlers == null) { + return; + } + this.mUpdateHandlers.clear(); + } + + @Override + public void registerEntityModifier(final IEntityModifier pEntityModifier) { + if(this.mEntityModifiers == null) { + this.allocateEntityModifiers(); + } + this.mEntityModifiers.add(pEntityModifier); + } + + @Override + public boolean unregisterEntityModifier(final IEntityModifier pEntityModifier) { + if(this.mEntityModifiers == null) { + return false; + } + return this.mEntityModifiers.remove(pEntityModifier); + } + + @Override + public boolean unregisterEntityModifiers(final IEntityModifierMatcher pEntityModifierMatcher) { + if(this.mEntityModifiers == null) { + return false; + } + return this.mEntityModifiers.removeAll(pEntityModifierMatcher); + } + + @Override + public void clearEntityModifiers() { + if(this.mEntityModifiers == null) { + return; + } + this.mEntityModifiers.clear(); + } + + @Override + public float[] getSceneCenterCoordinates() { + return this.convertLocalToSceneCoordinates(0, 0); + } + + public Transformation getLocalToParentTransformation() { + final Transformation localToParentTransformation = this.mLocalToParentTransformation; + 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; + + /* 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. */ + + localToParentTransformation.postTranslate(-scaleCenterX, -scaleCenterY); + localToParentTransformation.postScale(scaleX, scaleY); + localToParentTransformation.postTranslate(scaleCenterX, scaleCenterY); + } + + /* TODO There is a special, but very likely case when mRotationCenter and mScaleCenter are the same. + * In that case the last postTranslate of the scale and the first postTranslate of the rotation is superfluous. */ + + /* Rotation. */ + final float rotation = this.mRotation; + if(rotation != 0) { + final float rotationCenterX = this.mRotationCenterX; + final float rotationCenterY = this.mRotationCenterY; + + localToParentTransformation.postTranslate(-rotationCenterX, -rotationCenterY); + localToParentTransformation.postRotate(rotation); + localToParentTransformation.postTranslate(rotationCenterX, rotationCenterY); + } + + /* Translation. */ + localToParentTransformation.postTranslate(this.mX, this.mY); + + this.mLocalToParentTransformationDirty = false; + } + return localToParentTransformation; + } + + public Transformation getParentToLocalTransformation() { + final Transformation parentToLocalTransformation = this.mParentToLocalTransformation; + if(this.mParentToLocalTransformationDirty) { + parentToLocalTransformation.setToIdentity(); + + /* 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; + + parentToLocalTransformation.postTranslate(-rotationCenterX, -rotationCenterY); + parentToLocalTransformation.postRotate(-rotation); + parentToLocalTransformation.postTranslate(rotationCenterX, rotationCenterY); + } + + /* TODO There is a special, but very likely case when mRotationCenter and mScaleCenter are the same. + * In that case the last postTranslate of the rotation and the first postTranslate of the scale is superfluous. */ + + /* 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; + + parentToLocalTransformation.postTranslate(-scaleCenterX, -scaleCenterY); + parentToLocalTransformation.postScale(1 / scaleX, 1 / scaleY); + parentToLocalTransformation.postTranslate(scaleCenterX, scaleCenterY); + } + + this.mParentToLocalTransformationDirty = false; + } + return parentToLocalTransformation; + } + + @Override + public Transformation getLocalToSceneTransformation() { + // TODO Cache if parent(recursive) not dirty. + final Transformation localToSceneTransformation = this.mLocalToSceneTransformation; + localToSceneTransformation.setTo(this.getLocalToParentTransformation()); + + final IEntity parent = this.mParent; + if(parent != null) { + localToSceneTransformation.postConcat(parent.getLocalToSceneTransformation()); + } + + return localToSceneTransformation; + } + + @Override + public Transformation getSceneToLocalTransformation() { + // TODO Cache if parent(recursive) not dirty. + final Transformation sceneToLocalTransformation = this.mSceneToLocalTransformation; + sceneToLocalTransformation.setTo(this.getParentToLocalTransformation()); + + final IEntity parent = this.mParent; + if(parent != null) { + sceneToLocalTransformation.postConcat(parent.getSceneToLocalTransformation()); + } + + return sceneToLocalTransformation; + } + + /* (non-Javadoc) + * @see org.anddev.andengine.entity.IEntity#convertLocalToSceneCoordinates(float, float) + */ + @Override + public float[] convertLocalToSceneCoordinates(final float pX, final float pY) { + return this.convertLocalToSceneCoordinates(pX, pY, VERTICES_LOCAL_TO_SCENE_TMP); + } + + /* (non-Javadoc) + * @see org.anddev.andengine.entity.IEntity#convertLocalToSceneCoordinates(float, float, float[]) + */ + @Override + public float[] convertLocalToSceneCoordinates(final float pX, final float pY, final float[] pReuse) { + pReuse[Constants.VERTEX_INDEX_X] = pX; + pReuse[Constants.VERTEX_INDEX_Y] = pY; + + this.getLocalToSceneTransformation().transform(pReuse); + + return pReuse; + } + + /* (non-Javadoc) + * @see org.anddev.andengine.entity.IEntity#convertLocalToSceneCoordinates(float[]) + */ + @Override + public float[] convertLocalToSceneCoordinates(final float[] pCoordinates) { + return this.convertSceneToLocalCoordinates(pCoordinates, VERTICES_LOCAL_TO_SCENE_TMP); + } + + /* (non-Javadoc) + * @see org.anddev.andengine.entity.IEntity#convertLocalToSceneCoordinates(float[], float[]) + */ + @Override + public float[] convertLocalToSceneCoordinates(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.getLocalToSceneTransformation().transform(pReuse); + + return pReuse; + } + + /* (non-Javadoc) + * @see org.anddev.andengine.entity.IEntity#convertSceneToLocalCoordinates(float, float) + */ + @Override + public float[] convertSceneToLocalCoordinates(final float pX, final float pY) { + return this.convertSceneToLocalCoordinates(pX, pY, VERTICES_SCENE_TO_LOCAL_TMP); + } + + /* (non-Javadoc) + * @see org.anddev.andengine.entity.IEntity#convertSceneToLocalCoordinates(float, float, float[]) + */ + @Override + public float[] convertSceneToLocalCoordinates(final float pX, final float pY, final float[] pReuse) { + pReuse[Constants.VERTEX_INDEX_X] = pX; + pReuse[Constants.VERTEX_INDEX_Y] = pY; + + this.getSceneToLocalTransformation().transform(pReuse); + + return pReuse; + } + + /* (non-Javadoc) + * @see org.anddev.andengine.entity.IEntity#convertSceneToLocalCoordinates(float[]) + */ + @Override + public float[] convertSceneToLocalCoordinates(final float[] pCoordinates) { + return this.convertSceneToLocalCoordinates(pCoordinates, VERTICES_SCENE_TO_LOCAL_TMP); + } + + /* (non-Javadoc) + * @see org.anddev.andengine.entity.IEntity#convertSceneToLocalCoordinates(float[], float[]) + */ + @Override + public float[] convertSceneToLocalCoordinates(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.getSceneToLocalTransformation().transform(pReuse); + + return pReuse; + } + + @Override + public void onAttached() { + + } + + @Override + public void onDetached() { + + } + + @Override + public Object getUserData() { + return this.mUserData; + } + + @Override + public void setUserData(final Object pUserData) { + this.mUserData = pUserData; + } + + @Override + public final void onDraw(final GL10 pGL, final Camera pCamera) { + if(this.mVisible) { + this.onManagedDraw(pGL, pCamera); + } + } + + @Override + public final void onUpdate(final float pSecondsElapsed) { + if(!this.mIgnoreUpdate) { + this.onManagedUpdate(pSecondsElapsed); + } + } + + @Override + public void reset() { + this.mVisible = true; + this.mIgnoreUpdate = false; + this.mChildrenVisible = true; + this.mChildrenIgnoreUpdate = false; + + this.mX = this.mInitialX; + this.mY = this.mInitialY; + this.mRotation = 0; + this.mScaleX = 1; + this.mScaleY = 1; + + this.mRed = 1.0f; + this.mGreen = 1.0f; + this.mBlue = 1.0f; + this.mAlpha = 1.0f; + + if(this.mEntityModifiers != null) { + this.mEntityModifiers.reset(); + } + + if(this.mChildren != null) { + final ArrayList entities = this.mChildren; + for(int i = entities.size() - 1; i >= 0; i--) { + entities.get(i).reset(); + } + } + } + + // =========================================================== + // Methods + // =========================================================== + + /** + * @param pGL the OpenGL GL1.0 Context (potentially higher than 1.0) to use for drawing. + * @param pCamera the currently active {@link Camera} i.e. to be used for culling. + */ + protected void doDraw(final GL10 pGL, final Camera pCamera) { + + } + + private void allocateEntityModifiers() { + this.mEntityModifiers = new EntityModifierList(this, Entity.ENTITYMODIFIERS_CAPACITY_DEFAULT); + } + + private void allocateChildren() { + this.mChildren = new SmartList(Entity.CHILDREN_CAPACITY_DEFAULT); + } + + private void allocateUpdateHandlers() { + this.mUpdateHandlers = new UpdateHandlerList(Entity.UPDATEHANDLERS_CAPACITY_DEFAULT); + } + + protected void onApplyTransformations(final GL10 pGL) { + /* Translation. */ + this.applyTranslation(pGL); + + /* Rotation. */ + this.applyRotation(pGL); + + /* Scale. */ + this.applyScale(pGL); + } + + protected void applyTranslation(final GL10 pGL) { + pGL.glTranslatef(this.mX, this.mY, 0); + } + + protected void applyRotation(final GL10 pGL) { + final float rotation = this.mRotation; + + if(rotation != 0) { + final float rotationCenterX = this.mRotationCenterX; + final float rotationCenterY = this.mRotationCenterY; + + pGL.glTranslatef(rotationCenterX, rotationCenterY, 0); + pGL.glRotatef(rotation, 0, 0, 1); + pGL.glTranslatef(-rotationCenterX, -rotationCenterY, 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. + * The problem is that applyRotation and applyScale would need to be "merged" in order to efficiently check for that condition. */ + } + } + + protected void applyScale(final GL10 pGL) { + 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; + + pGL.glTranslatef(scaleCenterX, scaleCenterY, 0); + pGL.glScalef(scaleX, scaleY, 1); + pGL.glTranslatef(-scaleCenterX, -scaleCenterY, 0); + } + } + + protected void onManagedDraw(final GL10 pGL, final Camera pCamera) { + pGL.glPushMatrix(); + { + this.onApplyTransformations(pGL); + + this.doDraw(pGL, pCamera); + + this.onDrawChildren(pGL, pCamera); + } + pGL.glPopMatrix(); + } + + protected void onDrawChildren(final GL10 pGL, final Camera pCamera) { + if(this.mChildren != null && this.mChildrenVisible) { + this.onManagedDrawChildren(pGL, pCamera); + } + } + + public void onManagedDrawChildren(final GL10 pGL, final Camera pCamera) { + final ArrayList children = this.mChildren; + final int childCount = children.size(); + for(int i = 0; i < childCount; i++) { + children.get(i).onDraw(pGL, pCamera); + } + } + + protected void onManagedUpdate(final float pSecondsElapsed) { + if(this.mEntityModifiers != null) { + this.mEntityModifiers.onUpdate(pSecondsElapsed); + } + if(this.mUpdateHandlers != null) { + this.mUpdateHandlers.onUpdate(pSecondsElapsed); + } + + if(this.mChildren != null && !this.mChildrenIgnoreUpdate) { + final ArrayList entities = this.mChildren; + final int entityCount = entities.size(); + for(int i = 0; i < entityCount; i++) { + entities.get(i).onUpdate(pSecondsElapsed); + } + } + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/entity/IEntity.java b/AndEngine/src/org/anddev/andengine/entity/IEntity.java index d98f9af7..f9bb613f 100644 --- a/AndEngine/src/org/anddev/andengine/entity/IEntity.java +++ b/AndEngine/src/org/anddev/andengine/entity/IEntity.java @@ -24,263 +24,263 @@ * @since 11:20:25 - 08.03.2010 */ public interface IEntity extends IDrawable, IUpdateHandler { - // =========================================================== - // Final Fields - // =========================================================== - - // =========================================================== - // Methods - // =========================================================== - - public boolean isVisible(); - public void setVisible(final boolean pVisible); - - public boolean isIgnoreUpdate(); - public void setIgnoreUpdate(boolean pIgnoreUpdate); - - public boolean isChildrenVisible(); - public void setChildrenVisible(final boolean pChildrenVisible); - - public boolean isChildrenIgnoreUpdate(); - public void setChildrenIgnoreUpdate(boolean pChildrenIgnoreUpdate); - - public int getZIndex(); - public void setZIndex(final int pZIndex); - - public boolean hasParent(); - public IEntity getParent(); - public void setParent(final IEntity pEntity); - - public float getX(); - public float getY(); - - public float getInitialX(); - public float getInitialY(); - - public void setInitialPosition(); - public void setPosition(final IEntity pOtherEntity); - public void setPosition(final float pX, final float pY); - - public boolean isRotated(); - public float getRotation(); - public void setRotation(final float pRotation); - - public float getRotationCenterX(); - public float getRotationCenterY(); - public void setRotationCenterX(final float pRotationCenterX); - public void setRotationCenterY(final float pRotationCenterY); - public void setRotationCenter(final float pRotationCenterX, final float pRotationCenterY); - - public boolean isScaled(); - public float getScaleX(); - public float getScaleY(); - public void setScaleX(final float pScaleX); - public void setScaleY(final float pScaleY); - public void setScale(final float pScale); - public void setScale(final float pScaleX, final float pScaleY); - - public float getScaleCenterX(); - public float getScaleCenterY(); - public void setScaleCenterX(final float pScaleCenterX); - public void setScaleCenterY(final float pScaleCenterY); - public void setScaleCenter(final float pScaleCenterX, final float pScaleCenterY); - - public float getRed(); - public float getGreen(); - public float getBlue(); - public float getAlpha(); - public void setAlpha(final float pAlpha); - - 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); - - /** - * @return a shared(!) float[] of length 2. - */ - public float[] getSceneCenterCoordinates(); - - /** - * @param pX - * @param pY - * @return a shared(!) float[] of length 2. - */ - public float[] convertLocalToSceneCoordinates(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); - /** - * @param pCoordinates must be of length 2. - * @return a shared(!) float[] of length 2. - */ - public float[] convertLocalToSceneCoordinates(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); - - /** - * @param pX - * @param pY - * @return a shared(!) float[] of length 2. - */ - public float[] convertSceneToLocalCoordinates(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); - /** - * @param pCoordinates must be of length 2. - * @return a shared(!) float[] of length 2. - */ - public float[] convertSceneToLocalCoordinates(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 Transformation getLocalToSceneTransformation(); - public Transformation getSceneToLocalTransformation(); - - // public Transformation getLocalToParentTransformation(); // TODO Add this method. - // public Transformation getParentToLocalTransformation(); // TODO Add this method. - - public int getChildCount(); - - public void onAttached(); - public void onDetached(); - - public void attachChild(final IEntity pEntity); - public boolean attachChild(final IEntity pEntity, final int pIndex); - - public IEntity getChild(final int pIndex); - public IEntity getFirstChild(); - public IEntity getLastChild(); - public int getChildIndex(final IEntity pEntity); - public boolean setChildIndex(final IEntity pEntity, final int pIndex); - - public IEntity findChild(final IEntityMatcher pEntityMatcher); - /** - * @param pEntityMatcher - * @return all children (recursively!) that match the supplied {@link IEntityMatcher}. - */ - public ArrayList query(final IEntityMatcher pEntityMatcher); - /** - * @param pEntityMatcher - * @param pResult the {@link List} to put the result into. - * @return all children (recursively!) that match the supplied {@link IEntityMatcher}. - */ - public > L query(final IEntityMatcher pEntityMatcher, final L pResult); - /** - * @param pEntityMatcher - * @return all children (recursively!) that match the supplied {@link IEntityMatcher}. - * @throws ClassCastException when the supplied {@link IEntityMatcher} matched a {@link IEntity} that was not of the requested subtype. - */ - public ArrayList queryForSubclass(IEntityMatcher pEntityMatcher) throws ClassCastException; - /** - * @param pEntityMatcher - * @param pResult the {@link List} to put the result into. - * @return all children (recursively!) that match the supplied {@link IEntityMatcher}. - * @throws ClassCastException when the supplied {@link IEntityMatcher} matched a {@link IEntity} that was not of the requested subtype. - */ - public , S extends IEntity> L queryForSubclass(final IEntityMatcher pEntityMatcher, final L pResult) throws ClassCastException; - - public boolean swapChildren(final int pIndexA, final int pIndexB); - public boolean swapChildren(final IEntity pEntityA, final IEntity pEntityB); - - /** - * Sorts the {@link IEntity}s based on their ZIndex. Sort is stable. - */ - public void sortChildren(); - - /** - * Sorts the {@link IEntity}s based on the {@link Comparator} supplied. Sort is stable. - * @param pEntityComparator - */ - public void sortChildren(final Comparator pEntityComparator); - - public boolean detachSelf(); - - /** - * WARNING: This function should be called from within - * {@link RunnableHandler#postRunnable(Runnable)} which is registered - * to a {@link Scene} or the {@link Engine} itself, because otherwise - * it may throw an {@link IndexOutOfBoundsException} in the - * Update-Thread or the GL-Thread! - */ - public boolean detachChild(final IEntity pEntity); - /** - * WARNING: This function should be called from within - * {@link RunnableHandler#postRunnable(Runnable)} which is registered - * to a {@link Scene} or the {@link Engine} itself, because otherwise - * it may throw an {@link IndexOutOfBoundsException} in the - * Update-Thread or the GL-Thread! - */ - public IEntity detachChild(final IEntityMatcher pEntityMatcher); - /** - * WARNING: This function should be called from within - * {@link RunnableHandler#postRunnable(Runnable)} which is registered - * to a {@link Scene} or the {@link Engine} itself, because otherwise - * it may throw an {@link IndexOutOfBoundsException} in the - * Update-Thread or the GL-Thread! - */ - public boolean detachChildren(final IEntityMatcher pEntityMatcher); - - public void detachChildren(); - - public void callOnChildren(final IEntityCallable pEntityCallable); - public void callOnChildren(final IEntityMatcher pEntityMatcher, final IEntityCallable pEntityCallable); - - public void registerUpdateHandler(final IUpdateHandler pUpdateHandler); - public boolean unregisterUpdateHandler(final IUpdateHandler pUpdateHandler); - public boolean unregisterUpdateHandlers(final IUpdateHandlerMatcher pUpdateHandlerMatcher); - public void clearUpdateHandlers(); - - public void registerEntityModifier(final IEntityModifier pEntityModifier); - public boolean unregisterEntityModifier(final IEntityModifier pEntityModifier); - public boolean unregisterEntityModifiers(final IEntityModifierMatcher pEntityModifierMatcher); - public void clearEntityModifiers(); - - public void setUserData(Object pUserData); - public Object getUserData(); - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== - - public interface IEntityMatcher extends IMatcher { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Methods - // =========================================================== - - @Override - public boolean matches(final IEntity pEntity); - } - - public interface IEntityCallable extends ParameterCallable { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Methods - // =========================================================== - - @Override - public void call(final IEntity pEntity); - } + // =========================================================== + // Final Fields + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + public boolean isVisible(); + public void setVisible(final boolean pVisible); + + public boolean isIgnoreUpdate(); + public void setIgnoreUpdate(boolean pIgnoreUpdate); + + public boolean isChildrenVisible(); + public void setChildrenVisible(final boolean pChildrenVisible); + + public boolean isChildrenIgnoreUpdate(); + public void setChildrenIgnoreUpdate(boolean pChildrenIgnoreUpdate); + + public int getZIndex(); + public void setZIndex(final int pZIndex); + + public boolean hasParent(); + public IEntity getParent(); + public void setParent(final IEntity pEntity); + + public float getX(); + public float getY(); + + public float getInitialX(); + public float getInitialY(); + + public void setInitialPosition(); + public void setPosition(final IEntity pOtherEntity); + public void setPosition(final float pX, final float pY); + + public boolean isRotated(); + public float getRotation(); + public void setRotation(final float pRotation); + + public float getRotationCenterX(); + public float getRotationCenterY(); + public void setRotationCenterX(final float pRotationCenterX); + public void setRotationCenterY(final float pRotationCenterY); + public void setRotationCenter(final float pRotationCenterX, final float pRotationCenterY); + + public boolean isScaled(); + public float getScaleX(); + public float getScaleY(); + public void setScaleX(final float pScaleX); + public void setScaleY(final float pScaleY); + public void setScale(final float pScale); + public void setScale(final float pScaleX, final float pScaleY); + + public float getScaleCenterX(); + public float getScaleCenterY(); + public void setScaleCenterX(final float pScaleCenterX); + public void setScaleCenterY(final float pScaleCenterY); + public void setScaleCenter(final float pScaleCenterX, final float pScaleCenterY); + + public float getRed(); + public float getGreen(); + public float getBlue(); + public float getAlpha(); + public void setAlpha(final float pAlpha); + + 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); + + /** + * @return a shared(!) float[] of length 2. + */ + public float[] getSceneCenterCoordinates(); + + /** + * @param pX + * @param pY + * @return a shared(!) float[] of length 2. + */ + public float[] convertLocalToSceneCoordinates(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); + /** + * @param pCoordinates must be of length 2. + * @return a shared(!) float[] of length 2. + */ + public float[] convertLocalToSceneCoordinates(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); + + /** + * @param pX + * @param pY + * @return a shared(!) float[] of length 2. + */ + public float[] convertSceneToLocalCoordinates(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); + /** + * @param pCoordinates must be of length 2. + * @return a shared(!) float[] of length 2. + */ + public float[] convertSceneToLocalCoordinates(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 Transformation getLocalToSceneTransformation(); + public Transformation getSceneToLocalTransformation(); + + // public Transformation getLocalToParentTransformation(); // TODO Add this method. + // public Transformation getParentToLocalTransformation(); // TODO Add this method. + + public int getChildCount(); + + public void onAttached(); + public void onDetached(); + + public void attachChild(final IEntity pEntity); + public boolean attachChild(final IEntity pEntity, final int pIndex); + + public IEntity getChild(final int pIndex); + public IEntity getFirstChild(); + public IEntity getLastChild(); + public int getChildIndex(final IEntity pEntity); + public boolean setChildIndex(final IEntity pEntity, final int pIndex); + + public IEntity findChild(final IEntityMatcher pEntityMatcher); + /** + * @param pEntityMatcher + * @return all children (recursively!) that match the supplied {@link IEntityMatcher}. + */ + public ArrayList query(final IEntityMatcher pEntityMatcher); + /** + * @param pEntityMatcher + * @param pResult the {@link List} to put the result into. + * @return all children (recursively!) that match the supplied {@link IEntityMatcher}. + */ + public > L query(final IEntityMatcher pEntityMatcher, final L pResult); + /** + * @param pEntityMatcher + * @return all children (recursively!) that match the supplied {@link IEntityMatcher}. + * @throws ClassCastException when the supplied {@link IEntityMatcher} matched a {@link IEntity} that was not of the requested subtype. + */ + public ArrayList queryForSubclass(IEntityMatcher pEntityMatcher) throws ClassCastException; + /** + * @param pEntityMatcher + * @param pResult the {@link List} to put the result into. + * @return all children (recursively!) that match the supplied {@link IEntityMatcher}. + * @throws ClassCastException when the supplied {@link IEntityMatcher} matched a {@link IEntity} that was not of the requested subtype. + */ + public , S extends IEntity> L queryForSubclass(final IEntityMatcher pEntityMatcher, final L pResult) throws ClassCastException; + + public boolean swapChildren(final int pIndexA, final int pIndexB); + public boolean swapChildren(final IEntity pEntityA, final IEntity pEntityB); + + /** + * Sorts the {@link IEntity}s based on their ZIndex. Sort is stable. + */ + public void sortChildren(); + + /** + * Sorts the {@link IEntity}s based on the {@link Comparator} supplied. Sort is stable. + * @param pEntityComparator + */ + public void sortChildren(final Comparator pEntityComparator); + + public boolean detachSelf(); + + /** + * WARNING: This function should be called from within + * {@link RunnableHandler#postRunnable(Runnable)} which is registered + * to a {@link Scene} or the {@link Engine} itself, because otherwise + * it may throw an {@link IndexOutOfBoundsException} in the + * Update-Thread or the GL-Thread! + */ + public boolean detachChild(final IEntity pEntity); + /** + * WARNING: This function should be called from within + * {@link RunnableHandler#postRunnable(Runnable)} which is registered + * to a {@link Scene} or the {@link Engine} itself, because otherwise + * it may throw an {@link IndexOutOfBoundsException} in the + * Update-Thread or the GL-Thread! + */ + public IEntity detachChild(final IEntityMatcher pEntityMatcher); + /** + * WARNING: This function should be called from within + * {@link RunnableHandler#postRunnable(Runnable)} which is registered + * to a {@link Scene} or the {@link Engine} itself, because otherwise + * it may throw an {@link IndexOutOfBoundsException} in the + * Update-Thread or the GL-Thread! + */ + public boolean detachChildren(final IEntityMatcher pEntityMatcher); + + public void detachChildren(); + + public void callOnChildren(final IEntityCallable pEntityCallable); + public void callOnChildren(final IEntityMatcher pEntityMatcher, final IEntityCallable pEntityCallable); + + public void registerUpdateHandler(final IUpdateHandler pUpdateHandler); + public boolean unregisterUpdateHandler(final IUpdateHandler pUpdateHandler); + public boolean unregisterUpdateHandlers(final IUpdateHandlerMatcher pUpdateHandlerMatcher); + public void clearUpdateHandlers(); + + public void registerEntityModifier(final IEntityModifier pEntityModifier); + public boolean unregisterEntityModifier(final IEntityModifier pEntityModifier); + public boolean unregisterEntityModifiers(final IEntityModifierMatcher pEntityModifierMatcher); + public void clearEntityModifiers(); + + public void setUserData(Object pUserData); + public Object getUserData(); + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== + + public interface IEntityMatcher extends IMatcher { + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + @Override + public boolean matches(final IEntity pEntity); + } + + public interface IEntityCallable extends ParameterCallable { + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + @Override + public void call(final IEntity pEntity); + } } diff --git a/AndEngine/src/org/anddev/andengine/entity/ZIndexSorter.java b/AndEngine/src/org/anddev/andengine/entity/ZIndexSorter.java index d1cd103b..c6057bac 100644 --- a/AndEngine/src/org/anddev/andengine/entity/ZIndexSorter.java +++ b/AndEngine/src/org/anddev/andengine/entity/ZIndexSorter.java @@ -6,67 +6,67 @@ import org.anddev.andengine.util.sort.InsertionSorter; public class ZIndexSorter extends InsertionSorter { - // =========================================================== - // Constants - // =========================================================== - - private static ZIndexSorter INSTANCE; - - // =========================================================== - // Fields - // =========================================================== - - private final Comparator mZIndexComparator = new Comparator() { - @Override - public int compare(final IEntity pEntityA, final IEntity pEntityB) { - return pEntityA.getZIndex() - pEntityB.getZIndex(); - } - }; - - // =========================================================== - // Constructors - // =========================================================== - - private ZIndexSorter() { - - } - - public static ZIndexSorter getInstance() { - if(INSTANCE == null) { - INSTANCE = new ZIndexSorter(); - } - return INSTANCE; - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - // =========================================================== - // Methods - // =========================================================== - - public void sort(final IEntity[] pEntities) { - this.sort(pEntities, this.mZIndexComparator); - } - - public void sort(final IEntity[] pEntities, final int pStart, final int pEnd) { - this.sort(pEntities, pStart, pEnd, this.mZIndexComparator); - } - - public void sort(final List pEntities) { - this.sort(pEntities, this.mZIndexComparator); - } - - public void sort(final List pEntities, final int pStart, final int pEnd) { - this.sort(pEntities, pStart, pEnd, this.mZIndexComparator); - } - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== -} \ No newline at end of file + // =========================================================== + // Constants + // =========================================================== + + private static ZIndexSorter INSTANCE; + + // =========================================================== + // Fields + // =========================================================== + + private final Comparator mZIndexComparator = new Comparator() { + @Override + public int compare(final IEntity pEntityA, final IEntity pEntityB) { + return pEntityA.getZIndex() - pEntityB.getZIndex(); + } + }; + + // =========================================================== + // Constructors + // =========================================================== + + private ZIndexSorter() { + + } + + public static ZIndexSorter getInstance() { + if(INSTANCE == null) { + INSTANCE = new ZIndexSorter(); + } + return INSTANCE; + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + public void sort(final IEntity[] pEntities) { + this.sort(pEntities, this.mZIndexComparator); + } + + public void sort(final IEntity[] pEntities, final int pStart, final int pEnd) { + this.sort(pEntities, pStart, pEnd, this.mZIndexComparator); + } + + public void sort(final List pEntities) { + this.sort(pEntities, this.mZIndexComparator); + } + + public void sort(final List pEntities, final int pStart, final int pEnd) { + this.sort(pEntities, pStart, pEnd, this.mZIndexComparator); + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== +} diff --git a/AndEngine/src/org/anddev/andengine/entity/modifier/AlphaModifier.java b/AndEngine/src/org/anddev/andengine/entity/modifier/AlphaModifier.java index f729f2af..1eabe993 100644 --- a/AndEngine/src/org/anddev/andengine/entity/modifier/AlphaModifier.java +++ b/AndEngine/src/org/anddev/andengine/entity/modifier/AlphaModifier.java @@ -11,66 +11,66 @@ * @since 23:13:01 - 19.03.2010 */ public class AlphaModifier extends SingleValueSpanEntityModifier { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - // =========================================================== - // Constructors - // =========================================================== - - public AlphaModifier(final float pDuration, final float pFromAlpha, final float pToAlpha) { - this(pDuration, pFromAlpha, pToAlpha, null, IEaseFunction.DEFAULT); - } - - public AlphaModifier(final float pDuration, final float pFromAlpha, final float pToAlpha, final IEaseFunction pEaseFunction) { - this(pDuration, pFromAlpha, pToAlpha, null, pEaseFunction); - } - - public AlphaModifier(final float pDuration, final float pFromAlpha, final float pToAlpha, final IEntityModifierListener pEntityModifierListener) { - super(pDuration, pFromAlpha, pToAlpha, pEntityModifierListener, IEaseFunction.DEFAULT); - } - - public AlphaModifier(final float pDuration, final float pFromAlpha, final float pToAlpha, final IEntityModifierListener pEntityModifierListener, final IEaseFunction pEaseFunction) { - super(pDuration, pFromAlpha, pToAlpha, pEntityModifierListener, pEaseFunction); - } - - protected AlphaModifier(final AlphaModifier pAlphaModifier) { - super(pAlphaModifier); - } - - @Override - public AlphaModifier deepCopy(){ - return new AlphaModifier(this); - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - protected void onSetInitialValue(final IEntity pEntity, final float pAlpha) { - pEntity.setAlpha(pAlpha); - } - - @Override - protected void onSetValue(final IEntity pEntity, final float pPercentageDone, final float pAlpha) { - pEntity.setAlpha(pAlpha); - } - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + // =========================================================== + // Constructors + // =========================================================== + + public AlphaModifier(final float pDuration, final float pFromAlpha, final float pToAlpha) { + this(pDuration, pFromAlpha, pToAlpha, null, IEaseFunction.DEFAULT); + } + + public AlphaModifier(final float pDuration, final float pFromAlpha, final float pToAlpha, final IEaseFunction pEaseFunction) { + this(pDuration, pFromAlpha, pToAlpha, null, pEaseFunction); + } + + public AlphaModifier(final float pDuration, final float pFromAlpha, final float pToAlpha, final IEntityModifierListener pEntityModifierListener) { + super(pDuration, pFromAlpha, pToAlpha, pEntityModifierListener, IEaseFunction.DEFAULT); + } + + public AlphaModifier(final float pDuration, final float pFromAlpha, final float pToAlpha, final IEntityModifierListener pEntityModifierListener, final IEaseFunction pEaseFunction) { + super(pDuration, pFromAlpha, pToAlpha, pEntityModifierListener, pEaseFunction); + } + + protected AlphaModifier(final AlphaModifier pAlphaModifier) { + super(pAlphaModifier); + } + + @Override + public AlphaModifier deepCopy(){ + return new AlphaModifier(this); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + protected void onSetInitialValue(final IEntity pEntity, final float pAlpha) { + pEntity.setAlpha(pAlpha); + } + + @Override + protected void onSetValue(final IEntity pEntity, final float pPercentageDone, final float pAlpha) { + pEntity.setAlpha(pAlpha); + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/entity/modifier/ColorModifier.java b/AndEngine/src/org/anddev/andengine/entity/modifier/ColorModifier.java index b8fdd333..d2f541df 100644 --- a/AndEngine/src/org/anddev/andengine/entity/modifier/ColorModifier.java +++ b/AndEngine/src/org/anddev/andengine/entity/modifier/ColorModifier.java @@ -11,66 +11,66 @@ * @since 15:39:50 - 29.06.2010 */ public class ColorModifier extends TripleValueSpanEntityModifier { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - // =========================================================== - // Constructors - // =========================================================== - - public ColorModifier(final float pDuration, final float pFromRed, final float pToRed, final float pFromGreen, final float pToGreen, final float pFromBlue, final float pToBlue) { - this(pDuration, pFromRed, pToRed, pFromGreen, pToGreen, pFromBlue, pToBlue, null, IEaseFunction.DEFAULT); - } - - public ColorModifier(final float pDuration, final float pFromRed, final float pToRed, final float pFromGreen, final float pToGreen, final float pFromBlue, final float pToBlue, final IEaseFunction pEaseFunction) { - this(pDuration, pFromRed, pToRed, pFromGreen, pToGreen, pFromBlue, pToBlue, null, pEaseFunction); - } - - public ColorModifier(final float pDuration, final float pFromRed, final float pToRed, final float pFromGreen, final float pToGreen, final float pFromBlue, final float pToBlue, final IEntityModifierListener pEntityModifierListener) { - super(pDuration, pFromRed, pToRed, pFromGreen, pToGreen, pFromBlue, pToBlue, pEntityModifierListener, IEaseFunction.DEFAULT); - } - - public ColorModifier(final float pDuration, final float pFromRed, final float pToRed, final float pFromGreen, final float pToGreen, final float pFromBlue, final float pToBlue, final IEntityModifierListener pEntityModifierListener, final IEaseFunction pEaseFunction) { - super(pDuration, pFromRed, pToRed, pFromGreen, pToGreen, pFromBlue, pToBlue, pEntityModifierListener, pEaseFunction); - } - - protected ColorModifier(final ColorModifier pColorModifier) { - super(pColorModifier); - } - - @Override - public ColorModifier deepCopy(){ - return new ColorModifier(this); - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - protected void onSetInitialValues(final IEntity pEntity, final float pRed, final float pGreen, final float pBlue) { - pEntity.setColor(pRed, pGreen, pBlue); - } - - @Override - protected void onSetValues(final IEntity pEntity, final float pPerctentageDone, final float pRed, final float pGreen, final float pBlue) { - pEntity.setColor(pRed, pGreen, pBlue); - } - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + // =========================================================== + // Constructors + // =========================================================== + + public ColorModifier(final float pDuration, final float pFromRed, final float pToRed, final float pFromGreen, final float pToGreen, final float pFromBlue, final float pToBlue) { + this(pDuration, pFromRed, pToRed, pFromGreen, pToGreen, pFromBlue, pToBlue, null, IEaseFunction.DEFAULT); + } + + public ColorModifier(final float pDuration, final float pFromRed, final float pToRed, final float pFromGreen, final float pToGreen, final float pFromBlue, final float pToBlue, final IEaseFunction pEaseFunction) { + this(pDuration, pFromRed, pToRed, pFromGreen, pToGreen, pFromBlue, pToBlue, null, pEaseFunction); + } + + public ColorModifier(final float pDuration, final float pFromRed, final float pToRed, final float pFromGreen, final float pToGreen, final float pFromBlue, final float pToBlue, final IEntityModifierListener pEntityModifierListener) { + super(pDuration, pFromRed, pToRed, pFromGreen, pToGreen, pFromBlue, pToBlue, pEntityModifierListener, IEaseFunction.DEFAULT); + } + + public ColorModifier(final float pDuration, final float pFromRed, final float pToRed, final float pFromGreen, final float pToGreen, final float pFromBlue, final float pToBlue, final IEntityModifierListener pEntityModifierListener, final IEaseFunction pEaseFunction) { + super(pDuration, pFromRed, pToRed, pFromGreen, pToGreen, pFromBlue, pToBlue, pEntityModifierListener, pEaseFunction); + } + + protected ColorModifier(final ColorModifier pColorModifier) { + super(pColorModifier); + } + + @Override + public ColorModifier deepCopy(){ + return new ColorModifier(this); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + protected void onSetInitialValues(final IEntity pEntity, final float pRed, final float pGreen, final float pBlue) { + pEntity.setColor(pRed, pGreen, pBlue); + } + + @Override + protected void onSetValues(final IEntity pEntity, final float pPerctentageDone, final float pRed, final float pGreen, final float pBlue) { + pEntity.setColor(pRed, pGreen, pBlue); + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/entity/modifier/CubicBezierMoveModifier.java b/AndEngine/src/org/anddev/andengine/entity/modifier/CubicBezierMoveModifier.java index 7e5c2ae0..eb098eba 100644 --- a/AndEngine/src/org/anddev/andengine/entity/modifier/CubicBezierMoveModifier.java +++ b/AndEngine/src/org/anddev/andengine/entity/modifier/CubicBezierMoveModifier.java @@ -12,101 +12,101 @@ * @since 23:24:26 - 16.07.2011 */ public class CubicBezierMoveModifier extends DurationEntityModifier { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - private final float mX1; - private final float mY1; - private final float mX2; - private final float mY2; - private final float mX3; - private final float mY3; - private final float mX4; - private final float mY4; - - private final IEaseFunction mEaseFunction; - - // =========================================================== - // Constructors - // =========================================================== - - /** - * @param pDuration - * @param pX1 x coordinate of the start point. - * @param pY1 y coordinate of the start point. - * @param pX2 x coordinate of the first control point. - * @param pY2 y coordinate of the first control point. - * @param pX3 x coordinate of the second control point. - * @param pY3 y coordinate of the second control point. - * @param pX4 x coordinate of the end point. - * @param pY4 y coordinate of the end point. - * @param pEaseFunction - */ - public CubicBezierMoveModifier(final float pDuration, final float pX1, final float pY1, final float pX2, final float pY2, final float pX3, final float pY3, final float pX4, final float pY4, final IEaseFunction pEaseFunction) { - super(pDuration); - - this.mX1 = pX1; - this.mY1 = pY1; - this.mX2 = pX2; - this.mY2 = pY2; - this.mX3 = pX3; - this.mY3 = pY3; - this.mX4 = pX4; - this.mY4 = pY4; - - this.mEaseFunction = pEaseFunction; - } - - @Override - public CubicBezierMoveModifier deepCopy() { - return new CubicBezierMoveModifier(this.mDuration, this.mX1, this.mY1, this.mX2, this.mY2, this.mX3, this.mY3, this.mX4, this.mY4, this.mEaseFunction); - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - protected void onManagedUpdate(final float pSecondsElapsed, final IEntity pEntity) { - 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 uuu = uu * u; - final float ttt = tt * percentageDone; - - final float ut3 = 3 * uu * percentageDone; - final float utt3 = 3 * u * tt; - - /* - * Formula: ((1-t)^3 * p1) + (3*(t)*(1-t)^2 * p2) + (3*(t^2)*(1-t) * p3) + (t^3 * p4) - */ - final float x = (uuu * this.mX1) + (ut3 * this.mX2) + (utt3 * this.mX3) + (ttt * this.mX4); - final float y = (uuu * this.mY1) + (ut3 * this.mY2) + (utt3 * this.mY3) + (ttt * this.mY4); - - pEntity.setPosition(x, y); - } - - @Override - protected void onManagedInitialize(final IEntity pEntity) { - - } - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== -} \ No newline at end of file + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + private final float mX1; + private final float mY1; + private final float mX2; + private final float mY2; + private final float mX3; + private final float mY3; + private final float mX4; + private final float mY4; + + private final IEaseFunction mEaseFunction; + + // =========================================================== + // Constructors + // =========================================================== + + /** + * @param pDuration + * @param pX1 x coordinate of the start point. + * @param pY1 y coordinate of the start point. + * @param pX2 x coordinate of the first control point. + * @param pY2 y coordinate of the first control point. + * @param pX3 x coordinate of the second control point. + * @param pY3 y coordinate of the second control point. + * @param pX4 x coordinate of the end point. + * @param pY4 y coordinate of the end point. + * @param pEaseFunction + */ + public CubicBezierMoveModifier(final float pDuration, final float pX1, final float pY1, final float pX2, final float pY2, final float pX3, final float pY3, final float pX4, final float pY4, final IEaseFunction pEaseFunction) { + super(pDuration); + + this.mX1 = pX1; + this.mY1 = pY1; + this.mX2 = pX2; + this.mY2 = pY2; + this.mX3 = pX3; + this.mY3 = pY3; + this.mX4 = pX4; + this.mY4 = pY4; + + this.mEaseFunction = pEaseFunction; + } + + @Override + public CubicBezierMoveModifier deepCopy() { + return new CubicBezierMoveModifier(this.mDuration, this.mX1, this.mY1, this.mX2, this.mY2, this.mX3, this.mY3, this.mX4, this.mY4, this.mEaseFunction); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + protected void onManagedUpdate(final float pSecondsElapsed, final IEntity pEntity) { + 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 uuu = uu * u; + final float ttt = tt * percentageDone; + + final float ut3 = 3 * uu * percentageDone; + final float utt3 = 3 * u * tt; + + /* + * Formula: ((1-t)^3 * p1) + (3*(t)*(1-t)^2 * p2) + (3*(t^2)*(1-t) * p3) + (t^3 * p4) + */ + final float x = (uuu * this.mX1) + (ut3 * this.mX2) + (utt3 * this.mX3) + (ttt * this.mX4); + final float y = (uuu * this.mY1) + (ut3 * this.mY2) + (utt3 * this.mY3) + (ttt * this.mY4); + + pEntity.setPosition(x, y); + } + + @Override + protected void onManagedInitialize(final IEntity pEntity) { + + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== +} diff --git a/AndEngine/src/org/anddev/andengine/entity/modifier/DelayModifier.java b/AndEngine/src/org/anddev/andengine/entity/modifier/DelayModifier.java index a821edb9..a4e34dcb 100644 --- a/AndEngine/src/org/anddev/andengine/entity/modifier/DelayModifier.java +++ b/AndEngine/src/org/anddev/andengine/entity/modifier/DelayModifier.java @@ -10,58 +10,58 @@ * @since 22:55:13 - 19.03.2010 */ public class DelayModifier extends DurationEntityModifier { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - public DelayModifier(final float pDuration, final IEntityModifierListener pEntityModifierListener) { - super(pDuration, pEntityModifierListener); - } + public DelayModifier(final float pDuration, final IEntityModifierListener pEntityModifierListener) { + super(pDuration, pEntityModifierListener); + } - public DelayModifier(final float pDuration) { - super(pDuration); - } + public DelayModifier(final float pDuration) { + super(pDuration); + } - protected DelayModifier(final DelayModifier pDelayModifier) { - super(pDelayModifier); - } + protected DelayModifier(final DelayModifier pDelayModifier) { + super(pDelayModifier); + } - @Override - public DelayModifier deepCopy(){ - return new DelayModifier(this); - } + @Override + public DelayModifier deepCopy(){ + return new DelayModifier(this); + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - @Override - protected void onManagedInitialize(final IEntity pEntity) { + @Override + protected void onManagedInitialize(final IEntity pEntity) { - } + } - @Override - protected void onManagedUpdate(final float pSecondsElapsed, final IEntity pEntity) { + @Override + protected void onManagedUpdate(final float pSecondsElapsed, final IEntity pEntity) { - } + } - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/entity/modifier/DoubleValueChangeEntityModifier.java b/AndEngine/src/org/anddev/andengine/entity/modifier/DoubleValueChangeEntityModifier.java index 135933f6..77ebfe8d 100644 --- a/AndEngine/src/org/anddev/andengine/entity/modifier/DoubleValueChangeEntityModifier.java +++ b/AndEngine/src/org/anddev/andengine/entity/modifier/DoubleValueChangeEntityModifier.java @@ -10,43 +10,43 @@ * @since 14:27:48 - 10.08.2011 */ public abstract class DoubleValueChangeEntityModifier extends BaseDoubleValueChangeModifier implements IEntityModifier { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - public DoubleValueChangeEntityModifier(float pDuration, float pValueChangeA, float pValueChangeB) { - super(pDuration, pValueChangeA, pValueChangeB); - } + public DoubleValueChangeEntityModifier(float pDuration, float pValueChangeA, float pValueChangeB) { + super(pDuration, pValueChangeA, pValueChangeB); + } - public DoubleValueChangeEntityModifier(float pDuration, float pValueChangeA, float pValueChangeB, IEntityModifierListener pModifierListener) { - super(pDuration, pValueChangeA, pValueChangeB, pModifierListener); - } + public DoubleValueChangeEntityModifier(float pDuration, float pValueChangeA, float pValueChangeB, IEntityModifierListener pModifierListener) { + super(pDuration, pValueChangeA, pValueChangeB, pModifierListener); + } - public DoubleValueChangeEntityModifier(DoubleValueChangeEntityModifier pDoubleValueChangeEntityModifier) { - super(pDoubleValueChangeEntityModifier); - } + public DoubleValueChangeEntityModifier(DoubleValueChangeEntityModifier pDoubleValueChangeEntityModifier) { + super(pDoubleValueChangeEntityModifier); + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/entity/modifier/DoubleValueSpanEntityModifier.java b/AndEngine/src/org/anddev/andengine/entity/modifier/DoubleValueSpanEntityModifier.java index adb005ec..cc3c8ebc 100644 --- a/AndEngine/src/org/anddev/andengine/entity/modifier/DoubleValueSpanEntityModifier.java +++ b/AndEngine/src/org/anddev/andengine/entity/modifier/DoubleValueSpanEntityModifier.java @@ -12,51 +12,51 @@ * @since 23:29:22 - 19.03.2010 */ public abstract class DoubleValueSpanEntityModifier extends BaseDoubleValueSpanModifier implements IEntityModifier { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - public DoubleValueSpanEntityModifier(final float pDuration, final float pFromValueA, final float pToValueA, final float pFromValueB, final float pToValueB) { - super(pDuration, pFromValueA, pToValueA, pFromValueB, pToValueB); - } + public DoubleValueSpanEntityModifier(final float pDuration, final float pFromValueA, final float pToValueA, final float pFromValueB, final float pToValueB) { + super(pDuration, pFromValueA, pToValueA, pFromValueB, pToValueB); + } - public DoubleValueSpanEntityModifier(final float pDuration, final float pFromValueA, final float pToValueA, final float pFromValueB, final float pToValueB, final IEaseFunction pEaseFunction) { - super(pDuration, pFromValueA, pToValueA, pFromValueB, pToValueB, pEaseFunction); - } + public DoubleValueSpanEntityModifier(final float pDuration, final float pFromValueA, final float pToValueA, final float pFromValueB, final float pToValueB, final IEaseFunction pEaseFunction) { + super(pDuration, pFromValueA, pToValueA, pFromValueB, pToValueB, pEaseFunction); + } - public DoubleValueSpanEntityModifier(final float pDuration, final float pFromValueA, final float pToValueA, final float pFromValueB, final float pToValueB, final IEntityModifierListener pEntityModifierListener) { - super(pDuration, pFromValueA, pToValueA, pFromValueB, pToValueB, pEntityModifierListener); - } + public DoubleValueSpanEntityModifier(final float pDuration, final float pFromValueA, final float pToValueA, final float pFromValueB, final float pToValueB, final IEntityModifierListener pEntityModifierListener) { + super(pDuration, pFromValueA, pToValueA, pFromValueB, pToValueB, pEntityModifierListener); + } - public DoubleValueSpanEntityModifier(final float pDuration, final float pFromValueA, final float pToValueA, final float pFromValueB, final float pToValueB, final IEntityModifierListener pEntityModifierListener, final IEaseFunction pEaseFunction) { - super(pDuration, pFromValueA, pToValueA, pFromValueB, pToValueB, pEntityModifierListener, pEaseFunction); - } + public DoubleValueSpanEntityModifier(final float pDuration, final float pFromValueA, final float pToValueA, final float pFromValueB, final float pToValueB, final IEntityModifierListener pEntityModifierListener, final IEaseFunction pEaseFunction) { + super(pDuration, pFromValueA, pToValueA, pFromValueB, pToValueB, pEntityModifierListener, pEaseFunction); + } - protected DoubleValueSpanEntityModifier(final DoubleValueSpanEntityModifier pDoubleValueSpanEntityModifier) { - super(pDoubleValueSpanEntityModifier); - } + protected DoubleValueSpanEntityModifier(final DoubleValueSpanEntityModifier pDoubleValueSpanEntityModifier) { + super(pDoubleValueSpanEntityModifier); + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/entity/modifier/DurationEntityModifier.java b/AndEngine/src/org/anddev/andengine/entity/modifier/DurationEntityModifier.java index ada60630..14fabbf7 100644 --- a/AndEngine/src/org/anddev/andengine/entity/modifier/DurationEntityModifier.java +++ b/AndEngine/src/org/anddev/andengine/entity/modifier/DurationEntityModifier.java @@ -11,43 +11,43 @@ * @since 16:10:42 - 19.03.2010 */ public abstract class DurationEntityModifier extends BaseDurationModifier implements IEntityModifier { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - public DurationEntityModifier(final float pDuration) { - super(pDuration); - } + public DurationEntityModifier(final float pDuration) { + super(pDuration); + } - public DurationEntityModifier(final float pDuration, final IEntityModifierListener pEntityModifierListener) { - super(pDuration, pEntityModifierListener); - } + public DurationEntityModifier(final float pDuration, final IEntityModifierListener pEntityModifierListener) { + super(pDuration, pEntityModifierListener); + } - protected DurationEntityModifier(final DurationEntityModifier pDurationEntityModifier) { - super(pDurationEntityModifier); - } + protected DurationEntityModifier(final DurationEntityModifier pDurationEntityModifier) { + super(pDurationEntityModifier); + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/entity/modifier/EntityModifier.java b/AndEngine/src/org/anddev/andengine/entity/modifier/EntityModifier.java index a6604814..52af22dc 100644 --- a/AndEngine/src/org/anddev/andengine/entity/modifier/EntityModifier.java +++ b/AndEngine/src/org/anddev/andengine/entity/modifier/EntityModifier.java @@ -11,39 +11,39 @@ * @since 10:53:16 - 03.09.2010 */ public abstract class EntityModifier extends BaseModifier implements IEntityModifier { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - public EntityModifier() { - super(); - } + public EntityModifier() { + super(); + } - public EntityModifier(final IEntityModifierListener pEntityModifierListener) { - super(pEntityModifierListener); - } + public EntityModifier(final IEntityModifierListener pEntityModifierListener) { + super(pEntityModifierListener); + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/entity/modifier/EntityModifierList.java b/AndEngine/src/org/anddev/andengine/entity/modifier/EntityModifierList.java index 1f21b99e..6e5d2788 100644 --- a/AndEngine/src/org/anddev/andengine/entity/modifier/EntityModifierList.java +++ b/AndEngine/src/org/anddev/andengine/entity/modifier/EntityModifierList.java @@ -11,41 +11,41 @@ * @since 14:19:18 - 24.12.2010 */ public class EntityModifierList extends ModifierList { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - private static final long serialVersionUID = 161652765736600082L; + private static final long serialVersionUID = 161652765736600082L; - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - public EntityModifierList(final IEntity pTarget) { - super(pTarget); - } + public EntityModifierList(final IEntity pTarget) { + super(pTarget); + } - public EntityModifierList(final IEntity pTarget, final int pCapacity) { - super(pTarget, pCapacity); - } + public EntityModifierList(final IEntity pTarget, final int pCapacity) { + super(pTarget, pCapacity); + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/entity/modifier/FadeInModifier.java b/AndEngine/src/org/anddev/andengine/entity/modifier/FadeInModifier.java index 6d2ae63f..8944b58f 100644 --- a/AndEngine/src/org/anddev/andengine/entity/modifier/FadeInModifier.java +++ b/AndEngine/src/org/anddev/andengine/entity/modifier/FadeInModifier.java @@ -11,56 +11,56 @@ * @since 19:03:12 - 08.06.2010 */ public class FadeInModifier extends AlphaModifier { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - public FadeInModifier(final float pDuration) { - super(pDuration, 0.0f, 1.0f, IEaseFunction.DEFAULT); - } + public FadeInModifier(final float pDuration) { + super(pDuration, 0.0f, 1.0f, IEaseFunction.DEFAULT); + } - public FadeInModifier(final float pDuration, final IEaseFunction pEaseFunction) { - super(pDuration, 0.0f, 1.0f, pEaseFunction); - } + public FadeInModifier(final float pDuration, final IEaseFunction pEaseFunction) { + super(pDuration, 0.0f, 1.0f, pEaseFunction); + } - public FadeInModifier(final float pDuration, final IEntityModifierListener pEntityModifierListener) { - super(pDuration, 0.0f, 1.0f, pEntityModifierListener, IEaseFunction.DEFAULT); - } + public FadeInModifier(final float pDuration, final IEntityModifierListener pEntityModifierListener) { + super(pDuration, 0.0f, 1.0f, pEntityModifierListener, IEaseFunction.DEFAULT); + } - public FadeInModifier(final float pDuration, final IEntityModifierListener pEntityModifierListener, final IEaseFunction pEaseFunction) { - super(pDuration, 0.0f, 1.0f, pEntityModifierListener, pEaseFunction); - } + public FadeInModifier(final float pDuration, final IEntityModifierListener pEntityModifierListener, final IEaseFunction pEaseFunction) { + super(pDuration, 0.0f, 1.0f, pEntityModifierListener, pEaseFunction); + } - protected FadeInModifier(final FadeInModifier pFadeInModifier) { - super(pFadeInModifier); - } + protected FadeInModifier(final FadeInModifier pFadeInModifier) { + super(pFadeInModifier); + } - @Override - public FadeInModifier deepCopy() { - return new FadeInModifier(this); - } + @Override + public FadeInModifier deepCopy() { + return new FadeInModifier(this); + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/entity/modifier/FadeOutModifier.java b/AndEngine/src/org/anddev/andengine/entity/modifier/FadeOutModifier.java index c14d5e01..71de5232 100644 --- a/AndEngine/src/org/anddev/andengine/entity/modifier/FadeOutModifier.java +++ b/AndEngine/src/org/anddev/andengine/entity/modifier/FadeOutModifier.java @@ -11,56 +11,56 @@ * @since 19:03:12 - 08.06.2010 */ public class FadeOutModifier extends AlphaModifier { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - public FadeOutModifier(final float pDuration) { - super(pDuration, 1.0f, 0.0f, IEaseFunction.DEFAULT); - } + public FadeOutModifier(final float pDuration) { + super(pDuration, 1.0f, 0.0f, IEaseFunction.DEFAULT); + } - public FadeOutModifier(final float pDuration, final IEaseFunction pEaseFunction) { - super(pDuration, 1.0f, 0.0f, pEaseFunction); - } + public FadeOutModifier(final float pDuration, final IEaseFunction pEaseFunction) { + super(pDuration, 1.0f, 0.0f, pEaseFunction); + } - public FadeOutModifier(final float pDuration, final IEntityModifierListener pEntityModifierListener) { - super(pDuration, 1.0f, 0.0f, pEntityModifierListener, IEaseFunction.DEFAULT); - } + public FadeOutModifier(final float pDuration, final IEntityModifierListener pEntityModifierListener) { + super(pDuration, 1.0f, 0.0f, pEntityModifierListener, IEaseFunction.DEFAULT); + } - public FadeOutModifier(final float pDuration, final IEntityModifierListener pEntityModifierListener, final IEaseFunction pEaseFunction) { - super(pDuration, 1.0f, 0.0f, pEntityModifierListener, pEaseFunction); - } + public FadeOutModifier(final float pDuration, final IEntityModifierListener pEntityModifierListener, final IEaseFunction pEaseFunction) { + super(pDuration, 1.0f, 0.0f, pEntityModifierListener, pEaseFunction); + } - protected FadeOutModifier(final FadeOutModifier pFadeOutModifier) { - super(pFadeOutModifier); - } + protected FadeOutModifier(final FadeOutModifier pFadeOutModifier) { + super(pFadeOutModifier); + } - @Override - public FadeOutModifier deepCopy() { - return new FadeOutModifier(this); - } + @Override + public FadeOutModifier deepCopy() { + return new FadeOutModifier(this); + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/entity/modifier/IEntityModifier.java b/AndEngine/src/org/anddev/andengine/entity/modifier/IEntityModifier.java index f8548500..3847ba84 100644 --- a/AndEngine/src/org/anddev/andengine/entity/modifier/IEntityModifier.java +++ b/AndEngine/src/org/anddev/andengine/entity/modifier/IEntityModifier.java @@ -12,38 +12,38 @@ * @since 11:17:50 - 19.03.2010 */ public interface IEntityModifier extends IModifier { - // =========================================================== - // Final Fields - // =========================================================== + // =========================================================== + // Final Fields + // =========================================================== - // =========================================================== - // Methods - // =========================================================== - - @Override - public IEntityModifier deepCopy() throws DeepCopyNotSupportedException; + // =========================================================== + // Methods + // =========================================================== + + @Override + public IEntityModifier deepCopy() throws DeepCopyNotSupportedException; - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== - public static interface IEntityModifierListener extends IModifierListener{ - // =========================================================== - // Final Fields - // =========================================================== + public static interface IEntityModifierListener extends IModifierListener{ + // =========================================================== + // Final Fields + // =========================================================== - // =========================================================== - // Methods - // =========================================================== - } - - public interface IEntityModifierMatcher extends IMatcher> { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Methods + // =========================================================== + } + + public interface IEntityModifierMatcher extends IMatcher> { + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Methods - // =========================================================== - } + // =========================================================== + // Methods + // =========================================================== + } } diff --git a/AndEngine/src/org/anddev/andengine/entity/modifier/LoopEntityModifier.java b/AndEngine/src/org/anddev/andengine/entity/modifier/LoopEntityModifier.java index 9d02d74f..4c44d1aa 100644 --- a/AndEngine/src/org/anddev/andengine/entity/modifier/LoopEntityModifier.java +++ b/AndEngine/src/org/anddev/andengine/entity/modifier/LoopEntityModifier.java @@ -11,70 +11,70 @@ * @since 12:42:13 - 03.09.2010 */ public class LoopEntityModifier extends LoopModifier implements IEntityModifier { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - // =========================================================== - // Constructors - // =========================================================== - - public LoopEntityModifier(final IEntityModifier pEntityModifier) { - super(pEntityModifier); - } - - public LoopEntityModifier(final IEntityModifier pEntityModifier, final int pLoopCount) { - super(pEntityModifier, pLoopCount); - } - - public LoopEntityModifier(final IEntityModifier pEntityModifier, final int pLoopCount, final ILoopEntityModifierListener pLoopModifierListener) { - super(pEntityModifier, pLoopCount, pLoopModifierListener); - } - - public LoopEntityModifier(final IEntityModifier pEntityModifier, final int pLoopCount, final IEntityModifierListener pEntityModifierListener) { - super(pEntityModifier, pLoopCount, pEntityModifierListener); - } - - public LoopEntityModifier(final IEntityModifierListener pEntityModifierListener, final int pLoopCount, final ILoopEntityModifierListener pLoopModifierListener, final IEntityModifier pEntityModifier) { - super(pEntityModifier, pLoopCount, pLoopModifierListener, pEntityModifierListener); - } - - protected LoopEntityModifier(final LoopEntityModifier pLoopEntityModifier) throws DeepCopyNotSupportedException { - super(pLoopEntityModifier); - } - - @Override - public LoopEntityModifier deepCopy() throws DeepCopyNotSupportedException { - return new LoopEntityModifier(this); - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== - - public interface ILoopEntityModifierListener extends ILoopModifierListener { - // =========================================================== - // Final Fields - // =========================================================== - - // =========================================================== - // Methods - // =========================================================== - } + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + // =========================================================== + // Constructors + // =========================================================== + + public LoopEntityModifier(final IEntityModifier pEntityModifier) { + super(pEntityModifier); + } + + public LoopEntityModifier(final IEntityModifier pEntityModifier, final int pLoopCount) { + super(pEntityModifier, pLoopCount); + } + + public LoopEntityModifier(final IEntityModifier pEntityModifier, final int pLoopCount, final ILoopEntityModifierListener pLoopModifierListener) { + super(pEntityModifier, pLoopCount, pLoopModifierListener); + } + + public LoopEntityModifier(final IEntityModifier pEntityModifier, final int pLoopCount, final IEntityModifierListener pEntityModifierListener) { + super(pEntityModifier, pLoopCount, pEntityModifierListener); + } + + public LoopEntityModifier(final IEntityModifierListener pEntityModifierListener, final int pLoopCount, final ILoopEntityModifierListener pLoopModifierListener, final IEntityModifier pEntityModifier) { + super(pEntityModifier, pLoopCount, pLoopModifierListener, pEntityModifierListener); + } + + protected LoopEntityModifier(final LoopEntityModifier pLoopEntityModifier) throws DeepCopyNotSupportedException { + super(pLoopEntityModifier); + } + + @Override + public LoopEntityModifier deepCopy() throws DeepCopyNotSupportedException { + return new LoopEntityModifier(this); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== + + public interface ILoopEntityModifierListener extends ILoopModifierListener { + // =========================================================== + // Final Fields + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + } } diff --git a/AndEngine/src/org/anddev/andengine/entity/modifier/MoveByModifier.java b/AndEngine/src/org/anddev/andengine/entity/modifier/MoveByModifier.java index 74999264..5c968bfc 100644 --- a/AndEngine/src/org/anddev/andengine/entity/modifier/MoveByModifier.java +++ b/AndEngine/src/org/anddev/andengine/entity/modifier/MoveByModifier.java @@ -9,53 +9,53 @@ * @since 14:15:52 - 10.08.2011 */ public class MoveByModifier extends DoubleValueChangeEntityModifier { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - // =========================================================== - // Constructors - // =========================================================== - - public MoveByModifier(final float pDuration, final float pX, final float pY) { - super(pDuration, pX, pY); - } - - public MoveByModifier(final float pDuration, final float pX, final float pY, final IEntityModifierListener pEntityModifierListener) { - super(pDuration, pX, pY, pEntityModifierListener); - } - - protected MoveByModifier(final DoubleValueChangeEntityModifier pDoubleValueChangeEntityModifier) { - super(pDoubleValueChangeEntityModifier); - } - - @Override - public MoveByModifier deepCopy(){ - return new MoveByModifier(this); - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - protected void onChangeValues(final float pSecondsElapsed, final IEntity pEntity, final float pX, final float pY) { - pEntity.setPosition(pEntity.getX() + pX, pEntity.getY() + pY); - } - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + // =========================================================== + // Constructors + // =========================================================== + + public MoveByModifier(final float pDuration, final float pX, final float pY) { + super(pDuration, pX, pY); + } + + public MoveByModifier(final float pDuration, final float pX, final float pY, final IEntityModifierListener pEntityModifierListener) { + super(pDuration, pX, pY, pEntityModifierListener); + } + + protected MoveByModifier(final DoubleValueChangeEntityModifier pDoubleValueChangeEntityModifier) { + super(pDoubleValueChangeEntityModifier); + } + + @Override + public MoveByModifier deepCopy(){ + return new MoveByModifier(this); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + protected void onChangeValues(final float pSecondsElapsed, final IEntity pEntity, final float pX, final float pY) { + pEntity.setPosition(pEntity.getX() + pX, pEntity.getY() + pY); + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/entity/modifier/MoveModifier.java b/AndEngine/src/org/anddev/andengine/entity/modifier/MoveModifier.java index 2446c502..eaadf506 100644 --- a/AndEngine/src/org/anddev/andengine/entity/modifier/MoveModifier.java +++ b/AndEngine/src/org/anddev/andengine/entity/modifier/MoveModifier.java @@ -11,66 +11,66 @@ * @since 16:12:52 - 19.03.2010 */ public class MoveModifier extends DoubleValueSpanEntityModifier { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - // =========================================================== - // 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, IEaseFunction.DEFAULT); - } - - 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 pToX, final float pFromY, final float pToY, final IEntityModifierListener pEntityModifierListener) { - super(pDuration, pFromX, pToX, pFromY, pToY, pEntityModifierListener, IEaseFunction.DEFAULT); - } - - public MoveModifier(final float pDuration, final float pFromX, final float pToX, final float pFromY, final float pToY, final IEntityModifierListener pEntityModifierListener, final IEaseFunction pEaseFunction) { - super(pDuration, pFromX, pToX, pFromY, pToY, pEntityModifierListener, pEaseFunction); - } - - protected MoveModifier(final MoveModifier pMoveModifier) { - super(pMoveModifier); - } - - @Override - public MoveModifier deepCopy(){ - return new MoveModifier(this); - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - protected void onSetInitialValues(final IEntity pEntity, final float pX, final float pY) { - pEntity.setPosition(pX, pY); - } - - @Override - protected void onSetValues(final IEntity pEntity, final float pPercentageDone, final float pX, final float pY) { - pEntity.setPosition(pX, pY); - } - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + // =========================================================== + // 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, IEaseFunction.DEFAULT); + } + + 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 pToX, final float pFromY, final float pToY, final IEntityModifierListener pEntityModifierListener) { + super(pDuration, pFromX, pToX, pFromY, pToY, pEntityModifierListener, IEaseFunction.DEFAULT); + } + + public MoveModifier(final float pDuration, final float pFromX, final float pToX, final float pFromY, final float pToY, final IEntityModifierListener pEntityModifierListener, final IEaseFunction pEaseFunction) { + super(pDuration, pFromX, pToX, pFromY, pToY, pEntityModifierListener, pEaseFunction); + } + + protected MoveModifier(final MoveModifier pMoveModifier) { + super(pMoveModifier); + } + + @Override + public MoveModifier deepCopy(){ + return new MoveModifier(this); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + protected void onSetInitialValues(final IEntity pEntity, final float pX, final float pY) { + pEntity.setPosition(pX, pY); + } + + @Override + protected void onSetValues(final IEntity pEntity, final float pPercentageDone, final float pX, final float pY) { + pEntity.setPosition(pX, pY); + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/entity/modifier/MoveXModifier.java b/AndEngine/src/org/anddev/andengine/entity/modifier/MoveXModifier.java index 1f3f660b..5a0ce1bd 100644 --- a/AndEngine/src/org/anddev/andengine/entity/modifier/MoveXModifier.java +++ b/AndEngine/src/org/anddev/andengine/entity/modifier/MoveXModifier.java @@ -11,66 +11,66 @@ * @since 12:03:22 - 30.08.2010 */ public class MoveXModifier extends SingleValueSpanEntityModifier { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - // =========================================================== - // Constructors - // =========================================================== - - public MoveXModifier(final float pDuration, final float pFromX, final float pToX) { - this(pDuration, pFromX, pToX, null, IEaseFunction.DEFAULT); - } - - public MoveXModifier(final float pDuration, final float pFromX, final float pToX, final IEaseFunction pEaseFunction) { - this(pDuration, pFromX, pToX, null, pEaseFunction); - } - - public MoveXModifier(final float pDuration, final float pFromX, final float pToX, final IEntityModifierListener pEntityModifierListener) { - super(pDuration, pFromX, pToX, pEntityModifierListener, IEaseFunction.DEFAULT); - } - - public MoveXModifier(final float pDuration, final float pFromX, final float pToX, final IEntityModifierListener pEntityModifierListener, final IEaseFunction pEaseFunction) { - super(pDuration, pFromX, pToX, pEntityModifierListener, pEaseFunction); - } - - protected MoveXModifier(final MoveXModifier pMoveXModifier) { - super(pMoveXModifier); - } - - @Override - public MoveXModifier deepCopy(){ - return new MoveXModifier(this); - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - protected void onSetInitialValue(final IEntity pEntity, final float pX) { - pEntity.setPosition(pX, pEntity.getY()); - } - - @Override - protected void onSetValue(final IEntity pEntity, final float pPercentageDone, final float pX) { - pEntity.setPosition(pX, pEntity.getY()); - } - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + // =========================================================== + // Constructors + // =========================================================== + + public MoveXModifier(final float pDuration, final float pFromX, final float pToX) { + this(pDuration, pFromX, pToX, null, IEaseFunction.DEFAULT); + } + + public MoveXModifier(final float pDuration, final float pFromX, final float pToX, final IEaseFunction pEaseFunction) { + this(pDuration, pFromX, pToX, null, pEaseFunction); + } + + public MoveXModifier(final float pDuration, final float pFromX, final float pToX, final IEntityModifierListener pEntityModifierListener) { + super(pDuration, pFromX, pToX, pEntityModifierListener, IEaseFunction.DEFAULT); + } + + public MoveXModifier(final float pDuration, final float pFromX, final float pToX, final IEntityModifierListener pEntityModifierListener, final IEaseFunction pEaseFunction) { + super(pDuration, pFromX, pToX, pEntityModifierListener, pEaseFunction); + } + + protected MoveXModifier(final MoveXModifier pMoveXModifier) { + super(pMoveXModifier); + } + + @Override + public MoveXModifier deepCopy(){ + return new MoveXModifier(this); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + protected void onSetInitialValue(final IEntity pEntity, final float pX) { + pEntity.setPosition(pX, pEntity.getY()); + } + + @Override + protected void onSetValue(final IEntity pEntity, final float pPercentageDone, final float pX) { + pEntity.setPosition(pX, pEntity.getY()); + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/entity/modifier/MoveYModifier.java b/AndEngine/src/org/anddev/andengine/entity/modifier/MoveYModifier.java index 1f0e562c..dcc60ade 100644 --- a/AndEngine/src/org/anddev/andengine/entity/modifier/MoveYModifier.java +++ b/AndEngine/src/org/anddev/andengine/entity/modifier/MoveYModifier.java @@ -11,66 +11,66 @@ * @since 12:04:21 - 30.08.2010 */ public class MoveYModifier extends SingleValueSpanEntityModifier { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - // =========================================================== - // Constructors - // =========================================================== - - public MoveYModifier(final float pDuration, final float pFromY, final float pToY) { - this(pDuration, pFromY, pToY, null, IEaseFunction.DEFAULT); - } - - public MoveYModifier(final float pDuration, final float pFromY, final float pToY, final IEaseFunction pEaseFunction) { - this(pDuration, pFromY, pToY, null, pEaseFunction); - } - - public MoveYModifier(final float pDuration, final float pFromY, final float pToY, final IEntityModifierListener pEntityModifierListener) { - super(pDuration, pFromY, pToY, pEntityModifierListener, IEaseFunction.DEFAULT); - } - - public MoveYModifier(final float pDuration, final float pFromY, final float pToY, final IEntityModifierListener pEntityModifierListener, final IEaseFunction pEaseFunction) { - super(pDuration, pFromY, pToY, pEntityModifierListener, pEaseFunction); - } - - protected MoveYModifier(final MoveYModifier pMoveYModifier) { - super(pMoveYModifier); - } - - @Override - public MoveYModifier deepCopy(){ - return new MoveYModifier(this); - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - protected void onSetInitialValue(final IEntity pEntity, final float pY) { - pEntity.setPosition(pEntity.getX(), pY); - } - - @Override - protected void onSetValue(final IEntity pEntity, final float pPercentageDone, final float pY) { - pEntity.setPosition(pEntity.getX(), pY); - } - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + // =========================================================== + // Constructors + // =========================================================== + + public MoveYModifier(final float pDuration, final float pFromY, final float pToY) { + this(pDuration, pFromY, pToY, null, IEaseFunction.DEFAULT); + } + + public MoveYModifier(final float pDuration, final float pFromY, final float pToY, final IEaseFunction pEaseFunction) { + this(pDuration, pFromY, pToY, null, pEaseFunction); + } + + public MoveYModifier(final float pDuration, final float pFromY, final float pToY, final IEntityModifierListener pEntityModifierListener) { + super(pDuration, pFromY, pToY, pEntityModifierListener, IEaseFunction.DEFAULT); + } + + public MoveYModifier(final float pDuration, final float pFromY, final float pToY, final IEntityModifierListener pEntityModifierListener, final IEaseFunction pEaseFunction) { + super(pDuration, pFromY, pToY, pEntityModifierListener, pEaseFunction); + } + + protected MoveYModifier(final MoveYModifier pMoveYModifier) { + super(pMoveYModifier); + } + + @Override + public MoveYModifier deepCopy(){ + return new MoveYModifier(this); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + protected void onSetInitialValue(final IEntity pEntity, final float pY) { + pEntity.setPosition(pEntity.getX(), pY); + } + + @Override + protected void onSetValue(final IEntity pEntity, final float pPercentageDone, final float pY) { + pEntity.setPosition(pEntity.getX(), pY); + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/entity/modifier/ParallelEntityModifier.java b/AndEngine/src/org/anddev/andengine/entity/modifier/ParallelEntityModifier.java index 36c62332..a0f2e316 100644 --- a/AndEngine/src/org/anddev/andengine/entity/modifier/ParallelEntityModifier.java +++ b/AndEngine/src/org/anddev/andengine/entity/modifier/ParallelEntityModifier.java @@ -11,48 +11,48 @@ * @since 12:40:31 - 03.09.2010 */ public class ParallelEntityModifier extends ParallelModifier implements IEntityModifier { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - // =========================================================== - // Constructors - // =========================================================== - - public ParallelEntityModifier(final IEntityModifier... pEntityModifiers) throws IllegalArgumentException { - super(pEntityModifiers); - } - - public ParallelEntityModifier(final IEntityModifierListener pEntityModifierListener, final IEntityModifier... pEntityModifiers) throws IllegalArgumentException { - super(pEntityModifierListener, pEntityModifiers); - } - - protected ParallelEntityModifier(final ParallelEntityModifier pParallelShapeModifier) throws DeepCopyNotSupportedException { - super(pParallelShapeModifier); - } - - @Override - public ParallelEntityModifier deepCopy() throws DeepCopyNotSupportedException { - return new ParallelEntityModifier(this); - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + // =========================================================== + // Constructors + // =========================================================== + + public ParallelEntityModifier(final IEntityModifier... pEntityModifiers) throws IllegalArgumentException { + super(pEntityModifiers); + } + + public ParallelEntityModifier(final IEntityModifierListener pEntityModifierListener, final IEntityModifier... pEntityModifiers) throws IllegalArgumentException { + super(pEntityModifierListener, pEntityModifiers); + } + + protected ParallelEntityModifier(final ParallelEntityModifier pParallelShapeModifier) throws DeepCopyNotSupportedException { + super(pParallelShapeModifier); + } + + @Override + public ParallelEntityModifier deepCopy() throws DeepCopyNotSupportedException { + return new ParallelEntityModifier(this); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/entity/modifier/PathModifier.java b/AndEngine/src/org/anddev/andengine/entity/modifier/PathModifier.java index 914174c3..159dddfb 100644 --- a/AndEngine/src/org/anddev/andengine/entity/modifier/PathModifier.java +++ b/AndEngine/src/org/anddev/andengine/entity/modifier/PathModifier.java @@ -14,315 +14,315 @@ * @since 16:50:02 - 16.06.2010 */ public class PathModifier extends EntityModifier { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - private final SequenceModifier mSequenceModifier; - - private IPathModifierListener mPathModifierListener; - - private final Path mPath; - - // =========================================================== - // Constructors - // =========================================================== - - public PathModifier(final float pDuration, final Path pPath) { - this(pDuration, pPath, null, null, IEaseFunction.DEFAULT); - } - - public PathModifier(final float pDuration, final Path pPath, final IEaseFunction pEaseFunction) { - this(pDuration, pPath, null, null, pEaseFunction); - } - - public PathModifier(final float pDuration, final Path pPath, final IEntityModifierListener pEntityModiferListener) { - this(pDuration, pPath, pEntityModiferListener, null, IEaseFunction.DEFAULT); - } - - public PathModifier(final float pDuration, final Path pPath, final IPathModifierListener pPathModifierListener) { - this(pDuration, pPath, null, pPathModifierListener, IEaseFunction.DEFAULT); - } - - public PathModifier(final float pDuration, final Path pPath, final IPathModifierListener pPathModifierListener, final IEaseFunction pEaseFunction) { - this(pDuration, pPath, null, pPathModifierListener, pEaseFunction); - } - - public PathModifier(final float pDuration, final Path pPath, final IEntityModifierListener pEntityModiferListener, final IEaseFunction pEaseFunction) { - this(pDuration, pPath, pEntityModiferListener, null, pEaseFunction); - } - - public PathModifier(final float pDuration, final Path pPath, final IEntityModifierListener pEntityModiferListener, final IPathModifierListener pPathModifierListener) throws IllegalArgumentException { - this(pDuration, pPath, pEntityModiferListener, pPathModifierListener, IEaseFunction.DEFAULT); - } - - public PathModifier(final float pDuration, final Path pPath, final IEntityModifierListener pEntityModiferListener, final IPathModifierListener pPathModifierListener, final IEaseFunction pEaseFunction) throws IllegalArgumentException { - super(pEntityModiferListener); - final int pathSize = pPath.getSize(); - - if (pathSize < 2) { - throw new IllegalArgumentException("Path needs at least 2 waypoints!"); - } - - this.mPath = pPath; - this.mPathModifierListener = pPathModifierListener; - - final MoveModifier[] moveModifiers = new MoveModifier[pathSize - 1]; - - final float[] coordinatesX = pPath.getCoordinatesX(); - final float[] coordinatesY = pPath.getCoordinatesY(); - - final float velocity = pPath.getLength() / pDuration; - - final int modifierCount = moveModifiers.length; - 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); - } - - /* Create a new SequenceModifier and register the listeners that - * call through to mEntityModifierListener and mPathModifierListener. */ - this.mSequenceModifier = new SequenceModifier( - new ISubSequenceModifierListener() { - @Override - public void onSubSequenceStarted(final IModifier pModifier, final IEntity pEntity, final int pIndex) { - 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) { - PathModifier.this.mPathModifierListener.onPathWaypointFinished(PathModifier.this, pEntity, pIndex); - } - } - }, - new IEntityModifierListener() { - @Override - public void onModifierStarted(final IModifier pModifier, final IEntity pEntity) { - PathModifier.this.onModifierStarted(pEntity); - if(PathModifier.this.mPathModifierListener != null) { - PathModifier.this.mPathModifierListener.onPathStarted(PathModifier.this, pEntity); - } - } - - @Override - public void onModifierFinished(final IModifier pEntityModifier, final IEntity pEntity) { - PathModifier.this.onModifierFinished(pEntity); - if(PathModifier.this.mPathModifierListener != null) { - PathModifier.this.mPathModifierListener.onPathFinished(PathModifier.this, pEntity); - } - } - }, - moveModifiers - ); - } - - protected PathModifier(final PathModifier pPathModifier) throws DeepCopyNotSupportedException { - this.mPath = pPathModifier.mPath.deepCopy(); - this.mSequenceModifier = pPathModifier.mSequenceModifier.deepCopy(); - } - - @Override - public PathModifier deepCopy() throws DeepCopyNotSupportedException { - return new PathModifier(this); - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - public Path getPath() { - return this.mPath; - } - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - public boolean isFinished() { - return this.mSequenceModifier.isFinished(); - } - - @Override - public float getSecondsElapsed() { - return this.mSequenceModifier.getSecondsElapsed(); - } - - @Override - public float getDuration() { - return this.mSequenceModifier.getDuration(); - } - - public IPathModifierListener getPathModifierListener() { - return this.mPathModifierListener; - } - - public void setPathModifierListener(final IPathModifierListener pPathModifierListener) { - this.mPathModifierListener = pPathModifierListener; - } - - @Override - public void reset() { - this.mSequenceModifier.reset(); - } - - @Override - public float onUpdate(final float pSecondsElapsed, final IEntity pEntity) { - return this.mSequenceModifier.onUpdate(pSecondsElapsed, pEntity); - } - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== - - public static interface IPathModifierListener { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - public void onPathStarted(final PathModifier pPathModifier, final IEntity pEntity); - public void onPathWaypointStarted(final PathModifier pPathModifier, final IEntity pEntity, final int pWaypointIndex); - public void onPathWaypointFinished(final PathModifier pPathModifier, final IEntity pEntity, final int pWaypointIndex); - public void onPathFinished(final PathModifier pPathModifier, final IEntity pEntity); - } - - public static class Path { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - private final float[] mCoordinatesX; - private final float[] mCoordinatesY; - - private int mIndex; - private boolean mLengthChanged = false; - private float mLength; - - // =========================================================== - // Constructors - // =========================================================== - - public Path(final int pLength) { - this.mCoordinatesX = new float[pLength]; - this.mCoordinatesY = new float[pLength]; - - this.mIndex = 0; - this.mLengthChanged = false; - } - - public Path(final float[] pCoordinatesX, final float[] pCoordinatesY) throws IllegalArgumentException { - if (pCoordinatesX.length != pCoordinatesY.length) { - throw new IllegalArgumentException("Coordinate-Arrays must have the same length."); - } - - this.mCoordinatesX = pCoordinatesX; - this.mCoordinatesY = pCoordinatesY; - - this.mIndex = pCoordinatesX.length; - this.mLengthChanged = true; - } - - public Path(final Path pPath) { - final int size = pPath.getSize(); - this.mCoordinatesX = new float[size]; - this.mCoordinatesY = new float[size]; - - System.arraycopy(pPath.mCoordinatesX, 0, this.mCoordinatesX, 0, size); - System.arraycopy(pPath.mCoordinatesY, 0, this.mCoordinatesY, 0, size); - - this.mIndex = pPath.mIndex; - this.mLengthChanged = pPath.mLengthChanged; - this.mLength = pPath.mLength; - } - - public Path deepCopy() { - return new Path(this); - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - public Path to(final float pX, final float pY) { - this.mCoordinatesX[this.mIndex] = pX; - this.mCoordinatesY[this.mIndex] = pY; - - this.mIndex++; + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + private final SequenceModifier mSequenceModifier; + + private IPathModifierListener mPathModifierListener; + + private final Path mPath; + + // =========================================================== + // Constructors + // =========================================================== + + public PathModifier(final float pDuration, final Path pPath) { + this(pDuration, pPath, null, null, IEaseFunction.DEFAULT); + } + + public PathModifier(final float pDuration, final Path pPath, final IEaseFunction pEaseFunction) { + this(pDuration, pPath, null, null, pEaseFunction); + } + + public PathModifier(final float pDuration, final Path pPath, final IEntityModifierListener pEntityModiferListener) { + this(pDuration, pPath, pEntityModiferListener, null, IEaseFunction.DEFAULT); + } + + public PathModifier(final float pDuration, final Path pPath, final IPathModifierListener pPathModifierListener) { + this(pDuration, pPath, null, pPathModifierListener, IEaseFunction.DEFAULT); + } + + public PathModifier(final float pDuration, final Path pPath, final IPathModifierListener pPathModifierListener, final IEaseFunction pEaseFunction) { + this(pDuration, pPath, null, pPathModifierListener, pEaseFunction); + } + + public PathModifier(final float pDuration, final Path pPath, final IEntityModifierListener pEntityModiferListener, final IEaseFunction pEaseFunction) { + this(pDuration, pPath, pEntityModiferListener, null, pEaseFunction); + } + + public PathModifier(final float pDuration, final Path pPath, final IEntityModifierListener pEntityModiferListener, final IPathModifierListener pPathModifierListener) throws IllegalArgumentException { + this(pDuration, pPath, pEntityModiferListener, pPathModifierListener, IEaseFunction.DEFAULT); + } + + public PathModifier(final float pDuration, final Path pPath, final IEntityModifierListener pEntityModiferListener, final IPathModifierListener pPathModifierListener, final IEaseFunction pEaseFunction) throws IllegalArgumentException { + super(pEntityModiferListener); + final int pathSize = pPath.getSize(); + + if (pathSize < 2) { + throw new IllegalArgumentException("Path needs at least 2 waypoints!"); + } + + this.mPath = pPath; + this.mPathModifierListener = pPathModifierListener; + + final MoveModifier[] moveModifiers = new MoveModifier[pathSize - 1]; + + final float[] coordinatesX = pPath.getCoordinatesX(); + final float[] coordinatesY = pPath.getCoordinatesY(); + + final float velocity = pPath.getLength() / pDuration; + + final int modifierCount = moveModifiers.length; + 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); + } + + /* Create a new SequenceModifier and register the listeners that + * call through to mEntityModifierListener and mPathModifierListener. */ + this.mSequenceModifier = new SequenceModifier( + new ISubSequenceModifierListener() { + @Override + public void onSubSequenceStarted(final IModifier pModifier, final IEntity pEntity, final int pIndex) { + 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) { + PathModifier.this.mPathModifierListener.onPathWaypointFinished(PathModifier.this, pEntity, pIndex); + } + } + }, + new IEntityModifierListener() { + @Override + public void onModifierStarted(final IModifier pModifier, final IEntity pEntity) { + PathModifier.this.onModifierStarted(pEntity); + if(PathModifier.this.mPathModifierListener != null) { + PathModifier.this.mPathModifierListener.onPathStarted(PathModifier.this, pEntity); + } + } + + @Override + public void onModifierFinished(final IModifier pEntityModifier, final IEntity pEntity) { + PathModifier.this.onModifierFinished(pEntity); + if(PathModifier.this.mPathModifierListener != null) { + PathModifier.this.mPathModifierListener.onPathFinished(PathModifier.this, pEntity); + } + } + }, + moveModifiers + ); + } + + protected PathModifier(final PathModifier pPathModifier) throws DeepCopyNotSupportedException { + this.mPath = pPathModifier.mPath.deepCopy(); + this.mSequenceModifier = pPathModifier.mSequenceModifier.deepCopy(); + } + + @Override + public PathModifier deepCopy() throws DeepCopyNotSupportedException { + return new PathModifier(this); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + public Path getPath() { + return this.mPath; + } + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + public boolean isFinished() { + return this.mSequenceModifier.isFinished(); + } + + @Override + public float getSecondsElapsed() { + return this.mSequenceModifier.getSecondsElapsed(); + } + + @Override + public float getDuration() { + return this.mSequenceModifier.getDuration(); + } + + public IPathModifierListener getPathModifierListener() { + return this.mPathModifierListener; + } + + public void setPathModifierListener(final IPathModifierListener pPathModifierListener) { + this.mPathModifierListener = pPathModifierListener; + } + + @Override + public void reset() { + this.mSequenceModifier.reset(); + } + + @Override + public float onUpdate(final float pSecondsElapsed, final IEntity pEntity) { + return this.mSequenceModifier.onUpdate(pSecondsElapsed, pEntity); + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== + + public static interface IPathModifierListener { + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + public void onPathStarted(final PathModifier pPathModifier, final IEntity pEntity); + public void onPathWaypointStarted(final PathModifier pPathModifier, final IEntity pEntity, final int pWaypointIndex); + public void onPathWaypointFinished(final PathModifier pPathModifier, final IEntity pEntity, final int pWaypointIndex); + public void onPathFinished(final PathModifier pPathModifier, final IEntity pEntity); + } + + public static class Path { + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + private final float[] mCoordinatesX; + private final float[] mCoordinatesY; + + private int mIndex; + private boolean mLengthChanged = false; + private float mLength; + + // =========================================================== + // Constructors + // =========================================================== + + public Path(final int pLength) { + this.mCoordinatesX = new float[pLength]; + this.mCoordinatesY = new float[pLength]; + + this.mIndex = 0; + this.mLengthChanged = false; + } + + public Path(final float[] pCoordinatesX, final float[] pCoordinatesY) throws IllegalArgumentException { + if (pCoordinatesX.length != pCoordinatesY.length) { + throw new IllegalArgumentException("Coordinate-Arrays must have the same length."); + } + + this.mCoordinatesX = pCoordinatesX; + this.mCoordinatesY = pCoordinatesY; + + this.mIndex = pCoordinatesX.length; + this.mLengthChanged = true; + } + + public Path(final Path pPath) { + final int size = pPath.getSize(); + this.mCoordinatesX = new float[size]; + this.mCoordinatesY = new float[size]; + + System.arraycopy(pPath.mCoordinatesX, 0, this.mCoordinatesX, 0, size); + System.arraycopy(pPath.mCoordinatesY, 0, this.mCoordinatesY, 0, size); + + this.mIndex = pPath.mIndex; + this.mLengthChanged = pPath.mLengthChanged; + this.mLength = pPath.mLength; + } + + public Path deepCopy() { + return new Path(this); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + public Path to(final float pX, final float pY) { + this.mCoordinatesX[this.mIndex] = pX; + this.mCoordinatesY[this.mIndex] = pY; + + this.mIndex++; - this.mLengthChanged = true; - - return this; - } + this.mLengthChanged = true; + + return this; + } - public float[] getCoordinatesX() { - return this.mCoordinatesX; - } + public float[] getCoordinatesX() { + return this.mCoordinatesX; + } - public float[] getCoordinatesY() { - return this.mCoordinatesY; - } + public float[] getCoordinatesY() { + return this.mCoordinatesY; + } - public int getSize() { - return this.mCoordinatesX.length; - } + public int getSize() { + return this.mCoordinatesX.length; + } - public float getLength() { - if(this.mLengthChanged) { - this.updateLength(); - } - return this.mLength; - } + public float getLength() { + if(this.mLengthChanged) { + this.updateLength(); + } + return this.mLength; + } - public float getSegmentLength(final int pSegmentIndex) { - final float[] coordinatesX = this.mCoordinatesX; - final float[] coordinatesY = this.mCoordinatesY; + public float getSegmentLength(final int pSegmentIndex) { + final float[] coordinatesX = this.mCoordinatesX; + final float[] coordinatesY = this.mCoordinatesY; - final int nextSegmentIndex = pSegmentIndex + 1; + final int nextSegmentIndex = pSegmentIndex + 1; - final float dx = coordinatesX[pSegmentIndex] - coordinatesX[nextSegmentIndex]; - final float dy = coordinatesY[pSegmentIndex] - coordinatesY[nextSegmentIndex]; + final float dx = coordinatesX[pSegmentIndex] - coordinatesX[nextSegmentIndex]; + final float dy = coordinatesY[pSegmentIndex] - coordinatesY[nextSegmentIndex]; - return (float) Math.sqrt(dx * dx + dy * dy); - } + return (float) Math.sqrt(dx * dx + dy * dy); + } - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - private void updateLength() { - float length = 0.0f; + private void updateLength() { + float length = 0.0f; - for(int i = this.mIndex - 2; i >= 0; i--) { - length += this.getSegmentLength(i); - } - this.mLength = length; - } + for(int i = this.mIndex - 2; i >= 0; i--) { + length += this.getSegmentLength(i); + } + this.mLength = length; + } - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== - } + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== + } } diff --git a/AndEngine/src/org/anddev/andengine/entity/modifier/QuadraticBezierMoveModifier.java b/AndEngine/src/org/anddev/andengine/entity/modifier/QuadraticBezierMoveModifier.java index dcbd4445..96cd5474 100644 --- a/AndEngine/src/org/anddev/andengine/entity/modifier/QuadraticBezierMoveModifier.java +++ b/AndEngine/src/org/anddev/andengine/entity/modifier/QuadraticBezierMoveModifier.java @@ -11,81 +11,81 @@ * @since 23:24:26 - 16.07.2011 */ public class QuadraticBezierMoveModifier extends DurationEntityModifier { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - private final float mX1; - private final float mY1; - private final float mX2; - private final float mY2; - private final float mX3; - private final float mY3; - - private final IEaseFunction mEaseFunction; - - // =========================================================== - // Constructors - // =========================================================== - - public QuadraticBezierMoveModifier(final float pDuration, final float pX1, final float pY1, final float pX2, final float pY2, final float pX3, final float pY3, final IEaseFunction pEaseFunction) { - super(pDuration); - - this.mX1 = pX1; - this.mY1 = pY1; - this.mX2 = pX2; - this.mY2 = pY2; - this.mX3 = pX3; - this.mY3 = pY3; - - this.mEaseFunction = pEaseFunction; - } - - @Override - public QuadraticBezierMoveModifier deepCopy() { - return new QuadraticBezierMoveModifier(this.mDuration, this.mX1, this.mY1, this.mX2, this.mY2, this.mX3, this.mY3, this.mEaseFunction); - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - protected void onManagedUpdate(final float pSecondsElapsed, final IEntity pEntity) { - 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 ut2 = 2 * u * percentageDone; - - /* Formula: - * ((1-t)^2 * p1) + (2*(t)*(1-t) * p2) + ((t^2) * p3) */ - final float x = (uu * this.mX1) + (ut2 * this.mX2) + (tt * this.mX3); - final float y = (uu * this.mY1) + (ut2 * this.mY2) + (tt * this.mY3); - - pEntity.setPosition(x, y); - } - - @Override - protected void onManagedInitialize(final IEntity pEntity) { - - } - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== -} \ No newline at end of file + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + private final float mX1; + private final float mY1; + private final float mX2; + private final float mY2; + private final float mX3; + private final float mY3; + + private final IEaseFunction mEaseFunction; + + // =========================================================== + // Constructors + // =========================================================== + + public QuadraticBezierMoveModifier(final float pDuration, final float pX1, final float pY1, final float pX2, final float pY2, final float pX3, final float pY3, final IEaseFunction pEaseFunction) { + super(pDuration); + + this.mX1 = pX1; + this.mY1 = pY1; + this.mX2 = pX2; + this.mY2 = pY2; + this.mX3 = pX3; + this.mY3 = pY3; + + this.mEaseFunction = pEaseFunction; + } + + @Override + public QuadraticBezierMoveModifier deepCopy() { + return new QuadraticBezierMoveModifier(this.mDuration, this.mX1, this.mY1, this.mX2, this.mY2, this.mX3, this.mY3, this.mEaseFunction); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + protected void onManagedUpdate(final float pSecondsElapsed, final IEntity pEntity) { + 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 ut2 = 2 * u * percentageDone; + + /* Formula: + * ((1-t)^2 * p1) + (2*(t)*(1-t) * p2) + ((t^2) * p3) */ + final float x = (uu * this.mX1) + (ut2 * this.mX2) + (tt * this.mX3); + final float y = (uu * this.mY1) + (ut2 * this.mY2) + (tt * this.mY3); + + pEntity.setPosition(x, y); + } + + @Override + protected void onManagedInitialize(final IEntity pEntity) { + + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== +} diff --git a/AndEngine/src/org/anddev/andengine/entity/modifier/RotationAtModifier.java b/AndEngine/src/org/anddev/andengine/entity/modifier/RotationAtModifier.java index 2055ba3e..54bb4079 100644 --- a/AndEngine/src/org/anddev/andengine/entity/modifier/RotationAtModifier.java +++ b/AndEngine/src/org/anddev/andengine/entity/modifier/RotationAtModifier.java @@ -12,75 +12,75 @@ * @since 21:59:38 - 06.07.2010 */ public class RotationAtModifier extends RotationModifier { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - private final float mRotationCenterX; - private final float mRotationCenterY; - - // =========================================================== - // Constructors - // =========================================================== - - public RotationAtModifier(final float pDuration, final float pFromRotation, final float pToRotation, final float pRotationCenterX, final float pRotationCenterY) { - super(pDuration, pFromRotation, pToRotation, IEaseFunction.DEFAULT); - this.mRotationCenterX = pRotationCenterX; - this.mRotationCenterY = pRotationCenterY; - } - - public RotationAtModifier(final float pDuration, final float pFromRotation, final float pToRotation, final float pRotationCenterX, final float pRotationCenterY, final IEaseFunction pEaseFunction) { - super(pDuration, pFromRotation, pToRotation, pEaseFunction); - this.mRotationCenterX = pRotationCenterX; - this.mRotationCenterY = pRotationCenterY; - } - - public RotationAtModifier(final float pDuration, final float pFromRotation, final float pToRotation, final float pRotationCenterX, final float pRotationCenterY, final IEntityModifierListener pEntityModifierListener) { - super(pDuration, pFromRotation, pToRotation, pEntityModifierListener, IEaseFunction.DEFAULT); - this.mRotationCenterX = pRotationCenterX; - this.mRotationCenterY = pRotationCenterY; - } - - public RotationAtModifier(final float pDuration, final float pFromRotation, final float pToRotation, final float pRotationCenterX, final float pRotationCenterY, final IEntityModifierListener pEntityModifierListener, final IEaseFunction pEaseFunction) { - super(pDuration, pFromRotation, pToRotation, pEntityModifierListener, pEaseFunction); - this.mRotationCenterX = pRotationCenterX; - this.mRotationCenterY = pRotationCenterY; - } - - protected RotationAtModifier(final RotationAtModifier pRotationAtModifier) { - super(pRotationAtModifier); - this.mRotationCenterX = pRotationAtModifier.mRotationCenterX; - this.mRotationCenterY = pRotationAtModifier.mRotationCenterY; - } - - @Override - public RotationAtModifier deepCopy(){ - return new RotationAtModifier(this); - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - protected void onManagedInitialize(final IEntity pEntity) { - super.onManagedInitialize(pEntity); - pEntity.setRotationCenter(this.mRotationCenterX, this.mRotationCenterY); - } - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + private final float mRotationCenterX; + private final float mRotationCenterY; + + // =========================================================== + // Constructors + // =========================================================== + + public RotationAtModifier(final float pDuration, final float pFromRotation, final float pToRotation, final float pRotationCenterX, final float pRotationCenterY) { + super(pDuration, pFromRotation, pToRotation, IEaseFunction.DEFAULT); + this.mRotationCenterX = pRotationCenterX; + this.mRotationCenterY = pRotationCenterY; + } + + public RotationAtModifier(final float pDuration, final float pFromRotation, final float pToRotation, final float pRotationCenterX, final float pRotationCenterY, final IEaseFunction pEaseFunction) { + super(pDuration, pFromRotation, pToRotation, pEaseFunction); + this.mRotationCenterX = pRotationCenterX; + this.mRotationCenterY = pRotationCenterY; + } + + public RotationAtModifier(final float pDuration, final float pFromRotation, final float pToRotation, final float pRotationCenterX, final float pRotationCenterY, final IEntityModifierListener pEntityModifierListener) { + super(pDuration, pFromRotation, pToRotation, pEntityModifierListener, IEaseFunction.DEFAULT); + this.mRotationCenterX = pRotationCenterX; + this.mRotationCenterY = pRotationCenterY; + } + + public RotationAtModifier(final float pDuration, final float pFromRotation, final float pToRotation, final float pRotationCenterX, final float pRotationCenterY, final IEntityModifierListener pEntityModifierListener, final IEaseFunction pEaseFunction) { + super(pDuration, pFromRotation, pToRotation, pEntityModifierListener, pEaseFunction); + this.mRotationCenterX = pRotationCenterX; + this.mRotationCenterY = pRotationCenterY; + } + + protected RotationAtModifier(final RotationAtModifier pRotationAtModifier) { + super(pRotationAtModifier); + this.mRotationCenterX = pRotationAtModifier.mRotationCenterX; + this.mRotationCenterY = pRotationAtModifier.mRotationCenterY; + } + + @Override + public RotationAtModifier deepCopy(){ + return new RotationAtModifier(this); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + protected void onManagedInitialize(final IEntity pEntity) { + super.onManagedInitialize(pEntity); + pEntity.setRotationCenter(this.mRotationCenterX, this.mRotationCenterY); + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/entity/modifier/RotationByModifier.java b/AndEngine/src/org/anddev/andengine/entity/modifier/RotationByModifier.java index 67373c20..0395c354 100644 --- a/AndEngine/src/org/anddev/andengine/entity/modifier/RotationByModifier.java +++ b/AndEngine/src/org/anddev/andengine/entity/modifier/RotationByModifier.java @@ -10,53 +10,53 @@ * @since 16:12:52 - 19.03.2010 */ public class RotationByModifier extends SingleValueChangeEntityModifier { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - // =========================================================== - // Constructors - // =========================================================== - - public RotationByModifier(final float pDuration, final float pRotation) { - super(pDuration, pRotation); - } - - public RotationByModifier(final float pDuration, final float pRotation, final IEntityModifierListener pEntityModifierListener) { - super(pDuration, pRotation, pEntityModifierListener); - } - - protected RotationByModifier(final RotationByModifier pRotationByModifier) { - super(pRotationByModifier); - } - - @Override - public RotationByModifier deepCopy(){ - return new RotationByModifier(this); - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - protected void onChangeValue(final float pSecondsElapsed, final IEntity pEntity, final float pRotation) { - pEntity.setRotation(pEntity.getRotation() + pRotation); - } - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + // =========================================================== + // Constructors + // =========================================================== + + public RotationByModifier(final float pDuration, final float pRotation) { + super(pDuration, pRotation); + } + + public RotationByModifier(final float pDuration, final float pRotation, final IEntityModifierListener pEntityModifierListener) { + super(pDuration, pRotation, pEntityModifierListener); + } + + protected RotationByModifier(final RotationByModifier pRotationByModifier) { + super(pRotationByModifier); + } + + @Override + public RotationByModifier deepCopy(){ + return new RotationByModifier(this); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + protected void onChangeValue(final float pSecondsElapsed, final IEntity pEntity, final float pRotation) { + pEntity.setRotation(pEntity.getRotation() + pRotation); + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/entity/modifier/RotationModifier.java b/AndEngine/src/org/anddev/andengine/entity/modifier/RotationModifier.java index d26cc7cf..77f5367f 100644 --- a/AndEngine/src/org/anddev/andengine/entity/modifier/RotationModifier.java +++ b/AndEngine/src/org/anddev/andengine/entity/modifier/RotationModifier.java @@ -11,66 +11,66 @@ * @since 16:12:52 - 19.03.2010 */ public class RotationModifier extends SingleValueSpanEntityModifier { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - // =========================================================== - // Constructors - // =========================================================== - - public RotationModifier(final float pDuration, final float pFromRotation, final float pToRotation) { - this(pDuration, pFromRotation, pToRotation, null, IEaseFunction.DEFAULT); - } - - public RotationModifier(final float pDuration, final float pFromRotation, final float pToRotation, final IEaseFunction pEaseFunction) { - this(pDuration, pFromRotation, pToRotation, null, pEaseFunction); - } - - public RotationModifier(final float pDuration, final float pFromRotation, final float pToRotation, final IEntityModifierListener pEntityModifierListener) { - super(pDuration, pFromRotation, pToRotation, pEntityModifierListener, IEaseFunction.DEFAULT); - } - - public RotationModifier(final float pDuration, final float pFromRotation, final float pToRotation, final IEntityModifierListener pEntityModifierListener, final IEaseFunction pEaseFunction) { - super(pDuration, pFromRotation, pToRotation, pEntityModifierListener, pEaseFunction); - } - - protected RotationModifier(final RotationModifier pRotationModifier) { - super(pRotationModifier); - } - - @Override - public RotationModifier deepCopy(){ - return new RotationModifier(this); - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - protected void onSetInitialValue(final IEntity pEntity, final float pRotation) { - pEntity.setRotation(pRotation); - } - - @Override - protected void onSetValue(final IEntity pEntity, final float pPercentageDone, final float pRotation) { - pEntity.setRotation(pRotation); - } - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + // =========================================================== + // Constructors + // =========================================================== + + public RotationModifier(final float pDuration, final float pFromRotation, final float pToRotation) { + this(pDuration, pFromRotation, pToRotation, null, IEaseFunction.DEFAULT); + } + + public RotationModifier(final float pDuration, final float pFromRotation, final float pToRotation, final IEaseFunction pEaseFunction) { + this(pDuration, pFromRotation, pToRotation, null, pEaseFunction); + } + + public RotationModifier(final float pDuration, final float pFromRotation, final float pToRotation, final IEntityModifierListener pEntityModifierListener) { + super(pDuration, pFromRotation, pToRotation, pEntityModifierListener, IEaseFunction.DEFAULT); + } + + public RotationModifier(final float pDuration, final float pFromRotation, final float pToRotation, final IEntityModifierListener pEntityModifierListener, final IEaseFunction pEaseFunction) { + super(pDuration, pFromRotation, pToRotation, pEntityModifierListener, pEaseFunction); + } + + protected RotationModifier(final RotationModifier pRotationModifier) { + super(pRotationModifier); + } + + @Override + public RotationModifier deepCopy(){ + return new RotationModifier(this); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + protected void onSetInitialValue(final IEntity pEntity, final float pRotation) { + pEntity.setRotation(pRotation); + } + + @Override + protected void onSetValue(final IEntity pEntity, final float pPercentageDone, final float pRotation) { + pEntity.setRotation(pRotation); + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/entity/modifier/ScaleAtModifier.java b/AndEngine/src/org/anddev/andengine/entity/modifier/ScaleAtModifier.java index facfafca..77d502a2 100644 --- a/AndEngine/src/org/anddev/andengine/entity/modifier/ScaleAtModifier.java +++ b/AndEngine/src/org/anddev/andengine/entity/modifier/ScaleAtModifier.java @@ -12,85 +12,85 @@ * @since 21:53:30 - 06.07.2010 */ public class ScaleAtModifier extends ScaleModifier { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - private final float mScaleCenterX; - private final float mScaleCenterY; - - // =========================================================== - // Constructors - // =========================================================== - - public ScaleAtModifier(final float pDuration, final float pFromScale, final float pToScale, final float pScaleCenterX, final float pScaleCenterY) { - this(pDuration, pFromScale, pToScale, pScaleCenterX, pScaleCenterY, IEaseFunction.DEFAULT); - } - - public ScaleAtModifier(final float pDuration, final float pFromScale, final float pToScale, final float pScaleCenterX, final float pScaleCenterY, final IEaseFunction pEaseFunction) { - this(pDuration, pFromScale, pToScale, pScaleCenterX, pScaleCenterY, null, pEaseFunction); - } - - public ScaleAtModifier(final float pDuration, final float pFromScale, final float pToScale, final float pScaleCenterX, final float pScaleCenterY, final IEntityModifierListener pEntityModifierListener) { - this(pDuration, pFromScale, pToScale, pScaleCenterX, pScaleCenterY, pEntityModifierListener, IEaseFunction.DEFAULT); - } - - public ScaleAtModifier(final float pDuration, final float pFromScale, final float pToScale, final float pScaleCenterX, final float pScaleCenterY, final IEntityModifierListener pEntityModifierListener, final IEaseFunction pEaseFunction) { - this(pDuration, pFromScale, pToScale, pFromScale, pToScale, pScaleCenterX, pScaleCenterY, pEntityModifierListener, pEaseFunction); - } - - public ScaleAtModifier(final float pDuration, final float pFromScaleX, final float pToScaleX, final float pFromScaleY, final float pToScaleY, final float pScaleCenterX, final float pScaleCenterY) { - this(pDuration, pFromScaleX, pToScaleX, pFromScaleY, pToScaleY, pScaleCenterX, pScaleCenterY, IEaseFunction.DEFAULT); - } - - public ScaleAtModifier(final float pDuration, final float pFromScaleX, final float pToScaleX, final float pFromScaleY, final float pToScaleY, final float pScaleCenterX, final float pScaleCenterY, final IEaseFunction pEaseFunction) { - this(pDuration, pFromScaleX, pToScaleX, pFromScaleY, pToScaleY, pScaleCenterX, pScaleCenterY, null, pEaseFunction); - } - - public ScaleAtModifier(final float pDuration, final float pFromScaleX, final float pToScaleX, final float pFromScaleY, final float pToScaleY, final float pScaleCenterX, final float pScaleCenterY, final IEntityModifierListener pEntityModifierListener) { - this(pDuration, pFromScaleX, pToScaleX, pFromScaleY, pToScaleY, pScaleCenterX, pScaleCenterY, pEntityModifierListener, IEaseFunction.DEFAULT); - } - - public ScaleAtModifier(final float pDuration, final float pFromScaleX, final float pToScaleX, final float pFromScaleY, final float pToScaleY, final float pScaleCenterX, final float pScaleCenterY, final IEntityModifierListener pEntityModifierListener, final IEaseFunction pEaseFunction) { - super(pDuration, pFromScaleX, pToScaleX, pFromScaleY, pToScaleY, pEntityModifierListener, pEaseFunction); - this.mScaleCenterX = pScaleCenterX; - this.mScaleCenterY = pScaleCenterY; - } - - protected ScaleAtModifier(final ScaleAtModifier pScaleAtModifier) { - super(pScaleAtModifier); - this.mScaleCenterX = pScaleAtModifier.mScaleCenterX; - this.mScaleCenterY = pScaleAtModifier.mScaleCenterY; - } - - @Override - public ScaleAtModifier deepCopy(){ - return new ScaleAtModifier(this); - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - protected void onManagedInitialize(final IEntity pEntity) { - super.onManagedInitialize(pEntity); - pEntity.setScaleCenter(this.mScaleCenterX, this.mScaleCenterY); - } - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + private final float mScaleCenterX; + private final float mScaleCenterY; + + // =========================================================== + // Constructors + // =========================================================== + + public ScaleAtModifier(final float pDuration, final float pFromScale, final float pToScale, final float pScaleCenterX, final float pScaleCenterY) { + this(pDuration, pFromScale, pToScale, pScaleCenterX, pScaleCenterY, IEaseFunction.DEFAULT); + } + + public ScaleAtModifier(final float pDuration, final float pFromScale, final float pToScale, final float pScaleCenterX, final float pScaleCenterY, final IEaseFunction pEaseFunction) { + this(pDuration, pFromScale, pToScale, pScaleCenterX, pScaleCenterY, null, pEaseFunction); + } + + public ScaleAtModifier(final float pDuration, final float pFromScale, final float pToScale, final float pScaleCenterX, final float pScaleCenterY, final IEntityModifierListener pEntityModifierListener) { + this(pDuration, pFromScale, pToScale, pScaleCenterX, pScaleCenterY, pEntityModifierListener, IEaseFunction.DEFAULT); + } + + public ScaleAtModifier(final float pDuration, final float pFromScale, final float pToScale, final float pScaleCenterX, final float pScaleCenterY, final IEntityModifierListener pEntityModifierListener, final IEaseFunction pEaseFunction) { + this(pDuration, pFromScale, pToScale, pFromScale, pToScale, pScaleCenterX, pScaleCenterY, pEntityModifierListener, pEaseFunction); + } + + public ScaleAtModifier(final float pDuration, final float pFromScaleX, final float pToScaleX, final float pFromScaleY, final float pToScaleY, final float pScaleCenterX, final float pScaleCenterY) { + this(pDuration, pFromScaleX, pToScaleX, pFromScaleY, pToScaleY, pScaleCenterX, pScaleCenterY, IEaseFunction.DEFAULT); + } + + public ScaleAtModifier(final float pDuration, final float pFromScaleX, final float pToScaleX, final float pFromScaleY, final float pToScaleY, final float pScaleCenterX, final float pScaleCenterY, final IEaseFunction pEaseFunction) { + this(pDuration, pFromScaleX, pToScaleX, pFromScaleY, pToScaleY, pScaleCenterX, pScaleCenterY, null, pEaseFunction); + } + + public ScaleAtModifier(final float pDuration, final float pFromScaleX, final float pToScaleX, final float pFromScaleY, final float pToScaleY, final float pScaleCenterX, final float pScaleCenterY, final IEntityModifierListener pEntityModifierListener) { + this(pDuration, pFromScaleX, pToScaleX, pFromScaleY, pToScaleY, pScaleCenterX, pScaleCenterY, pEntityModifierListener, IEaseFunction.DEFAULT); + } + + public ScaleAtModifier(final float pDuration, final float pFromScaleX, final float pToScaleX, final float pFromScaleY, final float pToScaleY, final float pScaleCenterX, final float pScaleCenterY, final IEntityModifierListener pEntityModifierListener, final IEaseFunction pEaseFunction) { + super(pDuration, pFromScaleX, pToScaleX, pFromScaleY, pToScaleY, pEntityModifierListener, pEaseFunction); + this.mScaleCenterX = pScaleCenterX; + this.mScaleCenterY = pScaleCenterY; + } + + protected ScaleAtModifier(final ScaleAtModifier pScaleAtModifier) { + super(pScaleAtModifier); + this.mScaleCenterX = pScaleAtModifier.mScaleCenterX; + this.mScaleCenterY = pScaleAtModifier.mScaleCenterY; + } + + @Override + public ScaleAtModifier deepCopy(){ + return new ScaleAtModifier(this); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + protected void onManagedInitialize(final IEntity pEntity) { + super.onManagedInitialize(pEntity); + pEntity.setScaleCenter(this.mScaleCenterX, this.mScaleCenterY); + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/entity/modifier/ScaleModifier.java b/AndEngine/src/org/anddev/andengine/entity/modifier/ScaleModifier.java index 8c32a55e..9557cfbd 100644 --- a/AndEngine/src/org/anddev/andengine/entity/modifier/ScaleModifier.java +++ b/AndEngine/src/org/anddev/andengine/entity/modifier/ScaleModifier.java @@ -11,82 +11,82 @@ * @since 23:37:53 - 19.03.2010 */ public class ScaleModifier extends DoubleValueSpanEntityModifier { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - // =========================================================== - // Constructors - // =========================================================== - - public ScaleModifier(final float pDuration, final float pFromScale, final float pToScale) { - this(pDuration, pFromScale, pToScale, null, IEaseFunction.DEFAULT); - } - - public ScaleModifier(final float pDuration, final float pFromScale, final float pToScale, final IEaseFunction pEaseFunction) { - this(pDuration, pFromScale, pToScale, null, pEaseFunction); - } - - public ScaleModifier(final float pDuration, final float pFromScale, final float pToScale, final IEntityModifierListener pEntityModifierListener) { - this(pDuration, pFromScale, pToScale, pFromScale, pToScale, pEntityModifierListener, IEaseFunction.DEFAULT); - } - - public ScaleModifier(final float pDuration, final float pFromScale, final float pToScale, final IEntityModifierListener pEntityModifierListener, final IEaseFunction pEaseFunction) { - this(pDuration, pFromScale, pToScale, pFromScale, pToScale, pEntityModifierListener, pEaseFunction); - } - - public ScaleModifier(final float pDuration, final float pFromScaleX, final float pToScaleX, final float pFromScaleY, final float pToScaleY) { - this(pDuration, pFromScaleX, pToScaleX, pFromScaleY, pToScaleY, null, IEaseFunction.DEFAULT); - } - - public ScaleModifier(final float pDuration, final float pFromScaleX, final float pToScaleX, final float pFromScaleY, final float pToScaleY, final IEaseFunction pEaseFunction) { - this(pDuration, pFromScaleX, pToScaleX, pFromScaleY, pToScaleY, null, pEaseFunction); - } - - public ScaleModifier(final float pDuration, final float pFromScaleX, final float pToScaleX, final float pFromScaleY, final float pToScaleY, final IEntityModifierListener pEntityModifierListener) { - super(pDuration, pFromScaleX, pToScaleX, pFromScaleY, pToScaleY, pEntityModifierListener, IEaseFunction.DEFAULT); - } - - public ScaleModifier(final float pDuration, final float pFromScaleX, final float pToScaleX, final float pFromScaleY, final float pToScaleY, final IEntityModifierListener pEntityModifierListener, final IEaseFunction pEaseFunction) { - super(pDuration, pFromScaleX, pToScaleX, pFromScaleY, pToScaleY, pEntityModifierListener, pEaseFunction); - } - - protected ScaleModifier(final ScaleModifier pScaleModifier) { - super(pScaleModifier); - } - - @Override - public ScaleModifier deepCopy(){ - return new ScaleModifier(this); - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - protected void onSetInitialValues(final IEntity pEntity, final float pScaleA, final float pScaleB) { - pEntity.setScale(pScaleA, pScaleB); - } - - @Override - protected void onSetValues(final IEntity pEntity, final float pPercentageDone, final float pScaleA, final float pScaleB) { - pEntity.setScale(pScaleA, pScaleB); - } - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + // =========================================================== + // Constructors + // =========================================================== + + public ScaleModifier(final float pDuration, final float pFromScale, final float pToScale) { + this(pDuration, pFromScale, pToScale, null, IEaseFunction.DEFAULT); + } + + public ScaleModifier(final float pDuration, final float pFromScale, final float pToScale, final IEaseFunction pEaseFunction) { + this(pDuration, pFromScale, pToScale, null, pEaseFunction); + } + + public ScaleModifier(final float pDuration, final float pFromScale, final float pToScale, final IEntityModifierListener pEntityModifierListener) { + this(pDuration, pFromScale, pToScale, pFromScale, pToScale, pEntityModifierListener, IEaseFunction.DEFAULT); + } + + public ScaleModifier(final float pDuration, final float pFromScale, final float pToScale, final IEntityModifierListener pEntityModifierListener, final IEaseFunction pEaseFunction) { + this(pDuration, pFromScale, pToScale, pFromScale, pToScale, pEntityModifierListener, pEaseFunction); + } + + public ScaleModifier(final float pDuration, final float pFromScaleX, final float pToScaleX, final float pFromScaleY, final float pToScaleY) { + this(pDuration, pFromScaleX, pToScaleX, pFromScaleY, pToScaleY, null, IEaseFunction.DEFAULT); + } + + public ScaleModifier(final float pDuration, final float pFromScaleX, final float pToScaleX, final float pFromScaleY, final float pToScaleY, final IEaseFunction pEaseFunction) { + this(pDuration, pFromScaleX, pToScaleX, pFromScaleY, pToScaleY, null, pEaseFunction); + } + + public ScaleModifier(final float pDuration, final float pFromScaleX, final float pToScaleX, final float pFromScaleY, final float pToScaleY, final IEntityModifierListener pEntityModifierListener) { + super(pDuration, pFromScaleX, pToScaleX, pFromScaleY, pToScaleY, pEntityModifierListener, IEaseFunction.DEFAULT); + } + + public ScaleModifier(final float pDuration, final float pFromScaleX, final float pToScaleX, final float pFromScaleY, final float pToScaleY, final IEntityModifierListener pEntityModifierListener, final IEaseFunction pEaseFunction) { + super(pDuration, pFromScaleX, pToScaleX, pFromScaleY, pToScaleY, pEntityModifierListener, pEaseFunction); + } + + protected ScaleModifier(final ScaleModifier pScaleModifier) { + super(pScaleModifier); + } + + @Override + public ScaleModifier deepCopy(){ + return new ScaleModifier(this); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + protected void onSetInitialValues(final IEntity pEntity, final float pScaleA, final float pScaleB) { + pEntity.setScale(pScaleA, pScaleB); + } + + @Override + protected void onSetValues(final IEntity pEntity, final float pPercentageDone, final float pScaleA, final float pScaleB) { + pEntity.setScale(pScaleA, pScaleB); + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/entity/modifier/SequenceEntityModifier.java b/AndEngine/src/org/anddev/andengine/entity/modifier/SequenceEntityModifier.java index 3bcce1e2..4812e544 100644 --- a/AndEngine/src/org/anddev/andengine/entity/modifier/SequenceEntityModifier.java +++ b/AndEngine/src/org/anddev/andengine/entity/modifier/SequenceEntityModifier.java @@ -11,66 +11,66 @@ * @since 12:41:15 - 03.09.2010 */ public class SequenceEntityModifier extends SequenceModifier implements IEntityModifier { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - // =========================================================== - // Constructors - // =========================================================== - - public SequenceEntityModifier(final IEntityModifier... pEntityModifiers) throws IllegalArgumentException { - super(pEntityModifiers); - } - - public SequenceEntityModifier(final ISubSequenceShapeModifierListener pSubSequenceShapeModifierListener, final IEntityModifier... pEntityModifiers) throws IllegalArgumentException { - super(pSubSequenceShapeModifierListener, pEntityModifiers); - } - - public SequenceEntityModifier(final IEntityModifierListener pEntityModifierListener, final IEntityModifier... pEntityModifiers) throws IllegalArgumentException { - super(pEntityModifierListener, pEntityModifiers); - } - - public SequenceEntityModifier(final ISubSequenceShapeModifierListener pSubSequenceShapeModifierListener, final IEntityModifierListener pEntityModifierListener, final IEntityModifier... pEntityModifiers) throws IllegalArgumentException { - super(pSubSequenceShapeModifierListener, pEntityModifierListener, pEntityModifiers); - } - - protected SequenceEntityModifier(final SequenceEntityModifier pSequenceShapeModifier) throws DeepCopyNotSupportedException { - super(pSequenceShapeModifier); - } - - @Override - public SequenceEntityModifier deepCopy() throws DeepCopyNotSupportedException { - return new SequenceEntityModifier(this); - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== - - public interface ISubSequenceShapeModifierListener extends ISubSequenceModifierListener { - // =========================================================== - // Final Fields - // =========================================================== - - // =========================================================== - // Methods - // =========================================================== - } + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + // =========================================================== + // Constructors + // =========================================================== + + public SequenceEntityModifier(final IEntityModifier... pEntityModifiers) throws IllegalArgumentException { + super(pEntityModifiers); + } + + public SequenceEntityModifier(final ISubSequenceShapeModifierListener pSubSequenceShapeModifierListener, final IEntityModifier... pEntityModifiers) throws IllegalArgumentException { + super(pSubSequenceShapeModifierListener, pEntityModifiers); + } + + public SequenceEntityModifier(final IEntityModifierListener pEntityModifierListener, final IEntityModifier... pEntityModifiers) throws IllegalArgumentException { + super(pEntityModifierListener, pEntityModifiers); + } + + public SequenceEntityModifier(final ISubSequenceShapeModifierListener pSubSequenceShapeModifierListener, final IEntityModifierListener pEntityModifierListener, final IEntityModifier... pEntityModifiers) throws IllegalArgumentException { + super(pSubSequenceShapeModifierListener, pEntityModifierListener, pEntityModifiers); + } + + protected SequenceEntityModifier(final SequenceEntityModifier pSequenceShapeModifier) throws DeepCopyNotSupportedException { + super(pSequenceShapeModifier); + } + + @Override + public SequenceEntityModifier deepCopy() throws DeepCopyNotSupportedException { + return new SequenceEntityModifier(this); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== + + public interface ISubSequenceShapeModifierListener extends ISubSequenceModifierListener { + // =========================================================== + // Final Fields + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + } } diff --git a/AndEngine/src/org/anddev/andengine/entity/modifier/SingleValueChangeEntityModifier.java b/AndEngine/src/org/anddev/andengine/entity/modifier/SingleValueChangeEntityModifier.java index 8349ccc1..01ee11b2 100644 --- a/AndEngine/src/org/anddev/andengine/entity/modifier/SingleValueChangeEntityModifier.java +++ b/AndEngine/src/org/anddev/andengine/entity/modifier/SingleValueChangeEntityModifier.java @@ -11,43 +11,43 @@ * @since 15:34:35 - 17.06.2010 */ public abstract class SingleValueChangeEntityModifier extends BaseSingleValueChangeModifier implements IEntityModifier { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - public SingleValueChangeEntityModifier(final float pDuration, final float pValueChange) { - super(pDuration, pValueChange); - } + public SingleValueChangeEntityModifier(final float pDuration, final float pValueChange) { + super(pDuration, pValueChange); + } - public SingleValueChangeEntityModifier(final float pDuration, final float pValueChange, final IEntityModifierListener pEntityModifierListener) { - super(pDuration, pValueChange, pEntityModifierListener); - } + public SingleValueChangeEntityModifier(final float pDuration, final float pValueChange, final IEntityModifierListener pEntityModifierListener) { + super(pDuration, pValueChange, pEntityModifierListener); + } - protected SingleValueChangeEntityModifier(final SingleValueChangeEntityModifier pSingleValueChangeEntityModifier) { - super(pSingleValueChangeEntityModifier); - } + protected SingleValueChangeEntityModifier(final SingleValueChangeEntityModifier pSingleValueChangeEntityModifier) { + super(pSingleValueChangeEntityModifier); + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/entity/modifier/SingleValueSpanEntityModifier.java b/AndEngine/src/org/anddev/andengine/entity/modifier/SingleValueSpanEntityModifier.java index f5fcd584..1bc7091f 100644 --- a/AndEngine/src/org/anddev/andengine/entity/modifier/SingleValueSpanEntityModifier.java +++ b/AndEngine/src/org/anddev/andengine/entity/modifier/SingleValueSpanEntityModifier.java @@ -12,51 +12,51 @@ * @since 23:29:22 - 19.03.2010 */ public abstract class SingleValueSpanEntityModifier extends BaseSingleValueSpanModifier implements IEntityModifier { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - public SingleValueSpanEntityModifier(final float pDuration, final float pFromValue, final float pToValue) { - super(pDuration, pFromValue, pToValue); - } + public SingleValueSpanEntityModifier(final float pDuration, final float pFromValue, final float pToValue) { + super(pDuration, pFromValue, pToValue); + } - public SingleValueSpanEntityModifier(final float pDuration, final float pFromValue, final float pToValue, final IEaseFunction pEaseFunction) { - super(pDuration, pFromValue, pToValue, pEaseFunction); - } + public SingleValueSpanEntityModifier(final float pDuration, final float pFromValue, final float pToValue, final IEaseFunction pEaseFunction) { + super(pDuration, pFromValue, pToValue, pEaseFunction); + } - public SingleValueSpanEntityModifier(final float pDuration, final float pFromValue, final float pToValue, final IEntityModifierListener pEntityModifierListener) { - super(pDuration, pFromValue, pToValue, pEntityModifierListener); - } + public SingleValueSpanEntityModifier(final float pDuration, final float pFromValue, final float pToValue, final IEntityModifierListener pEntityModifierListener) { + super(pDuration, pFromValue, pToValue, pEntityModifierListener); + } - public SingleValueSpanEntityModifier(final float pDuration, final float pFromValue, final float pToValue, final IEntityModifierListener pEntityModifierListener, final IEaseFunction pEaseFunction) { - super(pDuration, pFromValue, pToValue, pEntityModifierListener, pEaseFunction); - } + public SingleValueSpanEntityModifier(final float pDuration, final float pFromValue, final float pToValue, final IEntityModifierListener pEntityModifierListener, final IEaseFunction pEaseFunction) { + super(pDuration, pFromValue, pToValue, pEntityModifierListener, pEaseFunction); + } - protected SingleValueSpanEntityModifier(final SingleValueSpanEntityModifier pSingleValueSpanEntityModifier) { - super(pSingleValueSpanEntityModifier); - } + protected SingleValueSpanEntityModifier(final SingleValueSpanEntityModifier pSingleValueSpanEntityModifier) { + super(pSingleValueSpanEntityModifier); + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/entity/modifier/TripleValueSpanEntityModifier.java b/AndEngine/src/org/anddev/andengine/entity/modifier/TripleValueSpanEntityModifier.java index 7f64bd42..667e8e4c 100644 --- a/AndEngine/src/org/anddev/andengine/entity/modifier/TripleValueSpanEntityModifier.java +++ b/AndEngine/src/org/anddev/andengine/entity/modifier/TripleValueSpanEntityModifier.java @@ -12,43 +12,43 @@ * @since 15:35:18 - 29.06.2010 */ public abstract class TripleValueSpanEntityModifier extends BaseTripleValueSpanModifier implements IEntityModifier { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - public TripleValueSpanEntityModifier(final float pDuration, final float pFromValueA, final float pToValueA, final float pFromValueB, final float pToValueB, final float pFromValueC, final float pToValueC, final IEaseFunction pEaseFunction) { - super(pDuration, pFromValueA, pToValueA, pFromValueB, pToValueB, pFromValueC, pToValueC, pEaseFunction); - } + public TripleValueSpanEntityModifier(final float pDuration, final float pFromValueA, final float pToValueA, final float pFromValueB, final float pToValueB, final float pFromValueC, final float pToValueC, final IEaseFunction pEaseFunction) { + super(pDuration, pFromValueA, pToValueA, pFromValueB, pToValueB, pFromValueC, pToValueC, pEaseFunction); + } - public TripleValueSpanEntityModifier(final float pDuration, final float pFromValueA, final float pToValueA, final float pFromValueB, final float pToValueB, final float pFromValueC, final float pToValueC, final IEntityModifierListener pEntityModifierListener, final IEaseFunction pEaseFunction) { - super(pDuration, pFromValueA, pToValueA, pFromValueB, pToValueB, pFromValueC, pToValueC, pEntityModifierListener, pEaseFunction); - } + public TripleValueSpanEntityModifier(final float pDuration, final float pFromValueA, final float pToValueA, final float pFromValueB, final float pToValueB, final float pFromValueC, final float pToValueC, final IEntityModifierListener pEntityModifierListener, final IEaseFunction pEaseFunction) { + super(pDuration, pFromValueA, pToValueA, pFromValueB, pToValueB, pFromValueC, pToValueC, pEntityModifierListener, pEaseFunction); + } - protected TripleValueSpanEntityModifier(final TripleValueSpanEntityModifier pTripleValueSpanEntityModifier) { - super(pTripleValueSpanEntityModifier); - } + protected TripleValueSpanEntityModifier(final TripleValueSpanEntityModifier pTripleValueSpanEntityModifier) { + super(pTripleValueSpanEntityModifier); + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/entity/particle/Particle.java b/AndEngine/src/org/anddev/andengine/entity/particle/Particle.java index 2bf43648..79127f87 100644 --- a/AndEngine/src/org/anddev/andengine/entity/particle/Particle.java +++ b/AndEngine/src/org/anddev/andengine/entity/particle/Particle.java @@ -13,92 +13,92 @@ * @since 19:37:13 - 14.03.2010 */ public class Particle extends Sprite { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - private float mLifeTime; - private float mDeathTime = -1; - boolean mDead = false; - private final PhysicsHandler mPhysicsHandler = new PhysicsHandler(this); - - // =========================================================== - // Constructors - // ===========================================================; - - public Particle(final float pX, final float pY, final TextureRegion pTextureRegion) { - super(pX, pY, pTextureRegion); - this.mLifeTime = 0; - } - - public Particle(final float pX, final float pY, final TextureRegion pTextureRegion, final RectangleVertexBuffer pRectangleVertexBuffer) { - super(pX, pY, pTextureRegion, pRectangleVertexBuffer); - this.mLifeTime = 0; - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - public float getLifeTime() { - return this.mLifeTime; - } - - public float getDeathTime() { - return this.mDeathTime; - } - - public void setDeathTime(final float pDeathTime) { - this.mDeathTime = pDeathTime; - } - - public boolean isDead() { - return this.mDead ; - } - - public void setDead(final boolean pDead) { - this.mDead = pDead; - } - - public PhysicsHandler getPhysicsHandler() { - return this.mPhysicsHandler; - } - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - protected void onManagedUpdate(final float pSecondsElapsed) { - if(!this.mDead){ - this.mLifeTime += pSecondsElapsed; - this.mPhysicsHandler.onUpdate(pSecondsElapsed); - super.onManagedUpdate(pSecondsElapsed); - final float deathTime = this.mDeathTime; - if(deathTime != -1 && this.mLifeTime > deathTime) { - this.setDead(true); - } - } - } - - // =========================================================== - // Methods - // =========================================================== - - @Override - public void reset() { - super.reset(); - this.mPhysicsHandler.reset(); - this.mDead = false; - this.mDeathTime = -1; - this.mLifeTime = 0; - } - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + private float mLifeTime; + private float mDeathTime = -1; + boolean mDead = false; + private final PhysicsHandler mPhysicsHandler = new PhysicsHandler(this); + + // =========================================================== + // Constructors + // ===========================================================; + + public Particle(final float pX, final float pY, final TextureRegion pTextureRegion) { + super(pX, pY, pTextureRegion); + this.mLifeTime = 0; + } + + public Particle(final float pX, final float pY, final TextureRegion pTextureRegion, final RectangleVertexBuffer pRectangleVertexBuffer) { + super(pX, pY, pTextureRegion, pRectangleVertexBuffer); + this.mLifeTime = 0; + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + public float getLifeTime() { + return this.mLifeTime; + } + + public float getDeathTime() { + return this.mDeathTime; + } + + public void setDeathTime(final float pDeathTime) { + this.mDeathTime = pDeathTime; + } + + public boolean isDead() { + return this.mDead ; + } + + public void setDead(final boolean pDead) { + this.mDead = pDead; + } + + public PhysicsHandler getPhysicsHandler() { + return this.mPhysicsHandler; + } + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + protected void onManagedUpdate(final float pSecondsElapsed) { + if(!this.mDead){ + this.mLifeTime += pSecondsElapsed; + this.mPhysicsHandler.onUpdate(pSecondsElapsed); + super.onManagedUpdate(pSecondsElapsed); + final float deathTime = this.mDeathTime; + if(deathTime != -1 && this.mLifeTime > deathTime) { + this.setDead(true); + } + } + } + + // =========================================================== + // Methods + // =========================================================== + + @Override + public void reset() { + super.reset(); + this.mPhysicsHandler.reset(); + this.mDead = false; + this.mDeathTime = -1; + this.mLifeTime = 0; + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/entity/particle/ParticleSystem.java b/AndEngine/src/org/anddev/andengine/entity/particle/ParticleSystem.java index c7379f3e..e4db0eb6 100644 --- a/AndEngine/src/org/anddev/andengine/entity/particle/ParticleSystem.java +++ b/AndEngine/src/org/anddev/andengine/entity/particle/ParticleSystem.java @@ -27,235 +27,235 @@ * @since 19:42:27 - 14.03.2010 */ public class ParticleSystem extends Entity { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - private static final int BLENDFUNCTION_SOURCE_DEFAULT = GL10.GL_ONE; - private static final int BLENDFUNCTION_DESTINATION_DEFAULT = GL10.GL_ONE_MINUS_SRC_ALPHA; + private static final int BLENDFUNCTION_SOURCE_DEFAULT = GL10.GL_ONE; + private static final int BLENDFUNCTION_DESTINATION_DEFAULT = GL10.GL_ONE_MINUS_SRC_ALPHA; - private final float[] POSITION_OFFSET = new float[2]; + private final float[] POSITION_OFFSET = new float[2]; - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - private final IParticleEmitter mParticleEmitter; + private final IParticleEmitter mParticleEmitter; - private final Particle[] mParticles; + private final Particle[] mParticles; - private int mSourceBlendFunction = BLENDFUNCTION_SOURCE_DEFAULT; - private int mDestinationBlendFunction = BLENDFUNCTION_DESTINATION_DEFAULT; + private int mSourceBlendFunction = BLENDFUNCTION_SOURCE_DEFAULT; + private int mDestinationBlendFunction = BLENDFUNCTION_DESTINATION_DEFAULT; - private final ArrayList mParticleInitializers = new ArrayList(); - private final ArrayList mParticleModifiers = new ArrayList(); + private final ArrayList mParticleInitializers = new ArrayList(); + private final ArrayList mParticleModifiers = new ArrayList(); - private final float mRateMinimum; - private final float mRateMaximum; + private final float mRateMinimum; + private final float mRateMaximum; - private final TextureRegion mTextureRegion; + private final TextureRegion mTextureRegion; - private boolean mParticlesSpawnEnabled = true; + private boolean mParticlesSpawnEnabled = true; - private final int mParticlesMaximum; - private int mParticlesAlive; - private float mParticlesDueToSpawn; + private final int mParticlesMaximum; + private int mParticlesAlive; + private float mParticlesDueToSpawn; - private int mParticleModifierCount; - private int mParticleInitializerCount; + private int mParticleModifierCount; + private int mParticleInitializerCount; - private RectangleVertexBuffer mSharedParticleVertexBuffer; + private RectangleVertexBuffer mSharedParticleVertexBuffer; - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - /** - * Creates a ParticleSystem with a {@link RectangleParticleEmitter}. - * @deprecated Instead use {@link ParticleSystem#ParticleSystem(IParticleEmitter, float, float, int, TextureRegion)}. - */ - @Deprecated - public ParticleSystem(final float pX, final float pY, final float pWidth, final float pHeight, final float pRateMinimum, final float pRateMaximum, final int pParticlesMaximum, final TextureRegion pTextureRegion) { - this(new RectangleParticleEmitter(pX + pWidth * 0.5f, pY + pHeight * 0.5f, pWidth, pHeight), pRateMinimum, pRateMaximum, pParticlesMaximum, pTextureRegion); - } - - public ParticleSystem(final IParticleEmitter pParticleEmitter, final float pRateMinimum, final float pRateMaximum, final int pParticlesMaximum, final TextureRegion pTextureRegion) { - super(0, 0); - - this.mParticleEmitter = pParticleEmitter; - this.mParticles = new Particle[pParticlesMaximum]; - this.mRateMinimum = pRateMinimum; - this.mRateMaximum = pRateMaximum; - this.mParticlesMaximum = pParticlesMaximum; - this.mTextureRegion = pTextureRegion; - - this.registerUpdateHandler(this.mParticleEmitter); - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - public boolean isParticlesSpawnEnabled() { - return this.mParticlesSpawnEnabled; - } - - public void setParticlesSpawnEnabled(final boolean pParticlesSpawnEnabled) { - this.mParticlesSpawnEnabled = pParticlesSpawnEnabled; - } - - public void setBlendFunction(final int pSourceBlendFunction, final int pDestinationBlendFunction) { - this.mSourceBlendFunction = pSourceBlendFunction; - this.mDestinationBlendFunction = pDestinationBlendFunction; - } + /** + * Creates a ParticleSystem with a {@link RectangleParticleEmitter}. + * @deprecated Instead use {@link ParticleSystem#ParticleSystem(IParticleEmitter, float, float, int, TextureRegion)}. + */ + @Deprecated + public ParticleSystem(final float pX, final float pY, final float pWidth, final float pHeight, final float pRateMinimum, final float pRateMaximum, final int pParticlesMaximum, final TextureRegion pTextureRegion) { + this(new RectangleParticleEmitter(pX + pWidth * 0.5f, pY + pHeight * 0.5f, pWidth, pHeight), pRateMinimum, pRateMaximum, pParticlesMaximum, pTextureRegion); + } + + public ParticleSystem(final IParticleEmitter pParticleEmitter, final float pRateMinimum, final float pRateMaximum, final int pParticlesMaximum, final TextureRegion pTextureRegion) { + super(0, 0); + + this.mParticleEmitter = pParticleEmitter; + this.mParticles = new Particle[pParticlesMaximum]; + this.mRateMinimum = pRateMinimum; + this.mRateMaximum = pRateMaximum; + this.mParticlesMaximum = pParticlesMaximum; + this.mTextureRegion = pTextureRegion; + + this.registerUpdateHandler(this.mParticleEmitter); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + public boolean isParticlesSpawnEnabled() { + return this.mParticlesSpawnEnabled; + } + + public void setParticlesSpawnEnabled(final boolean pParticlesSpawnEnabled) { + this.mParticlesSpawnEnabled = pParticlesSpawnEnabled; + } + + public void setBlendFunction(final int pSourceBlendFunction, final int pDestinationBlendFunction) { + this.mSourceBlendFunction = pSourceBlendFunction; + this.mDestinationBlendFunction = pDestinationBlendFunction; + } - public IParticleEmitter getParticleEmitter() { - return this.mParticleEmitter; - } + public IParticleEmitter getParticleEmitter() { + return this.mParticleEmitter; + } - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - @Override - public void reset() { - super.reset(); - - this.mParticlesDueToSpawn = 0; - this.mParticlesAlive = 0; - } - - @Override - protected void onManagedDraw(final GL10 pGL, final Camera pCamera) { - final Particle[] particles = this.mParticles; - for(int i = this.mParticlesAlive - 1; i >= 0; i--) { - particles[i].onDraw(pGL, pCamera); - } - } - - @Override - protected void onManagedUpdate(final float pSecondsElapsed) { - super.onManagedUpdate(pSecondsElapsed); - - if(this.mParticlesSpawnEnabled) { - 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]; - - /* Apply all particleModifiers */ - for(int j = particleModifierCountMinusOne; j >= 0; j--) { - particleModifiers.get(j).onUpdateParticle(particle); - } - - particle.onUpdate(pSecondsElapsed); - if(particle.mDead){ - this.mParticlesAlive--; - final int particlesAlive = this.mParticlesAlive; - particles[i] = particles[particlesAlive]; - particles[particlesAlive] = 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); - } - - private void spawnParticles(final float pSecondsElapsed) { - final float currentRate = this.determineCurrentRate(); - final float newParticlesThisFrame = currentRate * pSecondsElapsed; - - this.mParticlesDueToSpawn += newParticlesThisFrame; - - final int particlesToSpawnThisFrame = Math.min(this.mParticlesMaximum - this.mParticlesAlive, (int) Math.floor(this.mParticlesDueToSpawn)); - this.mParticlesDueToSpawn -= particlesToSpawnThisFrame; - - 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]; - - /* New particle needs to be created. */ - this.mParticleEmitter.getPositionOffset(this.POSITION_OFFSET); - - final float x = this.POSITION_OFFSET[VERTEX_INDEX_X]; - final float y = this.POSITION_OFFSET[VERTEX_INDEX_Y]; - - if(particle != null) { - particle.reset(); - particle.setPosition(x, y); - } else { - if(particlesAlive == 0) { - /* This is the very first particle. */ - particle = new Particle(x, y, this.mTextureRegion); - this.mSharedParticleVertexBuffer = particle.getVertexBuffer(); - } else { - particle = new Particle(x, y, this.mTextureRegion, this.mSharedParticleVertexBuffer); - } - particles[particlesAlive] = particle; - } - particle.setBlendFunction(this.mSourceBlendFunction, this.mDestinationBlendFunction); - - /* Apply particle initializers. */ - { - final ArrayList particleInitializers = this.mParticleInitializers; - for(int i = this.mParticleInitializerCount - 1; i >= 0; i--) { - particleInitializers.get(i).onInitializeParticle(particle); - } - - final ArrayList particleModifiers = this.mParticleModifiers; - for(int i = this.mParticleModifierCount - 1; i >= 0; i--) { - particleModifiers.get(i).onInitializeParticle(particle); - } - } - - this.mParticlesAlive++; - } - } - - private float determineCurrentRate() { - if(this.mRateMinimum == this.mRateMaximum){ - return this.mRateMinimum; - } else { - return (RANDOM.nextFloat() * (this.mRateMaximum - this.mRateMinimum)) + this.mRateMinimum; - } - } - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + @Override + public void reset() { + super.reset(); + + this.mParticlesDueToSpawn = 0; + this.mParticlesAlive = 0; + } + + @Override + protected void onManagedDraw(final GL10 pGL, final Camera pCamera) { + final Particle[] particles = this.mParticles; + for(int i = this.mParticlesAlive - 1; i >= 0; i--) { + particles[i].onDraw(pGL, pCamera); + } + } + + @Override + protected void onManagedUpdate(final float pSecondsElapsed) { + super.onManagedUpdate(pSecondsElapsed); + + if(this.mParticlesSpawnEnabled) { + 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]; + + /* Apply all particleModifiers */ + for(int j = particleModifierCountMinusOne; j >= 0; j--) { + particleModifiers.get(j).onUpdateParticle(particle); + } + + particle.onUpdate(pSecondsElapsed); + if(particle.mDead){ + this.mParticlesAlive--; + final int particlesAlive = this.mParticlesAlive; + particles[i] = particles[particlesAlive]; + particles[particlesAlive] = 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); + } + + private void spawnParticles(final float pSecondsElapsed) { + final float currentRate = this.determineCurrentRate(); + final float newParticlesThisFrame = currentRate * pSecondsElapsed; + + this.mParticlesDueToSpawn += newParticlesThisFrame; + + final int particlesToSpawnThisFrame = Math.min(this.mParticlesMaximum - this.mParticlesAlive, (int) Math.floor(this.mParticlesDueToSpawn)); + this.mParticlesDueToSpawn -= particlesToSpawnThisFrame; + + 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]; + + /* New particle needs to be created. */ + this.mParticleEmitter.getPositionOffset(this.POSITION_OFFSET); + + final float x = this.POSITION_OFFSET[VERTEX_INDEX_X]; + final float y = this.POSITION_OFFSET[VERTEX_INDEX_Y]; + + if(particle != null) { + particle.reset(); + particle.setPosition(x, y); + } else { + if(particlesAlive == 0) { + /* This is the very first particle. */ + particle = new Particle(x, y, this.mTextureRegion); + this.mSharedParticleVertexBuffer = particle.getVertexBuffer(); + } else { + particle = new Particle(x, y, this.mTextureRegion, this.mSharedParticleVertexBuffer); + } + particles[particlesAlive] = particle; + } + particle.setBlendFunction(this.mSourceBlendFunction, this.mDestinationBlendFunction); + + /* Apply particle initializers. */ + { + final ArrayList particleInitializers = this.mParticleInitializers; + for(int i = this.mParticleInitializerCount - 1; i >= 0; i--) { + particleInitializers.get(i).onInitializeParticle(particle); + } + + final ArrayList particleModifiers = this.mParticleModifiers; + for(int i = this.mParticleModifierCount - 1; i >= 0; i--) { + particleModifiers.get(i).onInitializeParticle(particle); + } + } + + this.mParticlesAlive++; + } + } + + private float determineCurrentRate() { + if(this.mRateMinimum == this.mRateMaximum){ + return this.mRateMinimum; + } else { + return (RANDOM.nextFloat() * (this.mRateMaximum - this.mRateMinimum)) + this.mRateMinimum; + } + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/entity/particle/emitter/BaseCircleParticleEmitter.java b/AndEngine/src/org/anddev/andengine/entity/particle/emitter/BaseCircleParticleEmitter.java index 4ce57b13..0d65c8ea 100644 --- a/AndEngine/src/org/anddev/andengine/entity/particle/emitter/BaseCircleParticleEmitter.java +++ b/AndEngine/src/org/anddev/andengine/entity/particle/emitter/BaseCircleParticleEmitter.java @@ -9,70 +9,70 @@ * @since 20:14:43 - 01.10.2010 */ public abstract class BaseCircleParticleEmitter extends BaseParticleEmitter { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - protected float mRadiusX; - protected float mRadiusY; - - // =========================================================== - // Constructors - // =========================================================== - - public BaseCircleParticleEmitter(final float pCenterX, final float pCenterY, final float pRadius) { - this(pCenterX, pCenterY, pRadius, pRadius); - } - - public BaseCircleParticleEmitter(final float pCenterX, final float pCenterY, final float pRadiusX, final float pRadiusY) { - super(pCenterX, pCenterY); - this.setRadiusX(pRadiusX); - this.setRadiusY(pRadiusY); - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - public float getRadiusX() { - return this.mRadiusX; - } - - public void setRadiusX(final float pRadiusX) { - this.mRadiusX = pRadiusX; - } - - public float getRadiusY() { - return this.mRadiusY; - } - - public void setRadiusY(final float pRadiusY) { - this.mRadiusY = pRadiusY; - } - - public void setRadius(final float pRadius) { - this.mRadiusX = pRadius; - this.mRadiusY = pRadius; - } - - public void setRadius(final float pRadiusX, final float pRadiusY) { - this.mRadiusX = pRadiusX; - this.mRadiusY = pRadiusY; - } - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + protected float mRadiusX; + protected float mRadiusY; + + // =========================================================== + // Constructors + // =========================================================== + + public BaseCircleParticleEmitter(final float pCenterX, final float pCenterY, final float pRadius) { + this(pCenterX, pCenterY, pRadius, pRadius); + } + + public BaseCircleParticleEmitter(final float pCenterX, final float pCenterY, final float pRadiusX, final float pRadiusY) { + super(pCenterX, pCenterY); + this.setRadiusX(pRadiusX); + this.setRadiusY(pRadiusY); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + public float getRadiusX() { + return this.mRadiusX; + } + + public void setRadiusX(final float pRadiusX) { + this.mRadiusX = pRadiusX; + } + + public float getRadiusY() { + return this.mRadiusY; + } + + public void setRadiusY(final float pRadiusY) { + this.mRadiusY = pRadiusY; + } + + public void setRadius(final float pRadius) { + this.mRadiusX = pRadius; + this.mRadiusY = pRadius; + } + + public void setRadius(final float pRadiusX, final float pRadiusY) { + this.mRadiusX = pRadiusX; + this.mRadiusY = pRadiusY; + } + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/entity/particle/emitter/BaseParticleEmitter.java b/AndEngine/src/org/anddev/andengine/entity/particle/emitter/BaseParticleEmitter.java index 6c90a3e2..8ac85b40 100644 --- a/AndEngine/src/org/anddev/andengine/entity/particle/emitter/BaseParticleEmitter.java +++ b/AndEngine/src/org/anddev/andengine/entity/particle/emitter/BaseParticleEmitter.java @@ -8,70 +8,70 @@ * @since 15:58:12 - 01.10.2010 */ public abstract class BaseParticleEmitter implements IParticleEmitter { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - protected float mCenterX; - protected float mCenterY; + protected float mCenterX; + protected float mCenterY; - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - public BaseParticleEmitter(final float pCenterX, final float pCenterY) { - this.mCenterX = pCenterX; - this.mCenterY = pCenterY; - } + public BaseParticleEmitter(final float pCenterX, final float pCenterY) { + this.mCenterX = pCenterX; + this.mCenterY = pCenterY; + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - public float getCenterX() { - return this.mCenterX; - } + public float getCenterX() { + return this.mCenterX; + } - public float getCenterY() { - return this.mCenterY; - } + public float getCenterY() { + return this.mCenterY; + } - public void setCenterX(final float pCenterX) { - this.mCenterX = pCenterX; - } + public void setCenterX(final float pCenterX) { + this.mCenterX = pCenterX; + } - public void setCenterY(final float pCenterY) { - this.mCenterY = pCenterY; - } + public void setCenterY(final float pCenterY) { + this.mCenterY = pCenterY; + } - public void setCenter(final float pCenterX, final float pCenterY) { - this.mCenterX = pCenterX; - this.mCenterY = pCenterY; - } + public void setCenter(final float pCenterX, final float pCenterY) { + this.mCenterX = pCenterX; + this.mCenterY = pCenterY; + } - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - @Override - public void onUpdate(final float pSecondsElapsed) { + @Override + public void onUpdate(final float pSecondsElapsed) { - } + } - @Override - public void reset() { + @Override + public void reset() { - } + } - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/entity/particle/emitter/BaseRectangleParticleEmitter.java b/AndEngine/src/org/anddev/andengine/entity/particle/emitter/BaseRectangleParticleEmitter.java index 17812dc6..5a9b4a21 100644 --- a/AndEngine/src/org/anddev/andengine/entity/particle/emitter/BaseRectangleParticleEmitter.java +++ b/AndEngine/src/org/anddev/andengine/entity/particle/emitter/BaseRectangleParticleEmitter.java @@ -9,64 +9,64 @@ * @since 18:53:18 - 01.10.2010 */ public abstract class BaseRectangleParticleEmitter extends BaseParticleEmitter { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - protected float mWidth; - protected float mHeight; - protected float mWidthHalf; - protected float mHeightHalf; + protected float mWidth; + protected float mHeight; + protected float mWidthHalf; + protected float mHeightHalf; - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - public BaseRectangleParticleEmitter(final float pCenterX, final float pCenterY, final float pSize) { - this(pCenterX, pCenterY, pSize, pSize); - } + public BaseRectangleParticleEmitter(final float pCenterX, final float pCenterY, final float pSize) { + this(pCenterX, pCenterY, pSize, pSize); + } - public BaseRectangleParticleEmitter(final float pCenterX, final float pCenterY, final float pWidth, final float pHeight) { - super(pCenterX, pCenterY); - this.setWidth(pWidth); - this.setHeight(pHeight); - } + public BaseRectangleParticleEmitter(final float pCenterX, final float pCenterY, final float pWidth, final float pHeight) { + super(pCenterX, pCenterY); + this.setWidth(pWidth); + this.setHeight(pHeight); + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - public float getWidth() { - return this.mWidth; - } + public float getWidth() { + return this.mWidth; + } - public void setWidth(final float pWidth) { - this.mWidth = pWidth; - this.mWidthHalf = pWidth * 0.5f; - } + public void setWidth(final float pWidth) { + this.mWidth = pWidth; + this.mWidthHalf = pWidth * 0.5f; + } - public float getHeight() { - return this.mHeight; - } + public float getHeight() { + return this.mHeight; + } - public void setHeight(final float pHeight) { - this.mHeight = pHeight; - this.mHeightHalf = pHeight * 0.5f; - } + public void setHeight(final float pHeight) { + this.mHeight = pHeight; + this.mHeightHalf = pHeight * 0.5f; + } - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/entity/particle/emitter/CircleOutlineParticleEmitter.java b/AndEngine/src/org/anddev/andengine/entity/particle/emitter/CircleOutlineParticleEmitter.java index 9d975513..feafa234 100644 --- a/AndEngine/src/org/anddev/andengine/entity/particle/emitter/CircleOutlineParticleEmitter.java +++ b/AndEngine/src/org/anddev/andengine/entity/particle/emitter/CircleOutlineParticleEmitter.java @@ -16,46 +16,46 @@ * @since 20:18:41 - 01.10.2010 */ public class CircleOutlineParticleEmitter extends BaseCircleParticleEmitter { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - // =========================================================== - // Constructors - // =========================================================== - - public CircleOutlineParticleEmitter(final float pCenterX, final float pCenterY, final float pRadius) { - super(pCenterX, pCenterY, pRadius); - } - - public CircleOutlineParticleEmitter(final float pCenterX, final float pCenterY, final float pRadiusX, final float pRadiusY) { - super(pCenterX, pCenterY, pRadiusX, pRadiusY); - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - public void getPositionOffset(final float[] pOffset) { - final float random = MathUtils.RANDOM.nextFloat() * MathConstants.PI * 2; - pOffset[VERTEX_INDEX_X] = this.mCenterX + (float) Math.cos(random) * this.mRadiusX; - pOffset[VERTEX_INDEX_Y] = this.mCenterY + (float) Math.sin(random) * this.mRadiusY; - } - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + // =========================================================== + // Constructors + // =========================================================== + + public CircleOutlineParticleEmitter(final float pCenterX, final float pCenterY, final float pRadius) { + super(pCenterX, pCenterY, pRadius); + } + + public CircleOutlineParticleEmitter(final float pCenterX, final float pCenterY, final float pRadiusX, final float pRadiusY) { + super(pCenterX, pCenterY, pRadiusX, pRadiusY); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + public void getPositionOffset(final float[] pOffset) { + final float random = MathUtils.RANDOM.nextFloat() * MathConstants.PI * 2; + pOffset[VERTEX_INDEX_X] = this.mCenterX + (float) Math.cos(random) * this.mRadiusX; + pOffset[VERTEX_INDEX_Y] = this.mCenterY + (float) Math.sin(random) * this.mRadiusY; + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/entity/particle/emitter/CircleParticleEmitter.java b/AndEngine/src/org/anddev/andengine/entity/particle/emitter/CircleParticleEmitter.java index ff13fd95..a262c9cc 100644 --- a/AndEngine/src/org/anddev/andengine/entity/particle/emitter/CircleParticleEmitter.java +++ b/AndEngine/src/org/anddev/andengine/entity/particle/emitter/CircleParticleEmitter.java @@ -16,46 +16,46 @@ * @since 20:18:41 - 01.10.2010 */ public class CircleParticleEmitter extends BaseCircleParticleEmitter { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - // =========================================================== - // Constructors - // =========================================================== - - public CircleParticleEmitter(final float pCenterX, final float pCenterY, final float pRadius) { - super(pCenterX, pCenterY, pRadius); - } - - public CircleParticleEmitter(final float pCenterX, final float pCenterY, final float pRadiusX, final float pRadiusY) { - super(pCenterX, pCenterY, pRadiusX, pRadiusY); - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - public void getPositionOffset(final float[] pOffset) { - final float random = MathUtils.RANDOM.nextFloat() * MathConstants.PI * 2; - 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(); - } - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + // =========================================================== + // Constructors + // =========================================================== + + public CircleParticleEmitter(final float pCenterX, final float pCenterY, final float pRadius) { + super(pCenterX, pCenterY, pRadius); + } + + public CircleParticleEmitter(final float pCenterX, final float pCenterY, final float pRadiusX, final float pRadiusY) { + super(pCenterX, pCenterY, pRadiusX, pRadiusY); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + public void getPositionOffset(final float[] pOffset) { + final float random = MathUtils.RANDOM.nextFloat() * MathConstants.PI * 2; + 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(); + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/entity/particle/emitter/IParticleEmitter.java b/AndEngine/src/org/anddev/andengine/entity/particle/emitter/IParticleEmitter.java index c49509ef..7fd4d177 100644 --- a/AndEngine/src/org/anddev/andengine/entity/particle/emitter/IParticleEmitter.java +++ b/AndEngine/src/org/anddev/andengine/entity/particle/emitter/IParticleEmitter.java @@ -10,13 +10,13 @@ * @since 15:48:09 - 01.10.2010 */ public interface IParticleEmitter extends IUpdateHandler { - // =========================================================== - // Final Fields - // =========================================================== + // =========================================================== + // Final Fields + // =========================================================== - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - public void getPositionOffset(final float[] pOffset); + public void getPositionOffset(final float[] pOffset); } diff --git a/AndEngine/src/org/anddev/andengine/entity/particle/emitter/PointParticleEmitter.java b/AndEngine/src/org/anddev/andengine/entity/particle/emitter/PointParticleEmitter.java index a4f9b1a0..9ba695c5 100644 --- a/AndEngine/src/org/anddev/andengine/entity/particle/emitter/PointParticleEmitter.java +++ b/AndEngine/src/org/anddev/andengine/entity/particle/emitter/PointParticleEmitter.java @@ -11,41 +11,41 @@ * @since 23:14:42 - 01.10.2010 */ public class PointParticleEmitter extends BaseParticleEmitter { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - // =========================================================== - // Constructors - // =========================================================== - - public PointParticleEmitter(final float pCenterX, final float pCenterY) { - super(pCenterX, pCenterY); - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - public void getPositionOffset(final float[] pOffset) { - pOffset[VERTEX_INDEX_X] = this.mCenterX; - pOffset[VERTEX_INDEX_Y] = this.mCenterY; - } - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + // =========================================================== + // Constructors + // =========================================================== + + public PointParticleEmitter(final float pCenterX, final float pCenterY) { + super(pCenterX, pCenterY); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + public void getPositionOffset(final float[] pOffset) { + pOffset[VERTEX_INDEX_X] = this.mCenterX; + pOffset[VERTEX_INDEX_Y] = this.mCenterY; + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/entity/particle/emitter/RectangleOutlineParticleEmitter.java b/AndEngine/src/org/anddev/andengine/entity/particle/emitter/RectangleOutlineParticleEmitter.java index 4f93edab..2636e1b9 100644 --- a/AndEngine/src/org/anddev/andengine/entity/particle/emitter/RectangleOutlineParticleEmitter.java +++ b/AndEngine/src/org/anddev/andengine/entity/particle/emitter/RectangleOutlineParticleEmitter.java @@ -13,41 +13,41 @@ * @since 15:48:00 - 01.10.2010 */ public class RectangleOutlineParticleEmitter extends BaseRectangleParticleEmitter { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - // =========================================================== - // Constructors - // =========================================================== - - public RectangleOutlineParticleEmitter(final float pCenterX, final float pCenterY, final float pWidth, final float pHeight) { - super(pCenterX, pCenterY, pWidth, pHeight); - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - public void getPositionOffset(final float[] pOffset) { - pOffset[VERTEX_INDEX_X] = this.mCenterX + MathUtils.randomSign() * this.mWidthHalf; - pOffset[VERTEX_INDEX_Y] = this.mCenterY + MathUtils.randomSign() * this.mHeightHalf; - } - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + // =========================================================== + // Constructors + // =========================================================== + + public RectangleOutlineParticleEmitter(final float pCenterX, final float pCenterY, final float pWidth, final float pHeight) { + super(pCenterX, pCenterY, pWidth, pHeight); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + public void getPositionOffset(final float[] pOffset) { + pOffset[VERTEX_INDEX_X] = this.mCenterX + MathUtils.randomSign() * this.mWidthHalf; + pOffset[VERTEX_INDEX_Y] = this.mCenterY + MathUtils.randomSign() * this.mHeightHalf; + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/entity/particle/emitter/RectangleParticleEmitter.java b/AndEngine/src/org/anddev/andengine/entity/particle/emitter/RectangleParticleEmitter.java index 4da98512..e6febc6b 100644 --- a/AndEngine/src/org/anddev/andengine/entity/particle/emitter/RectangleParticleEmitter.java +++ b/AndEngine/src/org/anddev/andengine/entity/particle/emitter/RectangleParticleEmitter.java @@ -13,41 +13,41 @@ * @since 15:48:00 - 01.10.2010 */ public class RectangleParticleEmitter extends BaseRectangleParticleEmitter { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - // =========================================================== - // Constructors - // =========================================================== - - public RectangleParticleEmitter(final float pCenterX, final float pCenterY, final float pWidth, final float pHeight) { - super(pCenterX, pCenterY, pWidth, pHeight); - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - public void getPositionOffset(final float[] pOffset) { - pOffset[VERTEX_INDEX_X] = this.mCenterX - this.mWidthHalf + MathUtils.RANDOM.nextFloat() * this.mWidth; - pOffset[VERTEX_INDEX_Y] = this.mCenterY - this.mHeightHalf + MathUtils.RANDOM.nextFloat() * this.mHeight; - } - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + // =========================================================== + // Constructors + // =========================================================== + + public RectangleParticleEmitter(final float pCenterX, final float pCenterY, final float pWidth, final float pHeight) { + super(pCenterX, pCenterY, pWidth, pHeight); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + public void getPositionOffset(final float[] pOffset) { + pOffset[VERTEX_INDEX_X] = this.mCenterX - this.mWidthHalf + MathUtils.RANDOM.nextFloat() * this.mWidth; + pOffset[VERTEX_INDEX_Y] = this.mCenterY - this.mHeightHalf + MathUtils.RANDOM.nextFloat() * this.mHeight; + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/entity/particle/initializer/AccelerationInitializer.java b/AndEngine/src/org/anddev/andengine/entity/particle/initializer/AccelerationInitializer.java index 0af888b2..090613c4 100644 --- a/AndEngine/src/org/anddev/andengine/entity/particle/initializer/AccelerationInitializer.java +++ b/AndEngine/src/org/anddev/andengine/entity/particle/initializer/AccelerationInitializer.java @@ -10,91 +10,91 @@ * @since 21:21:10 - 14.03.2010 */ public class AccelerationInitializer extends BaseDoubleValueInitializer { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - // =========================================================== - // Constructors - // =========================================================== - - public AccelerationInitializer(final float pAcceleration) { - this(pAcceleration, pAcceleration); - } - - public AccelerationInitializer(final float pAccelerationX, final float pAccelerationY) { - this(pAccelerationX, pAccelerationX, pAccelerationY, pAccelerationY); - } - - public AccelerationInitializer(final float pMinAccelerationX, final float pMaxAccelerationX, final float pMinAccelerationY, final float pMaxAccelerationY) { - super(pMinAccelerationX, pMaxAccelerationX, pMinAccelerationY, pMaxAccelerationY); - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - public float getMinAccelerationX() { - return this.mMinValue; - } - - public float getMaxAccelerationX() { - return this.mMaxValue; - } - - public float getMinAccelerationY() { - return this.mMinValueB; - } - - public float getMaxAccelerationY() { - return this.mMaxValueB; - } - - public void setAccelerationX(final float pAccelerationX) { - this.mMinValue = pAccelerationX; - this.mMaxValue = pAccelerationX; - } - - public void setAccelerationY(final float pAccelerationY) { - this.mMinValueB = pAccelerationY; - this.mMaxValueB = pAccelerationY; - } - - public void setAccelerationX(final float pMinAccelerationX, final float pMaxAccelerationX) { - this.mMinValue = pMinAccelerationX; - this.mMaxValue = pMaxAccelerationX; - } - - public void setAccelerationY(final float pMinAccelerationY, final float pMaxAccelerationY) { - this.mMinValueB = pMinAccelerationY; - this.mMaxValueB = pMaxAccelerationY; - } - - public void setAcceleration(final float pMinAccelerationX, final float pMaxAccelerationX, final float pMinAccelerationY, final float pMaxAccelerationY) { - this.mMinValue = pMinAccelerationX; - this.mMaxValue = pMaxAccelerationX; - this.mMinValueB = pMinAccelerationY; - this.mMaxValueB = pMaxAccelerationY; - } - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - public void onInitializeParticle(final Particle pParticle, final float pAccelerationX, final float pAccelerationY) { - pParticle.getPhysicsHandler().accelerate(pAccelerationX, pAccelerationY); - } - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + // =========================================================== + // Constructors + // =========================================================== + + public AccelerationInitializer(final float pAcceleration) { + this(pAcceleration, pAcceleration); + } + + public AccelerationInitializer(final float pAccelerationX, final float pAccelerationY) { + this(pAccelerationX, pAccelerationX, pAccelerationY, pAccelerationY); + } + + public AccelerationInitializer(final float pMinAccelerationX, final float pMaxAccelerationX, final float pMinAccelerationY, final float pMaxAccelerationY) { + super(pMinAccelerationX, pMaxAccelerationX, pMinAccelerationY, pMaxAccelerationY); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + public float getMinAccelerationX() { + return this.mMinValue; + } + + public float getMaxAccelerationX() { + return this.mMaxValue; + } + + public float getMinAccelerationY() { + return this.mMinValueB; + } + + public float getMaxAccelerationY() { + return this.mMaxValueB; + } + + public void setAccelerationX(final float pAccelerationX) { + this.mMinValue = pAccelerationX; + this.mMaxValue = pAccelerationX; + } + + public void setAccelerationY(final float pAccelerationY) { + this.mMinValueB = pAccelerationY; + this.mMaxValueB = pAccelerationY; + } + + public void setAccelerationX(final float pMinAccelerationX, final float pMaxAccelerationX) { + this.mMinValue = pMinAccelerationX; + this.mMaxValue = pMaxAccelerationX; + } + + public void setAccelerationY(final float pMinAccelerationY, final float pMaxAccelerationY) { + this.mMinValueB = pMinAccelerationY; + this.mMaxValueB = pMaxAccelerationY; + } + + public void setAcceleration(final float pMinAccelerationX, final float pMaxAccelerationX, final float pMinAccelerationY, final float pMaxAccelerationY) { + this.mMinValue = pMinAccelerationX; + this.mMaxValue = pMaxAccelerationX; + this.mMinValueB = pMinAccelerationY; + this.mMaxValueB = pMaxAccelerationY; + } + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + public void onInitializeParticle(final Particle pParticle, final float pAccelerationX, final float pAccelerationY) { + pParticle.getPhysicsHandler().accelerate(pAccelerationX, pAccelerationY); + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/entity/particle/initializer/AlphaInitializer.java b/AndEngine/src/org/anddev/andengine/entity/particle/initializer/AlphaInitializer.java index 3556cf2e..15c3372d 100644 --- a/AndEngine/src/org/anddev/andengine/entity/particle/initializer/AlphaInitializer.java +++ b/AndEngine/src/org/anddev/andengine/entity/particle/initializer/AlphaInitializer.java @@ -11,44 +11,44 @@ * @since 18:53:41 - 02.10.2010 */ public class AlphaInitializer extends BaseSingleValueInitializer { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - // =========================================================== - // Constructors - // =========================================================== - - public AlphaInitializer(final float pAlpha) { - super(pAlpha, pAlpha); - } - - public AlphaInitializer(final float pMinAlpha, final float pMaxAlpha) { - super(pMinAlpha, pMaxAlpha); - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - protected void onInitializeParticle(final Particle pParticle, final float pAlpha) { - pParticle.setAlpha(pAlpha); - } - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + // =========================================================== + // Constructors + // =========================================================== + + public AlphaInitializer(final float pAlpha) { + super(pAlpha, pAlpha); + } + + public AlphaInitializer(final float pMinAlpha, final float pMaxAlpha) { + super(pMinAlpha, pMaxAlpha); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + protected void onInitializeParticle(final Particle pParticle, final float pAlpha) { + pParticle.setAlpha(pAlpha); + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/entity/particle/initializer/BaseDoubleValueInitializer.java b/AndEngine/src/org/anddev/andengine/entity/particle/initializer/BaseDoubleValueInitializer.java index a9f257ae..908b916f 100644 --- a/AndEngine/src/org/anddev/andengine/entity/particle/initializer/BaseDoubleValueInitializer.java +++ b/AndEngine/src/org/anddev/andengine/entity/particle/initializer/BaseDoubleValueInitializer.java @@ -12,55 +12,55 @@ * @since 15:58:29 - 04.05.2010 */ public abstract class BaseDoubleValueInitializer extends BaseSingleValueInitializer { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - protected float mMinValueB; - protected float mMaxValueB; + protected float mMinValueB; + protected float mMaxValueB; - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - public BaseDoubleValueInitializer(final float pMinValueA, final float pMaxValueA, final float pMinValueB, final float pMaxValueB) { - super(pMinValueA, pMaxValueA); - this.mMinValueB = pMinValueB; - this.mMaxValueB = pMaxValueB; - } + public BaseDoubleValueInitializer(final float pMinValueA, final float pMaxValueA, final float pMinValueB, final float pMaxValueB) { + super(pMinValueA, pMaxValueA); + this.mMinValueB = pMinValueB; + this.mMaxValueB = pMaxValueB; + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - protected abstract void onInitializeParticle(final Particle pParticle, final float pValueA, final float pValueB); + protected abstract void onInitializeParticle(final Particle pParticle, final float pValueA, final float pValueB); - @Override - protected final void onInitializeParticle(final Particle pParticle, final float pValueA) { - this.onInitializeParticle(pParticle, pValueA, this.getRandomValueB()); - } + @Override + protected final void onInitializeParticle(final Particle pParticle, final float pValueA) { + this.onInitializeParticle(pParticle, pValueA, this.getRandomValueB()); + } - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - private final float getRandomValueB() { - if(this.mMinValueB == this.mMaxValueB) { - return this.mMaxValueB; - } else { - return RANDOM.nextFloat() * (this.mMaxValueB - this.mMinValueB) + this.mMinValueB; - } - } + private final float getRandomValueB() { + if(this.mMinValueB == this.mMaxValueB) { + return this.mMaxValueB; + } else { + return RANDOM.nextFloat() * (this.mMaxValueB - this.mMinValueB) + this.mMinValueB; + } + } - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/entity/particle/initializer/BaseSingleValueInitializer.java b/AndEngine/src/org/anddev/andengine/entity/particle/initializer/BaseSingleValueInitializer.java index dbcb9616..41da6c13 100644 --- a/AndEngine/src/org/anddev/andengine/entity/particle/initializer/BaseSingleValueInitializer.java +++ b/AndEngine/src/org/anddev/andengine/entity/particle/initializer/BaseSingleValueInitializer.java @@ -12,54 +12,54 @@ * @since 10:18:06 - 29.06.2010 */ public abstract class BaseSingleValueInitializer implements IParticleInitializer { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - protected float mMinValue; - protected float mMaxValue; + protected float mMinValue; + protected float mMaxValue; - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - public BaseSingleValueInitializer(final float pMinValue, final float pMaxValue) { - this.mMinValue = pMinValue; - this.mMaxValue = pMaxValue; - } + public BaseSingleValueInitializer(final float pMinValue, final float pMaxValue) { + this.mMinValue = pMinValue; + this.mMaxValue = pMaxValue; + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - protected abstract void onInitializeParticle(final Particle pParticle, final float pValue); + protected abstract void onInitializeParticle(final Particle pParticle, final float pValue); - @Override - public final void onInitializeParticle(final Particle pParticle) { - this.onInitializeParticle(pParticle, this.getRandomValue()); - } + @Override + public final void onInitializeParticle(final Particle pParticle) { + this.onInitializeParticle(pParticle, this.getRandomValue()); + } - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - private final float getRandomValue() { - if(this.mMinValue == this.mMaxValue) { - return this.mMaxValue; - } else { - return RANDOM.nextFloat() * (this.mMaxValue - this.mMinValue) + this.mMinValue; - } - } + private final float getRandomValue() { + if(this.mMinValue == this.mMaxValue) { + return this.mMaxValue; + } else { + return RANDOM.nextFloat() * (this.mMaxValue - this.mMinValue) + this.mMinValue; + } + } - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/entity/particle/initializer/BaseTripleValueInitializer.java b/AndEngine/src/org/anddev/andengine/entity/particle/initializer/BaseTripleValueInitializer.java index d4726e41..4f6e99f0 100644 --- a/AndEngine/src/org/anddev/andengine/entity/particle/initializer/BaseTripleValueInitializer.java +++ b/AndEngine/src/org/anddev/andengine/entity/particle/initializer/BaseTripleValueInitializer.java @@ -12,55 +12,55 @@ * @since 15:58:29 - 04.05.2010 */ public abstract class BaseTripleValueInitializer extends BaseDoubleValueInitializer { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - protected float mMinValueC; - protected float mMaxValueC; + protected float mMinValueC; + protected float mMaxValueC; - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - public BaseTripleValueInitializer(final float pMinValueA, final float pMaxValueA, final float pMinValueB, final float pMaxValueB, final float pMinValueC, final float pMaxValueC) { - super(pMinValueA, pMaxValueA, pMinValueB, pMaxValueB); - this.mMinValueC = pMinValueC; - this.mMaxValueC = pMaxValueC; - } + public BaseTripleValueInitializer(final float pMinValueA, final float pMaxValueA, final float pMinValueB, final float pMaxValueB, final float pMinValueC, final float pMaxValueC) { + super(pMinValueA, pMaxValueA, pMinValueB, pMaxValueB); + this.mMinValueC = pMinValueC; + this.mMaxValueC = pMaxValueC; + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - protected abstract void onInitializeParticle(final Particle pParticle, final float pValueA, final float pValueB, final float pValueC); + protected abstract void onInitializeParticle(final Particle pParticle, final float pValueA, final float pValueB, final float pValueC); - @Override - protected final void onInitializeParticle(final Particle pParticle, final float pValueA, final float pValueB) { - this.onInitializeParticle(pParticle, pValueA, pValueB, this.getRandomValueC()); - } + @Override + protected final void onInitializeParticle(final Particle pParticle, final float pValueA, final float pValueB) { + this.onInitializeParticle(pParticle, pValueA, pValueB, this.getRandomValueC()); + } - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - private final float getRandomValueC() { - if(this.mMinValueC == this.mMaxValueC) { - return this.mMaxValueC; - } else { - return RANDOM.nextFloat() * (this.mMaxValueC - this.mMinValueC) + this.mMinValueC; - } - } + private final float getRandomValueC() { + if(this.mMinValueC == this.mMaxValueC) { + return this.mMaxValueC; + } else { + return RANDOM.nextFloat() * (this.mMaxValueC - this.mMinValueC) + this.mMinValueC; + } + } - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/entity/particle/initializer/ColorInitializer.java b/AndEngine/src/org/anddev/andengine/entity/particle/initializer/ColorInitializer.java index 343f8906..e56b21a5 100644 --- a/AndEngine/src/org/anddev/andengine/entity/particle/initializer/ColorInitializer.java +++ b/AndEngine/src/org/anddev/andengine/entity/particle/initializer/ColorInitializer.java @@ -11,44 +11,44 @@ * @since 10:17:42 - 29.06.2010 */ public class ColorInitializer extends BaseTripleValueInitializer { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - // =========================================================== - // Constructors - // =========================================================== - - public ColorInitializer(final float pRed, final float pGreen, final float pBlue) { - super(pRed, pRed, pGreen, pGreen, pBlue, pBlue); - } - - public ColorInitializer(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); - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - protected void onInitializeParticle(final Particle pParticle, final float pRed, final float pGreen, final float pBlue) { - pParticle.setColor(pRed, pGreen, pBlue); - } - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + // =========================================================== + // Constructors + // =========================================================== + + public ColorInitializer(final float pRed, final float pGreen, final float pBlue) { + super(pRed, pRed, pGreen, pGreen, pBlue, pBlue); + } + + public ColorInitializer(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); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + protected void onInitializeParticle(final Particle pParticle, final float pRed, final float pGreen, final float pBlue) { + pParticle.setColor(pRed, pGreen, pBlue); + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/entity/particle/initializer/GravityInitializer.java b/AndEngine/src/org/anddev/andengine/entity/particle/initializer/GravityInitializer.java index 7b11ceef..c9265771 100644 --- a/AndEngine/src/org/anddev/andengine/entity/particle/initializer/GravityInitializer.java +++ b/AndEngine/src/org/anddev/andengine/entity/particle/initializer/GravityInitializer.java @@ -10,35 +10,35 @@ * @since 12:04:00 - 15.03.2010 */ public class GravityInitializer extends AccelerationInitializer { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - public GravityInitializer() { - super(0, SensorManager.GRAVITY_EARTH); - } + public GravityInitializer() { + super(0, SensorManager.GRAVITY_EARTH); + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/entity/particle/initializer/IParticleInitializer.java b/AndEngine/src/org/anddev/andengine/entity/particle/initializer/IParticleInitializer.java index 11efcd16..f313e89e 100644 --- a/AndEngine/src/org/anddev/andengine/entity/particle/initializer/IParticleInitializer.java +++ b/AndEngine/src/org/anddev/andengine/entity/particle/initializer/IParticleInitializer.java @@ -10,13 +10,13 @@ * @since 10:12:09 - 29.06.2010 */ public interface IParticleInitializer { - // =========================================================== - // Final Fields - // =========================================================== + // =========================================================== + // Final Fields + // =========================================================== - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - public void onInitializeParticle(final Particle pParticle); + public void onInitializeParticle(final Particle pParticle); } diff --git a/AndEngine/src/org/anddev/andengine/entity/particle/initializer/RotationInitializer.java b/AndEngine/src/org/anddev/andengine/entity/particle/initializer/RotationInitializer.java index 221fc5f5..679747b1 100644 --- a/AndEngine/src/org/anddev/andengine/entity/particle/initializer/RotationInitializer.java +++ b/AndEngine/src/org/anddev/andengine/entity/particle/initializer/RotationInitializer.java @@ -10,62 +10,62 @@ * @since 10:17:42 - 29.06.2010 */ public class RotationInitializer extends BaseSingleValueInitializer { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - public RotationInitializer(final float pRotation) { - this(pRotation, pRotation); - } + public RotationInitializer(final float pRotation) { + this(pRotation, pRotation); + } - public RotationInitializer(final float pMinRotation, final float pMaxRotation) { - super(pMinRotation, pMaxRotation); - } + public RotationInitializer(final float pMinRotation, final float pMaxRotation) { + super(pMinRotation, pMaxRotation); + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - public float getMinRotation() { - return this.mMinValue; - } + public float getMinRotation() { + return this.mMinValue; + } - public float getMaxRotation() { - return this.mMaxValue; - } + public float getMaxRotation() { + return this.mMaxValue; + } - public void setRotation(final float pRotation) { - this.mMinValue = pRotation; - this.mMaxValue = pRotation; - } + public void setRotation(final float pRotation) { + this.mMinValue = pRotation; + this.mMaxValue = pRotation; + } - public void setRotation(final float pMinRotation, final float pMaxRotation) { - this.mMinValue = pMinRotation; - this.mMaxValue = pMaxRotation; - } + public void setRotation(final float pMinRotation, final float pMaxRotation) { + this.mMinValue = pMinRotation; + this.mMaxValue = pMaxRotation; + } - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - @Override - public void onInitializeParticle(final Particle pParticle, final float pRotation) { - pParticle.setRotation(pRotation); - } + @Override + public void onInitializeParticle(final Particle pParticle, final float pRotation) { + pParticle.setRotation(pRotation); + } - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/entity/particle/initializer/VelocityInitializer.java b/AndEngine/src/org/anddev/andengine/entity/particle/initializer/VelocityInitializer.java index 779fe0a4..87d8fb70 100644 --- a/AndEngine/src/org/anddev/andengine/entity/particle/initializer/VelocityInitializer.java +++ b/AndEngine/src/org/anddev/andengine/entity/particle/initializer/VelocityInitializer.java @@ -10,91 +10,91 @@ * @since 21:21:10 - 14.03.2010 */ public class VelocityInitializer extends BaseDoubleValueInitializer { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - // =========================================================== - // Constructors - // =========================================================== - - public VelocityInitializer(final float pVelocity) { - this(pVelocity, pVelocity, pVelocity, pVelocity); - } - - public VelocityInitializer(final float pVelocityX, final float pVelocityY) { - this(pVelocityX, pVelocityX, pVelocityY, pVelocityY); - } - - public VelocityInitializer(final float pMinVelocityX, final float pMaxVelocityX, final float pMinVelocityY, final float pMaxVelocityY) { - super(pMinVelocityX, pMaxVelocityX, pMinVelocityY, pMaxVelocityY); - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - public float getMinVelocityX() { - return this.mMinValue; - } - - public float getMaxVelocityX() { - return this.mMaxValue; - } - - public float getMinVelocityY() { - return this.mMinValueB; - } - - public float getMaxVelocityY() { - return this.mMaxValueB; - } - - public void setVelocityX(final float pVelocityX) { - this.mMinValue = pVelocityX; - this.mMaxValue = pVelocityX; - } - - public void setVelocityY(final float pVelocityY) { - this.mMinValueB = pVelocityY; - this.mMaxValueB = pVelocityY; - } - - public void setVelocityX(final float pMinVelocityX, final float pMaxVelocityX) { - this.mMinValue = pMinVelocityX; - this.mMaxValue = pMaxVelocityX; - } - - public void setVelocityY(final float pMinVelocityY, final float pMaxVelocityY) { - this.mMinValueB = pMinVelocityY; - this.mMaxValueB = pMaxVelocityY; - } - - public void setVelocity(final float pMinVelocityX, final float pMaxVelocityX, final float pMinVelocityY, final float pMaxVelocityY) { - this.mMinValue = pMinVelocityX; - this.mMaxValue = pMaxVelocityX; - this.mMinValueB = pMinVelocityY; - this.mMaxValueB = pMaxVelocityY; - } - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - public void onInitializeParticle(final Particle pParticle, final float pVelocityX, final float pVelocityY) { - pParticle.getPhysicsHandler().setVelocity(pVelocityX, pVelocityY); - } - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + // =========================================================== + // Constructors + // =========================================================== + + public VelocityInitializer(final float pVelocity) { + this(pVelocity, pVelocity, pVelocity, pVelocity); + } + + public VelocityInitializer(final float pVelocityX, final float pVelocityY) { + this(pVelocityX, pVelocityX, pVelocityY, pVelocityY); + } + + public VelocityInitializer(final float pMinVelocityX, final float pMaxVelocityX, final float pMinVelocityY, final float pMaxVelocityY) { + super(pMinVelocityX, pMaxVelocityX, pMinVelocityY, pMaxVelocityY); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + public float getMinVelocityX() { + return this.mMinValue; + } + + public float getMaxVelocityX() { + return this.mMaxValue; + } + + public float getMinVelocityY() { + return this.mMinValueB; + } + + public float getMaxVelocityY() { + return this.mMaxValueB; + } + + public void setVelocityX(final float pVelocityX) { + this.mMinValue = pVelocityX; + this.mMaxValue = pVelocityX; + } + + public void setVelocityY(final float pVelocityY) { + this.mMinValueB = pVelocityY; + this.mMaxValueB = pVelocityY; + } + + public void setVelocityX(final float pMinVelocityX, final float pMaxVelocityX) { + this.mMinValue = pMinVelocityX; + this.mMaxValue = pMaxVelocityX; + } + + public void setVelocityY(final float pMinVelocityY, final float pMaxVelocityY) { + this.mMinValueB = pMinVelocityY; + this.mMaxValueB = pMaxVelocityY; + } + + public void setVelocity(final float pMinVelocityX, final float pMaxVelocityX, final float pMinVelocityY, final float pMaxVelocityY) { + this.mMinValue = pMinVelocityX; + this.mMaxValue = pMaxVelocityX; + this.mMinValueB = pMinVelocityY; + this.mMaxValueB = pMaxVelocityY; + } + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + public void onInitializeParticle(final Particle pParticle, final float pVelocityX, final float pVelocityY) { + pParticle.getPhysicsHandler().setVelocity(pVelocityX, pVelocityY); + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/entity/particle/modifier/AlphaModifier.java b/AndEngine/src/org/anddev/andengine/entity/particle/modifier/AlphaModifier.java index 11ea23ac..8ba2ba6b 100644 --- a/AndEngine/src/org/anddev/andengine/entity/particle/modifier/AlphaModifier.java +++ b/AndEngine/src/org/anddev/andengine/entity/particle/modifier/AlphaModifier.java @@ -10,45 +10,45 @@ * @since 21:21:10 - 14.03.2010 */ public class AlphaModifier extends BaseSingleValueSpanModifier { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - // =========================================================== - // Constructors - // =========================================================== - - public AlphaModifier(final float pFromAlpha, final float pToAlpha, final float pFromTime, final float pToTime) { - super(pFromAlpha, pToAlpha, pFromTime, pToTime); - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - protected void onSetInitialValue(final Particle pParticle, final float pAlpha) { - pParticle.setAlpha(pAlpha); - } - - @Override - protected void onSetValue(final Particle pParticle, final float pAlpha) { - pParticle.setAlpha(pAlpha); - } - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + // =========================================================== + // Constructors + // =========================================================== + + public AlphaModifier(final float pFromAlpha, final float pToAlpha, final float pFromTime, final float pToTime) { + super(pFromAlpha, pToAlpha, pFromTime, pToTime); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + protected void onSetInitialValue(final Particle pParticle, final float pAlpha) { + pParticle.setAlpha(pAlpha); + } + + @Override + protected void onSetValue(final Particle pParticle, final float pAlpha) { + pParticle.setAlpha(pAlpha); + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/entity/particle/modifier/BaseDoubleValueSpanModifier.java b/AndEngine/src/org/anddev/andengine/entity/particle/modifier/BaseDoubleValueSpanModifier.java index f9fd7f16..e8f9c15c 100644 --- a/AndEngine/src/org/anddev/andengine/entity/particle/modifier/BaseDoubleValueSpanModifier.java +++ b/AndEngine/src/org/anddev/andengine/entity/particle/modifier/BaseDoubleValueSpanModifier.java @@ -10,65 +10,65 @@ * @since 15:19:46 - 29.06.2010 */ public abstract class BaseDoubleValueSpanModifier extends BaseSingleValueSpanModifier { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - private final float mFromValueB; - private final float mToValueB; + private final float mFromValueB; + private final float mToValueB; - private final float mSpanValueB; + private final float mSpanValueB; - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - public BaseDoubleValueSpanModifier(final float pFromValueA, final float pToValueA, final float pFromValueB, final float pToValueB, final float pFromTime, final float pToTime) { - super(pFromValueA, pToValueA, pFromTime, pToTime); - this.mFromValueB = pFromValueB; - this.mToValueB = pToValueB; + public BaseDoubleValueSpanModifier(final float pFromValueA, final float pToValueA, final float pFromValueB, final float pToValueB, final float pFromTime, final float pToTime) { + super(pFromValueA, pToValueA, pFromTime, pToTime); + this.mFromValueB = pFromValueB; + this.mToValueB = pToValueB; - this.mSpanValueB = this.mToValueB - this.mFromValueB; - } + this.mSpanValueB = this.mToValueB - this.mFromValueB; + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - @Override - @Deprecated - protected void onSetValue(final Particle pParticle, final float pValue) { } + @Override + @Deprecated + protected void onSetValue(final Particle pParticle, final float pValue) { } - protected abstract void onSetInitialValues(final Particle pParticle, final float pValueA, final float pValueB); - protected abstract void onSetValues(final Particle pParticle, final float pValueA, final float pValueB); + protected abstract void onSetInitialValues(final Particle pParticle, final float pValueA, final float pValueB); + protected abstract void onSetValues(final Particle pParticle, final float pValueA, final float pValueB); - @Override - public void onSetInitialValue(final Particle pParticle, final float pValueA) { - this.onSetInitialValues(pParticle, pValueA, this.mFromValueB); - } + @Override + public void onSetInitialValue(final Particle pParticle, final float pValueA) { + this.onSetInitialValues(pParticle, pValueA, this.mFromValueB); + } - @Override - protected void onSetValueInternal(final Particle pParticle, final float pPercent) { - this.onSetValues(pParticle, super.calculateValue(pPercent), this.calculateValueB(pPercent)); - } + @Override + protected void onSetValueInternal(final Particle pParticle, final float pPercent) { + this.onSetValues(pParticle, super.calculateValue(pPercent), this.calculateValueB(pPercent)); + } - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - protected final float calculateValueB(final float pPercent) { - return this.mFromValueB + this.mSpanValueB * pPercent; - } + protected final float calculateValueB(final float pPercent) { + return this.mFromValueB + this.mSpanValueB * pPercent; + } - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/entity/particle/modifier/BaseSingleValueSpanModifier.java b/AndEngine/src/org/anddev/andengine/entity/particle/modifier/BaseSingleValueSpanModifier.java index 07a43f5d..412592f7 100644 --- a/AndEngine/src/org/anddev/andengine/entity/particle/modifier/BaseSingleValueSpanModifier.java +++ b/AndEngine/src/org/anddev/andengine/entity/particle/modifier/BaseSingleValueSpanModifier.java @@ -10,83 +10,83 @@ * @since 16:10:16 - 04.05.2010 */ public abstract class BaseSingleValueSpanModifier implements IParticleModifier { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - private final float mFromValue; - private final float mToValue; - - private final float mFromTime; - private final float mToTime; - - private final float mDuration; - private final float mSpanValue; - - // =========================================================== - // Constructors - // =========================================================== - - public BaseSingleValueSpanModifier(final float pFromValue, final float pToValue, final float pFromTime, final float pToTime) { - this.mFromValue = pFromValue; - this.mToValue = pToValue; - this.mFromTime = pFromTime; - this.mToTime = pToTime; - - this.mSpanValue = this.mToValue - this.mFromValue; - this.mDuration = this.mToTime - this.mFromTime; - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - protected abstract void onSetInitialValue(final Particle pParticle, final float pValue); - protected abstract void onSetValue(final Particle pParticle, final float pValue); - - @Override - public void onInitializeParticle(final Particle pParticle) { - this.onSetInitialValue(pParticle, this.mFromValue); - } - - @Override - public void onUpdateParticle(final Particle pParticle) { - final float lifeTime = pParticle.getLifeTime(); - if(lifeTime > this.mFromTime && lifeTime < this.mToTime) { - final float percent = (lifeTime - this.mFromTime) / this.mDuration; - this.onSetValueInternal(pParticle, percent); - } - } - - public void onUpdateParticle(final Particle pParticle, final float overrideToTime) { - final float lifeTime = pParticle.getLifeTime(); - if (lifeTime > this.mFromTime) { - final float percent = (lifeTime - this.mFromTime) / (overrideToTime - this.mFromTime); - this.onSetValueInternal(pParticle, percent); - } - } - - protected void onSetValueInternal(final Particle pParticle, final float pPercent) { - this.onSetValue(pParticle, this.calculateValue(pPercent)); - } - - protected final float calculateValue(final float pPercent) { - return this.mFromValue + this.mSpanValue * pPercent; - } - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + private final float mFromValue; + private final float mToValue; + + private final float mFromTime; + private final float mToTime; + + private final float mDuration; + private final float mSpanValue; + + // =========================================================== + // Constructors + // =========================================================== + + public BaseSingleValueSpanModifier(final float pFromValue, final float pToValue, final float pFromTime, final float pToTime) { + this.mFromValue = pFromValue; + this.mToValue = pToValue; + this.mFromTime = pFromTime; + this.mToTime = pToTime; + + this.mSpanValue = this.mToValue - this.mFromValue; + this.mDuration = this.mToTime - this.mFromTime; + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + protected abstract void onSetInitialValue(final Particle pParticle, final float pValue); + protected abstract void onSetValue(final Particle pParticle, final float pValue); + + @Override + public void onInitializeParticle(final Particle pParticle) { + this.onSetInitialValue(pParticle, this.mFromValue); + } + + @Override + public void onUpdateParticle(final Particle pParticle) { + final float lifeTime = pParticle.getLifeTime(); + if(lifeTime > this.mFromTime && lifeTime < this.mToTime) { + final float percent = (lifeTime - this.mFromTime) / this.mDuration; + this.onSetValueInternal(pParticle, percent); + } + } + + public void onUpdateParticle(final Particle pParticle, final float overrideToTime) { + final float lifeTime = pParticle.getLifeTime(); + if (lifeTime > this.mFromTime) { + final float percent = (lifeTime - this.mFromTime) / (overrideToTime - this.mFromTime); + this.onSetValueInternal(pParticle, percent); + } + } + + protected void onSetValueInternal(final Particle pParticle, final float pPercent) { + this.onSetValue(pParticle, this.calculateValue(pPercent)); + } + + protected final float calculateValue(final float pPercent) { + return this.mFromValue + this.mSpanValue * pPercent; + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/entity/particle/modifier/BaseTripleValueSpanModifier.java b/AndEngine/src/org/anddev/andengine/entity/particle/modifier/BaseTripleValueSpanModifier.java index 25df5d4a..eb3e7493 100644 --- a/AndEngine/src/org/anddev/andengine/entity/particle/modifier/BaseTripleValueSpanModifier.java +++ b/AndEngine/src/org/anddev/andengine/entity/particle/modifier/BaseTripleValueSpanModifier.java @@ -10,65 +10,65 @@ * @since 15:19:46 - 29.06.2010 */ public abstract class BaseTripleValueSpanModifier extends BaseDoubleValueSpanModifier { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - private final float mFromValueC; - private final float mToValueC; + private final float mFromValueC; + private final float mToValueC; - private final float mSpanValueC; + private final float mSpanValueC; - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - public BaseTripleValueSpanModifier(final float pFromValueA, final float pToValueA, final float pFromValueB, final float pToValueB, final float pFromValueC, final float pToValueC, final float pFromTime, final float pToTime) { - super(pFromValueA, pToValueA, pFromValueB, pToValueB, pFromTime, pToTime); - this.mFromValueC = pFromValueC; - this.mToValueC = pToValueC; + public BaseTripleValueSpanModifier(final float pFromValueA, final float pToValueA, final float pFromValueB, final float pToValueB, final float pFromValueC, final float pToValueC, final float pFromTime, final float pToTime) { + super(pFromValueA, pToValueA, pFromValueB, pToValueB, pFromTime, pToTime); + this.mFromValueC = pFromValueC; + this.mToValueC = pToValueC; - this.mSpanValueC = this.mToValueC - this.mFromValueC; - } + this.mSpanValueC = this.mToValueC - this.mFromValueC; + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - protected abstract void onSetInitialValues(final Particle pParticle, final float pValueA, final float pValueB, final float pValueC); - protected abstract void onSetValues(final Particle pParticle, final float pValueA, final float pValueB, final float pValueC); + protected abstract void onSetInitialValues(final Particle pParticle, final float pValueA, final float pValueB, final float pValueC); + protected abstract void onSetValues(final Particle pParticle, final float pValueA, final float pValueB, final float pValueC); - @Override - @Deprecated - protected void onSetValues(final Particle pParticle, final float pValueA, final float pValueB) { } + @Override + @Deprecated + protected void onSetValues(final Particle pParticle, final float pValueA, final float pValueB) { } - @Override - public void onSetInitialValues(final Particle pParticle, final float pValueA, final float pValueB) { - this.onSetInitialValues(pParticle, pValueA, pValueB, this.mFromValueC); - } + @Override + public void onSetInitialValues(final Particle pParticle, final float pValueA, final float pValueB) { + this.onSetInitialValues(pParticle, pValueA, pValueB, this.mFromValueC); + } - @Override - protected void onSetValueInternal(final Particle pParticle, final float pPercent) { - this.onSetValues(pParticle, super.calculateValue(pPercent), super.calculateValueB(pPercent), this.calculateValueC(pPercent)); - } + @Override + protected void onSetValueInternal(final Particle pParticle, final float pPercent) { + this.onSetValues(pParticle, super.calculateValue(pPercent), super.calculateValueB(pPercent), this.calculateValueC(pPercent)); + } - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - private final float calculateValueC(final float pPercent) { - return this.mFromValueC + this.mSpanValueC * pPercent; - } + private final float calculateValueC(final float pPercent) { + return this.mFromValueC + this.mSpanValueC * pPercent; + } - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/entity/particle/modifier/ColorModifier.java b/AndEngine/src/org/anddev/andengine/entity/particle/modifier/ColorModifier.java index 8f747cbb..dc3dd01f 100644 --- a/AndEngine/src/org/anddev/andengine/entity/particle/modifier/ColorModifier.java +++ b/AndEngine/src/org/anddev/andengine/entity/particle/modifier/ColorModifier.java @@ -10,45 +10,45 @@ * @since 15:22:26 - 29.06.2010 */ public class ColorModifier extends BaseTripleValueSpanModifier { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - // =========================================================== - // Constructors - // =========================================================== - - public ColorModifier(final float pFromRed, final float pToRed, final float pFromGreen, final float pToGreen, final float pFromBlue, final float pToBlue, final float pFromTime, final float pToTime) { - super(pFromRed, pToRed, pFromGreen, pToGreen, pFromBlue, pToBlue, pFromTime, pToTime); - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - protected void onSetInitialValues(final Particle pParticle, final float pRed, final float pGreen, final float pBlue) { - pParticle.setColor(pRed, pGreen, pBlue); - } - - @Override - protected void onSetValues(final Particle pParticle, final float pRed, final float pGreen, final float pBlue) { - pParticle.setColor(pRed, pGreen, pBlue); - } - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + // =========================================================== + // Constructors + // =========================================================== + + public ColorModifier(final float pFromRed, final float pToRed, final float pFromGreen, final float pToGreen, final float pFromBlue, final float pToBlue, final float pFromTime, final float pToTime) { + super(pFromRed, pToRed, pFromGreen, pToGreen, pFromBlue, pToBlue, pFromTime, pToTime); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + protected void onSetInitialValues(final Particle pParticle, final float pRed, final float pGreen, final float pBlue) { + pParticle.setColor(pRed, pGreen, pBlue); + } + + @Override + protected void onSetValues(final Particle pParticle, final float pRed, final float pGreen, final float pBlue) { + pParticle.setColor(pRed, pGreen, pBlue); + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/entity/particle/modifier/ContainerExpireModifier.java b/AndEngine/src/org/anddev/andengine/entity/particle/modifier/ContainerExpireModifier.java index b8a270ee..8dfc4e4e 100644 --- a/AndEngine/src/org/anddev/andengine/entity/particle/modifier/ContainerExpireModifier.java +++ b/AndEngine/src/org/anddev/andengine/entity/particle/modifier/ContainerExpireModifier.java @@ -17,70 +17,70 @@ * @since 21:01:00 - 08.08.2011 */ public class ContainerExpireModifier extends ExpireModifier { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - private final List mModifiers = new ArrayList(); + private final List mModifiers = new ArrayList(); - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - public ContainerExpireModifier(final float pLifeTime) { - super(pLifeTime); - } + public ContainerExpireModifier(final float pLifeTime) { + super(pLifeTime); + } - public ContainerExpireModifier(final float pMinLifeTime, final float pMaxLifeTime) { - super(pMinLifeTime, pMaxLifeTime); - } + public ContainerExpireModifier(final float pMinLifeTime, final float pMaxLifeTime) { + super(pMinLifeTime, pMaxLifeTime); + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override public void onUpdateParticle(final Particle pParticle) { - // Apply all the contained modifiers - for (final BaseSingleValueSpanModifier modifier : mModifiers) { - modifier.onUpdateParticle(pParticle, pParticle.getDeathTime()); - } + // Apply all the contained modifiers + for (final BaseSingleValueSpanModifier modifier : mModifiers) { + modifier.onUpdateParticle(pParticle, pParticle.getDeathTime()); + } } - // =========================================================== - // Methods - // =========================================================== - - /** - *

Adds the specified modifier to the contained modifier list.

- * - *

The toTime in the modifier will be ignored, and replaced with the actual - * lifetime of the {@link Particle}.

- * - * @param pModifier The modifier to add - */ - public void addParticleModifier(final BaseSingleValueSpanModifier pModifier) { - mModifiers.add(pModifier); - } - - /** - *

Removes the specified modifier from the contained modifier list.

- * @param pModifier The modifier to remove - * @return true if the list was modified by this operation, false otherwise. - */ - public boolean removeParticleModifier(final BaseSingleValueSpanModifier pModifier) { - return mModifiers.remove(pModifier); - } + // =========================================================== + // Methods + // =========================================================== + + /** + *

Adds the specified modifier to the contained modifier list.

+ * + *

The toTime in the modifier will be ignored, and replaced with the actual + * lifetime of the {@link Particle}.

+ * + * @param pModifier The modifier to add + */ + public void addParticleModifier(final BaseSingleValueSpanModifier pModifier) { + mModifiers.add(pModifier); + } + + /** + *

Removes the specified modifier from the contained modifier list.

+ * @param pModifier The modifier to remove + * @return true if the list was modified by this operation, false otherwise. + */ + public boolean removeParticleModifier(final BaseSingleValueSpanModifier pModifier) { + return mModifiers.remove(pModifier); + } - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/entity/particle/modifier/ExpireModifier.java b/AndEngine/src/org/anddev/andengine/entity/particle/modifier/ExpireModifier.java index 6c1be967..52161410 100644 --- a/AndEngine/src/org/anddev/andengine/entity/particle/modifier/ExpireModifier.java +++ b/AndEngine/src/org/anddev/andengine/entity/particle/modifier/ExpireModifier.java @@ -12,71 +12,71 @@ * @since 21:21:10 - 14.03.2010 */ public class ExpireModifier implements IParticleModifier { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - private float mMinLifeTime; - private float mMaxLifeTime; + private float mMinLifeTime; + private float mMaxLifeTime; - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - public ExpireModifier(final float pLifeTime) { - this(pLifeTime, pLifeTime); - } + public ExpireModifier(final float pLifeTime) { + this(pLifeTime, pLifeTime); + } - public ExpireModifier(final float pMinLifeTime, final float pMaxLifeTime) { - this.mMinLifeTime = pMinLifeTime; - this.mMaxLifeTime = pMaxLifeTime; - } + public ExpireModifier(final float pMinLifeTime, final float pMaxLifeTime) { + this.mMinLifeTime = pMinLifeTime; + this.mMaxLifeTime = pMaxLifeTime; + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - public float getMinLifeTime() { - return this.mMinLifeTime; - } + public float getMinLifeTime() { + return this.mMinLifeTime; + } - public float getMaxLifeTime() { - return this.mMaxLifeTime; - } + public float getMaxLifeTime() { + return this.mMaxLifeTime; + } - public void setLifeTime(final float pLifeTime) { - this.mMinLifeTime = pLifeTime; - this.mMaxLifeTime = pLifeTime; - } + public void setLifeTime(final float pLifeTime) { + this.mMinLifeTime = pLifeTime; + this.mMaxLifeTime = pLifeTime; + } - public void setLifeTime(final float pMinLifeTime, final float pMaxLifeTime) { - this.mMinLifeTime = pMinLifeTime; - this.mMaxLifeTime = pMaxLifeTime; - } + public void setLifeTime(final float pMinLifeTime, final float pMaxLifeTime) { + this.mMinLifeTime = pMinLifeTime; + this.mMaxLifeTime = pMaxLifeTime; + } - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - @Override - public void onInitializeParticle(final Particle pParticle) { - pParticle.setDeathTime(RANDOM.nextFloat() * (this.mMaxLifeTime - this.mMinLifeTime) + this.mMinLifeTime); - } + @Override + public void onInitializeParticle(final Particle pParticle) { + pParticle.setDeathTime(RANDOM.nextFloat() * (this.mMaxLifeTime - this.mMinLifeTime) + this.mMinLifeTime); + } - @Override - public void onUpdateParticle(final Particle pParticle) { + @Override + public void onUpdateParticle(final Particle pParticle) { - } + } - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/entity/particle/modifier/IParticleModifier.java b/AndEngine/src/org/anddev/andengine/entity/particle/modifier/IParticleModifier.java index 2be9f909..d2e63e90 100644 --- a/AndEngine/src/org/anddev/andengine/entity/particle/modifier/IParticleModifier.java +++ b/AndEngine/src/org/anddev/andengine/entity/particle/modifier/IParticleModifier.java @@ -11,13 +11,13 @@ * @since 20:06:05 - 14.03.2010 */ public interface IParticleModifier extends IParticleInitializer { - // =========================================================== - // Final Fields - // =========================================================== + // =========================================================== + // Final Fields + // =========================================================== - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - public void onUpdateParticle(final Particle pParticle); + public void onUpdateParticle(final Particle pParticle); } diff --git a/AndEngine/src/org/anddev/andengine/entity/particle/modifier/OffCameraExpireModifier.java b/AndEngine/src/org/anddev/andengine/entity/particle/modifier/OffCameraExpireModifier.java index cde70e4c..48f34ff9 100644 --- a/AndEngine/src/org/anddev/andengine/entity/particle/modifier/OffCameraExpireModifier.java +++ b/AndEngine/src/org/anddev/andengine/entity/particle/modifier/OffCameraExpireModifier.java @@ -12,53 +12,53 @@ * @since 21:21:10 - 14.03.2010 */ public class OffCameraExpireModifier implements IParticleModifier { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - private final Camera mCamera; + private final Camera mCamera; - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - public OffCameraExpireModifier(final Camera pCamera) { - this.mCamera = pCamera; - } + public OffCameraExpireModifier(final Camera pCamera) { + this.mCamera = pCamera; + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - public Camera getCamera() { - return this.mCamera; - } + public Camera getCamera() { + return this.mCamera; + } - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - @Override - public void onInitializeParticle(final Particle pParticle) { + @Override + public void onInitializeParticle(final Particle pParticle) { - } + } - @Override - public void onUpdateParticle(final Particle pParticle) { - if(!this.mCamera.isRectangularShapeVisible(pParticle)) { - pParticle.setDead(true); - } - } + @Override + public void onUpdateParticle(final Particle pParticle) { + if(!this.mCamera.isRectangularShapeVisible(pParticle)) { + pParticle.setDead(true); + } + } - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/entity/particle/modifier/RotationModifier.java b/AndEngine/src/org/anddev/andengine/entity/particle/modifier/RotationModifier.java index 82794017..98d36169 100644 --- a/AndEngine/src/org/anddev/andengine/entity/particle/modifier/RotationModifier.java +++ b/AndEngine/src/org/anddev/andengine/entity/particle/modifier/RotationModifier.java @@ -10,45 +10,45 @@ * @since 10:36:18 - 29.06.2010 */ public class RotationModifier extends BaseSingleValueSpanModifier { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - // =========================================================== - // Constructors - // =========================================================== - - public RotationModifier(final float pFromRotation, final float pToRotation, final float pFromTime, final float pToTime) { - super(pFromRotation, pToRotation, pFromTime, pToTime); - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - protected void onSetInitialValue(final Particle pParticle, final float pRotation) { - pParticle.setRotation(pRotation); - } - - @Override - protected void onSetValue(final Particle pParticle, final float pRotation) { - pParticle.setRotation(pRotation); - } - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + // =========================================================== + // Constructors + // =========================================================== + + public RotationModifier(final float pFromRotation, final float pToRotation, final float pFromTime, final float pToTime) { + super(pFromRotation, pToRotation, pFromTime, pToTime); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + protected void onSetInitialValue(final Particle pParticle, final float pRotation) { + pParticle.setRotation(pRotation); + } + + @Override + protected void onSetValue(final Particle pParticle, final float pRotation) { + pParticle.setRotation(pRotation); + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/entity/particle/modifier/ScaleModifier.java b/AndEngine/src/org/anddev/andengine/entity/particle/modifier/ScaleModifier.java index cdcafa0c..a6a1f640 100644 --- a/AndEngine/src/org/anddev/andengine/entity/particle/modifier/ScaleModifier.java +++ b/AndEngine/src/org/anddev/andengine/entity/particle/modifier/ScaleModifier.java @@ -10,49 +10,49 @@ * @since 20:37:27 - 04.05.2010 */ public class ScaleModifier extends BaseDoubleValueSpanModifier { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - // =========================================================== - // Constructors - // =========================================================== - - public ScaleModifier(final float pFromScale, final float pToScale, final float pFromTime, final float pToTime) { - this(pFromScale, pToScale, pFromScale, pToScale, pFromTime, pToTime); - } - - public ScaleModifier(final float pFromScaleX, final float pToScaleX, final float pFromScaleY, final float pToScaleY, final float pFromTime, final float pToTime) { - super(pFromScaleX, pToScaleX, pFromScaleY, pToScaleY, pFromTime, pToTime); - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - protected void onSetInitialValues(final Particle pParticle, final float pScaleX, final float pScaleY) { - pParticle.setScale(pScaleX, pScaleY); - } - - @Override - protected void onSetValues(final Particle pParticle, final float pScaleX, final float pScaleY) { - pParticle.setScale(pScaleX, pScaleY); - } - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + // =========================================================== + // Constructors + // =========================================================== + + public ScaleModifier(final float pFromScale, final float pToScale, final float pFromTime, final float pToTime) { + this(pFromScale, pToScale, pFromScale, pToScale, pFromTime, pToTime); + } + + public ScaleModifier(final float pFromScaleX, final float pToScaleX, final float pFromScaleY, final float pToScaleY, final float pFromTime, final float pToTime) { + super(pFromScaleX, pToScaleX, pFromScaleY, pToScaleY, pFromTime, pToTime); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + protected void onSetInitialValues(final Particle pParticle, final float pScaleX, final float pScaleY) { + pParticle.setScale(pScaleX, pScaleY); + } + + @Override + protected void onSetValues(final Particle pParticle, final float pScaleX, final float pScaleY) { + pParticle.setScale(pScaleX, pScaleY); + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/entity/primitive/BaseRectangle.java b/AndEngine/src/org/anddev/andengine/entity/primitive/BaseRectangle.java index fff5e842..de16ed30 100644 --- a/AndEngine/src/org/anddev/andengine/entity/primitive/BaseRectangle.java +++ b/AndEngine/src/org/anddev/andengine/entity/primitive/BaseRectangle.java @@ -13,50 +13,50 @@ * @since 19:05:49 - 11.04.2010 */ public abstract class BaseRectangle extends RectangularShape { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - // =========================================================== - // Constructors - // =========================================================== - - public BaseRectangle(final float pX, final float pY, final float pWidth, final float pHeight) { - super(pX, pY, pWidth, pHeight, new RectangleVertexBuffer(GL11.GL_STATIC_DRAW, true)); - this.updateVertexBuffer(); - } - - public BaseRectangle(final float pX, final float pY, final float pWidth, final float pHeight, final RectangleVertexBuffer pRectangleVertexBuffer) { - super(pX, pY, pWidth, pHeight, pRectangleVertexBuffer); - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - public RectangleVertexBuffer getVertexBuffer() { - return (RectangleVertexBuffer)this.mVertexBuffer; - } - - @Override - protected void onUpdateVertexBuffer(){ - this.getVertexBuffer().update(this.mWidth, this.mHeight); - } - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + // =========================================================== + // Constructors + // =========================================================== + + public BaseRectangle(final float pX, final float pY, final float pWidth, final float pHeight) { + super(pX, pY, pWidth, pHeight, new RectangleVertexBuffer(GL11.GL_STATIC_DRAW, true)); + this.updateVertexBuffer(); + } + + public BaseRectangle(final float pX, final float pY, final float pWidth, final float pHeight, final RectangleVertexBuffer pRectangleVertexBuffer) { + super(pX, pY, pWidth, pHeight, pRectangleVertexBuffer); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + public RectangleVertexBuffer getVertexBuffer() { + return (RectangleVertexBuffer)this.mVertexBuffer; + } + + @Override + protected void onUpdateVertexBuffer(){ + this.getVertexBuffer().update(this.mWidth, this.mHeight); + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/entity/primitive/Line.java b/AndEngine/src/org/anddev/andengine/entity/primitive/Line.java index 9aee53d4..63eb4957 100644 --- a/AndEngine/src/org/anddev/andengine/entity/primitive/Line.java +++ b/AndEngine/src/org/anddev/andengine/entity/primitive/Line.java @@ -20,216 +20,216 @@ * @since 09:50:36 - 04.04.2010 */ public class Line extends Shape { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - private static final float LINEWIDTH_DEFAULT = 1.0f; + private static final float LINEWIDTH_DEFAULT = 1.0f; - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - protected float mX2; - protected float mY2; + protected float mX2; + protected float mY2; - private float mLineWidth; + private float mLineWidth; - private final LineVertexBuffer mLineVertexBuffer; - - // =========================================================== - // Constructors - // =========================================================== - - public Line(final float pX1, final float pY1, final float pX2, final float pY2) { - this(pX1, pY1, pX2, pY2, LINEWIDTH_DEFAULT); - } - - public Line(final float pX1, final float pY1, final float pX2, final float pY2, final float pLineWidth) { - super(pX1, pY1); - - this.mX2 = pX2; - this.mY2 = pY2; + private final LineVertexBuffer mLineVertexBuffer; + + // =========================================================== + // Constructors + // =========================================================== + + public Line(final float pX1, final float pY1, final float pX2, final float pY2) { + this(pX1, pY1, pX2, pY2, LINEWIDTH_DEFAULT); + } + + public Line(final float pX1, final float pY1, final float pX2, final float pY2, final float pLineWidth) { + super(pX1, pY1); + + this.mX2 = pX2; + this.mY2 = pY2; - this.mLineWidth = pLineWidth; + this.mLineWidth = pLineWidth; - this.mLineVertexBuffer = new LineVertexBuffer(GL11.GL_STATIC_DRAW, true); - this.updateVertexBuffer(); + this.mLineVertexBuffer = new LineVertexBuffer(GL11.GL_STATIC_DRAW, true); + this.updateVertexBuffer(); - final float width = this.getWidth(); - final float height = this.getHeight(); + final float width = this.getWidth(); + final float height = this.getHeight(); - this.mRotationCenterX = width * 0.5f; - this.mRotationCenterY = height * 0.5f; + this.mRotationCenterX = width * 0.5f; + this.mRotationCenterY = height * 0.5f; - this.mScaleCenterX = this.mRotationCenterX; - this.mScaleCenterY = this.mRotationCenterY; - } + this.mScaleCenterX = this.mRotationCenterX; + this.mScaleCenterY = this.mRotationCenterY; + } - // =========================================================== - // Getter & Setter - // =========================================================== - - /** - * @deprecated Instead use {@link Line#getX1()} or {@link Line#getX2()}. - */ - @Deprecated - @Override - public float getX() { - return super.getX(); - } - - /** - * @deprecatedInstead use {@link Line#getY1()} or {@link Line#getY2()}. - */ - @Deprecated - @Override - public float getY() { - return super.getY(); - } - - public float getX1() { - return super.getX(); - } - - public float getY1() { - return super.getY(); - } - - public float getX2() { - return this.mX2; - } - - public float getY2() { - return this.mY2; - } - - public float getLineWidth() { - return this.mLineWidth; - } - - public void setLineWidth(final float pLineWidth) { - this.mLineWidth = pLineWidth; - } - - @Override - public float getBaseHeight() { - return this.mY2 - this.mY; - } - - @Override - public float getBaseWidth() { - return this.mX2 - this.mX; - } - - @Override - public float getHeight() { - return this.mY2 - this.mY; - } - - @Override - public float getWidth() { - return this.mX2 - this.mX; - } - - /** - * @deprecated Instead use {@link Line#setPosition(float, float, float, float)}. - */ - @Deprecated - @Override - 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; - } - - public void setPosition(final float pX1, final float pY1, final float pX2, final float pY2) { - this.mX2 = pX2; - this.mY2 = pY2; - - super.setPosition(pX1, pY1); - - this.updateVertexBuffer(); - } - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - protected boolean isCulled(final Camera pCamera) { - return pCamera.isLineVisible(this); - } - - @Override - protected void onInitDraw(final GL10 pGL) { - super.onInitDraw(pGL); - GLHelper.disableTextures(pGL); - GLHelper.disableTexCoordArray(pGL); - GLHelper.lineWidth(pGL, this.mLineWidth); - } - - @Override - public LineVertexBuffer getVertexBuffer() { - return this.mLineVertexBuffer; - } - - @Override - protected void onUpdateVertexBuffer() { - this.mLineVertexBuffer.update(0, 0, this.mX2 - this.mX, this.mY2 - this.mY); - } - - @Override - protected void drawVertices(final GL10 pGL, final Camera pCamera) { - pGL.glDrawArrays(GL10.GL_LINES, 0, LineVertexBuffer.VERTICES_PER_LINE); - } - - @Override - public float[] getSceneCenterCoordinates() { - return null; // TODO - // return convertLocalToSceneCoordinates(this, (this.mX + this.mX2) * 0.5f, (this.mY + this.mY2) * 0.5f); - } - - @Override - @Deprecated - public boolean contains(final float pX, final float pY) { - return false; - } - - @Override - @Deprecated - public float[] convertSceneToLocalCoordinates(final float pX, final float pY) { - return null; - } - - @Override - @Deprecated - public float[] convertLocalToSceneCoordinates(final float pX, final float pY) { - return null; - } - - @Override - public boolean collidesWith(final IShape pOtherShape) { - if(pOtherShape instanceof Line) { - final Line otherLine = (Line) pOtherShape; - return LineCollisionChecker.checkLineCollision(this.mX, this.mY, this.mX2, this.mY2, otherLine.mX, otherLine.mY, otherLine.mX2, otherLine.mY2); - } else if(pOtherShape instanceof RectangularShape) { - final RectangularShape rectangularShape = (RectangularShape) pOtherShape; - return RectangularShapeCollisionChecker.checkCollision(rectangularShape, this); - } else { - return false; - } - } - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== + + /** + * @deprecated Instead use {@link Line#getX1()} or {@link Line#getX2()}. + */ + @Deprecated + @Override + public float getX() { + return super.getX(); + } + + /** + * @deprecatedInstead use {@link Line#getY1()} or {@link Line#getY2()}. + */ + @Deprecated + @Override + public float getY() { + return super.getY(); + } + + public float getX1() { + return super.getX(); + } + + public float getY1() { + return super.getY(); + } + + public float getX2() { + return this.mX2; + } + + public float getY2() { + return this.mY2; + } + + public float getLineWidth() { + return this.mLineWidth; + } + + public void setLineWidth(final float pLineWidth) { + this.mLineWidth = pLineWidth; + } + + @Override + public float getBaseHeight() { + return this.mY2 - this.mY; + } + + @Override + public float getBaseWidth() { + return this.mX2 - this.mX; + } + + @Override + public float getHeight() { + return this.mY2 - this.mY; + } + + @Override + public float getWidth() { + return this.mX2 - this.mX; + } + + /** + * @deprecated Instead use {@link Line#setPosition(float, float, float, float)}. + */ + @Deprecated + @Override + 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; + } + + public void setPosition(final float pX1, final float pY1, final float pX2, final float pY2) { + this.mX2 = pX2; + this.mY2 = pY2; + + super.setPosition(pX1, pY1); + + this.updateVertexBuffer(); + } + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + protected boolean isCulled(final Camera pCamera) { + return pCamera.isLineVisible(this); + } + + @Override + protected void onInitDraw(final GL10 pGL) { + super.onInitDraw(pGL); + GLHelper.disableTextures(pGL); + GLHelper.disableTexCoordArray(pGL); + GLHelper.lineWidth(pGL, this.mLineWidth); + } + + @Override + public LineVertexBuffer getVertexBuffer() { + return this.mLineVertexBuffer; + } + + @Override + protected void onUpdateVertexBuffer() { + this.mLineVertexBuffer.update(0, 0, this.mX2 - this.mX, this.mY2 - this.mY); + } + + @Override + protected void drawVertices(final GL10 pGL, final Camera pCamera) { + pGL.glDrawArrays(GL10.GL_LINES, 0, LineVertexBuffer.VERTICES_PER_LINE); + } + + @Override + public float[] getSceneCenterCoordinates() { + return null; // TODO + // return convertLocalToSceneCoordinates(this, (this.mX + this.mX2) * 0.5f, (this.mY + this.mY2) * 0.5f); + } + + @Override + @Deprecated + public boolean contains(final float pX, final float pY) { + return false; + } + + @Override + @Deprecated + public float[] convertSceneToLocalCoordinates(final float pX, final float pY) { + return null; + } + + @Override + @Deprecated + public float[] convertLocalToSceneCoordinates(final float pX, final float pY) { + return null; + } + + @Override + public boolean collidesWith(final IShape pOtherShape) { + if(pOtherShape instanceof Line) { + final Line otherLine = (Line) pOtherShape; + return LineCollisionChecker.checkLineCollision(this.mX, this.mY, this.mX2, this.mY2, otherLine.mX, otherLine.mY, otherLine.mX2, otherLine.mY2); + } else if(pOtherShape instanceof RectangularShape) { + final RectangularShape rectangularShape = (RectangularShape) pOtherShape; + return RectangularShapeCollisionChecker.checkCollision(rectangularShape, this); + } else { + return false; + } + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/entity/primitive/Rectangle.java b/AndEngine/src/org/anddev/andengine/entity/primitive/Rectangle.java index d2a05abd..c36d68df 100644 --- a/AndEngine/src/org/anddev/andengine/entity/primitive/Rectangle.java +++ b/AndEngine/src/org/anddev/andengine/entity/primitive/Rectangle.java @@ -13,46 +13,46 @@ * @since 12:18:49 - 13.03.2010 */ public class Rectangle extends BaseRectangle { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - // =========================================================== - // Constructors - // =========================================================== - - public Rectangle(final float pX, final float pY, final float pWidth, final float pHeight) { - super(pX, pY, pWidth, pHeight); - } - - public Rectangle(final float pX, final float pY, final float pWidth, final float pHeight, final RectangleVertexBuffer pRectangleVertexBuffer) { - super(pX, pY, pWidth, pHeight, pRectangleVertexBuffer); - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - protected void onInitDraw(final GL10 pGL) { - super.onInitDraw(pGL); - GLHelper.disableTextures(pGL); - GLHelper.disableTexCoordArray(pGL); - } - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + // =========================================================== + // Constructors + // =========================================================== + + public Rectangle(final float pX, final float pY, final float pWidth, final float pHeight) { + super(pX, pY, pWidth, pHeight); + } + + public Rectangle(final float pX, final float pY, final float pWidth, final float pHeight, final RectangleVertexBuffer pRectangleVertexBuffer) { + super(pX, pY, pWidth, pHeight, pRectangleVertexBuffer); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + protected void onInitDraw(final GL10 pGL) { + super.onInitDraw(pGL); + GLHelper.disableTextures(pGL); + GLHelper.disableTexCoordArray(pGL); + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/entity/scene/CameraScene.java b/AndEngine/src/org/anddev/andengine/entity/scene/CameraScene.java index a0b6a7d8..50c562d6 100644 --- a/AndEngine/src/org/anddev/andengine/entity/scene/CameraScene.java +++ b/AndEngine/src/org/anddev/andengine/entity/scene/CameraScene.java @@ -14,114 +14,114 @@ * @since 15:35:53 - 29.03.2010 */ public class CameraScene extends Scene { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - protected Camera mCamera; - - // =========================================================== - // Constructors - // =========================================================== - - /** - * {@link CameraScene#setCamera(Camera)} needs to be called manually. Otherwise nothing will be drawn. - */ - public CameraScene() { - this(null); - } - - public CameraScene(final Camera pCamera) { - this.mCamera = pCamera; - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - public Camera getCamera() { - return this.mCamera; - } - - public void setCamera(final Camera pCamera) { - this.mCamera = pCamera; - } - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - public boolean onSceneTouchEvent(final TouchEvent pSceneTouchEvent) { - if(this.mCamera == null) { - return false; - } else { - this.mCamera.convertSceneToCameraSceneTouchEvent(pSceneTouchEvent); - - final boolean handled = super.onSceneTouchEvent(pSceneTouchEvent); - - if(handled) { - return true; - } else { - this.mCamera.convertCameraSceneToSceneTouchEvent(pSceneTouchEvent); - return false; - } - } - } - - @Override - protected boolean onChildSceneTouchEvent(final TouchEvent pSceneTouchEvent) { - final boolean childIsCameraScene = this.mChildScene instanceof CameraScene; - if(childIsCameraScene) { - this.mCamera.convertCameraSceneToSceneTouchEvent(pSceneTouchEvent); - final boolean result = super.onChildSceneTouchEvent(pSceneTouchEvent); - this.mCamera.convertSceneToCameraSceneTouchEvent(pSceneTouchEvent); - return result; - } else { - return super.onChildSceneTouchEvent(pSceneTouchEvent); - } - } - - @Override - protected void onManagedDraw(final GL10 pGL, final Camera pCamera) { - if(this.mCamera != null) { - pGL.glMatrixMode(GL10.GL_PROJECTION); - this.mCamera.onApplyCameraSceneMatrix(pGL); - { - pGL.glMatrixMode(GL10.GL_MODELVIEW); - pGL.glPushMatrix(); - pGL.glLoadIdentity(); - - super.onManagedDraw(pGL, pCamera); - - pGL.glPopMatrix(); - } - pGL.glMatrixMode(GL10.GL_PROJECTION); - } - } - - // =========================================================== - // Methods - // =========================================================== - - public void centerShapeInCamera(final Shape pShape) { - final Camera camera = this.mCamera; - pShape.setPosition((camera.getWidth() - pShape.getWidth()) * 0.5f, (camera.getHeight() - pShape.getHeight()) * 0.5f); - } - - public void centerShapeInCameraHorizontally(final Shape pShape) { - pShape.setPosition((this.mCamera.getWidth() - pShape.getWidth()) * 0.5f, pShape.getY()); - } - - public void centerShapeInCameraVertically(final Shape pShape) { - pShape.setPosition(pShape.getX(), (this.mCamera.getHeight() - pShape.getHeight()) * 0.5f); - } - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + protected Camera mCamera; + + // =========================================================== + // Constructors + // =========================================================== + + /** + * {@link CameraScene#setCamera(Camera)} needs to be called manually. Otherwise nothing will be drawn. + */ + public CameraScene() { + this(null); + } + + public CameraScene(final Camera pCamera) { + this.mCamera = pCamera; + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + public Camera getCamera() { + return this.mCamera; + } + + public void setCamera(final Camera pCamera) { + this.mCamera = pCamera; + } + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + public boolean onSceneTouchEvent(final TouchEvent pSceneTouchEvent) { + if(this.mCamera == null) { + return false; + } else { + this.mCamera.convertSceneToCameraSceneTouchEvent(pSceneTouchEvent); + + final boolean handled = super.onSceneTouchEvent(pSceneTouchEvent); + + if(handled) { + return true; + } else { + this.mCamera.convertCameraSceneToSceneTouchEvent(pSceneTouchEvent); + return false; + } + } + } + + @Override + protected boolean onChildSceneTouchEvent(final TouchEvent pSceneTouchEvent) { + final boolean childIsCameraScene = this.mChildScene instanceof CameraScene; + if(childIsCameraScene) { + this.mCamera.convertCameraSceneToSceneTouchEvent(pSceneTouchEvent); + final boolean result = super.onChildSceneTouchEvent(pSceneTouchEvent); + this.mCamera.convertSceneToCameraSceneTouchEvent(pSceneTouchEvent); + return result; + } else { + return super.onChildSceneTouchEvent(pSceneTouchEvent); + } + } + + @Override + protected void onManagedDraw(final GL10 pGL, final Camera pCamera) { + if(this.mCamera != null) { + pGL.glMatrixMode(GL10.GL_PROJECTION); + this.mCamera.onApplyCameraSceneMatrix(pGL); + { + pGL.glMatrixMode(GL10.GL_MODELVIEW); + pGL.glPushMatrix(); + pGL.glLoadIdentity(); + + super.onManagedDraw(pGL, pCamera); + + pGL.glPopMatrix(); + } + pGL.glMatrixMode(GL10.GL_PROJECTION); + } + } + + // =========================================================== + // Methods + // =========================================================== + + public void centerShapeInCamera(final Shape pShape) { + final Camera camera = this.mCamera; + pShape.setPosition((camera.getWidth() - pShape.getWidth()) * 0.5f, (camera.getHeight() - pShape.getHeight()) * 0.5f); + } + + public void centerShapeInCameraHorizontally(final Shape pShape) { + pShape.setPosition((this.mCamera.getWidth() - pShape.getWidth()) * 0.5f, pShape.getY()); + } + + public void centerShapeInCameraVertically(final Shape pShape) { + pShape.setPosition(pShape.getX(), (this.mCamera.getHeight() - pShape.getHeight()) * 0.5f); + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/entity/scene/Scene.java b/AndEngine/src/org/anddev/andengine/entity/scene/Scene.java index 4e82811d..15cab6e2 100644 --- a/AndEngine/src/org/anddev/andengine/entity/scene/Scene.java +++ b/AndEngine/src/org/anddev/andengine/entity/scene/Scene.java @@ -28,502 +28,502 @@ * @since 12:47:39 - 08.03.2010 */ public class Scene extends Entity { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - private static final int TOUCHAREAS_CAPACITY_DEFAULT = 4; + private static final int TOUCHAREAS_CAPACITY_DEFAULT = 4; - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - private float mSecondsElapsedTotal; + private float mSecondsElapsedTotal; - protected Scene mParentScene; - protected Scene mChildScene; - private boolean mChildSceneModalDraw; - private boolean mChildSceneModalUpdate; - private boolean mChildSceneModalTouch; + protected Scene mParentScene; + protected Scene mChildScene; + private boolean mChildSceneModalDraw; + private boolean mChildSceneModalUpdate; + private boolean mChildSceneModalTouch; - protected SmartList mTouchAreas = new SmartList(TOUCHAREAS_CAPACITY_DEFAULT); + protected SmartList mTouchAreas = new SmartList(TOUCHAREAS_CAPACITY_DEFAULT); - private final RunnableHandler mRunnableHandler = new RunnableHandler(); + private final RunnableHandler mRunnableHandler = new RunnableHandler(); - private IOnSceneTouchListener mOnSceneTouchListener; + private IOnSceneTouchListener mOnSceneTouchListener; - private IOnAreaTouchListener mOnAreaTouchListener; + private IOnAreaTouchListener mOnAreaTouchListener; - private IBackground mBackground = new ColorBackground(0, 0, 0); // Black - private boolean mBackgroundEnabled = true; + private IBackground mBackground = new ColorBackground(0, 0, 0); // Black + private boolean mBackgroundEnabled = true; - private boolean mOnAreaTouchTraversalBackToFront = true; + private boolean mOnAreaTouchTraversalBackToFront = true; - private boolean mTouchAreaBindingEnabled = false; - private final SparseArray mTouchAreaBindings = new SparseArray(); - private boolean mOnSceneTouchListenerBindingEnabled = false; - private final SparseArray mOnSceneTouchListenerBindings = new SparseArray(); + private boolean mTouchAreaBindingEnabled = false; + private final SparseArray mTouchAreaBindings = new SparseArray(); + private boolean mOnSceneTouchListenerBindingEnabled = false; + private final SparseArray mOnSceneTouchListenerBindings = new SparseArray(); - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - public Scene() { + public Scene() { - } + } - @Deprecated - public Scene(final int pChildCount) { - for(int i = 0; i < pChildCount; i++) { - this.attachChild(new Entity()); - } - } + @Deprecated + public Scene(final int pChildCount) { + for(int i = 0; i < pChildCount; i++) { + this.attachChild(new Entity()); + } + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - public float getSecondsElapsedTotal() { - return this.mSecondsElapsedTotal; - } - - public IBackground getBackground() { - return this.mBackground; - } - - public void setBackground(final IBackground pBackground) { - this.mBackground = pBackground; - } - - public boolean isBackgroundEnabled() { - return this.mBackgroundEnabled; - } - - public void setBackgroundEnabled(final boolean pEnabled) { - this.mBackgroundEnabled = pEnabled; - } - - public void setOnSceneTouchListener(final IOnSceneTouchListener pOnSceneTouchListener) { - this.mOnSceneTouchListener = pOnSceneTouchListener; - } - - public IOnSceneTouchListener getOnSceneTouchListener() { - return this.mOnSceneTouchListener; - } - - public boolean hasOnSceneTouchListener() { - return this.mOnSceneTouchListener != null; - } - - public void setOnAreaTouchListener(final IOnAreaTouchListener pOnAreaTouchListener) { - this.mOnAreaTouchListener = pOnAreaTouchListener; - } - - public IOnAreaTouchListener getOnAreaTouchListener() { - return this.mOnAreaTouchListener; - } - - public boolean hasOnAreaTouchListener() { - return this.mOnAreaTouchListener != null; - } - - private void setParentScene(final Scene pParentScene) { - this.mParentScene = pParentScene; - } - - public boolean hasChildScene() { - return this.mChildScene != null; - } - - public Scene getChildScene() { - return this.mChildScene; - } - - public void setChildSceneModal(final Scene pChildScene) { - this.setChildScene(pChildScene, true, true, true); - } - - public void setChildScene(final Scene pChildScene) { - this.setChildScene(pChildScene, false, false, false); - } - - public void setChildScene(final Scene pChildScene, final boolean pModalDraw, final boolean pModalUpdate, final boolean pModalTouch) { - pChildScene.setParentScene(this); - this.mChildScene = pChildScene; - this.mChildSceneModalDraw = pModalDraw; - this.mChildSceneModalUpdate = pModalUpdate; - this.mChildSceneModalTouch = pModalTouch; - } - - public void clearChildScene() { - this.mChildScene = null; - } - - public void setOnAreaTouchTraversalBackToFront() { - this.mOnAreaTouchTraversalBackToFront = true; - } - - public void setOnAreaTouchTraversalFrontToBack() { - this.mOnAreaTouchTraversalBackToFront = false; - } - - public boolean isTouchAreaBindingEnabled() { - return this.mTouchAreaBindingEnabled; - } - - /** - * Enable or disable the binding of TouchAreas to PointerIDs (fingers). - * When enabled: TouchAreas get bound to a PointerID (finger) when returning true in - * {@link Shape#onAreaTouched(TouchEvent, float, float)} or - * {@link IOnAreaTouchListener#onAreaTouched(TouchEvent, ITouchArea, float, float)} - * 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 pTouchAreaBindingEnabled - */ - public void setTouchAreaBindingEnabled(final boolean pTouchAreaBindingEnabled) { - if(this.mTouchAreaBindingEnabled && !pTouchAreaBindingEnabled) { - this.mTouchAreaBindings.clear(); - } - this.mTouchAreaBindingEnabled = pTouchAreaBindingEnabled; - } - - public boolean isOnSceneTouchListenerBindingEnabled() { - return this.mOnSceneTouchListenerBindingEnabled; - } - - /** - * Enable or disable the binding of TouchAreas to PointerIDs (fingers). - * When enabled: The OnSceneTouchListener gets bound to a PointerID (finger) when returning true in - * {@link Shape#onAreaTouched(TouchEvent, float, float)} or - * {@link IOnAreaTouchListener#onAreaTouched(TouchEvent, ITouchArea, float, float)} - * 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 pOnSceneTouchListenerBindingEnabled - */ - public void setOnSceneTouchListenerBindingEnabled(final boolean pOnSceneTouchListenerBindingEnabled) { - if(this.mOnSceneTouchListenerBindingEnabled && !pOnSceneTouchListenerBindingEnabled) { - this.mOnSceneTouchListenerBindings.clear(); - } - this.mOnSceneTouchListenerBindingEnabled = pOnSceneTouchListenerBindingEnabled; - } - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - protected void onManagedDraw(final GL10 pGL, final Camera pCamera) { - final Scene childScene = this.mChildScene; - - if(childScene == null || !this.mChildSceneModalDraw) { - if(this.mBackgroundEnabled) { - pCamera.onApplySceneBackgroundMatrix(pGL); - GLHelper.setModelViewIdentityMatrix(pGL); - - this.mBackground.onDraw(pGL, pCamera); - } - - pCamera.onApplySceneMatrix(pGL); - GLHelper.setModelViewIdentityMatrix(pGL); - - super.onManagedDraw(pGL, pCamera); - } - - if(childScene != null) { - childScene.onDraw(pGL, pCamera); - } - } - - @Override - protected void onManagedUpdate(final float pSecondsElapsed) { - this.mSecondsElapsedTotal += pSecondsElapsed; - - this.mRunnableHandler.onUpdate(pSecondsElapsed); - - final Scene childScene = this.mChildScene; - if(childScene == null || !this.mChildSceneModalUpdate) { - this.mBackground.onUpdate(pSecondsElapsed); - super.onManagedUpdate(pSecondsElapsed); - } - - if(childScene != null) { - childScene.onUpdate(pSecondsElapsed); - } - } - - public boolean onSceneTouchEvent(final TouchEvent pSceneTouchEvent) { - final int action = pSceneTouchEvent.getAction(); - final boolean isActionDown = pSceneTouchEvent.isActionDown(); - - if(!isActionDown) { - if(this.mOnSceneTouchListenerBindingEnabled) { - final IOnSceneTouchListener boundOnSceneTouchListener = this.mOnSceneTouchListenerBindings.get(pSceneTouchEvent.getPointerID()); - if (boundOnSceneTouchListener != null) { - /* Check if boundTouchArea needs to be removed. */ - 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) { - return true; - } - } - } - if(this.mTouchAreaBindingEnabled) { - 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) { - final float sceneTouchEventX = pSceneTouchEvent.getX(); - final float sceneTouchEventY = pSceneTouchEvent.getY(); - - /* Check if boundTouchArea needs to be removed. */ - 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) { - return true; - } - } - } - } - - final Scene childScene = this.mChildScene; - if(childScene != null) { - final boolean handledByChild = this.onChildSceneTouchEvent(pSceneTouchEvent); - if(handledByChild) { - return true; - } else if(this.mChildSceneModalTouch) { - return false; - } - } - - final float sceneTouchEventX = pSceneTouchEvent.getX(); - final float sceneTouchEventY = pSceneTouchEvent.getY(); - - final ArrayList touchAreas = this.mTouchAreas; - if(touchAreas != null) { - final int touchAreaCount = touchAreas.size(); - if(touchAreaCount > 0) { - if(this.mOnAreaTouchTraversalBackToFront) { /* Back to Front. */ - for(int i = 0; i < touchAreaCount; i++) { - final ITouchArea touchArea = touchAreas.get(i); - if (touchArea != null && touchArea.contains(sceneTouchEventX, sceneTouchEventY)) { - final Boolean handled = this.onAreaTouchEvent(pSceneTouchEvent, sceneTouchEventX, sceneTouchEventY, touchArea); - 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.mTouchAreaBindingEnabled && isActionDown) { - this.mTouchAreaBindings.put(pSceneTouchEvent.getPointerID(), touchArea); - } - return true; - } - } - } - } else { /* Front to back. */ - for(int i = touchAreaCount - 1; i >= 0; i--) { - final ITouchArea touchArea = touchAreas.get(i); - if(touchArea.contains(sceneTouchEventX, sceneTouchEventY)) { - final Boolean handled = this.onAreaTouchEvent(pSceneTouchEvent, sceneTouchEventX, sceneTouchEventY, touchArea); - 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.mTouchAreaBindingEnabled && isActionDown) { - this.mTouchAreaBindings.put(pSceneTouchEvent.getPointerID(), touchArea); - } - return true; - } - } - } - } - } - } - /* If no area was touched, the Scene itself was touched as a fallback. */ - if(this.mOnSceneTouchListener != null){ - final Boolean handled = this.mOnSceneTouchListener.onSceneTouchEvent(this, pSceneTouchEvent); - 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.mOnSceneTouchListenerBindingEnabled && isActionDown) { - this.mOnSceneTouchListenerBindings.put(pSceneTouchEvent.getPointerID(), this.mOnSceneTouchListener); - } - return true; - } else { - return false; - } - } else { - return false; - } - } - - private Boolean onAreaTouchEvent(final TouchEvent pSceneTouchEvent, final float sceneTouchEventX, final float sceneTouchEventY, final ITouchArea touchArea) { - final float[] touchAreaLocalCoordinates = touchArea.convertSceneToLocalCoordinates(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) { - return Boolean.TRUE; - } else if(this.mOnAreaTouchListener != null) { - return this.mOnAreaTouchListener.onAreaTouched(pSceneTouchEvent, touchArea, touchAreaLocalX, touchAreaLocalY); - } else { - return null; - } - } - - protected boolean onChildSceneTouchEvent(final TouchEvent pSceneTouchEvent) { - return this.mChildScene.onSceneTouchEvent(pSceneTouchEvent); - } - - @Override - public void reset() { - super.reset(); - - this.clearChildScene(); - } - - @Override - public void setParent(final IEntity pEntity) { - // super.setParent(pEntity); - } - - // =========================================================== - // Methods - // =========================================================== - - public void postRunnable(final Runnable pRunnable) { - this.mRunnableHandler.postRunnable(pRunnable); - } - - public void registerTouchArea(final ITouchArea pTouchArea) { - this.mTouchAreas.add(pTouchArea); - } - - public boolean unregisterTouchArea(final ITouchArea pTouchArea) { - return this.mTouchAreas.remove(pTouchArea); - } - - public boolean unregisterTouchAreas(final ITouchAreaMatcher pTouchAreaMatcher) { - return this.mTouchAreas.removeAll(pTouchAreaMatcher); - } - - public void clearTouchAreas() { - this.mTouchAreas.clear(); - } - - public ArrayList getTouchAreas() { - return this.mTouchAreas; - } - - public void back() { - this.clearChildScene(); - - if(this.mParentScene != null) { - this.mParentScene.clearChildScene(); - this.mParentScene = null; - } - } - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== - - public static interface ITouchArea { - // =========================================================== - // Final Fields - // =========================================================== - - // =========================================================== - // Methods - // =========================================================== - - 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); - - /** - * This method only fires if this {@link ITouchArea} is registered to the {@link Scene} via {@link Scene#registerTouchArea(ITouchArea)}. - * @param pSceneTouchEvent - * @return true if the event was handled (that means {@link IOnAreaTouchListener} of the {@link Scene} will not be fired!), otherwise false. - */ - public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final float pTouchAreaLocalX, final float pTouchAreaLocalY); - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== - - public interface ITouchAreaMatcher extends IMatcher { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Methods - // =========================================================== - } - } - - /** - * An interface for a callback to be invoked when a {@link TouchEvent} is - * dispatched to an {@link ITouchArea} area. The callback will be invoked - * before the {@link TouchEvent} is passed to the {@link ITouchArea}. - */ - public static interface IOnAreaTouchListener { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Methods - // =========================================================== - - /** - * 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); - } - - /** - * An interface for a callback to be invoked when a {@link TouchEvent} is - * dispatched to a {@link Scene}. The callback will be invoked - * after all {@link ITouchArea}s have been checked and none consumed the {@link TouchEvent}. - */ - public static interface IOnSceneTouchListener { - // =========================================================== - // Final Fields - // =========================================================== - - // =========================================================== - // Methods - // =========================================================== - - /** - * 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); - } + public float getSecondsElapsedTotal() { + return this.mSecondsElapsedTotal; + } + + public IBackground getBackground() { + return this.mBackground; + } + + public void setBackground(final IBackground pBackground) { + this.mBackground = pBackground; + } + + public boolean isBackgroundEnabled() { + return this.mBackgroundEnabled; + } + + public void setBackgroundEnabled(final boolean pEnabled) { + this.mBackgroundEnabled = pEnabled; + } + + public void setOnSceneTouchListener(final IOnSceneTouchListener pOnSceneTouchListener) { + this.mOnSceneTouchListener = pOnSceneTouchListener; + } + + public IOnSceneTouchListener getOnSceneTouchListener() { + return this.mOnSceneTouchListener; + } + + public boolean hasOnSceneTouchListener() { + return this.mOnSceneTouchListener != null; + } + + public void setOnAreaTouchListener(final IOnAreaTouchListener pOnAreaTouchListener) { + this.mOnAreaTouchListener = pOnAreaTouchListener; + } + + public IOnAreaTouchListener getOnAreaTouchListener() { + return this.mOnAreaTouchListener; + } + + public boolean hasOnAreaTouchListener() { + return this.mOnAreaTouchListener != null; + } + + private void setParentScene(final Scene pParentScene) { + this.mParentScene = pParentScene; + } + + public boolean hasChildScene() { + return this.mChildScene != null; + } + + public Scene getChildScene() { + return this.mChildScene; + } + + public void setChildSceneModal(final Scene pChildScene) { + this.setChildScene(pChildScene, true, true, true); + } + + public void setChildScene(final Scene pChildScene) { + this.setChildScene(pChildScene, false, false, false); + } + + public void setChildScene(final Scene pChildScene, final boolean pModalDraw, final boolean pModalUpdate, final boolean pModalTouch) { + pChildScene.setParentScene(this); + this.mChildScene = pChildScene; + this.mChildSceneModalDraw = pModalDraw; + this.mChildSceneModalUpdate = pModalUpdate; + this.mChildSceneModalTouch = pModalTouch; + } + + public void clearChildScene() { + this.mChildScene = null; + } + + public void setOnAreaTouchTraversalBackToFront() { + this.mOnAreaTouchTraversalBackToFront = true; + } + + public void setOnAreaTouchTraversalFrontToBack() { + this.mOnAreaTouchTraversalBackToFront = false; + } + + public boolean isTouchAreaBindingEnabled() { + return this.mTouchAreaBindingEnabled; + } + + /** + * Enable or disable the binding of TouchAreas to PointerIDs (fingers). + * When enabled: TouchAreas get bound to a PointerID (finger) when returning true in + * {@link Shape#onAreaTouched(TouchEvent, float, float)} or + * {@link IOnAreaTouchListener#onAreaTouched(TouchEvent, ITouchArea, float, float)} + * 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 pTouchAreaBindingEnabled + */ + public void setTouchAreaBindingEnabled(final boolean pTouchAreaBindingEnabled) { + if(this.mTouchAreaBindingEnabled && !pTouchAreaBindingEnabled) { + this.mTouchAreaBindings.clear(); + } + this.mTouchAreaBindingEnabled = pTouchAreaBindingEnabled; + } + + public boolean isOnSceneTouchListenerBindingEnabled() { + return this.mOnSceneTouchListenerBindingEnabled; + } + + /** + * Enable or disable the binding of TouchAreas to PointerIDs (fingers). + * When enabled: The OnSceneTouchListener gets bound to a PointerID (finger) when returning true in + * {@link Shape#onAreaTouched(TouchEvent, float, float)} or + * {@link IOnAreaTouchListener#onAreaTouched(TouchEvent, ITouchArea, float, float)} + * 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 pOnSceneTouchListenerBindingEnabled + */ + public void setOnSceneTouchListenerBindingEnabled(final boolean pOnSceneTouchListenerBindingEnabled) { + if(this.mOnSceneTouchListenerBindingEnabled && !pOnSceneTouchListenerBindingEnabled) { + this.mOnSceneTouchListenerBindings.clear(); + } + this.mOnSceneTouchListenerBindingEnabled = pOnSceneTouchListenerBindingEnabled; + } + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + protected void onManagedDraw(final GL10 pGL, final Camera pCamera) { + final Scene childScene = this.mChildScene; + + if(childScene == null || !this.mChildSceneModalDraw) { + if(this.mBackgroundEnabled) { + pCamera.onApplySceneBackgroundMatrix(pGL); + GLHelper.setModelViewIdentityMatrix(pGL); + + this.mBackground.onDraw(pGL, pCamera); + } + + pCamera.onApplySceneMatrix(pGL); + GLHelper.setModelViewIdentityMatrix(pGL); + + super.onManagedDraw(pGL, pCamera); + } + + if(childScene != null) { + childScene.onDraw(pGL, pCamera); + } + } + + @Override + protected void onManagedUpdate(final float pSecondsElapsed) { + this.mSecondsElapsedTotal += pSecondsElapsed; + + this.mRunnableHandler.onUpdate(pSecondsElapsed); + + final Scene childScene = this.mChildScene; + if(childScene == null || !this.mChildSceneModalUpdate) { + this.mBackground.onUpdate(pSecondsElapsed); + super.onManagedUpdate(pSecondsElapsed); + } + + if(childScene != null) { + childScene.onUpdate(pSecondsElapsed); + } + } + + public boolean onSceneTouchEvent(final TouchEvent pSceneTouchEvent) { + final int action = pSceneTouchEvent.getAction(); + final boolean isActionDown = pSceneTouchEvent.isActionDown(); + + if(!isActionDown) { + if(this.mOnSceneTouchListenerBindingEnabled) { + final IOnSceneTouchListener boundOnSceneTouchListener = this.mOnSceneTouchListenerBindings.get(pSceneTouchEvent.getPointerID()); + if (boundOnSceneTouchListener != null) { + /* Check if boundTouchArea needs to be removed. */ + 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) { + return true; + } + } + } + if(this.mTouchAreaBindingEnabled) { + 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) { + final float sceneTouchEventX = pSceneTouchEvent.getX(); + final float sceneTouchEventY = pSceneTouchEvent.getY(); + + /* Check if boundTouchArea needs to be removed. */ + 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) { + return true; + } + } + } + } + + final Scene childScene = this.mChildScene; + if(childScene != null) { + final boolean handledByChild = this.onChildSceneTouchEvent(pSceneTouchEvent); + if(handledByChild) { + return true; + } else if(this.mChildSceneModalTouch) { + return false; + } + } + + final float sceneTouchEventX = pSceneTouchEvent.getX(); + final float sceneTouchEventY = pSceneTouchEvent.getY(); + + final ArrayList touchAreas = this.mTouchAreas; + if(touchAreas != null) { + final int touchAreaCount = touchAreas.size(); + if(touchAreaCount > 0) { + if(this.mOnAreaTouchTraversalBackToFront) { /* Back to Front. */ + for(int i = 0; i < touchAreaCount; i++) { + final ITouchArea touchArea = touchAreas.get(i); + if (touchArea != null && touchArea.contains(sceneTouchEventX, sceneTouchEventY)) { + final Boolean handled = this.onAreaTouchEvent(pSceneTouchEvent, sceneTouchEventX, sceneTouchEventY, touchArea); + 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.mTouchAreaBindingEnabled && isActionDown) { + this.mTouchAreaBindings.put(pSceneTouchEvent.getPointerID(), touchArea); + } + return true; + } + } + } + } else { /* Front to back. */ + for(int i = touchAreaCount - 1; i >= 0; i--) { + final ITouchArea touchArea = touchAreas.get(i); + if(touchArea.contains(sceneTouchEventX, sceneTouchEventY)) { + final Boolean handled = this.onAreaTouchEvent(pSceneTouchEvent, sceneTouchEventX, sceneTouchEventY, touchArea); + 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.mTouchAreaBindingEnabled && isActionDown) { + this.mTouchAreaBindings.put(pSceneTouchEvent.getPointerID(), touchArea); + } + return true; + } + } + } + } + } + } + /* If no area was touched, the Scene itself was touched as a fallback. */ + if(this.mOnSceneTouchListener != null){ + final Boolean handled = this.mOnSceneTouchListener.onSceneTouchEvent(this, pSceneTouchEvent); + 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.mOnSceneTouchListenerBindingEnabled && isActionDown) { + this.mOnSceneTouchListenerBindings.put(pSceneTouchEvent.getPointerID(), this.mOnSceneTouchListener); + } + return true; + } else { + return false; + } + } else { + return false; + } + } + + private Boolean onAreaTouchEvent(final TouchEvent pSceneTouchEvent, final float sceneTouchEventX, final float sceneTouchEventY, final ITouchArea touchArea) { + final float[] touchAreaLocalCoordinates = touchArea.convertSceneToLocalCoordinates(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) { + return Boolean.TRUE; + } else if(this.mOnAreaTouchListener != null) { + return this.mOnAreaTouchListener.onAreaTouched(pSceneTouchEvent, touchArea, touchAreaLocalX, touchAreaLocalY); + } else { + return null; + } + } + + protected boolean onChildSceneTouchEvent(final TouchEvent pSceneTouchEvent) { + return this.mChildScene.onSceneTouchEvent(pSceneTouchEvent); + } + + @Override + public void reset() { + super.reset(); + + this.clearChildScene(); + } + + @Override + public void setParent(final IEntity pEntity) { + // super.setParent(pEntity); + } + + // =========================================================== + // Methods + // =========================================================== + + public void postRunnable(final Runnable pRunnable) { + this.mRunnableHandler.postRunnable(pRunnable); + } + + public void registerTouchArea(final ITouchArea pTouchArea) { + this.mTouchAreas.add(pTouchArea); + } + + public boolean unregisterTouchArea(final ITouchArea pTouchArea) { + return this.mTouchAreas.remove(pTouchArea); + } + + public boolean unregisterTouchAreas(final ITouchAreaMatcher pTouchAreaMatcher) { + return this.mTouchAreas.removeAll(pTouchAreaMatcher); + } + + public void clearTouchAreas() { + this.mTouchAreas.clear(); + } + + public ArrayList getTouchAreas() { + return this.mTouchAreas; + } + + public void back() { + this.clearChildScene(); + + if(this.mParentScene != null) { + this.mParentScene.clearChildScene(); + this.mParentScene = null; + } + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== + + public static interface ITouchArea { + // =========================================================== + // Final Fields + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + 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); + + /** + * This method only fires if this {@link ITouchArea} is registered to the {@link Scene} via {@link Scene#registerTouchArea(ITouchArea)}. + * @param pSceneTouchEvent + * @return true if the event was handled (that means {@link IOnAreaTouchListener} of the {@link Scene} will not be fired!), otherwise false. + */ + public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final float pTouchAreaLocalX, final float pTouchAreaLocalY); + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== + + public interface ITouchAreaMatcher extends IMatcher { + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + } + } + + /** + * An interface for a callback to be invoked when a {@link TouchEvent} is + * dispatched to an {@link ITouchArea} area. The callback will be invoked + * before the {@link TouchEvent} is passed to the {@link ITouchArea}. + */ + public static interface IOnAreaTouchListener { + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + /** + * 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); + } + + /** + * An interface for a callback to be invoked when a {@link TouchEvent} is + * dispatched to a {@link Scene}. The callback will be invoked + * after all {@link ITouchArea}s have been checked and none consumed the {@link TouchEvent}. + */ + public static interface IOnSceneTouchListener { + // =========================================================== + // Final Fields + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + /** + * 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/AndEngine/src/org/anddev/andengine/entity/scene/SplashScene.java b/AndEngine/src/org/anddev/andengine/entity/scene/SplashScene.java index 51742fd3..dff186e9 100644 --- a/AndEngine/src/org/anddev/andengine/entity/scene/SplashScene.java +++ b/AndEngine/src/org/anddev/andengine/entity/scene/SplashScene.java @@ -14,45 +14,45 @@ * @since 09:45:02 - 03.05.2010 */ public class SplashScene extends Scene { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - // =========================================================== - // Constructors - // =========================================================== - - public SplashScene(final Camera pCamera, final TextureRegion pTextureRegion) { - this(pCamera, pTextureRegion, -1, 1, 1); - } - - public SplashScene(final Camera pCamera, final TextureRegion pTextureRegion, final float pDuration, final float pScaleFrom, final float pScaleTo) { - final Sprite loadingScreenSprite = new Sprite(pCamera.getMinX(), pCamera.getMinY(), pCamera.getWidth(), pCamera.getHeight(), pTextureRegion); - if(pScaleFrom != 1 || pScaleTo != 1) { - loadingScreenSprite.setScale(pScaleFrom); - loadingScreenSprite.registerEntityModifier(new ScaleModifier(pDuration, pScaleFrom, pScaleTo, IEaseFunction.DEFAULT)); - } - - this.attachChild(loadingScreenSprite); - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + // =========================================================== + // Constructors + // =========================================================== + + public SplashScene(final Camera pCamera, final TextureRegion pTextureRegion) { + this(pCamera, pTextureRegion, -1, 1, 1); + } + + public SplashScene(final Camera pCamera, final TextureRegion pTextureRegion, final float pDuration, final float pScaleFrom, final float pScaleTo) { + final Sprite loadingScreenSprite = new Sprite(pCamera.getMinX(), pCamera.getMinY(), pCamera.getWidth(), pCamera.getHeight(), pTextureRegion); + if(pScaleFrom != 1 || pScaleTo != 1) { + loadingScreenSprite.setScale(pScaleFrom); + loadingScreenSprite.registerEntityModifier(new ScaleModifier(pDuration, pScaleFrom, pScaleTo, IEaseFunction.DEFAULT)); + } + + this.attachChild(loadingScreenSprite); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/entity/scene/background/AutoParallaxBackground.java b/AndEngine/src/org/anddev/andengine/entity/scene/background/AutoParallaxBackground.java index 33c40c3b..648c5fdb 100644 --- a/AndEngine/src/org/anddev/andengine/entity/scene/background/AutoParallaxBackground.java +++ b/AndEngine/src/org/anddev/andengine/entity/scene/background/AutoParallaxBackground.java @@ -10,49 +10,49 @@ * @since 19:44:31 - 19.07.2010 */ public class AutoParallaxBackground extends ParallaxBackground { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - private float mParallaxChangePerSecond; + private float mParallaxChangePerSecond; - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - public AutoParallaxBackground(final float pRed, final float pGreen, final float pBlue, final float pParallaxChangePerSecond) { - super(pRed, pGreen, pBlue); - this.mParallaxChangePerSecond = pParallaxChangePerSecond; - } + public AutoParallaxBackground(final float pRed, final float pGreen, final float pBlue, final float pParallaxChangePerSecond) { + super(pRed, pGreen, pBlue); + this.mParallaxChangePerSecond = pParallaxChangePerSecond; + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - public void setParallaxChangePerSecond(final float pParallaxChangePerSecond) { - this.mParallaxChangePerSecond = pParallaxChangePerSecond; - } + public void setParallaxChangePerSecond(final float pParallaxChangePerSecond) { + this.mParallaxChangePerSecond = pParallaxChangePerSecond; + } - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - @Override - public void onUpdate(final float pSecondsElapsed) { - super.onUpdate(pSecondsElapsed); + @Override + public void onUpdate(final float pSecondsElapsed) { + super.onUpdate(pSecondsElapsed); - this.mParallaxValue += this.mParallaxChangePerSecond * pSecondsElapsed; - } + this.mParallaxValue += this.mParallaxChangePerSecond * pSecondsElapsed; + } - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/entity/scene/background/BaseBackground.java b/AndEngine/src/org/anddev/andengine/entity/scene/background/BaseBackground.java index 217f9c1d..78b83cde 100644 --- a/AndEngine/src/org/anddev/andengine/entity/scene/background/BaseBackground.java +++ b/AndEngine/src/org/anddev/andengine/entity/scene/background/BaseBackground.java @@ -13,60 +13,60 @@ * @since 14:08:17 - 19.07.2010 */ public abstract class BaseBackground implements IBackground { - // =========================================================== - // Constants - // =========================================================== - - private static final int BACKGROUNDMODIFIERS_CAPACITY_DEFAULT = 4; - - // =========================================================== - // Fields - // =========================================================== - - private final ModifierList mBackgroundModifiers = new ModifierList(this, BACKGROUNDMODIFIERS_CAPACITY_DEFAULT); - - // =========================================================== - // Constructors - // =========================================================== - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - public void addBackgroundModifier(final IModifier pBackgroundModifier) { - this.mBackgroundModifiers.add(pBackgroundModifier); - } - - @Override - public boolean removeBackgroundModifier(final IModifier pBackgroundModifier) { - return this.mBackgroundModifiers.remove(pBackgroundModifier); - } - - @Override - public void clearBackgroundModifiers() { - this.mBackgroundModifiers.clear(); - } - - @Override - public void onUpdate(final float pSecondsElapsed) { - this.mBackgroundModifiers.onUpdate(pSecondsElapsed); - } - - @Override - public void reset() { - this.mBackgroundModifiers.reset(); - } - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + private static final int BACKGROUNDMODIFIERS_CAPACITY_DEFAULT = 4; + + // =========================================================== + // Fields + // =========================================================== + + private final ModifierList mBackgroundModifiers = new ModifierList(this, BACKGROUNDMODIFIERS_CAPACITY_DEFAULT); + + // =========================================================== + // Constructors + // =========================================================== + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + public void addBackgroundModifier(final IModifier pBackgroundModifier) { + this.mBackgroundModifiers.add(pBackgroundModifier); + } + + @Override + public boolean removeBackgroundModifier(final IModifier pBackgroundModifier) { + return this.mBackgroundModifiers.remove(pBackgroundModifier); + } + + @Override + public void clearBackgroundModifiers() { + this.mBackgroundModifiers.clear(); + } + + @Override + public void onUpdate(final float pSecondsElapsed) { + this.mBackgroundModifiers.onUpdate(pSecondsElapsed); + } + + @Override + public void reset() { + this.mBackgroundModifiers.reset(); + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/entity/scene/background/ColorBackground.java b/AndEngine/src/org/anddev/andengine/entity/scene/background/ColorBackground.java index c0f138ba..b3ae99f2 100644 --- a/AndEngine/src/org/anddev/andengine/entity/scene/background/ColorBackground.java +++ b/AndEngine/src/org/anddev/andengine/entity/scene/background/ColorBackground.java @@ -14,117 +14,117 @@ * @since 13:45:24 - 19.07.2010 */ public class ColorBackground extends BaseBackground { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - private float mRed = 0.0f; - private float mGreen = 0.0f; - private float mBlue = 0.0f; - private float mAlpha = 1.0f; - - private boolean mColorEnabled = true; - - // =========================================================== - // Constructors - // =========================================================== - - protected ColorBackground() { - - } - - public ColorBackground(final float pRed, final float pGreen, final float pBlue) { - this.mRed = pRed; - this.mGreen = pGreen; - this.mBlue = pBlue; - } - - public ColorBackground(final float pRed, final float pGreen, final float pBlue, final float pAlpha) { - this.mRed = pRed; - this.mGreen = pGreen; - this.mBlue = pBlue; - this.mAlpha = pAlpha; - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - /** - * Sets the color using the arithmetic scheme (0.0f - 1.0f RGB triple). - * @param pRed The red color value. Should be between 0.0 and 1.0, inclusive. - * @param pGreen The green color value. Should be between 0.0 and 1.0, inclusive. - * @param pBlue The blue color value. Should be between 0.0 and 1.0, inclusive. - */ - @Override - public void setColor(final float pRed, final float pGreen, final float pBlue) { - this.mRed = pRed; - this.mGreen = pGreen; - this.mBlue = pBlue; - } - - /** - * Sets the color using the arithmetic scheme (0.0f - 1.0f RGB quadruple). - * @param pRed The red color value. Should be between 0.0 and 1.0, inclusive. - * @param pGreen The green color value. Should be between 0.0 and 1.0, inclusive. - * @param pBlue The blue color value. Should be between 0.0 and 1.0, inclusive. - * @param pAlpha The alpha color value. Should be between 0.0 and 1.0, inclusive. - */ - @Override - public void setColor(final float pRed, final float pGreen, final float pBlue, final float pAlpha) { - this.setColor(pRed, pGreen, pBlue); - this.mAlpha = pAlpha; - } - - /** - * Sets the color using the digital 8-bit per channel scheme (0 - 255 RGB triple). - * @param pRed The red color value. Should be between 0 and 255, inclusive. - * @param pGreen The green color value. Should be between 0 and 255, inclusive. - * @param pBlue The blue color value. Should be between 0 and 255, inclusive. - */ - public void setColor(final int pRed, final int pGreen, final int pBlue) throws IllegalArgumentException { - this.setColor(pRed / COLOR_FACTOR_INT_TO_FLOAT, pGreen / COLOR_FACTOR_INT_TO_FLOAT, pBlue / COLOR_FACTOR_INT_TO_FLOAT); - } - - /** - * Sets the color using the digital 8-bit per channel scheme (0 - 255 RGB quadruple). - * @param pRed The red color value. Should be between 0 and 255, inclusive. - * @param pGreen The green color value. Should be between 0 and 255, inclusive. - * @param pBlue The blue color value. Should be between 0 and 255, inclusive. - */ - public void setColor(final int pRed, final int pGreen, final int pBlue, final int pAlpha) throws IllegalArgumentException { - this.setColor(pRed / COLOR_FACTOR_INT_TO_FLOAT, pGreen / COLOR_FACTOR_INT_TO_FLOAT, pBlue / COLOR_FACTOR_INT_TO_FLOAT, pAlpha / COLOR_FACTOR_INT_TO_FLOAT); - } - - public void setColorEnabled(final boolean pColorEnabled) { - this.mColorEnabled = pColorEnabled; - } - - public boolean isColorEnabled() { - return this.mColorEnabled; - } - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - public void onDraw(final GL10 pGL, final Camera pCamera) { - if(this.mColorEnabled) { - pGL.glClearColor(this.mRed, this.mGreen, this.mBlue, this.mAlpha); - pGL.glClear(GL10.GL_COLOR_BUFFER_BIT); - } - } - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + private float mRed = 0.0f; + private float mGreen = 0.0f; + private float mBlue = 0.0f; + private float mAlpha = 1.0f; + + private boolean mColorEnabled = true; + + // =========================================================== + // Constructors + // =========================================================== + + protected ColorBackground() { + + } + + public ColorBackground(final float pRed, final float pGreen, final float pBlue) { + this.mRed = pRed; + this.mGreen = pGreen; + this.mBlue = pBlue; + } + + public ColorBackground(final float pRed, final float pGreen, final float pBlue, final float pAlpha) { + this.mRed = pRed; + this.mGreen = pGreen; + this.mBlue = pBlue; + this.mAlpha = pAlpha; + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + /** + * Sets the color using the arithmetic scheme (0.0f - 1.0f RGB triple). + * @param pRed The red color value. Should be between 0.0 and 1.0, inclusive. + * @param pGreen The green color value. Should be between 0.0 and 1.0, inclusive. + * @param pBlue The blue color value. Should be between 0.0 and 1.0, inclusive. + */ + @Override + public void setColor(final float pRed, final float pGreen, final float pBlue) { + this.mRed = pRed; + this.mGreen = pGreen; + this.mBlue = pBlue; + } + + /** + * Sets the color using the arithmetic scheme (0.0f - 1.0f RGB quadruple). + * @param pRed The red color value. Should be between 0.0 and 1.0, inclusive. + * @param pGreen The green color value. Should be between 0.0 and 1.0, inclusive. + * @param pBlue The blue color value. Should be between 0.0 and 1.0, inclusive. + * @param pAlpha The alpha color value. Should be between 0.0 and 1.0, inclusive. + */ + @Override + public void setColor(final float pRed, final float pGreen, final float pBlue, final float pAlpha) { + this.setColor(pRed, pGreen, pBlue); + this.mAlpha = pAlpha; + } + + /** + * Sets the color using the digital 8-bit per channel scheme (0 - 255 RGB triple). + * @param pRed The red color value. Should be between 0 and 255, inclusive. + * @param pGreen The green color value. Should be between 0 and 255, inclusive. + * @param pBlue The blue color value. Should be between 0 and 255, inclusive. + */ + public void setColor(final int pRed, final int pGreen, final int pBlue) throws IllegalArgumentException { + this.setColor(pRed / COLOR_FACTOR_INT_TO_FLOAT, pGreen / COLOR_FACTOR_INT_TO_FLOAT, pBlue / COLOR_FACTOR_INT_TO_FLOAT); + } + + /** + * Sets the color using the digital 8-bit per channel scheme (0 - 255 RGB quadruple). + * @param pRed The red color value. Should be between 0 and 255, inclusive. + * @param pGreen The green color value. Should be between 0 and 255, inclusive. + * @param pBlue The blue color value. Should be between 0 and 255, inclusive. + */ + public void setColor(final int pRed, final int pGreen, final int pBlue, final int pAlpha) throws IllegalArgumentException { + this.setColor(pRed / COLOR_FACTOR_INT_TO_FLOAT, pGreen / COLOR_FACTOR_INT_TO_FLOAT, pBlue / COLOR_FACTOR_INT_TO_FLOAT, pAlpha / COLOR_FACTOR_INT_TO_FLOAT); + } + + public void setColorEnabled(final boolean pColorEnabled) { + this.mColorEnabled = pColorEnabled; + } + + public boolean isColorEnabled() { + return this.mColorEnabled; + } + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + public void onDraw(final GL10 pGL, final Camera pCamera) { + if(this.mColorEnabled) { + pGL.glClearColor(this.mRed, this.mGreen, this.mBlue, this.mAlpha); + pGL.glClear(GL10.GL_COLOR_BUFFER_BIT); + } + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/entity/scene/background/EntityBackground.java b/AndEngine/src/org/anddev/andengine/entity/scene/background/EntityBackground.java index 98d1dbe6..8e9078aa 100644 --- a/AndEngine/src/org/anddev/andengine/entity/scene/background/EntityBackground.java +++ b/AndEngine/src/org/anddev/andengine/entity/scene/background/EntityBackground.java @@ -13,48 +13,48 @@ * @since 18:25:10 - 21.07.2010 */ public class EntityBackground extends ColorBackground { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - protected IEntity mEntity; - - // =========================================================== - // Constructors - // =========================================================== - - public EntityBackground(final IEntity pEntity) { - this.mEntity = pEntity; - } - - public EntityBackground(final float pRed, final float pGreen, final float pBlue, final IEntity pEntity) { - super(pRed, pGreen, pBlue); - this.mEntity = pEntity; - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - public void onDraw(final GL10 pGL, final Camera pCamera) { - super.onDraw(pGL, pCamera); - this.mEntity.onDraw(pGL, pCamera); - } - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + protected IEntity mEntity; + + // =========================================================== + // Constructors + // =========================================================== + + public EntityBackground(final IEntity pEntity) { + this.mEntity = pEntity; + } + + public EntityBackground(final float pRed, final float pGreen, final float pBlue, final IEntity pEntity) { + super(pRed, pGreen, pBlue); + this.mEntity = pEntity; + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + public void onDraw(final GL10 pGL, final Camera pCamera) { + super.onDraw(pGL, pCamera); + this.mEntity.onDraw(pGL, pCamera); + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/entity/scene/background/IBackground.java b/AndEngine/src/org/anddev/andengine/entity/scene/background/IBackground.java index 680697bf..d4a3a7f9 100644 --- a/AndEngine/src/org/anddev/andengine/entity/scene/background/IBackground.java +++ b/AndEngine/src/org/anddev/andengine/entity/scene/background/IBackground.java @@ -12,18 +12,18 @@ * @since 13:47:41 - 19.07.2010 */ public interface IBackground extends IDrawable, IUpdateHandler { - // =========================================================== - // Final Fields - // =========================================================== + // =========================================================== + // Final Fields + // =========================================================== - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - public void addBackgroundModifier(final IModifier pBackgroundModifier); - public boolean removeBackgroundModifier(final IModifier pBackgroundModifier); - public void clearBackgroundModifiers(); + public void addBackgroundModifier(final IModifier pBackgroundModifier); + public boolean removeBackgroundModifier(final IModifier pBackgroundModifier); + public void clearBackgroundModifiers(); - 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); + 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); } diff --git a/AndEngine/src/org/anddev/andengine/entity/scene/background/ParallaxBackground.java b/AndEngine/src/org/anddev/andengine/entity/scene/background/ParallaxBackground.java index 7c341caa..a8b61e06 100644 --- a/AndEngine/src/org/anddev/andengine/entity/scene/background/ParallaxBackground.java +++ b/AndEngine/src/org/anddev/andengine/entity/scene/background/ParallaxBackground.java @@ -15,131 +15,131 @@ * @since 15:36:26 - 19.07.2010 */ public class ParallaxBackground extends ColorBackground { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - private final ArrayList mParallaxEntities = new ArrayList(); - private int mParallaxEntityCount; - - protected float mParallaxValue; - - // =========================================================== - // Constructors - // =========================================================== - - public ParallaxBackground(final float pRed, final float pGreen, final float pBlue) { - super(pRed, pGreen, pBlue); - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - public void setParallaxValue(final float pParallaxValue) { - this.mParallaxValue = pParallaxValue; - } - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - public void onDraw(final GL10 pGL, final Camera pCamera) { - super.onDraw(pGL, pCamera); - - final float parallaxValue = this.mParallaxValue; - final ArrayList parallaxEntities = this.mParallaxEntities; - - for(int i = 0; i < this.mParallaxEntityCount; i++) { - parallaxEntities.get(i).onDraw(pGL, parallaxValue, pCamera); - } - } - - // =========================================================== - // Methods - // =========================================================== - - public void attachParallaxEntity(final ParallaxEntity pParallaxEntity) { - this.mParallaxEntities.add(pParallaxEntity); - this.mParallaxEntityCount++; - } - - public boolean detachParallaxEntity(final ParallaxEntity pParallaxEntity) { - this.mParallaxEntityCount--; - final boolean success = this.mParallaxEntities.remove(pParallaxEntity); - if(!success) { - this.mParallaxEntityCount++; - } - return success; - } - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== - - public static class ParallaxEntity { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - final float mParallaxFactor; - final Shape mShape; - - // =========================================================== - // Constructors - // =========================================================== - - public ParallaxEntity(final float pParallaxFactor, final Shape pShape) { - this.mParallaxFactor = pParallaxFactor; - this.mShape = pShape; - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - // =========================================================== - // Methods - // =========================================================== - - public void onDraw(final GL10 pGL, final float pParallaxValue, final Camera pCamera) { - pGL.glPushMatrix(); - { - final float cameraWidth = pCamera.getWidth(); - final float shapeWidthScaled = this.mShape.getWidthScaled(); - float baseOffset = (pParallaxValue * this.mParallaxFactor) % shapeWidthScaled; - - while(baseOffset > 0) { - baseOffset -= shapeWidthScaled; - } - pGL.glTranslatef(baseOffset, 0, 0); - - float currentMaxX = baseOffset; - - do { - this.mShape.onDraw(pGL, pCamera); - pGL.glTranslatef(shapeWidthScaled, 0, 0); - currentMaxX += shapeWidthScaled; - } while(currentMaxX < cameraWidth); - } - pGL.glPopMatrix(); - } - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== - } + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + private final ArrayList mParallaxEntities = new ArrayList(); + private int mParallaxEntityCount; + + protected float mParallaxValue; + + // =========================================================== + // Constructors + // =========================================================== + + public ParallaxBackground(final float pRed, final float pGreen, final float pBlue) { + super(pRed, pGreen, pBlue); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + public void setParallaxValue(final float pParallaxValue) { + this.mParallaxValue = pParallaxValue; + } + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + public void onDraw(final GL10 pGL, final Camera pCamera) { + super.onDraw(pGL, pCamera); + + final float parallaxValue = this.mParallaxValue; + final ArrayList parallaxEntities = this.mParallaxEntities; + + for(int i = 0; i < this.mParallaxEntityCount; i++) { + parallaxEntities.get(i).onDraw(pGL, parallaxValue, pCamera); + } + } + + // =========================================================== + // Methods + // =========================================================== + + public void attachParallaxEntity(final ParallaxEntity pParallaxEntity) { + this.mParallaxEntities.add(pParallaxEntity); + this.mParallaxEntityCount++; + } + + public boolean detachParallaxEntity(final ParallaxEntity pParallaxEntity) { + this.mParallaxEntityCount--; + final boolean success = this.mParallaxEntities.remove(pParallaxEntity); + if(!success) { + this.mParallaxEntityCount++; + } + return success; + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== + + public static class ParallaxEntity { + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + final float mParallaxFactor; + final Shape mShape; + + // =========================================================== + // Constructors + // =========================================================== + + public ParallaxEntity(final float pParallaxFactor, final Shape pShape) { + this.mParallaxFactor = pParallaxFactor; + this.mShape = pShape; + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + public void onDraw(final GL10 pGL, final float pParallaxValue, final Camera pCamera) { + pGL.glPushMatrix(); + { + final float cameraWidth = pCamera.getWidth(); + final float shapeWidthScaled = this.mShape.getWidthScaled(); + float baseOffset = (pParallaxValue * this.mParallaxFactor) % shapeWidthScaled; + + while(baseOffset > 0) { + baseOffset -= shapeWidthScaled; + } + pGL.glTranslatef(baseOffset, 0, 0); + + float currentMaxX = baseOffset; + + do { + this.mShape.onDraw(pGL, pCamera); + pGL.glTranslatef(shapeWidthScaled, 0, 0); + currentMaxX += shapeWidthScaled; + } while(currentMaxX < cameraWidth); + } + pGL.glPopMatrix(); + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== + } } diff --git a/AndEngine/src/org/anddev/andengine/entity/scene/background/RepeatingSpriteBackground.java b/AndEngine/src/org/anddev/andengine/entity/scene/background/RepeatingSpriteBackground.java index db0315bb..de000595 100644 --- a/AndEngine/src/org/anddev/andengine/entity/scene/background/RepeatingSpriteBackground.java +++ b/AndEngine/src/org/anddev/andengine/entity/scene/background/RepeatingSpriteBackground.java @@ -17,72 +17,72 @@ * @since 15:11:10 - 19.07.2010 */ public class RepeatingSpriteBackground extends SpriteBackground { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // 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) throws IllegalArgumentException { - this(pCameraWidth, pCameraHeight, pTextureManager, pBitmapTextureAtlasSource, 1); - } - - public RepeatingSpriteBackground(final float pCameraWidth, final float pCameraHeight, final TextureManager pTextureManager, final IBitmapTextureAtlasSource pBitmapTextureAtlasSource, final float pScale) throws IllegalArgumentException { - super(null); - this.mScale = pScale; - this.mEntity = this.loadSprite(pCameraWidth, pCameraHeight, pTextureManager, pBitmapTextureAtlasSource); - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - public BitmapTextureAtlas getBitmapTextureAtlas() { - return this.mBitmapTextureAtlas; - } - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - // =========================================================== - // Methods - // =========================================================== - - private Sprite loadSprite(final float pCameraWidth, final float pCameraHeight, final TextureManager pTextureManager, final IBitmapTextureAtlasSource pBitmapTextureAtlasSource) throws IllegalArgumentException { - this.mBitmapTextureAtlas = new BitmapTextureAtlas(pBitmapTextureAtlasSource.getWidth(), pBitmapTextureAtlasSource.getHeight(), BitmapTextureFormat.RGBA_8888, TextureOptions.REPEATING_NEAREST_PREMULTIPLYALPHA); - final TextureRegion 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.setWidth(width); - textureRegion.setHeight(height); - - pTextureManager.loadTexture(this.mBitmapTextureAtlas); - - final Sprite sprite = new Sprite(0, 0, width, height, textureRegion); - sprite.setScaleCenter(0, 0); - sprite.setScale(this.mScale); - return sprite; - } - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // 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) throws IllegalArgumentException { + this(pCameraWidth, pCameraHeight, pTextureManager, pBitmapTextureAtlasSource, 1); + } + + public RepeatingSpriteBackground(final float pCameraWidth, final float pCameraHeight, final TextureManager pTextureManager, final IBitmapTextureAtlasSource pBitmapTextureAtlasSource, final float pScale) throws IllegalArgumentException { + super(null); + this.mScale = pScale; + this.mEntity = this.loadSprite(pCameraWidth, pCameraHeight, pTextureManager, pBitmapTextureAtlasSource); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + public BitmapTextureAtlas getBitmapTextureAtlas() { + return this.mBitmapTextureAtlas; + } + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + private Sprite loadSprite(final float pCameraWidth, final float pCameraHeight, final TextureManager pTextureManager, final IBitmapTextureAtlasSource pBitmapTextureAtlasSource) throws IllegalArgumentException { + this.mBitmapTextureAtlas = new BitmapTextureAtlas(pBitmapTextureAtlasSource.getWidth(), pBitmapTextureAtlasSource.getHeight(), BitmapTextureFormat.RGBA_8888, TextureOptions.REPEATING_NEAREST_PREMULTIPLYALPHA); + final TextureRegion 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.setWidth(width); + textureRegion.setHeight(height); + + pTextureManager.loadTexture(this.mBitmapTextureAtlas); + + final Sprite sprite = new Sprite(0, 0, width, height, textureRegion); + sprite.setScaleCenter(0, 0); + sprite.setScale(this.mScale); + return sprite; + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/entity/scene/background/SpriteBackground.java b/AndEngine/src/org/anddev/andengine/entity/scene/background/SpriteBackground.java index 3f59f314..8c8218ee 100644 --- a/AndEngine/src/org/anddev/andengine/entity/scene/background/SpriteBackground.java +++ b/AndEngine/src/org/anddev/andengine/entity/scene/background/SpriteBackground.java @@ -10,39 +10,39 @@ * @since 14:01:43 - 19.07.2010 */ public class SpriteBackground extends EntityBackground { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - public SpriteBackground(final BaseSprite pBaseSprite) { - super(pBaseSprite); - } + public SpriteBackground(final BaseSprite pBaseSprite) { + super(pBaseSprite); + } - public SpriteBackground(final float pRed, final float pGreen, final float pBlue, final BaseSprite pBaseSprite) { - super(pRed, pGreen, pBlue, pBaseSprite); - } + public SpriteBackground(final float pRed, final float pGreen, final float pBlue, final BaseSprite pBaseSprite) { + super(pRed, pGreen, pBlue, pBaseSprite); + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/entity/scene/background/modifier/ColorModifier.java b/AndEngine/src/org/anddev/andengine/entity/scene/background/modifier/ColorModifier.java index 8937435e..8f08a857 100644 --- a/AndEngine/src/org/anddev/andengine/entity/scene/background/modifier/ColorModifier.java +++ b/AndEngine/src/org/anddev/andengine/entity/scene/background/modifier/ColorModifier.java @@ -12,66 +12,66 @@ * @since 14:51:03 - 03.09.2010 */ public class ColorModifier extends BaseTripleValueSpanModifier implements IBackgroundModifier { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - // =========================================================== - // Constructors - // =========================================================== - - public ColorModifier(final float pDuration, final float pFromRed, final float pToRed, final float pFromGreen, final float pToGreen, final float pFromBlue, final float pToBlue) { - this(pDuration, pFromRed, pToRed, pFromGreen, pToGreen, pFromBlue, pToBlue, null, IEaseFunction.DEFAULT); - } - - public ColorModifier(final float pDuration, final float pFromRed, final float pToRed, final float pFromGreen, final float pToGreen, final float pFromBlue, final float pToBlue, final IEaseFunction pEaseFunction) { - this(pDuration, pFromRed, pToRed, pFromGreen, pToGreen, pFromBlue, pToBlue, null, pEaseFunction); - } - - public ColorModifier(final float pDuration, final float pFromRed, final float pToRed, final float pFromGreen, final float pToGreen, final float pFromBlue, final float pToBlue, final IBackgroundModifierListener pBackgroundModifierListener) { - super(pDuration, pFromRed, pToRed, pFromGreen, pToGreen, pFromBlue, pToBlue, pBackgroundModifierListener, IEaseFunction.DEFAULT); - } - - public ColorModifier(final float pDuration, final float pFromRed, final float pToRed, final float pFromGreen, final float pToGreen, final float pFromBlue, final float pToBlue, final IBackgroundModifierListener pBackgroundModifierListener, final IEaseFunction pEaseFunction) { - super(pDuration, pFromRed, pToRed, pFromGreen, pToGreen, pFromBlue, pToBlue, pBackgroundModifierListener, pEaseFunction); - } - - protected ColorModifier(final ColorModifier pColorModifier) { - super(pColorModifier); - } - - @Override - public ColorModifier deepCopy(){ - return new ColorModifier(this); - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - protected void onSetInitialValues(final IBackground pBackground, final float pRed, final float pGreen, final float pBlue) { - pBackground.setColor(pRed, pGreen, pBlue); - } - - @Override - protected void onSetValues(final IBackground pBackground, final float pPerctentageDone, final float pRed, final float pGreen, final float pBlue) { - pBackground.setColor(pRed, pGreen, pBlue); - } - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + // =========================================================== + // Constructors + // =========================================================== + + public ColorModifier(final float pDuration, final float pFromRed, final float pToRed, final float pFromGreen, final float pToGreen, final float pFromBlue, final float pToBlue) { + this(pDuration, pFromRed, pToRed, pFromGreen, pToGreen, pFromBlue, pToBlue, null, IEaseFunction.DEFAULT); + } + + public ColorModifier(final float pDuration, final float pFromRed, final float pToRed, final float pFromGreen, final float pToGreen, final float pFromBlue, final float pToBlue, final IEaseFunction pEaseFunction) { + this(pDuration, pFromRed, pToRed, pFromGreen, pToGreen, pFromBlue, pToBlue, null, pEaseFunction); + } + + public ColorModifier(final float pDuration, final float pFromRed, final float pToRed, final float pFromGreen, final float pToGreen, final float pFromBlue, final float pToBlue, final IBackgroundModifierListener pBackgroundModifierListener) { + super(pDuration, pFromRed, pToRed, pFromGreen, pToGreen, pFromBlue, pToBlue, pBackgroundModifierListener, IEaseFunction.DEFAULT); + } + + public ColorModifier(final float pDuration, final float pFromRed, final float pToRed, final float pFromGreen, final float pToGreen, final float pFromBlue, final float pToBlue, final IBackgroundModifierListener pBackgroundModifierListener, final IEaseFunction pEaseFunction) { + super(pDuration, pFromRed, pToRed, pFromGreen, pToGreen, pFromBlue, pToBlue, pBackgroundModifierListener, pEaseFunction); + } + + protected ColorModifier(final ColorModifier pColorModifier) { + super(pColorModifier); + } + + @Override + public ColorModifier deepCopy(){ + return new ColorModifier(this); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + protected void onSetInitialValues(final IBackground pBackground, final float pRed, final float pGreen, final float pBlue) { + pBackground.setColor(pRed, pGreen, pBlue); + } + + @Override + protected void onSetValues(final IBackground pBackground, final float pPerctentageDone, final float pRed, final float pGreen, final float pBlue) { + pBackground.setColor(pRed, pGreen, pBlue); + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/entity/scene/background/modifier/IBackgroundModifier.java b/AndEngine/src/org/anddev/andengine/entity/scene/background/modifier/IBackgroundModifier.java index 59022f36..1f308e8a 100644 --- a/AndEngine/src/org/anddev/andengine/entity/scene/background/modifier/IBackgroundModifier.java +++ b/AndEngine/src/org/anddev/andengine/entity/scene/background/modifier/IBackgroundModifier.java @@ -11,28 +11,28 @@ * @since 14:55:54 - 03.09.2010 */ public interface IBackgroundModifier extends IModifier { - // =========================================================== - // Final Fields - // =========================================================== + // =========================================================== + // Final Fields + // =========================================================== - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - @Override - public IBackgroundModifier deepCopy() throws DeepCopyNotSupportedException; + @Override + public IBackgroundModifier deepCopy() throws DeepCopyNotSupportedException; - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== - public static interface IBackgroundModifierListener extends IModifierListener{ - // =========================================================== - // Final Fields - // =========================================================== + public static interface IBackgroundModifierListener extends IModifierListener{ + // =========================================================== + // Final Fields + // =========================================================== - // =========================================================== - // Methods - // =========================================================== - } + // =========================================================== + // Methods + // =========================================================== + } } diff --git a/AndEngine/src/org/anddev/andengine/entity/scene/background/modifier/LoopBackgroundModifier.java b/AndEngine/src/org/anddev/andengine/entity/scene/background/modifier/LoopBackgroundModifier.java index 6736c493..c63180b7 100644 --- a/AndEngine/src/org/anddev/andengine/entity/scene/background/modifier/LoopBackgroundModifier.java +++ b/AndEngine/src/org/anddev/andengine/entity/scene/background/modifier/LoopBackgroundModifier.java @@ -11,70 +11,70 @@ * @since 15:03:53 - 03.09.2010 */ public class LoopBackgroundModifier extends LoopModifier implements IBackgroundModifier { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - // =========================================================== - // Constructors - // =========================================================== - - public LoopBackgroundModifier(final IBackgroundModifier pBackgroundModifier) { - super(pBackgroundModifier); - } - - public LoopBackgroundModifier(final IBackgroundModifier pBackgroundModifier, final int pLoopCount) { - super(pBackgroundModifier, pLoopCount); - } - - public LoopBackgroundModifier(final IBackgroundModifier pBackgroundModifier, final int pLoopCount, final ILoopBackgroundModifierListener pLoopModifierListener) { - super(pBackgroundModifier, pLoopCount, pLoopModifierListener, (IBackgroundModifierListener)null); - } - - public LoopBackgroundModifier(final IBackgroundModifier pBackgroundModifier, final int pLoopCount, final IBackgroundModifierListener pBackgroundModifierListener) { - super(pBackgroundModifier, pLoopCount, pBackgroundModifierListener); - } - - public LoopBackgroundModifier(final IBackgroundModifier pBackgroundModifier, final int pLoopCount, final ILoopBackgroundModifierListener pLoopModifierListener, final IBackgroundModifierListener pBackgroundModifierListener) { - super(pBackgroundModifier, pLoopCount, pLoopModifierListener, pBackgroundModifierListener); - } - - protected LoopBackgroundModifier(final LoopBackgroundModifier pLoopBackgroundModifier) throws DeepCopyNotSupportedException { - super(pLoopBackgroundModifier); - } - - @Override - public LoopBackgroundModifier deepCopy() throws DeepCopyNotSupportedException { - return new LoopBackgroundModifier(this); - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== - - public interface ILoopBackgroundModifierListener extends ILoopModifierListener { - // =========================================================== - // Final Fields - // =========================================================== - - // =========================================================== - // Methods - // =========================================================== - } + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + // =========================================================== + // Constructors + // =========================================================== + + public LoopBackgroundModifier(final IBackgroundModifier pBackgroundModifier) { + super(pBackgroundModifier); + } + + public LoopBackgroundModifier(final IBackgroundModifier pBackgroundModifier, final int pLoopCount) { + super(pBackgroundModifier, pLoopCount); + } + + public LoopBackgroundModifier(final IBackgroundModifier pBackgroundModifier, final int pLoopCount, final ILoopBackgroundModifierListener pLoopModifierListener) { + super(pBackgroundModifier, pLoopCount, pLoopModifierListener, (IBackgroundModifierListener)null); + } + + public LoopBackgroundModifier(final IBackgroundModifier pBackgroundModifier, final int pLoopCount, final IBackgroundModifierListener pBackgroundModifierListener) { + super(pBackgroundModifier, pLoopCount, pBackgroundModifierListener); + } + + public LoopBackgroundModifier(final IBackgroundModifier pBackgroundModifier, final int pLoopCount, final ILoopBackgroundModifierListener pLoopModifierListener, final IBackgroundModifierListener pBackgroundModifierListener) { + super(pBackgroundModifier, pLoopCount, pLoopModifierListener, pBackgroundModifierListener); + } + + protected LoopBackgroundModifier(final LoopBackgroundModifier pLoopBackgroundModifier) throws DeepCopyNotSupportedException { + super(pLoopBackgroundModifier); + } + + @Override + public LoopBackgroundModifier deepCopy() throws DeepCopyNotSupportedException { + return new LoopBackgroundModifier(this); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== + + public interface ILoopBackgroundModifierListener extends ILoopModifierListener { + // =========================================================== + // Final Fields + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + } } diff --git a/AndEngine/src/org/anddev/andengine/entity/scene/background/modifier/ParallelBackgroundModifier.java b/AndEngine/src/org/anddev/andengine/entity/scene/background/modifier/ParallelBackgroundModifier.java index a204dcbc..e245ab6f 100644 --- a/AndEngine/src/org/anddev/andengine/entity/scene/background/modifier/ParallelBackgroundModifier.java +++ b/AndEngine/src/org/anddev/andengine/entity/scene/background/modifier/ParallelBackgroundModifier.java @@ -11,48 +11,48 @@ * @since 15:03:57 - 03.09.2010 */ public class ParallelBackgroundModifier extends ParallelModifier implements IBackgroundModifier { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - // =========================================================== - // Constructors - // =========================================================== - - public ParallelBackgroundModifier(final IBackgroundModifier... pBackgroundModifiers) throws IllegalArgumentException { - super(pBackgroundModifiers); - } - - public ParallelBackgroundModifier(final IBackgroundModifierListener pBackgroundModifierListener, final IBackgroundModifier... pBackgroundModifiers) throws IllegalArgumentException { - super(pBackgroundModifierListener, pBackgroundModifiers); - } - - protected ParallelBackgroundModifier(final ParallelBackgroundModifier pParallelBackgroundModifier) throws DeepCopyNotSupportedException { - super(pParallelBackgroundModifier); - } - - @Override - public ParallelBackgroundModifier deepCopy() throws DeepCopyNotSupportedException { - return new ParallelBackgroundModifier(this); - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + // =========================================================== + // Constructors + // =========================================================== + + public ParallelBackgroundModifier(final IBackgroundModifier... pBackgroundModifiers) throws IllegalArgumentException { + super(pBackgroundModifiers); + } + + public ParallelBackgroundModifier(final IBackgroundModifierListener pBackgroundModifierListener, final IBackgroundModifier... pBackgroundModifiers) throws IllegalArgumentException { + super(pBackgroundModifierListener, pBackgroundModifiers); + } + + protected ParallelBackgroundModifier(final ParallelBackgroundModifier pParallelBackgroundModifier) throws DeepCopyNotSupportedException { + super(pParallelBackgroundModifier); + } + + @Override + public ParallelBackgroundModifier deepCopy() throws DeepCopyNotSupportedException { + return new ParallelBackgroundModifier(this); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/entity/scene/background/modifier/SequenceBackgroundModifier.java b/AndEngine/src/org/anddev/andengine/entity/scene/background/modifier/SequenceBackgroundModifier.java index cae8e08d..56664764 100644 --- a/AndEngine/src/org/anddev/andengine/entity/scene/background/modifier/SequenceBackgroundModifier.java +++ b/AndEngine/src/org/anddev/andengine/entity/scene/background/modifier/SequenceBackgroundModifier.java @@ -11,66 +11,66 @@ * @since 15:04:02 - 03.09.2010 */ public class SequenceBackgroundModifier extends SequenceModifier implements IBackgroundModifier { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - public SequenceBackgroundModifier(final IBackgroundModifier... pBackgroundModifiers) throws IllegalArgumentException { - super(pBackgroundModifiers); - } - - public SequenceBackgroundModifier(final ISubSequenceBackgroundModifierListener pSubSequenceBackgroundModifierListener, final IBackgroundModifier... pBackgroundModifiers) throws IllegalArgumentException { - super(pSubSequenceBackgroundModifierListener, pBackgroundModifiers); - } + public SequenceBackgroundModifier(final IBackgroundModifier... pBackgroundModifiers) throws IllegalArgumentException { + super(pBackgroundModifiers); + } + + public SequenceBackgroundModifier(final ISubSequenceBackgroundModifierListener pSubSequenceBackgroundModifierListener, final IBackgroundModifier... pBackgroundModifiers) throws IllegalArgumentException { + super(pSubSequenceBackgroundModifierListener, pBackgroundModifiers); + } - public SequenceBackgroundModifier(final IBackgroundModifierListener pBackgroundModifierListener, final IBackgroundModifier... pBackgroundModifiers) throws IllegalArgumentException { - super(pBackgroundModifierListener, pBackgroundModifiers); - } + public SequenceBackgroundModifier(final IBackgroundModifierListener pBackgroundModifierListener, final IBackgroundModifier... pBackgroundModifiers) throws IllegalArgumentException { + super(pBackgroundModifierListener, pBackgroundModifiers); + } - public SequenceBackgroundModifier(final ISubSequenceBackgroundModifierListener pSubSequenceBackgroundModifierListener, final IBackgroundModifierListener pBackgroundModifierListener, final IBackgroundModifier... pBackgroundModifiers) throws IllegalArgumentException { - super(pSubSequenceBackgroundModifierListener, pBackgroundModifierListener, pBackgroundModifiers); - } + public SequenceBackgroundModifier(final ISubSequenceBackgroundModifierListener pSubSequenceBackgroundModifierListener, final IBackgroundModifierListener pBackgroundModifierListener, final IBackgroundModifier... pBackgroundModifiers) throws IllegalArgumentException { + super(pSubSequenceBackgroundModifierListener, pBackgroundModifierListener, pBackgroundModifiers); + } - protected SequenceBackgroundModifier(final SequenceBackgroundModifier pSequenceBackgroundModifier) throws DeepCopyNotSupportedException { - super(pSequenceBackgroundModifier); - } + protected SequenceBackgroundModifier(final SequenceBackgroundModifier pSequenceBackgroundModifier) throws DeepCopyNotSupportedException { + super(pSequenceBackgroundModifier); + } - @Override - public SequenceBackgroundModifier deepCopy() throws DeepCopyNotSupportedException { - return new SequenceBackgroundModifier(this); - } + @Override + public SequenceBackgroundModifier deepCopy() throws DeepCopyNotSupportedException { + return new SequenceBackgroundModifier(this); + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== - public interface ISubSequenceBackgroundModifierListener extends ISubSequenceModifierListener { - // =========================================================== - // Final Fields - // =========================================================== + public interface ISubSequenceBackgroundModifierListener extends ISubSequenceModifierListener { + // =========================================================== + // Final Fields + // =========================================================== - // =========================================================== - // Methods - // =========================================================== - } + // =========================================================== + // Methods + // =========================================================== + } } diff --git a/AndEngine/src/org/anddev/andengine/entity/scene/menu/MenuScene.java b/AndEngine/src/org/anddev/andengine/entity/scene/menu/MenuScene.java index dabaf2c0..28eca3fa 100644 --- a/AndEngine/src/org/anddev/andengine/entity/scene/menu/MenuScene.java +++ b/AndEngine/src/org/anddev/andengine/entity/scene/menu/MenuScene.java @@ -21,189 +21,189 @@ * @since 20:06:51 - 01.04.2010 */ public class MenuScene extends CameraScene implements IOnAreaTouchListener, IOnSceneTouchListener { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - private final ArrayList mMenuItems = new ArrayList(); - - private IOnMenuItemClickListener mOnMenuItemClickListener; - - private IMenuAnimator mMenuAnimator = IMenuAnimator.DEFAULT; - - private IMenuItem mSelectedMenuItem; - - // =========================================================== - // Constructors - // =========================================================== - - public MenuScene() { - this(null, null); - } - - public MenuScene(final IOnMenuItemClickListener pOnMenuItemClickListener) { - this(null, pOnMenuItemClickListener); - } - - public MenuScene(final Camera pCamera) { - this(pCamera, null); - } - - public MenuScene(final Camera pCamera, final IOnMenuItemClickListener pOnMenuItemClickListener) { - super(pCamera); - this.mOnMenuItemClickListener = pOnMenuItemClickListener; - this.setOnSceneTouchListener(this); - this.setOnAreaTouchListener(this); - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - public IOnMenuItemClickListener getOnMenuItemClickListener() { - return this.mOnMenuItemClickListener; - } - - public void setOnMenuItemClickListener(final IOnMenuItemClickListener pOnMenuItemClickListener) { - this.mOnMenuItemClickListener = pOnMenuItemClickListener; - } - - public int getMenuItemCount() { - return this.mMenuItems.size(); - } - - public void addMenuItem(final IMenuItem pMenuItem) { - this.mMenuItems.add(pMenuItem); - this.attachChild(pMenuItem); - this.registerTouchArea(pMenuItem); - } - - @Override - public MenuScene getChildScene() { - return (MenuScene)super.getChildScene(); - } - - @Override - public void setChildScene(final Scene pChildScene, final boolean pModalDraw, final boolean pModalUpdate, final boolean pModalTouch) throws IllegalArgumentException { - if(pChildScene instanceof MenuScene) { - super.setChildScene(pChildScene, pModalDraw, pModalUpdate, pModalTouch); - } else { - throw new IllegalArgumentException("MenuScene accepts only MenuScenes as a ChildScene."); - } - } - - @Override - public void clearChildScene() { - if(this.getChildScene() != null) { - this.getChildScene().reset(); - super.clearChildScene(); - } - } - - public void setMenuAnimator(final IMenuAnimator pMenuAnimator) { - this.mMenuAnimator = pMenuAnimator; - } - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final ITouchArea pTouchArea, final float pTouchAreaLocalX, final float pTouchAreaLocalY) { - final IMenuItem menuItem = (IMenuItem)pTouchArea; - - switch(pSceneTouchEvent.getAction()) { - case MotionEvent.ACTION_DOWN: - case MotionEvent.ACTION_MOVE: - 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) { - final boolean handled = this.mOnMenuItemClickListener.onMenuItemClicked(this, menuItem, pTouchAreaLocalX, pTouchAreaLocalY); - menuItem.onUnselected(); - this.mSelectedMenuItem = null; - return handled; - } - break; - case MotionEvent.ACTION_CANCEL: - menuItem.onUnselected(); - this.mSelectedMenuItem = null; - break; - } - return true; - } - - @Override - public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) { - if(this.mSelectedMenuItem != null) { - this.mSelectedMenuItem.onUnselected(); - this.mSelectedMenuItem = null; - } - return false; - } - - @Override - public void back() { - super.back(); - - this.reset(); - } - - @Override - public void reset() { - super.reset(); - - final ArrayList menuItems = this.mMenuItems; - for(int i = menuItems.size() - 1; i >= 0; i--) { - menuItems.get(i).reset(); - } - - this.prepareAnimations(); - } - - // =========================================================== - // Methods - // =========================================================== - - public void closeMenuScene() { - this.back(); - } - - public void buildAnimations() { - this.prepareAnimations(); - - final float cameraWidthRaw = this.mCamera.getWidthRaw(); - final float cameraHeightRaw = this.mCamera.getHeightRaw(); - this.mMenuAnimator.buildAnimations(this.mMenuItems, cameraWidthRaw, cameraHeightRaw); - } - - public void prepareAnimations() { - final float cameraWidthRaw = this.mCamera.getWidthRaw(); - final float cameraHeightRaw = this.mCamera.getHeightRaw(); - this.mMenuAnimator.prepareAnimations(this.mMenuItems, cameraWidthRaw, cameraHeightRaw); - } - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== - - public static interface IOnMenuItemClickListener { - // =========================================================== - // Final Fields - // =========================================================== - - // =========================================================== - // Methods - // =========================================================== - - public boolean onMenuItemClicked(final MenuScene pMenuScene, final IMenuItem pMenuItem, final float pMenuItemLocalX, final float pMenuItemLocalY); - } + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + private final ArrayList mMenuItems = new ArrayList(); + + private IOnMenuItemClickListener mOnMenuItemClickListener; + + private IMenuAnimator mMenuAnimator = IMenuAnimator.DEFAULT; + + private IMenuItem mSelectedMenuItem; + + // =========================================================== + // Constructors + // =========================================================== + + public MenuScene() { + this(null, null); + } + + public MenuScene(final IOnMenuItemClickListener pOnMenuItemClickListener) { + this(null, pOnMenuItemClickListener); + } + + public MenuScene(final Camera pCamera) { + this(pCamera, null); + } + + public MenuScene(final Camera pCamera, final IOnMenuItemClickListener pOnMenuItemClickListener) { + super(pCamera); + this.mOnMenuItemClickListener = pOnMenuItemClickListener; + this.setOnSceneTouchListener(this); + this.setOnAreaTouchListener(this); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + public IOnMenuItemClickListener getOnMenuItemClickListener() { + return this.mOnMenuItemClickListener; + } + + public void setOnMenuItemClickListener(final IOnMenuItemClickListener pOnMenuItemClickListener) { + this.mOnMenuItemClickListener = pOnMenuItemClickListener; + } + + public int getMenuItemCount() { + return this.mMenuItems.size(); + } + + public void addMenuItem(final IMenuItem pMenuItem) { + this.mMenuItems.add(pMenuItem); + this.attachChild(pMenuItem); + this.registerTouchArea(pMenuItem); + } + + @Override + public MenuScene getChildScene() { + return (MenuScene)super.getChildScene(); + } + + @Override + public void setChildScene(final Scene pChildScene, final boolean pModalDraw, final boolean pModalUpdate, final boolean pModalTouch) throws IllegalArgumentException { + if(pChildScene instanceof MenuScene) { + super.setChildScene(pChildScene, pModalDraw, pModalUpdate, pModalTouch); + } else { + throw new IllegalArgumentException("MenuScene accepts only MenuScenes as a ChildScene."); + } + } + + @Override + public void clearChildScene() { + if(this.getChildScene() != null) { + this.getChildScene().reset(); + super.clearChildScene(); + } + } + + public void setMenuAnimator(final IMenuAnimator pMenuAnimator) { + this.mMenuAnimator = pMenuAnimator; + } + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final ITouchArea pTouchArea, final float pTouchAreaLocalX, final float pTouchAreaLocalY) { + final IMenuItem menuItem = (IMenuItem)pTouchArea; + + switch(pSceneTouchEvent.getAction()) { + case MotionEvent.ACTION_DOWN: + case MotionEvent.ACTION_MOVE: + 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) { + final boolean handled = this.mOnMenuItemClickListener.onMenuItemClicked(this, menuItem, pTouchAreaLocalX, pTouchAreaLocalY); + menuItem.onUnselected(); + this.mSelectedMenuItem = null; + return handled; + } + break; + case MotionEvent.ACTION_CANCEL: + menuItem.onUnselected(); + this.mSelectedMenuItem = null; + break; + } + return true; + } + + @Override + public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) { + if(this.mSelectedMenuItem != null) { + this.mSelectedMenuItem.onUnselected(); + this.mSelectedMenuItem = null; + } + return false; + } + + @Override + public void back() { + super.back(); + + this.reset(); + } + + @Override + public void reset() { + super.reset(); + + final ArrayList menuItems = this.mMenuItems; + for(int i = menuItems.size() - 1; i >= 0; i--) { + menuItems.get(i).reset(); + } + + this.prepareAnimations(); + } + + // =========================================================== + // Methods + // =========================================================== + + public void closeMenuScene() { + this.back(); + } + + public void buildAnimations() { + this.prepareAnimations(); + + final float cameraWidthRaw = this.mCamera.getWidthRaw(); + final float cameraHeightRaw = this.mCamera.getHeightRaw(); + this.mMenuAnimator.buildAnimations(this.mMenuItems, cameraWidthRaw, cameraHeightRaw); + } + + public void prepareAnimations() { + final float cameraWidthRaw = this.mCamera.getWidthRaw(); + final float cameraHeightRaw = this.mCamera.getHeightRaw(); + this.mMenuAnimator.prepareAnimations(this.mMenuItems, cameraWidthRaw, cameraHeightRaw); + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== + + public static interface IOnMenuItemClickListener { + // =========================================================== + // Final Fields + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + public boolean onMenuItemClicked(final MenuScene pMenuScene, final IMenuItem pMenuItem, final float pMenuItemLocalX, final float pMenuItemLocalY); + } } diff --git a/AndEngine/src/org/anddev/andengine/entity/scene/menu/animator/AlphaMenuAnimator.java b/AndEngine/src/org/anddev/andengine/entity/scene/menu/animator/AlphaMenuAnimator.java index 61c75e04..702449ec 100644 --- a/AndEngine/src/org/anddev/andengine/entity/scene/menu/animator/AlphaMenuAnimator.java +++ b/AndEngine/src/org/anddev/andengine/entity/scene/menu/animator/AlphaMenuAnimator.java @@ -15,113 +15,113 @@ * @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.setRemoveWhenFinished(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 - // =========================================================== + // =========================================================== + // 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.setRemoveWhenFinished(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/AndEngine/src/org/anddev/andengine/entity/scene/menu/animator/BaseMenuAnimator.java b/AndEngine/src/org/anddev/andengine/entity/scene/menu/animator/BaseMenuAnimator.java index 4d336424..7f8727ac 100644 --- a/AndEngine/src/org/anddev/andengine/entity/scene/menu/animator/BaseMenuAnimator.java +++ b/AndEngine/src/org/anddev/andengine/entity/scene/menu/animator/BaseMenuAnimator.java @@ -14,95 +14,95 @@ * @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, IEaseFunction.DEFAULT); - } - - 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 - // =========================================================== + // =========================================================== + // 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, IEaseFunction.DEFAULT); + } + + 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/AndEngine/src/org/anddev/andengine/entity/scene/menu/animator/DirectMenuAnimator.java b/AndEngine/src/org/anddev/andengine/entity/scene/menu/animator/DirectMenuAnimator.java index bd63b085..812fa2f9 100644 --- a/AndEngine/src/org/anddev/andengine/entity/scene/menu/animator/DirectMenuAnimator.java +++ b/AndEngine/src/org/anddev/andengine/entity/scene/menu/animator/DirectMenuAnimator.java @@ -13,86 +13,86 @@ * @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 - // =========================================================== + // =========================================================== + // 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/AndEngine/src/org/anddev/andengine/entity/scene/menu/animator/IMenuAnimator.java b/AndEngine/src/org/anddev/andengine/entity/scene/menu/animator/IMenuAnimator.java index 99bb90b6..40ea03cd 100644 --- a/AndEngine/src/org/anddev/andengine/entity/scene/menu/animator/IMenuAnimator.java +++ b/AndEngine/src/org/anddev/andengine/entity/scene/menu/animator/IMenuAnimator.java @@ -12,16 +12,16 @@ * @since 10:50:36 - 02.04.2010 */ public interface IMenuAnimator { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - public static final IMenuAnimator DEFAULT = new AlphaMenuAnimator(); + public static final IMenuAnimator DEFAULT = new AlphaMenuAnimator(); - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // 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); + 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/AndEngine/src/org/anddev/andengine/entity/scene/menu/animator/SlideMenuAnimator.java b/AndEngine/src/org/anddev/andengine/entity/scene/menu/animator/SlideMenuAnimator.java index ab583ccf..12ecfd69 100644 --- a/AndEngine/src/org/anddev/andengine/entity/scene/menu/animator/SlideMenuAnimator.java +++ b/AndEngine/src/org/anddev/andengine/entity/scene/menu/animator/SlideMenuAnimator.java @@ -15,119 +15,119 @@ * @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.setRemoveWhenFinished(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 - // =========================================================== + // =========================================================== + // 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.setRemoveWhenFinished(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/AndEngine/src/org/anddev/andengine/entity/scene/menu/item/AnimatedSpriteMenuItem.java b/AndEngine/src/org/anddev/andengine/entity/scene/menu/item/AnimatedSpriteMenuItem.java index 46ef80a3..0b91608e 100644 --- a/AndEngine/src/org/anddev/andengine/entity/scene/menu/item/AnimatedSpriteMenuItem.java +++ b/AndEngine/src/org/anddev/andengine/entity/scene/menu/item/AnimatedSpriteMenuItem.java @@ -11,57 +11,57 @@ * @since 15:44:39 - 07.07.2010 */ public class AnimatedSpriteMenuItem extends AnimatedSprite implements IMenuItem { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - private final int mID; + private final int mID; - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - public AnimatedSpriteMenuItem(final int pID, final TiledTextureRegion pTiledTextureRegion) { - super(0, 0, pTiledTextureRegion); - this.mID = pID; - } + public AnimatedSpriteMenuItem(final int pID, final TiledTextureRegion pTiledTextureRegion) { + super(0, 0, pTiledTextureRegion); + this.mID = pID; + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - @Override - public int getID() { - return this.mID; - } + @Override + public int getID() { + return this.mID; + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - @Override - public void onSelected() { - /* Nothing. */ - } + @Override + public void onSelected() { + /* Nothing. */ + } - @Override - public void onUnselected() { - /* Nothing. */ - } + @Override + public void onUnselected() { + /* Nothing. */ + } - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/entity/scene/menu/item/IMenuItem.java b/AndEngine/src/org/anddev/andengine/entity/scene/menu/item/IMenuItem.java index b3517331..d3e4fa56 100644 --- a/AndEngine/src/org/anddev/andengine/entity/scene/menu/item/IMenuItem.java +++ b/AndEngine/src/org/anddev/andengine/entity/scene/menu/item/IMenuItem.java @@ -10,15 +10,15 @@ * @since 13:27:16 - 07.07.2010 */ public interface IMenuItem extends IShape { - // =========================================================== - // Final Fields - // =========================================================== + // =========================================================== + // Final Fields + // =========================================================== - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - public int getID(); - public abstract void onSelected(); - public abstract void onUnselected(); + public int getID(); + public abstract void onSelected(); + public abstract void onUnselected(); } diff --git a/AndEngine/src/org/anddev/andengine/entity/scene/menu/item/SpriteMenuItem.java b/AndEngine/src/org/anddev/andengine/entity/scene/menu/item/SpriteMenuItem.java index a783875a..732859dc 100644 --- a/AndEngine/src/org/anddev/andengine/entity/scene/menu/item/SpriteMenuItem.java +++ b/AndEngine/src/org/anddev/andengine/entity/scene/menu/item/SpriteMenuItem.java @@ -11,57 +11,57 @@ * @since 20:15:20 - 01.04.2010 */ public class SpriteMenuItem extends Sprite implements IMenuItem { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - private final int mID; + private final int mID; - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - public SpriteMenuItem(final int pID, final TextureRegion pTextureRegion) { - super(0, 0, pTextureRegion); - this.mID = pID; - } + public SpriteMenuItem(final int pID, final TextureRegion pTextureRegion) { + super(0, 0, pTextureRegion); + this.mID = pID; + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - @Override - public int getID() { - return this.mID; - } + @Override + public int getID() { + return this.mID; + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - @Override - public void onSelected() { - /* Nothing. */ - } + @Override + public void onSelected() { + /* Nothing. */ + } - @Override - public void onUnselected() { - /* Nothing. */ - } + @Override + public void onUnselected() { + /* Nothing. */ + } - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/entity/scene/menu/item/TextMenuItem.java b/AndEngine/src/org/anddev/andengine/entity/scene/menu/item/TextMenuItem.java index eaff2a53..39882b02 100644 --- a/AndEngine/src/org/anddev/andengine/entity/scene/menu/item/TextMenuItem.java +++ b/AndEngine/src/org/anddev/andengine/entity/scene/menu/item/TextMenuItem.java @@ -11,57 +11,57 @@ * @since 20:15:20 - 01.04.2010 */ public class TextMenuItem extends Text implements IMenuItem{ - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - private final int mID; + private final int mID; - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - public TextMenuItem(final int pID, final Font pFont, final String pText) { - super(0, 0, pFont, pText); - this.mID = pID; - } + public TextMenuItem(final int pID, final Font pFont, final String pText) { + super(0, 0, pFont, pText); + this.mID = pID; + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - @Override - public int getID() { - return this.mID; - } + @Override + public int getID() { + return this.mID; + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - @Override - public void onSelected() { - /* Nothing. */ - } + @Override + public void onSelected() { + /* Nothing. */ + } - @Override - public void onUnselected() { - /* Nothing. */ - } + @Override + public void onUnselected() { + /* Nothing. */ + } - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/entity/scene/menu/item/decorator/BaseMenuItemDecorator.java b/AndEngine/src/org/anddev/andengine/entity/scene/menu/item/decorator/BaseMenuItemDecorator.java index 64a27a7a..b194b153 100644 --- a/AndEngine/src/org/anddev/andengine/entity/scene/menu/item/decorator/BaseMenuItemDecorator.java +++ b/AndEngine/src/org/anddev/andengine/entity/scene/menu/item/decorator/BaseMenuItemDecorator.java @@ -24,601 +24,601 @@ * @since 15:05:44 - 18.11.2010 */ public abstract class BaseMenuItemDecorator implements IMenuItem { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - private final IMenuItem mMenuItem; - - // =========================================================== - // Constructors - // =========================================================== - - public BaseMenuItemDecorator(final IMenuItem pMenuItem) { - this.mMenuItem = pMenuItem; - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - protected abstract void onMenuItemSelected(final IMenuItem pMenuItem); - protected abstract void onMenuItemUnselected(final IMenuItem pMenuItem); - protected abstract void onMenuItemReset(final IMenuItem pMenuItem); - - @Override - public int getID() { - return this.mMenuItem.getID(); - } - - @Override - public final void onSelected() { - this.mMenuItem.onSelected(); - this.onMenuItemSelected(this.mMenuItem); - } - - @Override - public final void onUnselected() { - this.mMenuItem.onUnselected(); - this.onMenuItemUnselected(this.mMenuItem); - } - - @Override - public float getX() { - return this.mMenuItem.getX(); - } - - @Override - public float getY() { - return this.mMenuItem.getY(); - } - - @Override - public void setPosition(final IEntity pOtherEntity) { - this.mMenuItem.setPosition(pOtherEntity); - } - - @Override - public void setPosition(final float pX, final float pY) { - this.mMenuItem.setPosition(pX, pY); - } - - @Override - public float getBaseWidth() { - return this.mMenuItem.getBaseWidth(); - } - - @Override - public float getBaseHeight() { - return this.mMenuItem.getBaseHeight(); - } - - @Override - public float getWidth() { - return this.mMenuItem.getWidth(); - } - - @Override - public float getWidthScaled() { - return this.mMenuItem.getWidthScaled(); - } - - @Override - public float getHeight() { - return this.mMenuItem.getHeight(); - } - - @Override - public float getHeightScaled() { - return this.mMenuItem.getHeightScaled(); - } - - @Override - public float getInitialX() { - return this.mMenuItem.getInitialX(); - } - - @Override - public float getInitialY() { - return this.mMenuItem.getInitialY(); - } - - @Override - public float getRed() { - return this.mMenuItem.getRed(); - } - - @Override - public float getGreen() { - return this.mMenuItem.getGreen(); - } - - @Override - public float getBlue() { - return this.mMenuItem.getBlue(); - } - - @Override - public float getAlpha() { - return this.mMenuItem.getAlpha(); - } - - @Override - public void setAlpha(final float pAlpha) { - this.mMenuItem.setAlpha(pAlpha); - } - - @Override - public void setColor(final float pRed, final float pGreen, final float pBlue) { - this.mMenuItem.setColor(pRed, pGreen, pBlue); - } - - @Override - public void setColor(final float pRed, final float pGreen, final float pBlue, final float pAlpha) { - this.mMenuItem.setColor(pRed, pGreen, pBlue, pAlpha); - } - - @Override - public boolean isRotated() { - return this.mMenuItem.isRotated(); - } - - @Override - public float getRotation() { - return this.mMenuItem.getRotation(); - } - - @Override - public void setRotation(final float pRotation) { - this.mMenuItem.setRotation(pRotation); - } - - @Override - public float getRotationCenterX() { - return this.mMenuItem.getRotationCenterX(); - } - - @Override - public float getRotationCenterY() { - return this.mMenuItem.getRotationCenterY(); - } - - @Override - public void setRotationCenterX(final float pRotationCenterX) { - this.mMenuItem.setRotationCenterX(pRotationCenterX); - } - - @Override - public void setRotationCenterY(final float pRotationCenterY) { - this.mMenuItem.setRotationCenterY(pRotationCenterY); - } - - @Override - public void setRotationCenter(final float pRotationCenterX, final float pRotationCenterY) { - this.mMenuItem.setRotationCenter(pRotationCenterX, pRotationCenterY); - } - - @Override - public boolean isScaled() { - return this.mMenuItem.isScaled(); - } - - @Override - public float getScaleX() { - return this.mMenuItem.getScaleX(); - } - - @Override - public float getScaleY() { - return this.mMenuItem.getScaleY(); - } - - @Override - public void setScale(final float pScale) { - this.mMenuItem.setScale(pScale); - } - - @Override - public void setScale(final float pScaleX, final float pScaleY) { - this.mMenuItem.setScale(pScaleX, pScaleY); - } - - @Override - public void setScaleX(final float pScaleX) { - this.mMenuItem.setScaleX(pScaleX); - } - - @Override - public void setScaleY(final float pScaleY) { - this.mMenuItem.setScaleY(pScaleY); - } - - @Override - public float getScaleCenterX() { - return this.mMenuItem.getScaleCenterX(); - } - - @Override - public float getScaleCenterY() { - return this.mMenuItem.getScaleCenterY(); - } - - @Override - public void setScaleCenterX(final float pScaleCenterX) { - this.mMenuItem.setScaleCenterX(pScaleCenterX); - } - - @Override - public void setScaleCenterY(final float pScaleCenterY) { - this.mMenuItem.setScaleCenterY(pScaleCenterY); - } - - @Override - public void setScaleCenter(final float pScaleCenterX, final float pScaleCenterY) { - this.mMenuItem.setScaleCenter(pScaleCenterX, pScaleCenterY); - } - - @Override - public boolean collidesWith(final IShape pOtherShape) { - return this.mMenuItem.collidesWith(pOtherShape); - } - - @Override - public float[] getSceneCenterCoordinates() { - return this.mMenuItem.getSceneCenterCoordinates(); - } - - @Override - public boolean isCullingEnabled() { - return this.mMenuItem.isCullingEnabled(); - } - - @Override - public void registerEntityModifier(final IEntityModifier pEntityModifier) { - this.mMenuItem.registerEntityModifier(pEntityModifier); - } - - @Override - public boolean unregisterEntityModifier(final IEntityModifier pEntityModifier) { - return this.mMenuItem.unregisterEntityModifier(pEntityModifier); - } - - @Override - public boolean unregisterEntityModifiers(final IEntityModifierMatcher pEntityModifierMatcher) { - return this.mMenuItem.unregisterEntityModifiers(pEntityModifierMatcher); - } - - @Override - public void clearEntityModifiers() { - this.mMenuItem.clearEntityModifiers(); - } - - @Override - public void setInitialPosition() { - this.mMenuItem.setInitialPosition(); - } - - @Override - public void setBlendFunction(final int pSourceBlendFunction, final int pDestinationBlendFunction) { - this.mMenuItem.setBlendFunction(pSourceBlendFunction, pDestinationBlendFunction); - } - - @Override - public void setCullingEnabled(final boolean pCullingEnabled) { - this.mMenuItem.setCullingEnabled(pCullingEnabled); - } - - @Override - public int getZIndex() { - return this.mMenuItem.getZIndex(); - } - - @Override - public void setZIndex(final int pZIndex) { - this.mMenuItem.setZIndex(pZIndex); - } - - @Override - public void onDraw(final GL10 pGL, final Camera pCamera) { - this.mMenuItem.onDraw(pGL, pCamera); - } - - @Override - public void onUpdate(final float pSecondsElapsed) { - this.mMenuItem.onUpdate(pSecondsElapsed); - } - - @Override - public void reset() { - this.mMenuItem.reset(); - this.onMenuItemReset(this.mMenuItem); - } - - @Override - public boolean contains(final float pX, final float pY) { - return this.mMenuItem.contains(pX, pY); - } - - @Override - public float[] convertLocalToSceneCoordinates(final float pX, final float pY) { - return this.mMenuItem.convertLocalToSceneCoordinates(pX, pY); - } - - @Override - public float[] convertLocalToSceneCoordinates(final float pX, final float pY, final float[] pReuse) { - return this.mMenuItem.convertLocalToSceneCoordinates(pX, pY, pReuse); - } - - @Override - public float[] convertLocalToSceneCoordinates(final float[] pCoordinates) { - return this.mMenuItem.convertLocalToSceneCoordinates(pCoordinates); - } - - @Override - public float[] convertLocalToSceneCoordinates(final float[] pCoordinates, final float[] pReuse) { - return this.mMenuItem.convertLocalToSceneCoordinates(pCoordinates, pReuse); - } - - @Override - public float[] convertSceneToLocalCoordinates(final float pX, final float pY) { - return this.mMenuItem.convertSceneToLocalCoordinates(pX, pY); - } - - @Override - public float[] convertSceneToLocalCoordinates(final float pX, final float pY, final float[] pReuse) { - return this.mMenuItem.convertSceneToLocalCoordinates(pX, pY, pReuse); - } - - @Override - public float[] convertSceneToLocalCoordinates(final float[] pCoordinates) { - return this.mMenuItem.convertSceneToLocalCoordinates(pCoordinates); - } - - @Override - public float[] convertSceneToLocalCoordinates(final float[] pCoordinates, final float[] pReuse) { - return this.mMenuItem.convertSceneToLocalCoordinates(pCoordinates, pReuse); - } - - @Override - public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final float pTouchAreaLocalX, final float pTouchAreaLocalY) { - return this.mMenuItem.onAreaTouched(pSceneTouchEvent, pTouchAreaLocalX, pTouchAreaLocalY); - } - - @Override - public int getChildCount() { - return this.mMenuItem.getChildCount(); - } - - @Override - public void attachChild(final IEntity pEntity) { - this.mMenuItem.attachChild(pEntity); - } - - @Override - public boolean attachChild(final IEntity pEntity, final int pIndex) { - return this.mMenuItem.attachChild(pEntity, pIndex); - } - - @Override - public IEntity getFirstChild() { - return this.mMenuItem.getFirstChild(); - } - - @Override - public IEntity getLastChild() { - return this.mMenuItem.getLastChild(); - } - - @Override - public IEntity getChild(final int pIndex) { - return this.mMenuItem.getChild(pIndex); - } - - @Override - public int getChildIndex(final IEntity pEntity) { - return this.mMenuItem.getChildIndex(pEntity); - } - - @Override - public boolean setChildIndex(final IEntity pEntity, final int pIndex) { - return this.mMenuItem.setChildIndex(pEntity, pIndex); - } - - @Override - public IEntity findChild(final IEntityMatcher pEntityMatcher) { - return this.mMenuItem.findChild(pEntityMatcher); - } - - public ArrayList query(final IEntityMatcher pEntityMatcher) { - return this.mMenuItem.query(pEntityMatcher); - } - - public > L query(final IEntityMatcher pEntityMatcher, final L pResult) { - return this.mMenuItem.query(pEntityMatcher, pResult); - } - - @Override - public ArrayList queryForSubclass(final IEntityMatcher pEntityMatcher) throws ClassCastException { - return this.mMenuItem.queryForSubclass(pEntityMatcher); - } - - public , S extends IEntity> L queryForSubclass(final IEntityMatcher pEntityMatcher, final L pResult) throws ClassCastException { - return this.mMenuItem.queryForSubclass(pEntityMatcher, pResult); - } - - @Override - public boolean swapChildren(final IEntity pEntityA, final IEntity pEntityB) { - return this.mMenuItem.swapChildren(pEntityA, pEntityB); - } - - @Override - public boolean swapChildren(final int pIndexA, final int pIndexB) { - return this.mMenuItem.swapChildren(pIndexA, pIndexB); - } - - @Override - public void sortChildren() { - this.mMenuItem.sortChildren(); - } - - @Override - public void sortChildren(final Comparator pEntityComparator) { - this.mMenuItem.sortChildren(pEntityComparator); - } - - @Override - public boolean detachSelf() { - return this.mMenuItem.detachSelf(); - } - - @Override - public boolean detachChild(final IEntity pEntity) { - return this.mMenuItem.detachChild(pEntity); - } - - @Override - public IEntity detachChild(final IEntityMatcher pEntityMatcher) { - return this.mMenuItem.detachChild(pEntityMatcher); - } - - @Override - public boolean detachChildren(final IEntityMatcher pEntityMatcher) { - return this.mMenuItem.detachChildren(pEntityMatcher); - } - - @Override - public void detachChildren() { - this.mMenuItem.detachChildren(); - } - - @Override - public void callOnChildren(final IEntityCallable pEntityCallable) { - this.callOnChildren(pEntityCallable); - } - - @Override - public void callOnChildren(final IEntityMatcher pEntityMatcher, final IEntityCallable pEntityCallable) { - this.mMenuItem.callOnChildren(pEntityMatcher, pEntityCallable); - } - - @Override - public Transformation getLocalToSceneTransformation() { - return this.mMenuItem.getLocalToSceneTransformation(); - } - - @Override - public Transformation getSceneToLocalTransformation() { - return this.mMenuItem.getSceneToLocalTransformation(); - } - - @Override - public boolean hasParent() { - return this.mMenuItem.hasParent(); - } - - @Override - public IEntity getParent() { - return this.mMenuItem.getParent(); - } - - @Override - public void setParent(final IEntity pEntity) { - this.mMenuItem.setParent(pEntity); - } - - @Override - public boolean isVisible() { - return this.mMenuItem.isVisible(); - } - - @Override - public void setVisible(final boolean pVisible) { - this.mMenuItem.setVisible(pVisible); - } - - @Override - public boolean isChildrenVisible() { - return this.mMenuItem.isChildrenVisible(); - } - - @Override - public void setChildrenVisible(final boolean pChildrenVisible) { - this.mMenuItem.setChildrenVisible(pChildrenVisible); - } - - @Override - public boolean isIgnoreUpdate() { - return this.mMenuItem.isIgnoreUpdate(); - } - - @Override - public void setIgnoreUpdate(final boolean pIgnoreUpdate) { - this.mMenuItem.setIgnoreUpdate(pIgnoreUpdate); - } - - @Override - public boolean isChildrenIgnoreUpdate() { - return this.mMenuItem.isChildrenIgnoreUpdate(); - } - - @Override - public void setChildrenIgnoreUpdate(final boolean pChildrenIgnoreUpdate) { - this.mMenuItem.setChildrenIgnoreUpdate(pChildrenIgnoreUpdate); - } - - @Override - public void setUserData(final Object pUserData) { - this.mMenuItem.setUserData(pUserData); - } - - @Override - public Object getUserData() { - return this.mMenuItem.getUserData(); - } - - @Override - public void onAttached() { - this.mMenuItem.onAttached(); - } - - @Override - public void onDetached() { - this.mMenuItem.onDetached(); - } - - @Override - public void registerUpdateHandler(final IUpdateHandler pUpdateHandler) { - this.mMenuItem.registerUpdateHandler(pUpdateHandler); - } - - @Override - public boolean unregisterUpdateHandler(final IUpdateHandler pUpdateHandler) { - return this.mMenuItem.unregisterUpdateHandler(pUpdateHandler); - } - - @Override - public void clearUpdateHandlers() { - this.mMenuItem.clearUpdateHandlers(); - } - - @Override - public boolean unregisterUpdateHandlers(final IUpdateHandlerMatcher pUpdateHandlerMatcher) { - return this.mMenuItem.unregisterUpdateHandlers(pUpdateHandlerMatcher); - } - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + private final IMenuItem mMenuItem; + + // =========================================================== + // Constructors + // =========================================================== + + public BaseMenuItemDecorator(final IMenuItem pMenuItem) { + this.mMenuItem = pMenuItem; + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + protected abstract void onMenuItemSelected(final IMenuItem pMenuItem); + protected abstract void onMenuItemUnselected(final IMenuItem pMenuItem); + protected abstract void onMenuItemReset(final IMenuItem pMenuItem); + + @Override + public int getID() { + return this.mMenuItem.getID(); + } + + @Override + public final void onSelected() { + this.mMenuItem.onSelected(); + this.onMenuItemSelected(this.mMenuItem); + } + + @Override + public final void onUnselected() { + this.mMenuItem.onUnselected(); + this.onMenuItemUnselected(this.mMenuItem); + } + + @Override + public float getX() { + return this.mMenuItem.getX(); + } + + @Override + public float getY() { + return this.mMenuItem.getY(); + } + + @Override + public void setPosition(final IEntity pOtherEntity) { + this.mMenuItem.setPosition(pOtherEntity); + } + + @Override + public void setPosition(final float pX, final float pY) { + this.mMenuItem.setPosition(pX, pY); + } + + @Override + public float getBaseWidth() { + return this.mMenuItem.getBaseWidth(); + } + + @Override + public float getBaseHeight() { + return this.mMenuItem.getBaseHeight(); + } + + @Override + public float getWidth() { + return this.mMenuItem.getWidth(); + } + + @Override + public float getWidthScaled() { + return this.mMenuItem.getWidthScaled(); + } + + @Override + public float getHeight() { + return this.mMenuItem.getHeight(); + } + + @Override + public float getHeightScaled() { + return this.mMenuItem.getHeightScaled(); + } + + @Override + public float getInitialX() { + return this.mMenuItem.getInitialX(); + } + + @Override + public float getInitialY() { + return this.mMenuItem.getInitialY(); + } + + @Override + public float getRed() { + return this.mMenuItem.getRed(); + } + + @Override + public float getGreen() { + return this.mMenuItem.getGreen(); + } + + @Override + public float getBlue() { + return this.mMenuItem.getBlue(); + } + + @Override + public float getAlpha() { + return this.mMenuItem.getAlpha(); + } + + @Override + public void setAlpha(final float pAlpha) { + this.mMenuItem.setAlpha(pAlpha); + } + + @Override + public void setColor(final float pRed, final float pGreen, final float pBlue) { + this.mMenuItem.setColor(pRed, pGreen, pBlue); + } + + @Override + public void setColor(final float pRed, final float pGreen, final float pBlue, final float pAlpha) { + this.mMenuItem.setColor(pRed, pGreen, pBlue, pAlpha); + } + + @Override + public boolean isRotated() { + return this.mMenuItem.isRotated(); + } + + @Override + public float getRotation() { + return this.mMenuItem.getRotation(); + } + + @Override + public void setRotation(final float pRotation) { + this.mMenuItem.setRotation(pRotation); + } + + @Override + public float getRotationCenterX() { + return this.mMenuItem.getRotationCenterX(); + } + + @Override + public float getRotationCenterY() { + return this.mMenuItem.getRotationCenterY(); + } + + @Override + public void setRotationCenterX(final float pRotationCenterX) { + this.mMenuItem.setRotationCenterX(pRotationCenterX); + } + + @Override + public void setRotationCenterY(final float pRotationCenterY) { + this.mMenuItem.setRotationCenterY(pRotationCenterY); + } + + @Override + public void setRotationCenter(final float pRotationCenterX, final float pRotationCenterY) { + this.mMenuItem.setRotationCenter(pRotationCenterX, pRotationCenterY); + } + + @Override + public boolean isScaled() { + return this.mMenuItem.isScaled(); + } + + @Override + public float getScaleX() { + return this.mMenuItem.getScaleX(); + } + + @Override + public float getScaleY() { + return this.mMenuItem.getScaleY(); + } + + @Override + public void setScale(final float pScale) { + this.mMenuItem.setScale(pScale); + } + + @Override + public void setScale(final float pScaleX, final float pScaleY) { + this.mMenuItem.setScale(pScaleX, pScaleY); + } + + @Override + public void setScaleX(final float pScaleX) { + this.mMenuItem.setScaleX(pScaleX); + } + + @Override + public void setScaleY(final float pScaleY) { + this.mMenuItem.setScaleY(pScaleY); + } + + @Override + public float getScaleCenterX() { + return this.mMenuItem.getScaleCenterX(); + } + + @Override + public float getScaleCenterY() { + return this.mMenuItem.getScaleCenterY(); + } + + @Override + public void setScaleCenterX(final float pScaleCenterX) { + this.mMenuItem.setScaleCenterX(pScaleCenterX); + } + + @Override + public void setScaleCenterY(final float pScaleCenterY) { + this.mMenuItem.setScaleCenterY(pScaleCenterY); + } + + @Override + public void setScaleCenter(final float pScaleCenterX, final float pScaleCenterY) { + this.mMenuItem.setScaleCenter(pScaleCenterX, pScaleCenterY); + } + + @Override + public boolean collidesWith(final IShape pOtherShape) { + return this.mMenuItem.collidesWith(pOtherShape); + } + + @Override + public float[] getSceneCenterCoordinates() { + return this.mMenuItem.getSceneCenterCoordinates(); + } + + @Override + public boolean isCullingEnabled() { + return this.mMenuItem.isCullingEnabled(); + } + + @Override + public void registerEntityModifier(final IEntityModifier pEntityModifier) { + this.mMenuItem.registerEntityModifier(pEntityModifier); + } + + @Override + public boolean unregisterEntityModifier(final IEntityModifier pEntityModifier) { + return this.mMenuItem.unregisterEntityModifier(pEntityModifier); + } + + @Override + public boolean unregisterEntityModifiers(final IEntityModifierMatcher pEntityModifierMatcher) { + return this.mMenuItem.unregisterEntityModifiers(pEntityModifierMatcher); + } + + @Override + public void clearEntityModifiers() { + this.mMenuItem.clearEntityModifiers(); + } + + @Override + public void setInitialPosition() { + this.mMenuItem.setInitialPosition(); + } + + @Override + public void setBlendFunction(final int pSourceBlendFunction, final int pDestinationBlendFunction) { + this.mMenuItem.setBlendFunction(pSourceBlendFunction, pDestinationBlendFunction); + } + + @Override + public void setCullingEnabled(final boolean pCullingEnabled) { + this.mMenuItem.setCullingEnabled(pCullingEnabled); + } + + @Override + public int getZIndex() { + return this.mMenuItem.getZIndex(); + } + + @Override + public void setZIndex(final int pZIndex) { + this.mMenuItem.setZIndex(pZIndex); + } + + @Override + public void onDraw(final GL10 pGL, final Camera pCamera) { + this.mMenuItem.onDraw(pGL, pCamera); + } + + @Override + public void onUpdate(final float pSecondsElapsed) { + this.mMenuItem.onUpdate(pSecondsElapsed); + } + + @Override + public void reset() { + this.mMenuItem.reset(); + this.onMenuItemReset(this.mMenuItem); + } + + @Override + public boolean contains(final float pX, final float pY) { + return this.mMenuItem.contains(pX, pY); + } + + @Override + public float[] convertLocalToSceneCoordinates(final float pX, final float pY) { + return this.mMenuItem.convertLocalToSceneCoordinates(pX, pY); + } + + @Override + public float[] convertLocalToSceneCoordinates(final float pX, final float pY, final float[] pReuse) { + return this.mMenuItem.convertLocalToSceneCoordinates(pX, pY, pReuse); + } + + @Override + public float[] convertLocalToSceneCoordinates(final float[] pCoordinates) { + return this.mMenuItem.convertLocalToSceneCoordinates(pCoordinates); + } + + @Override + public float[] convertLocalToSceneCoordinates(final float[] pCoordinates, final float[] pReuse) { + return this.mMenuItem.convertLocalToSceneCoordinates(pCoordinates, pReuse); + } + + @Override + public float[] convertSceneToLocalCoordinates(final float pX, final float pY) { + return this.mMenuItem.convertSceneToLocalCoordinates(pX, pY); + } + + @Override + public float[] convertSceneToLocalCoordinates(final float pX, final float pY, final float[] pReuse) { + return this.mMenuItem.convertSceneToLocalCoordinates(pX, pY, pReuse); + } + + @Override + public float[] convertSceneToLocalCoordinates(final float[] pCoordinates) { + return this.mMenuItem.convertSceneToLocalCoordinates(pCoordinates); + } + + @Override + public float[] convertSceneToLocalCoordinates(final float[] pCoordinates, final float[] pReuse) { + return this.mMenuItem.convertSceneToLocalCoordinates(pCoordinates, pReuse); + } + + @Override + public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final float pTouchAreaLocalX, final float pTouchAreaLocalY) { + return this.mMenuItem.onAreaTouched(pSceneTouchEvent, pTouchAreaLocalX, pTouchAreaLocalY); + } + + @Override + public int getChildCount() { + return this.mMenuItem.getChildCount(); + } + + @Override + public void attachChild(final IEntity pEntity) { + this.mMenuItem.attachChild(pEntity); + } + + @Override + public boolean attachChild(final IEntity pEntity, final int pIndex) { + return this.mMenuItem.attachChild(pEntity, pIndex); + } + + @Override + public IEntity getFirstChild() { + return this.mMenuItem.getFirstChild(); + } + + @Override + public IEntity getLastChild() { + return this.mMenuItem.getLastChild(); + } + + @Override + public IEntity getChild(final int pIndex) { + return this.mMenuItem.getChild(pIndex); + } + + @Override + public int getChildIndex(final IEntity pEntity) { + return this.mMenuItem.getChildIndex(pEntity); + } + + @Override + public boolean setChildIndex(final IEntity pEntity, final int pIndex) { + return this.mMenuItem.setChildIndex(pEntity, pIndex); + } + + @Override + public IEntity findChild(final IEntityMatcher pEntityMatcher) { + return this.mMenuItem.findChild(pEntityMatcher); + } + + public ArrayList query(final IEntityMatcher pEntityMatcher) { + return this.mMenuItem.query(pEntityMatcher); + } + + public > L query(final IEntityMatcher pEntityMatcher, final L pResult) { + return this.mMenuItem.query(pEntityMatcher, pResult); + } + + @Override + public ArrayList queryForSubclass(final IEntityMatcher pEntityMatcher) throws ClassCastException { + return this.mMenuItem.queryForSubclass(pEntityMatcher); + } + + public , S extends IEntity> L queryForSubclass(final IEntityMatcher pEntityMatcher, final L pResult) throws ClassCastException { + return this.mMenuItem.queryForSubclass(pEntityMatcher, pResult); + } + + @Override + public boolean swapChildren(final IEntity pEntityA, final IEntity pEntityB) { + return this.mMenuItem.swapChildren(pEntityA, pEntityB); + } + + @Override + public boolean swapChildren(final int pIndexA, final int pIndexB) { + return this.mMenuItem.swapChildren(pIndexA, pIndexB); + } + + @Override + public void sortChildren() { + this.mMenuItem.sortChildren(); + } + + @Override + public void sortChildren(final Comparator pEntityComparator) { + this.mMenuItem.sortChildren(pEntityComparator); + } + + @Override + public boolean detachSelf() { + return this.mMenuItem.detachSelf(); + } + + @Override + public boolean detachChild(final IEntity pEntity) { + return this.mMenuItem.detachChild(pEntity); + } + + @Override + public IEntity detachChild(final IEntityMatcher pEntityMatcher) { + return this.mMenuItem.detachChild(pEntityMatcher); + } + + @Override + public boolean detachChildren(final IEntityMatcher pEntityMatcher) { + return this.mMenuItem.detachChildren(pEntityMatcher); + } + + @Override + public void detachChildren() { + this.mMenuItem.detachChildren(); + } + + @Override + public void callOnChildren(final IEntityCallable pEntityCallable) { + this.callOnChildren(pEntityCallable); + } + + @Override + public void callOnChildren(final IEntityMatcher pEntityMatcher, final IEntityCallable pEntityCallable) { + this.mMenuItem.callOnChildren(pEntityMatcher, pEntityCallable); + } + + @Override + public Transformation getLocalToSceneTransformation() { + return this.mMenuItem.getLocalToSceneTransformation(); + } + + @Override + public Transformation getSceneToLocalTransformation() { + return this.mMenuItem.getSceneToLocalTransformation(); + } + + @Override + public boolean hasParent() { + return this.mMenuItem.hasParent(); + } + + @Override + public IEntity getParent() { + return this.mMenuItem.getParent(); + } + + @Override + public void setParent(final IEntity pEntity) { + this.mMenuItem.setParent(pEntity); + } + + @Override + public boolean isVisible() { + return this.mMenuItem.isVisible(); + } + + @Override + public void setVisible(final boolean pVisible) { + this.mMenuItem.setVisible(pVisible); + } + + @Override + public boolean isChildrenVisible() { + return this.mMenuItem.isChildrenVisible(); + } + + @Override + public void setChildrenVisible(final boolean pChildrenVisible) { + this.mMenuItem.setChildrenVisible(pChildrenVisible); + } + + @Override + public boolean isIgnoreUpdate() { + return this.mMenuItem.isIgnoreUpdate(); + } + + @Override + public void setIgnoreUpdate(final boolean pIgnoreUpdate) { + this.mMenuItem.setIgnoreUpdate(pIgnoreUpdate); + } + + @Override + public boolean isChildrenIgnoreUpdate() { + return this.mMenuItem.isChildrenIgnoreUpdate(); + } + + @Override + public void setChildrenIgnoreUpdate(final boolean pChildrenIgnoreUpdate) { + this.mMenuItem.setChildrenIgnoreUpdate(pChildrenIgnoreUpdate); + } + + @Override + public void setUserData(final Object pUserData) { + this.mMenuItem.setUserData(pUserData); + } + + @Override + public Object getUserData() { + return this.mMenuItem.getUserData(); + } + + @Override + public void onAttached() { + this.mMenuItem.onAttached(); + } + + @Override + public void onDetached() { + this.mMenuItem.onDetached(); + } + + @Override + public void registerUpdateHandler(final IUpdateHandler pUpdateHandler) { + this.mMenuItem.registerUpdateHandler(pUpdateHandler); + } + + @Override + public boolean unregisterUpdateHandler(final IUpdateHandler pUpdateHandler) { + return this.mMenuItem.unregisterUpdateHandler(pUpdateHandler); + } + + @Override + public void clearUpdateHandlers() { + this.mMenuItem.clearUpdateHandlers(); + } + + @Override + public boolean unregisterUpdateHandlers(final IUpdateHandlerMatcher pUpdateHandlerMatcher) { + return this.mMenuItem.unregisterUpdateHandlers(pUpdateHandlerMatcher); + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/entity/scene/menu/item/decorator/ColorMenuItemDecorator.java b/AndEngine/src/org/anddev/andengine/entity/scene/menu/item/decorator/ColorMenuItemDecorator.java index 691f8c77..9da06a23 100644 --- a/AndEngine/src/org/anddev/andengine/entity/scene/menu/item/decorator/ColorMenuItemDecorator.java +++ b/AndEngine/src/org/anddev/andengine/entity/scene/menu/item/decorator/ColorMenuItemDecorator.java @@ -10,71 +10,71 @@ * @since 14:25:35 - 07.07.2010 */ public class ColorMenuItemDecorator extends BaseMenuItemDecorator { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - private final float mSelectedRed; - private final float mSelectedGreen; - private final float mSelectedBlue; - private final float mUnselectedRed; - private final float mUnselectedGreen; - private final float mUnselectedBlue; - - // =========================================================== - // Constructors - // =========================================================== - - public ColorMenuItemDecorator(final IMenuItem pMenuItem, final float pSelectedRed, final float pSelectedGreen, final float pSelectedBlue, final float pUnselectedRed, final float pUnselectedGreen, final float pUnselectedBlue) { - super(pMenuItem); - - this.mSelectedRed = pSelectedRed; - this.mSelectedGreen = pSelectedGreen; - this.mSelectedBlue = pSelectedBlue; - - this.mUnselectedRed = pUnselectedRed; - this.mUnselectedGreen = pUnselectedGreen; - this.mUnselectedBlue = pUnselectedBlue; - - pMenuItem.setColor(this.mUnselectedRed, this.mUnselectedGreen, this.mUnselectedBlue); - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - public void onMenuItemSelected(final IMenuItem pMenuItem) { - pMenuItem.setColor(this.mSelectedRed, this.mSelectedGreen, this.mSelectedBlue); - } - - @Override - public void onMenuItemUnselected(final IMenuItem pMenuItem) { - pMenuItem.setColor(this.mUnselectedRed, this.mUnselectedGreen, this.mUnselectedBlue); - } - - @Override - public void onMenuItemReset(final IMenuItem pMenuItem) { - pMenuItem.setColor(this.mUnselectedRed, this.mUnselectedGreen, this.mUnselectedBlue); - } - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + private final float mSelectedRed; + private final float mSelectedGreen; + private final float mSelectedBlue; + private final float mUnselectedRed; + private final float mUnselectedGreen; + private final float mUnselectedBlue; + + // =========================================================== + // Constructors + // =========================================================== + + public ColorMenuItemDecorator(final IMenuItem pMenuItem, final float pSelectedRed, final float pSelectedGreen, final float pSelectedBlue, final float pUnselectedRed, final float pUnselectedGreen, final float pUnselectedBlue) { + super(pMenuItem); + + this.mSelectedRed = pSelectedRed; + this.mSelectedGreen = pSelectedGreen; + this.mSelectedBlue = pSelectedBlue; + + this.mUnselectedRed = pUnselectedRed; + this.mUnselectedGreen = pUnselectedGreen; + this.mUnselectedBlue = pUnselectedBlue; + + pMenuItem.setColor(this.mUnselectedRed, this.mUnselectedGreen, this.mUnselectedBlue); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + public void onMenuItemSelected(final IMenuItem pMenuItem) { + pMenuItem.setColor(this.mSelectedRed, this.mSelectedGreen, this.mSelectedBlue); + } + + @Override + public void onMenuItemUnselected(final IMenuItem pMenuItem) { + pMenuItem.setColor(this.mUnselectedRed, this.mUnselectedGreen, this.mUnselectedBlue); + } + + @Override + public void onMenuItemReset(final IMenuItem pMenuItem) { + pMenuItem.setColor(this.mUnselectedRed, this.mUnselectedGreen, this.mUnselectedBlue); + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/entity/scene/menu/item/decorator/ScaleMenuItemDecorator.java b/AndEngine/src/org/anddev/andengine/entity/scene/menu/item/decorator/ScaleMenuItemDecorator.java index 40312d85..05075cc7 100644 --- a/AndEngine/src/org/anddev/andengine/entity/scene/menu/item/decorator/ScaleMenuItemDecorator.java +++ b/AndEngine/src/org/anddev/andengine/entity/scene/menu/item/decorator/ScaleMenuItemDecorator.java @@ -10,62 +10,62 @@ * @since 15:04:29 - 18.11.2010 */ public class ScaleMenuItemDecorator extends BaseMenuItemDecorator { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - private final float mSelectedScale; - private final float mUnselectedScale; + private final float mSelectedScale; + private final float mUnselectedScale; - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - public ScaleMenuItemDecorator(final IMenuItem pMenuItem, final float pSelectedScale, final float pUnselectedScale) { - super(pMenuItem); + public ScaleMenuItemDecorator(final IMenuItem pMenuItem, final float pSelectedScale, final float pUnselectedScale) { + super(pMenuItem); - this.mSelectedScale = pSelectedScale; - this.mUnselectedScale = pUnselectedScale; + this.mSelectedScale = pSelectedScale; + this.mUnselectedScale = pUnselectedScale; - pMenuItem.setScale(pUnselectedScale); - } + pMenuItem.setScale(pUnselectedScale); + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - @Override - public void onMenuItemSelected(final IMenuItem pMenuItem) { - this.setScale(this.mSelectedScale); - } + @Override + public void onMenuItemSelected(final IMenuItem pMenuItem) { + this.setScale(this.mSelectedScale); + } - @Override - public void onMenuItemUnselected(final IMenuItem pMenuItem) { - this.setScale(this.mUnselectedScale); - } + @Override + public void onMenuItemUnselected(final IMenuItem pMenuItem) { + this.setScale(this.mUnselectedScale); + } - @Override - public void onMenuItemReset(final IMenuItem pMenuItem) { - this.setScale(this.mUnselectedScale); - } + @Override + public void onMenuItemReset(final IMenuItem pMenuItem) { + this.setScale(this.mUnselectedScale); + } - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/entity/scene/popup/PopupScene.java b/AndEngine/src/org/anddev/andengine/entity/scene/popup/PopupScene.java index d3a25112..89b8dfb5 100644 --- a/AndEngine/src/org/anddev/andengine/entity/scene/popup/PopupScene.java +++ b/AndEngine/src/org/anddev/andengine/entity/scene/popup/PopupScene.java @@ -14,53 +14,53 @@ * @since 16:36:51 - 03.08.2010 */ public class PopupScene extends CameraScene { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - public PopupScene(final Camera pCamera, final Scene pParentScene, final float pDurationSeconds) { - this(pCamera, pParentScene, pDurationSeconds, null); - } + public PopupScene(final Camera pCamera, final Scene pParentScene, final float pDurationSeconds) { + this(pCamera, pParentScene, pDurationSeconds, null); + } - public PopupScene(final Camera pCamera, final Scene pParentScene, final float pDurationSeconds, final Runnable pRunnable) { - super(pCamera); - this.setBackgroundEnabled(false); + public PopupScene(final Camera pCamera, final Scene pParentScene, final float pDurationSeconds, final Runnable pRunnable) { + super(pCamera); + this.setBackgroundEnabled(false); - pParentScene.setChildScene(this, false, true, true); + pParentScene.setChildScene(this, false, true, true); - this.registerUpdateHandler(new TimerHandler(pDurationSeconds, new ITimerCallback() { - @Override - public void onTimePassed(final TimerHandler pTimerHandler) { - PopupScene.this.unregisterUpdateHandler(pTimerHandler); - pParentScene.clearChildScene(); - if(pRunnable != null) { - pRunnable.run(); - } - } - })); - } + this.registerUpdateHandler(new TimerHandler(pDurationSeconds, new ITimerCallback() { + @Override + public void onTimePassed(final TimerHandler pTimerHandler) { + PopupScene.this.unregisterUpdateHandler(pTimerHandler); + pParentScene.clearChildScene(); + if(pRunnable != null) { + pRunnable.run(); + } + } + })); + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/entity/scene/popup/TextPopupScene.java b/AndEngine/src/org/anddev/andengine/entity/scene/popup/TextPopupScene.java index 32c34294..71ab39a7 100644 --- a/AndEngine/src/org/anddev/andengine/entity/scene/popup/TextPopupScene.java +++ b/AndEngine/src/org/anddev/andengine/entity/scene/popup/TextPopupScene.java @@ -15,62 +15,62 @@ * @since 17:19:30 - 03.08.2010 */ public class TextPopupScene extends PopupScene { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - private final Text mText; + private final Text mText; - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - public TextPopupScene(final Camera pCamera, final Scene pParentScene, final Font pFont, final String pText, final float pDurationSeconds) { - this(pCamera, pParentScene, pFont, pText, pDurationSeconds, null, null); - } + public TextPopupScene(final Camera pCamera, final Scene pParentScene, final Font pFont, final String pText, final float pDurationSeconds) { + this(pCamera, pParentScene, pFont, pText, pDurationSeconds, null, null); + } - public TextPopupScene(final Camera pCamera, final Scene pParentScene, final Font pFont, final String pText, final float pDurationSeconds, final IEntityModifier pShapeModifier) { - this(pCamera, pParentScene, pFont, pText, pDurationSeconds, pShapeModifier, null); - } + public TextPopupScene(final Camera pCamera, final Scene pParentScene, final Font pFont, final String pText, final float pDurationSeconds, final IEntityModifier pShapeModifier) { + this(pCamera, pParentScene, pFont, pText, pDurationSeconds, pShapeModifier, null); + } - public TextPopupScene(final Camera pCamera, final Scene pParentScene, final Font pFont, final String pText, final float pDurationSeconds, final Runnable pRunnable) { - this(pCamera, pParentScene, pFont, pText, pDurationSeconds, null, pRunnable); - } + public TextPopupScene(final Camera pCamera, final Scene pParentScene, final Font pFont, final String pText, final float pDurationSeconds, final Runnable pRunnable) { + this(pCamera, pParentScene, pFont, pText, pDurationSeconds, null, pRunnable); + } - public TextPopupScene(final Camera pCamera, final Scene pParentScene, final Font pFont, final String pText, final float pDurationSeconds, final IEntityModifier pShapeModifier, final Runnable pRunnable) { - super(pCamera, pParentScene, pDurationSeconds, pRunnable); + public TextPopupScene(final Camera pCamera, final Scene pParentScene, final Font pFont, final String pText, final float pDurationSeconds, final IEntityModifier pShapeModifier, final Runnable pRunnable) { + super(pCamera, pParentScene, pDurationSeconds, pRunnable); - this.mText = new Text(0, 0, pFont, pText, HorizontalAlign.CENTER); - this.centerShapeInCamera(this.mText); + this.mText = new Text(0, 0, pFont, pText, HorizontalAlign.CENTER); + this.centerShapeInCamera(this.mText); - if(pShapeModifier != null) { - this.mText.registerEntityModifier(pShapeModifier); - } + if(pShapeModifier != null) { + this.mText.registerEntityModifier(pShapeModifier); + } - this.attachChild(this.mText); - } + this.attachChild(this.mText); + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - public Text getText() { - return this.mText; - } + public Text getText() { + return this.mText; + } - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/entity/shape/IShape.java b/AndEngine/src/org/anddev/andengine/entity/shape/IShape.java index 9dc4518e..cce06ecb 100644 --- a/AndEngine/src/org/anddev/andengine/entity/shape/IShape.java +++ b/AndEngine/src/org/anddev/andengine/entity/shape/IShape.java @@ -11,28 +11,28 @@ * @since 13:32:52 - 07.07.2010 */ public interface IShape extends IEntity, ITouchArea { - // =========================================================== - // Final Fields - // =========================================================== + // =========================================================== + // Final Fields + // =========================================================== - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - public boolean isCullingEnabled(); - public void setCullingEnabled(final boolean pCullingEnabled); + public boolean isCullingEnabled(); + public void setCullingEnabled(final boolean pCullingEnabled); - public float getWidth(); - public float getHeight(); + public float getWidth(); + public float getHeight(); - public float getBaseWidth(); - public float getBaseHeight(); + public float getBaseWidth(); + public float getBaseHeight(); - public float getWidthScaled(); - public float getHeightScaled(); + public float getWidthScaled(); + public float getHeightScaled(); -// public boolean isVisible(final Camera pCamera); // TODO. Could be use for automated culling. - public boolean collidesWith(final IShape pOtherShape); +// public boolean isVisible(final Camera pCamera); // TODO. Could be use for automated culling. + public boolean collidesWith(final IShape pOtherShape); - public void setBlendFunction(final int pSourceBlendFunction, final int pDestinationBlendFunction); -} \ No newline at end of file + public void setBlendFunction(final int pSourceBlendFunction, final int pDestinationBlendFunction); +} diff --git a/AndEngine/src/org/anddev/andengine/entity/shape/RectangularShape.java b/AndEngine/src/org/anddev/andengine/entity/shape/RectangularShape.java index 8f1ad96c..733f6382 100644 --- a/AndEngine/src/org/anddev/andengine/entity/shape/RectangularShape.java +++ b/AndEngine/src/org/anddev/andengine/entity/shape/RectangularShape.java @@ -15,159 +15,159 @@ * @since 11:37:50 - 04.04.2010 */ public abstract class RectangularShape extends Shape { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - protected float mBaseWidth; - protected float mBaseHeight; - - protected float mWidth; - protected float mHeight; - - protected final VertexBuffer mVertexBuffer; - - // =========================================================== - // Constructors - // =========================================================== - - public RectangularShape(final float pX, final float pY, final float pWidth, final float pHeight, final VertexBuffer pVertexBuffer) { - super(pX, pY); - - this.mBaseWidth = pWidth; - this.mBaseHeight = pHeight; - - this.mWidth = pWidth; - this.mHeight = pHeight; - - this.mVertexBuffer = pVertexBuffer; - - this.mRotationCenterX = pWidth * 0.5f; - this.mRotationCenterY = pHeight * 0.5f; - - this.mScaleCenterX = this.mRotationCenterX; - this.mScaleCenterY = this.mRotationCenterY; - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - @Override - public VertexBuffer getVertexBuffer() { - return this.mVertexBuffer; - } - - @Override - public float getWidth() { - return this.mWidth; - } - - @Override - public float getHeight() { - return this.mHeight; - } - - @Override - public float getBaseWidth() { - return this.mBaseWidth; - } - - @Override - public float getBaseHeight() { - return this.mBaseHeight; - } - - public void setWidth(final float pWidth) { - this.mWidth = pWidth; - this.updateVertexBuffer(); - } - - public void setHeight(final float pHeight) { - this.mHeight = pHeight; - this.updateVertexBuffer(); - } - - public void setSize(final float pWidth, final float pHeight) { - this.mWidth = pWidth; - this.mHeight = pHeight; - this.updateVertexBuffer(); - } - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - public void setBaseSize() { - if(this.mWidth != this.mBaseWidth || this.mHeight != this.mBaseHeight) { - this.mWidth = this.mBaseWidth; - this.mHeight = this.mBaseHeight; - this.updateVertexBuffer(); - } - } - - @Override - protected boolean isCulled(final Camera pCamera) { // TODO Advanced culling! - final float x = this.mX; - final float y = this.mY; - return x > pCamera.getMaxX() - || y > pCamera.getMaxY() - || x + this.getWidth() < pCamera.getMinX() - || y + this.getHeight() < pCamera.getMinY(); - } - - @Override - protected void drawVertices(final GL10 pGL, final Camera pCamera) { - pGL.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, 4); - } - - @Override - public void reset() { - super.reset(); - this.setBaseSize(); - - final float baseWidth = this.getBaseWidth(); - final float baseHeight = this.getBaseHeight(); - - this.mRotationCenterX = baseWidth * 0.5f; - this.mRotationCenterY = baseHeight * 0.5f; - - this.mScaleCenterX = this.mRotationCenterX; - this.mScaleCenterY = this.mRotationCenterY; - } - - @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); - } - - @Override - public boolean collidesWith(final IShape pOtherShape) { - if(pOtherShape instanceof RectangularShape) { - final RectangularShape pOtherRectangularShape = (RectangularShape) pOtherShape; - return RectangularShapeCollisionChecker.checkCollision(this, pOtherRectangularShape); - } else if(pOtherShape instanceof Line) { - final Line line = (Line) pOtherShape; - return RectangularShapeCollisionChecker.checkCollision(this, line); - } else { - return false; - } - } - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + protected float mBaseWidth; + protected float mBaseHeight; + + protected float mWidth; + protected float mHeight; + + protected final VertexBuffer mVertexBuffer; + + // =========================================================== + // Constructors + // =========================================================== + + public RectangularShape(final float pX, final float pY, final float pWidth, final float pHeight, final VertexBuffer pVertexBuffer) { + super(pX, pY); + + this.mBaseWidth = pWidth; + this.mBaseHeight = pHeight; + + this.mWidth = pWidth; + this.mHeight = pHeight; + + this.mVertexBuffer = pVertexBuffer; + + this.mRotationCenterX = pWidth * 0.5f; + this.mRotationCenterY = pHeight * 0.5f; + + this.mScaleCenterX = this.mRotationCenterX; + this.mScaleCenterY = this.mRotationCenterY; + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + @Override + public VertexBuffer getVertexBuffer() { + return this.mVertexBuffer; + } + + @Override + public float getWidth() { + return this.mWidth; + } + + @Override + public float getHeight() { + return this.mHeight; + } + + @Override + public float getBaseWidth() { + return this.mBaseWidth; + } + + @Override + public float getBaseHeight() { + return this.mBaseHeight; + } + + public void setWidth(final float pWidth) { + this.mWidth = pWidth; + this.updateVertexBuffer(); + } + + public void setHeight(final float pHeight) { + this.mHeight = pHeight; + this.updateVertexBuffer(); + } + + public void setSize(final float pWidth, final float pHeight) { + this.mWidth = pWidth; + this.mHeight = pHeight; + this.updateVertexBuffer(); + } + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + public void setBaseSize() { + if(this.mWidth != this.mBaseWidth || this.mHeight != this.mBaseHeight) { + this.mWidth = this.mBaseWidth; + this.mHeight = this.mBaseHeight; + this.updateVertexBuffer(); + } + } + + @Override + protected boolean isCulled(final Camera pCamera) { // TODO Advanced culling! + final float x = this.mX; + final float y = this.mY; + return x > pCamera.getMaxX() + || y > pCamera.getMaxY() + || x + this.getWidth() < pCamera.getMinX() + || y + this.getHeight() < pCamera.getMinY(); + } + + @Override + protected void drawVertices(final GL10 pGL, final Camera pCamera) { + pGL.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, 4); + } + + @Override + public void reset() { + super.reset(); + this.setBaseSize(); + + final float baseWidth = this.getBaseWidth(); + final float baseHeight = this.getBaseHeight(); + + this.mRotationCenterX = baseWidth * 0.5f; + this.mRotationCenterY = baseHeight * 0.5f; + + this.mScaleCenterX = this.mRotationCenterX; + this.mScaleCenterY = this.mRotationCenterY; + } + + @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); + } + + @Override + public boolean collidesWith(final IShape pOtherShape) { + if(pOtherShape instanceof RectangularShape) { + final RectangularShape pOtherRectangularShape = (RectangularShape) pOtherShape; + return RectangularShapeCollisionChecker.checkCollision(this, pOtherRectangularShape); + } else if(pOtherShape instanceof Line) { + final Line line = (Line) pOtherShape; + return RectangularShapeCollisionChecker.checkCollision(this, line); + } else { + return false; + } + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/entity/shape/Shape.java b/AndEngine/src/org/anddev/andengine/entity/shape/Shape.java index 29457cbb..477f8875 100644 --- a/AndEngine/src/org/anddev/andengine/entity/shape/Shape.java +++ b/AndEngine/src/org/anddev/andengine/entity/shape/Shape.java @@ -18,154 +18,154 @@ * @since 11:51:27 - 13.03.2010 */ public abstract class Shape extends Entity implements IShape { - // =========================================================== - // Constants - // =========================================================== - - public static final int BLENDFUNCTION_SOURCE_DEFAULT = GL10.GL_SRC_ALPHA; - public static final int BLENDFUNCTION_DESTINATION_DEFAULT = GL10.GL_ONE_MINUS_SRC_ALPHA; - - public static final int BLENDFUNCTION_SOURCE_PREMULTIPLYALPHA_DEFAULT = GL10.GL_ONE; - public static final int BLENDFUNCTION_DESTINATION_PREMULTIPLYALPHA_DEFAULT = GL10.GL_ONE_MINUS_SRC_ALPHA; - - // =========================================================== - // Fields - // =========================================================== - - protected int mSourceBlendFunction = BLENDFUNCTION_SOURCE_DEFAULT; - protected int mDestinationBlendFunction = BLENDFUNCTION_DESTINATION_DEFAULT; - - private boolean mCullingEnabled = false; - - // =========================================================== - // Constructors - // =========================================================== - - public Shape(final float pX, final float pY) { - super(pX, pY); - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - @Override - public void setBlendFunction(final int pSourceBlendFunction, final int pDestinationBlendFunction) { - this.mSourceBlendFunction = pSourceBlendFunction; - this.mDestinationBlendFunction = pDestinationBlendFunction; - } - - @Override - public boolean isCullingEnabled() { - return this.mCullingEnabled; - } - - @Override - public void setCullingEnabled(final boolean pCullingEnabled) { - this.mCullingEnabled = pCullingEnabled; - } - - @Override - public float getWidthScaled() { - return this.getWidth() * this.mScaleX; - } - - @Override - public float getHeightScaled() { - return this.getHeight() * this.mScaleY; - } - - public boolean isVertexBufferManaged() { - return this.getVertexBuffer().isManaged(); - } - - /** - * @param pVertexBufferManaged when passing true this {@link Shape} will make its {@link VertexBuffer} unload itself from the active {@link BufferObjectManager}, when this {@link Shape} is finalized/garbage-collected. WARNING: When passing false one needs to take care of that by oneself! - */ - public void setVertexBufferManaged(final boolean pVertexBufferManaged) { - this.getVertexBuffer().setManaged(pVertexBufferManaged); - } - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - protected abstract void onUpdateVertexBuffer(); - protected abstract VertexBuffer getVertexBuffer(); - - protected abstract void drawVertices(final GL10 pGL, final Camera pCamera); - - @Override - protected void doDraw(final GL10 pGL, final Camera pCamera) { - this.onInitDraw(pGL); - this.onApplyVertices(pGL); - this.drawVertices(pGL, pCamera); - } - - @Override - public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final float pTouchAreaLocalX, final float pTouchAreaLocalY) { - return false; - } - - /** - * Will only be performed if {@link Shape#isCullingEnabled()} is true. - * @param pCamera - * @return true when this object is visible by the {@link Camera}, false otherwise. - */ - protected abstract boolean isCulled(final Camera pCamera); - - @Override - protected void onManagedDraw(final GL10 pGL, final Camera pCamera) { - if(!this.mCullingEnabled || !this.isCulled(pCamera)) { - super.onManagedDraw(pGL, pCamera); - } - } - - @Override - public void reset() { - super.reset(); - - this.mSourceBlendFunction = BLENDFUNCTION_SOURCE_DEFAULT; - this.mDestinationBlendFunction = BLENDFUNCTION_DESTINATION_DEFAULT; - } - - @Override - protected void finalize() throws Throwable { - super.finalize(); - - final VertexBuffer vertexBuffer = this.getVertexBuffer(); - if (vertexBuffer != null && vertexBuffer.isManaged()) { - vertexBuffer.unloadFromActiveBufferObjectManager(); - } - } - - // =========================================================== - // Methods - // =========================================================== - - protected void onInitDraw(final GL10 pGL) { - GLHelper.setColor(pGL, this.mRed, this.mGreen, this.mBlue, this.mAlpha); - - GLHelper.enableVertexArray(pGL); - GLHelper.blendFunction(pGL, this.mSourceBlendFunction, this.mDestinationBlendFunction); - } - - protected void onApplyVertices(final GL10 pGL) { - if(GLHelper.EXTENSIONS_VERTEXBUFFEROBJECTS) { - final GL11 gl11 = (GL11)pGL; - - this.getVertexBuffer().selectOnHardware(gl11); - GLHelper.vertexZeroPointer(gl11); - } else { - GLHelper.vertexPointer(pGL, this.getVertexBuffer().getFloatBuffer()); - } - } - - protected void updateVertexBuffer() { - this.onUpdateVertexBuffer(); - } - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + public static final int BLENDFUNCTION_SOURCE_DEFAULT = GL10.GL_SRC_ALPHA; + public static final int BLENDFUNCTION_DESTINATION_DEFAULT = GL10.GL_ONE_MINUS_SRC_ALPHA; + + public static final int BLENDFUNCTION_SOURCE_PREMULTIPLYALPHA_DEFAULT = GL10.GL_ONE; + public static final int BLENDFUNCTION_DESTINATION_PREMULTIPLYALPHA_DEFAULT = GL10.GL_ONE_MINUS_SRC_ALPHA; + + // =========================================================== + // Fields + // =========================================================== + + protected int mSourceBlendFunction = BLENDFUNCTION_SOURCE_DEFAULT; + protected int mDestinationBlendFunction = BLENDFUNCTION_DESTINATION_DEFAULT; + + private boolean mCullingEnabled = false; + + // =========================================================== + // Constructors + // =========================================================== + + public Shape(final float pX, final float pY) { + super(pX, pY); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + @Override + public void setBlendFunction(final int pSourceBlendFunction, final int pDestinationBlendFunction) { + this.mSourceBlendFunction = pSourceBlendFunction; + this.mDestinationBlendFunction = pDestinationBlendFunction; + } + + @Override + public boolean isCullingEnabled() { + return this.mCullingEnabled; + } + + @Override + public void setCullingEnabled(final boolean pCullingEnabled) { + this.mCullingEnabled = pCullingEnabled; + } + + @Override + public float getWidthScaled() { + return this.getWidth() * this.mScaleX; + } + + @Override + public float getHeightScaled() { + return this.getHeight() * this.mScaleY; + } + + public boolean isVertexBufferManaged() { + return this.getVertexBuffer().isManaged(); + } + + /** + * @param pVertexBufferManaged when passing true this {@link Shape} will make its {@link VertexBuffer} unload itself from the active {@link BufferObjectManager}, when this {@link Shape} is finalized/garbage-collected. WARNING: When passing false one needs to take care of that by oneself! + */ + public void setVertexBufferManaged(final boolean pVertexBufferManaged) { + this.getVertexBuffer().setManaged(pVertexBufferManaged); + } + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + protected abstract void onUpdateVertexBuffer(); + protected abstract VertexBuffer getVertexBuffer(); + + protected abstract void drawVertices(final GL10 pGL, final Camera pCamera); + + @Override + protected void doDraw(final GL10 pGL, final Camera pCamera) { + this.onInitDraw(pGL); + this.onApplyVertices(pGL); + this.drawVertices(pGL, pCamera); + } + + @Override + public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final float pTouchAreaLocalX, final float pTouchAreaLocalY) { + return false; + } + + /** + * Will only be performed if {@link Shape#isCullingEnabled()} is true. + * @param pCamera + * @return true when this object is visible by the {@link Camera}, false otherwise. + */ + protected abstract boolean isCulled(final Camera pCamera); + + @Override + protected void onManagedDraw(final GL10 pGL, final Camera pCamera) { + if(!this.mCullingEnabled || !this.isCulled(pCamera)) { + super.onManagedDraw(pGL, pCamera); + } + } + + @Override + public void reset() { + super.reset(); + + this.mSourceBlendFunction = BLENDFUNCTION_SOURCE_DEFAULT; + this.mDestinationBlendFunction = BLENDFUNCTION_DESTINATION_DEFAULT; + } + + @Override + protected void finalize() throws Throwable { + super.finalize(); + + final VertexBuffer vertexBuffer = this.getVertexBuffer(); + if (vertexBuffer != null && vertexBuffer.isManaged()) { + vertexBuffer.unloadFromActiveBufferObjectManager(); + } + } + + // =========================================================== + // Methods + // =========================================================== + + protected void onInitDraw(final GL10 pGL) { + GLHelper.setColor(pGL, this.mRed, this.mGreen, this.mBlue, this.mAlpha); + + GLHelper.enableVertexArray(pGL); + GLHelper.blendFunction(pGL, this.mSourceBlendFunction, this.mDestinationBlendFunction); + } + + protected void onApplyVertices(final GL10 pGL) { + if(GLHelper.EXTENSIONS_VERTEXBUFFEROBJECTS) { + final GL11 gl11 = (GL11)pGL; + + this.getVertexBuffer().selectOnHardware(gl11); + GLHelper.vertexZeroPointer(gl11); + } else { + GLHelper.vertexPointer(pGL, this.getVertexBuffer().getFloatBuffer()); + } + } + + protected void updateVertexBuffer() { + this.onUpdateVertexBuffer(); + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/entity/sprite/AnimatedSprite.java b/AndEngine/src/org/anddev/andengine/entity/sprite/AnimatedSprite.java index 71854359..e27c2132 100644 --- a/AndEngine/src/org/anddev/andengine/entity/sprite/AnimatedSprite.java +++ b/AndEngine/src/org/anddev/andengine/entity/sprite/AnimatedSprite.java @@ -8,249 +8,249 @@ import org.anddev.andengine.util.constants.TimeConstants; public class AnimatedSprite extends TiledSprite implements TimeConstants { - // =========================================================== - // Constants - // =========================================================== - - private static final int LOOP_CONTINUOUS = -1; - - // =========================================================== - // Fields - // =========================================================== - - private boolean mAnimationRunning; - - private long mAnimationProgress; - private long mAnimationDuration; - private long[] mFrameEndsInNanoseconds; - - private int mFirstTileIndex; - private int mInitialLoopCount; - private int mLoopCount; - private IAnimationListener mAnimationListener; - - private int mFrameCount; - private int[] mFrames; - - // =========================================================== - // Constructors - // =========================================================== - - public AnimatedSprite(final float pX, final float pY, final TiledTextureRegion pTiledTextureRegion) { - super(pX, pY, pTiledTextureRegion); - } - - public AnimatedSprite(final float pX, final float pY, final float pTileWidth, final float pTileHeight, final TiledTextureRegion pTiledTextureRegion) { - super(pX, pY, pTileWidth, pTileHeight, pTiledTextureRegion); - } - - public AnimatedSprite(final float pX, final float pY, final TiledTextureRegion pTiledTextureRegion, final RectangleVertexBuffer pRectangleVertexBuffer) { - super(pX, pY, pTiledTextureRegion, pRectangleVertexBuffer); - } - - public AnimatedSprite(final float pX, final float pY, final float pTileWidth, final float pTileHeight, final TiledTextureRegion pTiledTextureRegion, final RectangleVertexBuffer pRectangleVertexBuffer) { - super(pX, pY, pTileWidth, pTileHeight, pTiledTextureRegion, pRectangleVertexBuffer); - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - public boolean isAnimationRunning() { - return this.mAnimationRunning; - } - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - protected void onManagedUpdate(final float pSecondsElapsed) { - super.onManagedUpdate(pSecondsElapsed); - if(this.mAnimationRunning) { - final long nanoSecondsElapsed = (long) (pSecondsElapsed * TimeConstants.NANOSECONDSPERSECOND); - this.mAnimationProgress += nanoSecondsElapsed; - - if(this.mAnimationProgress > this.mAnimationDuration) { - this.mAnimationProgress %= this.mAnimationDuration; - if(this.mInitialLoopCount != AnimatedSprite.LOOP_CONTINUOUS) { - this.mLoopCount--; - } - } - - if(this.mInitialLoopCount == AnimatedSprite.LOOP_CONTINUOUS || this.mLoopCount >= 0) { - final int currentFrameIndex = this.calculateCurrentFrameIndex(); - - if(this.mFrames == null) { - this.setCurrentTileIndex(this.mFirstTileIndex + currentFrameIndex); - } else { - this.setCurrentTileIndex(this.mFrames[currentFrameIndex]); - } - } else { - this.mAnimationRunning = false; - if(this.mAnimationListener != null) { - this.mAnimationListener.onAnimationEnd(this); - } - } - } - } - - // =========================================================== - // Methods - // =========================================================== - - public void stopAnimation() { - this.mAnimationRunning = false; - } - - public void stopAnimation(final int pTileIndex) { - this.mAnimationRunning = false; - this.setCurrentTileIndex(pTileIndex); - } - - private int calculateCurrentFrameIndex() { - final long animationProgress = this.mAnimationProgress; - final long[] frameEnds = this.mFrameEndsInNanoseconds; - final int frameCount = this.mFrameCount; - for(int i = 0; i < frameCount; i++) { - if(frameEnds[i] > animationProgress) { - return i; - } - } - - return frameCount - 1; - } - - public AnimatedSprite animate(final long pFrameDurationEach) { - return this.animate(pFrameDurationEach, true); - } - - public AnimatedSprite animate(final long pFrameDurationEach, final boolean pLoop) { - return this.animate(pFrameDurationEach, (pLoop) ? AnimatedSprite.LOOP_CONTINUOUS : 0, null); - } - - public AnimatedSprite animate(final long pFrameDurationEach, final int pLoopCount) { - return this.animate(pFrameDurationEach, pLoopCount, null); - } - - public AnimatedSprite animate(final long pFrameDurationEach, final boolean pLoop, final IAnimationListener pAnimationListener) { - return this.animate(pFrameDurationEach, (pLoop) ? AnimatedSprite.LOOP_CONTINUOUS : 0, pAnimationListener); - } - - public AnimatedSprite animate(final long pFrameDurationEach, final int pLoopCount, final IAnimationListener pAnimationListener) { - final long[] frameDurations = new long[this.getTextureRegion().getTileCount()]; - Arrays.fill(frameDurations, pFrameDurationEach); - return this.animate(frameDurations, pLoopCount, pAnimationListener); - } - - public AnimatedSprite animate(final long[] pFrameDurations) { - return this.animate(pFrameDurations, true); - } - - public AnimatedSprite animate(final long[] pFrameDurations, final boolean pLoop) { - return this.animate(pFrameDurations, (pLoop) ? AnimatedSprite.LOOP_CONTINUOUS : 0, null); - } - - public AnimatedSprite animate(final long[] pFrameDurations, final int pLoopCount) { - return this.animate(pFrameDurations, pLoopCount, null); - } - - public AnimatedSprite animate(final long[] pFrameDurations, final boolean pLoop, final IAnimationListener pAnimationListener) { - return this.animate(pFrameDurations, (pLoop) ? AnimatedSprite.LOOP_CONTINUOUS : 0, pAnimationListener); - } - - public AnimatedSprite animate(final long[] pFrameDurations, final int pLoopCount, final IAnimationListener pAnimationListener) { - return this.animate(pFrameDurations, 0, this.getTextureRegion().getTileCount() - 1, pLoopCount, pAnimationListener); - } - - public AnimatedSprite animate(final long[] pFrameDurations, final int pFirstTileIndex, final int pLastTileIndex, final boolean pLoop) { - return this.animate(pFrameDurations, pFirstTileIndex, pLastTileIndex, (pLoop) ? AnimatedSprite.LOOP_CONTINUOUS : 0, null); - } - - public AnimatedSprite animate(final long[] pFrameDurations, final int pFirstTileIndex, final int pLastTileIndex, final int pLoopCount) { - return this.animate(pFrameDurations, pFirstTileIndex, pLastTileIndex, pLoopCount, null); - } - - public AnimatedSprite animate(final long[] pFrameDurations, final int[] pFrames, final int pLoopCount) { - return this.animate(pFrameDurations, pFrames, pLoopCount, null); - } - - /** - * Animate specifics frames - * - * @param pFrameDurations must have the same length as pFrames. - * @param pFrames indices of the frames to animate. - * @param pLoopCount - * @param pAnimationListener - */ - public AnimatedSprite animate(final long[] pFrameDurations, final int[] pFrames, final int pLoopCount, final IAnimationListener pAnimationListener) { - final int frameCount = pFrames.length; - if(pFrameDurations.length != frameCount) { - throw new IllegalArgumentException("pFrameDurations must have the same length as pFrames."); - } - - return this.init(pFrameDurations, frameCount, pFrames, 0, pLoopCount, pAnimationListener); - } - - /** - * @param pFrameDurations - * must have the same length as pFirstTileIndex to - * pLastTileIndex. - * @param pFirstTileIndex - * @param pLastTileIndex - * @param pLoopCount - * @param pAnimationListener - */ - public AnimatedSprite animate(final long[] pFrameDurations, final int pFirstTileIndex, final int pLastTileIndex, final int pLoopCount, final IAnimationListener pAnimationListener) { - if(pLastTileIndex - pFirstTileIndex < 1) { - throw new IllegalArgumentException("An animation needs at least two tiles to animate between."); - } - - final int frameCount = (pLastTileIndex - pFirstTileIndex) + 1; - if(pFrameDurations.length != frameCount) { - throw new IllegalArgumentException("pFrameDurations must have the same length as pFirstTileIndex to pLastTileIndex."); - } - - return this.init(pFrameDurations, frameCount, null, pFirstTileIndex, pLoopCount, pAnimationListener); - } - - private AnimatedSprite init(final long[] pFrameDurations, final int frameCount, final int[] pFrames, final int pFirstTileIndex, final int pLoopCount, final IAnimationListener pAnimationListener) { - this.mFrameCount = frameCount; - this.mAnimationListener = pAnimationListener; - this.mInitialLoopCount = pLoopCount; - this.mLoopCount = pLoopCount; - this.mFrames = pFrames; - this.mFirstTileIndex = pFirstTileIndex; - - if(this.mFrameEndsInNanoseconds == null || this.mFrameCount > this.mFrameEndsInNanoseconds.length) { - this.mFrameEndsInNanoseconds = new long[this.mFrameCount]; - } - - final long[] frameEndsInNanoseconds = this.mFrameEndsInNanoseconds; - MathUtils.arraySumInto(pFrameDurations, frameEndsInNanoseconds, TimeConstants.NANOSECONDSPERMILLISECOND); - - final long lastFrameEnd = frameEndsInNanoseconds[this.mFrameCount - 1]; - this.mAnimationDuration = lastFrameEnd; - - this.mAnimationProgress = 0; - this.mAnimationRunning = true; - - return this; - } - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== - - public static interface IAnimationListener { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - public void onAnimationEnd(final AnimatedSprite pAnimatedSprite); - } + // =========================================================== + // Constants + // =========================================================== + + private static final int LOOP_CONTINUOUS = -1; + + // =========================================================== + // Fields + // =========================================================== + + private boolean mAnimationRunning; + + private long mAnimationProgress; + private long mAnimationDuration; + private long[] mFrameEndsInNanoseconds; + + private int mFirstTileIndex; + private int mInitialLoopCount; + private int mLoopCount; + private IAnimationListener mAnimationListener; + + private int mFrameCount; + private int[] mFrames; + + // =========================================================== + // Constructors + // =========================================================== + + public AnimatedSprite(final float pX, final float pY, final TiledTextureRegion pTiledTextureRegion) { + super(pX, pY, pTiledTextureRegion); + } + + public AnimatedSprite(final float pX, final float pY, final float pTileWidth, final float pTileHeight, final TiledTextureRegion pTiledTextureRegion) { + super(pX, pY, pTileWidth, pTileHeight, pTiledTextureRegion); + } + + public AnimatedSprite(final float pX, final float pY, final TiledTextureRegion pTiledTextureRegion, final RectangleVertexBuffer pRectangleVertexBuffer) { + super(pX, pY, pTiledTextureRegion, pRectangleVertexBuffer); + } + + public AnimatedSprite(final float pX, final float pY, final float pTileWidth, final float pTileHeight, final TiledTextureRegion pTiledTextureRegion, final RectangleVertexBuffer pRectangleVertexBuffer) { + super(pX, pY, pTileWidth, pTileHeight, pTiledTextureRegion, pRectangleVertexBuffer); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + public boolean isAnimationRunning() { + return this.mAnimationRunning; + } + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + protected void onManagedUpdate(final float pSecondsElapsed) { + super.onManagedUpdate(pSecondsElapsed); + if(this.mAnimationRunning) { + final long nanoSecondsElapsed = (long) (pSecondsElapsed * TimeConstants.NANOSECONDSPERSECOND); + this.mAnimationProgress += nanoSecondsElapsed; + + if(this.mAnimationProgress > this.mAnimationDuration) { + this.mAnimationProgress %= this.mAnimationDuration; + if(this.mInitialLoopCount != AnimatedSprite.LOOP_CONTINUOUS) { + this.mLoopCount--; + } + } + + if(this.mInitialLoopCount == AnimatedSprite.LOOP_CONTINUOUS || this.mLoopCount >= 0) { + final int currentFrameIndex = this.calculateCurrentFrameIndex(); + + if(this.mFrames == null) { + this.setCurrentTileIndex(this.mFirstTileIndex + currentFrameIndex); + } else { + this.setCurrentTileIndex(this.mFrames[currentFrameIndex]); + } + } else { + this.mAnimationRunning = false; + if(this.mAnimationListener != null) { + this.mAnimationListener.onAnimationEnd(this); + } + } + } + } + + // =========================================================== + // Methods + // =========================================================== + + public void stopAnimation() { + this.mAnimationRunning = false; + } + + public void stopAnimation(final int pTileIndex) { + this.mAnimationRunning = false; + this.setCurrentTileIndex(pTileIndex); + } + + private int calculateCurrentFrameIndex() { + final long animationProgress = this.mAnimationProgress; + final long[] frameEnds = this.mFrameEndsInNanoseconds; + final int frameCount = this.mFrameCount; + for(int i = 0; i < frameCount; i++) { + if(frameEnds[i] > animationProgress) { + return i; + } + } + + return frameCount - 1; + } + + public AnimatedSprite animate(final long pFrameDurationEach) { + return this.animate(pFrameDurationEach, true); + } + + public AnimatedSprite animate(final long pFrameDurationEach, final boolean pLoop) { + return this.animate(pFrameDurationEach, (pLoop) ? AnimatedSprite.LOOP_CONTINUOUS : 0, null); + } + + public AnimatedSprite animate(final long pFrameDurationEach, final int pLoopCount) { + return this.animate(pFrameDurationEach, pLoopCount, null); + } + + public AnimatedSprite animate(final long pFrameDurationEach, final boolean pLoop, final IAnimationListener pAnimationListener) { + return this.animate(pFrameDurationEach, (pLoop) ? AnimatedSprite.LOOP_CONTINUOUS : 0, pAnimationListener); + } + + public AnimatedSprite animate(final long pFrameDurationEach, final int pLoopCount, final IAnimationListener pAnimationListener) { + final long[] frameDurations = new long[this.getTextureRegion().getTileCount()]; + Arrays.fill(frameDurations, pFrameDurationEach); + return this.animate(frameDurations, pLoopCount, pAnimationListener); + } + + public AnimatedSprite animate(final long[] pFrameDurations) { + return this.animate(pFrameDurations, true); + } + + public AnimatedSprite animate(final long[] pFrameDurations, final boolean pLoop) { + return this.animate(pFrameDurations, (pLoop) ? AnimatedSprite.LOOP_CONTINUOUS : 0, null); + } + + public AnimatedSprite animate(final long[] pFrameDurations, final int pLoopCount) { + return this.animate(pFrameDurations, pLoopCount, null); + } + + public AnimatedSprite animate(final long[] pFrameDurations, final boolean pLoop, final IAnimationListener pAnimationListener) { + return this.animate(pFrameDurations, (pLoop) ? AnimatedSprite.LOOP_CONTINUOUS : 0, pAnimationListener); + } + + public AnimatedSprite animate(final long[] pFrameDurations, final int pLoopCount, final IAnimationListener pAnimationListener) { + return this.animate(pFrameDurations, 0, this.getTextureRegion().getTileCount() - 1, pLoopCount, pAnimationListener); + } + + public AnimatedSprite animate(final long[] pFrameDurations, final int pFirstTileIndex, final int pLastTileIndex, final boolean pLoop) { + return this.animate(pFrameDurations, pFirstTileIndex, pLastTileIndex, (pLoop) ? AnimatedSprite.LOOP_CONTINUOUS : 0, null); + } + + public AnimatedSprite animate(final long[] pFrameDurations, final int pFirstTileIndex, final int pLastTileIndex, final int pLoopCount) { + return this.animate(pFrameDurations, pFirstTileIndex, pLastTileIndex, pLoopCount, null); + } + + public AnimatedSprite animate(final long[] pFrameDurations, final int[] pFrames, final int pLoopCount) { + return this.animate(pFrameDurations, pFrames, pLoopCount, null); + } + + /** + * Animate specifics frames + * + * @param pFrameDurations must have the same length as pFrames. + * @param pFrames indices of the frames to animate. + * @param pLoopCount + * @param pAnimationListener + */ + public AnimatedSprite animate(final long[] pFrameDurations, final int[] pFrames, final int pLoopCount, final IAnimationListener pAnimationListener) { + final int frameCount = pFrames.length; + if(pFrameDurations.length != frameCount) { + throw new IllegalArgumentException("pFrameDurations must have the same length as pFrames."); + } + + return this.init(pFrameDurations, frameCount, pFrames, 0, pLoopCount, pAnimationListener); + } + + /** + * @param pFrameDurations + * must have the same length as pFirstTileIndex to + * pLastTileIndex. + * @param pFirstTileIndex + * @param pLastTileIndex + * @param pLoopCount + * @param pAnimationListener + */ + public AnimatedSprite animate(final long[] pFrameDurations, final int pFirstTileIndex, final int pLastTileIndex, final int pLoopCount, final IAnimationListener pAnimationListener) { + if(pLastTileIndex - pFirstTileIndex < 1) { + throw new IllegalArgumentException("An animation needs at least two tiles to animate between."); + } + + final int frameCount = (pLastTileIndex - pFirstTileIndex) + 1; + if(pFrameDurations.length != frameCount) { + throw new IllegalArgumentException("pFrameDurations must have the same length as pFirstTileIndex to pLastTileIndex."); + } + + return this.init(pFrameDurations, frameCount, null, pFirstTileIndex, pLoopCount, pAnimationListener); + } + + private AnimatedSprite init(final long[] pFrameDurations, final int frameCount, final int[] pFrames, final int pFirstTileIndex, final int pLoopCount, final IAnimationListener pAnimationListener) { + this.mFrameCount = frameCount; + this.mAnimationListener = pAnimationListener; + this.mInitialLoopCount = pLoopCount; + this.mLoopCount = pLoopCount; + this.mFrames = pFrames; + this.mFirstTileIndex = pFirstTileIndex; + + if(this.mFrameEndsInNanoseconds == null || this.mFrameCount > this.mFrameEndsInNanoseconds.length) { + this.mFrameEndsInNanoseconds = new long[this.mFrameCount]; + } + + final long[] frameEndsInNanoseconds = this.mFrameEndsInNanoseconds; + MathUtils.arraySumInto(pFrameDurations, frameEndsInNanoseconds, TimeConstants.NANOSECONDSPERMILLISECOND); + + final long lastFrameEnd = frameEndsInNanoseconds[this.mFrameCount - 1]; + this.mAnimationDuration = lastFrameEnd; + + this.mAnimationProgress = 0; + this.mAnimationRunning = true; + + return this; + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== + + public static interface IAnimationListener { + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + public void onAnimationEnd(final AnimatedSprite pAnimatedSprite); + } } diff --git a/AndEngine/src/org/anddev/andengine/entity/sprite/BaseSprite.java b/AndEngine/src/org/anddev/andengine/entity/sprite/BaseSprite.java index 579a4745..2e066411 100644 --- a/AndEngine/src/org/anddev/andengine/entity/sprite/BaseSprite.java +++ b/AndEngine/src/org/anddev/andengine/entity/sprite/BaseSprite.java @@ -17,96 +17,96 @@ * @since 11:38:53 - 08.03.2010 */ public abstract class BaseSprite extends BaseRectangle { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - protected final BaseTextureRegion mTextureRegion; - - // =========================================================== - // Constructors - // =========================================================== - - public BaseSprite(final float pX, final float pY, final float pWidth, final float pHeight, final BaseTextureRegion pTextureRegion) { - super(pX, pY, pWidth, pHeight); - - this.mTextureRegion = pTextureRegion; - this.initBlendFunction(); - } - - public BaseSprite(final float pX, final float pY, final float pWidth, final float pHeight, final BaseTextureRegion pTextureRegion, final RectangleVertexBuffer pRectangleVertexBuffer) { - super(pX, pY, pWidth, pHeight, pRectangleVertexBuffer); - - this.mTextureRegion = pTextureRegion; - this.initBlendFunction(); - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - public BaseTextureRegion getTextureRegion() { - return this.mTextureRegion; - } - - public void setFlippedHorizontal(final boolean pFlippedHorizontal) { - this.mTextureRegion.setFlippedHorizontal(pFlippedHorizontal); - } - - public void setFlippedVertical(final boolean pFlippedVertical) { - this.mTextureRegion.setFlippedVertical(pFlippedVertical); - } - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - public void reset() { - super.reset(); - - this.initBlendFunction(); - } - - @Override - protected void onInitDraw(final GL10 pGL) { - super.onInitDraw(pGL); - GLHelper.enableTextures(pGL); - GLHelper.enableTexCoordArray(pGL); - } - - @Override - protected void doDraw(final GL10 pGL, final Camera pCamera) { - this.mTextureRegion.onApply(pGL); - - super.doDraw(pGL, pCamera); - } - - @Override - protected void finalize() throws Throwable { - super.finalize(); - - final TextureRegionBuffer textureRegionBuffer = this.mTextureRegion.getTextureBuffer(); - if(textureRegionBuffer.isManaged()) { - textureRegionBuffer.unloadFromActiveBufferObjectManager(); - } - } - - // =========================================================== - // Methods - // =========================================================== - - private void initBlendFunction() { - if(this.mTextureRegion.getTexture().getTextureOptions().mPreMultipyAlpha) { - this.setBlendFunction(BLENDFUNCTION_SOURCE_PREMULTIPLYALPHA_DEFAULT, BLENDFUNCTION_DESTINATION_PREMULTIPLYALPHA_DEFAULT); - } - } - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + protected final BaseTextureRegion mTextureRegion; + + // =========================================================== + // Constructors + // =========================================================== + + public BaseSprite(final float pX, final float pY, final float pWidth, final float pHeight, final BaseTextureRegion pTextureRegion) { + super(pX, pY, pWidth, pHeight); + + this.mTextureRegion = pTextureRegion; + this.initBlendFunction(); + } + + public BaseSprite(final float pX, final float pY, final float pWidth, final float pHeight, final BaseTextureRegion pTextureRegion, final RectangleVertexBuffer pRectangleVertexBuffer) { + super(pX, pY, pWidth, pHeight, pRectangleVertexBuffer); + + this.mTextureRegion = pTextureRegion; + this.initBlendFunction(); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + public BaseTextureRegion getTextureRegion() { + return this.mTextureRegion; + } + + public void setFlippedHorizontal(final boolean pFlippedHorizontal) { + this.mTextureRegion.setFlippedHorizontal(pFlippedHorizontal); + } + + public void setFlippedVertical(final boolean pFlippedVertical) { + this.mTextureRegion.setFlippedVertical(pFlippedVertical); + } + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + public void reset() { + super.reset(); + + this.initBlendFunction(); + } + + @Override + protected void onInitDraw(final GL10 pGL) { + super.onInitDraw(pGL); + GLHelper.enableTextures(pGL); + GLHelper.enableTexCoordArray(pGL); + } + + @Override + protected void doDraw(final GL10 pGL, final Camera pCamera) { + this.mTextureRegion.onApply(pGL); + + super.doDraw(pGL, pCamera); + } + + @Override + protected void finalize() throws Throwable { + super.finalize(); + + final TextureRegionBuffer textureRegionBuffer = this.mTextureRegion.getTextureBuffer(); + if(textureRegionBuffer.isManaged()) { + textureRegionBuffer.unloadFromActiveBufferObjectManager(); + } + } + + // =========================================================== + // Methods + // =========================================================== + + private void initBlendFunction() { + if(this.mTextureRegion.getTexture().getTextureOptions().mPreMultipyAlpha) { + this.setBlendFunction(BLENDFUNCTION_SOURCE_PREMULTIPLYALPHA_DEFAULT, BLENDFUNCTION_DESTINATION_PREMULTIPLYALPHA_DEFAULT); + } + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/entity/sprite/Sprite.java b/AndEngine/src/org/anddev/andengine/entity/sprite/Sprite.java index 88614259..f8358cc5 100644 --- a/AndEngine/src/org/anddev/andengine/entity/sprite/Sprite.java +++ b/AndEngine/src/org/anddev/andengine/entity/sprite/Sprite.java @@ -11,52 +11,52 @@ * @since 19:22:38 - 09.03.2010 */ public class Sprite extends BaseSprite { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - // =========================================================== - // Constructors - // =========================================================== - - public Sprite(final float pX, final float pY, final TextureRegion pTextureRegion) { - super(pX, pY, pTextureRegion.getWidth(), pTextureRegion.getHeight(), pTextureRegion); - } - - public Sprite(final float pX, final float pY, final float pWidth, final float pHeight, final TextureRegion pTextureRegion) { - super(pX, pY, pWidth, pHeight, pTextureRegion); - } - - public Sprite(final float pX, final float pY, final TextureRegion pTextureRegion, final RectangleVertexBuffer pRectangleVertexBuffer) { - super(pX, pY, pTextureRegion.getWidth(), pTextureRegion.getHeight(), pTextureRegion, pRectangleVertexBuffer); - } - - public Sprite(final float pX, final float pY, final float pWidth, final float pHeight, final TextureRegion pTextureRegion, final RectangleVertexBuffer pRectangleVertexBuffer) { - super(pX, pY, pWidth, pHeight, pTextureRegion, pRectangleVertexBuffer); - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - public TextureRegion getTextureRegion() { - return (TextureRegion)this.mTextureRegion; - } - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + // =========================================================== + // Constructors + // =========================================================== + + public Sprite(final float pX, final float pY, final TextureRegion pTextureRegion) { + super(pX, pY, pTextureRegion.getWidth(), pTextureRegion.getHeight(), pTextureRegion); + } + + public Sprite(final float pX, final float pY, final float pWidth, final float pHeight, final TextureRegion pTextureRegion) { + super(pX, pY, pWidth, pHeight, pTextureRegion); + } + + public Sprite(final float pX, final float pY, final TextureRegion pTextureRegion, final RectangleVertexBuffer pRectangleVertexBuffer) { + super(pX, pY, pTextureRegion.getWidth(), pTextureRegion.getHeight(), pTextureRegion, pRectangleVertexBuffer); + } + + public Sprite(final float pX, final float pY, final float pWidth, final float pHeight, final TextureRegion pTextureRegion, final RectangleVertexBuffer pRectangleVertexBuffer) { + super(pX, pY, pWidth, pHeight, pTextureRegion, pRectangleVertexBuffer); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + public TextureRegion getTextureRegion() { + return (TextureRegion)this.mTextureRegion; + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/entity/sprite/TiledSprite.java b/AndEngine/src/org/anddev/andengine/entity/sprite/TiledSprite.java index 5516b1ba..2c86bc0c 100644 --- a/AndEngine/src/org/anddev/andengine/entity/sprite/TiledSprite.java +++ b/AndEngine/src/org/anddev/andengine/entity/sprite/TiledSprite.java @@ -11,68 +11,68 @@ * @since 19:30:13 - 09.03.2010 */ public class TiledSprite extends BaseSprite { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - // =========================================================== - // Constructors - // =========================================================== - - public TiledSprite(final float pX, final float pY, final TiledTextureRegion pTiledTextureRegion) { - super(pX, pY, pTiledTextureRegion.getTileWidth(), pTiledTextureRegion.getTileHeight(), pTiledTextureRegion); - } - - public TiledSprite(final float pX, final float pY, final float pTileWidth, final float pTileHeight, final TiledTextureRegion pTiledTextureRegion) { - super(pX, pY, pTileWidth, pTileHeight, pTiledTextureRegion); - } - - public TiledSprite(final float pX, final float pY, final TiledTextureRegion pTiledTextureRegion, final RectangleVertexBuffer pRectangleVertexBuffer) { - super(pX, pY, pTiledTextureRegion.getTileWidth(), pTiledTextureRegion.getTileHeight(), pTiledTextureRegion, pRectangleVertexBuffer); - } - - public TiledSprite(final float pX, final float pY, final float pTileWidth, final float pTileHeight, final TiledTextureRegion pTiledTextureRegion, final RectangleVertexBuffer pRectangleVertexBuffer) { - super(pX, pY, pTileWidth, pTileHeight, pTiledTextureRegion, pRectangleVertexBuffer); - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - public TiledTextureRegion getTextureRegion() { - return (TiledTextureRegion)super.getTextureRegion(); - } - - // =========================================================== - // Methods - // =========================================================== - - public int getCurrentTileIndex() { - return this.getTextureRegion().getCurrentTileIndex(); - } - - public void setCurrentTileIndex(final int pTileIndex) { - this.getTextureRegion().setCurrentTileIndex(pTileIndex); - } - - public void setCurrentTileIndex(final int pTileColumn, final int pTileRow) { - this.getTextureRegion().setCurrentTileIndex(pTileColumn, pTileRow); - } - - public void nextTile() { - this.getTextureRegion().nextTile(); - } - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + // =========================================================== + // Constructors + // =========================================================== + + public TiledSprite(final float pX, final float pY, final TiledTextureRegion pTiledTextureRegion) { + super(pX, pY, pTiledTextureRegion.getTileWidth(), pTiledTextureRegion.getTileHeight(), pTiledTextureRegion); + } + + public TiledSprite(final float pX, final float pY, final float pTileWidth, final float pTileHeight, final TiledTextureRegion pTiledTextureRegion) { + super(pX, pY, pTileWidth, pTileHeight, pTiledTextureRegion); + } + + public TiledSprite(final float pX, final float pY, final TiledTextureRegion pTiledTextureRegion, final RectangleVertexBuffer pRectangleVertexBuffer) { + super(pX, pY, pTiledTextureRegion.getTileWidth(), pTiledTextureRegion.getTileHeight(), pTiledTextureRegion, pRectangleVertexBuffer); + } + + public TiledSprite(final float pX, final float pY, final float pTileWidth, final float pTileHeight, final TiledTextureRegion pTiledTextureRegion, final RectangleVertexBuffer pRectangleVertexBuffer) { + super(pX, pY, pTileWidth, pTileHeight, pTiledTextureRegion, pRectangleVertexBuffer); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + public TiledTextureRegion getTextureRegion() { + return (TiledTextureRegion)super.getTextureRegion(); + } + + // =========================================================== + // Methods + // =========================================================== + + public int getCurrentTileIndex() { + return this.getTextureRegion().getCurrentTileIndex(); + } + + public void setCurrentTileIndex(final int pTileIndex) { + this.getTextureRegion().setCurrentTileIndex(pTileIndex); + } + + public void setCurrentTileIndex(final int pTileColumn, final int pTileRow) { + this.getTextureRegion().setCurrentTileIndex(pTileColumn, pTileRow); + } + + public void nextTile() { + this.getTextureRegion().nextTile(); + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/entity/sprite/batch/DynamicSpriteBatch.java b/AndEngine/src/org/anddev/andengine/entity/sprite/batch/DynamicSpriteBatch.java index 06a823a9..d86be1e2 100644 --- a/AndEngine/src/org/anddev/andengine/entity/sprite/batch/DynamicSpriteBatch.java +++ b/AndEngine/src/org/anddev/andengine/entity/sprite/batch/DynamicSpriteBatch.java @@ -13,53 +13,53 @@ * @since 21:48:21 - 27.07.2011 */ public abstract class DynamicSpriteBatch extends SpriteBatch { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - public DynamicSpriteBatch(final ITexture pTexture, final int pCapacity) { - super(pTexture, pCapacity); - } + public DynamicSpriteBatch(final ITexture pTexture, final int pCapacity) { + super(pTexture, pCapacity); + } - public DynamicSpriteBatch(final ITexture pTexture, final int pCapacity, final SpriteBatchVertexBuffer pSpriteBatchVertexBuffer, final SpriteBatchTextureRegionBuffer pSpriteBatchTextureRegionBuffer) { - super(pTexture, pCapacity, pSpriteBatchVertexBuffer, pSpriteBatchTextureRegionBuffer); - } + public DynamicSpriteBatch(final ITexture pTexture, final int pCapacity, final SpriteBatchVertexBuffer pSpriteBatchVertexBuffer, final SpriteBatchTextureRegionBuffer pSpriteBatchTextureRegionBuffer) { + super(pTexture, pCapacity, pSpriteBatchVertexBuffer, pSpriteBatchTextureRegionBuffer); + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - /** - * @return true to submit, if you made any changes, or false otherwise. - */ - protected abstract boolean onUpdateSpriteBatch(); + /** + * @return true to submit, if you made any changes, or false otherwise. + */ + protected abstract boolean onUpdateSpriteBatch(); - @Override - protected void begin(final GL10 pGL) { - super.begin(pGL); + @Override + protected void begin(final GL10 pGL) { + super.begin(pGL); - if(this.onUpdateSpriteBatch()) { - this.submit(); - } - } + if(this.onUpdateSpriteBatch()) { + this.submit(); + } + } - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/entity/sprite/batch/SpriteBatch.java b/AndEngine/src/org/anddev/andengine/entity/sprite/batch/SpriteBatch.java index 1e7b197d..5a88d796 100644 --- a/AndEngine/src/org/anddev/andengine/entity/sprite/batch/SpriteBatch.java +++ b/AndEngine/src/org/anddev/andengine/entity/sprite/batch/SpriteBatch.java @@ -24,332 +24,332 @@ * @since 11:45:48 - 14.06.2011 */ public class SpriteBatch extends Entity { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - protected final ITexture mTexture; - protected final int mCapacity; + protected final ITexture mTexture; + protected final int mCapacity; - protected int mIndex; - private int mVertices; + protected int mIndex; + private int mVertices; - private int mSourceBlendFunction; - private int mDestinationBlendFunction; + private int mSourceBlendFunction; + private int mDestinationBlendFunction; - private final SpriteBatchVertexBuffer mSpriteBatchVertexBuffer; - private final SpriteBatchTextureRegionBuffer mSpriteBatchTextureRegionBuffer; + private final SpriteBatchVertexBuffer mSpriteBatchVertexBuffer; + private final SpriteBatchTextureRegionBuffer mSpriteBatchTextureRegionBuffer; - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - public SpriteBatch(final ITexture pTexture, final int pCapacity) { - this(pTexture, pCapacity, new SpriteBatchVertexBuffer(pCapacity, GL11.GL_STATIC_DRAW, true), new SpriteBatchTextureRegionBuffer(pCapacity, GL11.GL_STATIC_DRAW, true)); - } + public SpriteBatch(final ITexture pTexture, final int pCapacity) { + this(pTexture, pCapacity, new SpriteBatchVertexBuffer(pCapacity, GL11.GL_STATIC_DRAW, true), new SpriteBatchTextureRegionBuffer(pCapacity, GL11.GL_STATIC_DRAW, true)); + } - public SpriteBatch(final ITexture pTexture, final int pCapacity, final SpriteBatchVertexBuffer pSpriteBatchVertexBuffer, final SpriteBatchTextureRegionBuffer pSpriteBatchTextureRegionBuffer) { - this.mTexture = pTexture; - this.mCapacity = pCapacity; - this.mSpriteBatchVertexBuffer = pSpriteBatchVertexBuffer; - this.mSpriteBatchTextureRegionBuffer = pSpriteBatchTextureRegionBuffer; + public SpriteBatch(final ITexture pTexture, final int pCapacity, final SpriteBatchVertexBuffer pSpriteBatchVertexBuffer, final SpriteBatchTextureRegionBuffer pSpriteBatchTextureRegionBuffer) { + this.mTexture = pTexture; + this.mCapacity = pCapacity; + this.mSpriteBatchVertexBuffer = pSpriteBatchVertexBuffer; + this.mSpriteBatchTextureRegionBuffer = pSpriteBatchTextureRegionBuffer; - this.initBlendFunction(); - } + this.initBlendFunction(); + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - public void setBlendFunction(final int pSourceBlendFunction, final int pDestinationBlendFunction) { - this.mSourceBlendFunction = pSourceBlendFunction; - this.mDestinationBlendFunction = pDestinationBlendFunction; - } + public void setBlendFunction(final int pSourceBlendFunction, final int pDestinationBlendFunction) { + this.mSourceBlendFunction = pSourceBlendFunction; + this.mDestinationBlendFunction = pDestinationBlendFunction; + } - public int getIndex() { - return this.mIndex; - } + public int getIndex() { + return this.mIndex; + } - public void setIndex(final int pIndex) { - this.assertCapacity(pIndex); + public void setIndex(final int pIndex) { + this.assertCapacity(pIndex); - this.mIndex = pIndex; + this.mIndex = pIndex; - final int vertexIndex = pIndex * 2 * SpriteBatchVertexBuffer.VERTICES_PER_RECTANGLE; + final int vertexIndex = pIndex * 2 * SpriteBatchVertexBuffer.VERTICES_PER_RECTANGLE; - this.mSpriteBatchVertexBuffer.setIndex(vertexIndex); - this.mSpriteBatchTextureRegionBuffer.setIndex(vertexIndex); - } + this.mSpriteBatchVertexBuffer.setIndex(vertexIndex); + this.mSpriteBatchTextureRegionBuffer.setIndex(vertexIndex); + } - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - protected void doDraw(final GL10 pGL, final Camera pCamera) { - this.onInitDraw(pGL); + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + protected void doDraw(final GL10 pGL, final Camera pCamera) { + this.onInitDraw(pGL); - this.begin(pGL); + this.begin(pGL); - this.onApplyVertices(pGL); - this.onApplyTextureRegion(pGL); - this.drawVertices(pGL, pCamera); + this.onApplyVertices(pGL); + this.onApplyTextureRegion(pGL); + this.drawVertices(pGL, pCamera); - this.end(pGL); - } + this.end(pGL); + } - @Override - public void reset() { - super.reset(); + @Override + public void reset() { + super.reset(); - this.initBlendFunction(); - } + this.initBlendFunction(); + } - @Override - protected void finalize() throws Throwable { - super.finalize(); + @Override + protected void finalize() throws Throwable { + super.finalize(); - if(this.mSpriteBatchVertexBuffer.isManaged()) { - this.mSpriteBatchVertexBuffer.unloadFromActiveBufferObjectManager(); - } - if(this.mSpriteBatchTextureRegionBuffer.isManaged()) { - this.mSpriteBatchTextureRegionBuffer.unloadFromActiveBufferObjectManager(); - } - } + if(this.mSpriteBatchVertexBuffer.isManaged()) { + this.mSpriteBatchVertexBuffer.unloadFromActiveBufferObjectManager(); + } + if(this.mSpriteBatchTextureRegionBuffer.isManaged()) { + this.mSpriteBatchTextureRegionBuffer.unloadFromActiveBufferObjectManager(); + } + } - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - protected void begin(@SuppressWarnings("unused") final GL10 pGL) { -// GLHelper.disableDepthMask(pGL); - } + protected void begin(@SuppressWarnings("unused") final GL10 pGL) { +// GLHelper.disableDepthMask(pGL); + } - protected void end(@SuppressWarnings("unused") final GL10 pGL) { -// GLHelper.enableDepthMask(pGL); - } + protected void end(@SuppressWarnings("unused") final GL10 pGL) { +// GLHelper.enableDepthMask(pGL); + } - /** - * @see {@link SpriteBatchVertexBuffer#add(float, float, float, float)}. - */ - public void draw(final BaseTextureRegion pTextureRegion, final float pX, final float pY, final float pWidth, final float pHeight) { - this.assertCapacity(); - this.assertTexture(pTextureRegion); + /** + * @see {@link SpriteBatchVertexBuffer#add(float, float, float, float)}. + */ + public void draw(final BaseTextureRegion pTextureRegion, final float pX, final float pY, final float pWidth, final float pHeight) { + this.assertCapacity(); + this.assertTexture(pTextureRegion); - this.mSpriteBatchVertexBuffer.add(pX, pY, pWidth, pHeight); - this.mSpriteBatchTextureRegionBuffer.add(pTextureRegion); + this.mSpriteBatchVertexBuffer.add(pX, pY, pWidth, pHeight); + this.mSpriteBatchTextureRegionBuffer.add(pTextureRegion); - this.mIndex++; - } - - public void drawWithoutChecks(final BaseTextureRegion pTextureRegion, final float pX, final float pY, final float pWidth, final float pHeight) { - this.mSpriteBatchVertexBuffer.add(pX, pY, pWidth, pHeight); - this.mSpriteBatchTextureRegionBuffer.add(pTextureRegion); - - this.mIndex++; - } - - /** - * @see {@link SpriteBatchVertexBuffer#add(float, float, float, float, float)}. - */ - public void draw(final BaseTextureRegion pTextureRegion, final float pX, final float pY, final float pWidth, final float pHeight, final float pRotation) { - this.assertCapacity(); - this.assertTexture(pTextureRegion); + this.mIndex++; + } + + public void drawWithoutChecks(final BaseTextureRegion pTextureRegion, final float pX, final float pY, final float pWidth, final float pHeight) { + this.mSpriteBatchVertexBuffer.add(pX, pY, pWidth, pHeight); + this.mSpriteBatchTextureRegionBuffer.add(pTextureRegion); + + this.mIndex++; + } + + /** + * @see {@link SpriteBatchVertexBuffer#add(float, float, float, float, float)}. + */ + public void draw(final BaseTextureRegion pTextureRegion, final float pX, final float pY, final float pWidth, final float pHeight, final float pRotation) { + this.assertCapacity(); + this.assertTexture(pTextureRegion); - this.mSpriteBatchVertexBuffer.add(pX, pY, pWidth, pHeight, pRotation); - this.mSpriteBatchTextureRegionBuffer.add(pTextureRegion); - - this.mIndex++; - } - - public void drawWithoutChecks(final BaseTextureRegion pTextureRegion, final float pX, final float pY, final float pWidth, final float pHeight, final float pRotation) { - this.mSpriteBatchVertexBuffer.add(pX, pY, pWidth, pHeight, pRotation); - this.mSpriteBatchTextureRegionBuffer.add(pTextureRegion); + this.mSpriteBatchVertexBuffer.add(pX, pY, pWidth, pHeight, pRotation); + this.mSpriteBatchTextureRegionBuffer.add(pTextureRegion); + + this.mIndex++; + } + + public void drawWithoutChecks(final BaseTextureRegion pTextureRegion, final float pX, final float pY, final float pWidth, final float pHeight, final float pRotation) { + this.mSpriteBatchVertexBuffer.add(pX, pY, pWidth, pHeight, pRotation); + this.mSpriteBatchTextureRegionBuffer.add(pTextureRegion); - this.mIndex++; - } + this.mIndex++; + } - /** - * @see {@link SpriteBatchVertexBuffer#add(float, float, float, float, float, float)}. - */ - public void draw(final BaseTextureRegion pTextureRegion, final float pX, final float pY, final float pWidth, final float pHeight, final float pScaleX, final float pScaleY) { - this.assertCapacity(); - this.assertTexture(pTextureRegion); - - this.mSpriteBatchVertexBuffer.add(pX, pY, pWidth, pHeight, pScaleX, pScaleY); - this.mSpriteBatchTextureRegionBuffer.add(pTextureRegion); - - this.mIndex++; - } - - public void drawWithoutChecks(final BaseTextureRegion pTextureRegion, final float pX, final float pY, final float pWidth, final float pHeight, final float pScaleX, final float pScaleY) { - this.mSpriteBatchVertexBuffer.add(pX, pY, pWidth, pHeight, pScaleX, pScaleY); - this.mSpriteBatchTextureRegionBuffer.add(pTextureRegion); - - this.mIndex++; - } + /** + * @see {@link SpriteBatchVertexBuffer#add(float, float, float, float, float, float)}. + */ + public void draw(final BaseTextureRegion pTextureRegion, final float pX, final float pY, final float pWidth, final float pHeight, final float pScaleX, final float pScaleY) { + this.assertCapacity(); + this.assertTexture(pTextureRegion); + + this.mSpriteBatchVertexBuffer.add(pX, pY, pWidth, pHeight, pScaleX, pScaleY); + this.mSpriteBatchTextureRegionBuffer.add(pTextureRegion); + + this.mIndex++; + } + + public void drawWithoutChecks(final BaseTextureRegion pTextureRegion, final float pX, final float pY, final float pWidth, final float pHeight, final float pScaleX, final float pScaleY) { + this.mSpriteBatchVertexBuffer.add(pX, pY, pWidth, pHeight, pScaleX, pScaleY); + this.mSpriteBatchTextureRegionBuffer.add(pTextureRegion); + + this.mIndex++; + } - /** - * @see {@link SpriteBatchVertexBuffer#add(float, float, float, float, float, float, float)}. - */ - public void draw(final BaseTextureRegion pTextureRegion, final float pX, final float pY, final float pWidth, final float pHeight, final float pRotation, final float pScaleX, final float pScaleY) { - this.assertCapacity(); - this.assertTexture(pTextureRegion); - - this.mSpriteBatchVertexBuffer.add(pX, pY, pWidth, pHeight, pRotation, pScaleX, pScaleY); - this.mSpriteBatchTextureRegionBuffer.add(pTextureRegion); - - this.mIndex++; - } + /** + * @see {@link SpriteBatchVertexBuffer#add(float, float, float, float, float, float, float)}. + */ + public void draw(final BaseTextureRegion pTextureRegion, final float pX, final float pY, final float pWidth, final float pHeight, final float pRotation, final float pScaleX, final float pScaleY) { + this.assertCapacity(); + this.assertTexture(pTextureRegion); + + this.mSpriteBatchVertexBuffer.add(pX, pY, pWidth, pHeight, pRotation, pScaleX, pScaleY); + this.mSpriteBatchTextureRegionBuffer.add(pTextureRegion); + + this.mIndex++; + } - public void drawWithoutChecks(final BaseTextureRegion pTextureRegion, final float pX, final float pY, final float pWidth, final float pHeight, final float pRotation, final float pScaleX, final float pScaleY) { - this.mSpriteBatchVertexBuffer.add(pX, pY, pWidth, pHeight, pRotation, pScaleX, pScaleY); - this.mSpriteBatchTextureRegionBuffer.add(pTextureRegion); - - this.mIndex++; - } - - /** - * {@link SpriteBatchVertexBuffer#add(float, float, float, float, float, float, float, float)}. - */ - public void draw(final BaseTextureRegion pTextureRegion, final float pX1, final float pY1, final float pX2, final float pY2, final float pX3, final float pY3, final float pX4, final float pY4) { - this.assertCapacity(); - this.assertTexture(pTextureRegion); + public void drawWithoutChecks(final BaseTextureRegion pTextureRegion, final float pX, final float pY, final float pWidth, final float pHeight, final float pRotation, final float pScaleX, final float pScaleY) { + this.mSpriteBatchVertexBuffer.add(pX, pY, pWidth, pHeight, pRotation, pScaleX, pScaleY); + this.mSpriteBatchTextureRegionBuffer.add(pTextureRegion); + + this.mIndex++; + } + + /** + * {@link SpriteBatchVertexBuffer#add(float, float, float, float, float, float, float, float)}. + */ + public void draw(final BaseTextureRegion pTextureRegion, final float pX1, final float pY1, final float pX2, final float pY2, final float pX3, final float pY3, final float pX4, final float pY4) { + this.assertCapacity(); + this.assertTexture(pTextureRegion); - this.mSpriteBatchVertexBuffer.addInner(pX1, pY1, pX2, pY2, pX3, pY3, pX4, pY4); - this.mSpriteBatchTextureRegionBuffer.add(pTextureRegion); - - this.mIndex++; - } - - public void drawWithoutChecks(final BaseTextureRegion pTextureRegion, final float pX1, final float pY1, final float pX2, final float pY2, final float pX3, final float pY3, final float pX4, final float pY4) { - this.mSpriteBatchVertexBuffer.addInner(pX1, pY1, pX2, pY2, pX3, pY3, pX4, pY4); - this.mSpriteBatchTextureRegionBuffer.add(pTextureRegion); - - this.mIndex++; - } - - /** - * {@link SpriteBatchVertexBuffer#add(BaseSprite)}. - */ - public void draw(final BaseSprite pBaseSprite) { - if(pBaseSprite.isVisible()) { - this.assertCapacity(); - - final BaseTextureRegion textureRegion = pBaseSprite.getTextureRegion(); - this.assertTexture(textureRegion); - - if(pBaseSprite.getRotation() == 0 && !pBaseSprite.isScaled()) { - this.mSpriteBatchVertexBuffer.add(pBaseSprite.getX(), pBaseSprite.getY(), pBaseSprite.getWidth(), pBaseSprite.getHeight()); - } else { - this.mSpriteBatchVertexBuffer.add(pBaseSprite.getWidth(), pBaseSprite.getHeight(), pBaseSprite.getLocalToParentTransformation()); - } - - this.mSpriteBatchTextureRegionBuffer.add(textureRegion); - - this.mIndex++; - } - } - - public void drawWithoutChecks(final BaseSprite pBaseSprite) { - if(pBaseSprite.isVisible()) { - final BaseTextureRegion textureRegion = pBaseSprite.getTextureRegion(); - - if(pBaseSprite.getRotation() == 0 && !pBaseSprite.isScaled()) { - this.mSpriteBatchVertexBuffer.add(pBaseSprite.getX(), pBaseSprite.getY(), pBaseSprite.getWidth(), pBaseSprite.getHeight()); - } else { - this.mSpriteBatchVertexBuffer.add(pBaseSprite.getWidth(), pBaseSprite.getHeight(), pBaseSprite.getLocalToParentTransformation()); - } - - this.mSpriteBatchTextureRegionBuffer.add(textureRegion); - - this.mIndex++; - } - } - - public void submit() { - this.onSubmit(); - } - - private void onSubmit() { - this.mVertices = this.mIndex * SpriteBatchVertexBuffer.VERTICES_PER_RECTANGLE; - - this.mSpriteBatchVertexBuffer.submit(); - this.mSpriteBatchTextureRegionBuffer.submit(); - - this.mIndex = 0; - this.mSpriteBatchVertexBuffer.setIndex(0); - this.mSpriteBatchTextureRegionBuffer.setIndex(0); - } - - private void initBlendFunction() { - if(this.mTexture.getTextureOptions().mPreMultipyAlpha) { - this.setBlendFunction(Shape.BLENDFUNCTION_SOURCE_PREMULTIPLYALPHA_DEFAULT, Shape.BLENDFUNCTION_DESTINATION_PREMULTIPLYALPHA_DEFAULT); - } - } - - protected void onInitDraw(final GL10 pGL) { - GLHelper.setColor(pGL, this.mRed, this.mGreen, this.mBlue, this.mAlpha); - - GLHelper.enableVertexArray(pGL); - GLHelper.blendFunction(pGL, this.mSourceBlendFunction, this.mDestinationBlendFunction); - - GLHelper.enableTextures(pGL); - GLHelper.enableTexCoordArray(pGL); - } - - protected void onApplyVertices(final GL10 pGL) { - if(GLHelper.EXTENSIONS_VERTEXBUFFEROBJECTS) { - final GL11 gl11 = (GL11)pGL; - - this.mSpriteBatchVertexBuffer.selectOnHardware(gl11); - GLHelper.vertexZeroPointer(gl11); - } else { - GLHelper.vertexPointer(pGL, this.mSpriteBatchVertexBuffer.getFloatBuffer()); - } - } - - private void onApplyTextureRegion(final GL10 pGL) { - if(GLHelper.EXTENSIONS_VERTEXBUFFEROBJECTS) { - final GL11 gl11 = (GL11)pGL; - - this.mSpriteBatchTextureRegionBuffer.selectOnHardware(gl11); - - this.mTexture.bind(pGL); - GLHelper.texCoordZeroPointer(gl11); - } else { - this.mTexture.bind(pGL); - GLHelper.texCoordPointer(pGL, this.mSpriteBatchTextureRegionBuffer.getFloatBuffer()); - } - } - - private void drawVertices(final GL10 pGL, @SuppressWarnings("unused") final Camera pCamera) { - pGL.glDrawArrays(GL10.GL_TRIANGLES, 0, this.mVertices); - } - - 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!"); - } - } - - private void assertCapacity() { - if(this.mIndex == this.mCapacity) { - throw new IllegalStateException("This SpriteBatch has already reached its capacity (" + this.mCapacity + ") !"); - } - } - - protected void assertTexture(final BaseTextureRegion pTextureRegion) { - if(pTextureRegion.getTexture() != this.mTexture) { - throw new IllegalArgumentException("The supplied Texture does match the Texture of this SpriteBatch!"); - } - } - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + this.mSpriteBatchVertexBuffer.addInner(pX1, pY1, pX2, pY2, pX3, pY3, pX4, pY4); + this.mSpriteBatchTextureRegionBuffer.add(pTextureRegion); + + this.mIndex++; + } + + public void drawWithoutChecks(final BaseTextureRegion pTextureRegion, final float pX1, final float pY1, final float pX2, final float pY2, final float pX3, final float pY3, final float pX4, final float pY4) { + this.mSpriteBatchVertexBuffer.addInner(pX1, pY1, pX2, pY2, pX3, pY3, pX4, pY4); + this.mSpriteBatchTextureRegionBuffer.add(pTextureRegion); + + this.mIndex++; + } + + /** + * {@link SpriteBatchVertexBuffer#add(BaseSprite)}. + */ + public void draw(final BaseSprite pBaseSprite) { + if(pBaseSprite.isVisible()) { + this.assertCapacity(); + + final BaseTextureRegion textureRegion = pBaseSprite.getTextureRegion(); + this.assertTexture(textureRegion); + + if(pBaseSprite.getRotation() == 0 && !pBaseSprite.isScaled()) { + this.mSpriteBatchVertexBuffer.add(pBaseSprite.getX(), pBaseSprite.getY(), pBaseSprite.getWidth(), pBaseSprite.getHeight()); + } else { + this.mSpriteBatchVertexBuffer.add(pBaseSprite.getWidth(), pBaseSprite.getHeight(), pBaseSprite.getLocalToParentTransformation()); + } + + this.mSpriteBatchTextureRegionBuffer.add(textureRegion); + + this.mIndex++; + } + } + + public void drawWithoutChecks(final BaseSprite pBaseSprite) { + if(pBaseSprite.isVisible()) { + final BaseTextureRegion textureRegion = pBaseSprite.getTextureRegion(); + + if(pBaseSprite.getRotation() == 0 && !pBaseSprite.isScaled()) { + this.mSpriteBatchVertexBuffer.add(pBaseSprite.getX(), pBaseSprite.getY(), pBaseSprite.getWidth(), pBaseSprite.getHeight()); + } else { + this.mSpriteBatchVertexBuffer.add(pBaseSprite.getWidth(), pBaseSprite.getHeight(), pBaseSprite.getLocalToParentTransformation()); + } + + this.mSpriteBatchTextureRegionBuffer.add(textureRegion); + + this.mIndex++; + } + } + + public void submit() { + this.onSubmit(); + } + + private void onSubmit() { + this.mVertices = this.mIndex * SpriteBatchVertexBuffer.VERTICES_PER_RECTANGLE; + + this.mSpriteBatchVertexBuffer.submit(); + this.mSpriteBatchTextureRegionBuffer.submit(); + + this.mIndex = 0; + this.mSpriteBatchVertexBuffer.setIndex(0); + this.mSpriteBatchTextureRegionBuffer.setIndex(0); + } + + private void initBlendFunction() { + if(this.mTexture.getTextureOptions().mPreMultipyAlpha) { + this.setBlendFunction(Shape.BLENDFUNCTION_SOURCE_PREMULTIPLYALPHA_DEFAULT, Shape.BLENDFUNCTION_DESTINATION_PREMULTIPLYALPHA_DEFAULT); + } + } + + protected void onInitDraw(final GL10 pGL) { + GLHelper.setColor(pGL, this.mRed, this.mGreen, this.mBlue, this.mAlpha); + + GLHelper.enableVertexArray(pGL); + GLHelper.blendFunction(pGL, this.mSourceBlendFunction, this.mDestinationBlendFunction); + + GLHelper.enableTextures(pGL); + GLHelper.enableTexCoordArray(pGL); + } + + protected void onApplyVertices(final GL10 pGL) { + if(GLHelper.EXTENSIONS_VERTEXBUFFEROBJECTS) { + final GL11 gl11 = (GL11)pGL; + + this.mSpriteBatchVertexBuffer.selectOnHardware(gl11); + GLHelper.vertexZeroPointer(gl11); + } else { + GLHelper.vertexPointer(pGL, this.mSpriteBatchVertexBuffer.getFloatBuffer()); + } + } + + private void onApplyTextureRegion(final GL10 pGL) { + if(GLHelper.EXTENSIONS_VERTEXBUFFEROBJECTS) { + final GL11 gl11 = (GL11)pGL; + + this.mSpriteBatchTextureRegionBuffer.selectOnHardware(gl11); + + this.mTexture.bind(pGL); + GLHelper.texCoordZeroPointer(gl11); + } else { + this.mTexture.bind(pGL); + GLHelper.texCoordPointer(pGL, this.mSpriteBatchTextureRegionBuffer.getFloatBuffer()); + } + } + + private void drawVertices(final GL10 pGL, @SuppressWarnings("unused") final Camera pCamera) { + pGL.glDrawArrays(GL10.GL_TRIANGLES, 0, this.mVertices); + } + + 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!"); + } + } + + private void assertCapacity() { + if(this.mIndex == this.mCapacity) { + throw new IllegalStateException("This SpriteBatch has already reached its capacity (" + this.mCapacity + ") !"); + } + } + + protected void assertTexture(final BaseTextureRegion pTextureRegion) { + if(pTextureRegion.getTexture() != this.mTexture) { + throw new IllegalArgumentException("The supplied Texture does match the Texture of this SpriteBatch!"); + } + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/entity/sprite/batch/SpriteGroup.java b/AndEngine/src/org/anddev/andengine/entity/sprite/batch/SpriteGroup.java index 66580962..897fd21f 100644 --- a/AndEngine/src/org/anddev/andengine/entity/sprite/batch/SpriteGroup.java +++ b/AndEngine/src/org/anddev/andengine/entity/sprite/batch/SpriteGroup.java @@ -17,91 +17,91 @@ * @since 12:10:35 - 15.06.2011 */ public class SpriteGroup extends DynamicSpriteBatch { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - // =========================================================== - // Constructors - // =========================================================== - - public SpriteGroup(final ITexture pTexture, final int pCapacity) { - super(pTexture, pCapacity); - - /* Make children not be drawn automatically, as we handle the drawing ourself. */ - this.setChildrenVisible(false); - } - - public SpriteGroup(final ITexture pTexture, final int pCapacity, final SpriteBatchVertexBuffer pSpriteBatchVertexBuffer, final SpriteBatchTextureRegionBuffer pSpriteBatchTextureRegionBuffer) { - super(pTexture, pCapacity, pSpriteBatchVertexBuffer, pSpriteBatchTextureRegionBuffer); - - /* Make children not be drawn automatically, as we handle the drawing ourself. */ - this.setChildrenVisible(false); - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - /** - * Instead use {@link SpriteGroup#attachChild(BaseSprite)}. - */ - @Override - @Deprecated - public void attachChild(final IEntity pEntity) throws IllegalArgumentException { - if(pEntity instanceof BaseSprite) { - this.attachChild((BaseSprite)pEntity); - } else { - throw new IllegalArgumentException("A SpriteGroup can only handle children of type BaseSprite or subclasses of BaseSprite, like Sprite, TiledSprite or AnimatedSprite."); - } - } - - public void attachChild(final BaseSprite pBaseSprite) { - this.assertCapacity(); - this.assertTexture(pBaseSprite.getTextureRegion()); - super.attachChild(pBaseSprite); - } - - public void attachChildren(final ArrayList pBaseSprites) { - final int baseSpriteCount = pBaseSprites.size(); - for(int i = 0; i < baseSpriteCount; i++) { - this.attachChild(pBaseSprites.get(i)); - } - } - - @Override - protected boolean onUpdateSpriteBatch() { - final SmartList children = this.mChildren; - if(children == null) { - return false; - } else { - final int childCount = children.size(); - for(int i = 0; i < childCount; i++) { - super.drawWithoutChecks((BaseSprite)children.get(i)); - } - return true; - } - } - - // =========================================================== - // Methods - // =========================================================== - - private void assertCapacity() { - if(this.getChildCount() >= this.mCapacity) { - throw new IllegalStateException("This SpriteGroup has already reached its capacity (" + this.mCapacity + ") !"); - } - } - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + // =========================================================== + // Constructors + // =========================================================== + + public SpriteGroup(final ITexture pTexture, final int pCapacity) { + super(pTexture, pCapacity); + + /* Make children not be drawn automatically, as we handle the drawing ourself. */ + this.setChildrenVisible(false); + } + + public SpriteGroup(final ITexture pTexture, final int pCapacity, final SpriteBatchVertexBuffer pSpriteBatchVertexBuffer, final SpriteBatchTextureRegionBuffer pSpriteBatchTextureRegionBuffer) { + super(pTexture, pCapacity, pSpriteBatchVertexBuffer, pSpriteBatchTextureRegionBuffer); + + /* Make children not be drawn automatically, as we handle the drawing ourself. */ + this.setChildrenVisible(false); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + /** + * Instead use {@link SpriteGroup#attachChild(BaseSprite)}. + */ + @Override + @Deprecated + public void attachChild(final IEntity pEntity) throws IllegalArgumentException { + if(pEntity instanceof BaseSprite) { + this.attachChild((BaseSprite)pEntity); + } else { + throw new IllegalArgumentException("A SpriteGroup can only handle children of type BaseSprite or subclasses of BaseSprite, like Sprite, TiledSprite or AnimatedSprite."); + } + } + + public void attachChild(final BaseSprite pBaseSprite) { + this.assertCapacity(); + this.assertTexture(pBaseSprite.getTextureRegion()); + super.attachChild(pBaseSprite); + } + + public void attachChildren(final ArrayList pBaseSprites) { + final int baseSpriteCount = pBaseSprites.size(); + for(int i = 0; i < baseSpriteCount; i++) { + this.attachChild(pBaseSprites.get(i)); + } + } + + @Override + protected boolean onUpdateSpriteBatch() { + final SmartList children = this.mChildren; + if(children == null) { + return false; + } else { + final int childCount = children.size(); + for(int i = 0; i < childCount; i++) { + super.drawWithoutChecks((BaseSprite)children.get(i)); + } + return true; + } + } + + // =========================================================== + // Methods + // =========================================================== + + private void assertCapacity() { + if(this.getChildCount() >= this.mCapacity) { + throw new IllegalStateException("This SpriteGroup has already reached its capacity (" + this.mCapacity + ") !"); + } + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/entity/text/ChangeableText.java b/AndEngine/src/org/anddev/andengine/entity/text/ChangeableText.java index c3150413..c9ce1bab 100644 --- a/AndEngine/src/org/anddev/andengine/entity/text/ChangeableText.java +++ b/AndEngine/src/org/anddev/andengine/entity/text/ChangeableText.java @@ -16,78 +16,78 @@ * @since 18:07:06 - 08.07.2010 */ public class ChangeableText extends Text { - // =========================================================== - // Constants - // =========================================================== - - private static final String ELLIPSIS = "..."; - private static final int ELLIPSIS_CHARACTER_COUNT = ELLIPSIS.length(); - - // =========================================================== - // Fields - // =========================================================== - - private int mCharacterCountCurrentText; - - // =========================================================== - // Constructors - // =========================================================== - - public ChangeableText(final float pX, final float pY, final Font pFont, final String pText) { - this(pX, pY, pFont, pText, pText.length() - StringUtils.countOccurrences(pText, '\n')); - } - - public ChangeableText(final float pX, final float pY, final Font pFont, final String pText, final int pCharactersMaximum) { - this(pX, pY, pFont, pText, HorizontalAlign.LEFT, pCharactersMaximum); - } - - public ChangeableText(final float pX, final float pY, final Font pFont, final String pText, final HorizontalAlign pHorizontalAlign, final int pCharactersMaximum) { - super(pX, pY, pFont, pText, pHorizontalAlign, pCharactersMaximum); - this.mCharacterCountCurrentText = pText.length() - StringUtils.countOccurrences(pText, '\n'); - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - public void setText(final String pText) { - this.setText(pText, false); - } - - /** - * @param pText - * @param pAllowEllipsis in the case pText is longer than pCharactersMaximum, - * which was passed to the constructor, the displayed text will end with an ellipsis ("..."). - */ - public void setText(final String pText, final boolean pAllowEllipsis) { - final int textCharacterCount = pText.length() - StringUtils.countOccurrences(pText, '\n'); - if(textCharacterCount > this.mCharactersMaximum) { - if(pAllowEllipsis && this.mCharactersMaximum > ELLIPSIS_CHARACTER_COUNT) { - this.updateText(pText.substring(0, this.mCharactersMaximum - ELLIPSIS_CHARACTER_COUNT).concat(ELLIPSIS)); // TODO This allocation could maybe be avoided... - } else { - this.updateText(pText.substring(0, this.mCharactersMaximum)); // TODO This allocation could be avoided... - } - this.mCharacterCountCurrentText = this.mCharactersMaximum; - } else { - this.updateText(pText); - this.mCharacterCountCurrentText = textCharacterCount; - } - } - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - protected void drawVertices(final GL10 pGL, final Camera pCamera) { - pGL.glDrawArrays(GL10.GL_TRIANGLES, 0, this.mCharacterCountCurrentText * TextVertexBuffer.VERTICES_PER_CHARACTER); - } - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + private static final String ELLIPSIS = "..."; + private static final int ELLIPSIS_CHARACTER_COUNT = ELLIPSIS.length(); + + // =========================================================== + // Fields + // =========================================================== + + private int mCharacterCountCurrentText; + + // =========================================================== + // Constructors + // =========================================================== + + public ChangeableText(final float pX, final float pY, final Font pFont, final String pText) { + this(pX, pY, pFont, pText, pText.length() - StringUtils.countOccurrences(pText, '\n')); + } + + public ChangeableText(final float pX, final float pY, final Font pFont, final String pText, final int pCharactersMaximum) { + this(pX, pY, pFont, pText, HorizontalAlign.LEFT, pCharactersMaximum); + } + + public ChangeableText(final float pX, final float pY, final Font pFont, final String pText, final HorizontalAlign pHorizontalAlign, final int pCharactersMaximum) { + super(pX, pY, pFont, pText, pHorizontalAlign, pCharactersMaximum); + this.mCharacterCountCurrentText = pText.length() - StringUtils.countOccurrences(pText, '\n'); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + public void setText(final String pText) { + this.setText(pText, false); + } + + /** + * @param pText + * @param pAllowEllipsis in the case pText is longer than pCharactersMaximum, + * which was passed to the constructor, the displayed text will end with an ellipsis ("..."). + */ + public void setText(final String pText, final boolean pAllowEllipsis) { + final int textCharacterCount = pText.length() - StringUtils.countOccurrences(pText, '\n'); + if(textCharacterCount > this.mCharactersMaximum) { + if(pAllowEllipsis && this.mCharactersMaximum > ELLIPSIS_CHARACTER_COUNT) { + this.updateText(pText.substring(0, this.mCharactersMaximum - ELLIPSIS_CHARACTER_COUNT).concat(ELLIPSIS)); // TODO This allocation could maybe be avoided... + } else { + this.updateText(pText.substring(0, this.mCharactersMaximum)); // TODO This allocation could be avoided... + } + this.mCharacterCountCurrentText = this.mCharactersMaximum; + } else { + this.updateText(pText); + this.mCharacterCountCurrentText = textCharacterCount; + } + } + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + protected void drawVertices(final GL10 pGL, final Camera pCamera) { + pGL.glDrawArrays(GL10.GL_TRIANGLES, 0, this.mCharacterCountCurrentText * TextVertexBuffer.VERTICES_PER_CHARACTER); + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/entity/text/Text.java b/AndEngine/src/org/anddev/andengine/entity/text/Text.java index 893df1bb..bda7cf58 100644 --- a/AndEngine/src/org/anddev/andengine/entity/text/Text.java +++ b/AndEngine/src/org/anddev/andengine/entity/text/Text.java @@ -20,173 +20,173 @@ * @since 10:54:59 - 03.04.2010 */ public class Text extends RectangularShape { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - private final TextTextureBuffer mTextTextureBuffer; + private final TextTextureBuffer mTextTextureBuffer; - private String mText; - private String[] mLines; - private int[] mWidths; + private String mText; + private String[] mLines; + private int[] mWidths; - private final Font mFont; + private final Font mFont; - private int mMaximumLineWidth; + private int mMaximumLineWidth; - protected final int mCharactersMaximum; - protected final int mVertexCount; + protected final int mCharactersMaximum; + protected final int mVertexCount; - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - public Text(final float pX, final float pY, final Font pFont, final String pText) { - this(pX, pY, pFont, pText, HorizontalAlign.LEFT); - } + public Text(final float pX, final float pY, final Font pFont, final String pText) { + this(pX, pY, pFont, pText, HorizontalAlign.LEFT); + } - public Text(final float pX, final float pY, final Font pFont, final String pText, final HorizontalAlign pHorizontalAlign) { - this(pX, pY, pFont, pText, pHorizontalAlign, pText.length() - StringUtils.countOccurrences(pText, '\n')); - } + public Text(final float pX, final float pY, final Font pFont, final String pText, final HorizontalAlign pHorizontalAlign) { + this(pX, pY, pFont, pText, pHorizontalAlign, pText.length() - StringUtils.countOccurrences(pText, '\n')); + } - protected Text(final float pX, final float pY, final Font pFont, final String pText, final HorizontalAlign pHorizontalAlign, final int pCharactersMaximum) { - super(pX, pY, 0, 0, new TextVertexBuffer(pCharactersMaximum, pHorizontalAlign, GL11.GL_STATIC_DRAW, true)); + protected Text(final float pX, final float pY, final Font pFont, final String pText, final HorizontalAlign pHorizontalAlign, final int pCharactersMaximum) { + super(pX, pY, 0, 0, new TextVertexBuffer(pCharactersMaximum, pHorizontalAlign, GL11.GL_STATIC_DRAW, true)); - this.mCharactersMaximum = pCharactersMaximum; - this.mVertexCount = TextVertexBuffer.VERTICES_PER_CHARACTER * this.mCharactersMaximum; + this.mCharactersMaximum = pCharactersMaximum; + this.mVertexCount = TextVertexBuffer.VERTICES_PER_CHARACTER * this.mCharactersMaximum; - this.mTextTextureBuffer = new TextTextureBuffer(2 * this.mVertexCount, GL11.GL_STATIC_DRAW, true); - this.mFont = pFont; + this.mTextTextureBuffer = new TextTextureBuffer(2 * this.mVertexCount, GL11.GL_STATIC_DRAW, true); + this.mFont = pFont; - this.updateText(pText); - - this.initBlendFunction(); - } + this.updateText(pText); + + this.initBlendFunction(); + } - protected void updateText(final String pText) { - this.mText = pText; - final Font font = this.mFont; - - this.mLines = StringUtils.split(this.mText, '\n', this.mLines); - final String[] lines = this.mLines; - - final int lineCount = lines.length; - final boolean widthsReusable = this.mWidths != null && this.mWidths.length == lineCount; - if(!widthsReusable) { - this.mWidths = new int[lineCount]; - } - final int[] widths = this.mWidths; - - int maximumLineWidth = 0; - - for (int i = lineCount - 1; i >= 0; i--) { - widths[i] = font.getStringWidth(lines[i]); - maximumLineWidth = Math.max(maximumLineWidth, widths[i]); - } - this.mMaximumLineWidth = maximumLineWidth; - - super.mWidth = this.mMaximumLineWidth; - final float width = super.mWidth; - super.mBaseWidth = width; - - super.mHeight = lineCount * font.getLineHeight() + (lineCount - 1) * font.getLineGap(); - final float height = super.mHeight; - super.mBaseHeight = height; - - this.mRotationCenterX = width * 0.5f; - this.mRotationCenterY = height * 0.5f; - - this.mScaleCenterX = this.mRotationCenterX; - this.mScaleCenterY = this.mRotationCenterY; - - this.mTextTextureBuffer.update(font, lines); - this.updateVertexBuffer(); - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - public String getText() { - return this.mText; - } - - public int getCharactersMaximum() { - return this.mCharactersMaximum; - } - - @Override - public TextVertexBuffer getVertexBuffer() { - return (TextVertexBuffer)this.mVertexBuffer; - } - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - protected void onInitDraw(final GL10 pGL) { - super.onInitDraw(pGL); - GLHelper.enableTextures(pGL); - GLHelper.enableTexCoordArray(pGL); - } - - @Override - protected void drawVertices(final GL10 pGL, final Camera pCamera) { - pGL.glDrawArrays(GL10.GL_TRIANGLES, 0, this.mVertexCount); - } - - @Override - protected void onUpdateVertexBuffer() { - final Font font = this.mFont; - if(font != null) { - this.getVertexBuffer().update(font, this.mMaximumLineWidth, this.mWidths, this.mLines); - } - } - - @Override - protected void onApplyTransformations(final GL10 pGL) { - super.onApplyTransformations(pGL); - this.applyTexture(pGL); - } - - @Override - protected void finalize() throws Throwable { - super.finalize(); - if(this.mTextTextureBuffer.isManaged()) { - this.mTextTextureBuffer.unloadFromActiveBufferObjectManager(); - } - } - - // =========================================================== - // Methods - // =========================================================== - - private void initBlendFunction() { - if(this.mFont.getTexture().getTextureOptions().mPreMultipyAlpha) { - this.setBlendFunction(BLENDFUNCTION_SOURCE_PREMULTIPLYALPHA_DEFAULT, BLENDFUNCTION_DESTINATION_PREMULTIPLYALPHA_DEFAULT); - } - } - - private void applyTexture(final GL10 pGL) { - if(GLHelper.EXTENSIONS_VERTEXBUFFEROBJECTS) { - final GL11 gl11 = (GL11)pGL; - - this.mTextTextureBuffer.selectOnHardware(gl11); - - this.mFont.getTexture().bind(pGL); - GLHelper.texCoordZeroPointer(gl11); - } else { - this.mFont.getTexture().bind(pGL); - GLHelper.texCoordPointer(pGL, this.mTextTextureBuffer.getFloatBuffer()); - } - } - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== -} \ No newline at end of file + protected void updateText(final String pText) { + this.mText = pText; + final Font font = this.mFont; + + this.mLines = StringUtils.split(this.mText, '\n', this.mLines); + final String[] lines = this.mLines; + + final int lineCount = lines.length; + final boolean widthsReusable = this.mWidths != null && this.mWidths.length == lineCount; + if(!widthsReusable) { + this.mWidths = new int[lineCount]; + } + final int[] widths = this.mWidths; + + int maximumLineWidth = 0; + + for (int i = lineCount - 1; i >= 0; i--) { + widths[i] = font.getStringWidth(lines[i]); + maximumLineWidth = Math.max(maximumLineWidth, widths[i]); + } + this.mMaximumLineWidth = maximumLineWidth; + + super.mWidth = this.mMaximumLineWidth; + final float width = super.mWidth; + super.mBaseWidth = width; + + super.mHeight = lineCount * font.getLineHeight() + (lineCount - 1) * font.getLineGap(); + final float height = super.mHeight; + super.mBaseHeight = height; + + this.mRotationCenterX = width * 0.5f; + this.mRotationCenterY = height * 0.5f; + + this.mScaleCenterX = this.mRotationCenterX; + this.mScaleCenterY = this.mRotationCenterY; + + this.mTextTextureBuffer.update(font, lines); + this.updateVertexBuffer(); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + public String getText() { + return this.mText; + } + + public int getCharactersMaximum() { + return this.mCharactersMaximum; + } + + @Override + public TextVertexBuffer getVertexBuffer() { + return (TextVertexBuffer)this.mVertexBuffer; + } + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + protected void onInitDraw(final GL10 pGL) { + super.onInitDraw(pGL); + GLHelper.enableTextures(pGL); + GLHelper.enableTexCoordArray(pGL); + } + + @Override + protected void drawVertices(final GL10 pGL, final Camera pCamera) { + pGL.glDrawArrays(GL10.GL_TRIANGLES, 0, this.mVertexCount); + } + + @Override + protected void onUpdateVertexBuffer() { + final Font font = this.mFont; + if(font != null) { + this.getVertexBuffer().update(font, this.mMaximumLineWidth, this.mWidths, this.mLines); + } + } + + @Override + protected void onApplyTransformations(final GL10 pGL) { + super.onApplyTransformations(pGL); + this.applyTexture(pGL); + } + + @Override + protected void finalize() throws Throwable { + super.finalize(); + if(this.mTextTextureBuffer.isManaged()) { + this.mTextTextureBuffer.unloadFromActiveBufferObjectManager(); + } + } + + // =========================================================== + // Methods + // =========================================================== + + private void initBlendFunction() { + if(this.mFont.getTexture().getTextureOptions().mPreMultipyAlpha) { + this.setBlendFunction(BLENDFUNCTION_SOURCE_PREMULTIPLYALPHA_DEFAULT, BLENDFUNCTION_DESTINATION_PREMULTIPLYALPHA_DEFAULT); + } + } + + private void applyTexture(final GL10 pGL) { + if(GLHelper.EXTENSIONS_VERTEXBUFFEROBJECTS) { + final GL11 gl11 = (GL11)pGL; + + this.mTextTextureBuffer.selectOnHardware(gl11); + + this.mFont.getTexture().bind(pGL); + GLHelper.texCoordZeroPointer(gl11); + } else { + this.mFont.getTexture().bind(pGL); + GLHelper.texCoordPointer(pGL, this.mTextTextureBuffer.getFloatBuffer()); + } + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== +} diff --git a/AndEngine/src/org/anddev/andengine/entity/text/TickerText.java b/AndEngine/src/org/anddev/andengine/entity/text/TickerText.java index b2676ce0..214a0623 100644 --- a/AndEngine/src/org/anddev/andengine/entity/text/TickerText.java +++ b/AndEngine/src/org/anddev/andengine/entity/text/TickerText.java @@ -15,96 +15,96 @@ * @since 10:02:04 - 05.05.2010 */ public class TickerText extends Text { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - private float mCharactersPerSecond; - - private int mCharactersVisible = 0; - private float mSecondsElapsed = 0; - - private boolean mReverse = false; - - private float mDuration; - - // =========================================================== - // Constructors - // =========================================================== - - public TickerText(final float pX, final float pY, final Font pFont, final String pText, final HorizontalAlign pHorizontalAlign, final float pCharactersPerSecond) { - super(pX, pY, pFont, pText, pHorizontalAlign); - this.setCharactersPerSecond(pCharactersPerSecond); - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - public boolean isReverse() { - return this.mReverse; - } - - public void setReverse(final boolean pReverse) { - this.mReverse = pReverse; - } - - public float getCharactersPerSecond() { - return this.mCharactersPerSecond; - } - - public void setCharactersPerSecond(final float pCharactersPerSecond) { - this.mCharactersPerSecond = pCharactersPerSecond; - this.mDuration = this.mCharactersMaximum * this.mCharactersPerSecond; - } - - public int getCharactersVisible() { - return this.mCharactersVisible; - } - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - protected void onManagedUpdate(final float pSecondsElapsed) { - super.onManagedUpdate(pSecondsElapsed); - if(this.mReverse){ - if(this.mCharactersVisible < this.mCharactersMaximum){ - this.mSecondsElapsed = Math.max(0, this.mSecondsElapsed - pSecondsElapsed); - this.mCharactersVisible = (int)(this.mSecondsElapsed * this.mCharactersPerSecond); - } - } else { - if(this.mCharactersVisible < this.mCharactersMaximum){ - this.mSecondsElapsed = Math.min(this.mDuration, this.mSecondsElapsed + pSecondsElapsed); - this.mCharactersVisible = (int)(this.mSecondsElapsed * this.mCharactersPerSecond); - } - } - } - - @Override - protected void drawVertices(final GL10 pGL, final Camera pCamera) { - pGL.glDrawArrays(GL10.GL_TRIANGLES, 0, this.mCharactersVisible * TextVertexBuffer.VERTICES_PER_CHARACTER); - } - - @Override - public void reset() { - super.reset(); - - this.mCharactersVisible = 0; - this.mSecondsElapsed = 0; - this.mReverse = false; - } - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + private float mCharactersPerSecond; + + private int mCharactersVisible = 0; + private float mSecondsElapsed = 0; + + private boolean mReverse = false; + + private float mDuration; + + // =========================================================== + // Constructors + // =========================================================== + + public TickerText(final float pX, final float pY, final Font pFont, final String pText, final HorizontalAlign pHorizontalAlign, final float pCharactersPerSecond) { + super(pX, pY, pFont, pText, pHorizontalAlign); + this.setCharactersPerSecond(pCharactersPerSecond); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + public boolean isReverse() { + return this.mReverse; + } + + public void setReverse(final boolean pReverse) { + this.mReverse = pReverse; + } + + public float getCharactersPerSecond() { + return this.mCharactersPerSecond; + } + + public void setCharactersPerSecond(final float pCharactersPerSecond) { + this.mCharactersPerSecond = pCharactersPerSecond; + this.mDuration = this.mCharactersMaximum * this.mCharactersPerSecond; + } + + public int getCharactersVisible() { + return this.mCharactersVisible; + } + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + protected void onManagedUpdate(final float pSecondsElapsed) { + super.onManagedUpdate(pSecondsElapsed); + if(this.mReverse){ + if(this.mCharactersVisible < this.mCharactersMaximum){ + this.mSecondsElapsed = Math.max(0, this.mSecondsElapsed - pSecondsElapsed); + this.mCharactersVisible = (int)(this.mSecondsElapsed * this.mCharactersPerSecond); + } + } else { + if(this.mCharactersVisible < this.mCharactersMaximum){ + this.mSecondsElapsed = Math.min(this.mDuration, this.mSecondsElapsed + pSecondsElapsed); + this.mCharactersVisible = (int)(this.mSecondsElapsed * this.mCharactersPerSecond); + } + } + } + + @Override + protected void drawVertices(final GL10 pGL, final Camera pCamera) { + pGL.glDrawArrays(GL10.GL_TRIANGLES, 0, this.mCharactersVisible * TextVertexBuffer.VERTICES_PER_CHARACTER); + } + + @Override + public void reset() { + super.reset(); + + this.mCharactersVisible = 0; + this.mSecondsElapsed = 0; + this.mReverse = false; + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/entity/util/AverageFPSCounter.java b/AndEngine/src/org/anddev/andengine/entity/util/AverageFPSCounter.java index bf451752..b3fb82af 100644 --- a/AndEngine/src/org/anddev/andengine/entity/util/AverageFPSCounter.java +++ b/AndEngine/src/org/anddev/andengine/entity/util/AverageFPSCounter.java @@ -11,57 +11,57 @@ * @since 19:52:31 - 09.03.2010 */ public abstract class AverageFPSCounter extends FPSCounter implements TimeConstants { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - private static final float AVERAGE_DURATION_DEFAULT = 5; + private static final float AVERAGE_DURATION_DEFAULT = 5; - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - protected final float mAverageDuration; + protected final float mAverageDuration; - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - public AverageFPSCounter() { - this(AVERAGE_DURATION_DEFAULT); - } + public AverageFPSCounter() { + this(AVERAGE_DURATION_DEFAULT); + } - public AverageFPSCounter(final float pAverageDuration) { - this.mAverageDuration = pAverageDuration; - } + public AverageFPSCounter(final float pAverageDuration) { + this.mAverageDuration = pAverageDuration; + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - protected abstract void onHandleAverageDurationElapsed(final float pFPS); + protected abstract void onHandleAverageDurationElapsed(final float pFPS); - @Override - public void onUpdate(final float pSecondsElapsed) { - super.onUpdate(pSecondsElapsed); + @Override + public void onUpdate(final float pSecondsElapsed) { + super.onUpdate(pSecondsElapsed); - if(this.mSecondsElapsed > this.mAverageDuration){ - this.onHandleAverageDurationElapsed(this.getFPS()); + if(this.mSecondsElapsed > this.mAverageDuration){ + this.onHandleAverageDurationElapsed(this.getFPS()); - this.mSecondsElapsed -= this.mAverageDuration; - this.mFrames = 0; - } - } + this.mSecondsElapsed -= this.mAverageDuration; + this.mFrames = 0; + } + } - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/entity/util/FPSCounter.java b/AndEngine/src/org/anddev/andengine/entity/util/FPSCounter.java index d9da69dd..5299681c 100644 --- a/AndEngine/src/org/anddev/andengine/entity/util/FPSCounter.java +++ b/AndEngine/src/org/anddev/andengine/entity/util/FPSCounter.java @@ -10,51 +10,51 @@ * @since 19:52:31 - 09.03.2010 */ public class FPSCounter implements IUpdateHandler { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - protected float mSecondsElapsed; + protected float mSecondsElapsed; - protected int mFrames; + protected int mFrames; - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - public float getFPS() { - return this.mFrames / this.mSecondsElapsed; - } + public float getFPS() { + return this.mFrames / this.mSecondsElapsed; + } - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - @Override - public void onUpdate(final float pSecondsElapsed) { - this.mFrames++; - this.mSecondsElapsed += pSecondsElapsed; - } + @Override + public void onUpdate(final float pSecondsElapsed) { + this.mFrames++; + this.mSecondsElapsed += pSecondsElapsed; + } - @Override - public void reset() { - this.mFrames = 0; - this.mSecondsElapsed = 0; - } + @Override + public void reset() { + this.mFrames = 0; + this.mSecondsElapsed = 0; + } - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/entity/util/FPSLogger.java b/AndEngine/src/org/anddev/andengine/entity/util/FPSLogger.java index 6cbc8a67..2e102f36 100644 --- a/AndEngine/src/org/anddev/andengine/entity/util/FPSLogger.java +++ b/AndEngine/src/org/anddev/andengine/entity/util/FPSLogger.java @@ -10,73 +10,73 @@ * @since 19:52:31 - 09.03.2010 */ public class FPSLogger extends AverageFPSCounter { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - protected float mShortestFrame = Float.MAX_VALUE; - protected float mLongestFrame = Float.MIN_VALUE; - - // =========================================================== - // Constructors - // =========================================================== - - public FPSLogger() { - super(); - } - - public FPSLogger(final float pAverageDuration) { - super(pAverageDuration); - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - protected void onHandleAverageDurationElapsed(final float pFPS) { - this.onLogFPS(); - - this.mLongestFrame = Float.MIN_VALUE; - this.mShortestFrame = Float.MAX_VALUE; - } - - @Override - public void onUpdate(final float pSecondsElapsed) { - super.onUpdate(pSecondsElapsed); - - this.mShortestFrame = Math.min(this.mShortestFrame, pSecondsElapsed); - this.mLongestFrame = Math.max(this.mLongestFrame, pSecondsElapsed); - } - - @Override - public void reset() { - super.reset(); - - this.mShortestFrame = Float.MAX_VALUE; - this.mLongestFrame = Float.MIN_VALUE; - } - - // =========================================================== - // Methods - // =========================================================== - - protected void onLogFPS() { - Debug.d(String.format("FPS: %.2f (MIN: %.0f ms | MAX: %.0f ms)", - this.mFrames / this.mSecondsElapsed, - this.mShortestFrame * MILLISECONDSPERSECOND, - this.mLongestFrame * MILLISECONDSPERSECOND)); - } - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + protected float mShortestFrame = Float.MAX_VALUE; + protected float mLongestFrame = Float.MIN_VALUE; + + // =========================================================== + // Constructors + // =========================================================== + + public FPSLogger() { + super(); + } + + public FPSLogger(final float pAverageDuration) { + super(pAverageDuration); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + protected void onHandleAverageDurationElapsed(final float pFPS) { + this.onLogFPS(); + + this.mLongestFrame = Float.MIN_VALUE; + this.mShortestFrame = Float.MAX_VALUE; + } + + @Override + public void onUpdate(final float pSecondsElapsed) { + super.onUpdate(pSecondsElapsed); + + this.mShortestFrame = Math.min(this.mShortestFrame, pSecondsElapsed); + this.mLongestFrame = Math.max(this.mLongestFrame, pSecondsElapsed); + } + + @Override + public void reset() { + super.reset(); + + this.mShortestFrame = Float.MAX_VALUE; + this.mLongestFrame = Float.MIN_VALUE; + } + + // =========================================================== + // Methods + // =========================================================== + + protected void onLogFPS() { + Debug.d(String.format("FPS: %.2f (MIN: %.0f ms | MAX: %.0f ms)", + this.mFrames / this.mSecondsElapsed, + this.mShortestFrame * MILLISECONDSPERSECOND, + this.mLongestFrame * MILLISECONDSPERSECOND)); + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/entity/util/FrameCountCrasher.java b/AndEngine/src/org/anddev/andengine/entity/util/FrameCountCrasher.java index 793376d2..af9c8cdf 100644 --- a/AndEngine/src/org/anddev/andengine/entity/util/FrameCountCrasher.java +++ b/AndEngine/src/org/anddev/andengine/entity/util/FrameCountCrasher.java @@ -12,61 +12,61 @@ * @since 19:52:31 - 09.03.2010 */ public class FrameCountCrasher implements IUpdateHandler, TimeConstants { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - private int mFramesLeft; + private int mFramesLeft; - private final float[] mFrameLengths; + private final float[] mFrameLengths; - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - public FrameCountCrasher(final int pFrameCount) { - this.mFramesLeft = pFrameCount; - this.mFrameLengths = new float[pFrameCount]; - } + public FrameCountCrasher(final int pFrameCount) { + this.mFramesLeft = pFrameCount; + this.mFrameLengths = new float[pFrameCount]; + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - @Override - public void onUpdate(final float pSecondsElapsed) { - this.mFramesLeft--; + @Override + public void onUpdate(final float pSecondsElapsed) { + this.mFramesLeft--; - final float[] frameLengths = this.mFrameLengths; - if(this.mFramesLeft >= 0) { - frameLengths[this.mFramesLeft] = pSecondsElapsed; - } else { - for(int i = frameLengths.length - 1; i >= 0; i--) { - Debug.d("Elapsed: " + frameLengths[i]); - } + final float[] frameLengths = this.mFrameLengths; + if(this.mFramesLeft >= 0) { + frameLengths[this.mFramesLeft] = pSecondsElapsed; + } else { + for(int i = frameLengths.length - 1; i >= 0; i--) { + Debug.d("Elapsed: " + frameLengths[i]); + } - throw new RuntimeException(); - } - } + throw new RuntimeException(); + } + } - @Override - public void reset() { + @Override + public void reset() { - } + } - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/entity/util/FrameCounter.java b/AndEngine/src/org/anddev/andengine/entity/util/FrameCounter.java index 08e2ef32..0c16ab7f 100644 --- a/AndEngine/src/org/anddev/andengine/entity/util/FrameCounter.java +++ b/AndEngine/src/org/anddev/andengine/entity/util/FrameCounter.java @@ -10,47 +10,47 @@ * @since 11:00:55 - 22.06.2010 */ public class FrameCounter implements IUpdateHandler { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - private int mFrames; + private int mFrames; - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - public int getFrames() { - return this.mFrames; - } + public int getFrames() { + return this.mFrames; + } - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - @Override - public void onUpdate(final float pSecondsElapsed) { - this.mFrames++; - } + @Override + public void onUpdate(final float pSecondsElapsed) { + this.mFrames++; + } - @Override - public void reset() { - this.mFrames = 0; - } + @Override + public void reset() { + this.mFrames = 0; + } - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/entity/util/ScreenCapture.java b/AndEngine/src/org/anddev/andengine/entity/util/ScreenCapture.java index 756c6d36..91032527 100644 --- a/AndEngine/src/org/anddev/andengine/entity/util/ScreenCapture.java +++ b/AndEngine/src/org/anddev/andengine/entity/util/ScreenCapture.java @@ -22,103 +22,103 @@ * @since 15:11:50 - 15.03.2010 */ public class ScreenCapture extends Entity implements IScreenGrabberCallback { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - private String mFilePath; - - private final ScreenGrabber mScreenGrabber = new ScreenGrabber(); - - private IScreenCaptureCallback mScreenCaptureCallback; - - // =========================================================== - // Constructors - // =========================================================== - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - protected void onManagedDraw(final GL10 pGL, final Camera pCamera) { - this.mScreenGrabber.onManagedDraw(pGL, pCamera); - } - - @Override - protected void onManagedUpdate(final float pSecondsElapsed) { - /* Nothing */ - } - - @Override - public void reset() { - /* Nothing */ - } - - @Override - public void onScreenGrabbed(final Bitmap pBitmap) { - try { - ScreenCapture.saveCapture(pBitmap, this.mFilePath); - this.mScreenCaptureCallback.onScreenCaptured(this.mFilePath); - } catch (final FileNotFoundException e) { - this.mScreenCaptureCallback.onScreenCaptureFailed(this.mFilePath, e); - } - } - - @Override - public void onScreenGrabFailed(final Exception pException) { - this.mScreenCaptureCallback.onScreenCaptureFailed(this.mFilePath, pException); - } - - // =========================================================== - // Methods - // =========================================================== - - public void capture(final int pCaptureWidth, final int pCaptureHeight, final String pFilePath, final IScreenCaptureCallback pScreenCaptureCallback) { - this.capture(0, 0, pCaptureWidth, pCaptureHeight, pFilePath, pScreenCaptureCallback); - } - - public void capture(final int pCaptureX, final int pCaptureY, final int pCaptureWidth, final int pCaptureHeight, final String pFilePath, final IScreenCaptureCallback pScreencaptureCallback) { - this.mFilePath = pFilePath; - this.mScreenCaptureCallback = pScreencaptureCallback; - this.mScreenGrabber.grab(pCaptureX, pCaptureY, pCaptureWidth, pCaptureHeight, this); - } - - private static void saveCapture(final Bitmap pBitmap, final String pFilePath) throws FileNotFoundException { - FileOutputStream fos = null; - try { - fos = new FileOutputStream(pFilePath); - pBitmap.compress(CompressFormat.PNG, 100, fos); - - } catch (final FileNotFoundException e) { - StreamUtils.flushCloseStream(fos); - Debug.e("Error saving file to: " + pFilePath, e); - throw e; - } - } - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== - - public static interface IScreenCaptureCallback { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Methods - // =========================================================== - - public void onScreenCaptured(final String pFilePath); - public void onScreenCaptureFailed(final String pFilePath, final Exception pException); - } + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + private String mFilePath; + + private final ScreenGrabber mScreenGrabber = new ScreenGrabber(); + + private IScreenCaptureCallback mScreenCaptureCallback; + + // =========================================================== + // Constructors + // =========================================================== + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + protected void onManagedDraw(final GL10 pGL, final Camera pCamera) { + this.mScreenGrabber.onManagedDraw(pGL, pCamera); + } + + @Override + protected void onManagedUpdate(final float pSecondsElapsed) { + /* Nothing */ + } + + @Override + public void reset() { + /* Nothing */ + } + + @Override + public void onScreenGrabbed(final Bitmap pBitmap) { + try { + ScreenCapture.saveCapture(pBitmap, this.mFilePath); + this.mScreenCaptureCallback.onScreenCaptured(this.mFilePath); + } catch (final FileNotFoundException e) { + this.mScreenCaptureCallback.onScreenCaptureFailed(this.mFilePath, e); + } + } + + @Override + public void onScreenGrabFailed(final Exception pException) { + this.mScreenCaptureCallback.onScreenCaptureFailed(this.mFilePath, pException); + } + + // =========================================================== + // Methods + // =========================================================== + + public void capture(final int pCaptureWidth, final int pCaptureHeight, final String pFilePath, final IScreenCaptureCallback pScreenCaptureCallback) { + this.capture(0, 0, pCaptureWidth, pCaptureHeight, pFilePath, pScreenCaptureCallback); + } + + public void capture(final int pCaptureX, final int pCaptureY, final int pCaptureWidth, final int pCaptureHeight, final String pFilePath, final IScreenCaptureCallback pScreencaptureCallback) { + this.mFilePath = pFilePath; + this.mScreenCaptureCallback = pScreencaptureCallback; + this.mScreenGrabber.grab(pCaptureX, pCaptureY, pCaptureWidth, pCaptureHeight, this); + } + + private static void saveCapture(final Bitmap pBitmap, final String pFilePath) throws FileNotFoundException { + FileOutputStream fos = null; + try { + fos = new FileOutputStream(pFilePath); + pBitmap.compress(CompressFormat.PNG, 100, fos); + + } catch (final FileNotFoundException e) { + StreamUtils.flushCloseStream(fos); + Debug.e("Error saving file to: " + pFilePath, e); + throw e; + } + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== + + public static interface IScreenCaptureCallback { + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + public void onScreenCaptured(final String pFilePath); + public void onScreenCaptureFailed(final String pFilePath, final Exception pException); + } } diff --git a/AndEngine/src/org/anddev/andengine/entity/util/ScreenGrabber.java b/AndEngine/src/org/anddev/andengine/entity/util/ScreenGrabber.java index 3931f882..8c6ca799 100644 --- a/AndEngine/src/org/anddev/andengine/entity/util/ScreenGrabber.java +++ b/AndEngine/src/org/anddev/andengine/entity/util/ScreenGrabber.java @@ -18,118 +18,118 @@ * @since 15:27:22 - 10.01.2011 */ public class ScreenGrabber extends Entity { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - private int mGrabX; - private int mGrabY; - private int mGrabWidth; - private int mGrabHeight; - - private boolean mScreenGrabPending = false; - private IScreenGrabberCallback mScreenGrabCallback; - - // =========================================================== - // Constructors - // =========================================================== - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - protected void onManagedDraw(final GL10 pGL, final Camera pCamera) { - if(this.mScreenGrabPending) { - try { - final Bitmap screenGrab = ScreenGrabber.grab(this.mGrabX, this.mGrabY, this.mGrabWidth, this.mGrabHeight, pGL); - - this.mScreenGrabCallback.onScreenGrabbed(screenGrab); - } catch (final Exception e) { - this.mScreenGrabCallback.onScreenGrabFailed(e); - } - - this.mScreenGrabPending = false; - } - } - - @Override - protected void onManagedUpdate(final float pSecondsElapsed) { - /* Nothing */ - } - - @Override - public void reset() { - /* Nothing */ - } - - // =========================================================== - // Methods - // =========================================================== - - public void grab(final int pGrabWidth, final int pGrabHeight, final IScreenGrabberCallback pScreenGrabCallback) { - this.grab(0, 0, pGrabWidth, pGrabHeight, pScreenGrabCallback); - } - - public void grab(final int pGrabX, final int pGrabY, final int pGrabWidth, final int pGrabHeight, final IScreenGrabberCallback pScreenGrabCallback) { - this.mGrabX = pGrabX; - this.mGrabY = pGrabY; - this.mGrabWidth = pGrabWidth; - this.mGrabHeight = pGrabHeight; - this.mScreenGrabCallback = pScreenGrabCallback; - - this.mScreenGrabPending = true; - } - - private static Bitmap grab(final int pGrabX, final int pGrabY, final int pGrabWidth, final int pGrabHeight, final GL10 pGL) { - final int[] source = new int[pGrabWidth * (pGrabY + pGrabHeight)]; - final IntBuffer sourceBuffer = IntBuffer.wrap(source); - sourceBuffer.position(0); - - // TODO Check availability of OpenGL and GL10.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'. - pGL.glReadPixels(pGrabX, 0, pGrabWidth, pGrabY + pGrabHeight, GL10.GL_RGBA, GL10.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; - } - } - - return Bitmap.createBitmap(pixels, pGrabWidth, pGrabHeight, Config.ARGB_8888); - } - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== - - public static interface IScreenGrabberCallback { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Methods - // =========================================================== - - public void onScreenGrabbed(final Bitmap pBitmap); - public void onScreenGrabFailed(final Exception pException); - } + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + private int mGrabX; + private int mGrabY; + private int mGrabWidth; + private int mGrabHeight; + + private boolean mScreenGrabPending = false; + private IScreenGrabberCallback mScreenGrabCallback; + + // =========================================================== + // Constructors + // =========================================================== + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + protected void onManagedDraw(final GL10 pGL, final Camera pCamera) { + if(this.mScreenGrabPending) { + try { + final Bitmap screenGrab = ScreenGrabber.grab(this.mGrabX, this.mGrabY, this.mGrabWidth, this.mGrabHeight, pGL); + + this.mScreenGrabCallback.onScreenGrabbed(screenGrab); + } catch (final Exception e) { + this.mScreenGrabCallback.onScreenGrabFailed(e); + } + + this.mScreenGrabPending = false; + } + } + + @Override + protected void onManagedUpdate(final float pSecondsElapsed) { + /* Nothing */ + } + + @Override + public void reset() { + /* Nothing */ + } + + // =========================================================== + // Methods + // =========================================================== + + public void grab(final int pGrabWidth, final int pGrabHeight, final IScreenGrabberCallback pScreenGrabCallback) { + this.grab(0, 0, pGrabWidth, pGrabHeight, pScreenGrabCallback); + } + + public void grab(final int pGrabX, final int pGrabY, final int pGrabWidth, final int pGrabHeight, final IScreenGrabberCallback pScreenGrabCallback) { + this.mGrabX = pGrabX; + this.mGrabY = pGrabY; + this.mGrabWidth = pGrabWidth; + this.mGrabHeight = pGrabHeight; + this.mScreenGrabCallback = pScreenGrabCallback; + + this.mScreenGrabPending = true; + } + + private static Bitmap grab(final int pGrabX, final int pGrabY, final int pGrabWidth, final int pGrabHeight, final GL10 pGL) { + final int[] source = new int[pGrabWidth * (pGrabY + pGrabHeight)]; + final IntBuffer sourceBuffer = IntBuffer.wrap(source); + sourceBuffer.position(0); + + // TODO Check availability of OpenGL and GL10.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'. + pGL.glReadPixels(pGrabX, 0, pGrabWidth, pGrabY + pGrabHeight, GL10.GL_RGBA, GL10.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; + } + } + + return Bitmap.createBitmap(pixels, pGrabWidth, pGrabHeight, Config.ARGB_8888); + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== + + public static interface IScreenGrabberCallback { + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + public void onScreenGrabbed(final Bitmap pBitmap); + public void onScreenGrabFailed(final Exception pException); + } } diff --git a/AndEngine/src/org/anddev/andengine/extension/input/touch/controller/MultiTouch.java b/AndEngine/src/org/anddev/andengine/extension/input/touch/controller/MultiTouch.java index 6cee76b5..3d8539e8 100644 --- a/AndEngine/src/org/anddev/andengine/extension/input/touch/controller/MultiTouch.java +++ b/AndEngine/src/org/anddev/andengine/extension/input/touch/controller/MultiTouch.java @@ -14,54 +14,54 @@ * @since 16:00:38 - 14.07.2010 */ public class MultiTouch { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - private static Boolean SUPPORTED = null; - private static Boolean SUPPORTED_DISTINCT = null; + private static Boolean SUPPORTED = null; + private static Boolean SUPPORTED_DISTINCT = null; - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - public static boolean isSupportedByAndroidVersion() { - return SystemUtils.isAndroidVersionOrHigher(Build.VERSION_CODES.ECLAIR); - } + public static boolean isSupportedByAndroidVersion() { + return SystemUtils.isAndroidVersionOrHigher(Build.VERSION_CODES.ECLAIR); + } - public static boolean isSupported(final Context pContext) { - if(SUPPORTED == null) { - SUPPORTED = SystemUtils.isAndroidVersionOrHigher(Build.VERSION_CODES.ECLAIR) && SystemUtils.hasSystemFeature(pContext, PackageManager.FEATURE_TOUCHSCREEN_MULTITOUCH); - } + public static boolean isSupported(final Context pContext) { + if(SUPPORTED == null) { + SUPPORTED = SystemUtils.isAndroidVersionOrHigher(Build.VERSION_CODES.ECLAIR) && SystemUtils.hasSystemFeature(pContext, PackageManager.FEATURE_TOUCHSCREEN_MULTITOUCH); + } - return SUPPORTED; - } + return SUPPORTED; + } - public static boolean isSupportedDistinct(final Context pContext) { - if(SUPPORTED_DISTINCT == null) { - SUPPORTED_DISTINCT = SystemUtils.isAndroidVersionOrHigher(Build.VERSION_CODES.ECLAIR_MR1) && SystemUtils.hasSystemFeature(pContext, PackageManager.FEATURE_TOUCHSCREEN_MULTITOUCH_DISTINCT); - } + public static boolean isSupportedDistinct(final Context pContext) { + if(SUPPORTED_DISTINCT == null) { + SUPPORTED_DISTINCT = SystemUtils.isAndroidVersionOrHigher(Build.VERSION_CODES.ECLAIR_MR1) && SystemUtils.hasSystemFeature(pContext, PackageManager.FEATURE_TOUCHSCREEN_MULTITOUCH_DISTINCT); + } - return SUPPORTED_DISTINCT; - } + return SUPPORTED_DISTINCT; + } - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/extension/input/touch/controller/MultiTouchController.java b/AndEngine/src/org/anddev/andengine/extension/input/touch/controller/MultiTouchController.java index c11206b7..2b40c81b 100644 --- a/AndEngine/src/org/anddev/andengine/extension/input/touch/controller/MultiTouchController.java +++ b/AndEngine/src/org/anddev/andengine/extension/input/touch/controller/MultiTouchController.java @@ -13,78 +13,78 @@ * @since 20:23:33 - 13.07.2010 */ public class MultiTouchController extends BaseTouchController { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - // =========================================================== - // Constructors - // =========================================================== - - public MultiTouchController() throws MultiTouchException { - if(MultiTouch.isSupportedByAndroidVersion() == false) { - throw new MultiTouchException(); - } - } + // =========================================================== + // Constructors + // =========================================================== + + public MultiTouchController() throws MultiTouchException { + if(MultiTouch.isSupportedByAndroidVersion() == false) { + throw new MultiTouchException(); + } + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - @Override - public boolean onHandleMotionEvent(final MotionEvent pMotionEvent) { - final int action = pMotionEvent.getAction() & MotionEvent.ACTION_MASK; - switch(action) { - case MotionEvent.ACTION_DOWN: - case MotionEvent.ACTION_POINTER_DOWN: - return this.onHandleTouchAction(MotionEvent.ACTION_DOWN, pMotionEvent); - case MotionEvent.ACTION_UP: - case MotionEvent.ACTION_POINTER_UP: - return this.onHandleTouchAction(MotionEvent.ACTION_UP, pMotionEvent); - case MotionEvent.ACTION_CANCEL: - case MotionEvent.ACTION_OUTSIDE: - return this.onHandleTouchAction(action, pMotionEvent); - case MotionEvent.ACTION_MOVE: - return this.onHandleTouchMove(pMotionEvent); - default: - throw new IllegalArgumentException("Invalid Action detected: " + action); - } - } + @Override + public boolean onHandleMotionEvent(final MotionEvent pMotionEvent) { + final int action = pMotionEvent.getAction() & MotionEvent.ACTION_MASK; + switch(action) { + case MotionEvent.ACTION_DOWN: + case MotionEvent.ACTION_POINTER_DOWN: + return this.onHandleTouchAction(MotionEvent.ACTION_DOWN, pMotionEvent); + case MotionEvent.ACTION_UP: + case MotionEvent.ACTION_POINTER_UP: + return this.onHandleTouchAction(MotionEvent.ACTION_UP, pMotionEvent); + case MotionEvent.ACTION_CANCEL: + case MotionEvent.ACTION_OUTSIDE: + return this.onHandleTouchAction(action, pMotionEvent); + case MotionEvent.ACTION_MOVE: + return this.onHandleTouchMove(pMotionEvent); + default: + throw new IllegalArgumentException("Invalid Action detected: " + action); + } + } - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - private boolean onHandleTouchMove(final MotionEvent pMotionEvent) { - boolean handled = false; - for(int i = pMotionEvent.getPointerCount() - 1; i >= 0; i--) { - final int pointerIndex = i; - final int pointerID = pMotionEvent.getPointerId(pointerIndex); - final boolean handledInner = this.fireTouchEvent(pMotionEvent.getX(pointerIndex), pMotionEvent.getY(pointerIndex), MotionEvent.ACTION_MOVE, pointerID, pMotionEvent); - handled = handled || handledInner; - } - return handled; - } - - private boolean onHandleTouchAction(final int pAction, final MotionEvent pMotionEvent) { - final int pointerIndex = this.getPointerIndex(pMotionEvent); - final int pointerID = pMotionEvent.getPointerId(pointerIndex); - return this.fireTouchEvent(pMotionEvent.getX(pointerIndex), pMotionEvent.getY(pointerIndex), pAction, pointerID, pMotionEvent); - } + private boolean onHandleTouchMove(final MotionEvent pMotionEvent) { + boolean handled = false; + for(int i = pMotionEvent.getPointerCount() - 1; i >= 0; i--) { + final int pointerIndex = i; + final int pointerID = pMotionEvent.getPointerId(pointerIndex); + final boolean handledInner = this.fireTouchEvent(pMotionEvent.getX(pointerIndex), pMotionEvent.getY(pointerIndex), MotionEvent.ACTION_MOVE, pointerID, pMotionEvent); + handled = handled || handledInner; + } + return handled; + } + + private boolean onHandleTouchAction(final int pAction, final MotionEvent pMotionEvent) { + final int pointerIndex = this.getPointerIndex(pMotionEvent); + final int pointerID = pMotionEvent.getPointerId(pointerIndex); + return this.fireTouchEvent(pMotionEvent.getX(pointerIndex), pMotionEvent.getY(pointerIndex), pAction, pointerID, pMotionEvent); + } - private int getPointerIndex(final MotionEvent pMotionEvent) { - return (pMotionEvent.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) >> MotionEvent.ACTION_POINTER_INDEX_SHIFT; - } + private int getPointerIndex(final MotionEvent pMotionEvent) { + return (pMotionEvent.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) >> MotionEvent.ACTION_POINTER_INDEX_SHIFT; + } - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/extension/input/touch/detector/PinchZoomDetector.java b/AndEngine/src/org/anddev/andengine/extension/input/touch/detector/PinchZoomDetector.java index b1e89c2c..3704d510 100644 --- a/AndEngine/src/org/anddev/andengine/extension/input/touch/detector/PinchZoomDetector.java +++ b/AndEngine/src/org/anddev/andengine/extension/input/touch/detector/PinchZoomDetector.java @@ -16,113 +16,113 @@ * @since 19:16:19 - 04.11.2010 */ public class PinchZoomDetector extends BaseDetector { - // =========================================================== - // Constants - // =========================================================== - - private static final float TRIGGER_PINCHZOOM_MINIMUM_DISTANCE_DEFAULT = 10; - - // =========================================================== - // Fields - // =========================================================== - - private final IPinchZoomDetectorListener mPinchZoomDetectorListener; - - private float mInitialDistance; - private float mCurrentDistance; - - private boolean mPinchZooming; - - // =========================================================== - // Constructors - // =========================================================== - - public PinchZoomDetector(final IPinchZoomDetectorListener pPinchZoomDetectorListener) throws MultiTouchException { - if(MultiTouch.isSupportedByAndroidVersion() == false) { - throw new MultiTouchException(); - } - this.mPinchZoomDetectorListener = pPinchZoomDetectorListener; - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - public boolean isZooming() { - return this.mPinchZooming; - } - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - public boolean onManagedTouchEvent(final TouchEvent pSceneTouchEvent) { - final MotionEvent motionEvent = pSceneTouchEvent.getMotionEvent(); - - final int action = motionEvent.getAction() & MotionEvent.ACTION_MASK; - - switch(action) { - case MotionEvent.ACTION_POINTER_DOWN: - if(!this.mPinchZooming) { - this.mInitialDistance = PinchZoomDetector.calculatePointerDistance(motionEvent); - if(this.mInitialDistance > TRIGGER_PINCHZOOM_MINIMUM_DISTANCE_DEFAULT) { - this.mPinchZooming = true; - this.mPinchZoomDetectorListener.onPinchZoomStarted(this, pSceneTouchEvent); - } - } - break; - case MotionEvent.ACTION_UP: - case MotionEvent.ACTION_POINTER_UP: - if(this.mPinchZooming) { - this.mPinchZooming = false; - this.mPinchZoomDetectorListener.onPinchZoomFinished(this, pSceneTouchEvent, this.getZoomFactor()); - } - break; - case MotionEvent.ACTION_MOVE: - if(this.mPinchZooming) { - this.mCurrentDistance = PinchZoomDetector.calculatePointerDistance(motionEvent); - if(this.mCurrentDistance > TRIGGER_PINCHZOOM_MINIMUM_DISTANCE_DEFAULT) { - this.mPinchZoomDetectorListener.onPinchZoom(this, pSceneTouchEvent, this.getZoomFactor()); - } - } - break; - } - return true; - } - - private float getZoomFactor() { - return this.mCurrentDistance / this.mInitialDistance; - } - - // =========================================================== - // Methods - // =========================================================== - - /** - * Calculate the euclidian distance between the first two fingers. - */ - private static float calculatePointerDistance(final MotionEvent pMotionEvent) { - final float x = pMotionEvent.getX(0) - pMotionEvent.getX(1); - final float y = pMotionEvent.getY(0) - pMotionEvent.getY(1); - return (float) Math.sqrt(x * x + y * y); - } - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== - - public static interface IPinchZoomDetectorListener { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Methods - // =========================================================== - - public void onPinchZoomStarted(final PinchZoomDetector pPinchZoomDetector, final TouchEvent pSceneTouchEvent); - public void onPinchZoom(final PinchZoomDetector pPinchZoomDetector, final TouchEvent pTouchEvent, final float pZoomFactor); - public void onPinchZoomFinished(final PinchZoomDetector pPinchZoomDetector, final TouchEvent pTouchEvent, final float pZoomFactor); - } + // =========================================================== + // Constants + // =========================================================== + + private static final float TRIGGER_PINCHZOOM_MINIMUM_DISTANCE_DEFAULT = 10; + + // =========================================================== + // Fields + // =========================================================== + + private final IPinchZoomDetectorListener mPinchZoomDetectorListener; + + private float mInitialDistance; + private float mCurrentDistance; + + private boolean mPinchZooming; + + // =========================================================== + // Constructors + // =========================================================== + + public PinchZoomDetector(final IPinchZoomDetectorListener pPinchZoomDetectorListener) throws MultiTouchException { + if(MultiTouch.isSupportedByAndroidVersion() == false) { + throw new MultiTouchException(); + } + this.mPinchZoomDetectorListener = pPinchZoomDetectorListener; + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + public boolean isZooming() { + return this.mPinchZooming; + } + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + public boolean onManagedTouchEvent(final TouchEvent pSceneTouchEvent) { + final MotionEvent motionEvent = pSceneTouchEvent.getMotionEvent(); + + final int action = motionEvent.getAction() & MotionEvent.ACTION_MASK; + + switch(action) { + case MotionEvent.ACTION_POINTER_DOWN: + if(!this.mPinchZooming) { + this.mInitialDistance = PinchZoomDetector.calculatePointerDistance(motionEvent); + if(this.mInitialDistance > TRIGGER_PINCHZOOM_MINIMUM_DISTANCE_DEFAULT) { + this.mPinchZooming = true; + this.mPinchZoomDetectorListener.onPinchZoomStarted(this, pSceneTouchEvent); + } + } + break; + case MotionEvent.ACTION_UP: + case MotionEvent.ACTION_POINTER_UP: + if(this.mPinchZooming) { + this.mPinchZooming = false; + this.mPinchZoomDetectorListener.onPinchZoomFinished(this, pSceneTouchEvent, this.getZoomFactor()); + } + break; + case MotionEvent.ACTION_MOVE: + if(this.mPinchZooming) { + this.mCurrentDistance = PinchZoomDetector.calculatePointerDistance(motionEvent); + if(this.mCurrentDistance > TRIGGER_PINCHZOOM_MINIMUM_DISTANCE_DEFAULT) { + this.mPinchZoomDetectorListener.onPinchZoom(this, pSceneTouchEvent, this.getZoomFactor()); + } + } + break; + } + return true; + } + + private float getZoomFactor() { + return this.mCurrentDistance / this.mInitialDistance; + } + + // =========================================================== + // Methods + // =========================================================== + + /** + * Calculate the euclidian distance between the first two fingers. + */ + private static float calculatePointerDistance(final MotionEvent pMotionEvent) { + final float x = pMotionEvent.getX(0) - pMotionEvent.getX(1); + final float y = pMotionEvent.getY(0) - pMotionEvent.getY(1); + return (float) Math.sqrt(x * x + y * y); + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== + + public static interface IPinchZoomDetectorListener { + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + public void onPinchZoomStarted(final PinchZoomDetector pPinchZoomDetector, final TouchEvent pSceneTouchEvent); + public void onPinchZoom(final PinchZoomDetector pPinchZoomDetector, final TouchEvent pTouchEvent, final float pZoomFactor); + public void onPinchZoomFinished(final PinchZoomDetector pPinchZoomDetector, final TouchEvent pTouchEvent, final float pZoomFactor); + } } diff --git a/AndEngine/src/org/anddev/andengine/extension/input/touch/exception/MultiTouchException.java b/AndEngine/src/org/anddev/andengine/extension/input/touch/exception/MultiTouchException.java index 779927b8..757d7532 100644 --- a/AndEngine/src/org/anddev/andengine/extension/input/touch/exception/MultiTouchException.java +++ b/AndEngine/src/org/anddev/andengine/extension/input/touch/exception/MultiTouchException.java @@ -8,37 +8,37 @@ * @since 16:26:07 - 14.07.2010 */ public class MultiTouchException extends Exception { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - private static final long serialVersionUID = -5231480372313280777L; + private static final long serialVersionUID = -5231480372313280777L; - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - public MultiTouchException() { + public MultiTouchException() { - } + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/input/touch/TouchEvent.java b/AndEngine/src/org/anddev/andengine/input/touch/TouchEvent.java index 5dc41f33..dd34618c 100644 --- a/AndEngine/src/org/anddev/andengine/input/touch/TouchEvent.java +++ b/AndEngine/src/org/anddev/andengine/input/touch/TouchEvent.java @@ -12,136 +12,136 @@ * @since 10:17:42 - 13.07.2010 */ public class TouchEvent { - // =========================================================== - // Constants - // =========================================================== - - public static final int ACTION_CANCEL = MotionEvent.ACTION_CANCEL; - public static final int ACTION_DOWN = MotionEvent.ACTION_DOWN; - public static final int ACTION_MOVE = MotionEvent.ACTION_MOVE; - public static final int ACTION_OUTSIDE = MotionEvent.ACTION_OUTSIDE; - public static final int ACTION_UP = MotionEvent.ACTION_UP; - - private static final TouchEventPool TOUCHEVENT_POOL = new TouchEventPool(); - - // =========================================================== - // Fields - // =========================================================== - - protected int mPointerID; - - protected float mX; - protected float mY; - - protected int mAction; - - protected MotionEvent mMotionEvent; - - // =========================================================== - // Constructors - // =========================================================== - - public static TouchEvent obtain(final float pX, final float pY, final int pAction, final int pPointerID, final MotionEvent pMotionEvent) { - final TouchEvent touchEvent = TOUCHEVENT_POOL.obtainPoolItem(); - touchEvent.set(pX, pY, pAction, pPointerID, pMotionEvent); - return touchEvent; - } - - private void set(final float pX, final float pY, final int pAction, final int pPointerID, final MotionEvent pMotionEvent) { - this.mX = pX; - this.mY = pY; - this.mAction = pAction; - this.mPointerID = pPointerID; - this.mMotionEvent = pMotionEvent; - } - - public void recycle() { - TOUCHEVENT_POOL.recyclePoolItem(this); - } - - public static void recycle(final TouchEvent pTouchEvent) { - TOUCHEVENT_POOL.recyclePoolItem(pTouchEvent); - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - public float getX() { - return this.mX; - } - - public float getY() { - return this.mY; - } - - public void set(final float pX, final float pY) { - this.mX = pX; - this.mY = pY; - } - - public void offset(final float pDeltaX, final float pDeltaY) { - this.mX += pDeltaX; - this.mY += pDeltaY; - } - - public int getPointerID() { - return this.mPointerID; - } - - public int getAction() { - return this.mAction; - } - - public boolean isActionDown() { - return this.mAction == TouchEvent.ACTION_DOWN; - } - - public boolean isActionUp() { - return this.mAction == TouchEvent.ACTION_UP; - } - - public boolean isActionMove() { - return this.mAction == TouchEvent.ACTION_MOVE; - } - - public boolean isActionCancel() { - return this.mAction == TouchEvent.ACTION_CANCEL; - } - - public boolean isActionOutside() { - return this.mAction == TouchEvent.ACTION_OUTSIDE; - } - - /** - * Provides the raw {@link MotionEvent} that originally caused this {@link TouchEvent}. - * The coordinates of this {@link MotionEvent} are in surface-coordinates! - * @return - */ - public MotionEvent getMotionEvent() { - return this.mMotionEvent; - } - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== - - private static final class TouchEventPool extends GenericPool { - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - protected TouchEvent onAllocatePoolItem() { - return new TouchEvent(); - } - } + // =========================================================== + // Constants + // =========================================================== + + public static final int ACTION_CANCEL = MotionEvent.ACTION_CANCEL; + public static final int ACTION_DOWN = MotionEvent.ACTION_DOWN; + public static final int ACTION_MOVE = MotionEvent.ACTION_MOVE; + public static final int ACTION_OUTSIDE = MotionEvent.ACTION_OUTSIDE; + public static final int ACTION_UP = MotionEvent.ACTION_UP; + + private static final TouchEventPool TOUCHEVENT_POOL = new TouchEventPool(); + + // =========================================================== + // Fields + // =========================================================== + + protected int mPointerID; + + protected float mX; + protected float mY; + + protected int mAction; + + protected MotionEvent mMotionEvent; + + // =========================================================== + // Constructors + // =========================================================== + + public static TouchEvent obtain(final float pX, final float pY, final int pAction, final int pPointerID, final MotionEvent pMotionEvent) { + final TouchEvent touchEvent = TOUCHEVENT_POOL.obtainPoolItem(); + touchEvent.set(pX, pY, pAction, pPointerID, pMotionEvent); + return touchEvent; + } + + private void set(final float pX, final float pY, final int pAction, final int pPointerID, final MotionEvent pMotionEvent) { + this.mX = pX; + this.mY = pY; + this.mAction = pAction; + this.mPointerID = pPointerID; + this.mMotionEvent = pMotionEvent; + } + + public void recycle() { + TOUCHEVENT_POOL.recyclePoolItem(this); + } + + public static void recycle(final TouchEvent pTouchEvent) { + TOUCHEVENT_POOL.recyclePoolItem(pTouchEvent); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + public float getX() { + return this.mX; + } + + public float getY() { + return this.mY; + } + + public void set(final float pX, final float pY) { + this.mX = pX; + this.mY = pY; + } + + public void offset(final float pDeltaX, final float pDeltaY) { + this.mX += pDeltaX; + this.mY += pDeltaY; + } + + public int getPointerID() { + return this.mPointerID; + } + + public int getAction() { + return this.mAction; + } + + public boolean isActionDown() { + return this.mAction == TouchEvent.ACTION_DOWN; + } + + public boolean isActionUp() { + return this.mAction == TouchEvent.ACTION_UP; + } + + public boolean isActionMove() { + return this.mAction == TouchEvent.ACTION_MOVE; + } + + public boolean isActionCancel() { + return this.mAction == TouchEvent.ACTION_CANCEL; + } + + public boolean isActionOutside() { + return this.mAction == TouchEvent.ACTION_OUTSIDE; + } + + /** + * Provides the raw {@link MotionEvent} that originally caused this {@link TouchEvent}. + * The coordinates of this {@link MotionEvent} are in surface-coordinates! + * @return + */ + public MotionEvent getMotionEvent() { + return this.mMotionEvent; + } + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== + + private static final class TouchEventPool extends GenericPool { + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + protected TouchEvent onAllocatePoolItem() { + return new TouchEvent(); + } + } } diff --git a/AndEngine/src/org/anddev/andengine/input/touch/controller/BaseTouchController.java b/AndEngine/src/org/anddev/andengine/input/touch/controller/BaseTouchController.java index 185afd28..2143dcc0 100644 --- a/AndEngine/src/org/anddev/andengine/input/touch/controller/BaseTouchController.java +++ b/AndEngine/src/org/anddev/andengine/input/touch/controller/BaseTouchController.java @@ -15,123 +15,123 @@ * @since 21:06:40 - 13.07.2010 */ public abstract class BaseTouchController implements ITouchController { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - private ITouchEventCallback mTouchEventCallback; - - private boolean mRunOnUpdateThread; - - private final RunnablePoolUpdateHandler mTouchEventRunnablePoolUpdateHandler = new RunnablePoolUpdateHandler() { - @Override - protected TouchEventRunnablePoolItem onAllocatePoolItem() { - return new TouchEventRunnablePoolItem(); - } - }; - - // =========================================================== - // Constructors - // =========================================================== - - public BaseTouchController() { - - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - @Override - public void setTouchEventCallback(final ITouchEventCallback pTouchEventCallback) { - this.mTouchEventCallback = pTouchEventCallback; - } - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - public void reset() { - if(this.mRunOnUpdateThread) { - this.mTouchEventRunnablePoolUpdateHandler.reset(); - } - } - - @Override - public void onUpdate(final float pSecondsElapsed) { - if(this.mRunOnUpdateThread) { - this.mTouchEventRunnablePoolUpdateHandler.onUpdate(pSecondsElapsed); - } - } - - protected boolean fireTouchEvent(final float pX, final float pY, final int pAction, final int pPointerID, final MotionEvent pMotionEvent) { - final boolean handled; - - if(this.mRunOnUpdateThread) { - final TouchEvent touchEvent = TouchEvent.obtain(pX, pY, pAction, pPointerID, MotionEvent.obtain(pMotionEvent)); - - final TouchEventRunnablePoolItem touchEventRunnablePoolItem = this.mTouchEventRunnablePoolUpdateHandler.obtainPoolItem(); - touchEventRunnablePoolItem.set(touchEvent); - this.mTouchEventRunnablePoolUpdateHandler.postPoolItem(touchEventRunnablePoolItem); - - handled = true; - } else { - final TouchEvent touchEvent = TouchEvent.obtain(pX, pY, pAction, pPointerID, pMotionEvent); - handled = this.mTouchEventCallback.onTouchEvent(touchEvent); - touchEvent.recycle(); - } - - return handled; - } - - // =========================================================== - // Methods - // =========================================================== - - @Override - public void applyTouchOptions(final TouchOptions pTouchOptions) { - this.mRunOnUpdateThread = pTouchOptions.isRunOnUpdateThread(); - } - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== - - class TouchEventRunnablePoolItem extends RunnablePoolItem { - // =========================================================== - // Fields - // =========================================================== - - private TouchEvent mTouchEvent; - - // =========================================================== - // Getter & Setter - // =========================================================== - - public void set(final TouchEvent pTouchEvent) { - this.mTouchEvent = pTouchEvent; - } - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - public void run() { - BaseTouchController.this.mTouchEventCallback.onTouchEvent(this.mTouchEvent); - } - - @Override - protected void onRecycle() { - super.onRecycle(); - final TouchEvent touchEvent = this.mTouchEvent; - touchEvent.getMotionEvent().recycle(); - touchEvent.recycle(); - } - } + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + private ITouchEventCallback mTouchEventCallback; + + private boolean mRunOnUpdateThread; + + private final RunnablePoolUpdateHandler mTouchEventRunnablePoolUpdateHandler = new RunnablePoolUpdateHandler() { + @Override + protected TouchEventRunnablePoolItem onAllocatePoolItem() { + return new TouchEventRunnablePoolItem(); + } + }; + + // =========================================================== + // Constructors + // =========================================================== + + public BaseTouchController() { + + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + @Override + public void setTouchEventCallback(final ITouchEventCallback pTouchEventCallback) { + this.mTouchEventCallback = pTouchEventCallback; + } + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + public void reset() { + if(this.mRunOnUpdateThread) { + this.mTouchEventRunnablePoolUpdateHandler.reset(); + } + } + + @Override + public void onUpdate(final float pSecondsElapsed) { + if(this.mRunOnUpdateThread) { + this.mTouchEventRunnablePoolUpdateHandler.onUpdate(pSecondsElapsed); + } + } + + protected boolean fireTouchEvent(final float pX, final float pY, final int pAction, final int pPointerID, final MotionEvent pMotionEvent) { + final boolean handled; + + if(this.mRunOnUpdateThread) { + final TouchEvent touchEvent = TouchEvent.obtain(pX, pY, pAction, pPointerID, MotionEvent.obtain(pMotionEvent)); + + final TouchEventRunnablePoolItem touchEventRunnablePoolItem = this.mTouchEventRunnablePoolUpdateHandler.obtainPoolItem(); + touchEventRunnablePoolItem.set(touchEvent); + this.mTouchEventRunnablePoolUpdateHandler.postPoolItem(touchEventRunnablePoolItem); + + handled = true; + } else { + final TouchEvent touchEvent = TouchEvent.obtain(pX, pY, pAction, pPointerID, pMotionEvent); + handled = this.mTouchEventCallback.onTouchEvent(touchEvent); + touchEvent.recycle(); + } + + return handled; + } + + // =========================================================== + // Methods + // =========================================================== + + @Override + public void applyTouchOptions(final TouchOptions pTouchOptions) { + this.mRunOnUpdateThread = pTouchOptions.isRunOnUpdateThread(); + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== + + class TouchEventRunnablePoolItem extends RunnablePoolItem { + // =========================================================== + // Fields + // =========================================================== + + private TouchEvent mTouchEvent; + + // =========================================================== + // Getter & Setter + // =========================================================== + + public void set(final TouchEvent pTouchEvent) { + this.mTouchEvent = pTouchEvent; + } + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + public void run() { + BaseTouchController.this.mTouchEventCallback.onTouchEvent(this.mTouchEvent); + } + + @Override + protected void onRecycle() { + super.onRecycle(); + final TouchEvent touchEvent = this.mTouchEvent; + touchEvent.getMotionEvent().recycle(); + touchEvent.recycle(); + } + } } diff --git a/AndEngine/src/org/anddev/andengine/input/touch/controller/ITouchController.java b/AndEngine/src/org/anddev/andengine/input/touch/controller/ITouchController.java index c48bdfce..68d18e53 100644 --- a/AndEngine/src/org/anddev/andengine/input/touch/controller/ITouchController.java +++ b/AndEngine/src/org/anddev/andengine/input/touch/controller/ITouchController.java @@ -14,25 +14,25 @@ * @since 20:23:45 - 13.07.2010 */ public interface ITouchController extends IUpdateHandler { - // =========================================================== - // Final Fields - // =========================================================== + // =========================================================== + // Final Fields + // =========================================================== - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - public void setTouchEventCallback(final ITouchEventCallback pTouchEventCallback); + public void setTouchEventCallback(final ITouchEventCallback pTouchEventCallback); - public void applyTouchOptions(final TouchOptions pTouchOptions); + public void applyTouchOptions(final TouchOptions pTouchOptions); - public boolean onHandleMotionEvent(final MotionEvent pMotionEvent); + public boolean onHandleMotionEvent(final MotionEvent pMotionEvent); - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== - static interface ITouchEventCallback { - public boolean onTouchEvent(final TouchEvent pTouchEvent); - } + static interface ITouchEventCallback { + public boolean onTouchEvent(final TouchEvent pTouchEvent); + } } diff --git a/AndEngine/src/org/anddev/andengine/input/touch/controller/SingleTouchControler.java b/AndEngine/src/org/anddev/andengine/input/touch/controller/SingleTouchControler.java index 73ef394f..9f9e2f07 100644 --- a/AndEngine/src/org/anddev/andengine/input/touch/controller/SingleTouchControler.java +++ b/AndEngine/src/org/anddev/andengine/input/touch/controller/SingleTouchControler.java @@ -10,40 +10,40 @@ * @since 20:23:33 - 13.07.2010 */ public class SingleTouchControler extends BaseTouchController { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - public SingleTouchControler() { + public SingleTouchControler() { - } + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - @Override - public boolean onHandleMotionEvent(final MotionEvent pMotionEvent) { - return this.fireTouchEvent(pMotionEvent.getX(), pMotionEvent.getY(), pMotionEvent.getAction(), 0, pMotionEvent); - } + @Override + public boolean onHandleMotionEvent(final MotionEvent pMotionEvent) { + return this.fireTouchEvent(pMotionEvent.getX(), pMotionEvent.getY(), pMotionEvent.getAction(), 0, pMotionEvent); + } - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/input/touch/detector/BaseDetector.java b/AndEngine/src/org/anddev/andengine/input/touch/detector/BaseDetector.java index 85897142..0f5e1715 100644 --- a/AndEngine/src/org/anddev/andengine/input/touch/detector/BaseDetector.java +++ b/AndEngine/src/org/anddev/andengine/input/touch/detector/BaseDetector.java @@ -12,56 +12,56 @@ * @since 15:59:00 - 05.11.2010 */ public abstract class BaseDetector implements IOnSceneTouchListener { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - private boolean mEnabled = true; + private boolean mEnabled = true; - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - public boolean isEnabled() { - return this.mEnabled; - } + public boolean isEnabled() { + return this.mEnabled; + } - public void setEnabled(final boolean pEnabled) { - this.mEnabled = pEnabled; - } + public void setEnabled(final boolean pEnabled) { + this.mEnabled = pEnabled; + } - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - protected abstract boolean onManagedTouchEvent(TouchEvent pSceneTouchEvent); + protected abstract boolean onManagedTouchEvent(TouchEvent pSceneTouchEvent); - @Override - public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) { - return this.onTouchEvent(pSceneTouchEvent); - } + @Override + public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) { + return this.onTouchEvent(pSceneTouchEvent); + } - public final boolean onTouchEvent(final TouchEvent pSceneTouchEvent) { - if(this.mEnabled) { - return this.onManagedTouchEvent(pSceneTouchEvent); - } else { - return false; - } - } + public final boolean onTouchEvent(final TouchEvent pSceneTouchEvent) { + if(this.mEnabled) { + return this.onManagedTouchEvent(pSceneTouchEvent); + } else { + return false; + } + } - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/input/touch/detector/ClickDetector.java b/AndEngine/src/org/anddev/andengine/input/touch/detector/ClickDetector.java index d8da64fc..bba0912b 100644 --- a/AndEngine/src/org/anddev/andengine/input/touch/detector/ClickDetector.java +++ b/AndEngine/src/org/anddev/andengine/input/touch/detector/ClickDetector.java @@ -12,87 +12,87 @@ * @since 14:29:59 - 16.08.2010 */ public class ClickDetector extends BaseDetector { - // =========================================================== - // Constants - // =========================================================== - - private static final long TRIGGER_CLICK_MAXIMUM_MILLISECONDS_DEFAULT = 200; - - // =========================================================== - // Fields - // =========================================================== - - private long mTriggerClickMaximumMilliseconds; - private final IClickDetectorListener mClickDetectorListener; - - private long mDownTimeMilliseconds = Long.MIN_VALUE; - - // =========================================================== - // Constructors - // =========================================================== - - public ClickDetector(final IClickDetectorListener pClickDetectorListener) { - this(TRIGGER_CLICK_MAXIMUM_MILLISECONDS_DEFAULT, pClickDetectorListener); - } - - public ClickDetector(final long pTriggerClickMaximumMilliseconds, final IClickDetectorListener pClickDetectorListener) { - this.mTriggerClickMaximumMilliseconds = pTriggerClickMaximumMilliseconds; - this.mClickDetectorListener = pClickDetectorListener; - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - public long getTriggerClickMaximumMilliseconds() { - return this.mTriggerClickMaximumMilliseconds; - } - - public void setTriggerClickMaximumMilliseconds(final long pClickMaximumMilliseconds) { - this.mTriggerClickMaximumMilliseconds = pClickMaximumMilliseconds; - } - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - public boolean onManagedTouchEvent(final TouchEvent pSceneTouchEvent) { - switch(pSceneTouchEvent.getAction()) { - case MotionEvent.ACTION_DOWN: - this.mDownTimeMilliseconds = pSceneTouchEvent.getMotionEvent().getDownTime(); - return true; - case MotionEvent.ACTION_UP: - case MotionEvent.ACTION_CANCEL: - final long upTimeMilliseconds = pSceneTouchEvent.getMotionEvent().getEventTime(); - - if(upTimeMilliseconds - this.mDownTimeMilliseconds <= this.mTriggerClickMaximumMilliseconds) { - this.mDownTimeMilliseconds = Long.MIN_VALUE; - this.mClickDetectorListener.onClick(this, pSceneTouchEvent); - } - return true; - default: - return false; - } - } - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== - - public static interface IClickDetectorListener { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Methods - // =========================================================== - - public void onClick(final ClickDetector pClickDetector, final TouchEvent pTouchEvent); - } + // =========================================================== + // Constants + // =========================================================== + + private static final long TRIGGER_CLICK_MAXIMUM_MILLISECONDS_DEFAULT = 200; + + // =========================================================== + // Fields + // =========================================================== + + private long mTriggerClickMaximumMilliseconds; + private final IClickDetectorListener mClickDetectorListener; + + private long mDownTimeMilliseconds = Long.MIN_VALUE; + + // =========================================================== + // Constructors + // =========================================================== + + public ClickDetector(final IClickDetectorListener pClickDetectorListener) { + this(TRIGGER_CLICK_MAXIMUM_MILLISECONDS_DEFAULT, pClickDetectorListener); + } + + public ClickDetector(final long pTriggerClickMaximumMilliseconds, final IClickDetectorListener pClickDetectorListener) { + this.mTriggerClickMaximumMilliseconds = pTriggerClickMaximumMilliseconds; + this.mClickDetectorListener = pClickDetectorListener; + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + public long getTriggerClickMaximumMilliseconds() { + return this.mTriggerClickMaximumMilliseconds; + } + + public void setTriggerClickMaximumMilliseconds(final long pClickMaximumMilliseconds) { + this.mTriggerClickMaximumMilliseconds = pClickMaximumMilliseconds; + } + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + public boolean onManagedTouchEvent(final TouchEvent pSceneTouchEvent) { + switch(pSceneTouchEvent.getAction()) { + case MotionEvent.ACTION_DOWN: + this.mDownTimeMilliseconds = pSceneTouchEvent.getMotionEvent().getDownTime(); + return true; + case MotionEvent.ACTION_UP: + case MotionEvent.ACTION_CANCEL: + final long upTimeMilliseconds = pSceneTouchEvent.getMotionEvent().getEventTime(); + + if(upTimeMilliseconds - this.mDownTimeMilliseconds <= this.mTriggerClickMaximumMilliseconds) { + this.mDownTimeMilliseconds = Long.MIN_VALUE; + this.mClickDetectorListener.onClick(this, pSceneTouchEvent); + } + return true; + default: + return false; + } + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== + + public static interface IClickDetectorListener { + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + public void onClick(final ClickDetector pClickDetector, final TouchEvent pTouchEvent); + } } diff --git a/AndEngine/src/org/anddev/andengine/input/touch/detector/HoldDetector.java b/AndEngine/src/org/anddev/andengine/input/touch/detector/HoldDetector.java index 9488ab13..d95d30e7 100644 --- a/AndEngine/src/org/anddev/andengine/input/touch/detector/HoldDetector.java +++ b/AndEngine/src/org/anddev/andengine/input/touch/detector/HoldDetector.java @@ -19,173 +19,173 @@ * @since 20:49:25 - 23.08.2010 */ public class HoldDetector extends BaseDetector implements IUpdateHandler { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - private static final long TRIGGER_HOLD_MINIMUM_MILLISECONDS_DEFAULT = 200; - private static final float TRIGGER_HOLD_MAXIMUM_DISTANCE_DEFAULT = 10; + private static final long TRIGGER_HOLD_MINIMUM_MILLISECONDS_DEFAULT = 200; + private static final float TRIGGER_HOLD_MAXIMUM_DISTANCE_DEFAULT = 10; - private static final float TIME_BETWEEN_UPDATES_DEFAULT = 0.1f; + private static final float TIME_BETWEEN_UPDATES_DEFAULT = 0.1f; - // =========================================================== - // Fields - // =========================================================== - - private long mTriggerHoldMinimumMilliseconds; - private float mTriggerHoldMaximumDistance; - private final IHoldDetectorListener mHoldDetectorListener; - - private long mDownTimeMilliseconds = Long.MIN_VALUE; - - private float mDownX; - private float mDownY; - - private float mHoldX; - private float mHoldY; - - private boolean mMaximumDistanceExceeded = false; - - private boolean mTriggerOnHold = false; - private boolean mTriggerOnHoldFinished = false; - - private final TimerHandler mTimerHandler; - - // =========================================================== - // Constructors - // =========================================================== - - public HoldDetector(final IHoldDetectorListener pClickDetectorListener) { - this(TRIGGER_HOLD_MINIMUM_MILLISECONDS_DEFAULT, TRIGGER_HOLD_MAXIMUM_DISTANCE_DEFAULT, TIME_BETWEEN_UPDATES_DEFAULT, pClickDetectorListener); - } - - public HoldDetector(final long pTriggerHoldMinimumMilliseconds, final float pTriggerHoldMaximumDistance, final float pTimeBetweenUpdates, final IHoldDetectorListener pClickDetectorListener) { - this.mTriggerHoldMinimumMilliseconds = pTriggerHoldMinimumMilliseconds; - this.mTriggerHoldMaximumDistance = pTriggerHoldMaximumDistance; - this.mHoldDetectorListener = pClickDetectorListener; - - this.mTimerHandler = new TimerHandler(pTimeBetweenUpdates, true, new ITimerCallback() { - @Override - public void onTimePassed(final TimerHandler pTimerHandler) { - HoldDetector.this.fireListener(); - } - }); - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - public long getTriggerHoldMinimumMilliseconds() { - return this.mTriggerHoldMinimumMilliseconds; - } - - public void setTriggerHoldMinimumMilliseconds(final long pTriggerHoldMinimumMilliseconds) { - this.mTriggerHoldMinimumMilliseconds = pTriggerHoldMinimumMilliseconds; - } - - public float getTriggerHoldMaximumDistance() { - return this.mTriggerHoldMaximumDistance; - } - - public void setTriggerHoldMaximumDistance(final float pTriggerHoldMaximumDistance) { - this.mTriggerHoldMaximumDistance = pTriggerHoldMaximumDistance; - } - - public boolean isHolding() { - return this.mTriggerOnHold; - } - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - public void onUpdate(final float pSecondsElapsed) { - this.mTimerHandler.onUpdate(pSecondsElapsed); - } - - @Override - public void reset() { - this.mTimerHandler.reset(); - } - - @Override - public boolean onManagedTouchEvent(final TouchEvent pSceneTouchEvent) { - final MotionEvent motionEvent = pSceneTouchEvent.getMotionEvent(); - - this.mHoldX = pSceneTouchEvent.getX(); - this.mHoldY = pSceneTouchEvent.getY(); - - switch(pSceneTouchEvent.getAction()) { - case MotionEvent.ACTION_DOWN: - this.mDownTimeMilliseconds = motionEvent.getDownTime(); - this.mDownX = motionEvent.getX(); - this.mDownY = motionEvent.getY(); - this.mMaximumDistanceExceeded = false; - return true; - case MotionEvent.ACTION_MOVE: - { - final long currentTimeMilliseconds = motionEvent.getEventTime(); - - final float triggerHoldMaximumDistance = this.mTriggerHoldMaximumDistance; - this.mMaximumDistanceExceeded = this.mMaximumDistanceExceeded || Math.abs(this.mDownX - motionEvent.getX()) > triggerHoldMaximumDistance || Math.abs(this.mDownY - motionEvent.getY()) > triggerHoldMaximumDistance; - if(this.mTriggerOnHold || !this.mMaximumDistanceExceeded) { - final long holdTimeMilliseconds = currentTimeMilliseconds - this.mDownTimeMilliseconds; - if(holdTimeMilliseconds >= this.mTriggerHoldMinimumMilliseconds) { - this.mTriggerOnHold = true; - } - } - return true; - } - case MotionEvent.ACTION_UP: - case MotionEvent.ACTION_CANCEL: - { - final long upTimeMilliseconds = motionEvent.getEventTime(); - - final float triggerHoldMaximumDistance = this.mTriggerHoldMaximumDistance; - this.mMaximumDistanceExceeded = this.mMaximumDistanceExceeded || Math.abs(this.mDownX - motionEvent.getX()) > triggerHoldMaximumDistance || Math.abs(this.mDownY - motionEvent.getY()) > triggerHoldMaximumDistance; - if(this.mTriggerOnHold || !this.mMaximumDistanceExceeded) { - final long holdTimeMilliseconds = upTimeMilliseconds - this.mDownTimeMilliseconds; - if(holdTimeMilliseconds >= this.mTriggerHoldMinimumMilliseconds) { - this.mTriggerOnHoldFinished = true; - } - } - return true; - } - default: - return false; - } - } - - // =========================================================== - // Methods - // =========================================================== - - protected void fireListener() { - if(this.mTriggerOnHoldFinished) { - this.mHoldDetectorListener.onHoldFinished(this, SystemClock.uptimeMillis() - this.mDownTimeMilliseconds, this.mHoldX, this.mHoldY); - this.mTriggerOnHoldFinished = false; - this.mTriggerOnHold = false; - } else if(this.mTriggerOnHold) { - this.mHoldDetectorListener.onHold(this, SystemClock.uptimeMillis() - this.mDownTimeMilliseconds, this.mHoldX, this.mHoldY); - } - } - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== - - public static interface IHoldDetectorListener { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Methods - // =========================================================== - - public void onHold(final HoldDetector pHoldDetector, final long pHoldTimeMilliseconds, final float pHoldX, final float pHoldY); - public void onHoldFinished(final HoldDetector pHoldDetector, final long pHoldTimeMilliseconds, final float pHoldX, final float pHoldY); - } + // =========================================================== + // Fields + // =========================================================== + + private long mTriggerHoldMinimumMilliseconds; + private float mTriggerHoldMaximumDistance; + private final IHoldDetectorListener mHoldDetectorListener; + + private long mDownTimeMilliseconds = Long.MIN_VALUE; + + private float mDownX; + private float mDownY; + + private float mHoldX; + private float mHoldY; + + private boolean mMaximumDistanceExceeded = false; + + private boolean mTriggerOnHold = false; + private boolean mTriggerOnHoldFinished = false; + + private final TimerHandler mTimerHandler; + + // =========================================================== + // Constructors + // =========================================================== + + public HoldDetector(final IHoldDetectorListener pClickDetectorListener) { + this(TRIGGER_HOLD_MINIMUM_MILLISECONDS_DEFAULT, TRIGGER_HOLD_MAXIMUM_DISTANCE_DEFAULT, TIME_BETWEEN_UPDATES_DEFAULT, pClickDetectorListener); + } + + public HoldDetector(final long pTriggerHoldMinimumMilliseconds, final float pTriggerHoldMaximumDistance, final float pTimeBetweenUpdates, final IHoldDetectorListener pClickDetectorListener) { + this.mTriggerHoldMinimumMilliseconds = pTriggerHoldMinimumMilliseconds; + this.mTriggerHoldMaximumDistance = pTriggerHoldMaximumDistance; + this.mHoldDetectorListener = pClickDetectorListener; + + this.mTimerHandler = new TimerHandler(pTimeBetweenUpdates, true, new ITimerCallback() { + @Override + public void onTimePassed(final TimerHandler pTimerHandler) { + HoldDetector.this.fireListener(); + } + }); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + public long getTriggerHoldMinimumMilliseconds() { + return this.mTriggerHoldMinimumMilliseconds; + } + + public void setTriggerHoldMinimumMilliseconds(final long pTriggerHoldMinimumMilliseconds) { + this.mTriggerHoldMinimumMilliseconds = pTriggerHoldMinimumMilliseconds; + } + + public float getTriggerHoldMaximumDistance() { + return this.mTriggerHoldMaximumDistance; + } + + public void setTriggerHoldMaximumDistance(final float pTriggerHoldMaximumDistance) { + this.mTriggerHoldMaximumDistance = pTriggerHoldMaximumDistance; + } + + public boolean isHolding() { + return this.mTriggerOnHold; + } + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + public void onUpdate(final float pSecondsElapsed) { + this.mTimerHandler.onUpdate(pSecondsElapsed); + } + + @Override + public void reset() { + this.mTimerHandler.reset(); + } + + @Override + public boolean onManagedTouchEvent(final TouchEvent pSceneTouchEvent) { + final MotionEvent motionEvent = pSceneTouchEvent.getMotionEvent(); + + this.mHoldX = pSceneTouchEvent.getX(); + this.mHoldY = pSceneTouchEvent.getY(); + + switch(pSceneTouchEvent.getAction()) { + case MotionEvent.ACTION_DOWN: + this.mDownTimeMilliseconds = motionEvent.getDownTime(); + this.mDownX = motionEvent.getX(); + this.mDownY = motionEvent.getY(); + this.mMaximumDistanceExceeded = false; + return true; + case MotionEvent.ACTION_MOVE: + { + final long currentTimeMilliseconds = motionEvent.getEventTime(); + + final float triggerHoldMaximumDistance = this.mTriggerHoldMaximumDistance; + this.mMaximumDistanceExceeded = this.mMaximumDistanceExceeded || Math.abs(this.mDownX - motionEvent.getX()) > triggerHoldMaximumDistance || Math.abs(this.mDownY - motionEvent.getY()) > triggerHoldMaximumDistance; + if(this.mTriggerOnHold || !this.mMaximumDistanceExceeded) { + final long holdTimeMilliseconds = currentTimeMilliseconds - this.mDownTimeMilliseconds; + if(holdTimeMilliseconds >= this.mTriggerHoldMinimumMilliseconds) { + this.mTriggerOnHold = true; + } + } + return true; + } + case MotionEvent.ACTION_UP: + case MotionEvent.ACTION_CANCEL: + { + final long upTimeMilliseconds = motionEvent.getEventTime(); + + final float triggerHoldMaximumDistance = this.mTriggerHoldMaximumDistance; + this.mMaximumDistanceExceeded = this.mMaximumDistanceExceeded || Math.abs(this.mDownX - motionEvent.getX()) > triggerHoldMaximumDistance || Math.abs(this.mDownY - motionEvent.getY()) > triggerHoldMaximumDistance; + if(this.mTriggerOnHold || !this.mMaximumDistanceExceeded) { + final long holdTimeMilliseconds = upTimeMilliseconds - this.mDownTimeMilliseconds; + if(holdTimeMilliseconds >= this.mTriggerHoldMinimumMilliseconds) { + this.mTriggerOnHoldFinished = true; + } + } + return true; + } + default: + return false; + } + } + + // =========================================================== + // Methods + // =========================================================== + + protected void fireListener() { + if(this.mTriggerOnHoldFinished) { + this.mHoldDetectorListener.onHoldFinished(this, SystemClock.uptimeMillis() - this.mDownTimeMilliseconds, this.mHoldX, this.mHoldY); + this.mTriggerOnHoldFinished = false; + this.mTriggerOnHold = false; + } else if(this.mTriggerOnHold) { + this.mHoldDetectorListener.onHold(this, SystemClock.uptimeMillis() - this.mDownTimeMilliseconds, this.mHoldX, this.mHoldY); + } + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== + + public static interface IHoldDetectorListener { + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + public void onHold(final HoldDetector pHoldDetector, final long pHoldTimeMilliseconds, final float pHoldX, final float pHoldY); + public void onHoldFinished(final HoldDetector pHoldDetector, final long pHoldTimeMilliseconds, final float pHoldX, final float pHoldY); + } } diff --git a/AndEngine/src/org/anddev/andengine/input/touch/detector/ScrollDetector.java b/AndEngine/src/org/anddev/andengine/input/touch/detector/ScrollDetector.java index 5afba0d6..877911d8 100644 --- a/AndEngine/src/org/anddev/andengine/input/touch/detector/ScrollDetector.java +++ b/AndEngine/src/org/anddev/andengine/input/touch/detector/ScrollDetector.java @@ -12,109 +12,109 @@ * @since 14:29:59 - 16.08.2010 */ public class ScrollDetector extends BaseDetector { - // =========================================================== - // Constants - // =========================================================== - - private static final float TRIGGER_SCROLL_MINIMUM_DISTANCE_DEFAULT = 10; - - // =========================================================== - // Fields - // =========================================================== - - private float mTriggerScrollMinimumDistance; - - private final IScrollDetectorListener mScrollDetectorListener; - - private boolean mTriggered; - - private float mLastX; - private float mLastY; - - // =========================================================== - // Constructors - // =========================================================== - - public ScrollDetector(final IScrollDetectorListener pScrollDetectorListener) { - this(TRIGGER_SCROLL_MINIMUM_DISTANCE_DEFAULT, pScrollDetectorListener); - } - - public ScrollDetector(final float pTriggerScrollMinimumDistance, final IScrollDetectorListener pScrollDetectorListener) { - this.mTriggerScrollMinimumDistance = pTriggerScrollMinimumDistance; - this.mScrollDetectorListener = pScrollDetectorListener; - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - public float getTriggerScrollMinimumDistance() { - return this.mTriggerScrollMinimumDistance; - } - - public void setTriggerScrollMinimumDistance(final float pTriggerScrollMinimumDistance) { - this.mTriggerScrollMinimumDistance = pTriggerScrollMinimumDistance; - } - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - public boolean onManagedTouchEvent(final TouchEvent pSceneTouchEvent) { - final float touchX = this.getX(pSceneTouchEvent); - final float touchY = this.getY(pSceneTouchEvent); - - switch(pSceneTouchEvent.getAction()) { - case MotionEvent.ACTION_DOWN: - this.mLastX = touchX; - this.mLastY = touchY; - this.mTriggered = false; - return true; - case MotionEvent.ACTION_MOVE: - case MotionEvent.ACTION_UP: - case MotionEvent.ACTION_CANCEL: - final float distanceX = touchX - this.mLastX; - final float distanceY = touchY - this.mLastY; - - final float triggerScrollMinimumDistance = this.mTriggerScrollMinimumDistance; - if(this.mTriggered || Math.abs(distanceX) > triggerScrollMinimumDistance || Math.abs(distanceY) > triggerScrollMinimumDistance) { - this.mScrollDetectorListener.onScroll(this, pSceneTouchEvent, distanceX, distanceY); - this.mLastX = touchX; - this.mLastY = touchY; - this.mTriggered = true; - } - return true; - default: - return false; - } - } - - // =========================================================== - // Methods - // =========================================================== - - protected float getX(final TouchEvent pTouchEvent) { - return pTouchEvent.getX(); - } - - protected float getY(final TouchEvent pTouchEvent) { - return pTouchEvent.getY(); - } - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== - - public static interface IScrollDetectorListener { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Methods - // =========================================================== - - public void onScroll(final ScrollDetector pScollDetector, final TouchEvent pTouchEvent, final float pDistanceX, final float pDistanceY); - } + // =========================================================== + // Constants + // =========================================================== + + private static final float TRIGGER_SCROLL_MINIMUM_DISTANCE_DEFAULT = 10; + + // =========================================================== + // Fields + // =========================================================== + + private float mTriggerScrollMinimumDistance; + + private final IScrollDetectorListener mScrollDetectorListener; + + private boolean mTriggered; + + private float mLastX; + private float mLastY; + + // =========================================================== + // Constructors + // =========================================================== + + public ScrollDetector(final IScrollDetectorListener pScrollDetectorListener) { + this(TRIGGER_SCROLL_MINIMUM_DISTANCE_DEFAULT, pScrollDetectorListener); + } + + public ScrollDetector(final float pTriggerScrollMinimumDistance, final IScrollDetectorListener pScrollDetectorListener) { + this.mTriggerScrollMinimumDistance = pTriggerScrollMinimumDistance; + this.mScrollDetectorListener = pScrollDetectorListener; + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + public float getTriggerScrollMinimumDistance() { + return this.mTriggerScrollMinimumDistance; + } + + public void setTriggerScrollMinimumDistance(final float pTriggerScrollMinimumDistance) { + this.mTriggerScrollMinimumDistance = pTriggerScrollMinimumDistance; + } + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + public boolean onManagedTouchEvent(final TouchEvent pSceneTouchEvent) { + final float touchX = this.getX(pSceneTouchEvent); + final float touchY = this.getY(pSceneTouchEvent); + + switch(pSceneTouchEvent.getAction()) { + case MotionEvent.ACTION_DOWN: + this.mLastX = touchX; + this.mLastY = touchY; + this.mTriggered = false; + return true; + case MotionEvent.ACTION_MOVE: + case MotionEvent.ACTION_UP: + case MotionEvent.ACTION_CANCEL: + final float distanceX = touchX - this.mLastX; + final float distanceY = touchY - this.mLastY; + + final float triggerScrollMinimumDistance = this.mTriggerScrollMinimumDistance; + if(this.mTriggered || Math.abs(distanceX) > triggerScrollMinimumDistance || Math.abs(distanceY) > triggerScrollMinimumDistance) { + this.mScrollDetectorListener.onScroll(this, pSceneTouchEvent, distanceX, distanceY); + this.mLastX = touchX; + this.mLastY = touchY; + this.mTriggered = true; + } + return true; + default: + return false; + } + } + + // =========================================================== + // Methods + // =========================================================== + + protected float getX(final TouchEvent pTouchEvent) { + return pTouchEvent.getX(); + } + + protected float getY(final TouchEvent pTouchEvent) { + return pTouchEvent.getY(); + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== + + public static interface IScrollDetectorListener { + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + public void onScroll(final ScrollDetector pScollDetector, final TouchEvent pTouchEvent, final float pDistanceX, final float pDistanceY); + } } diff --git a/AndEngine/src/org/anddev/andengine/input/touch/detector/SurfaceGestureDetector.java b/AndEngine/src/org/anddev/andengine/input/touch/detector/SurfaceGestureDetector.java index cd1e64f4..b494e378 100644 --- a/AndEngine/src/org/anddev/andengine/input/touch/detector/SurfaceGestureDetector.java +++ b/AndEngine/src/org/anddev/andengine/input/touch/detector/SurfaceGestureDetector.java @@ -15,184 +15,184 @@ * @since 11:36:26 - 11.10.2010 */ public abstract class SurfaceGestureDetector extends BaseDetector { - // =========================================================== - // Constants - // =========================================================== - - private static final float SWIPE_MIN_DISTANCE_DEFAULT = 120; - - // =========================================================== - // Fields - // =========================================================== - - private final GestureDetector mGestureDetector; - - // =========================================================== - // Constructors - // =========================================================== - - public SurfaceGestureDetector() { - this(SWIPE_MIN_DISTANCE_DEFAULT); - } - - public SurfaceGestureDetector(final float pSwipeMinDistance) { - this.mGestureDetector = new GestureDetector(new InnerOnGestureDetectorListener(pSwipeMinDistance)); - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - protected abstract boolean onSingleTap(); - protected abstract boolean onDoubleTap(); - protected abstract boolean onSwipeUp(); - protected abstract boolean onSwipeDown(); - protected abstract boolean onSwipeLeft(); - protected abstract boolean onSwipeRight(); - - @Override - public boolean onManagedTouchEvent(final TouchEvent pSceneTouchEvent) { - return this.mGestureDetector.onTouchEvent(pSceneTouchEvent.getMotionEvent()); - } - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== - - private class InnerOnGestureDetectorListener extends SimpleOnGestureListener { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - private final float mSwipeMinDistance; - - // =========================================================== - // Constructors - // =========================================================== - - public InnerOnGestureDetectorListener(final float pSwipeMinDistance) { - this.mSwipeMinDistance = pSwipeMinDistance; - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - public boolean onSingleTapConfirmed(final MotionEvent pMotionEvent) { - return SurfaceGestureDetector.this.onSingleTap(); - } - - @Override - public boolean onDoubleTap(final MotionEvent pMotionEvent) { - return SurfaceGestureDetector.this.onDoubleTap(); - } - - @Override - public boolean onFling(final MotionEvent pMotionEventStart, final MotionEvent pMotionEventEnd, final float pVelocityX, final float pVelocityY) { - final float swipeMinDistance = this.mSwipeMinDistance; - - final boolean isHorizontalFling = Math.abs(pVelocityX) > Math.abs(pVelocityY); - - if(isHorizontalFling) { - if(pMotionEventStart.getX() - pMotionEventEnd.getX() > swipeMinDistance) { - return SurfaceGestureDetector.this.onSwipeLeft(); - } else if(pMotionEventEnd.getX() - pMotionEventStart.getX() > swipeMinDistance) { - return SurfaceGestureDetector.this.onSwipeRight(); - } - } else { - if(pMotionEventStart.getY() - pMotionEventEnd.getY() > swipeMinDistance) { - return SurfaceGestureDetector.this.onSwipeUp(); - } else if(pMotionEventEnd.getY() - pMotionEventStart.getY() > swipeMinDistance) { - return SurfaceGestureDetector.this.onSwipeDown(); - } - } - - return false; - } - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== - } - - public static class SurfaceGestureDetectorAdapter extends SurfaceGestureDetector { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - // =========================================================== - // Constructors - // =========================================================== - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - protected boolean onDoubleTap() { - return false; - } - - @Override - protected boolean onSingleTap() { - return false; - } - - @Override - protected boolean onSwipeDown() { - return false; - } - - @Override - protected boolean onSwipeLeft() { - return false; - } - - @Override - protected boolean onSwipeRight() { - return false; - } - - @Override - protected boolean onSwipeUp() { - return false; - } - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== - } -} \ No newline at end of file + // =========================================================== + // Constants + // =========================================================== + + private static final float SWIPE_MIN_DISTANCE_DEFAULT = 120; + + // =========================================================== + // Fields + // =========================================================== + + private final GestureDetector mGestureDetector; + + // =========================================================== + // Constructors + // =========================================================== + + public SurfaceGestureDetector() { + this(SWIPE_MIN_DISTANCE_DEFAULT); + } + + public SurfaceGestureDetector(final float pSwipeMinDistance) { + this.mGestureDetector = new GestureDetector(new InnerOnGestureDetectorListener(pSwipeMinDistance)); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + protected abstract boolean onSingleTap(); + protected abstract boolean onDoubleTap(); + protected abstract boolean onSwipeUp(); + protected abstract boolean onSwipeDown(); + protected abstract boolean onSwipeLeft(); + protected abstract boolean onSwipeRight(); + + @Override + public boolean onManagedTouchEvent(final TouchEvent pSceneTouchEvent) { + return this.mGestureDetector.onTouchEvent(pSceneTouchEvent.getMotionEvent()); + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== + + private class InnerOnGestureDetectorListener extends SimpleOnGestureListener { + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + private final float mSwipeMinDistance; + + // =========================================================== + // Constructors + // =========================================================== + + public InnerOnGestureDetectorListener(final float pSwipeMinDistance) { + this.mSwipeMinDistance = pSwipeMinDistance; + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + public boolean onSingleTapConfirmed(final MotionEvent pMotionEvent) { + return SurfaceGestureDetector.this.onSingleTap(); + } + + @Override + public boolean onDoubleTap(final MotionEvent pMotionEvent) { + return SurfaceGestureDetector.this.onDoubleTap(); + } + + @Override + public boolean onFling(final MotionEvent pMotionEventStart, final MotionEvent pMotionEventEnd, final float pVelocityX, final float pVelocityY) { + final float swipeMinDistance = this.mSwipeMinDistance; + + final boolean isHorizontalFling = Math.abs(pVelocityX) > Math.abs(pVelocityY); + + if(isHorizontalFling) { + if(pMotionEventStart.getX() - pMotionEventEnd.getX() > swipeMinDistance) { + return SurfaceGestureDetector.this.onSwipeLeft(); + } else if(pMotionEventEnd.getX() - pMotionEventStart.getX() > swipeMinDistance) { + return SurfaceGestureDetector.this.onSwipeRight(); + } + } else { + if(pMotionEventStart.getY() - pMotionEventEnd.getY() > swipeMinDistance) { + return SurfaceGestureDetector.this.onSwipeUp(); + } else if(pMotionEventEnd.getY() - pMotionEventStart.getY() > swipeMinDistance) { + return SurfaceGestureDetector.this.onSwipeDown(); + } + } + + return false; + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== + } + + public static class SurfaceGestureDetectorAdapter extends SurfaceGestureDetector { + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + // =========================================================== + // Constructors + // =========================================================== + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + protected boolean onDoubleTap() { + return false; + } + + @Override + protected boolean onSingleTap() { + return false; + } + + @Override + protected boolean onSwipeDown() { + return false; + } + + @Override + protected boolean onSwipeLeft() { + return false; + } + + @Override + protected boolean onSwipeRight() { + return false; + } + + @Override + protected boolean onSwipeUp() { + return false; + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== + } +} diff --git a/AndEngine/src/org/anddev/andengine/input/touch/detector/SurfaceScrollDetector.java b/AndEngine/src/org/anddev/andengine/input/touch/detector/SurfaceScrollDetector.java index 04111a90..cf1d6c5e 100644 --- a/AndEngine/src/org/anddev/andengine/input/touch/detector/SurfaceScrollDetector.java +++ b/AndEngine/src/org/anddev/andengine/input/touch/detector/SurfaceScrollDetector.java @@ -10,49 +10,49 @@ * @since 16:12:29 - 16.08.2010 */ public class SurfaceScrollDetector extends ScrollDetector { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - // =========================================================== - // Constructors - // =========================================================== - - public SurfaceScrollDetector(final float pTriggerScrollMinimumDistance, final IScrollDetectorListener pScrollDetectorListener) { - super(pTriggerScrollMinimumDistance, pScrollDetectorListener); - } - - public SurfaceScrollDetector(final IScrollDetectorListener pScrollDetectorListener) { - super(pScrollDetectorListener); - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - protected float getX(final TouchEvent pTouchEvent) { - return pTouchEvent.getMotionEvent().getX(); - } - - @Override - protected float getY(final TouchEvent pTouchEvent) { - return pTouchEvent.getMotionEvent().getY(); - } - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + // =========================================================== + // Constructors + // =========================================================== + + public SurfaceScrollDetector(final float pTriggerScrollMinimumDistance, final IScrollDetectorListener pScrollDetectorListener) { + super(pTriggerScrollMinimumDistance, pScrollDetectorListener); + } + + public SurfaceScrollDetector(final IScrollDetectorListener pScrollDetectorListener) { + super(pScrollDetectorListener); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + protected float getX(final TouchEvent pTouchEvent) { + return pTouchEvent.getMotionEvent().getX(); + } + + @Override + protected float getY(final TouchEvent pTouchEvent) { + return pTouchEvent.getMotionEvent().getY(); + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/level/LevelLoader.java b/AndEngine/src/org/anddev/andengine/level/LevelLoader.java index 465d4595..38a43cc3 100644 --- a/AndEngine/src/org/anddev/andengine/level/LevelLoader.java +++ b/AndEngine/src/org/anddev/andengine/level/LevelLoader.java @@ -27,129 +27,129 @@ * @since 14:16:19 - 11.10.2010 */ public class LevelLoader implements LevelConstants { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - private String mAssetBasePath; - - private IEntityLoader mDefaultEntityLoader; - private final HashMap mEntityLoaders = new HashMap(); - - // =========================================================== - // Constructors - // =========================================================== - - public LevelLoader() { - this(""); - } - - public LevelLoader(final String pAssetBasePath) { - this.setAssetBasePath(pAssetBasePath); - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - public IEntityLoader getDefaultEntityLoader() { - return this.mDefaultEntityLoader; - } - - public void setDefaultEntityLoader(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() { - - } - - protected void onBeforeLoadLevel() { - - } - - // =========================================================== - // Methods - // =========================================================== - - public void registerEntityLoader(final String pEntityName, final IEntityLoader pEntityLoader) { - this.mEntityLoaders.put(pEntityName, pEntityLoader); - } - - public void registerEntityLoader(final String[] pEntityNames, final IEntityLoader pEntityLoader) { - final HashMap entityLoaders = this.mEntityLoaders; - - for(int i = pEntityNames.length - 1; i >= 0; i--) { - entityLoaders.put(pEntityNames[i], pEntityLoader); - } - } - - public void loadLevelFromAsset(final Context pContext, final String pAssetPath) throws IOException { - this.loadLevelFromStream(pContext.getAssets().open(this.mAssetBasePath + pAssetPath)); - } - - public void loadLevelFromResource(final Context pContext, final int pRawResourceID) throws IOException { - this.loadLevelFromStream(pContext.getResources().openRawResource(pRawResourceID)); - } - - public void loadLevelFromStream(final InputStream pInputStream) throws IOException { - 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); - - 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. */ - } finally { - StreamUtils.close(pInputStream); - } - } - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== - - public static interface IEntityLoader { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Methods - // =========================================================== - - public void onLoadEntity(final String pEntityName, final Attributes pAttributes); - } + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + private String mAssetBasePath; + + private IEntityLoader mDefaultEntityLoader; + private final HashMap mEntityLoaders = new HashMap(); + + // =========================================================== + // Constructors + // =========================================================== + + public LevelLoader() { + this(""); + } + + public LevelLoader(final String pAssetBasePath) { + this.setAssetBasePath(pAssetBasePath); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + public IEntityLoader getDefaultEntityLoader() { + return this.mDefaultEntityLoader; + } + + public void setDefaultEntityLoader(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() { + + } + + protected void onBeforeLoadLevel() { + + } + + // =========================================================== + // Methods + // =========================================================== + + public void registerEntityLoader(final String pEntityName, final IEntityLoader pEntityLoader) { + this.mEntityLoaders.put(pEntityName, pEntityLoader); + } + + public void registerEntityLoader(final String[] pEntityNames, final IEntityLoader pEntityLoader) { + final HashMap entityLoaders = this.mEntityLoaders; + + for(int i = pEntityNames.length - 1; i >= 0; i--) { + entityLoaders.put(pEntityNames[i], pEntityLoader); + } + } + + public void loadLevelFromAsset(final Context pContext, final String pAssetPath) throws IOException { + this.loadLevelFromStream(pContext.getAssets().open(this.mAssetBasePath + pAssetPath)); + } + + public void loadLevelFromResource(final Context pContext, final int pRawResourceID) throws IOException { + this.loadLevelFromStream(pContext.getResources().openRawResource(pRawResourceID)); + } + + public void loadLevelFromStream(final InputStream pInputStream) throws IOException { + 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); + + 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. */ + } finally { + StreamUtils.close(pInputStream); + } + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== + + public static interface IEntityLoader { + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + public void onLoadEntity(final String pEntityName, final Attributes pAttributes); + } } diff --git a/AndEngine/src/org/anddev/andengine/level/LevelParser.java b/AndEngine/src/org/anddev/andengine/level/LevelParser.java index 032fdbe9..13538155 100644 --- a/AndEngine/src/org/anddev/andengine/level/LevelParser.java +++ b/AndEngine/src/org/anddev/andengine/level/LevelParser.java @@ -16,53 +16,53 @@ * @since 14:35:32 - 11.10.2010 */ public class LevelParser extends DefaultHandler implements LevelConstants { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - private final IEntityLoader mDefaultEntityLoader; - private final HashMap mEntityLoaders; + private final IEntityLoader mDefaultEntityLoader; + private final HashMap mEntityLoaders; - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - public LevelParser(final IEntityLoader pDefaultEntityLoader, final HashMap pEntityLoaders) { - this.mDefaultEntityLoader = pDefaultEntityLoader; - this.mEntityLoaders = pEntityLoaders; - } + public LevelParser(final IEntityLoader pDefaultEntityLoader, final HashMap pEntityLoaders) { + this.mDefaultEntityLoader = pDefaultEntityLoader; + this.mEntityLoaders = pEntityLoaders; + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - @Override - public void startElement(final String pUri, final String pLocalName, final String pQualifiedName, final Attributes pAttributes) throws SAXException { - final IEntityLoader entityLoader = this.mEntityLoaders.get(pLocalName); - if(entityLoader != null) { - entityLoader.onLoadEntity(pLocalName, pAttributes); - } else { - if(this.mDefaultEntityLoader != null) { - this.mDefaultEntityLoader.onLoadEntity(pLocalName, pAttributes); - } else { - throw new IllegalArgumentException("Unexpected tag: '" + pLocalName + "'."); - } - } - } + @Override + public void startElement(final String pUri, final String pLocalName, final String pQualifiedName, final Attributes pAttributes) throws SAXException { + final IEntityLoader entityLoader = this.mEntityLoaders.get(pLocalName); + if(entityLoader != null) { + entityLoader.onLoadEntity(pLocalName, pAttributes); + } else { + if(this.mDefaultEntityLoader != null) { + this.mDefaultEntityLoader.onLoadEntity(pLocalName, pAttributes); + } else { + throw new IllegalArgumentException("Unexpected tag: '" + pLocalName + "'."); + } + } + } - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/level/util/constants/LevelConstants.java b/AndEngine/src/org/anddev/andengine/level/util/constants/LevelConstants.java index 2fb6059b..385c7c1d 100644 --- a/AndEngine/src/org/anddev/andengine/level/util/constants/LevelConstants.java +++ b/AndEngine/src/org/anddev/andengine/level/util/constants/LevelConstants.java @@ -9,17 +9,17 @@ * @since 14:23:27 - 11.10.2010 */ public interface LevelConstants { - // =========================================================== - // Final Fields - // =========================================================== + // =========================================================== + // Final Fields + // =========================================================== - public static final String TAG_LEVEL = "level"; - public static final String TAG_LEVEL_ATTRIBUTE_NAME = "name"; - public static final String TAG_LEVEL_ATTRIBUTE_UID = "uid"; - public static final String TAG_LEVEL_ATTRIBUTE_WIDTH = "width"; - public static final String TAG_LEVEL_ATTRIBUTE_HEIGHT = "height"; + public static final String TAG_LEVEL = "level"; + public static final String TAG_LEVEL_ATTRIBUTE_NAME = "name"; + public static final String TAG_LEVEL_ATTRIBUTE_UID = "uid"; + public static final String TAG_LEVEL_ATTRIBUTE_WIDTH = "width"; + public static final String TAG_LEVEL_ATTRIBUTE_HEIGHT = "height"; - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/opengl/IDrawable.java b/AndEngine/src/org/anddev/andengine/opengl/IDrawable.java index a6e58ce8..1c8c08af 100644 --- a/AndEngine/src/org/anddev/andengine/opengl/IDrawable.java +++ b/AndEngine/src/org/anddev/andengine/opengl/IDrawable.java @@ -13,13 +13,13 @@ * @since 10:50:58 - 08.08.2010 */ public interface IDrawable { - // =========================================================== - // Final Fields - // =========================================================== + // =========================================================== + // Final Fields + // =========================================================== - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - public void onDraw(final GL10 pGL, final Camera pCamera); + public void onDraw(final GL10 pGL, final Camera pCamera); } diff --git a/AndEngine/src/org/anddev/andengine/opengl/buffer/BufferObject.java b/AndEngine/src/org/anddev/andengine/opengl/buffer/BufferObject.java index 300fee8c..15ff0ab1 100644 --- a/AndEngine/src/org/anddev/andengine/opengl/buffer/BufferObject.java +++ b/AndEngine/src/org/anddev/andengine/opengl/buffer/BufferObject.java @@ -13,136 +13,136 @@ * @since 14:22:56 - 07.04.2010 */ public abstract class BufferObject { - // =========================================================== - // Constants - // =========================================================== - - private static final int[] HARDWAREBUFFERID_FETCHER = new int[1]; + // =========================================================== + // Constants + // =========================================================== + + private static final int[] HARDWAREBUFFERID_FETCHER = new int[1]; - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - protected final int[] mBufferData; + protected final int[] mBufferData; - private final int mDrawType; + private final int mDrawType; - protected final FastFloatBuffer mFloatBuffer; + protected final FastFloatBuffer mFloatBuffer; - private int mHardwareBufferID = -1; - private boolean mLoadedToHardware; - private boolean mHardwareBufferNeedsUpdate = true; + private int mHardwareBufferID = -1; + private boolean mLoadedToHardware; + private boolean mHardwareBufferNeedsUpdate = true; - private boolean mManaged; + private boolean mManaged; - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - /** - * @param pCapacity - * @param pDrawType - * @param pManaged when passing true this {@link BufferObject} loads itself to the active {@link BufferObjectManager}. WARNING: When passing false one needs to take care of that by oneself! - */ - public BufferObject(final int pCapacity, final int pDrawType, final boolean pManaged) { - this.mDrawType = pDrawType; - this.mManaged = pManaged; - this.mBufferData = new int[pCapacity]; - this.mFloatBuffer = new FastFloatBuffer(pCapacity); + /** + * @param pCapacity + * @param pDrawType + * @param pManaged when passing true this {@link BufferObject} loads itself to the active {@link BufferObjectManager}. WARNING: When passing false one needs to take care of that by oneself! + */ + public BufferObject(final int pCapacity, final int pDrawType, final boolean pManaged) { + this.mDrawType = pDrawType; + this.mManaged = pManaged; + this.mBufferData = new int[pCapacity]; + this.mFloatBuffer = new FastFloatBuffer(pCapacity); - if(pManaged) { - this.loadToActiveBufferObjectManager(); - } - } + if(pManaged) { + this.loadToActiveBufferObjectManager(); + } + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - public boolean isManaged() { - return this.mManaged; - } + public boolean isManaged() { + return this.mManaged; + } - public void setManaged(final boolean pManaged) { - this.mManaged = pManaged; - } + public void setManaged(final boolean pManaged) { + this.mManaged = pManaged; + } - public FastFloatBuffer getFloatBuffer() { - return this.mFloatBuffer; - } + public FastFloatBuffer getFloatBuffer() { + return this.mFloatBuffer; + } - public int getHardwareBufferID() { - return this.mHardwareBufferID; - } + public int getHardwareBufferID() { + return this.mHardwareBufferID; + } - public boolean isLoadedToHardware() { - return this.mLoadedToHardware; - } + public boolean isLoadedToHardware() { + return this.mLoadedToHardware; + } - void setLoadedToHardware(final boolean pLoadedToHardware) { - this.mLoadedToHardware = pLoadedToHardware; - } + void setLoadedToHardware(final boolean pLoadedToHardware) { + this.mLoadedToHardware = pLoadedToHardware; + } - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - public void setHardwareBufferNeedsUpdate(){ - this.mHardwareBufferNeedsUpdate = true; - } + public void setHardwareBufferNeedsUpdate(){ + this.mHardwareBufferNeedsUpdate = true; + } - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - public void selectOnHardware(final GL11 pGL11) { - final int hardwareBufferID = this.mHardwareBufferID; - if(hardwareBufferID == -1) { - return; - } + public void selectOnHardware(final GL11 pGL11) { + final int hardwareBufferID = this.mHardwareBufferID; + if(hardwareBufferID == -1) { + return; + } - GLHelper.bindBuffer(pGL11, hardwareBufferID); // TODO Does this always need to be bound, or are just for buffers of the same 'type'(texture/vertex)? + GLHelper.bindBuffer(pGL11, hardwareBufferID); // TODO Does this always need to be bound, or are just for buffers of the same 'type'(texture/vertex)? - if(this.mHardwareBufferNeedsUpdate) { - this.mHardwareBufferNeedsUpdate = false; - synchronized(this) { - GLHelper.bufferData(pGL11, this.mFloatBuffer.mByteBuffer, this.mDrawType); - } - } - } + if(this.mHardwareBufferNeedsUpdate) { + this.mHardwareBufferNeedsUpdate = false; + synchronized(this) { + GLHelper.bufferData(pGL11, this.mFloatBuffer.mByteBuffer, this.mDrawType); + } + } + } - public void loadToActiveBufferObjectManager() { - BufferObjectManager.getActiveInstance().loadBufferObject(this); - } + public void loadToActiveBufferObjectManager() { + BufferObjectManager.getActiveInstance().loadBufferObject(this); + } - public void unloadFromActiveBufferObjectManager() { - BufferObjectManager.getActiveInstance().unloadBufferObject(this); - } + public void unloadFromActiveBufferObjectManager() { + BufferObjectManager.getActiveInstance().unloadBufferObject(this); + } - public void loadToHardware(final GL11 pGL11) { - this.mHardwareBufferID = this.generateHardwareBufferID(pGL11); + public void loadToHardware(final GL11 pGL11) { + this.mHardwareBufferID = this.generateHardwareBufferID(pGL11); - this.mLoadedToHardware = true; - } + this.mLoadedToHardware = true; + } - public void unloadFromHardware(final GL11 pGL11) { - this.deleteBufferOnHardware(pGL11); - - this.mHardwareBufferID = -1; - this.mLoadedToHardware = false; - } - - private void deleteBufferOnHardware(final GL11 pGL11) { - GLHelper.deleteBuffer(pGL11, this.mHardwareBufferID); - } - - private int generateHardwareBufferID(final GL11 pGL11) { - pGL11.glGenBuffers(1, HARDWAREBUFFERID_FETCHER, 0); - - return HARDWAREBUFFERID_FETCHER[0]; - } - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + public void unloadFromHardware(final GL11 pGL11) { + this.deleteBufferOnHardware(pGL11); + + this.mHardwareBufferID = -1; + this.mLoadedToHardware = false; + } + + private void deleteBufferOnHardware(final GL11 pGL11) { + GLHelper.deleteBuffer(pGL11, this.mHardwareBufferID); + } + + private int generateHardwareBufferID(final GL11 pGL11) { + pGL11.glGenBuffers(1, HARDWAREBUFFERID_FETCHER, 0); + + return HARDWAREBUFFERID_FETCHER[0]; + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/opengl/buffer/BufferObjectManager.java b/AndEngine/src/org/anddev/andengine/opengl/buffer/BufferObjectManager.java index 9c3c3ccc..e5906c3e 100644 --- a/AndEngine/src/org/anddev/andengine/opengl/buffer/BufferObjectManager.java +++ b/AndEngine/src/org/anddev/andengine/opengl/buffer/BufferObjectManager.java @@ -13,141 +13,141 @@ * @since 17:48:46 - 08.03.2010 */ public class BufferObjectManager { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - private static final HashSet mBufferObjectsManaged = new HashSet(); - - private static final ArrayList mBufferObjectsLoaded = new ArrayList(); - - private static final ArrayList mBufferObjectsToBeLoaded = new ArrayList(); - private static final ArrayList mBufferObjectsToBeUnloaded = new ArrayList(); - - private static BufferObjectManager mActiveInstance = null; - - // =========================================================== - // Constructors - // =========================================================== - - public static BufferObjectManager getActiveInstance() { - return BufferObjectManager.mActiveInstance; - } - - public static void setActiveInstance(final BufferObjectManager pActiveInstance) { - BufferObjectManager.mActiveInstance = pActiveInstance; - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - // =========================================================== - // Methods - // =========================================================== - - public synchronized void clear() { - BufferObjectManager.mBufferObjectsToBeLoaded.clear(); - BufferObjectManager.mBufferObjectsLoaded.clear(); - BufferObjectManager.mBufferObjectsManaged.clear(); - } - - public synchronized void loadBufferObject(final BufferObject pBufferObject) { - if(pBufferObject == null) { - return; - } - - if(BufferObjectManager.mBufferObjectsManaged.contains(pBufferObject)) { - /* Just make sure it doesn't get deleted. */ - BufferObjectManager.mBufferObjectsToBeUnloaded.remove(pBufferObject); - } else { - BufferObjectManager.mBufferObjectsManaged.add(pBufferObject); - BufferObjectManager.mBufferObjectsToBeLoaded.add(pBufferObject); - } - } - - public synchronized void unloadBufferObject(final BufferObject pBufferObject) { - if(pBufferObject == null) { - return; - } - if(BufferObjectManager.mBufferObjectsManaged.contains(pBufferObject)) { - if(BufferObjectManager.mBufferObjectsLoaded.contains(pBufferObject)) { - BufferObjectManager.mBufferObjectsToBeUnloaded.add(pBufferObject); - } else if(BufferObjectManager.mBufferObjectsToBeLoaded.remove(pBufferObject)) { - BufferObjectManager.mBufferObjectsManaged.remove(pBufferObject); - } - } - } - - public void loadBufferObjects(final BufferObject... pBufferObjects) { - for(int i = pBufferObjects.length - 1; i >= 0; i--) { - this.loadBufferObject(pBufferObjects[i]); - } - } - - public void unloadBufferObjects(final BufferObject... pBufferObjects) { - for(int i = pBufferObjects.length - 1; i >= 0; i--) { - this.unloadBufferObject(pBufferObjects[i]); - } - } - - public synchronized void reloadBufferObjects() { - final ArrayList loadedBufferObjects = BufferObjectManager.mBufferObjectsLoaded; - for(int i = loadedBufferObjects.size() - 1; i >= 0; i--) { - loadedBufferObjects.get(i).setLoadedToHardware(false); - } - - BufferObjectManager.mBufferObjectsToBeLoaded.addAll(loadedBufferObjects); - - loadedBufferObjects.clear(); - } - - public synchronized void updateBufferObjects(final GL11 pGL11) { - final HashSet bufferObjectsManaged = BufferObjectManager.mBufferObjectsManaged; - final ArrayList bufferObjectsLoaded = BufferObjectManager.mBufferObjectsLoaded; - final ArrayList bufferObjectsToBeLoaded = BufferObjectManager.mBufferObjectsToBeLoaded; - final ArrayList bufferObjectsToBeUnloaded = BufferObjectManager.mBufferObjectsToBeUnloaded; - - /* First load pending BufferObjects. */ - final int bufferObjectToBeLoadedCount = bufferObjectsToBeLoaded.size(); - - if(bufferObjectToBeLoadedCount > 0) { - for(int i = bufferObjectToBeLoadedCount - 1; i >= 0; i--) { - final BufferObject bufferObjectToBeLoaded = bufferObjectsToBeLoaded.get(i); - if(!bufferObjectToBeLoaded.isLoadedToHardware()) { - bufferObjectToBeLoaded.loadToHardware(pGL11); - bufferObjectToBeLoaded.setHardwareBufferNeedsUpdate(); - } - bufferObjectsLoaded.add(bufferObjectToBeLoaded); - } - - bufferObjectsToBeLoaded.clear(); - } - - /* Then unload pending BufferObjects. */ - final int bufferObjectsToBeUnloadedCount = bufferObjectsToBeUnloaded.size(); - - if(bufferObjectsToBeUnloadedCount > 0){ - for(int i = bufferObjectsToBeUnloadedCount - 1; i >= 0; i--){ - final BufferObject bufferObjectToBeUnloaded = bufferObjectsToBeUnloaded.remove(i); - if(bufferObjectToBeUnloaded.isLoadedToHardware()){ - bufferObjectToBeUnloaded.unloadFromHardware(pGL11); - } - bufferObjectsLoaded.remove(bufferObjectToBeUnloaded); - bufferObjectsManaged.remove(bufferObjectToBeUnloaded); - } - } - } - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + private static final HashSet mBufferObjectsManaged = new HashSet(); + + private static final ArrayList mBufferObjectsLoaded = new ArrayList(); + + private static final ArrayList mBufferObjectsToBeLoaded = new ArrayList(); + private static final ArrayList mBufferObjectsToBeUnloaded = new ArrayList(); + + private static BufferObjectManager mActiveInstance = null; + + // =========================================================== + // Constructors + // =========================================================== + + public static BufferObjectManager getActiveInstance() { + return BufferObjectManager.mActiveInstance; + } + + public static void setActiveInstance(final BufferObjectManager pActiveInstance) { + BufferObjectManager.mActiveInstance = pActiveInstance; + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + public synchronized void clear() { + BufferObjectManager.mBufferObjectsToBeLoaded.clear(); + BufferObjectManager.mBufferObjectsLoaded.clear(); + BufferObjectManager.mBufferObjectsManaged.clear(); + } + + public synchronized void loadBufferObject(final BufferObject pBufferObject) { + if(pBufferObject == null) { + return; + } + + if(BufferObjectManager.mBufferObjectsManaged.contains(pBufferObject)) { + /* Just make sure it doesn't get deleted. */ + BufferObjectManager.mBufferObjectsToBeUnloaded.remove(pBufferObject); + } else { + BufferObjectManager.mBufferObjectsManaged.add(pBufferObject); + BufferObjectManager.mBufferObjectsToBeLoaded.add(pBufferObject); + } + } + + public synchronized void unloadBufferObject(final BufferObject pBufferObject) { + if(pBufferObject == null) { + return; + } + if(BufferObjectManager.mBufferObjectsManaged.contains(pBufferObject)) { + if(BufferObjectManager.mBufferObjectsLoaded.contains(pBufferObject)) { + BufferObjectManager.mBufferObjectsToBeUnloaded.add(pBufferObject); + } else if(BufferObjectManager.mBufferObjectsToBeLoaded.remove(pBufferObject)) { + BufferObjectManager.mBufferObjectsManaged.remove(pBufferObject); + } + } + } + + public void loadBufferObjects(final BufferObject... pBufferObjects) { + for(int i = pBufferObjects.length - 1; i >= 0; i--) { + this.loadBufferObject(pBufferObjects[i]); + } + } + + public void unloadBufferObjects(final BufferObject... pBufferObjects) { + for(int i = pBufferObjects.length - 1; i >= 0; i--) { + this.unloadBufferObject(pBufferObjects[i]); + } + } + + public synchronized void reloadBufferObjects() { + final ArrayList loadedBufferObjects = BufferObjectManager.mBufferObjectsLoaded; + for(int i = loadedBufferObjects.size() - 1; i >= 0; i--) { + loadedBufferObjects.get(i).setLoadedToHardware(false); + } + + BufferObjectManager.mBufferObjectsToBeLoaded.addAll(loadedBufferObjects); + + loadedBufferObjects.clear(); + } + + public synchronized void updateBufferObjects(final GL11 pGL11) { + final HashSet bufferObjectsManaged = BufferObjectManager.mBufferObjectsManaged; + final ArrayList bufferObjectsLoaded = BufferObjectManager.mBufferObjectsLoaded; + final ArrayList bufferObjectsToBeLoaded = BufferObjectManager.mBufferObjectsToBeLoaded; + final ArrayList bufferObjectsToBeUnloaded = BufferObjectManager.mBufferObjectsToBeUnloaded; + + /* First load pending BufferObjects. */ + final int bufferObjectToBeLoadedCount = bufferObjectsToBeLoaded.size(); + + if(bufferObjectToBeLoadedCount > 0) { + for(int i = bufferObjectToBeLoadedCount - 1; i >= 0; i--) { + final BufferObject bufferObjectToBeLoaded = bufferObjectsToBeLoaded.get(i); + if(!bufferObjectToBeLoaded.isLoadedToHardware()) { + bufferObjectToBeLoaded.loadToHardware(pGL11); + bufferObjectToBeLoaded.setHardwareBufferNeedsUpdate(); + } + bufferObjectsLoaded.add(bufferObjectToBeLoaded); + } + + bufferObjectsToBeLoaded.clear(); + } + + /* Then unload pending BufferObjects. */ + final int bufferObjectsToBeUnloadedCount = bufferObjectsToBeUnloaded.size(); + + if(bufferObjectsToBeUnloadedCount > 0){ + for(int i = bufferObjectsToBeUnloadedCount - 1; i >= 0; i--){ + final BufferObject bufferObjectToBeUnloaded = bufferObjectsToBeUnloaded.remove(i); + if(bufferObjectToBeUnloaded.isLoadedToHardware()){ + bufferObjectToBeUnloaded.unloadFromHardware(pGL11); + } + bufferObjectsLoaded.remove(bufferObjectToBeUnloaded); + bufferObjectsManaged.remove(bufferObjectToBeUnloaded); + } + } + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/opengl/font/Font.java b/AndEngine/src/org/anddev/andengine/opengl/font/Font.java index 6591f974..1399f0eb 100644 --- a/AndEngine/src/org/anddev/andengine/opengl/font/Font.java +++ b/AndEngine/src/org/anddev/andengine/opengl/font/Font.java @@ -26,207 +26,207 @@ * @since 10:39:33 - 03.04.2010 */ public class Font { - // =========================================================== - // Constants - // =========================================================== - - protected static final float LETTER_LEFT_OFFSET = 0; - protected static final int LETTER_EXTRA_WIDTH = 10; - - protected final static int PADDING = 1; - - // =========================================================== - // Fields - // =========================================================== - - private final ITexture mTexture; - private final float mTextureWidth; - private final float mTextureHeight; - private int mCurrentTextureX = 0; - private int mCurrentTextureY = 0; - - private final SparseArray mManagedCharacterToLetterMap = new SparseArray(); - private final ArrayList mLettersPendingToBeDrawnToTexture = new ArrayList(); - - protected final Paint mPaint; - private final Paint mBackgroundPaint; - - protected final FontMetrics mFontMetrics; - private final int mLineHeight; - private final int mLineGap; - - private final Size mCreateLetterTemporarySize = new Size(); - private final Rect mGetLetterBitmapTemporaryRect = new Rect(); - private final Rect mGetStringWidthTemporaryRect = new Rect(); - private final Rect mGetLetterBoundsTemporaryRect = new Rect(); - private final float[] mTemporaryTextWidthFetchers = new float[1]; - - protected final Canvas mCanvas = new Canvas(); - - // =========================================================== - // Constructors - // =========================================================== - - public Font(final ITexture pTexture, final Typeface pTypeface, final float pSize, final boolean pAntiAlias, final int pColor) { - this.mTexture = pTexture; - this.mTextureWidth = pTexture.getWidth(); - this.mTextureHeight = pTexture.getHeight(); - - this.mPaint = new Paint(); - this.mPaint.setTypeface(pTypeface); - this.mPaint.setColor(pColor); - this.mPaint.setTextSize(pSize); - this.mPaint.setAntiAlias(pAntiAlias); - - this.mBackgroundPaint = new Paint(); - this.mBackgroundPaint.setColor(Color.TRANSPARENT); - this.mBackgroundPaint.setStyle(Style.FILL); - - this.mFontMetrics = this.mPaint.getFontMetrics(); - this.mLineHeight = (int) Math.ceil(Math.abs(this.mFontMetrics.ascent) + Math.abs(this.mFontMetrics.descent)) + (PADDING * 2); - this.mLineGap = (int) (Math.ceil(this.mFontMetrics.leading)); - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - public int getLineGap() { - return this.mLineGap; - } - - public int getLineHeight() { - return this.mLineHeight; - } - - public ITexture getTexture() { - return this.mTexture; - } - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - // =========================================================== - // Methods - // =========================================================== - - public synchronized void reload() { - final ArrayList lettersPendingToBeDrawnToTexture = this.mLettersPendingToBeDrawnToTexture; - final SparseArray managedCharacterToLetterMap = this.mManagedCharacterToLetterMap; - - /* Make all letters redraw to the texture. */ - for(int i = managedCharacterToLetterMap.size() - 1; i >= 0; i--) { - lettersPendingToBeDrawnToTexture.add(managedCharacterToLetterMap.valueAt(i)); - } - } - - private int getLetterAdvance(final char pCharacter) { - this.mPaint.getTextWidths(String.valueOf(pCharacter), this.mTemporaryTextWidthFetchers); - return (int) (Math.ceil(this.mTemporaryTextWidthFetchers[0])); - } - - private Bitmap getLetterBitmap(final char pCharacter) { - final Rect getLetterBitmapTemporaryRect = this.mGetLetterBitmapTemporaryRect; - final String characterAsString = String.valueOf(pCharacter); - this.mPaint.getTextBounds(characterAsString, 0, 1, getLetterBitmapTemporaryRect); - - getLetterBitmapTemporaryRect.right += PADDING * 2; - - final int lineHeight = this.getLineHeight(); - final Bitmap bitmap = Bitmap.createBitmap(getLetterBitmapTemporaryRect.width() == 0 ? 1 + (2 * PADDING) : getLetterBitmapTemporaryRect.width() + LETTER_EXTRA_WIDTH, lineHeight, Bitmap.Config.ARGB_8888); - this.mCanvas.setBitmap(bitmap); - - /* Make background transparent. */ - this.mCanvas.drawRect(0, 0, bitmap.getWidth(), bitmap.getHeight(), this.mBackgroundPaint); - - /* Actually draw the character. */ - this.drawCharacterString(characterAsString); - - return bitmap; - } - - protected void drawCharacterString(final String pCharacterAsString) { - this.mCanvas.drawText(pCharacterAsString, LETTER_LEFT_OFFSET + PADDING, -this.mFontMetrics.ascent + PADDING, this.mPaint); - } - - public int getStringWidth(final String pText) { - this.mPaint.getTextBounds(pText, 0, pText.length(), this.mGetStringWidthTemporaryRect); - return this.mGetStringWidthTemporaryRect.width(); - } - - private void getLetterBounds(final char pCharacter, final Size pSize) { - this.mPaint.getTextBounds(String.valueOf(pCharacter), 0, 1, this.mGetLetterBoundsTemporaryRect); - pSize.set(this.mGetLetterBoundsTemporaryRect.width() + LETTER_EXTRA_WIDTH + (2 * PADDING), this.getLineHeight()); - } - - public void prepareLetters(final char ... pCharacters) { - for(final char character : pCharacters) { - this.getLetter(character); - } - } - - public synchronized Letter getLetter(final char pCharacter) { - final SparseArray managedCharacterToLetterMap = this.mManagedCharacterToLetterMap; - Letter letter = managedCharacterToLetterMap.get(pCharacter); - if (letter == null) { - letter = this.createLetter(pCharacter); - - this.mLettersPendingToBeDrawnToTexture.add(letter); - managedCharacterToLetterMap.put(pCharacter, letter); - } - return letter; - } - - private Letter createLetter(final char pCharacter) { - final float textureWidth = this.mTextureWidth; - final float textureHeight = this.mTextureHeight; - - final Size createLetterTemporarySize = this.mCreateLetterTemporarySize; - this.getLetterBounds(pCharacter, createLetterTemporarySize); - - final float letterWidth = createLetterTemporarySize.getWidth(); - final float letterHeight = createLetterTemporarySize.getHeight(); - - if (this.mCurrentTextureX + letterWidth >= textureWidth) { - this.mCurrentTextureX = 0; - this.mCurrentTextureY += this.getLineGap() + this.getLineHeight(); - } - - final float letterTextureX = this.mCurrentTextureX / textureWidth; - final float letterTextureY = this.mCurrentTextureY / textureHeight; - final float letterTextureWidth = letterWidth / textureWidth; - final float letterTextureHeight = letterHeight / textureHeight; - - final Letter letter = new Letter(pCharacter, this.getLetterAdvance(pCharacter), (int)letterWidth, (int)letterHeight, letterTextureX, letterTextureY, letterTextureWidth, letterTextureHeight); - this.mCurrentTextureX += letterWidth; - - return letter; - } - - public synchronized void update(final GL10 pGL) { - final ArrayList lettersPendingToBeDrawnToTexture = this.mLettersPendingToBeDrawnToTexture; - if(lettersPendingToBeDrawnToTexture.size() > 0) { - this.mTexture.bind(pGL); - - final float textureWidth = this.mTextureWidth; - final float textureHeight = this.mTextureHeight; - - for(int i = lettersPendingToBeDrawnToTexture.size() - 1; i >= 0; i--) { - final Letter letter = lettersPendingToBeDrawnToTexture.get(i); - final Bitmap bitmap = this.getLetterBitmap(letter.mCharacter); - - // TODO What about premultiplyalpha of the textureOptions? - GLUtils.texSubImage2D(GL10.GL_TEXTURE_2D, 0, (int)(letter.mTextureX * textureWidth), (int)(letter.mTextureY * textureHeight), bitmap); - - bitmap.recycle(); - } - lettersPendingToBeDrawnToTexture.clear(); - System.gc(); - } - } - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== -} \ No newline at end of file + // =========================================================== + // Constants + // =========================================================== + + protected static final float LETTER_LEFT_OFFSET = 0; + protected static final int LETTER_EXTRA_WIDTH = 10; + + protected final static int PADDING = 1; + + // =========================================================== + // Fields + // =========================================================== + + private final ITexture mTexture; + private final float mTextureWidth; + private final float mTextureHeight; + private int mCurrentTextureX = 0; + private int mCurrentTextureY = 0; + + private final SparseArray mManagedCharacterToLetterMap = new SparseArray(); + private final ArrayList mLettersPendingToBeDrawnToTexture = new ArrayList(); + + protected final Paint mPaint; + private final Paint mBackgroundPaint; + + protected final FontMetrics mFontMetrics; + private final int mLineHeight; + private final int mLineGap; + + private final Size mCreateLetterTemporarySize = new Size(); + private final Rect mGetLetterBitmapTemporaryRect = new Rect(); + private final Rect mGetStringWidthTemporaryRect = new Rect(); + private final Rect mGetLetterBoundsTemporaryRect = new Rect(); + private final float[] mTemporaryTextWidthFetchers = new float[1]; + + protected final Canvas mCanvas = new Canvas(); + + // =========================================================== + // Constructors + // =========================================================== + + public Font(final ITexture pTexture, final Typeface pTypeface, final float pSize, final boolean pAntiAlias, final int pColor) { + this.mTexture = pTexture; + this.mTextureWidth = pTexture.getWidth(); + this.mTextureHeight = pTexture.getHeight(); + + this.mPaint = new Paint(); + this.mPaint.setTypeface(pTypeface); + this.mPaint.setColor(pColor); + this.mPaint.setTextSize(pSize); + this.mPaint.setAntiAlias(pAntiAlias); + + this.mBackgroundPaint = new Paint(); + this.mBackgroundPaint.setColor(Color.TRANSPARENT); + this.mBackgroundPaint.setStyle(Style.FILL); + + this.mFontMetrics = this.mPaint.getFontMetrics(); + this.mLineHeight = (int) Math.ceil(Math.abs(this.mFontMetrics.ascent) + Math.abs(this.mFontMetrics.descent)) + (PADDING * 2); + this.mLineGap = (int) (Math.ceil(this.mFontMetrics.leading)); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + public int getLineGap() { + return this.mLineGap; + } + + public int getLineHeight() { + return this.mLineHeight; + } + + public ITexture getTexture() { + return this.mTexture; + } + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + public synchronized void reload() { + final ArrayList lettersPendingToBeDrawnToTexture = this.mLettersPendingToBeDrawnToTexture; + final SparseArray managedCharacterToLetterMap = this.mManagedCharacterToLetterMap; + + /* Make all letters redraw to the texture. */ + for(int i = managedCharacterToLetterMap.size() - 1; i >= 0; i--) { + lettersPendingToBeDrawnToTexture.add(managedCharacterToLetterMap.valueAt(i)); + } + } + + private int getLetterAdvance(final char pCharacter) { + this.mPaint.getTextWidths(String.valueOf(pCharacter), this.mTemporaryTextWidthFetchers); + return (int) (Math.ceil(this.mTemporaryTextWidthFetchers[0])); + } + + private Bitmap getLetterBitmap(final char pCharacter) { + final Rect getLetterBitmapTemporaryRect = this.mGetLetterBitmapTemporaryRect; + final String characterAsString = String.valueOf(pCharacter); + this.mPaint.getTextBounds(characterAsString, 0, 1, getLetterBitmapTemporaryRect); + + getLetterBitmapTemporaryRect.right += PADDING * 2; + + final int lineHeight = this.getLineHeight(); + final Bitmap bitmap = Bitmap.createBitmap(getLetterBitmapTemporaryRect.width() == 0 ? 1 + (2 * PADDING) : getLetterBitmapTemporaryRect.width() + LETTER_EXTRA_WIDTH, lineHeight, Bitmap.Config.ARGB_8888); + this.mCanvas.setBitmap(bitmap); + + /* Make background transparent. */ + this.mCanvas.drawRect(0, 0, bitmap.getWidth(), bitmap.getHeight(), this.mBackgroundPaint); + + /* Actually draw the character. */ + this.drawCharacterString(characterAsString); + + return bitmap; + } + + protected void drawCharacterString(final String pCharacterAsString) { + this.mCanvas.drawText(pCharacterAsString, LETTER_LEFT_OFFSET + PADDING, -this.mFontMetrics.ascent + PADDING, this.mPaint); + } + + public int getStringWidth(final String pText) { + this.mPaint.getTextBounds(pText, 0, pText.length(), this.mGetStringWidthTemporaryRect); + return this.mGetStringWidthTemporaryRect.width(); + } + + private void getLetterBounds(final char pCharacter, final Size pSize) { + this.mPaint.getTextBounds(String.valueOf(pCharacter), 0, 1, this.mGetLetterBoundsTemporaryRect); + pSize.set(this.mGetLetterBoundsTemporaryRect.width() + LETTER_EXTRA_WIDTH + (2 * PADDING), this.getLineHeight()); + } + + public void prepareLetters(final char ... pCharacters) { + for(final char character : pCharacters) { + this.getLetter(character); + } + } + + public synchronized Letter getLetter(final char pCharacter) { + final SparseArray managedCharacterToLetterMap = this.mManagedCharacterToLetterMap; + Letter letter = managedCharacterToLetterMap.get(pCharacter); + if (letter == null) { + letter = this.createLetter(pCharacter); + + this.mLettersPendingToBeDrawnToTexture.add(letter); + managedCharacterToLetterMap.put(pCharacter, letter); + } + return letter; + } + + private Letter createLetter(final char pCharacter) { + final float textureWidth = this.mTextureWidth; + final float textureHeight = this.mTextureHeight; + + final Size createLetterTemporarySize = this.mCreateLetterTemporarySize; + this.getLetterBounds(pCharacter, createLetterTemporarySize); + + final float letterWidth = createLetterTemporarySize.getWidth(); + final float letterHeight = createLetterTemporarySize.getHeight(); + + if (this.mCurrentTextureX + letterWidth >= textureWidth) { + this.mCurrentTextureX = 0; + this.mCurrentTextureY += this.getLineGap() + this.getLineHeight(); + } + + final float letterTextureX = this.mCurrentTextureX / textureWidth; + final float letterTextureY = this.mCurrentTextureY / textureHeight; + final float letterTextureWidth = letterWidth / textureWidth; + final float letterTextureHeight = letterHeight / textureHeight; + + final Letter letter = new Letter(pCharacter, this.getLetterAdvance(pCharacter), (int)letterWidth, (int)letterHeight, letterTextureX, letterTextureY, letterTextureWidth, letterTextureHeight); + this.mCurrentTextureX += letterWidth; + + return letter; + } + + public synchronized void update(final GL10 pGL) { + final ArrayList lettersPendingToBeDrawnToTexture = this.mLettersPendingToBeDrawnToTexture; + if(lettersPendingToBeDrawnToTexture.size() > 0) { + this.mTexture.bind(pGL); + + final float textureWidth = this.mTextureWidth; + final float textureHeight = this.mTextureHeight; + + for(int i = lettersPendingToBeDrawnToTexture.size() - 1; i >= 0; i--) { + final Letter letter = lettersPendingToBeDrawnToTexture.get(i); + final Bitmap bitmap = this.getLetterBitmap(letter.mCharacter); + + // TODO What about premultiplyalpha of the textureOptions? + GLUtils.texSubImage2D(GL10.GL_TEXTURE_2D, 0, (int)(letter.mTextureX * textureWidth), (int)(letter.mTextureY * textureHeight), bitmap); + + bitmap.recycle(); + } + lettersPendingToBeDrawnToTexture.clear(); + System.gc(); + } + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== +} diff --git a/AndEngine/src/org/anddev/andengine/opengl/font/FontFactory.java b/AndEngine/src/org/anddev/andengine/opengl/font/FontFactory.java index 5c404076..8cd6e280 100644 --- a/AndEngine/src/org/anddev/andengine/opengl/font/FontFactory.java +++ b/AndEngine/src/org/anddev/andengine/opengl/font/FontFactory.java @@ -13,72 +13,72 @@ * @since 17:17:28 - 16.06.2010 */ public class FontFactory { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - private static String sAssetBasePath = ""; - - // =========================================================== - // Constructors - // =========================================================== - - // =========================================================== - // Getter & Setter - // =========================================================== - - /** - * @param pAssetBasePath must end with '/' or have .length() == 0. - */ - public static void setAssetBasePath(final String pAssetBasePath) { - if(pAssetBasePath.endsWith("/") || pAssetBasePath.length() == 0) { - FontFactory.sAssetBasePath = pAssetBasePath; - } else { - throw new IllegalStateException("pAssetBasePath must end with '/' or be lenght zero."); - } - } - - public static void reset() { - FontFactory.setAssetBasePath(""); - } - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - // =========================================================== - // Methods - // =========================================================== - - public static Font create(final ITexture pTexture, final Typeface pTypeface, final float pSize, final boolean pAntiAlias, final int pColor) { - return new Font(pTexture, pTypeface, pSize, pAntiAlias, pColor); - } - - public static StrokeFont createStroke(final ITexture pTexture, final Typeface pTypeface, final float pSize, final boolean pAntiAlias, final int pColor, final float pStrokeWidth, final int pStrokeColor) { - return new StrokeFont(pTexture, pTypeface, pSize, pAntiAlias, pColor, pStrokeWidth, pStrokeColor); - } - - public static StrokeFont createStroke(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(pTexture, pTypeface, pSize, pAntiAlias, pColor, pStrokeWidth, pStrokeColor, pStrokeOnly); - } - - public static Font createFromAsset(final ITexture pTexture, final Context pContext, final String pAssetPath, final float pSize, final boolean pAntiAlias, final int pColor) { - return new Font(pTexture, Typeface.createFromAsset(pContext.getAssets(), FontFactory.sAssetBasePath + pAssetPath), pSize, pAntiAlias, pColor); - } - - public static StrokeFont createStrokeFromAsset(final ITexture pTexture, final Context pContext, final String pAssetPath, final float pSize, final boolean pAntiAlias, final int pColor, final float pStrokeWidth, final int pStrokeColor) { - return new StrokeFont(pTexture, Typeface.createFromAsset(pContext.getAssets(), FontFactory.sAssetBasePath + pAssetPath), pSize, pAntiAlias, pColor, pStrokeWidth, pStrokeColor); - } - - public static StrokeFont createStrokeFromAsset(final ITexture pTexture, final Context pContext, final String pAssetPath, final float pSize, final boolean pAntiAlias, final int pColor, final float pStrokeWidth, final int pStrokeColor, final boolean pStrokeOnly) { - return new StrokeFont(pTexture, Typeface.createFromAsset(pContext.getAssets(), FontFactory.sAssetBasePath + pAssetPath), pSize, pAntiAlias, pColor, pStrokeWidth, pStrokeColor, pStrokeOnly); - } - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + private static String sAssetBasePath = ""; + + // =========================================================== + // Constructors + // =========================================================== + + // =========================================================== + // Getter & Setter + // =========================================================== + + /** + * @param pAssetBasePath must end with '/' or have .length() == 0. + */ + public static void setAssetBasePath(final String pAssetBasePath) { + if(pAssetBasePath.endsWith("/") || pAssetBasePath.length() == 0) { + FontFactory.sAssetBasePath = pAssetBasePath; + } else { + throw new IllegalStateException("pAssetBasePath must end with '/' or be lenght zero."); + } + } + + public static void reset() { + FontFactory.setAssetBasePath(""); + } + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + public static Font create(final ITexture pTexture, final Typeface pTypeface, final float pSize, final boolean pAntiAlias, final int pColor) { + return new Font(pTexture, pTypeface, pSize, pAntiAlias, pColor); + } + + public static StrokeFont createStroke(final ITexture pTexture, final Typeface pTypeface, final float pSize, final boolean pAntiAlias, final int pColor, final float pStrokeWidth, final int pStrokeColor) { + return new StrokeFont(pTexture, pTypeface, pSize, pAntiAlias, pColor, pStrokeWidth, pStrokeColor); + } + + public static StrokeFont createStroke(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(pTexture, pTypeface, pSize, pAntiAlias, pColor, pStrokeWidth, pStrokeColor, pStrokeOnly); + } + + public static Font createFromAsset(final ITexture pTexture, final Context pContext, final String pAssetPath, final float pSize, final boolean pAntiAlias, final int pColor) { + return new Font(pTexture, Typeface.createFromAsset(pContext.getAssets(), FontFactory.sAssetBasePath + pAssetPath), pSize, pAntiAlias, pColor); + } + + public static StrokeFont createStrokeFromAsset(final ITexture pTexture, final Context pContext, final String pAssetPath, final float pSize, final boolean pAntiAlias, final int pColor, final float pStrokeWidth, final int pStrokeColor) { + return new StrokeFont(pTexture, Typeface.createFromAsset(pContext.getAssets(), FontFactory.sAssetBasePath + pAssetPath), pSize, pAntiAlias, pColor, pStrokeWidth, pStrokeColor); + } + + public static StrokeFont createStrokeFromAsset(final ITexture pTexture, final Context pContext, final String pAssetPath, final float pSize, final boolean pAntiAlias, final int pColor, final float pStrokeWidth, final int pStrokeColor, final boolean pStrokeOnly) { + return new StrokeFont(pTexture, Typeface.createFromAsset(pContext.getAssets(), FontFactory.sAssetBasePath + pAssetPath), pSize, pAntiAlias, pColor, pStrokeWidth, pStrokeColor, pStrokeOnly); + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/opengl/font/FontLibrary.java b/AndEngine/src/org/anddev/andengine/opengl/font/FontLibrary.java index 3c182ba9..8f925879 100644 --- a/AndEngine/src/org/anddev/andengine/opengl/font/FontLibrary.java +++ b/AndEngine/src/org/anddev/andengine/opengl/font/FontLibrary.java @@ -12,49 +12,49 @@ * @since 11:52:26 - 20.08.2010 */ public class FontLibrary extends Library { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - // =========================================================== - // Constructors - // =========================================================== - - public FontLibrary() { - super(); - } - - public FontLibrary(final int pInitialCapacity) { - super(pInitialCapacity); - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - // =========================================================== - // Methods - // =========================================================== - - void loadFonts(final FontManager pFontManager) { - final SparseArray items = this.mItems; - for(int i = items.size() - 1; i >= 0; i--) { - final Font font = items.valueAt(i); - if(font != null) { - pFontManager.loadFont(font); - } - } - } - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + // =========================================================== + // Constructors + // =========================================================== + + public FontLibrary() { + super(); + } + + public FontLibrary(final int pInitialCapacity) { + super(pInitialCapacity); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + void loadFonts(final FontManager pFontManager) { + final SparseArray items = this.mItems; + for(int i = items.size() - 1; i >= 0; i--) { + final Font font = items.valueAt(i); + if(font != null) { + pFontManager.loadFont(font); + } + } + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/opengl/font/FontManager.java b/AndEngine/src/org/anddev/andengine/opengl/font/FontManager.java index a8b6f289..e0f61cac 100644 --- a/AndEngine/src/org/anddev/andengine/opengl/font/FontManager.java +++ b/AndEngine/src/org/anddev/andengine/opengl/font/FontManager.java @@ -13,71 +13,71 @@ * @since 17:48:46 - 08.03.2010 */ public class FontManager { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - private final ArrayList mFontsManaged = new ArrayList(); - - // =========================================================== - // Constructors - // =========================================================== - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - // =========================================================== - // Methods - // =========================================================== - - public synchronized void clear() { - this.mFontsManaged.clear(); - } - - public synchronized void loadFont(final Font pFont) { - if(pFont == null) { - throw new IllegalArgumentException("pFont must not be null!"); - } - this.mFontsManaged.add(pFont); - } - - public synchronized void loadFonts(final FontLibrary pFontLibrary) { - pFontLibrary.loadFonts(this); - } - - public void loadFonts(final Font ... pFonts) { - for(int i = pFonts.length - 1; i >= 0; i--) { - this.loadFont(pFonts[i]); - } - } - - public synchronized void updateFonts(final GL10 pGL) { - final ArrayList fonts = this.mFontsManaged; - final int fontCount = fonts.size(); - if(fontCount > 0){ - for(int i = fontCount - 1; i >= 0; i--){ - fonts.get(i).update(pGL); - } - } - } - - public synchronized void reloadFonts() { - final ArrayList managedFonts = this.mFontsManaged; - for(int i = managedFonts.size() - 1; i >= 0; i--) { - managedFonts.get(i).reload(); - } - } - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + private final ArrayList mFontsManaged = new ArrayList(); + + // =========================================================== + // Constructors + // =========================================================== + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + public synchronized void clear() { + this.mFontsManaged.clear(); + } + + public synchronized void loadFont(final Font pFont) { + if(pFont == null) { + throw new IllegalArgumentException("pFont must not be null!"); + } + this.mFontsManaged.add(pFont); + } + + public synchronized void loadFonts(final FontLibrary pFontLibrary) { + pFontLibrary.loadFonts(this); + } + + public void loadFonts(final Font ... pFonts) { + for(int i = pFonts.length - 1; i >= 0; i--) { + this.loadFont(pFonts[i]); + } + } + + public synchronized void updateFonts(final GL10 pGL) { + final ArrayList fonts = this.mFontsManaged; + final int fontCount = fonts.size(); + if(fontCount > 0){ + for(int i = fontCount - 1; i >= 0; i--){ + fonts.get(i).update(pGL); + } + } + } + + public synchronized void reloadFonts() { + final ArrayList managedFonts = this.mFontsManaged; + for(int i = managedFonts.size() - 1; i >= 0; i--) { + managedFonts.get(i).reload(); + } + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/opengl/font/Letter.java b/AndEngine/src/org/anddev/andengine/opengl/font/Letter.java index ebb6d74f..905ba98c 100644 --- a/AndEngine/src/org/anddev/andengine/opengl/font/Letter.java +++ b/AndEngine/src/org/anddev/andengine/opengl/font/Letter.java @@ -11,77 +11,77 @@ * @since 10:30:22 - 03.04.2010 */ public class Letter { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - public final int mAdvance; - public final int mWidth; - public final int mHeight; - public final float mTextureX; - public final float mTextureY; - public final float mTextureWidth; - public final float mTextureHeight; - public final char mCharacter; + public final int mAdvance; + public final int mWidth; + public final int mHeight; + public final float mTextureX; + public final float mTextureY; + public final float mTextureWidth; + public final float mTextureHeight; + public final char mCharacter; - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - Letter(final char pCharacter, final int pAdvance, final int pWidth, final int pHeight, final float pTextureX, final float pTextureY, final float pTextureWidth, final float pTextureHeight) { - this.mCharacter = pCharacter; - this.mAdvance = pAdvance; - this.mWidth = pWidth; - this.mHeight = pHeight; - this.mTextureX = pTextureX; - this.mTextureY = pTextureY; - this.mTextureWidth = pTextureWidth; - this.mTextureHeight = pTextureHeight; - } + Letter(final char pCharacter, final int pAdvance, final int pWidth, final int pHeight, final float pTextureX, final float pTextureY, final float pTextureWidth, final float pTextureHeight) { + this.mCharacter = pCharacter; + this.mAdvance = pAdvance; + this.mWidth = pWidth; + this.mHeight = pHeight; + this.mTextureX = pTextureX; + this.mTextureY = pTextureY; + this.mTextureWidth = pTextureWidth; + this.mTextureHeight = pTextureHeight; + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + this.mCharacter; - return result; - } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + this.mCharacter; + return result; + } - @Override - public boolean equals(final Object obj) { - if(this == obj) { - return true; - } - if(obj == null) { - return false; - } - if(this.getClass() != obj.getClass()) { - return false; - } - final Letter other = (Letter) obj; - if(this.mCharacter != other.mCharacter) { - return false; - } - return true; - } + @Override + public boolean equals(final Object obj) { + if(this == obj) { + return true; + } + if(obj == null) { + return false; + } + if(this.getClass() != obj.getClass()) { + return false; + } + final Letter other = (Letter) obj; + if(this.mCharacter != other.mCharacter) { + return false; + } + return true; + } - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== -} \ No newline at end of file + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== +} diff --git a/AndEngine/src/org/anddev/andengine/opengl/font/Size.java b/AndEngine/src/org/anddev/andengine/opengl/font/Size.java index 300ae8a4..488618c7 100644 --- a/AndEngine/src/org/anddev/andengine/opengl/font/Size.java +++ b/AndEngine/src/org/anddev/andengine/opengl/font/Size.java @@ -8,64 +8,64 @@ * @since 10:29:21 - 03.04.2010 */ class Size { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - private float mWidth; - private float mHeight; + private float mWidth; + private float mHeight; - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - public Size() { - this(0, 0); - } + public Size() { + this(0, 0); + } - public Size(final float pWidth, final float pHeight) { - this.setWidth(pWidth); - this.setHeight(pHeight); - } + public Size(final float pWidth, final float pHeight) { + this.setWidth(pWidth); + this.setHeight(pHeight); + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - public void setWidth(final float width) { - this.mWidth = width; - } + public void setWidth(final float width) { + this.mWidth = width; + } - public float getWidth() { - return this.mWidth; - } + public float getWidth() { + return this.mWidth; + } - public void setHeight(final float height) { - this.mHeight = height; - } + public void setHeight(final float height) { + this.mHeight = height; + } - public float getHeight() { - return this.mHeight; - } + public float getHeight() { + return this.mHeight; + } - public void set(final int pWidth, final int pHeight) { - this.setWidth(pWidth); - this.setHeight(pHeight); - } + public void set(final int pWidth, final int pHeight) { + this.setWidth(pWidth); + this.setHeight(pHeight); + } - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== -} \ No newline at end of file + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== +} diff --git a/AndEngine/src/org/anddev/andengine/opengl/font/StrokeFont.java b/AndEngine/src/org/anddev/andengine/opengl/font/StrokeFont.java index 8962f4c2..63e1bb75 100644 --- a/AndEngine/src/org/anddev/andengine/opengl/font/StrokeFont.java +++ b/AndEngine/src/org/anddev/andengine/opengl/font/StrokeFont.java @@ -14,59 +14,59 @@ * @since 10:39:33 - 03.04.2010 */ public class StrokeFont extends Font { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - private final Paint mStrokePaint; - private final boolean mStrokeOnly; + private final Paint mStrokePaint; + private final boolean mStrokeOnly; - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - public StrokeFont(final ITexture pTexture, final Typeface pTypeface, final float pSize, final boolean pAntiAlias, final int pColor, final float pStrokeWidth, final int pStrokeColor) { - this(pTexture, pTypeface, pSize, pAntiAlias, pColor, pStrokeWidth, pStrokeColor, false); - } + public StrokeFont(final ITexture pTexture, final Typeface pTypeface, final float pSize, final boolean pAntiAlias, final int pColor, final float pStrokeWidth, final int pStrokeColor) { + this(pTexture, pTypeface, pSize, pAntiAlias, pColor, pStrokeWidth, pStrokeColor, false); + } - public StrokeFont(final ITexture pTexture, final Typeface pTypeface, final float pSize, final boolean pAntiAlias, final int pColor, final float pStrokeWidth, final int pStrokeColor, final boolean pStrokeOnly) { - super(pTexture, pTypeface, pSize, pAntiAlias, pColor); - this.mStrokePaint = new Paint(); - this.mStrokePaint.setTypeface(pTypeface); - this.mStrokePaint.setStyle(Style.STROKE); - this.mStrokePaint.setStrokeWidth(pStrokeWidth); - this.mStrokePaint.setColor(pStrokeColor); - this.mStrokePaint.setTextSize(pSize); - this.mStrokePaint.setAntiAlias(pAntiAlias); + public StrokeFont(final ITexture pTexture, final Typeface pTypeface, final float pSize, final boolean pAntiAlias, final int pColor, final float pStrokeWidth, final int pStrokeColor, final boolean pStrokeOnly) { + super(pTexture, pTypeface, pSize, pAntiAlias, pColor); + this.mStrokePaint = new Paint(); + this.mStrokePaint.setTypeface(pTypeface); + this.mStrokePaint.setStyle(Style.STROKE); + this.mStrokePaint.setStrokeWidth(pStrokeWidth); + this.mStrokePaint.setColor(pStrokeColor); + this.mStrokePaint.setTextSize(pSize); + this.mStrokePaint.setAntiAlias(pAntiAlias); - this.mStrokeOnly = pStrokeOnly; - } + this.mStrokeOnly = pStrokeOnly; + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - @Override - protected void drawCharacterString(final String pCharacterAsString) { - if(!this.mStrokeOnly) { - super.drawCharacterString(pCharacterAsString); - } - this.mCanvas.drawText(pCharacterAsString, LETTER_LEFT_OFFSET, -this.mFontMetrics.ascent, this.mStrokePaint); - } + @Override + protected void drawCharacterString(final String pCharacterAsString) { + if(!this.mStrokeOnly) { + super.drawCharacterString(pCharacterAsString); + } + this.mCanvas.drawText(pCharacterAsString, LETTER_LEFT_OFFSET, -this.mFontMetrics.ascent, this.mStrokePaint); + } - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/opengl/texture/ITexture.java b/AndEngine/src/org/anddev/andengine/opengl/texture/ITexture.java index 20b9da93..ef024e47 100644 --- a/AndEngine/src/org/anddev/andengine/opengl/texture/ITexture.java +++ b/AndEngine/src/org/anddev/andengine/opengl/texture/ITexture.java @@ -15,74 +15,74 @@ * @since 15:01:03 - 11.07.2011 */ public interface ITexture { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Methods - // =========================================================== - - public int getWidth(); - public int getHeight(); - - public int getHardwareTextureID(); - - public boolean isLoadedToHardware(); - public void setLoadedToHardware(final boolean pLoadedToHardware); - - public boolean isUpdateOnHardwareNeeded(); - public void setUpdateOnHardwareNeeded(final boolean pUpdateOnHardwareNeeded); - - public void loadToHardware(final GL10 pGL) throws IOException; - public void unloadFromHardware(final GL10 pGL); - public void reloadToHardware(final GL10 pGL) throws IOException; - - public void bind(final GL10 pGL); - - public TextureOptions getTextureOptions(); - - public boolean hasTextureStateListener(); - public ITextureStateListener getTextureStateListener(); - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - public static interface ITextureStateListener { - // =========================================================== - // Final Fields - // =========================================================== - - // =========================================================== - // Methods - // =========================================================== - - public void onLoadedToHardware(final ITexture pTexture); - public void onUnloadedFromHardware(final ITexture pTexture); - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== - - public static class TextureStateAdapter implements ITextureStateListener { - @Override - public void onLoadedToHardware(final ITexture pTexture) { } - - @Override - public void onUnloadedFromHardware(final ITexture pTexture) { } - } - - public static class DebugTextureStateListener implements ITextureStateListener { - @Override - public void onLoadedToHardware(final ITexture pTexture) { - Debug.d("Texture loaded: " + pTexture.toString()); - } - - @Override - public void onUnloadedFromHardware(final ITexture pTexture) { - Debug.d("Texture unloaded: " + pTexture.toString()); - } - } - } -} \ No newline at end of file + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + public int getWidth(); + public int getHeight(); + + public int getHardwareTextureID(); + + public boolean isLoadedToHardware(); + public void setLoadedToHardware(final boolean pLoadedToHardware); + + public boolean isUpdateOnHardwareNeeded(); + public void setUpdateOnHardwareNeeded(final boolean pUpdateOnHardwareNeeded); + + public void loadToHardware(final GL10 pGL) throws IOException; + public void unloadFromHardware(final GL10 pGL); + public void reloadToHardware(final GL10 pGL) throws IOException; + + public void bind(final GL10 pGL); + + public TextureOptions getTextureOptions(); + + public boolean hasTextureStateListener(); + public ITextureStateListener getTextureStateListener(); + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + public static interface ITextureStateListener { + // =========================================================== + // Final Fields + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + public void onLoadedToHardware(final ITexture pTexture); + public void onUnloadedFromHardware(final ITexture pTexture); + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== + + public static class TextureStateAdapter implements ITextureStateListener { + @Override + public void onLoadedToHardware(final ITexture pTexture) { } + + @Override + public void onUnloadedFromHardware(final ITexture pTexture) { } + } + + public static class DebugTextureStateListener implements ITextureStateListener { + @Override + public void onLoadedToHardware(final ITexture pTexture) { + Debug.d("Texture loaded: " + pTexture.toString()); + } + + @Override + public void onUnloadedFromHardware(final ITexture pTexture) { + Debug.d("Texture unloaded: " + pTexture.toString()); + } + } + } +} diff --git a/AndEngine/src/org/anddev/andengine/opengl/texture/Texture.java b/AndEngine/src/org/anddev/andengine/opengl/texture/Texture.java index 6f52d0f1..a11c3615 100644 --- a/AndEngine/src/org/anddev/andengine/opengl/texture/Texture.java +++ b/AndEngine/src/org/anddev/andengine/opengl/texture/Texture.java @@ -15,228 +15,228 @@ * @since 14:55:02 - 08.03.2010 */ public abstract class Texture implements ITexture { - // =========================================================== - // Constants - // =========================================================== - - private static final int[] HARDWARETEXTUREID_FETCHER = new int[1]; - - // =========================================================== - // Fields - // =========================================================== - - protected final PixelFormat mPixelFormat; - protected final TextureOptions mTextureOptions; - - protected int mHardwareTextureID = -1; - protected boolean mLoadedToHardware; - protected boolean mUpdateOnHardwareNeeded = false; + // =========================================================== + // Constants + // =========================================================== + + private static final int[] HARDWARETEXTUREID_FETCHER = new int[1]; + + // =========================================================== + // Fields + // =========================================================== + + protected final PixelFormat mPixelFormat; + protected final TextureOptions mTextureOptions; + + protected int mHardwareTextureID = -1; + protected boolean mLoadedToHardware; + protected boolean mUpdateOnHardwareNeeded = false; - protected final ITextureStateListener mTextureStateListener; + protected final ITextureStateListener mTextureStateListener; - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - /** - * @param pPixelFormat - * @param pTextureOptions the (quality) settings of the Texture. - * @param pTextureStateListener to be informed when this {@link Texture} is loaded, unloaded or a {@link ITextureAtlasSource} failed to load. - */ - public Texture(final PixelFormat pPixelFormat, final TextureOptions pTextureOptions, final ITextureStateListener pTextureStateListener) throws IllegalArgumentException { - this.mPixelFormat = pPixelFormat; - this.mTextureOptions = pTextureOptions; - this.mTextureStateListener = pTextureStateListener; - } + /** + * @param pPixelFormat + * @param pTextureOptions the (quality) settings of the Texture. + * @param pTextureStateListener to be informed when this {@link Texture} is loaded, unloaded or a {@link ITextureAtlasSource} failed to load. + */ + public Texture(final PixelFormat pPixelFormat, final TextureOptions pTextureOptions, final ITextureStateListener pTextureStateListener) throws IllegalArgumentException { + this.mPixelFormat = pPixelFormat; + this.mTextureOptions = pTextureOptions; + this.mTextureStateListener = pTextureStateListener; + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - @Override - public int getHardwareTextureID() { - return this.mHardwareTextureID; - } + @Override + public int getHardwareTextureID() { + return this.mHardwareTextureID; + } - @Override - public boolean isLoadedToHardware() { - return this.mLoadedToHardware; - } - - @Override - public void setLoadedToHardware(final boolean pLoadedToHardware) { - this.mLoadedToHardware = pLoadedToHardware; - } + @Override + public boolean isLoadedToHardware() { + return this.mLoadedToHardware; + } + + @Override + public void setLoadedToHardware(final boolean pLoadedToHardware) { + this.mLoadedToHardware = pLoadedToHardware; + } - @Override - public boolean isUpdateOnHardwareNeeded() { - return this.mUpdateOnHardwareNeeded; - } + @Override + public boolean isUpdateOnHardwareNeeded() { + return this.mUpdateOnHardwareNeeded; + } - @Override - public void setUpdateOnHardwareNeeded(final boolean pUpdateOnHardwareNeeded) { - this.mUpdateOnHardwareNeeded = pUpdateOnHardwareNeeded; - } - - public PixelFormat getPixelFormat() { - return this.mPixelFormat; - } + @Override + public void setUpdateOnHardwareNeeded(final boolean pUpdateOnHardwareNeeded) { + this.mUpdateOnHardwareNeeded = pUpdateOnHardwareNeeded; + } + + public PixelFormat getPixelFormat() { + return this.mPixelFormat; + } - @Override - public TextureOptions getTextureOptions() { - return this.mTextureOptions; - } - - @Override - public ITextureStateListener getTextureStateListener() { - return this.mTextureStateListener; - } - - @Override - public boolean hasTextureStateListener() { - return this.mTextureStateListener != null; - } - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - protected abstract void writeTextureToHardware(final GL10 pGL) throws IOException; - - @Override - public void loadToHardware(final GL10 pGL) throws IOException { - GLHelper.enableTextures(pGL); - - this.generateHardwareTextureID(pGL); - - this.bindTextureOnHardware(pGL); - - this.applyTextureOptions(pGL); - - this.writeTextureToHardware(pGL); - - this.mUpdateOnHardwareNeeded = false; - this.mLoadedToHardware = true; - - if(this.mTextureStateListener != null) { - this.mTextureStateListener.onLoadedToHardware(this); - } - } - - @Override - public void unloadFromHardware(final GL10 pGL) { - GLHelper.enableTextures(pGL); - - this.deleteTextureOnHardware(pGL); - - this.mHardwareTextureID = -1; - - this.mLoadedToHardware = false; - - if(this.mTextureStateListener != null) { - this.mTextureStateListener.onUnloadedFromHardware(this); - } - } - - @Override - public void reloadToHardware(final GL10 pGL) throws IOException { - this.unloadFromHardware(pGL); - this.loadToHardware(pGL); - } - - @Override - public void bind(final GL10 pGL) { - GLHelper.bindTexture(pGL, this.mHardwareTextureID); - } - - // =========================================================== - // Methods - // =========================================================== - - protected void applyTextureOptions(final GL10 pGL) { - this.mTextureOptions.apply(pGL); - } - - protected void bindTextureOnHardware(final GL10 pGL) { - GLHelper.forceBindTexture(pGL, this.mHardwareTextureID); - } - - protected void deleteTextureOnHardware(final GL10 pGL) { - GLHelper.deleteTexture(pGL, this.mHardwareTextureID); - } - - protected void generateHardwareTextureID(final GL10 pGL) { - pGL.glGenTextures(1, Texture.HARDWARETEXTUREID_FETCHER, 0); - - this.mHardwareTextureID = Texture.HARDWARETEXTUREID_FETCHER[0]; - } - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== - - public enum PixelFormat { - // =========================================================== - // Elements - // =========================================================== + @Override + public TextureOptions getTextureOptions() { + return this.mTextureOptions; + } + + @Override + public ITextureStateListener getTextureStateListener() { + return this.mTextureStateListener; + } + + @Override + public boolean hasTextureStateListener() { + return this.mTextureStateListener != null; + } + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + protected abstract void writeTextureToHardware(final GL10 pGL) throws IOException; + + @Override + public void loadToHardware(final GL10 pGL) throws IOException { + GLHelper.enableTextures(pGL); + + this.generateHardwareTextureID(pGL); + + this.bindTextureOnHardware(pGL); + + this.applyTextureOptions(pGL); + + this.writeTextureToHardware(pGL); + + this.mUpdateOnHardwareNeeded = false; + this.mLoadedToHardware = true; + + if(this.mTextureStateListener != null) { + this.mTextureStateListener.onLoadedToHardware(this); + } + } + + @Override + public void unloadFromHardware(final GL10 pGL) { + GLHelper.enableTextures(pGL); + + this.deleteTextureOnHardware(pGL); + + this.mHardwareTextureID = -1; + + this.mLoadedToHardware = false; + + if(this.mTextureStateListener != null) { + this.mTextureStateListener.onUnloadedFromHardware(this); + } + } + + @Override + public void reloadToHardware(final GL10 pGL) throws IOException { + this.unloadFromHardware(pGL); + this.loadToHardware(pGL); + } + + @Override + public void bind(final GL10 pGL) { + GLHelper.bindTexture(pGL, this.mHardwareTextureID); + } + + // =========================================================== + // Methods + // =========================================================== + + protected void applyTextureOptions(final GL10 pGL) { + this.mTextureOptions.apply(pGL); + } + + protected void bindTextureOnHardware(final GL10 pGL) { + GLHelper.forceBindTexture(pGL, this.mHardwareTextureID); + } + + protected void deleteTextureOnHardware(final GL10 pGL) { + GLHelper.deleteTexture(pGL, this.mHardwareTextureID); + } + + protected void generateHardwareTextureID(final GL10 pGL) { + pGL.glGenTextures(1, Texture.HARDWARETEXTUREID_FETCHER, 0); + + this.mHardwareTextureID = Texture.HARDWARETEXTUREID_FETCHER[0]; + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== + + public enum PixelFormat { + // =========================================================== + // Elements + // =========================================================== - UNDEFINED(-1, -1, -1), - RGBA_4444(GL10.GL_RGBA, GL10.GL_UNSIGNED_SHORT_4_4_4_4, 16), - RGBA_5551(GL10.GL_RGBA, GL10.GL_UNSIGNED_SHORT_5_5_5_1, 16), - RGBA_8888(GL10.GL_RGBA, GL10.GL_UNSIGNED_BYTE, 32), - RGB_565(GL10.GL_RGB, GL10.GL_UNSIGNED_SHORT_5_6_5, 16), - A_8(GL10.GL_ALPHA, GL10.GL_UNSIGNED_BYTE, 8), - I_8(GL10.GL_LUMINANCE, GL10.GL_UNSIGNED_BYTE, 8), - AI_88(GL10.GL_LUMINANCE_ALPHA, GL10.GL_UNSIGNED_BYTE, 16); + UNDEFINED(-1, -1, -1), + RGBA_4444(GL10.GL_RGBA, GL10.GL_UNSIGNED_SHORT_4_4_4_4, 16), + RGBA_5551(GL10.GL_RGBA, GL10.GL_UNSIGNED_SHORT_5_5_5_1, 16), + RGBA_8888(GL10.GL_RGBA, GL10.GL_UNSIGNED_BYTE, 32), + RGB_565(GL10.GL_RGB, GL10.GL_UNSIGNED_SHORT_5_6_5, 16), + A_8(GL10.GL_ALPHA, GL10.GL_UNSIGNED_BYTE, 8), + I_8(GL10.GL_LUMINANCE, GL10.GL_UNSIGNED_BYTE, 8), + AI_88(GL10.GL_LUMINANCE_ALPHA, GL10.GL_UNSIGNED_BYTE, 16); - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - private final int mGLFormat; - private final int mGLType; - private final int mBitsPerPixel; + private final int mGLFormat; + private final int mGLType; + private final int mBitsPerPixel; - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - private PixelFormat(final int pGLFormat, final int pGLType, final int pBitsPerPixel) { - this.mGLFormat = pGLFormat; - this.mGLType = pGLType; - this.mBitsPerPixel = pBitsPerPixel; - } + private PixelFormat(final int pGLFormat, final int pGLType, final int pBitsPerPixel) { + this.mGLFormat = pGLFormat; + this.mGLType = pGLType; + this.mBitsPerPixel = pBitsPerPixel; + } - // =========================================================== - // Getter & Setter - // =========================================================== - - public int getGLFormat() { - return this.mGLFormat; - } - - public int getGLType() { - return this.mGLType; - } - - public int getBitsPerPixel() { - return this.mBitsPerPixel; - } - - // =========================================================== - // Methods from SuperClass/Interfaces - // =========================================================== - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== - } -} \ No newline at end of file + // =========================================================== + // Getter & Setter + // =========================================================== + + public int getGLFormat() { + return this.mGLFormat; + } + + public int getGLType() { + return this.mGLType; + } + + public int getBitsPerPixel() { + return this.mBitsPerPixel; + } + + // =========================================================== + // Methods from SuperClass/Interfaces + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== + } +} diff --git a/AndEngine/src/org/anddev/andengine/opengl/texture/TextureManager.java b/AndEngine/src/org/anddev/andengine/opengl/texture/TextureManager.java index 3613f73e..4ef16c5b 100644 --- a/AndEngine/src/org/anddev/andengine/opengl/texture/TextureManager.java +++ b/AndEngine/src/org/anddev/andengine/opengl/texture/TextureManager.java @@ -16,163 +16,163 @@ * @since 17:48:46 - 08.03.2010 */ public class TextureManager { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - private final HashSet mTexturesManaged = new HashSet(); - - private final ArrayList mTexturesLoaded = new ArrayList(); - - private final ArrayList mTexturesToBeLoaded = new ArrayList(); - private final ArrayList mTexturesToBeUnloaded = new ArrayList(); - - // =========================================================== - // Constructors - // =========================================================== - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - // =========================================================== - // Methods - // =========================================================== - - protected synchronized void clear() { - this.mTexturesToBeLoaded.clear(); - this.mTexturesLoaded.clear(); - this.mTexturesManaged.clear(); - } - - /** - * @param pTexture the {@link ITexture} to be loaded before the very next frame is drawn (Or prevent it from being unloaded then). - * @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(this.mTexturesManaged.contains(pTexture)) { - /* Just make sure it doesn't get deleted. */ - this.mTexturesToBeUnloaded.remove(pTexture); - return false; - } else { - this.mTexturesManaged.add(pTexture); - this.mTexturesToBeLoaded.add(pTexture); - return true; - } - } - - /** - * @param pTexture the {@link ITexture} to be unloaded before the very next frame is drawn (Or prevent it from being loaded then). - * @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(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)){ - this.mTexturesToBeUnloaded.add(pTexture); - } else if(this.mTexturesToBeLoaded.remove(pTexture)){ - this.mTexturesManaged.remove(pTexture); - } - return true; - } else { - return false; - } - } - - public void loadTextures(final ITexture ... pTextures) { - for(int i = pTextures.length - 1; i >= 0; i--) { - this.loadTexture(pTextures[i]); - } - } - - public void unloadTextures(final ITexture ... pTextures) { - for(int i = pTextures.length - 1; i >= 0; i--) { - this.unloadTexture(pTextures[i]); - } - } - - public synchronized void reloadTextures() { - final HashSet managedTextures = this.mTexturesManaged; - for(final ITexture texture : managedTextures) { // TODO Can the use of the iterator be avoided somehow? - texture.setLoadedToHardware(false); - } - - this.mTexturesToBeLoaded.addAll(this.mTexturesLoaded); // TODO Check if addAll uses iterator internally! - this.mTexturesLoaded.clear(); - - this.mTexturesManaged.removeAll(this.mTexturesToBeUnloaded); // TODO Check if removeAll uses iterator internally! - this.mTexturesToBeUnloaded.clear(); - } - - public synchronized void updateTextures(final GL10 pGL) { - final HashSet texturesManaged = this.mTexturesManaged; - final ArrayList texturesLoaded = this.mTexturesLoaded; - final ArrayList texturesToBeLoaded = this.mTexturesToBeLoaded; - final ArrayList texturesToBeUnloaded = this.mTexturesToBeUnloaded; - - /* First reload Textures that need to be updated. */ - final int textursLoadedCount = texturesLoaded.size(); - - if(textursLoadedCount > 0){ - for(int i = textursLoadedCount - 1; i >= 0; i--){ - final ITexture textureToBeReloaded = texturesLoaded.get(i); - if(textureToBeReloaded.isUpdateOnHardwareNeeded()){ - try { - textureToBeReloaded.reloadToHardware(pGL); - } catch(IOException e) { - Debug.e(e); - } - } - } - } - - /* Then load pending Textures. */ - final int texturesToBeLoadedCount = texturesToBeLoaded.size(); - - if(texturesToBeLoadedCount > 0){ - for(int i = texturesToBeLoadedCount - 1; i >= 0; i--){ - final ITexture textureToBeLoaded = texturesToBeLoaded.remove(i); - if(!textureToBeLoaded.isLoadedToHardware()){ - try { - textureToBeLoaded.loadToHardware(pGL); - } catch(IOException e) { - Debug.e(e); - } - } - texturesLoaded.add(textureToBeLoaded); - } - } - - /* Then unload pending Textures. */ - final int texturesToBeUnloadedCount = texturesToBeUnloaded.size(); - - if(texturesToBeUnloadedCount > 0){ - for(int i = texturesToBeUnloadedCount - 1; i >= 0; i--){ - final ITexture textureToBeUnloaded = texturesToBeUnloaded.remove(i); - if(textureToBeUnloaded.isLoadedToHardware()){ - textureToBeUnloaded.unloadFromHardware(pGL); - } - texturesLoaded.remove(textureToBeUnloaded); - texturesManaged.remove(textureToBeUnloaded); - } - } - - /* Finally invoke the GC if anything has changed. */ - if(texturesToBeLoadedCount > 0 || texturesToBeUnloadedCount > 0){ - System.gc(); - } - } - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + private final HashSet mTexturesManaged = new HashSet(); + + private final ArrayList mTexturesLoaded = new ArrayList(); + + private final ArrayList mTexturesToBeLoaded = new ArrayList(); + private final ArrayList mTexturesToBeUnloaded = new ArrayList(); + + // =========================================================== + // Constructors + // =========================================================== + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + protected synchronized void clear() { + this.mTexturesToBeLoaded.clear(); + this.mTexturesLoaded.clear(); + this.mTexturesManaged.clear(); + } + + /** + * @param pTexture the {@link ITexture} to be loaded before the very next frame is drawn (Or prevent it from being unloaded then). + * @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(this.mTexturesManaged.contains(pTexture)) { + /* Just make sure it doesn't get deleted. */ + this.mTexturesToBeUnloaded.remove(pTexture); + return false; + } else { + this.mTexturesManaged.add(pTexture); + this.mTexturesToBeLoaded.add(pTexture); + return true; + } + } + + /** + * @param pTexture the {@link ITexture} to be unloaded before the very next frame is drawn (Or prevent it from being loaded then). + * @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(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)){ + this.mTexturesToBeUnloaded.add(pTexture); + } else if(this.mTexturesToBeLoaded.remove(pTexture)){ + this.mTexturesManaged.remove(pTexture); + } + return true; + } else { + return false; + } + } + + public void loadTextures(final ITexture ... pTextures) { + for(int i = pTextures.length - 1; i >= 0; i--) { + this.loadTexture(pTextures[i]); + } + } + + public void unloadTextures(final ITexture ... pTextures) { + for(int i = pTextures.length - 1; i >= 0; i--) { + this.unloadTexture(pTextures[i]); + } + } + + public synchronized void reloadTextures() { + final HashSet managedTextures = this.mTexturesManaged; + for(final ITexture texture : managedTextures) { // TODO Can the use of the iterator be avoided somehow? + texture.setLoadedToHardware(false); + } + + this.mTexturesToBeLoaded.addAll(this.mTexturesLoaded); // TODO Check if addAll uses iterator internally! + this.mTexturesLoaded.clear(); + + this.mTexturesManaged.removeAll(this.mTexturesToBeUnloaded); // TODO Check if removeAll uses iterator internally! + this.mTexturesToBeUnloaded.clear(); + } + + public synchronized void updateTextures(final GL10 pGL) { + final HashSet texturesManaged = this.mTexturesManaged; + final ArrayList texturesLoaded = this.mTexturesLoaded; + final ArrayList texturesToBeLoaded = this.mTexturesToBeLoaded; + final ArrayList texturesToBeUnloaded = this.mTexturesToBeUnloaded; + + /* First reload Textures that need to be updated. */ + final int textursLoadedCount = texturesLoaded.size(); + + if(textursLoadedCount > 0){ + for(int i = textursLoadedCount - 1; i >= 0; i--){ + final ITexture textureToBeReloaded = texturesLoaded.get(i); + if(textureToBeReloaded.isUpdateOnHardwareNeeded()){ + try { + textureToBeReloaded.reloadToHardware(pGL); + } catch(IOException e) { + Debug.e(e); + } + } + } + } + + /* Then load pending Textures. */ + final int texturesToBeLoadedCount = texturesToBeLoaded.size(); + + if(texturesToBeLoadedCount > 0){ + for(int i = texturesToBeLoadedCount - 1; i >= 0; i--){ + final ITexture textureToBeLoaded = texturesToBeLoaded.remove(i); + if(!textureToBeLoaded.isLoadedToHardware()){ + try { + textureToBeLoaded.loadToHardware(pGL); + } catch(IOException e) { + Debug.e(e); + } + } + texturesLoaded.add(textureToBeLoaded); + } + } + + /* Then unload pending Textures. */ + final int texturesToBeUnloadedCount = texturesToBeUnloaded.size(); + + if(texturesToBeUnloadedCount > 0){ + for(int i = texturesToBeUnloadedCount - 1; i >= 0; i--){ + final ITexture textureToBeUnloaded = texturesToBeUnloaded.remove(i); + if(textureToBeUnloaded.isLoadedToHardware()){ + textureToBeUnloaded.unloadFromHardware(pGL); + } + texturesLoaded.remove(textureToBeUnloaded); + texturesManaged.remove(textureToBeUnloaded); + } + } + + /* Finally invoke the GC if anything has changed. */ + if(texturesToBeLoadedCount > 0 || texturesToBeUnloadedCount > 0){ + System.gc(); + } + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/opengl/texture/TextureOptions.java b/AndEngine/src/org/anddev/andengine/opengl/texture/TextureOptions.java index b52ce417..23ef5360 100644 --- a/AndEngine/src/org/anddev/andengine/opengl/texture/TextureOptions.java +++ b/AndEngine/src/org/anddev/andengine/opengl/texture/TextureOptions.java @@ -10,65 +10,65 @@ * @since 13:00:09 - 05.04.2010 */ public class TextureOptions { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - public static final TextureOptions NEAREST = new TextureOptions(GL10.GL_NEAREST, GL10.GL_NEAREST, GL10.GL_CLAMP_TO_EDGE, GL10.GL_CLAMP_TO_EDGE, false); - public static final TextureOptions BILINEAR = new TextureOptions(GL10.GL_LINEAR, GL10.GL_LINEAR, GL10.GL_CLAMP_TO_EDGE, GL10.GL_CLAMP_TO_EDGE, false); - public static final TextureOptions REPEATING_NEAREST = new TextureOptions(GL10.GL_NEAREST, GL10.GL_NEAREST, GL10.GL_REPEAT, GL10.GL_REPEAT, false); - public static final TextureOptions REPEATING_BILINEAR = new TextureOptions(GL10.GL_LINEAR, GL10.GL_LINEAR, GL10.GL_REPEAT, GL10.GL_REPEAT, false); + public static final TextureOptions NEAREST = new TextureOptions(GL10.GL_NEAREST, GL10.GL_NEAREST, GL10.GL_CLAMP_TO_EDGE, GL10.GL_CLAMP_TO_EDGE, false); + public static final TextureOptions BILINEAR = new TextureOptions(GL10.GL_LINEAR, GL10.GL_LINEAR, GL10.GL_CLAMP_TO_EDGE, GL10.GL_CLAMP_TO_EDGE, false); + public static final TextureOptions REPEATING_NEAREST = new TextureOptions(GL10.GL_NEAREST, GL10.GL_NEAREST, GL10.GL_REPEAT, GL10.GL_REPEAT, false); + public static final TextureOptions REPEATING_BILINEAR = new TextureOptions(GL10.GL_LINEAR, GL10.GL_LINEAR, GL10.GL_REPEAT, GL10.GL_REPEAT, false); - public static final TextureOptions NEAREST_PREMULTIPLYALPHA = new TextureOptions(GL10.GL_NEAREST, GL10.GL_NEAREST, GL10.GL_CLAMP_TO_EDGE, GL10.GL_CLAMP_TO_EDGE, true); - public static final TextureOptions BILINEAR_PREMULTIPLYALPHA = new TextureOptions(GL10.GL_LINEAR, GL10.GL_LINEAR, GL10.GL_CLAMP_TO_EDGE, GL10.GL_CLAMP_TO_EDGE, true); - public static final TextureOptions REPEATING_NEAREST_PREMULTIPLYALPHA = new TextureOptions(GL10.GL_NEAREST, GL10.GL_NEAREST, GL10.GL_REPEAT, GL10.GL_REPEAT, true); - public static final TextureOptions REPEATING_BILINEAR_PREMULTIPLYALPHA = new TextureOptions(GL10.GL_LINEAR, GL10.GL_LINEAR, GL10.GL_REPEAT, GL10.GL_REPEAT, true); + public static final TextureOptions NEAREST_PREMULTIPLYALPHA = new TextureOptions(GL10.GL_NEAREST, GL10.GL_NEAREST, GL10.GL_CLAMP_TO_EDGE, GL10.GL_CLAMP_TO_EDGE, true); + public static final TextureOptions BILINEAR_PREMULTIPLYALPHA = new TextureOptions(GL10.GL_LINEAR, GL10.GL_LINEAR, GL10.GL_CLAMP_TO_EDGE, GL10.GL_CLAMP_TO_EDGE, true); + public static final TextureOptions REPEATING_NEAREST_PREMULTIPLYALPHA = new TextureOptions(GL10.GL_NEAREST, GL10.GL_NEAREST, GL10.GL_REPEAT, GL10.GL_REPEAT, true); + public static final TextureOptions REPEATING_BILINEAR_PREMULTIPLYALPHA = new TextureOptions(GL10.GL_LINEAR, GL10.GL_LINEAR, GL10.GL_REPEAT, GL10.GL_REPEAT, true); - public static final TextureOptions DEFAULT = TextureOptions.NEAREST_PREMULTIPLYALPHA; + public static final TextureOptions DEFAULT = TextureOptions.NEAREST_PREMULTIPLYALPHA; - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - public final int mMagFilter; - public final int mMinFilter; - public final float mWrapT; - public final float mWrapS; - public boolean mPreMultipyAlpha; + public final int mMagFilter; + public final int mMinFilter; + public final float mWrapT; + public final float mWrapS; + public boolean mPreMultipyAlpha; - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - public TextureOptions(final int pMinFilter, final int pMagFilter, final int pWrapT, final int pWrapS, final boolean pPreMultiplyAlpha) { - this.mMinFilter = pMinFilter; - this.mMagFilter = pMagFilter; - this.mWrapT = pWrapT; - this.mWrapS = pWrapS; - this.mPreMultipyAlpha = pPreMultiplyAlpha; - } + public TextureOptions(final int pMinFilter, final int pMagFilter, final int pWrapT, final int pWrapS, final boolean pPreMultiplyAlpha) { + this.mMinFilter = pMinFilter; + this.mMagFilter = pMagFilter; + this.mWrapT = pWrapT; + this.mWrapS = pWrapS; + this.mPreMultipyAlpha = pPreMultiplyAlpha; + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - public void apply(final GL10 pGL) { - pGL.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, this.mMinFilter); - pGL.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, this.mMagFilter); - pGL.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, this.mWrapS); - pGL.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, this.mWrapT); - pGL.glTexEnvf(GL10.GL_TEXTURE_ENV, GL10.GL_TEXTURE_ENV_MODE, GL10.GL_MODULATE); - } + public void apply(final GL10 pGL) { + pGL.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, this.mMinFilter); + pGL.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, this.mMagFilter); + pGL.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, this.mWrapS); + pGL.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, this.mWrapT); + pGL.glTexEnvf(GL10.GL_TEXTURE_ENV, GL10.GL_TEXTURE_ENV_MODE, GL10.GL_MODULATE); + } - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/opengl/texture/atlas/ITextureAtlas.java b/AndEngine/src/org/anddev/andengine/opengl/texture/atlas/ITextureAtlas.java index 095784c0..904e0829 100644 --- a/AndEngine/src/org/anddev/andengine/opengl/texture/atlas/ITextureAtlas.java +++ b/AndEngine/src/org/anddev/andengine/opengl/texture/atlas/ITextureAtlas.java @@ -12,66 +12,66 @@ * @since 14:24:29 - 14.07.2011 */ public interface ITextureAtlas extends ITexture { - // =========================================================== - // Final Fields - // =========================================================== + // =========================================================== + // Final Fields + // =========================================================== - // =========================================================== - // Methods - // =========================================================== - - public void addTextureAtlasSource(final T pTextureAtlasSource, final int pTexturePositionX, final int pTexturePositionY) throws IllegalArgumentException; - public void removeTextureAtlasSource(final T pTextureAtlasSource, final int pTexturePositionX, final int pTexturePositionY); - public void clearTextureAtlasSources(); - - @Override - public ITextureAtlasStateListener getTextureStateListener(); + // =========================================================== + // Methods + // =========================================================== + + public void addTextureAtlasSource(final T pTextureAtlasSource, final int pTexturePositionX, final int pTexturePositionY) throws IllegalArgumentException; + public void removeTextureAtlasSource(final T pTextureAtlasSource, final int pTexturePositionX, final int pTexturePositionY); + public void clearTextureAtlasSources(); + + @Override + public ITextureAtlasStateListener getTextureStateListener(); - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== - - public static interface ITextureAtlasStateListener extends ITextureStateListener { - // =========================================================== - // Final Fields - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== + + public static interface ITextureAtlasStateListener extends ITextureStateListener { + // =========================================================== + // Final Fields + // =========================================================== - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - public void onTextureAtlasSourceLoadExeption(final ITextureAtlas pTextureAtlas, final T pTextureAtlasSource, final Throwable pThrowable); + public void onTextureAtlasSourceLoadExeption(final ITextureAtlas pTextureAtlas, final T pTextureAtlasSource, final Throwable pThrowable); - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== - public static class TextureAtlasStateAdapter implements ITextureAtlasStateListener { - @Override - public void onLoadedToHardware(final ITexture pTexture) { } + public static class TextureAtlasStateAdapter implements ITextureAtlasStateListener { + @Override + public void onLoadedToHardware(final ITexture pTexture) { } - @Override - public void onTextureAtlasSourceLoadExeption(final ITextureAtlas pTextureAtlas, final T pTextureAtlasSource, final Throwable pThrowable) { } + @Override + public void onTextureAtlasSourceLoadExeption(final ITextureAtlas pTextureAtlas, final T pTextureAtlasSource, final Throwable pThrowable) { } - @Override - public void onUnloadedFromHardware(final ITexture pTexture) { } - } + @Override + public void onUnloadedFromHardware(final ITexture pTexture) { } + } - public static class DebugTextureAtlasStateListener implements ITextureAtlasStateListener { - @Override - public void onLoadedToHardware(final ITexture pTexture) { - Debug.d("Texture loaded: " + pTexture.toString()); - } + public static class DebugTextureAtlasStateListener implements ITextureAtlasStateListener { + @Override + public void onLoadedToHardware(final ITexture pTexture) { + Debug.d("Texture loaded: " + pTexture.toString()); + } - @Override - public void onTextureAtlasSourceLoadExeption(final ITextureAtlas pTextureAtlas, final T pTextureAtlasSource, final Throwable pThrowable) { - Debug.e("Exception loading TextureAtlasSource. TextureAtlas: " + pTextureAtlas.toString() + " TextureAtlasSource: " + pTextureAtlasSource.toString(), pThrowable); - } + @Override + public void onTextureAtlasSourceLoadExeption(final ITextureAtlas pTextureAtlas, final T pTextureAtlasSource, final Throwable pThrowable) { + Debug.e("Exception loading TextureAtlasSource. TextureAtlas: " + pTextureAtlas.toString() + " TextureAtlasSource: " + pTextureAtlasSource.toString(), pThrowable); + } - @Override - public void onUnloadedFromHardware(final ITexture pTexture) { - Debug.d("Texture unloaded: " + pTexture.toString()); - } - } - } + @Override + public void onUnloadedFromHardware(final ITexture pTexture) { + Debug.d("Texture unloaded: " + pTexture.toString()); + } + } + } } diff --git a/AndEngine/src/org/anddev/andengine/opengl/texture/atlas/TextureAtlas.java b/AndEngine/src/org/anddev/andengine/opengl/texture/atlas/TextureAtlas.java index c2296c82..df3fd6f4 100644 --- a/AndEngine/src/org/anddev/andengine/opengl/texture/atlas/TextureAtlas.java +++ b/AndEngine/src/org/anddev/andengine/opengl/texture/atlas/TextureAtlas.java @@ -15,100 +15,100 @@ * @since 14:22:55 - 14.07.2011 */ public abstract class TextureAtlas extends Texture implements ITextureAtlas { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - protected final int mWidth; - protected final int mHeight; - - protected final ArrayList mTextureAtlasSources = new ArrayList(); - - // =========================================================== - // Constructors - // =========================================================== - - public TextureAtlas(final int pWidth, final int pHeight, final PixelFormat pPixelFormat, final TextureOptions pTextureOptions, final ITextureAtlasStateListener pTextureAtlasStateListener) { - super(pPixelFormat, pTextureOptions, pTextureAtlasStateListener); - - if(!MathUtils.isPowerOfTwo(pWidth) || !MathUtils.isPowerOfTwo(pHeight)) { // TODO GLHelper.EXTENSIONS_NON_POWER_OF_TWO - throw new IllegalArgumentException("pWidth and pHeight must be a power of 2!"); - } - this.mWidth = pWidth; - this.mHeight = pHeight; - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - @Override - public int getWidth() { - return this.mWidth; - } - - @Override - public int getHeight() { - return this.mHeight; - } - - @SuppressWarnings("unchecked") - @Override - public ITextureAtlasStateListener getTextureStateListener() { - return (ITextureAtlasStateListener) super.getTextureStateListener(); - } - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - public void addTextureAtlasSource(final T pTextureAtlasSource, final int pTexturePositionX, final int pTexturePositionY) throws IllegalArgumentException { - this.checkTextureAtlasSourcePosition(pTextureAtlasSource, pTexturePositionX, pTexturePositionY); - pTextureAtlasSource.setTexturePositionX(pTexturePositionX); - pTextureAtlasSource.setTexturePositionY(pTexturePositionY); - this.mTextureAtlasSources.add(pTextureAtlasSource); - this.mUpdateOnHardwareNeeded = true; - } - - @Override - public void removeTextureAtlasSource(final T pTextureAtlasSource, final int pTexturePositionX, final int pTexturePositionY) { - final ArrayList textureSources = this.mTextureAtlasSources; - for(int i = textureSources.size() - 1; i >= 0; i--) { - final T textureSource = textureSources.get(i); - if(textureSource == pTextureAtlasSource && textureSource.getTexturePositionX() == pTexturePositionX && textureSource.getTexturePositionY() == pTexturePositionY) { - textureSources.remove(i); - this.mUpdateOnHardwareNeeded = true; - return; - } - } - } - - @Override - public void clearTextureAtlasSources() { - this.mTextureAtlasSources.clear(); - this.mUpdateOnHardwareNeeded = true; - } - - // =========================================================== - // Methods - // =========================================================== - - private void checkTextureAtlasSourcePosition(final T pTextureAtlasSource, final int pTexturePositionX, final int pTexturePositionY) throws IllegalArgumentException { - if(pTexturePositionX < 0) { - throw new IllegalArgumentException("Illegal negative pTexturePositionX supplied: '" + pTexturePositionX + "'"); - } else if(pTexturePositionY < 0) { - throw new IllegalArgumentException("Illegal negative pTexturePositionY supplied: '" + pTexturePositionY + "'"); - } else if(pTexturePositionX + pTextureAtlasSource.getWidth() > this.getWidth() || pTexturePositionY + pTextureAtlasSource.getHeight() > this.getHeight()) { - throw new IllegalArgumentException("Supplied pTextureAtlasSource must not exceed bounds of Texture."); - } - } - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + protected final int mWidth; + protected final int mHeight; + + protected final ArrayList mTextureAtlasSources = new ArrayList(); + + // =========================================================== + // Constructors + // =========================================================== + + public TextureAtlas(final int pWidth, final int pHeight, final PixelFormat pPixelFormat, final TextureOptions pTextureOptions, final ITextureAtlasStateListener pTextureAtlasStateListener) { + super(pPixelFormat, pTextureOptions, pTextureAtlasStateListener); + + if(!MathUtils.isPowerOfTwo(pWidth) || !MathUtils.isPowerOfTwo(pHeight)) { // TODO GLHelper.EXTENSIONS_NON_POWER_OF_TWO + throw new IllegalArgumentException("pWidth and pHeight must be a power of 2!"); + } + this.mWidth = pWidth; + this.mHeight = pHeight; + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + @Override + public int getWidth() { + return this.mWidth; + } + + @Override + public int getHeight() { + return this.mHeight; + } + + @SuppressWarnings("unchecked") + @Override + public ITextureAtlasStateListener getTextureStateListener() { + return (ITextureAtlasStateListener) super.getTextureStateListener(); + } + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + public void addTextureAtlasSource(final T pTextureAtlasSource, final int pTexturePositionX, final int pTexturePositionY) throws IllegalArgumentException { + this.checkTextureAtlasSourcePosition(pTextureAtlasSource, pTexturePositionX, pTexturePositionY); + pTextureAtlasSource.setTexturePositionX(pTexturePositionX); + pTextureAtlasSource.setTexturePositionY(pTexturePositionY); + this.mTextureAtlasSources.add(pTextureAtlasSource); + this.mUpdateOnHardwareNeeded = true; + } + + @Override + public void removeTextureAtlasSource(final T pTextureAtlasSource, final int pTexturePositionX, final int pTexturePositionY) { + final ArrayList textureSources = this.mTextureAtlasSources; + for(int i = textureSources.size() - 1; i >= 0; i--) { + final T textureSource = textureSources.get(i); + if(textureSource == pTextureAtlasSource && textureSource.getTexturePositionX() == pTexturePositionX && textureSource.getTexturePositionY() == pTexturePositionY) { + textureSources.remove(i); + this.mUpdateOnHardwareNeeded = true; + return; + } + } + } + + @Override + public void clearTextureAtlasSources() { + this.mTextureAtlasSources.clear(); + this.mUpdateOnHardwareNeeded = true; + } + + // =========================================================== + // Methods + // =========================================================== + + private void checkTextureAtlasSourcePosition(final T pTextureAtlasSource, final int pTexturePositionX, final int pTexturePositionY) throws IllegalArgumentException { + if(pTexturePositionX < 0) { + throw new IllegalArgumentException("Illegal negative pTexturePositionX supplied: '" + pTexturePositionX + "'"); + } else if(pTexturePositionY < 0) { + throw new IllegalArgumentException("Illegal negative pTexturePositionY supplied: '" + pTexturePositionY + "'"); + } else if(pTexturePositionX + pTextureAtlasSource.getWidth() > this.getWidth() || pTexturePositionY + pTextureAtlasSource.getHeight() > this.getHeight()) { + throw new IllegalArgumentException("Supplied pTextureAtlasSource must not exceed bounds of Texture."); + } + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/opengl/texture/atlas/bitmap/BitmapTextureAtlas.java b/AndEngine/src/org/anddev/andengine/opengl/texture/atlas/bitmap/BitmapTextureAtlas.java index f2428f49..60c8a05d 100644 --- a/AndEngine/src/org/anddev/andengine/opengl/texture/atlas/bitmap/BitmapTextureAtlas.java +++ b/AndEngine/src/org/anddev/andengine/opengl/texture/atlas/bitmap/BitmapTextureAtlas.java @@ -24,195 +24,195 @@ * @since 14:55:02 - 08.03.2010 */ public class BitmapTextureAtlas extends TextureAtlas { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - private final BitmapTextureFormat mBitmapTextureFormat; - - // =========================================================== - // Constructors - // =========================================================== - - /** - * Uses {@link BitmapTextureFormat#RGBA_8888}. - * - * @param pWidth must be a power of 2 (i.e. 32, 64, 128, 256, 512, 1024). - * @param pHeight must be a power of 2 (i.e. 32, 64, 128, 256, 512, 1024). - */ - public BitmapTextureAtlas(final int pWidth, final int pHeight) { - this(pWidth, pHeight, BitmapTextureFormat.RGBA_8888); - } - - /** - * @param pWidth must be a power of 2 (i.e. 32, 64, 128, 256, 512, 1024). - * @param pHeight must be a power of 2 (i.e. 32, 64, 128, 256, 512, 1024). - * @param pBitmapTextureFormat use {@link BitmapTextureFormat#RGBA_8888} for {@link BitmapTextureAtlas}MAGIC_CONSTANT with transparency and {@link BitmapTextureFormat#RGB_565} for {@link BitmapTextureAtlas}MAGIC_CONSTANT without transparency. - */ - public BitmapTextureAtlas(final int pWidth, final int pHeight, final BitmapTextureFormat pBitmapTextureFormat) { - this(pWidth, pHeight, pBitmapTextureFormat, TextureOptions.DEFAULT, null); - } - - /** - * Uses {@link BitmapTextureFormat#RGBA_8888}. - * - * @param pWidth must be a power of 2 (i.e. 32, 64, 128, 256, 512, 1024). - * @param pHeight must be a power of 2 (i.e. 32, 64, 128, 256, 512, 1024). - * @param pTextureStateListener to be informed when this {@link BitmapTextureAtlas} is loaded, unloaded or a {@link ITextureAtlasSource} failed to load. - */ - public BitmapTextureAtlas(final int pWidth, final int pHeight, final ITextureAtlasStateListener pTextureAtlasStateListener) { - this(pWidth, pHeight, BitmapTextureFormat.RGBA_8888, TextureOptions.DEFAULT, pTextureAtlasStateListener); - } - - /** - * @param pWidth must be a power of 2 (i.e. 32, 64, 128, 256, 512, 1024). - * @param pHeight must be a power of 2 (i.e. 32, 64, 128, 256, 512, 1024). - * @param pBitmapTextureFormat use {@link BitmapTextureFormat#RGBA_8888} for {@link BitmapTextureAtlas}MAGIC_CONSTANT with transparency and {@link BitmapTextureFormat#RGB_565} for {@link BitmapTextureAtlas}MAGIC_CONSTANT without transparency. - * @param pTextureAtlasStateListener to be informed when this {@link BitmapTextureAtlas} is loaded, unloaded or a {@link ITextureAtlasSource} failed to load. - */ - public BitmapTextureAtlas(final int pWidth, final int pHeight, final BitmapTextureFormat pBitmapTextureFormat, final ITextureAtlasStateListener pTextureAtlasStateListener) { - this(pWidth, pHeight, pBitmapTextureFormat, TextureOptions.DEFAULT, pTextureAtlasStateListener); - } - - /** - * Uses {@link BitmapTextureFormat#RGBA_8888}. - * - * @param pWidth must be a power of 2 (i.e. 32, 64, 128, 256, 512, 1024). - * @param pHeight must be a power of 2 (i.e. 32, 64, 128, 256, 512, 1024). - * @param pTextureOptions the (quality) settings of the BitmapTexture. - */ - public BitmapTextureAtlas(final int pWidth, final int pHeight, final TextureOptions pTextureOptions) throws IllegalArgumentException { - this(pWidth, pHeight, BitmapTextureFormat.RGBA_8888, pTextureOptions, null); - } - - /** - * @param pWidth must be a power of 2 (i.e. 32, 64, 128, 256, 512, 1024). - * @param pHeight must be a power of 2 (i.e. 32, 64, 128, 256, 512, 1024). - * @param pBitmapTextureFormat use {@link BitmapTextureFormat#RGBA_8888} for {@link BitmapTextureAtlas}MAGIC_CONSTANT with transparency and {@link BitmapTextureFormat#RGB_565} for {@link BitmapTextureAtlas}MAGIC_CONSTANT without transparency. - * @param pTextureOptions the (quality) settings of the BitmapTexture. - */ - public BitmapTextureAtlas(final int pWidth, final int pHeight, final BitmapTextureFormat pBitmapTextureFormat, final TextureOptions pTextureOptions) throws IllegalArgumentException { - this(pWidth, pHeight, pBitmapTextureFormat, pTextureOptions, null); - } - - /** - * Uses {@link BitmapTextureFormat#RGBA_8888}. - * - * @param pWidth must be a power of 2 (i.e. 32, 64, 128, 256, 512, 1024). - * @param pHeight must be a power of 2 (i.e. 32, 64, 128, 256, 512, 1024). - * @param pTextureOptions the (quality) settings of the BitmapTexture. - * @param pTextureAtlasStateListener to be informed when this {@link BitmapTextureAtlas} is loaded, unloaded or a {@link ITextureAtlasSource} failed to load. - */ - public BitmapTextureAtlas(final int pWidth, final int pHeight, final TextureOptions pTextureOptions, final ITextureAtlasStateListener pTextureAtlasStateListener) throws IllegalArgumentException { - this(pWidth, pHeight, BitmapTextureFormat.RGBA_8888, pTextureOptions, pTextureAtlasStateListener); - } - - /** - * @param pWidth must be a power of 2 (i.e. 32, 64, 128, 256, 512, 1024). - * @param pHeight must be a power of 2 (i.e. 32, 64, 128, 256, 512, 1024). - * @param pBitmapTextureFormat use {@link BitmapTextureFormat#RGBA_8888} for {@link BitmapTextureAtlas}MAGIC_CONSTANT with transparency and {@link BitmapTextureFormat#RGB_565} for {@link BitmapTextureAtlas}MAGIC_CONSTANT without transparency. - * @param pTextureOptions the (quality) settings of the BitmapTexture. - * @param pTextureAtlasStateListener to be informed when this {@link BitmapTextureAtlas} is loaded, unloaded or a {@link ITextureAtlasSource} failed to load. - */ - public BitmapTextureAtlas(final int pWidth, final int pHeight, final BitmapTextureFormat pBitmapTextureFormat, final TextureOptions pTextureOptions, final ITextureAtlasStateListener pTextureAtlasStateListener) throws IllegalArgumentException { - super(pWidth, pHeight, pBitmapTextureFormat.getPixelFormat(), pTextureOptions, pTextureAtlasStateListener); - - this.mBitmapTextureFormat = pBitmapTextureFormat; - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - public BitmapTextureFormat getBitmapTextureFormat() { - return this.mBitmapTextureFormat; - } - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - // =========================================================== - // Methods - // =========================================================== - - @Override - protected void writeTextureToHardware(final GL10 pGL) { - final Config bitmapConfig = this.mBitmapTextureFormat.getBitmapConfig(); - final int glFormat = this.mPixelFormat.getGLFormat(); - final int glType = this.mPixelFormat.getGLType(); - final boolean preMultipyAlpha = this.mTextureOptions.mPreMultipyAlpha; - - final ArrayList textureSources = this.mTextureAtlasSources; - final int textureSourceCount = textureSources.size(); - - for(int j = 0; j < textureSourceCount; j++) { - final IBitmapTextureAtlasSource bitmapTextureAtlasSource = textureSources.get(j); - if(bitmapTextureAtlasSource != null) { - final Bitmap bitmap = bitmapTextureAtlasSource.onLoadBitmap(bitmapConfig); - try { - if(bitmap == null) { - throw new IllegalArgumentException(bitmapTextureAtlasSource.getClass().getSimpleName() + ": " + bitmapTextureAtlasSource.toString() + " returned a null Bitmap."); - } - if(preMultipyAlpha) { - //System.out.println("load preMultipyAlpha texture"); - GLUtils.texSubImage2D(GL10.GL_TEXTURE_2D, 0, bitmapTextureAtlasSource.getTexturePositionX(), bitmapTextureAtlasSource.getTexturePositionY(), bitmap, glFormat, glType); - } else { + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + private final BitmapTextureFormat mBitmapTextureFormat; + + // =========================================================== + // Constructors + // =========================================================== + + /** + * Uses {@link BitmapTextureFormat#RGBA_8888}. + * + * @param pWidth must be a power of 2 (i.e. 32, 64, 128, 256, 512, 1024). + * @param pHeight must be a power of 2 (i.e. 32, 64, 128, 256, 512, 1024). + */ + public BitmapTextureAtlas(final int pWidth, final int pHeight) { + this(pWidth, pHeight, BitmapTextureFormat.RGBA_8888); + } + + /** + * @param pWidth must be a power of 2 (i.e. 32, 64, 128, 256, 512, 1024). + * @param pHeight must be a power of 2 (i.e. 32, 64, 128, 256, 512, 1024). + * @param pBitmapTextureFormat use {@link BitmapTextureFormat#RGBA_8888} for {@link BitmapTextureAtlas}MAGIC_CONSTANT with transparency and {@link BitmapTextureFormat#RGB_565} for {@link BitmapTextureAtlas}MAGIC_CONSTANT without transparency. + */ + public BitmapTextureAtlas(final int pWidth, final int pHeight, final BitmapTextureFormat pBitmapTextureFormat) { + this(pWidth, pHeight, pBitmapTextureFormat, TextureOptions.DEFAULT, null); + } + + /** + * Uses {@link BitmapTextureFormat#RGBA_8888}. + * + * @param pWidth must be a power of 2 (i.e. 32, 64, 128, 256, 512, 1024). + * @param pHeight must be a power of 2 (i.e. 32, 64, 128, 256, 512, 1024). + * @param pTextureStateListener to be informed when this {@link BitmapTextureAtlas} is loaded, unloaded or a {@link ITextureAtlasSource} failed to load. + */ + public BitmapTextureAtlas(final int pWidth, final int pHeight, final ITextureAtlasStateListener pTextureAtlasStateListener) { + this(pWidth, pHeight, BitmapTextureFormat.RGBA_8888, TextureOptions.DEFAULT, pTextureAtlasStateListener); + } + + /** + * @param pWidth must be a power of 2 (i.e. 32, 64, 128, 256, 512, 1024). + * @param pHeight must be a power of 2 (i.e. 32, 64, 128, 256, 512, 1024). + * @param pBitmapTextureFormat use {@link BitmapTextureFormat#RGBA_8888} for {@link BitmapTextureAtlas}MAGIC_CONSTANT with transparency and {@link BitmapTextureFormat#RGB_565} for {@link BitmapTextureAtlas}MAGIC_CONSTANT without transparency. + * @param pTextureAtlasStateListener to be informed when this {@link BitmapTextureAtlas} is loaded, unloaded or a {@link ITextureAtlasSource} failed to load. + */ + public BitmapTextureAtlas(final int pWidth, final int pHeight, final BitmapTextureFormat pBitmapTextureFormat, final ITextureAtlasStateListener pTextureAtlasStateListener) { + this(pWidth, pHeight, pBitmapTextureFormat, TextureOptions.DEFAULT, pTextureAtlasStateListener); + } + + /** + * Uses {@link BitmapTextureFormat#RGBA_8888}. + * + * @param pWidth must be a power of 2 (i.e. 32, 64, 128, 256, 512, 1024). + * @param pHeight must be a power of 2 (i.e. 32, 64, 128, 256, 512, 1024). + * @param pTextureOptions the (quality) settings of the BitmapTexture. + */ + public BitmapTextureAtlas(final int pWidth, final int pHeight, final TextureOptions pTextureOptions) throws IllegalArgumentException { + this(pWidth, pHeight, BitmapTextureFormat.RGBA_8888, pTextureOptions, null); + } + + /** + * @param pWidth must be a power of 2 (i.e. 32, 64, 128, 256, 512, 1024). + * @param pHeight must be a power of 2 (i.e. 32, 64, 128, 256, 512, 1024). + * @param pBitmapTextureFormat use {@link BitmapTextureFormat#RGBA_8888} for {@link BitmapTextureAtlas}MAGIC_CONSTANT with transparency and {@link BitmapTextureFormat#RGB_565} for {@link BitmapTextureAtlas}MAGIC_CONSTANT without transparency. + * @param pTextureOptions the (quality) settings of the BitmapTexture. + */ + public BitmapTextureAtlas(final int pWidth, final int pHeight, final BitmapTextureFormat pBitmapTextureFormat, final TextureOptions pTextureOptions) throws IllegalArgumentException { + this(pWidth, pHeight, pBitmapTextureFormat, pTextureOptions, null); + } + + /** + * Uses {@link BitmapTextureFormat#RGBA_8888}. + * + * @param pWidth must be a power of 2 (i.e. 32, 64, 128, 256, 512, 1024). + * @param pHeight must be a power of 2 (i.e. 32, 64, 128, 256, 512, 1024). + * @param pTextureOptions the (quality) settings of the BitmapTexture. + * @param pTextureAtlasStateListener to be informed when this {@link BitmapTextureAtlas} is loaded, unloaded or a {@link ITextureAtlasSource} failed to load. + */ + public BitmapTextureAtlas(final int pWidth, final int pHeight, final TextureOptions pTextureOptions, final ITextureAtlasStateListener pTextureAtlasStateListener) throws IllegalArgumentException { + this(pWidth, pHeight, BitmapTextureFormat.RGBA_8888, pTextureOptions, pTextureAtlasStateListener); + } + + /** + * @param pWidth must be a power of 2 (i.e. 32, 64, 128, 256, 512, 1024). + * @param pHeight must be a power of 2 (i.e. 32, 64, 128, 256, 512, 1024). + * @param pBitmapTextureFormat use {@link BitmapTextureFormat#RGBA_8888} for {@link BitmapTextureAtlas}MAGIC_CONSTANT with transparency and {@link BitmapTextureFormat#RGB_565} for {@link BitmapTextureAtlas}MAGIC_CONSTANT without transparency. + * @param pTextureOptions the (quality) settings of the BitmapTexture. + * @param pTextureAtlasStateListener to be informed when this {@link BitmapTextureAtlas} is loaded, unloaded or a {@link ITextureAtlasSource} failed to load. + */ + public BitmapTextureAtlas(final int pWidth, final int pHeight, final BitmapTextureFormat pBitmapTextureFormat, final TextureOptions pTextureOptions, final ITextureAtlasStateListener pTextureAtlasStateListener) throws IllegalArgumentException { + super(pWidth, pHeight, pBitmapTextureFormat.getPixelFormat(), pTextureOptions, pTextureAtlasStateListener); + + this.mBitmapTextureFormat = pBitmapTextureFormat; + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + public BitmapTextureFormat getBitmapTextureFormat() { + return this.mBitmapTextureFormat; + } + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + @Override + protected void writeTextureToHardware(final GL10 pGL) { + final Config bitmapConfig = this.mBitmapTextureFormat.getBitmapConfig(); + final int glFormat = this.mPixelFormat.getGLFormat(); + final int glType = this.mPixelFormat.getGLType(); + final boolean preMultipyAlpha = this.mTextureOptions.mPreMultipyAlpha; + + final ArrayList textureSources = this.mTextureAtlasSources; + final int textureSourceCount = textureSources.size(); + + for(int j = 0; j < textureSourceCount; j++) { + final IBitmapTextureAtlasSource bitmapTextureAtlasSource = textureSources.get(j); + if(bitmapTextureAtlasSource != null) { + final Bitmap bitmap = bitmapTextureAtlasSource.onLoadBitmap(bitmapConfig); + try { + if(bitmap == null) { + throw new IllegalArgumentException(bitmapTextureAtlasSource.getClass().getSimpleName() + ": " + bitmapTextureAtlasSource.toString() + " returned a null Bitmap."); + } + if(preMultipyAlpha) { + //System.out.println("load preMultipyAlpha texture"); + GLUtils.texSubImage2D(GL10.GL_TEXTURE_2D, 0, bitmapTextureAtlasSource.getTexturePositionX(), bitmapTextureAtlasSource.getTexturePositionY(), bitmap, glFormat, glType); + } else { //System.out.println("load unpreMultipyAlpha texture"); - GLHelper.glTexSubImage2D(pGL, GL10.GL_TEXTURE_2D, 0, bitmapTextureAtlasSource.getTexturePositionX(), bitmapTextureAtlasSource.getTexturePositionY(), bitmap, this.mPixelFormat); - } - - bitmap.recycle(); - } catch (final IllegalArgumentException iae) { - // TODO Load some static checkerboard or so to visualize that loading the texture has failed. - //private Buffer createImage(final int width, final int height) { - // final int stride = 3 * width; - // final ByteBuffer image = ByteBuffer.allocateDirect(height * stride) - // .order(ByteOrder.nativeOrder()); - // - // // Fill with a pretty "munching squares" pattern: - // for (int t = 0; t < height; t++) { - // final byte red = (byte) (255 - 2 * t); - // final byte green = (byte) (2 * t); - // final byte blue = 0; - // for (int x = 0; x < width; x++) { - // final int y = x ^ t; - // image.position(stride * y + x * 3); - // image.put(red); - // image.put(green); - // image.put(blue); - // } - // } - // image.position(0); - // return image; - //} - - Debug.e("Error loading: " + bitmapTextureAtlasSource.toString(), iae); - if(this.getTextureStateListener() != null) { - this.getTextureStateListener().onTextureAtlasSourceLoadExeption(this, bitmapTextureAtlasSource, iae); - } else { - throw iae; - } - } - } - } - } - - @Override - protected void bindTextureOnHardware(final GL10 pGL) { - super.bindTextureOnHardware(pGL); - - final PixelFormat pixelFormat = this.mBitmapTextureFormat.getPixelFormat(); - final int glFormat = pixelFormat.getGLFormat(); - final int glType = pixelFormat.getGLType(); - pGL.glTexImage2D(GL10.GL_TEXTURE_2D, 0, glFormat, this.mWidth, this.mHeight, 0, glFormat, glType, null); - } - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + GLHelper.glTexSubImage2D(pGL, GL10.GL_TEXTURE_2D, 0, bitmapTextureAtlasSource.getTexturePositionX(), bitmapTextureAtlasSource.getTexturePositionY(), bitmap, this.mPixelFormat); + } + + bitmap.recycle(); + } catch (final IllegalArgumentException iae) { + // TODO Load some static checkerboard or so to visualize that loading the texture has failed. + //private Buffer createImage(final int width, final int height) { + // final int stride = 3 * width; + // final ByteBuffer image = ByteBuffer.allocateDirect(height * stride) + // .order(ByteOrder.nativeOrder()); + // + // // Fill with a pretty "munching squares" pattern: + // for (int t = 0; t < height; t++) { + // final byte red = (byte) (255 - 2 * t); + // final byte green = (byte) (2 * t); + // final byte blue = 0; + // for (int x = 0; x < width; x++) { + // final int y = x ^ t; + // image.position(stride * y + x * 3); + // image.put(red); + // image.put(green); + // image.put(blue); + // } + // } + // image.position(0); + // return image; + //} + + Debug.e("Error loading: " + bitmapTextureAtlasSource.toString(), iae); + if(this.getTextureStateListener() != null) { + this.getTextureStateListener().onTextureAtlasSourceLoadExeption(this, bitmapTextureAtlasSource, iae); + } else { + throw iae; + } + } + } + } + } + + @Override + protected void bindTextureOnHardware(final GL10 pGL) { + super.bindTextureOnHardware(pGL); + + final PixelFormat pixelFormat = this.mBitmapTextureFormat.getPixelFormat(); + final int glFormat = pixelFormat.getGLFormat(); + final int glType = pixelFormat.getGLType(); + pGL.glTexImage2D(GL10.GL_TEXTURE_2D, 0, glFormat, this.mWidth, this.mHeight, 0, glFormat, glType, null); + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/opengl/texture/atlas/bitmap/BitmapTextureAtlasFactory.java b/AndEngine/src/org/anddev/andengine/opengl/texture/atlas/bitmap/BitmapTextureAtlasFactory.java index 4e3e9ee0..99e77c61 100644 --- a/AndEngine/src/org/anddev/andengine/opengl/texture/atlas/bitmap/BitmapTextureAtlasFactory.java +++ b/AndEngine/src/org/anddev/andengine/opengl/texture/atlas/bitmap/BitmapTextureAtlasFactory.java @@ -14,51 +14,51 @@ * @since 09:38:51 - 03.05.2010 */ public class BitmapTextureAtlasFactory { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - public static BitmapTextureAtlas createForTextureAtlasSourceSize(final BitmapTextureFormat pBitmapTextureFormat, final TextureRegion pTextureRegion) { - return BitmapTextureAtlasFactory.createForTextureRegionSize(pBitmapTextureFormat, pTextureRegion, TextureOptions.DEFAULT); - } + public static BitmapTextureAtlas createForTextureAtlasSourceSize(final BitmapTextureFormat pBitmapTextureFormat, final TextureRegion pTextureRegion) { + return BitmapTextureAtlasFactory.createForTextureRegionSize(pBitmapTextureFormat, pTextureRegion, TextureOptions.DEFAULT); + } - public static BitmapTextureAtlas createForTextureRegionSize(final BitmapTextureFormat pBitmapTextureFormat, final TextureRegion pTextureRegion, final TextureOptions pTextureOptions) { - final int textureRegionWidth = pTextureRegion.getWidth(); - final int textureRegionHeight = pTextureRegion.getHeight(); - return new BitmapTextureAtlas(MathUtils.nextPowerOfTwo(textureRegionWidth), MathUtils.nextPowerOfTwo(textureRegionHeight), pBitmapTextureFormat, pTextureOptions); - } + public static BitmapTextureAtlas createForTextureRegionSize(final BitmapTextureFormat pBitmapTextureFormat, final TextureRegion pTextureRegion, final TextureOptions pTextureOptions) { + final int textureRegionWidth = pTextureRegion.getWidth(); + final int textureRegionHeight = pTextureRegion.getHeight(); + return new BitmapTextureAtlas(MathUtils.nextPowerOfTwo(textureRegionWidth), MathUtils.nextPowerOfTwo(textureRegionHeight), pBitmapTextureFormat, pTextureOptions); + } - public static BitmapTextureAtlas createForTextureAtlasSourceSize(final BitmapTextureFormat pBitmapTextureFormat, final IBitmapTextureAtlasSource pBitmapTextureAtlasSource) { - return BitmapTextureAtlasFactory.createForTextureAtlasSourceSize(pBitmapTextureFormat, pBitmapTextureAtlasSource, TextureOptions.DEFAULT); - } + public static BitmapTextureAtlas createForTextureAtlasSourceSize(final BitmapTextureFormat pBitmapTextureFormat, final IBitmapTextureAtlasSource pBitmapTextureAtlasSource) { + return BitmapTextureAtlasFactory.createForTextureAtlasSourceSize(pBitmapTextureFormat, pBitmapTextureAtlasSource, TextureOptions.DEFAULT); + } - public static BitmapTextureAtlas createForTextureAtlasSourceSize(final BitmapTextureFormat pBitmapTextureFormat, final IBitmapTextureAtlasSource pBitmapTextureAtlasSource, final TextureOptions pTextureOptions) { - final int textureSourceWidth = pBitmapTextureAtlasSource.getWidth(); - final int textureSourceHeight = pBitmapTextureAtlasSource.getHeight(); - return new BitmapTextureAtlas(MathUtils.nextPowerOfTwo(textureSourceWidth), MathUtils.nextPowerOfTwo(textureSourceHeight), pBitmapTextureFormat, pTextureOptions); - } + public static BitmapTextureAtlas createForTextureAtlasSourceSize(final BitmapTextureFormat pBitmapTextureFormat, final IBitmapTextureAtlasSource pBitmapTextureAtlasSource, final TextureOptions pTextureOptions) { + final int textureSourceWidth = pBitmapTextureAtlasSource.getWidth(); + final int textureSourceHeight = pBitmapTextureAtlasSource.getHeight(); + return new BitmapTextureAtlas(MathUtils.nextPowerOfTwo(textureSourceWidth), MathUtils.nextPowerOfTwo(textureSourceHeight), pBitmapTextureFormat, pTextureOptions); + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/opengl/texture/atlas/bitmap/BitmapTextureAtlasTextureRegionFactory.java b/AndEngine/src/org/anddev/andengine/opengl/texture/atlas/bitmap/BitmapTextureAtlasTextureRegionFactory.java index 064091f8..4a6140b1 100644 --- a/AndEngine/src/org/anddev/andengine/opengl/texture/atlas/bitmap/BitmapTextureAtlasTextureRegionFactory.java +++ b/AndEngine/src/org/anddev/andengine/opengl/texture/atlas/bitmap/BitmapTextureAtlasTextureRegionFactory.java @@ -20,121 +20,121 @@ * @since 18:15:14 - 09.03.2010 */ public class BitmapTextureAtlasTextureRegionFactory { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - private static String sAssetBasePath = ""; - private static boolean sCreateTextureRegionBuffersManaged; - - // =========================================================== - // Constructors - // =========================================================== - - // =========================================================== - // Getter & Setter - // =========================================================== - - /** - * @param pAssetBasePath must end with '/' or have .length() == 0. - */ - public static void setAssetBasePath(final String pAssetBasePath) { - if(pAssetBasePath.endsWith("/") || pAssetBasePath.length() == 0) { - BitmapTextureAtlasTextureRegionFactory.sAssetBasePath = pAssetBasePath; - } else { - throw new IllegalArgumentException("pAssetBasePath must end with '/' or be lenght zero."); - } - } - - public static void setCreateTextureRegionBuffersManaged(final boolean pCreateTextureRegionBuffersManaged) { - BitmapTextureAtlasTextureRegionFactory.sCreateTextureRegionBuffersManaged = pCreateTextureRegionBuffersManaged; - } - - public static void reset() { - BitmapTextureAtlasTextureRegionFactory.setAssetBasePath(""); - BitmapTextureAtlasTextureRegionFactory.setCreateTextureRegionBuffersManaged(false); - } - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Methods using BitmapTexture - // =========================================================== - - public static TextureRegion createFromAsset(final BitmapTextureAtlas pBitmapTextureAtlas, final Context pContext, final String pAssetPath, final int pTexturePositionX, final int pTexturePositionY) { - final IBitmapTextureAtlasSource bitmapTextureAtlasSource = new AssetBitmapTextureAtlasSource(pContext, BitmapTextureAtlasTextureRegionFactory.sAssetBasePath + pAssetPath); - return BitmapTextureAtlasTextureRegionFactory.createFromSource(pBitmapTextureAtlas, bitmapTextureAtlasSource, pTexturePositionX, pTexturePositionY); - } - - public static TiledTextureRegion createTiledFromAsset(final BitmapTextureAtlas pBitmapTextureAtlas, final Context pContext, final String pAssetPath, final int pTexturePositionX, final int pTexturePositionY, final int pTileColumns, final int pTileRows) { - final IBitmapTextureAtlasSource bitmapTextureAtlasSource = new AssetBitmapTextureAtlasSource(pContext, BitmapTextureAtlasTextureRegionFactory.sAssetBasePath + pAssetPath); - return BitmapTextureAtlasTextureRegionFactory.createTiledFromSource(pBitmapTextureAtlas, bitmapTextureAtlasSource, pTexturePositionX, pTexturePositionY, pTileColumns, pTileRows); - } - - - public static TextureRegion createFromResource(final BitmapTextureAtlas pBitmapTextureAtlas, final Context pContext, final int pDrawableResourceID, final int pTexturePositionX, final int pTexturePositionY) { - final IBitmapTextureAtlasSource bitmapTextureAtlasSource = new ResourceBitmapTextureAtlasSource(pContext, pDrawableResourceID); - return BitmapTextureAtlasTextureRegionFactory.createFromSource(pBitmapTextureAtlas, bitmapTextureAtlasSource, pTexturePositionX, pTexturePositionY); - } - - public static TiledTextureRegion createTiledFromResource(final BitmapTextureAtlas pBitmapTextureAtlas, final Context pContext, final int pDrawableResourceID, final int pTexturePositionX, final int pTexturePositionY, final int pTileColumns, final int pTileRows) { - final IBitmapTextureAtlasSource bitmapTextureAtlasSource = new ResourceBitmapTextureAtlasSource(pContext, pDrawableResourceID); - return BitmapTextureAtlasTextureRegionFactory.createTiledFromSource(pBitmapTextureAtlas, bitmapTextureAtlasSource, pTexturePositionX, pTexturePositionY, pTileColumns, pTileRows); - } - - public static TextureRegion createFromSource(final BitmapTextureAtlas pBitmapTextureAtlas, final IBitmapTextureAtlasSource pBitmapTextureAtlasSource, final int pTexturePositionX, final int pTexturePositionY) { - return TextureRegionFactory.createFromSource(pBitmapTextureAtlas, pBitmapTextureAtlasSource, pTexturePositionX, pTexturePositionY, sCreateTextureRegionBuffersManaged); - } - - public static TiledTextureRegion createTiledFromSource(final BitmapTextureAtlas pBitmapTextureAtlas, final IBitmapTextureAtlasSource pBitmapTextureAtlasSource, final int pTexturePositionX, final int pTexturePositionY, final int pTileColumns, final int pTileRows) { - return TextureRegionFactory.createTiledFromSource(pBitmapTextureAtlas, pBitmapTextureAtlasSource, pTexturePositionX, pTexturePositionY, pTileColumns, pTileRows, sCreateTextureRegionBuffersManaged); - } - - // =========================================================== - // Methods using BuildableTexture - // =========================================================== - - public static TextureRegion createFromAsset(final BuildableBitmapTextureAtlas pBuildableBitmapTextureAtlas, final Context pContext, final String pAssetPath) { - final IBitmapTextureAtlasSource bitmapTextureAtlasSource = new AssetBitmapTextureAtlasSource(pContext, BitmapTextureAtlasTextureRegionFactory.sAssetBasePath + pAssetPath); - return BitmapTextureAtlasTextureRegionFactory.createFromSource(pBuildableBitmapTextureAtlas, bitmapTextureAtlasSource); - } - - public static TiledTextureRegion createTiledFromAsset(final BuildableBitmapTextureAtlas pBuildableBitmapTextureAtlas, final Context pContext, final String pAssetPath, final int pTileColumns, final int pTileRows) { - final IBitmapTextureAtlasSource bitmapTextureAtlasSource = new AssetBitmapTextureAtlasSource(pContext, BitmapTextureAtlasTextureRegionFactory.sAssetBasePath + pAssetPath); - return BitmapTextureAtlasTextureRegionFactory.createTiledFromSource(pBuildableBitmapTextureAtlas, bitmapTextureAtlasSource, pTileColumns, pTileRows); - } - - - public static TextureRegion createFromResource(final BuildableBitmapTextureAtlas pBuildableBitmapTextureAtlas, final Context pContext, final int pDrawableResourceID) { - final IBitmapTextureAtlasSource bitmapTextureAtlasSource = new ResourceBitmapTextureAtlasSource(pContext, pDrawableResourceID); - return BitmapTextureAtlasTextureRegionFactory.createFromSource(pBuildableBitmapTextureAtlas, bitmapTextureAtlasSource); - } - - public static TiledTextureRegion createTiledFromResource(final BuildableBitmapTextureAtlas pBuildableBitmapTextureAtlas, final Context pContext, final int pDrawableResourceID, final int pTileColumns, final int pTileRows) { - final IBitmapTextureAtlasSource bitmapTextureAtlasSource = new ResourceBitmapTextureAtlasSource(pContext, pDrawableResourceID); - return BitmapTextureAtlasTextureRegionFactory.createTiledFromSource(pBuildableBitmapTextureAtlas, bitmapTextureAtlasSource, pTileColumns, pTileRows); - } - - - public static TextureRegion createFromSource(final BuildableBitmapTextureAtlas pBuildableBitmapTextureAtlas, final IBitmapTextureAtlasSource pBitmapTextureAtlasSource) { - return BuildableTextureAtlasTextureRegionFactory.createFromSource(pBuildableBitmapTextureAtlas, pBitmapTextureAtlasSource, sCreateTextureRegionBuffersManaged); - } - - public static TiledTextureRegion createTiledFromSource(final BuildableBitmapTextureAtlas pBuildableBitmapTextureAtlas, final IBitmapTextureAtlasSource pBitmapTextureAtlasSource, final int pTileColumns, final int pTileRows) { - return BuildableTextureAtlasTextureRegionFactory.createTiledFromSource(pBuildableBitmapTextureAtlas, pBitmapTextureAtlasSource, pTileColumns, pTileRows, sCreateTextureRegionBuffersManaged); - } - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + private static String sAssetBasePath = ""; + private static boolean sCreateTextureRegionBuffersManaged; + + // =========================================================== + // Constructors + // =========================================================== + + // =========================================================== + // Getter & Setter + // =========================================================== + + /** + * @param pAssetBasePath must end with '/' or have .length() == 0. + */ + public static void setAssetBasePath(final String pAssetBasePath) { + if(pAssetBasePath.endsWith("/") || pAssetBasePath.length() == 0) { + BitmapTextureAtlasTextureRegionFactory.sAssetBasePath = pAssetBasePath; + } else { + throw new IllegalArgumentException("pAssetBasePath must end with '/' or be lenght zero."); + } + } + + public static void setCreateTextureRegionBuffersManaged(final boolean pCreateTextureRegionBuffersManaged) { + BitmapTextureAtlasTextureRegionFactory.sCreateTextureRegionBuffersManaged = pCreateTextureRegionBuffersManaged; + } + + public static void reset() { + BitmapTextureAtlasTextureRegionFactory.setAssetBasePath(""); + BitmapTextureAtlasTextureRegionFactory.setCreateTextureRegionBuffersManaged(false); + } + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Methods using BitmapTexture + // =========================================================== + + public static TextureRegion createFromAsset(final BitmapTextureAtlas pBitmapTextureAtlas, final Context pContext, final String pAssetPath, final int pTexturePositionX, final int pTexturePositionY) { + final IBitmapTextureAtlasSource bitmapTextureAtlasSource = new AssetBitmapTextureAtlasSource(pContext, BitmapTextureAtlasTextureRegionFactory.sAssetBasePath + pAssetPath); + return BitmapTextureAtlasTextureRegionFactory.createFromSource(pBitmapTextureAtlas, bitmapTextureAtlasSource, pTexturePositionX, pTexturePositionY); + } + + public static TiledTextureRegion createTiledFromAsset(final BitmapTextureAtlas pBitmapTextureAtlas, final Context pContext, final String pAssetPath, final int pTexturePositionX, final int pTexturePositionY, final int pTileColumns, final int pTileRows) { + final IBitmapTextureAtlasSource bitmapTextureAtlasSource = new AssetBitmapTextureAtlasSource(pContext, BitmapTextureAtlasTextureRegionFactory.sAssetBasePath + pAssetPath); + return BitmapTextureAtlasTextureRegionFactory.createTiledFromSource(pBitmapTextureAtlas, bitmapTextureAtlasSource, pTexturePositionX, pTexturePositionY, pTileColumns, pTileRows); + } + + + public static TextureRegion createFromResource(final BitmapTextureAtlas pBitmapTextureAtlas, final Context pContext, final int pDrawableResourceID, final int pTexturePositionX, final int pTexturePositionY) { + final IBitmapTextureAtlasSource bitmapTextureAtlasSource = new ResourceBitmapTextureAtlasSource(pContext, pDrawableResourceID); + return BitmapTextureAtlasTextureRegionFactory.createFromSource(pBitmapTextureAtlas, bitmapTextureAtlasSource, pTexturePositionX, pTexturePositionY); + } + + public static TiledTextureRegion createTiledFromResource(final BitmapTextureAtlas pBitmapTextureAtlas, final Context pContext, final int pDrawableResourceID, final int pTexturePositionX, final int pTexturePositionY, final int pTileColumns, final int pTileRows) { + final IBitmapTextureAtlasSource bitmapTextureAtlasSource = new ResourceBitmapTextureAtlasSource(pContext, pDrawableResourceID); + return BitmapTextureAtlasTextureRegionFactory.createTiledFromSource(pBitmapTextureAtlas, bitmapTextureAtlasSource, pTexturePositionX, pTexturePositionY, pTileColumns, pTileRows); + } + + public static TextureRegion createFromSource(final BitmapTextureAtlas pBitmapTextureAtlas, final IBitmapTextureAtlasSource pBitmapTextureAtlasSource, final int pTexturePositionX, final int pTexturePositionY) { + return TextureRegionFactory.createFromSource(pBitmapTextureAtlas, pBitmapTextureAtlasSource, pTexturePositionX, pTexturePositionY, sCreateTextureRegionBuffersManaged); + } + + public static TiledTextureRegion createTiledFromSource(final BitmapTextureAtlas pBitmapTextureAtlas, final IBitmapTextureAtlasSource pBitmapTextureAtlasSource, final int pTexturePositionX, final int pTexturePositionY, final int pTileColumns, final int pTileRows) { + return TextureRegionFactory.createTiledFromSource(pBitmapTextureAtlas, pBitmapTextureAtlasSource, pTexturePositionX, pTexturePositionY, pTileColumns, pTileRows, sCreateTextureRegionBuffersManaged); + } + + // =========================================================== + // Methods using BuildableTexture + // =========================================================== + + public static TextureRegion createFromAsset(final BuildableBitmapTextureAtlas pBuildableBitmapTextureAtlas, final Context pContext, final String pAssetPath) { + final IBitmapTextureAtlasSource bitmapTextureAtlasSource = new AssetBitmapTextureAtlasSource(pContext, BitmapTextureAtlasTextureRegionFactory.sAssetBasePath + pAssetPath); + return BitmapTextureAtlasTextureRegionFactory.createFromSource(pBuildableBitmapTextureAtlas, bitmapTextureAtlasSource); + } + + public static TiledTextureRegion createTiledFromAsset(final BuildableBitmapTextureAtlas pBuildableBitmapTextureAtlas, final Context pContext, final String pAssetPath, final int pTileColumns, final int pTileRows) { + final IBitmapTextureAtlasSource bitmapTextureAtlasSource = new AssetBitmapTextureAtlasSource(pContext, BitmapTextureAtlasTextureRegionFactory.sAssetBasePath + pAssetPath); + return BitmapTextureAtlasTextureRegionFactory.createTiledFromSource(pBuildableBitmapTextureAtlas, bitmapTextureAtlasSource, pTileColumns, pTileRows); + } + + + public static TextureRegion createFromResource(final BuildableBitmapTextureAtlas pBuildableBitmapTextureAtlas, final Context pContext, final int pDrawableResourceID) { + final IBitmapTextureAtlasSource bitmapTextureAtlasSource = new ResourceBitmapTextureAtlasSource(pContext, pDrawableResourceID); + return BitmapTextureAtlasTextureRegionFactory.createFromSource(pBuildableBitmapTextureAtlas, bitmapTextureAtlasSource); + } + + public static TiledTextureRegion createTiledFromResource(final BuildableBitmapTextureAtlas pBuildableBitmapTextureAtlas, final Context pContext, final int pDrawableResourceID, final int pTileColumns, final int pTileRows) { + final IBitmapTextureAtlasSource bitmapTextureAtlasSource = new ResourceBitmapTextureAtlasSource(pContext, pDrawableResourceID); + return BitmapTextureAtlasTextureRegionFactory.createTiledFromSource(pBuildableBitmapTextureAtlas, bitmapTextureAtlasSource, pTileColumns, pTileRows); + } + + + public static TextureRegion createFromSource(final BuildableBitmapTextureAtlas pBuildableBitmapTextureAtlas, final IBitmapTextureAtlasSource pBitmapTextureAtlasSource) { + return BuildableTextureAtlasTextureRegionFactory.createFromSource(pBuildableBitmapTextureAtlas, pBitmapTextureAtlasSource, sCreateTextureRegionBuffersManaged); + } + + public static TiledTextureRegion createTiledFromSource(final BuildableBitmapTextureAtlas pBuildableBitmapTextureAtlas, final IBitmapTextureAtlasSource pBitmapTextureAtlasSource, final int pTileColumns, final int pTileRows) { + return BuildableTextureAtlasTextureRegionFactory.createTiledFromSource(pBuildableBitmapTextureAtlas, pBitmapTextureAtlasSource, pTileColumns, pTileRows, sCreateTextureRegionBuffersManaged); + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/opengl/texture/atlas/bitmap/BuildableBitmapTextureAtlas.java b/AndEngine/src/org/anddev/andengine/opengl/texture/atlas/bitmap/BuildableBitmapTextureAtlas.java index 7d0bef6a..8416d132 100644 --- a/AndEngine/src/org/anddev/andengine/opengl/texture/atlas/bitmap/BuildableBitmapTextureAtlas.java +++ b/AndEngine/src/org/anddev/andengine/opengl/texture/atlas/bitmap/BuildableBitmapTextureAtlas.java @@ -14,115 +14,115 @@ * @since 15:51:46 - 12.07.2011 */ public class BuildableBitmapTextureAtlas extends BuildableTextureAtlas { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - // =========================================================== - // Constructors - // =========================================================== - - /** - * Uses {@link BitmapTextureFormat#RGBA_8888}. - * - * @param pWidth must be a power of 2 (i.e. 32, 64, 128, 256, 512, 1024). - * @param pHeight must be a power of 2 (i.e. 32, 64, 128, 256, 512, 1024). - */ - public BuildableBitmapTextureAtlas(final int pWidth, final int pHeight) { - this(pWidth, pHeight, BitmapTextureFormat.RGBA_8888); - } - - /** - * @param pWidth must be a power of 2 (i.e. 32, 64, 128, 256, 512, 1024). - * @param pHeight must be a power of 2 (i.e. 32, 64, 128, 256, 512, 1024). - * @param pBitmapTextureFormat use {@link BitmapTextureFormat#RGBA_8888} for {@link BitmapTextureAtlas}MAGIC_CONSTANT with transparency and {@link BitmapTextureFormat#RGB_565} for {@link BitmapTextureAtlas}MAGIC_CONSTANT without transparency. - */ - public BuildableBitmapTextureAtlas(final int pWidth, final int pHeight, final BitmapTextureFormat pBitmapTextureFormat) { - this(pWidth, pHeight, pBitmapTextureFormat, TextureOptions.DEFAULT, null); - } - - /** - * Uses {@link BitmapTextureFormat#RGBA_8888}. - * - * @param pWidth must be a power of 2 (i.e. 32, 64, 128, 256, 512, 1024). - * @param pHeight must be a power of 2 (i.e. 32, 64, 128, 256, 512, 1024). - * @param pTextureStateListener to be informed when this {@link BitmapTextureAtlas} is loaded, unloaded or a {@link ITextureAtlasSource} failed to load. - */ - public BuildableBitmapTextureAtlas(final int pWidth, final int pHeight, final ITextureAtlasStateListener pTextureStateListener) { - this(pWidth, pHeight, BitmapTextureFormat.RGBA_8888, TextureOptions.DEFAULT, pTextureStateListener); - } - - /** - * @param pWidth must be a power of 2 (i.e. 32, 64, 128, 256, 512, 1024). - * @param pHeight must be a power of 2 (i.e. 32, 64, 128, 256, 512, 1024). - * @param pBitmapTextureFormat use {@link BitmapTextureFormat#RGBA_8888} for {@link BitmapTextureAtlas}MAGIC_CONSTANT with transparency and {@link BitmapTextureFormat#RGB_565} for {@link BitmapTextureAtlas}MAGIC_CONSTANT without transparency. - * @param pTextureStateListener to be informed when this {@link BitmapTextureAtlas} is loaded, unloaded or a {@link ITextureAtlasSource} failed to load. - */ - public BuildableBitmapTextureAtlas(final int pWidth, final int pHeight, final BitmapTextureFormat pBitmapTextureFormat, final ITextureAtlasStateListener pTextureStateListener) { - this(pWidth, pHeight, pBitmapTextureFormat, TextureOptions.DEFAULT, pTextureStateListener); - } - - /** - * Uses {@link BitmapTextureFormat#RGBA_8888}. - * - * @param pWidth must be a power of 2 (i.e. 32, 64, 128, 256, 512, 1024). - * @param pHeight must be a power of 2 (i.e. 32, 64, 128, 256, 512, 1024). - * @param pTextureOptions the (quality) settings of the BitmapTexture. - */ - public BuildableBitmapTextureAtlas(final int pWidth, final int pHeight, final TextureOptions pTextureOptions) throws IllegalArgumentException { - this(pWidth, pHeight, BitmapTextureFormat.RGBA_8888, pTextureOptions, null); - } - - /** - * @param pWidth must be a power of 2 (i.e. 32, 64, 128, 256, 512, 1024). - * @param pHeight must be a power of 2 (i.e. 32, 64, 128, 256, 512, 1024). - * @param pBitmapTextureFormat use {@link BitmapTextureFormat#RGBA_8888} for {@link BitmapTextureAtlas}MAGIC_CONSTANT with transparency and {@link BitmapTextureFormat#RGB_565} for {@link BitmapTextureAtlas}MAGIC_CONSTANT without transparency. - * @param pTextureOptions the (quality) settings of the BitmapTexture. - */ - public BuildableBitmapTextureAtlas(final int pWidth, final int pHeight, final BitmapTextureFormat pBitmapTextureFormat, final TextureOptions pTextureOptions) throws IllegalArgumentException { - this(pWidth, pHeight, pBitmapTextureFormat, pTextureOptions, null); - } - - /** - * Uses {@link BitmapTextureFormat#RGBA_8888}. - * - * @param pWidth must be a power of 2 (i.e. 32, 64, 128, 256, 512, 1024). - * @param pHeight must be a power of 2 (i.e. 32, 64, 128, 256, 512, 1024). - * @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. - */ - public BuildableBitmapTextureAtlas(final int pWidth, final int pHeight, final TextureOptions pTextureOptions, final ITextureAtlasStateListener pTextureStateListener) throws IllegalArgumentException { - this(pWidth, pHeight, BitmapTextureFormat.RGBA_8888, pTextureOptions, pTextureStateListener); - } - - /** - * @param pWidth must be a power of 2 (i.e. 32, 64, 128, 256, 512, 1024). - * @param pHeight must be a power of 2 (i.e. 32, 64, 128, 256, 512, 1024). - * @param pBitmapTextureFormat use {@link BitmapTextureFormat#RGBA_8888} for {@link BitmapTextureAtlas}MAGIC_CONSTANT with transparency and {@link BitmapTextureFormat#RGB_565} for {@link BitmapTextureAtlas}MAGIC_CONSTANT 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. - */ - public BuildableBitmapTextureAtlas(final int pWidth, final int pHeight, final BitmapTextureFormat pBitmapTextureFormat, final TextureOptions pTextureOptions, final ITextureAtlasStateListener pTextureStateListener) throws IllegalArgumentException { - super(new BitmapTextureAtlas(pWidth, pHeight, pBitmapTextureFormat, pTextureOptions, pTextureStateListener)); - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + // =========================================================== + // Constructors + // =========================================================== + + /** + * Uses {@link BitmapTextureFormat#RGBA_8888}. + * + * @param pWidth must be a power of 2 (i.e. 32, 64, 128, 256, 512, 1024). + * @param pHeight must be a power of 2 (i.e. 32, 64, 128, 256, 512, 1024). + */ + public BuildableBitmapTextureAtlas(final int pWidth, final int pHeight) { + this(pWidth, pHeight, BitmapTextureFormat.RGBA_8888); + } + + /** + * @param pWidth must be a power of 2 (i.e. 32, 64, 128, 256, 512, 1024). + * @param pHeight must be a power of 2 (i.e. 32, 64, 128, 256, 512, 1024). + * @param pBitmapTextureFormat use {@link BitmapTextureFormat#RGBA_8888} for {@link BitmapTextureAtlas}MAGIC_CONSTANT with transparency and {@link BitmapTextureFormat#RGB_565} for {@link BitmapTextureAtlas}MAGIC_CONSTANT without transparency. + */ + public BuildableBitmapTextureAtlas(final int pWidth, final int pHeight, final BitmapTextureFormat pBitmapTextureFormat) { + this(pWidth, pHeight, pBitmapTextureFormat, TextureOptions.DEFAULT, null); + } + + /** + * Uses {@link BitmapTextureFormat#RGBA_8888}. + * + * @param pWidth must be a power of 2 (i.e. 32, 64, 128, 256, 512, 1024). + * @param pHeight must be a power of 2 (i.e. 32, 64, 128, 256, 512, 1024). + * @param pTextureStateListener to be informed when this {@link BitmapTextureAtlas} is loaded, unloaded or a {@link ITextureAtlasSource} failed to load. + */ + public BuildableBitmapTextureAtlas(final int pWidth, final int pHeight, final ITextureAtlasStateListener pTextureStateListener) { + this(pWidth, pHeight, BitmapTextureFormat.RGBA_8888, TextureOptions.DEFAULT, pTextureStateListener); + } + + /** + * @param pWidth must be a power of 2 (i.e. 32, 64, 128, 256, 512, 1024). + * @param pHeight must be a power of 2 (i.e. 32, 64, 128, 256, 512, 1024). + * @param pBitmapTextureFormat use {@link BitmapTextureFormat#RGBA_8888} for {@link BitmapTextureAtlas}MAGIC_CONSTANT with transparency and {@link BitmapTextureFormat#RGB_565} for {@link BitmapTextureAtlas}MAGIC_CONSTANT without transparency. + * @param pTextureStateListener to be informed when this {@link BitmapTextureAtlas} is loaded, unloaded or a {@link ITextureAtlasSource} failed to load. + */ + public BuildableBitmapTextureAtlas(final int pWidth, final int pHeight, final BitmapTextureFormat pBitmapTextureFormat, final ITextureAtlasStateListener pTextureStateListener) { + this(pWidth, pHeight, pBitmapTextureFormat, TextureOptions.DEFAULT, pTextureStateListener); + } + + /** + * Uses {@link BitmapTextureFormat#RGBA_8888}. + * + * @param pWidth must be a power of 2 (i.e. 32, 64, 128, 256, 512, 1024). + * @param pHeight must be a power of 2 (i.e. 32, 64, 128, 256, 512, 1024). + * @param pTextureOptions the (quality) settings of the BitmapTexture. + */ + public BuildableBitmapTextureAtlas(final int pWidth, final int pHeight, final TextureOptions pTextureOptions) throws IllegalArgumentException { + this(pWidth, pHeight, BitmapTextureFormat.RGBA_8888, pTextureOptions, null); + } + + /** + * @param pWidth must be a power of 2 (i.e. 32, 64, 128, 256, 512, 1024). + * @param pHeight must be a power of 2 (i.e. 32, 64, 128, 256, 512, 1024). + * @param pBitmapTextureFormat use {@link BitmapTextureFormat#RGBA_8888} for {@link BitmapTextureAtlas}MAGIC_CONSTANT with transparency and {@link BitmapTextureFormat#RGB_565} for {@link BitmapTextureAtlas}MAGIC_CONSTANT without transparency. + * @param pTextureOptions the (quality) settings of the BitmapTexture. + */ + public BuildableBitmapTextureAtlas(final int pWidth, final int pHeight, final BitmapTextureFormat pBitmapTextureFormat, final TextureOptions pTextureOptions) throws IllegalArgumentException { + this(pWidth, pHeight, pBitmapTextureFormat, pTextureOptions, null); + } + + /** + * Uses {@link BitmapTextureFormat#RGBA_8888}. + * + * @param pWidth must be a power of 2 (i.e. 32, 64, 128, 256, 512, 1024). + * @param pHeight must be a power of 2 (i.e. 32, 64, 128, 256, 512, 1024). + * @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. + */ + public BuildableBitmapTextureAtlas(final int pWidth, final int pHeight, final TextureOptions pTextureOptions, final ITextureAtlasStateListener pTextureStateListener) throws IllegalArgumentException { + this(pWidth, pHeight, BitmapTextureFormat.RGBA_8888, pTextureOptions, pTextureStateListener); + } + + /** + * @param pWidth must be a power of 2 (i.e. 32, 64, 128, 256, 512, 1024). + * @param pHeight must be a power of 2 (i.e. 32, 64, 128, 256, 512, 1024). + * @param pBitmapTextureFormat use {@link BitmapTextureFormat#RGBA_8888} for {@link BitmapTextureAtlas}MAGIC_CONSTANT with transparency and {@link BitmapTextureFormat#RGB_565} for {@link BitmapTextureAtlas}MAGIC_CONSTANT 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. + */ + public BuildableBitmapTextureAtlas(final int pWidth, final int pHeight, final BitmapTextureFormat pBitmapTextureFormat, final TextureOptions pTextureOptions, final ITextureAtlasStateListener pTextureStateListener) throws IllegalArgumentException { + super(new BitmapTextureAtlas(pWidth, pHeight, pBitmapTextureFormat, pTextureOptions, pTextureStateListener)); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/opengl/texture/atlas/bitmap/source/AssetBitmapTextureAtlasSource.java b/AndEngine/src/org/anddev/andengine/opengl/texture/atlas/bitmap/source/AssetBitmapTextureAtlasSource.java index ef901041..6ad7ba04 100644 --- a/AndEngine/src/org/anddev/andengine/opengl/texture/atlas/bitmap/source/AssetBitmapTextureAtlasSource.java +++ b/AndEngine/src/org/anddev/andengine/opengl/texture/atlas/bitmap/source/AssetBitmapTextureAtlasSource.java @@ -20,108 +20,108 @@ * @since 12:07:52 - 09.03.2010 */ public class AssetBitmapTextureAtlasSource extends BaseTextureAtlasSource implements IBitmapTextureAtlasSource { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - private final int mWidth; - private final int mHeight; - - private final String mAssetPath; - private final Context mContext; - - // =========================================================== - // Constructors - // =========================================================== - - public AssetBitmapTextureAtlasSource(final Context pContext, final String pAssetPath) { - this(pContext, pAssetPath, 0, 0); - } - - public AssetBitmapTextureAtlasSource(final Context pContext, final String pAssetPath, final int pTexturePositionX, final int pTexturePositionY) { - super(pTexturePositionX, pTexturePositionY); - this.mContext = pContext; - this.mAssetPath = pAssetPath; - - final BitmapFactory.Options decodeOptions = new BitmapFactory.Options(); - decodeOptions.inJustDecodeBounds = true; - - InputStream in = null; - try { - in = pContext.getAssets().open(pAssetPath); - BitmapFactory.decodeStream(in, null, decodeOptions); - } catch (final IOException e) { - Debug.e("Failed loading Bitmap in AssetBitmapTextureAtlasSource. AssetPath: " + pAssetPath, e); - } finally { - StreamUtils.close(in); - } - - this.mWidth = decodeOptions.outWidth; - this.mHeight = decodeOptions.outHeight; - } - - AssetBitmapTextureAtlasSource(final Context pContext, final String pAssetPath, final int pTexturePositionX, final int pTexturePositionY, final int pWidth, final int pHeight) { - super(pTexturePositionX, pTexturePositionY); - this.mContext = pContext; - this.mAssetPath = pAssetPath; - this.mWidth = pWidth; - this.mHeight = pHeight; - } - - @Override - public AssetBitmapTextureAtlasSource deepCopy() { - return new AssetBitmapTextureAtlasSource(this.mContext, this.mAssetPath, this.mTexturePositionX, this.mTexturePositionY, this.mWidth, this.mHeight); - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - public int getWidth() { - return this.mWidth; - } - - @Override - public int getHeight() { - return this.mHeight; - } - - @Override - public Bitmap onLoadBitmap(final Config pBitmapConfig) { - InputStream in = null; - try { - final BitmapFactory.Options decodeOptions = new BitmapFactory.Options(); - decodeOptions.inPreferredConfig = pBitmapConfig; - - in = this.mContext.getAssets().open(this.mAssetPath); - return BitmapFactory.decodeStream(in, null, decodeOptions); - } catch (final IOException e) { - Debug.e("Failed loading Bitmap in " + this.getClass().getSimpleName() + ". AssetPath: " + this.mAssetPath, e); - return null; - } finally { - StreamUtils.close(in); - } - } - - @Override - public String toString() { - return this.getClass().getSimpleName() + "(" + this.mAssetPath + ")"; - } - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== -} \ No newline at end of file + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + private final int mWidth; + private final int mHeight; + + private final String mAssetPath; + private final Context mContext; + + // =========================================================== + // Constructors + // =========================================================== + + public AssetBitmapTextureAtlasSource(final Context pContext, final String pAssetPath) { + this(pContext, pAssetPath, 0, 0); + } + + public AssetBitmapTextureAtlasSource(final Context pContext, final String pAssetPath, final int pTexturePositionX, final int pTexturePositionY) { + super(pTexturePositionX, pTexturePositionY); + this.mContext = pContext; + this.mAssetPath = pAssetPath; + + final BitmapFactory.Options decodeOptions = new BitmapFactory.Options(); + decodeOptions.inJustDecodeBounds = true; + + InputStream in = null; + try { + in = pContext.getAssets().open(pAssetPath); + BitmapFactory.decodeStream(in, null, decodeOptions); + } catch (final IOException e) { + Debug.e("Failed loading Bitmap in AssetBitmapTextureAtlasSource. AssetPath: " + pAssetPath, e); + } finally { + StreamUtils.close(in); + } + + this.mWidth = decodeOptions.outWidth; + this.mHeight = decodeOptions.outHeight; + } + + AssetBitmapTextureAtlasSource(final Context pContext, final String pAssetPath, final int pTexturePositionX, final int pTexturePositionY, final int pWidth, final int pHeight) { + super(pTexturePositionX, pTexturePositionY); + this.mContext = pContext; + this.mAssetPath = pAssetPath; + this.mWidth = pWidth; + this.mHeight = pHeight; + } + + @Override + public AssetBitmapTextureAtlasSource deepCopy() { + return new AssetBitmapTextureAtlasSource(this.mContext, this.mAssetPath, this.mTexturePositionX, this.mTexturePositionY, this.mWidth, this.mHeight); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + public int getWidth() { + return this.mWidth; + } + + @Override + public int getHeight() { + return this.mHeight; + } + + @Override + public Bitmap onLoadBitmap(final Config pBitmapConfig) { + InputStream in = null; + try { + final BitmapFactory.Options decodeOptions = new BitmapFactory.Options(); + decodeOptions.inPreferredConfig = pBitmapConfig; + + in = this.mContext.getAssets().open(this.mAssetPath); + return BitmapFactory.decodeStream(in, null, decodeOptions); + } catch (final IOException e) { + Debug.e("Failed loading Bitmap in " + this.getClass().getSimpleName() + ". AssetPath: " + this.mAssetPath, e); + return null; + } finally { + StreamUtils.close(in); + } + } + + @Override + public String toString() { + return this.getClass().getSimpleName() + "(" + this.mAssetPath + ")"; + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== +} diff --git a/AndEngine/src/org/anddev/andengine/opengl/texture/atlas/bitmap/source/FileBitmapTextureAtlasSource.java b/AndEngine/src/org/anddev/andengine/opengl/texture/atlas/bitmap/source/FileBitmapTextureAtlasSource.java index 73621a10..8a763794 100644 --- a/AndEngine/src/org/anddev/andengine/opengl/texture/atlas/bitmap/source/FileBitmapTextureAtlasSource.java +++ b/AndEngine/src/org/anddev/andengine/opengl/texture/atlas/bitmap/source/FileBitmapTextureAtlasSource.java @@ -22,105 +22,105 @@ * @since 16:39:22 - 10.08.2010 */ public class FileBitmapTextureAtlasSource extends BaseTextureAtlasSource implements IBitmapTextureAtlasSource { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - private final int mWidth; - private final int mHeight; - - private final File mFile; - - // =========================================================== - // Constructors - // =========================================================== - - public FileBitmapTextureAtlasSource(final File pFile) { - this(pFile, 0, 0); - } - - public FileBitmapTextureAtlasSource(final File pFile, final int pTexturePositionX, final int pTexturePositionY) { - super(pTexturePositionX, pTexturePositionY); - this.mFile = pFile; - - final BitmapFactory.Options decodeOptions = new BitmapFactory.Options(); - decodeOptions.inJustDecodeBounds = true; - - InputStream in = null; - try { - in = new FileInputStream(pFile); - BitmapFactory.decodeStream(in, null, decodeOptions); - } catch (final IOException e) { - Debug.e("Failed loading Bitmap in FileBitmapTextureAtlasSource. File: " + pFile, e); - } finally { - StreamUtils.close(in); - } - - this.mWidth = decodeOptions.outWidth; - this.mHeight = decodeOptions.outHeight; - } - - FileBitmapTextureAtlasSource(final File pFile, final int pTexturePositionX, final int pTexturePositionY, final int pWidth, final int pHeight) { - super(pTexturePositionX, pTexturePositionY); - this.mFile = pFile; - this.mWidth = pWidth; - this.mHeight = pHeight; - } - - @Override - public FileBitmapTextureAtlasSource deepCopy() { - return new FileBitmapTextureAtlasSource(this.mFile, this.mTexturePositionX, this.mTexturePositionY, this.mWidth, this.mHeight); - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - public int getWidth() { - return this.mWidth; - } - - @Override - public int getHeight() { - return this.mHeight; - } - - @Override - public Bitmap onLoadBitmap(final Config pBitmapConfig) { - final BitmapFactory.Options decodeOptions = new BitmapFactory.Options(); - decodeOptions.inPreferredConfig = pBitmapConfig; - - InputStream in = null; - try { - in = new FileInputStream(this.mFile); - return BitmapFactory.decodeStream(in, null, decodeOptions); - } catch (final IOException e) { - Debug.e("Failed loading Bitmap in " + this.getClass().getSimpleName() + ". File: " + this.mFile, e); - return null; - } finally { - StreamUtils.close(in); - } - } - - @Override - public String toString() { - return this.getClass().getSimpleName() + "(" + this.mFile + ")"; - } - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== -} \ No newline at end of file + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + private final int mWidth; + private final int mHeight; + + private final File mFile; + + // =========================================================== + // Constructors + // =========================================================== + + public FileBitmapTextureAtlasSource(final File pFile) { + this(pFile, 0, 0); + } + + public FileBitmapTextureAtlasSource(final File pFile, final int pTexturePositionX, final int pTexturePositionY) { + super(pTexturePositionX, pTexturePositionY); + this.mFile = pFile; + + final BitmapFactory.Options decodeOptions = new BitmapFactory.Options(); + decodeOptions.inJustDecodeBounds = true; + + InputStream in = null; + try { + in = new FileInputStream(pFile); + BitmapFactory.decodeStream(in, null, decodeOptions); + } catch (final IOException e) { + Debug.e("Failed loading Bitmap in FileBitmapTextureAtlasSource. File: " + pFile, e); + } finally { + StreamUtils.close(in); + } + + this.mWidth = decodeOptions.outWidth; + this.mHeight = decodeOptions.outHeight; + } + + FileBitmapTextureAtlasSource(final File pFile, final int pTexturePositionX, final int pTexturePositionY, final int pWidth, final int pHeight) { + super(pTexturePositionX, pTexturePositionY); + this.mFile = pFile; + this.mWidth = pWidth; + this.mHeight = pHeight; + } + + @Override + public FileBitmapTextureAtlasSource deepCopy() { + return new FileBitmapTextureAtlasSource(this.mFile, this.mTexturePositionX, this.mTexturePositionY, this.mWidth, this.mHeight); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + public int getWidth() { + return this.mWidth; + } + + @Override + public int getHeight() { + return this.mHeight; + } + + @Override + public Bitmap onLoadBitmap(final Config pBitmapConfig) { + final BitmapFactory.Options decodeOptions = new BitmapFactory.Options(); + decodeOptions.inPreferredConfig = pBitmapConfig; + + InputStream in = null; + try { + in = new FileInputStream(this.mFile); + return BitmapFactory.decodeStream(in, null, decodeOptions); + } catch (final IOException e) { + Debug.e("Failed loading Bitmap in " + this.getClass().getSimpleName() + ". File: " + this.mFile, e); + return null; + } finally { + StreamUtils.close(in); + } + } + + @Override + public String toString() { + return this.getClass().getSimpleName() + "(" + this.mFile + ")"; + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== +} diff --git a/AndEngine/src/org/anddev/andengine/opengl/texture/atlas/bitmap/source/IBitmapTextureAtlasSource.java b/AndEngine/src/org/anddev/andengine/opengl/texture/atlas/bitmap/source/IBitmapTextureAtlasSource.java index 2b3a64f4..e188bcba 100644 --- a/AndEngine/src/org/anddev/andengine/opengl/texture/atlas/bitmap/source/IBitmapTextureAtlasSource.java +++ b/AndEngine/src/org/anddev/andengine/opengl/texture/atlas/bitmap/source/IBitmapTextureAtlasSource.java @@ -13,16 +13,16 @@ * @since 12:08:52 - 09.03.2010 */ public interface IBitmapTextureAtlasSource extends ITextureAtlasSource { - // =========================================================== - // Final Fields - // =========================================================== + // =========================================================== + // Final Fields + // =========================================================== - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - @Override - public IBitmapTextureAtlasSource deepCopy(); + @Override + public IBitmapTextureAtlasSource deepCopy(); - public Bitmap onLoadBitmap(final Config pBitmapConfig); -} \ No newline at end of file + public Bitmap onLoadBitmap(final Config pBitmapConfig); +} diff --git a/AndEngine/src/org/anddev/andengine/opengl/texture/atlas/bitmap/source/ResourceBitmapTextureAtlasSource.java b/AndEngine/src/org/anddev/andengine/opengl/texture/atlas/bitmap/source/ResourceBitmapTextureAtlasSource.java index 4aa3aa70..09275a1a 100644 --- a/AndEngine/src/org/anddev/andengine/opengl/texture/atlas/bitmap/source/ResourceBitmapTextureAtlasSource.java +++ b/AndEngine/src/org/anddev/andengine/opengl/texture/atlas/bitmap/source/ResourceBitmapTextureAtlasSource.java @@ -15,92 +15,92 @@ * @since 15:07:23 - 09.03.2010 */ public class ResourceBitmapTextureAtlasSource extends BaseTextureAtlasSource implements IBitmapTextureAtlasSource { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - private final int mWidth; - private final int mHeight; - - private final int mDrawableResourceID; - private final Context mContext; - - // =========================================================== - // Constructors - // =========================================================== - - public ResourceBitmapTextureAtlasSource(final Context pContext, final int pDrawableResourceID) { - this(pContext, pDrawableResourceID, 0, 0); - } - - public ResourceBitmapTextureAtlasSource(final Context pContext, final int pDrawableResourceID, final int pTexturePositionX, final int pTexturePositionY) { - super(pTexturePositionX, pTexturePositionY); - this.mContext = pContext; - this.mDrawableResourceID = pDrawableResourceID; - - final BitmapFactory.Options decodeOptions = new BitmapFactory.Options(); - decodeOptions.inJustDecodeBounds = true; -// decodeOptions.inScaled = false; // TODO Check how this behaves with drawable-""/nodpi/ldpi/mdpi/hdpi folders - - BitmapFactory.decodeResource(pContext.getResources(), pDrawableResourceID, decodeOptions); - - this.mWidth = decodeOptions.outWidth; - this.mHeight = decodeOptions.outHeight; - } - - protected ResourceBitmapTextureAtlasSource(final Context pContext, final int pDrawableResourceID, final int pTexturePositionX, final int pTexturePositionY, final int pWidth, final int pHeight) { - super(pTexturePositionX, pTexturePositionY); - this.mContext = pContext; - this.mDrawableResourceID = pDrawableResourceID; - this.mWidth = pWidth; - this.mHeight = pHeight; - } - - @Override - public ResourceBitmapTextureAtlasSource deepCopy() { - return new ResourceBitmapTextureAtlasSource(this.mContext, this.mDrawableResourceID, this.mTexturePositionX, this.mTexturePositionY, this.mWidth, this.mHeight); - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - public int getWidth() { - return this.mWidth; - } - - @Override - public int getHeight() { - return this.mHeight; - } - - @Override - public Bitmap onLoadBitmap(final Config pBitmapConfig) { - final BitmapFactory.Options decodeOptions = new BitmapFactory.Options(); - decodeOptions.inPreferredConfig = pBitmapConfig; -// decodeOptions.inScaled = false; // TODO Check how this behaves with drawable-""/nodpi/ldpi/mdpi/hdpi folders - return BitmapFactory.decodeResource(this.mContext.getResources(), this.mDrawableResourceID, decodeOptions); - } - - @Override - public String toString() { - return this.getClass().getSimpleName() + "(" + this.mDrawableResourceID + ")"; - } - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== -} \ No newline at end of file + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + private final int mWidth; + private final int mHeight; + + private final int mDrawableResourceID; + private final Context mContext; + + // =========================================================== + // Constructors + // =========================================================== + + public ResourceBitmapTextureAtlasSource(final Context pContext, final int pDrawableResourceID) { + this(pContext, pDrawableResourceID, 0, 0); + } + + public ResourceBitmapTextureAtlasSource(final Context pContext, final int pDrawableResourceID, final int pTexturePositionX, final int pTexturePositionY) { + super(pTexturePositionX, pTexturePositionY); + this.mContext = pContext; + this.mDrawableResourceID = pDrawableResourceID; + + final BitmapFactory.Options decodeOptions = new BitmapFactory.Options(); + decodeOptions.inJustDecodeBounds = true; +// decodeOptions.inScaled = false; // TODO Check how this behaves with drawable-""/nodpi/ldpi/mdpi/hdpi folders + + BitmapFactory.decodeResource(pContext.getResources(), pDrawableResourceID, decodeOptions); + + this.mWidth = decodeOptions.outWidth; + this.mHeight = decodeOptions.outHeight; + } + + protected ResourceBitmapTextureAtlasSource(final Context pContext, final int pDrawableResourceID, final int pTexturePositionX, final int pTexturePositionY, final int pWidth, final int pHeight) { + super(pTexturePositionX, pTexturePositionY); + this.mContext = pContext; + this.mDrawableResourceID = pDrawableResourceID; + this.mWidth = pWidth; + this.mHeight = pHeight; + } + + @Override + public ResourceBitmapTextureAtlasSource deepCopy() { + return new ResourceBitmapTextureAtlasSource(this.mContext, this.mDrawableResourceID, this.mTexturePositionX, this.mTexturePositionY, this.mWidth, this.mHeight); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + public int getWidth() { + return this.mWidth; + } + + @Override + public int getHeight() { + return this.mHeight; + } + + @Override + public Bitmap onLoadBitmap(final Config pBitmapConfig) { + final BitmapFactory.Options decodeOptions = new BitmapFactory.Options(); + decodeOptions.inPreferredConfig = pBitmapConfig; +// decodeOptions.inScaled = false; // TODO Check how this behaves with drawable-""/nodpi/ldpi/mdpi/hdpi folders + return BitmapFactory.decodeResource(this.mContext.getResources(), this.mDrawableResourceID, decodeOptions); + } + + @Override + public String toString() { + return this.getClass().getSimpleName() + "(" + this.mDrawableResourceID + ")"; + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== +} diff --git a/AndEngine/src/org/anddev/andengine/opengl/texture/atlas/buildable/BuildableTextureAtlas.java b/AndEngine/src/org/anddev/andengine/opengl/texture/atlas/buildable/BuildableTextureAtlas.java index ef19c389..e1120da1 100644 --- a/AndEngine/src/org/anddev/andengine/opengl/texture/atlas/buildable/BuildableTextureAtlas.java +++ b/AndEngine/src/org/anddev/andengine/opengl/texture/atlas/buildable/BuildableTextureAtlas.java @@ -21,212 +21,212 @@ * @since 21:26:38 - 12.08.2010 */ public class BuildableTextureAtlas> implements ITextureAtlas { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - private final A mTextureAtlas; - private final ArrayList> mTextureAtlasSourcesToPlace = new ArrayList>(); - - // =========================================================== - // Constructors - // =========================================================== - - public BuildableTextureAtlas(final A pTextureAtlas) { - this.mTextureAtlas = pTextureAtlas; - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - public int getWidth() { - return this.mTextureAtlas.getWidth(); - } - - @Override - public int getHeight() { - return this.mTextureAtlas.getHeight(); - } - - @Override - public int getHardwareTextureID() { - return this.mTextureAtlas.getHardwareTextureID(); - } - - @Override - public boolean isLoadedToHardware() { - return this.mTextureAtlas.isLoadedToHardware(); - } - - @Override - public void setLoadedToHardware(final boolean pLoadedToHardware) { - this.mTextureAtlas.setLoadedToHardware(pLoadedToHardware); - } - - @Override - public boolean isUpdateOnHardwareNeeded() { - return this.mTextureAtlas.isUpdateOnHardwareNeeded(); - } - - @Override - public void setUpdateOnHardwareNeeded(final boolean pUpdateOnHardwareNeeded) { - this.mTextureAtlas.setUpdateOnHardwareNeeded(pUpdateOnHardwareNeeded); - } - - @Override - public void loadToHardware(final GL10 pGL) throws IOException { - this.mTextureAtlas.loadToHardware(pGL); - } - - @Override - public void unloadFromHardware(final GL10 pGL) { - this.mTextureAtlas.unloadFromHardware(pGL); - } - - @Override - public void reloadToHardware(final GL10 pGL) throws IOException { - this.mTextureAtlas.reloadToHardware(pGL); - } - - @Override - public void bind(final GL10 pGL) { - this.mTextureAtlas.bind(pGL); - } - - @Override - public TextureOptions getTextureOptions() { - return this.mTextureAtlas.getTextureOptions(); - } - - /** - * Most likely this is not the method you'd want to be using, as the {@link ITextureAtlasSource} won't get packed through this. - * @deprecated Use {@link BuildableTextureAtlas#addTextureAtlasSource(ITextureAtlasSource)} instead. - */ - @Deprecated - @Override - public void addTextureAtlasSource(final T pTextureAtlasSource, final int pTexturePositionX, final int pTexturePositionY) { - this.mTextureAtlas.addTextureAtlasSource(pTextureAtlasSource, pTexturePositionX, pTexturePositionY); - } - - @Override - public void removeTextureAtlasSource(final T pTextureAtlasSource, final int pTexturePositionX, final int pTexturePositionY) { - this.mTextureAtlas.removeTextureAtlasSource(pTextureAtlasSource, pTexturePositionX, pTexturePositionY); - } - - @Override - public void clearTextureAtlasSources() { - this.mTextureAtlas.clearTextureAtlasSources(); - this.mTextureAtlasSourcesToPlace.clear(); - } - - @Override - public boolean hasTextureStateListener() { - return this.mTextureAtlas.hasTextureStateListener(); - } - - @Override - public ITextureAtlasStateListener getTextureStateListener() { - return this.mTextureAtlas.getTextureStateListener(); - } - - // =========================================================== - // Methods - // =========================================================== - - /** - * When all {@link ITextureAtlasSource}MAGIC_CONSTANT are added you have to call {@link BuildableBitmapTextureAtlas#build(ITextureBuilder)}. - * @param pTextureAtlasSource to be added. - * @param pTextureRegion - */ - public void addTextureAtlasSource(final T pTextureAtlasSource, final Callback pCallback) { - this.mTextureAtlasSourcesToPlace.add(new TextureAtlasSourceWithWithLocationCallback(pTextureAtlasSource, pCallback)); - } - - /** - * Removes a {@link ITextureAtlasSource} before {@link BuildableBitmapTextureAtlas#build(ITextureBuilder)} is called. - * @param pBitmapTextureAtlasSource to be removed. - */ - public void removeTextureAtlasSource(final ITextureAtlasSource pTextureAtlasSource) { - final ArrayList> textureSources = this.mTextureAtlasSourcesToPlace; - for(int i = textureSources.size() - 1; i >= 0; i--) { - final TextureAtlasSourceWithWithLocationCallback textureSource = textureSources.get(i); - if(textureSource.mTextureAtlasSource == pTextureAtlasSource) { - textureSources.remove(i); - this.mTextureAtlas.setUpdateOnHardwareNeeded(true); - return; - } - } - } - - /** - * May draw over already added {@link ITextureAtlasSource}MAGIC_CONSTANT. - * - * @param pTextureAtlasSourcePackingAlgorithm the {@link ITextureBuilder} to use for packing the {@link ITextureAtlasSource} in this {@link BuildableBitmapTextureAtlas}. - * @throws TextureAtlasSourcePackingException i.e. when the {@link ITextureAtlasSource}MAGIC_CONSTANT didn't fit into this {@link BuildableBitmapTextureAtlas}. - */ - public void build(final ITextureBuilder pTextureAtlasSourcePackingAlgorithm) throws TextureAtlasSourcePackingException { - pTextureAtlasSourcePackingAlgorithm.pack(this.mTextureAtlas, this.mTextureAtlasSourcesToPlace); - this.mTextureAtlasSourcesToPlace.clear(); - this.mTextureAtlas.setUpdateOnHardwareNeeded(true); - } - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== - - public static class TextureAtlasSourceWithWithLocationCallback { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - private final T mTextureAtlasSource; - private final Callback mCallback; - - // =========================================================== - // Constructors - // =========================================================== - - public TextureAtlasSourceWithWithLocationCallback(final T pTextureAtlasSource, final Callback pCallback) { - this.mTextureAtlasSource = pTextureAtlasSource; - this.mCallback = pCallback; - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - public Callback getCallback() { - return this.mCallback; - } - - public T getTextureAtlasSource() { - return this.mTextureAtlasSource; - } - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== - } + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + private final A mTextureAtlas; + private final ArrayList> mTextureAtlasSourcesToPlace = new ArrayList>(); + + // =========================================================== + // Constructors + // =========================================================== + + public BuildableTextureAtlas(final A pTextureAtlas) { + this.mTextureAtlas = pTextureAtlas; + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + public int getWidth() { + return this.mTextureAtlas.getWidth(); + } + + @Override + public int getHeight() { + return this.mTextureAtlas.getHeight(); + } + + @Override + public int getHardwareTextureID() { + return this.mTextureAtlas.getHardwareTextureID(); + } + + @Override + public boolean isLoadedToHardware() { + return this.mTextureAtlas.isLoadedToHardware(); + } + + @Override + public void setLoadedToHardware(final boolean pLoadedToHardware) { + this.mTextureAtlas.setLoadedToHardware(pLoadedToHardware); + } + + @Override + public boolean isUpdateOnHardwareNeeded() { + return this.mTextureAtlas.isUpdateOnHardwareNeeded(); + } + + @Override + public void setUpdateOnHardwareNeeded(final boolean pUpdateOnHardwareNeeded) { + this.mTextureAtlas.setUpdateOnHardwareNeeded(pUpdateOnHardwareNeeded); + } + + @Override + public void loadToHardware(final GL10 pGL) throws IOException { + this.mTextureAtlas.loadToHardware(pGL); + } + + @Override + public void unloadFromHardware(final GL10 pGL) { + this.mTextureAtlas.unloadFromHardware(pGL); + } + + @Override + public void reloadToHardware(final GL10 pGL) throws IOException { + this.mTextureAtlas.reloadToHardware(pGL); + } + + @Override + public void bind(final GL10 pGL) { + this.mTextureAtlas.bind(pGL); + } + + @Override + public TextureOptions getTextureOptions() { + return this.mTextureAtlas.getTextureOptions(); + } + + /** + * Most likely this is not the method you'd want to be using, as the {@link ITextureAtlasSource} won't get packed through this. + * @deprecated Use {@link BuildableTextureAtlas#addTextureAtlasSource(ITextureAtlasSource)} instead. + */ + @Deprecated + @Override + public void addTextureAtlasSource(final T pTextureAtlasSource, final int pTexturePositionX, final int pTexturePositionY) { + this.mTextureAtlas.addTextureAtlasSource(pTextureAtlasSource, pTexturePositionX, pTexturePositionY); + } + + @Override + public void removeTextureAtlasSource(final T pTextureAtlasSource, final int pTexturePositionX, final int pTexturePositionY) { + this.mTextureAtlas.removeTextureAtlasSource(pTextureAtlasSource, pTexturePositionX, pTexturePositionY); + } + + @Override + public void clearTextureAtlasSources() { + this.mTextureAtlas.clearTextureAtlasSources(); + this.mTextureAtlasSourcesToPlace.clear(); + } + + @Override + public boolean hasTextureStateListener() { + return this.mTextureAtlas.hasTextureStateListener(); + } + + @Override + public ITextureAtlasStateListener getTextureStateListener() { + return this.mTextureAtlas.getTextureStateListener(); + } + + // =========================================================== + // Methods + // =========================================================== + + /** + * When all {@link ITextureAtlasSource}MAGIC_CONSTANT are added you have to call {@link BuildableBitmapTextureAtlas#build(ITextureBuilder)}. + * @param pTextureAtlasSource to be added. + * @param pTextureRegion + */ + public void addTextureAtlasSource(final T pTextureAtlasSource, final Callback pCallback) { + this.mTextureAtlasSourcesToPlace.add(new TextureAtlasSourceWithWithLocationCallback(pTextureAtlasSource, pCallback)); + } + + /** + * Removes a {@link ITextureAtlasSource} before {@link BuildableBitmapTextureAtlas#build(ITextureBuilder)} is called. + * @param pBitmapTextureAtlasSource to be removed. + */ + public void removeTextureAtlasSource(final ITextureAtlasSource pTextureAtlasSource) { + final ArrayList> textureSources = this.mTextureAtlasSourcesToPlace; + for(int i = textureSources.size() - 1; i >= 0; i--) { + final TextureAtlasSourceWithWithLocationCallback textureSource = textureSources.get(i); + if(textureSource.mTextureAtlasSource == pTextureAtlasSource) { + textureSources.remove(i); + this.mTextureAtlas.setUpdateOnHardwareNeeded(true); + return; + } + } + } + + /** + * May draw over already added {@link ITextureAtlasSource}MAGIC_CONSTANT. + * + * @param pTextureAtlasSourcePackingAlgorithm the {@link ITextureBuilder} to use for packing the {@link ITextureAtlasSource} in this {@link BuildableBitmapTextureAtlas}. + * @throws TextureAtlasSourcePackingException i.e. when the {@link ITextureAtlasSource}MAGIC_CONSTANT didn't fit into this {@link BuildableBitmapTextureAtlas}. + */ + public void build(final ITextureBuilder pTextureAtlasSourcePackingAlgorithm) throws TextureAtlasSourcePackingException { + pTextureAtlasSourcePackingAlgorithm.pack(this.mTextureAtlas, this.mTextureAtlasSourcesToPlace); + this.mTextureAtlasSourcesToPlace.clear(); + this.mTextureAtlas.setUpdateOnHardwareNeeded(true); + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== + + public static class TextureAtlasSourceWithWithLocationCallback { + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + private final T mTextureAtlasSource; + private final Callback mCallback; + + // =========================================================== + // Constructors + // =========================================================== + + public TextureAtlasSourceWithWithLocationCallback(final T pTextureAtlasSource, final Callback pCallback) { + this.mTextureAtlasSource = pTextureAtlasSource; + this.mCallback = pCallback; + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + public Callback getCallback() { + return this.mCallback; + } + + public T getTextureAtlasSource() { + return this.mTextureAtlasSource; + } + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== + } } diff --git a/AndEngine/src/org/anddev/andengine/opengl/texture/atlas/buildable/BuildableTextureAtlasTextureRegionFactory.java b/AndEngine/src/org/anddev/andengine/opengl/texture/atlas/buildable/BuildableTextureAtlasTextureRegionFactory.java index 3fc340d2..573eb1d7 100644 --- a/AndEngine/src/org/anddev/andengine/opengl/texture/atlas/buildable/BuildableTextureAtlasTextureRegionFactory.java +++ b/AndEngine/src/org/anddev/andengine/opengl/texture/atlas/buildable/BuildableTextureAtlasTextureRegionFactory.java @@ -16,63 +16,63 @@ * @since 16:42:08 - 12.07.2011 */ public class BuildableTextureAtlasTextureRegionFactory { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - // =========================================================== - // Methods using BuildableBitmapTexture - // =========================================================== + // =========================================================== + // Methods using BuildableBitmapTexture + // =========================================================== - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - public static > TextureRegion createFromSource(final BuildableTextureAtlas pBuildableTextureAtlas, final T pTextureAtlasSource, final boolean pTextureRegionBufferManaged) { - final TextureRegion textureRegion = new TextureRegion(pBuildableTextureAtlas, 0, 0, pTextureAtlasSource.getWidth(), pTextureAtlasSource.getHeight()); - pBuildableTextureAtlas.addTextureAtlasSource(pTextureAtlasSource, new Callback() { - @Override - public void onCallback(final T pCallbackValue) { - textureRegion.setTexturePosition(pCallbackValue.getTexturePositionX(), pCallbackValue.getTexturePositionY()); - } - }); - textureRegion.setTextureRegionBufferManaged(pTextureRegionBufferManaged); - return textureRegion; - } + public static > TextureRegion createFromSource(final BuildableTextureAtlas pBuildableTextureAtlas, final T pTextureAtlasSource, final boolean pTextureRegionBufferManaged) { + final TextureRegion textureRegion = new TextureRegion(pBuildableTextureAtlas, 0, 0, pTextureAtlasSource.getWidth(), pTextureAtlasSource.getHeight()); + pBuildableTextureAtlas.addTextureAtlasSource(pTextureAtlasSource, new Callback() { + @Override + public void onCallback(final T pCallbackValue) { + textureRegion.setTexturePosition(pCallbackValue.getTexturePositionX(), pCallbackValue.getTexturePositionY()); + } + }); + textureRegion.setTextureRegionBufferManaged(pTextureRegionBufferManaged); + return textureRegion; + } - public static > TiledTextureRegion createTiledFromSource(final BuildableTextureAtlas pBuildableTextureAtlas, final T pTextureAtlasSource, final int pTileColumns, final int pTileRows, final boolean pTextureRegionBufferManaged) { - final TiledTextureRegion tiledTextureRegion = new TiledTextureRegion(pBuildableTextureAtlas, 0, 0, pTextureAtlasSource.getWidth(), pTextureAtlasSource.getHeight(), pTileColumns, pTileRows); - pBuildableTextureAtlas.addTextureAtlasSource(pTextureAtlasSource, new Callback() { - @Override - public void onCallback(final T pCallbackValue) { - tiledTextureRegion.setTexturePosition(pCallbackValue.getTexturePositionX(), pCallbackValue.getTexturePositionY()); - } - }); - tiledTextureRegion.setTextureRegionBufferManaged(pTextureRegionBufferManaged); - return tiledTextureRegion; - } + public static > TiledTextureRegion createTiledFromSource(final BuildableTextureAtlas pBuildableTextureAtlas, final T pTextureAtlasSource, final int pTileColumns, final int pTileRows, final boolean pTextureRegionBufferManaged) { + final TiledTextureRegion tiledTextureRegion = new TiledTextureRegion(pBuildableTextureAtlas, 0, 0, pTextureAtlasSource.getWidth(), pTextureAtlasSource.getHeight(), pTileColumns, pTileRows); + pBuildableTextureAtlas.addTextureAtlasSource(pTextureAtlasSource, new Callback() { + @Override + public void onCallback(final T pCallbackValue) { + tiledTextureRegion.setTexturePosition(pCallbackValue.getTexturePositionX(), pCallbackValue.getTexturePositionY()); + } + }); + tiledTextureRegion.setTextureRegionBufferManaged(pTextureRegionBufferManaged); + return tiledTextureRegion; + } - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/opengl/texture/atlas/buildable/builder/BlackPawnTextureBuilder.java b/AndEngine/src/org/anddev/andengine/opengl/texture/atlas/buildable/builder/BlackPawnTextureBuilder.java index f9eced9a..2db54ba1 100644 --- a/AndEngine/src/org/anddev/andengine/opengl/texture/atlas/buildable/builder/BlackPawnTextureBuilder.java +++ b/AndEngine/src/org/anddev/andengine/opengl/texture/atlas/buildable/builder/BlackPawnTextureBuilder.java @@ -18,309 +18,309 @@ * @see http://www.blackpawn.com/texts/lightmaps/default.html */ public class BlackPawnTextureBuilder> implements ITextureBuilder { - // =========================================================== - // Constants - // =========================================================== - - private static final Comparator> TEXTURESOURCE_COMPARATOR = new Comparator>() { - @Override - public int compare(final TextureAtlasSourceWithWithLocationCallback pTextureAtlasSourceWithWithLocationCallbackA, final TextureAtlasSourceWithWithLocationCallback pTextureAtlasSourceWithWithLocationCallbackB) { - final int deltaWidth = pTextureAtlasSourceWithWithLocationCallbackB.getTextureAtlasSource().getWidth() - pTextureAtlasSourceWithWithLocationCallbackA.getTextureAtlasSource().getWidth(); - if(deltaWidth != 0) { - return deltaWidth; - } else { - return pTextureAtlasSourceWithWithLocationCallbackB.getTextureAtlasSource().getHeight() - pTextureAtlasSourceWithWithLocationCallbackA.getTextureAtlasSource().getHeight(); - } - } - }; - - // =========================================================== - // Fields - // =========================================================== - - private final int mTextureAtlasSourceSpacing; - - // =========================================================== - // Constructors - // =========================================================== - - public BlackPawnTextureBuilder(final int pTextureAtlasSourceSpacing) { - this.mTextureAtlasSourceSpacing = pTextureAtlasSourceSpacing; - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - public void pack(final A pTextureAtlas, final ArrayList> pTextureAtlasSourcesWithLocationCallback) throws TextureAtlasSourcePackingException { - Collections.sort(pTextureAtlasSourcesWithLocationCallback, TEXTURESOURCE_COMPARATOR); - - final Node root = new Node(new Rect(0, 0, pTextureAtlas.getWidth(), pTextureAtlas.getHeight())); - - final int textureSourceCount = pTextureAtlasSourcesWithLocationCallback.size(); - - for(int i = 0; i < textureSourceCount; i++) { - final TextureAtlasSourceWithWithLocationCallback textureSourceWithLocationCallback = pTextureAtlasSourcesWithLocationCallback.get(i); - final T textureSource = textureSourceWithLocationCallback.getTextureAtlasSource(); - - final Node inserted = root.insert(textureSource, pTextureAtlas.getWidth(), pTextureAtlas.getHeight(), this.mTextureAtlasSourceSpacing); - - if(inserted == null) { - throw new TextureAtlasSourcePackingException("Could not pack: " + textureSource.toString()); - } - pTextureAtlas.addTextureAtlasSource(textureSource, inserted.mRect.mLeft, inserted.mRect.mTop); - textureSourceWithLocationCallback.getCallback().onCallback(textureSource); - } - } - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== - - protected static class Rect { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - private final int mLeft; - private final int mTop; - private final int mWidth; - private final int mHeight; - - // =========================================================== - // Constructors - // =========================================================== - - public Rect(final int pLeft, final int pTop, final int pWidth, final int pHeight) { - this.mLeft = pLeft; - this.mTop = pTop; - this.mWidth = pWidth; - this.mHeight = pHeight; - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - public int getWidth() { - return this.mWidth; - } - - public int getHeight() { - return this.mHeight; - } - - public int getLeft() { - return this.mLeft; - } - - public int getTop() { - return this.mTop; - } - - public int getRight() { - return this.mLeft + this.mWidth; - } - - public int getBottom() { - return this.mTop + this.mHeight; - } - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - public String toString() { - return "@: " + this.mLeft + "/" + this.mTop + " * " + this.mWidth + "x" + this.mHeight; - } - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== - } - - protected static class Node { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - private Node mChildA; - private Node mChildB; - private final Rect mRect; - private ITextureAtlasSource mTextureAtlasSource; - - // =========================================================== - // Constructors - // =========================================================== - - public Node(final int pLeft, final int pTop, final int pWidth, final int pHeight) { - this(new Rect(pLeft, pTop, pWidth, pHeight)); - } - - public Node(final Rect pRect) { - this.mRect = pRect; - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - public Rect getRect() { - return this.mRect; - } - - public Node getChildA() { - return this.mChildA; - } - - public Node getChildB() { - return this.mChildB; - } - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - // =========================================================== - // Methods - // =========================================================== - - public Node insert(final ITextureAtlasSource pTextureAtlasSource, final int pTextureWidth, final int pTextureHeight, final int pTextureSpacing) throws IllegalArgumentException { - if(this.mChildA != null && this.mChildB != null) { - final Node newNode = this.mChildA.insert(pTextureAtlasSource, pTextureWidth, pTextureHeight, pTextureSpacing); - if(newNode != null){ - return newNode; - } else { - return this.mChildB.insert(pTextureAtlasSource, pTextureWidth, pTextureHeight, pTextureSpacing); - } - } else { - if(this.mTextureAtlasSource != null) { - return null; - } - - final int textureSourceWidth = pTextureAtlasSource.getWidth(); - final int textureSourceHeight = pTextureAtlasSource.getHeight(); - - final int rectWidth = this.mRect.getWidth(); - final int rectHeight = this.mRect.getHeight(); - - if(textureSourceWidth > rectWidth || textureSourceHeight > rectHeight) { - return null; - } - - final int textureSourceWidthWithSpacing = textureSourceWidth + pTextureSpacing; - final int textureSourceHeightWithSpacing = textureSourceHeight + pTextureSpacing; - - final int rectLeft = this.mRect.getLeft(); - final int rectTop = this.mRect.getTop(); - - 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. */ - this.mTextureAtlasSource = pTextureAtlasSource; - return this; - } else if(fitToBottomWithoutSpacing) { /* Bottom edge of the BitmapTexture. */ - this.mTextureAtlasSource = pTextureAtlasSource; - return this; - } - } - - if(fitToRightWithoutSpacing) { /* Right edge of the BitmapTexture. */ - if(textureSourceHeightWithSpacing == rectHeight) { - this.mTextureAtlasSource = pTextureAtlasSource; - return this; - } else if(fitToBottomWithoutSpacing) { /* Bottom edge of the BitmapTexture. */ - this.mTextureAtlasSource = pTextureAtlasSource; - return this; - } else if(textureSourceHeightWithSpacing > rectHeight) { - return null; - } else { - - return this.createChildren(pTextureAtlasSource, pTextureWidth, pTextureHeight, pTextureSpacing, rectWidth - textureSourceWidth, rectHeight - textureSourceHeightWithSpacing); - } - } - - if(fitToBottomWithoutSpacing) { - if(textureSourceWidthWithSpacing == rectWidth) { - this.mTextureAtlasSource = pTextureAtlasSource; - return this; - } else if(textureSourceWidthWithSpacing > rectWidth) { - return null; - } else { - return this.createChildren(pTextureAtlasSource, pTextureWidth, pTextureHeight, pTextureSpacing, rectWidth - textureSourceWidthWithSpacing, rectHeight - textureSourceHeight); - } - } else if(textureSourceWidthWithSpacing > rectWidth || textureSourceHeightWithSpacing > rectHeight) { - return null; - } else { - return this.createChildren(pTextureAtlasSource, pTextureWidth, pTextureHeight, pTextureSpacing, rectWidth - textureSourceWidthWithSpacing, rectHeight - textureSourceHeightWithSpacing); - } - } - } - - private Node createChildren(final ITextureAtlasSource pTextureAtlasSource, final int pTextureWidth, final int pTextureHeight, final int pTextureSpacing, final int pDeltaWidth, final int pDeltaHeight) { - final Rect rect = this.mRect; - - if(pDeltaWidth >= pDeltaHeight) { - /* Split using a vertical axis. */ - this.mChildA = new Node( - rect.getLeft(), - rect.getTop(), - pTextureAtlasSource.getWidth() + pTextureSpacing, - rect.getHeight() - ); - - this.mChildB = new Node( - rect.getLeft() + (pTextureAtlasSource.getWidth() + pTextureSpacing), - rect.getTop(), - rect.getWidth() - (pTextureAtlasSource.getWidth() + pTextureSpacing), - rect.getHeight() - ); - } else { - /* Split using a horizontal axis. */ - this.mChildA = new Node( - rect.getLeft(), - rect.getTop(), - rect.getWidth(), - pTextureAtlasSource.getHeight() + pTextureSpacing - ); - - this.mChildB = new Node( - rect.getLeft(), - rect.getTop() + (pTextureAtlasSource.getHeight() + pTextureSpacing), - rect.getWidth(), - rect.getHeight() - (pTextureAtlasSource.getHeight() + pTextureSpacing) - ); - } - - return this.mChildA.insert(pTextureAtlasSource, pTextureWidth, pTextureHeight, pTextureSpacing); - } - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== - } + // =========================================================== + // Constants + // =========================================================== + + private static final Comparator> TEXTURESOURCE_COMPARATOR = new Comparator>() { + @Override + public int compare(final TextureAtlasSourceWithWithLocationCallback pTextureAtlasSourceWithWithLocationCallbackA, final TextureAtlasSourceWithWithLocationCallback pTextureAtlasSourceWithWithLocationCallbackB) { + final int deltaWidth = pTextureAtlasSourceWithWithLocationCallbackB.getTextureAtlasSource().getWidth() - pTextureAtlasSourceWithWithLocationCallbackA.getTextureAtlasSource().getWidth(); + if(deltaWidth != 0) { + return deltaWidth; + } else { + return pTextureAtlasSourceWithWithLocationCallbackB.getTextureAtlasSource().getHeight() - pTextureAtlasSourceWithWithLocationCallbackA.getTextureAtlasSource().getHeight(); + } + } + }; + + // =========================================================== + // Fields + // =========================================================== + + private final int mTextureAtlasSourceSpacing; + + // =========================================================== + // Constructors + // =========================================================== + + public BlackPawnTextureBuilder(final int pTextureAtlasSourceSpacing) { + this.mTextureAtlasSourceSpacing = pTextureAtlasSourceSpacing; + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + public void pack(final A pTextureAtlas, final ArrayList> pTextureAtlasSourcesWithLocationCallback) throws TextureAtlasSourcePackingException { + Collections.sort(pTextureAtlasSourcesWithLocationCallback, TEXTURESOURCE_COMPARATOR); + + final Node root = new Node(new Rect(0, 0, pTextureAtlas.getWidth(), pTextureAtlas.getHeight())); + + final int textureSourceCount = pTextureAtlasSourcesWithLocationCallback.size(); + + for(int i = 0; i < textureSourceCount; i++) { + final TextureAtlasSourceWithWithLocationCallback textureSourceWithLocationCallback = pTextureAtlasSourcesWithLocationCallback.get(i); + final T textureSource = textureSourceWithLocationCallback.getTextureAtlasSource(); + + final Node inserted = root.insert(textureSource, pTextureAtlas.getWidth(), pTextureAtlas.getHeight(), this.mTextureAtlasSourceSpacing); + + if(inserted == null) { + throw new TextureAtlasSourcePackingException("Could not pack: " + textureSource.toString()); + } + pTextureAtlas.addTextureAtlasSource(textureSource, inserted.mRect.mLeft, inserted.mRect.mTop); + textureSourceWithLocationCallback.getCallback().onCallback(textureSource); + } + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== + + protected static class Rect { + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + private final int mLeft; + private final int mTop; + private final int mWidth; + private final int mHeight; + + // =========================================================== + // Constructors + // =========================================================== + + public Rect(final int pLeft, final int pTop, final int pWidth, final int pHeight) { + this.mLeft = pLeft; + this.mTop = pTop; + this.mWidth = pWidth; + this.mHeight = pHeight; + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + public int getWidth() { + return this.mWidth; + } + + public int getHeight() { + return this.mHeight; + } + + public int getLeft() { + return this.mLeft; + } + + public int getTop() { + return this.mTop; + } + + public int getRight() { + return this.mLeft + this.mWidth; + } + + public int getBottom() { + return this.mTop + this.mHeight; + } + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + public String toString() { + return "@: " + this.mLeft + "/" + this.mTop + " * " + this.mWidth + "x" + this.mHeight; + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== + } + + protected static class Node { + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + private Node mChildA; + private Node mChildB; + private final Rect mRect; + private ITextureAtlasSource mTextureAtlasSource; + + // =========================================================== + // Constructors + // =========================================================== + + public Node(final int pLeft, final int pTop, final int pWidth, final int pHeight) { + this(new Rect(pLeft, pTop, pWidth, pHeight)); + } + + public Node(final Rect pRect) { + this.mRect = pRect; + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + public Rect getRect() { + return this.mRect; + } + + public Node getChildA() { + return this.mChildA; + } + + public Node getChildB() { + return this.mChildB; + } + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + public Node insert(final ITextureAtlasSource pTextureAtlasSource, final int pTextureWidth, final int pTextureHeight, final int pTextureSpacing) throws IllegalArgumentException { + if(this.mChildA != null && this.mChildB != null) { + final Node newNode = this.mChildA.insert(pTextureAtlasSource, pTextureWidth, pTextureHeight, pTextureSpacing); + if(newNode != null){ + return newNode; + } else { + return this.mChildB.insert(pTextureAtlasSource, pTextureWidth, pTextureHeight, pTextureSpacing); + } + } else { + if(this.mTextureAtlasSource != null) { + return null; + } + + final int textureSourceWidth = pTextureAtlasSource.getWidth(); + final int textureSourceHeight = pTextureAtlasSource.getHeight(); + + final int rectWidth = this.mRect.getWidth(); + final int rectHeight = this.mRect.getHeight(); + + if(textureSourceWidth > rectWidth || textureSourceHeight > rectHeight) { + return null; + } + + final int textureSourceWidthWithSpacing = textureSourceWidth + pTextureSpacing; + final int textureSourceHeightWithSpacing = textureSourceHeight + pTextureSpacing; + + final int rectLeft = this.mRect.getLeft(); + final int rectTop = this.mRect.getTop(); + + 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. */ + this.mTextureAtlasSource = pTextureAtlasSource; + return this; + } else if(fitToBottomWithoutSpacing) { /* Bottom edge of the BitmapTexture. */ + this.mTextureAtlasSource = pTextureAtlasSource; + return this; + } + } + + if(fitToRightWithoutSpacing) { /* Right edge of the BitmapTexture. */ + if(textureSourceHeightWithSpacing == rectHeight) { + this.mTextureAtlasSource = pTextureAtlasSource; + return this; + } else if(fitToBottomWithoutSpacing) { /* Bottom edge of the BitmapTexture. */ + this.mTextureAtlasSource = pTextureAtlasSource; + return this; + } else if(textureSourceHeightWithSpacing > rectHeight) { + return null; + } else { + + return this.createChildren(pTextureAtlasSource, pTextureWidth, pTextureHeight, pTextureSpacing, rectWidth - textureSourceWidth, rectHeight - textureSourceHeightWithSpacing); + } + } + + if(fitToBottomWithoutSpacing) { + if(textureSourceWidthWithSpacing == rectWidth) { + this.mTextureAtlasSource = pTextureAtlasSource; + return this; + } else if(textureSourceWidthWithSpacing > rectWidth) { + return null; + } else { + return this.createChildren(pTextureAtlasSource, pTextureWidth, pTextureHeight, pTextureSpacing, rectWidth - textureSourceWidthWithSpacing, rectHeight - textureSourceHeight); + } + } else if(textureSourceWidthWithSpacing > rectWidth || textureSourceHeightWithSpacing > rectHeight) { + return null; + } else { + return this.createChildren(pTextureAtlasSource, pTextureWidth, pTextureHeight, pTextureSpacing, rectWidth - textureSourceWidthWithSpacing, rectHeight - textureSourceHeightWithSpacing); + } + } + } + + private Node createChildren(final ITextureAtlasSource pTextureAtlasSource, final int pTextureWidth, final int pTextureHeight, final int pTextureSpacing, final int pDeltaWidth, final int pDeltaHeight) { + final Rect rect = this.mRect; + + if(pDeltaWidth >= pDeltaHeight) { + /* Split using a vertical axis. */ + this.mChildA = new Node( + rect.getLeft(), + rect.getTop(), + pTextureAtlasSource.getWidth() + pTextureSpacing, + rect.getHeight() + ); + + this.mChildB = new Node( + rect.getLeft() + (pTextureAtlasSource.getWidth() + pTextureSpacing), + rect.getTop(), + rect.getWidth() - (pTextureAtlasSource.getWidth() + pTextureSpacing), + rect.getHeight() + ); + } else { + /* Split using a horizontal axis. */ + this.mChildA = new Node( + rect.getLeft(), + rect.getTop(), + rect.getWidth(), + pTextureAtlasSource.getHeight() + pTextureSpacing + ); + + this.mChildB = new Node( + rect.getLeft(), + rect.getTop() + (pTextureAtlasSource.getHeight() + pTextureSpacing), + rect.getWidth(), + rect.getHeight() - (pTextureAtlasSource.getHeight() + pTextureSpacing) + ); + } + + return this.mChildA.insert(pTextureAtlasSource, pTextureWidth, pTextureHeight, pTextureSpacing); + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== + } } diff --git a/AndEngine/src/org/anddev/andengine/opengl/texture/atlas/buildable/builder/ITextureBuilder.java b/AndEngine/src/org/anddev/andengine/opengl/texture/atlas/buildable/builder/ITextureBuilder.java index b0ee9650..5d869904 100644 --- a/AndEngine/src/org/anddev/andengine/opengl/texture/atlas/buildable/builder/ITextureBuilder.java +++ b/AndEngine/src/org/anddev/andengine/opengl/texture/atlas/buildable/builder/ITextureBuilder.java @@ -14,54 +14,54 @@ * @since 15:59:14 - 12.08.2010 */ public interface ITextureBuilder> { - // =========================================================== - // Final Fields - // =========================================================== + // =========================================================== + // Final Fields + // =========================================================== - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - public void pack(final A pTextureAtlas, final ArrayList> pTextureAtlasSourcesWithLocationCallback) throws TextureAtlasSourcePackingException; + public void pack(final A pTextureAtlas, final ArrayList> pTextureAtlasSourcesWithLocationCallback) throws TextureAtlasSourcePackingException; - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== - public static class TextureAtlasSourcePackingException extends Exception { - // =========================================================== - // Constants - // =========================================================== + public static class TextureAtlasSourcePackingException extends Exception { + // =========================================================== + // Constants + // =========================================================== - private static final long serialVersionUID = 4700734424214372671L; + private static final long serialVersionUID = 4700734424214372671L; - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - public TextureAtlasSourcePackingException(final String pMessage) { - super(pMessage); - } + public TextureAtlasSourcePackingException(final String pMessage) { + super(pMessage); + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== - } + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== + } } diff --git a/AndEngine/src/org/anddev/andengine/opengl/texture/bitmap/BitmapTexture.java b/AndEngine/src/org/anddev/andengine/opengl/texture/bitmap/BitmapTexture.java index f8053060..f6c0f347 100644 --- a/AndEngine/src/org/anddev/andengine/opengl/texture/bitmap/BitmapTexture.java +++ b/AndEngine/src/org/anddev/andengine/opengl/texture/bitmap/BitmapTexture.java @@ -23,174 +23,174 @@ * @since 16:16:25 - 30.07.2011 */ public abstract class BitmapTexture extends Texture { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - private final int mWidth; - private final int mHeight; - private final BitmapTextureFormat mBitmapTextureFormat; - - // =========================================================== - // Constructors - // =========================================================== - - public BitmapTexture() throws IOException { - this(BitmapTextureFormat.RGBA_8888, TextureOptions.DEFAULT, null); - } - - public BitmapTexture(final BitmapTextureFormat pBitmapTextureFormat) throws IOException { - this(pBitmapTextureFormat, TextureOptions.DEFAULT, null); - } - - public BitmapTexture(final TextureOptions pTextureOptions) throws IOException { - this(BitmapTextureFormat.RGBA_8888, pTextureOptions, null); - } - - public BitmapTexture(final BitmapTextureFormat pBitmapTextureFormat, final TextureOptions pTextureOptions) throws IOException { - this(pBitmapTextureFormat, pTextureOptions, null); - } - - public BitmapTexture(final BitmapTextureFormat pBitmapTextureFormat, final TextureOptions pTextureOptions, final ITextureStateListener pTextureStateListener) throws IOException { - super(pBitmapTextureFormat.getPixelFormat(), pTextureOptions, pTextureStateListener); - this.mBitmapTextureFormat = pBitmapTextureFormat; - - final BitmapFactory.Options decodeOptions = new BitmapFactory.Options(); - decodeOptions.inJustDecodeBounds = true; - - final InputStream in = null; - try { - BitmapFactory.decodeStream(this.onGetInputStream(), null, decodeOptions); - } finally { - StreamUtils.close(in); - } - - this.mWidth = decodeOptions.outWidth; - this.mHeight = decodeOptions.outHeight; - - if(!MathUtils.isPowerOfTwo(this.mWidth) || !MathUtils.isPowerOfTwo(this.mHeight)) { // TODO GLHelper.EXTENSIONS_NON_POWER_OF_TWO - throw new IllegalArgumentException("pWidth and pHeight must be a power of 2!"); - } - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - @Override - public int getWidth() { - return this.mWidth; - } - - @Override - public int getHeight() { - return this.mHeight; - } - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - protected abstract InputStream onGetInputStream() throws IOException; - - @Override - protected void writeTextureToHardware(final GL10 pGL) throws IOException { - final Config bitmapConfig = this.mBitmapTextureFormat.getBitmapConfig(); - final boolean preMultipyAlpha = this.mTextureOptions.mPreMultipyAlpha; - - final BitmapFactory.Options decodeOptions = new BitmapFactory.Options(); - decodeOptions.inPreferredConfig = bitmapConfig; - - final Bitmap bitmap = BitmapFactory.decodeStream(this.onGetInputStream(), null, decodeOptions); - - if(preMultipyAlpha) { - GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0); - } else { - GLHelper.glTexImage2D(pGL, GL10.GL_TEXTURE_2D, 0, bitmap, 0, this.mPixelFormat); - } - - bitmap.recycle(); - } - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== - - public static enum BitmapTextureFormat { - // =========================================================== - // Elements - // =========================================================== - - RGBA_8888(Config.ARGB_8888, PixelFormat.RGBA_8888), - RGB_565(Config.RGB_565, PixelFormat.RGB_565), - RGBA_4444(Config.ARGB_4444, PixelFormat.RGBA_4444), // TODO - A_8(Config.ALPHA_8, PixelFormat.A_8); // TODO - - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - private final Config mBitmapConfig; - private final PixelFormat mPixelFormat; - - // =========================================================== - // Constructors - // =========================================================== - - private BitmapTextureFormat(final Config pBitmapConfig, final PixelFormat pPixelFormat) { - this.mBitmapConfig = pBitmapConfig; - this.mPixelFormat = pPixelFormat; - } - - public static BitmapTextureFormat fromPixelFormat(final PixelFormat pPixelFormat) { - switch(pPixelFormat) { - case RGBA_8888: - return RGBA_8888; - case RGBA_4444: - return RGBA_4444; - case RGB_565: - return RGB_565; - case A_8: - return A_8; - default: - throw new IllegalArgumentException("Unsupported " + PixelFormat.class.getName() + ": '" + pPixelFormat + "'."); - } - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - public Config getBitmapConfig() { - return this.mBitmapConfig; - } - - public PixelFormat getPixelFormat() { - return this.mPixelFormat; - } - - // =========================================================== - // Methods from SuperClass/Interfaces - // =========================================================== - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== - } + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + private final int mWidth; + private final int mHeight; + private final BitmapTextureFormat mBitmapTextureFormat; + + // =========================================================== + // Constructors + // =========================================================== + + public BitmapTexture() throws IOException { + this(BitmapTextureFormat.RGBA_8888, TextureOptions.DEFAULT, null); + } + + public BitmapTexture(final BitmapTextureFormat pBitmapTextureFormat) throws IOException { + this(pBitmapTextureFormat, TextureOptions.DEFAULT, null); + } + + public BitmapTexture(final TextureOptions pTextureOptions) throws IOException { + this(BitmapTextureFormat.RGBA_8888, pTextureOptions, null); + } + + public BitmapTexture(final BitmapTextureFormat pBitmapTextureFormat, final TextureOptions pTextureOptions) throws IOException { + this(pBitmapTextureFormat, pTextureOptions, null); + } + + public BitmapTexture(final BitmapTextureFormat pBitmapTextureFormat, final TextureOptions pTextureOptions, final ITextureStateListener pTextureStateListener) throws IOException { + super(pBitmapTextureFormat.getPixelFormat(), pTextureOptions, pTextureStateListener); + this.mBitmapTextureFormat = pBitmapTextureFormat; + + final BitmapFactory.Options decodeOptions = new BitmapFactory.Options(); + decodeOptions.inJustDecodeBounds = true; + + final InputStream in = null; + try { + BitmapFactory.decodeStream(this.onGetInputStream(), null, decodeOptions); + } finally { + StreamUtils.close(in); + } + + this.mWidth = decodeOptions.outWidth; + this.mHeight = decodeOptions.outHeight; + + if(!MathUtils.isPowerOfTwo(this.mWidth) || !MathUtils.isPowerOfTwo(this.mHeight)) { // TODO GLHelper.EXTENSIONS_NON_POWER_OF_TWO + throw new IllegalArgumentException("pWidth and pHeight must be a power of 2!"); + } + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + @Override + public int getWidth() { + return this.mWidth; + } + + @Override + public int getHeight() { + return this.mHeight; + } + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + protected abstract InputStream onGetInputStream() throws IOException; + + @Override + protected void writeTextureToHardware(final GL10 pGL) throws IOException { + final Config bitmapConfig = this.mBitmapTextureFormat.getBitmapConfig(); + final boolean preMultipyAlpha = this.mTextureOptions.mPreMultipyAlpha; + + final BitmapFactory.Options decodeOptions = new BitmapFactory.Options(); + decodeOptions.inPreferredConfig = bitmapConfig; + + final Bitmap bitmap = BitmapFactory.decodeStream(this.onGetInputStream(), null, decodeOptions); + + if(preMultipyAlpha) { + GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0); + } else { + GLHelper.glTexImage2D(pGL, GL10.GL_TEXTURE_2D, 0, bitmap, 0, this.mPixelFormat); + } + + bitmap.recycle(); + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== + + public static enum BitmapTextureFormat { + // =========================================================== + // Elements + // =========================================================== + + RGBA_8888(Config.ARGB_8888, PixelFormat.RGBA_8888), + RGB_565(Config.RGB_565, PixelFormat.RGB_565), + RGBA_4444(Config.ARGB_4444, PixelFormat.RGBA_4444), // TODO + A_8(Config.ALPHA_8, PixelFormat.A_8); // TODO + + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + private final Config mBitmapConfig; + private final PixelFormat mPixelFormat; + + // =========================================================== + // Constructors + // =========================================================== + + private BitmapTextureFormat(final Config pBitmapConfig, final PixelFormat pPixelFormat) { + this.mBitmapConfig = pBitmapConfig; + this.mPixelFormat = pPixelFormat; + } + + public static BitmapTextureFormat fromPixelFormat(final PixelFormat pPixelFormat) { + switch(pPixelFormat) { + case RGBA_8888: + return RGBA_8888; + case RGBA_4444: + return RGBA_4444; + case RGB_565: + return RGB_565; + case A_8: + return A_8; + default: + throw new IllegalArgumentException("Unsupported " + PixelFormat.class.getName() + ": '" + pPixelFormat + "'."); + } + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + public Config getBitmapConfig() { + return this.mBitmapConfig; + } + + public PixelFormat getPixelFormat() { + return this.mPixelFormat; + } + + // =========================================================== + // Methods from SuperClass/Interfaces + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== + } } diff --git a/AndEngine/src/org/anddev/andengine/opengl/texture/buffer/TextTextureBuffer.java b/AndEngine/src/org/anddev/andengine/opengl/texture/buffer/TextTextureBuffer.java index 4f45a104..8d6724fc 100644 --- a/AndEngine/src/org/anddev/andengine/opengl/texture/buffer/TextTextureBuffer.java +++ b/AndEngine/src/org/anddev/andengine/opengl/texture/buffer/TextTextureBuffer.java @@ -13,79 +13,79 @@ * @since 11:05:56 - 03.04.2010 */ public class TextTextureBuffer extends BufferObject { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - public TextTextureBuffer(final int pCapacity, final int pDrawType, final boolean pManaged) { - super(pCapacity, pDrawType, pManaged); - } + public TextTextureBuffer(final int pCapacity, final int pDrawType, final boolean pManaged) { + super(pCapacity, pDrawType, pManaged); + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - public synchronized void update(final Font pFont, final String[] pLines) { - final FastFloatBuffer textureFloatBuffer = this.getFloatBuffer(); - textureFloatBuffer.position(0); + public synchronized void update(final Font pFont, final String[] pLines) { + final FastFloatBuffer textureFloatBuffer = this.getFloatBuffer(); + textureFloatBuffer.position(0); - final Font font = pFont; - final String[] lines = pLines; + final Font font = pFont; + final String[] lines = pLines; - final int lineCount = lines.length; - for (int i = 0; i < lineCount; i++) { - final String line = lines[i]; + final int lineCount = lines.length; + for (int i = 0; i < lineCount; i++) { + final String line = lines[i]; - final int lineLength = line.length(); - for (int j = 0; j < lineLength; j++) { - final Letter letter = font.getLetter(line.charAt(j)); + final int lineLength = line.length(); + for (int j = 0; j < lineLength; j++) { + final Letter letter = font.getLetter(line.charAt(j)); - final float letterTextureX = letter.mTextureX; - final float letterTextureY = letter.mTextureY; - final float letterTextureX2 = letterTextureX + letter.mTextureWidth; - final float letterTextureY2 = letterTextureY + letter.mTextureHeight; + final float letterTextureX = letter.mTextureX; + final float letterTextureY = letter.mTextureY; + final float letterTextureX2 = letterTextureX + letter.mTextureWidth; + final float letterTextureY2 = letterTextureY + letter.mTextureHeight; - textureFloatBuffer.put(letterTextureX); - textureFloatBuffer.put(letterTextureY); + textureFloatBuffer.put(letterTextureX); + textureFloatBuffer.put(letterTextureY); - textureFloatBuffer.put(letterTextureX); - textureFloatBuffer.put(letterTextureY2); + textureFloatBuffer.put(letterTextureX); + textureFloatBuffer.put(letterTextureY2); - textureFloatBuffer.put(letterTextureX2); - textureFloatBuffer.put(letterTextureY2); + textureFloatBuffer.put(letterTextureX2); + textureFloatBuffer.put(letterTextureY2); - textureFloatBuffer.put(letterTextureX2); - textureFloatBuffer.put(letterTextureY2); + textureFloatBuffer.put(letterTextureX2); + textureFloatBuffer.put(letterTextureY2); - textureFloatBuffer.put(letterTextureX2); - textureFloatBuffer.put(letterTextureY); + textureFloatBuffer.put(letterTextureX2); + textureFloatBuffer.put(letterTextureY); - textureFloatBuffer.put(letterTextureX); - textureFloatBuffer.put(letterTextureY); - } - } - textureFloatBuffer.position(0); + textureFloatBuffer.put(letterTextureX); + textureFloatBuffer.put(letterTextureY); + } + } + textureFloatBuffer.position(0); - this.setHardwareBufferNeedsUpdate(); - } + this.setHardwareBufferNeedsUpdate(); + } - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/opengl/texture/compressed/etc1/ETC1Texture.java b/AndEngine/src/org/anddev/andengine/opengl/texture/compressed/etc1/ETC1Texture.java index 36ce0166..f146cbfd 100644 --- a/AndEngine/src/org/anddev/andengine/opengl/texture/compressed/etc1/ETC1Texture.java +++ b/AndEngine/src/org/anddev/andengine/opengl/texture/compressed/etc1/ETC1Texture.java @@ -24,136 +24,136 @@ * @since 15:32:01 - 13.07.2011 */ public abstract class ETC1Texture extends Texture { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - private ETC1TextureHeader mETC1TextureHeader; + private ETC1TextureHeader mETC1TextureHeader; - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - public ETC1Texture() throws IOException { - this(TextureOptions.DEFAULT, null); - } + public ETC1Texture() throws IOException { + this(TextureOptions.DEFAULT, null); + } - public ETC1Texture(final ITextureStateListener pTextureStateListener) throws IOException { - this(TextureOptions.DEFAULT, pTextureStateListener); - } + public ETC1Texture(final ITextureStateListener pTextureStateListener) throws IOException { + this(TextureOptions.DEFAULT, pTextureStateListener); + } - public ETC1Texture(final TextureOptions pTextureOptions) throws IOException { - this(pTextureOptions, null); - } + public ETC1Texture(final TextureOptions pTextureOptions) throws IOException { + this(pTextureOptions, null); + } - public ETC1Texture(final TextureOptions pTextureOptions, final ITextureStateListener pTextureStateListener) throws IOException { - super(PixelFormat.RGB_565, pTextureOptions, pTextureStateListener); + public ETC1Texture(final TextureOptions pTextureOptions, final ITextureStateListener pTextureStateListener) throws IOException { + super(PixelFormat.RGB_565, pTextureOptions, pTextureStateListener); - InputStream inputStream = null; - try { - inputStream = this.getInputStream(); - - this.mETC1TextureHeader = new ETC1TextureHeader(StreamUtils.streamToBytes(inputStream, ETC1.ETC_PKM_HEADER_SIZE)); - } finally { - StreamUtils.close(inputStream); - } - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - @Override - public int getWidth() { - return this.mETC1TextureHeader.getWidth(); - } - - @Override - public int getHeight() { - return this.mETC1TextureHeader.getHeight(); - } - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - protected abstract InputStream getInputStream() throws IOException; - - @Override - protected void writeTextureToHardware(final GL10 pGL) throws IOException { - final InputStream inputStream = this.getInputStream(); - ETC1Util.loadTexture(GL10.GL_TEXTURE_2D, 0, 0, this.mPixelFormat.getGLFormat(), this.mPixelFormat.getGLType(), inputStream); - } - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== - - public static class ETC1TextureHeader { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - private final ByteBuffer mDataByteBuffer; - - private final int mWidth; - private final int mHeight; - - // =========================================================== - // Constructors - // =========================================================== - - public ETC1TextureHeader(final byte[] pData) { - if(pData.length != ETC1.ETC_PKM_HEADER_SIZE) { - throw new IllegalArgumentException("Invalid " + this.getClass().getSimpleName() + "!"); - } - - this.mDataByteBuffer = ByteBuffer.allocateDirect(ETC1.ETC_PKM_HEADER_SIZE).order(ByteOrder.nativeOrder()); - this.mDataByteBuffer.put(pData, 0, ETC1.ETC_PKM_HEADER_SIZE); - this.mDataByteBuffer.position(0); - - if (!ETC1.isValid(this.mDataByteBuffer)) { - throw new IllegalArgumentException("Invalid " + this.getClass().getSimpleName() + "!"); - } + InputStream inputStream = null; + try { + inputStream = this.getInputStream(); + + this.mETC1TextureHeader = new ETC1TextureHeader(StreamUtils.streamToBytes(inputStream, ETC1.ETC_PKM_HEADER_SIZE)); + } finally { + StreamUtils.close(inputStream); + } + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + @Override + public int getWidth() { + return this.mETC1TextureHeader.getWidth(); + } + + @Override + public int getHeight() { + return this.mETC1TextureHeader.getHeight(); + } + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + protected abstract InputStream getInputStream() throws IOException; + + @Override + protected void writeTextureToHardware(final GL10 pGL) throws IOException { + final InputStream inputStream = this.getInputStream(); + ETC1Util.loadTexture(GL10.GL_TEXTURE_2D, 0, 0, this.mPixelFormat.getGLFormat(), this.mPixelFormat.getGLType(), inputStream); + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== + + public static class ETC1TextureHeader { + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + private final ByteBuffer mDataByteBuffer; + + private final int mWidth; + private final int mHeight; + + // =========================================================== + // Constructors + // =========================================================== + + public ETC1TextureHeader(final byte[] pData) { + if(pData.length != ETC1.ETC_PKM_HEADER_SIZE) { + throw new IllegalArgumentException("Invalid " + this.getClass().getSimpleName() + "!"); + } + + this.mDataByteBuffer = ByteBuffer.allocateDirect(ETC1.ETC_PKM_HEADER_SIZE).order(ByteOrder.nativeOrder()); + this.mDataByteBuffer.put(pData, 0, ETC1.ETC_PKM_HEADER_SIZE); + this.mDataByteBuffer.position(0); + + if (!ETC1.isValid(this.mDataByteBuffer)) { + throw new IllegalArgumentException("Invalid " + this.getClass().getSimpleName() + "!"); + } - this.mWidth = ETC1.getWidth(this.mDataByteBuffer); - this.mHeight = ETC1.getHeight(this.mDataByteBuffer); - } + this.mWidth = ETC1.getWidth(this.mDataByteBuffer); + this.mHeight = ETC1.getHeight(this.mDataByteBuffer); + } - // =========================================================== - // Getter & Setter - // =========================================================== - - public int getWidth() { - return this.mWidth; - } - - public int getHeight() { - return this.mHeight; - } - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== - } + // =========================================================== + // Getter & Setter + // =========================================================== + + public int getWidth() { + return this.mWidth; + } + + public int getHeight() { + return this.mHeight; + } + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== + } } diff --git a/AndEngine/src/org/anddev/andengine/opengl/texture/compressed/pvr/PVRCCZTexture.java b/AndEngine/src/org/anddev/andengine/opengl/texture/compressed/pvr/PVRCCZTexture.java index 31adf590..a4d337b7 100644 --- a/AndEngine/src/org/anddev/andengine/opengl/texture/compressed/pvr/PVRCCZTexture.java +++ b/AndEngine/src/org/anddev/andengine/opengl/texture/compressed/pvr/PVRCCZTexture.java @@ -20,217 +20,217 @@ * @since 14:17:23 - 27.07.2011 */ public abstract class PVRCCZTexture extends PVRTexture { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - private CCZHeader mCCZHeader; - - // =========================================================== - // Constructors - // =========================================================== - - public PVRCCZTexture(final PVRTextureFormat pPVRTextureFormat) throws IllegalArgumentException, IOException { - super(pPVRTextureFormat); - } - - public PVRCCZTexture(final PVRTextureFormat pPVRTextureFormat, final ITextureStateListener pTextureStateListener) throws IllegalArgumentException, IOException { - super(pPVRTextureFormat, pTextureStateListener); - } - - public PVRCCZTexture(final PVRTextureFormat pPVRTextureFormat, final TextureOptions pTextureOptions) throws IllegalArgumentException, IOException { - super(pPVRTextureFormat, pTextureOptions); - } - - public PVRCCZTexture(final PVRTextureFormat pPVRTextureFormat, final TextureOptions pTextureOptions, final ITextureStateListener pTextureStateListener) throws IllegalArgumentException, IOException { - super(pPVRTextureFormat, pTextureOptions, pTextureStateListener); - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - protected final InputStream getInputStream() throws IOException { - final InputStream inputStream = this.onGetInputStream(); - - this.mCCZHeader = new CCZHeader(StreamUtils.streamToBytes(inputStream, CCZHeader.SIZE)); - - return this.mCCZHeader.getCCZCompressionFormat().wrap(inputStream); - } - - @Override - protected ByteBuffer getPVRDataBuffer() throws IOException { - final InputStream inputStream = this.getInputStream(); - try { - final byte[] data = new byte[this.mCCZHeader.getUncompressedSize()]; - StreamUtils.copy(inputStream, data); - return ByteBuffer.wrap(data); - } finally { - StreamUtils.close(inputStream); - } - } - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== - - public static class CCZHeader { - // =========================================================== - // Constants - // =========================================================== - - public static final byte[] MAGIC_IDENTIFIER = { - (byte)'C', - (byte)'C', - (byte)'Z', - (byte)'!' - }; - - public static final int SIZE = 16; - - // =========================================================== - // Fields - // =========================================================== - - private final ByteBuffer mDataByteBuffer; - private final CCZCompressionFormat mCCZCompressionFormat; - - // =========================================================== - // Constructors - // =========================================================== - - public CCZHeader(final byte[] pData) { - this.mDataByteBuffer = ByteBuffer.wrap(pData); - this.mDataByteBuffer.rewind(); - this.mDataByteBuffer.order(ByteOrder.BIG_ENDIAN); - - /* Check magic bytes. */ - if(!ArrayUtils.equals(pData, 0, CCZHeader.MAGIC_IDENTIFIER, 0, CCZHeader.MAGIC_IDENTIFIER.length)) { - throw new IllegalArgumentException("Invalid " + this.getClass().getSimpleName() + "!"); - } - - // TODO Check the version? - - this.mCCZCompressionFormat = CCZCompressionFormat.fromID(this.getCCZCompressionFormatID()); - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - private short getCCZCompressionFormatID() { - return this.mDataByteBuffer.getShort(4); - } - - public CCZCompressionFormat getCCZCompressionFormat() { - return this.mCCZCompressionFormat; - } - - public short getVersion() { - return this.mDataByteBuffer.getShort(6); - } - - public int getUserdata() { - return this.mDataByteBuffer.getInt(8); - } - - public int getUncompressedSize() { - return this.mDataByteBuffer.getInt(12); - } - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== - } - - public static enum CCZCompressionFormat { - // =========================================================== - // Elements - // =========================================================== - - ZLIB((short)0), - BZIP2((short)1), - GZIP((short)2), - NONE((short)3); - - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - private final short mID; - - // =========================================================== - // Constructors - // =========================================================== - - private CCZCompressionFormat(final short pID) { - this.mID = pID; - } - - public InputStream wrap(final InputStream pInputStream) throws IOException { - switch(this) { - case GZIP: - return new GZIPInputStream(pInputStream); - case ZLIB: - return new InflaterInputStream(pInputStream, new Inflater()); - case NONE: - case BZIP2: - default: - throw new IllegalArgumentException("Unexpected " + CCZCompressionFormat.class.getSimpleName() + ": '" + this + "'."); - } - } - - public static CCZCompressionFormat fromID(final short pID) { - final CCZCompressionFormat[] cczCompressionFormats = CCZCompressionFormat.values(); - final int cczCompressionFormatCount = cczCompressionFormats.length; - for(int i = 0; i < cczCompressionFormatCount; i++) { - final CCZCompressionFormat cczCompressionFormat = cczCompressionFormats[i]; - if(cczCompressionFormat.mID == pID) { - return cczCompressionFormat; - } - } - throw new IllegalArgumentException("Unexpected " + CCZCompressionFormat.class.getSimpleName() + "-ID: '" + pID + "'."); - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== - } + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + private CCZHeader mCCZHeader; + + // =========================================================== + // Constructors + // =========================================================== + + public PVRCCZTexture(final PVRTextureFormat pPVRTextureFormat) throws IllegalArgumentException, IOException { + super(pPVRTextureFormat); + } + + public PVRCCZTexture(final PVRTextureFormat pPVRTextureFormat, final ITextureStateListener pTextureStateListener) throws IllegalArgumentException, IOException { + super(pPVRTextureFormat, pTextureStateListener); + } + + public PVRCCZTexture(final PVRTextureFormat pPVRTextureFormat, final TextureOptions pTextureOptions) throws IllegalArgumentException, IOException { + super(pPVRTextureFormat, pTextureOptions); + } + + public PVRCCZTexture(final PVRTextureFormat pPVRTextureFormat, final TextureOptions pTextureOptions, final ITextureStateListener pTextureStateListener) throws IllegalArgumentException, IOException { + super(pPVRTextureFormat, pTextureOptions, pTextureStateListener); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + protected final InputStream getInputStream() throws IOException { + final InputStream inputStream = this.onGetInputStream(); + + this.mCCZHeader = new CCZHeader(StreamUtils.streamToBytes(inputStream, CCZHeader.SIZE)); + + return this.mCCZHeader.getCCZCompressionFormat().wrap(inputStream); + } + + @Override + protected ByteBuffer getPVRDataBuffer() throws IOException { + final InputStream inputStream = this.getInputStream(); + try { + final byte[] data = new byte[this.mCCZHeader.getUncompressedSize()]; + StreamUtils.copy(inputStream, data); + return ByteBuffer.wrap(data); + } finally { + StreamUtils.close(inputStream); + } + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== + + public static class CCZHeader { + // =========================================================== + // Constants + // =========================================================== + + public static final byte[] MAGIC_IDENTIFIER = { + (byte)'C', + (byte)'C', + (byte)'Z', + (byte)'!' + }; + + public static final int SIZE = 16; + + // =========================================================== + // Fields + // =========================================================== + + private final ByteBuffer mDataByteBuffer; + private final CCZCompressionFormat mCCZCompressionFormat; + + // =========================================================== + // Constructors + // =========================================================== + + public CCZHeader(final byte[] pData) { + this.mDataByteBuffer = ByteBuffer.wrap(pData); + this.mDataByteBuffer.rewind(); + this.mDataByteBuffer.order(ByteOrder.BIG_ENDIAN); + + /* Check magic bytes. */ + if(!ArrayUtils.equals(pData, 0, CCZHeader.MAGIC_IDENTIFIER, 0, CCZHeader.MAGIC_IDENTIFIER.length)) { + throw new IllegalArgumentException("Invalid " + this.getClass().getSimpleName() + "!"); + } + + // TODO Check the version? + + this.mCCZCompressionFormat = CCZCompressionFormat.fromID(this.getCCZCompressionFormatID()); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + private short getCCZCompressionFormatID() { + return this.mDataByteBuffer.getShort(4); + } + + public CCZCompressionFormat getCCZCompressionFormat() { + return this.mCCZCompressionFormat; + } + + public short getVersion() { + return this.mDataByteBuffer.getShort(6); + } + + public int getUserdata() { + return this.mDataByteBuffer.getInt(8); + } + + public int getUncompressedSize() { + return this.mDataByteBuffer.getInt(12); + } + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== + } + + public static enum CCZCompressionFormat { + // =========================================================== + // Elements + // =========================================================== + + ZLIB((short)0), + BZIP2((short)1), + GZIP((short)2), + NONE((short)3); + + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + private final short mID; + + // =========================================================== + // Constructors + // =========================================================== + + private CCZCompressionFormat(final short pID) { + this.mID = pID; + } + + public InputStream wrap(final InputStream pInputStream) throws IOException { + switch(this) { + case GZIP: + return new GZIPInputStream(pInputStream); + case ZLIB: + return new InflaterInputStream(pInputStream, new Inflater()); + case NONE: + case BZIP2: + default: + throw new IllegalArgumentException("Unexpected " + CCZCompressionFormat.class.getSimpleName() + ": '" + this + "'."); + } + } + + public static CCZCompressionFormat fromID(final short pID) { + final CCZCompressionFormat[] cczCompressionFormats = CCZCompressionFormat.values(); + final int cczCompressionFormatCount = cczCompressionFormats.length; + for(int i = 0; i < cczCompressionFormatCount; i++) { + final CCZCompressionFormat cczCompressionFormat = cczCompressionFormats[i]; + if(cczCompressionFormat.mID == pID) { + return cczCompressionFormat; + } + } + throw new IllegalArgumentException("Unexpected " + CCZCompressionFormat.class.getSimpleName() + "-ID: '" + pID + "'."); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== + } } diff --git a/AndEngine/src/org/anddev/andengine/opengl/texture/compressed/pvr/PVRGZTexture.java b/AndEngine/src/org/anddev/andengine/opengl/texture/compressed/pvr/PVRGZTexture.java index 5e9bbd7f..71df423d 100644 --- a/AndEngine/src/org/anddev/andengine/opengl/texture/compressed/pvr/PVRGZTexture.java +++ b/AndEngine/src/org/anddev/andengine/opengl/texture/compressed/pvr/PVRGZTexture.java @@ -13,52 +13,52 @@ * @since 14:31:23 - 15.07.2011 */ public abstract class PVRGZTexture extends PVRTexture { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - public PVRGZTexture(final PVRTextureFormat pPVRTextureFormat) throws IllegalArgumentException, IOException { - super(pPVRTextureFormat); - } + public PVRGZTexture(final PVRTextureFormat pPVRTextureFormat) throws IllegalArgumentException, IOException { + super(pPVRTextureFormat); + } - public PVRGZTexture(final PVRTextureFormat pPVRTextureFormat, final ITextureStateListener pTextureStateListener) throws IllegalArgumentException, IOException { - super(pPVRTextureFormat, pTextureStateListener); - } + public PVRGZTexture(final PVRTextureFormat pPVRTextureFormat, final ITextureStateListener pTextureStateListener) throws IllegalArgumentException, IOException { + super(pPVRTextureFormat, pTextureStateListener); + } - public PVRGZTexture(final PVRTextureFormat pPVRTextureFormat, final TextureOptions pTextureOptions) throws IllegalArgumentException, IOException { - super(pPVRTextureFormat, pTextureOptions); - } + public PVRGZTexture(final PVRTextureFormat pPVRTextureFormat, final TextureOptions pTextureOptions) throws IllegalArgumentException, IOException { + super(pPVRTextureFormat, pTextureOptions); + } - public PVRGZTexture(final PVRTextureFormat pPVRTextureFormat, final TextureOptions pTextureOptions, final ITextureStateListener pTextureStateListener) throws IllegalArgumentException, IOException { - super(pPVRTextureFormat, pTextureOptions, pTextureStateListener); - } + public PVRGZTexture(final PVRTextureFormat pPVRTextureFormat, final TextureOptions pTextureOptions, final ITextureStateListener pTextureStateListener) throws IllegalArgumentException, IOException { + super(pPVRTextureFormat, pTextureOptions, pTextureStateListener); + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - @Override - protected GZIPInputStream getInputStream() throws IOException { - return new GZIPInputStream(this.onGetInputStream()); - } + @Override + protected GZIPInputStream getInputStream() throws IOException { + return new GZIPInputStream(this.onGetInputStream()); + } - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/opengl/texture/compressed/pvr/PVRTexture.java b/AndEngine/src/org/anddev/andengine/opengl/texture/compressed/pvr/PVRTexture.java index eba4af32..4a01f551 100644 --- a/AndEngine/src/org/anddev/andengine/opengl/texture/compressed/pvr/PVRTexture.java +++ b/AndEngine/src/org/anddev/andengine/opengl/texture/compressed/pvr/PVRTexture.java @@ -27,371 +27,371 @@ * @see https://github.com/cocos2d/cocos2d-iphone/blob/develop/cocos2d/CCTexturePVR.m */ public abstract class PVRTexture extends Texture { - // =========================================================== - // Constants - // =========================================================== - - public static final int FLAG_MIPMAP = 1<<8; // has mip map levels - public static final int FLAG_TWIDDLE = 1<<9; // is twiddled - public static final int FLAG_BUMPMAP = 1<<10; // has normals encoded for a bump map - public static final int FLAG_TILING = 1<<11; // is bordered for tiled pvr - public static final int FLAG_CUBEMAP = 1<<12; // is a cubemap/skybox - public static final int FLAG_FALSEMIPCOL = 1<<13; // are there false colored MIP levels - public static final int FLAG_VOLUME = 1<<14; // is this a volume texture - public static final int FLAG_ALPHA = 1<<15; // v2.1 is there transparency info in the texture - public static final int FLAG_VERTICALFLIP = 1<<16; // v2.1 is the texture vertically flipped - - // =========================================================== - // Fields - // =========================================================== - - private final PVRTextureHeader mPVRTextureHeader; - - // =========================================================== - // Constructors - // =========================================================== - - public PVRTexture(final PVRTextureFormat pPVRTextureFormat) throws IllegalArgumentException, IOException { - this(pPVRTextureFormat, TextureOptions.DEFAULT, null); - } - - public PVRTexture(final PVRTextureFormat pPVRTextureFormat, final ITextureStateListener pTextureStateListener) throws IllegalArgumentException, IOException { - this(pPVRTextureFormat, TextureOptions.DEFAULT, pTextureStateListener); - } - - public PVRTexture(final PVRTextureFormat pPVRTextureFormat, final TextureOptions pTextureOptions) throws IllegalArgumentException, IOException { - this(pPVRTextureFormat, pTextureOptions, null); - } - - public PVRTexture(final PVRTextureFormat pPVRTextureFormat, final TextureOptions pTextureOptions, final ITextureStateListener pTextureStateListener) throws IllegalArgumentException, IOException { - super(pPVRTextureFormat.getPixelFormat(), pTextureOptions, pTextureStateListener); + // =========================================================== + // Constants + // =========================================================== + + public static final int FLAG_MIPMAP = 1<<8; // has mip map levels + public static final int FLAG_TWIDDLE = 1<<9; // is twiddled + public static final int FLAG_BUMPMAP = 1<<10; // has normals encoded for a bump map + public static final int FLAG_TILING = 1<<11; // is bordered for tiled pvr + public static final int FLAG_CUBEMAP = 1<<12; // is a cubemap/skybox + public static final int FLAG_FALSEMIPCOL = 1<<13; // are there false colored MIP levels + public static final int FLAG_VOLUME = 1<<14; // is this a volume texture + public static final int FLAG_ALPHA = 1<<15; // v2.1 is there transparency info in the texture + public static final int FLAG_VERTICALFLIP = 1<<16; // v2.1 is the texture vertically flipped + + // =========================================================== + // Fields + // =========================================================== + + private final PVRTextureHeader mPVRTextureHeader; + + // =========================================================== + // Constructors + // =========================================================== + + public PVRTexture(final PVRTextureFormat pPVRTextureFormat) throws IllegalArgumentException, IOException { + this(pPVRTextureFormat, TextureOptions.DEFAULT, null); + } + + public PVRTexture(final PVRTextureFormat pPVRTextureFormat, final ITextureStateListener pTextureStateListener) throws IllegalArgumentException, IOException { + this(pPVRTextureFormat, TextureOptions.DEFAULT, pTextureStateListener); + } + + public PVRTexture(final PVRTextureFormat pPVRTextureFormat, final TextureOptions pTextureOptions) throws IllegalArgumentException, IOException { + this(pPVRTextureFormat, pTextureOptions, null); + } + + public PVRTexture(final PVRTextureFormat pPVRTextureFormat, final TextureOptions pTextureOptions, final ITextureStateListener pTextureStateListener) throws IllegalArgumentException, IOException { + super(pPVRTextureFormat.getPixelFormat(), pTextureOptions, pTextureStateListener); - InputStream inputStream = null; - try { - inputStream = this.getInputStream(); - this.mPVRTextureHeader = new PVRTextureHeader(StreamUtils.streamToBytes(inputStream, PVRTextureHeader.SIZE)); - } finally { - StreamUtils.close(inputStream); - } - - if(!MathUtils.isPowerOfTwo(this.getWidth()) || !MathUtils.isPowerOfTwo(this.getHeight())) { // TODO GLHelper.EXTENSIONS_NON_POWER_OF_TWO - throw new IllegalArgumentException("mWidth and mHeight must be a power of 2!"); - } - - 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] ) { - throw new IllegalArgumentException("Invalid PVRTextureFormat: '" + this.mPVRTextureHeader.getPVRTextureFormat() + "'."); - } - - this.mUpdateOnHardwareNeeded = true; - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - @Override - public int getWidth() { - return this.mPVRTextureHeader.getWidth(); - } - - @Override - public int getHeight() { - return this.mPVRTextureHeader.getHeight(); - } - - public PVRTextureHeader getPVRTextureHeader() { - return this.mPVRTextureHeader; - } - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - protected abstract InputStream onGetInputStream() throws IOException; - - protected InputStream getInputStream() throws IOException { - return this.onGetInputStream(); - } - - @Override - protected void generateHardwareTextureID(final GL10 pGL) { - // // TODO - // if(this.mMipMapCount > 0) { - pGL.glPixelStorei(GL10.GL_UNPACK_ALIGNMENT, 1); - // } - - super.generateHardwareTextureID(pGL); - } - - @Override - protected void writeTextureToHardware(final GL10 pGL) throws IOException { - final ByteBuffer pvrDataBuffer = this.getPVRDataBuffer(); - - int width = this.getWidth(); - int height = this.getHeight(); - - final int dataLength = this.mPVRTextureHeader.getDataLength(); - final int glFormat = this.mPixelFormat.getGLFormat(); - final int glType = this.mPixelFormat.getGLType(); - - final int bytesPerPixel = this.mPVRTextureHeader.getBitsPerPixel() / DataConstants.BITS_PER_BYTE; - - /* Calculate the data size for each texture level and respect the minimum number of blocks. */ - int mipmapLevel = 0; - int currentPixelDataOffset = 0; - while (currentPixelDataOffset < dataLength) { - final int currentPixelDataSize = width * height * bytesPerPixel; - - if (mipmapLevel > 0 && (width != height || MathUtils.nextPowerOfTwo(width) != width)) { - Debug.w(String.format("Mipmap level '%u' is not squared. Width: '%u', height: '%u'. Texture won't render correctly.", mipmapLevel, width, height)); - } - - pvrDataBuffer.position(PVRTextureHeader.SIZE + currentPixelDataOffset); - pvrDataBuffer.limit(PVRTextureHeader.SIZE + currentPixelDataOffset + currentPixelDataSize); - ByteBuffer pixelBuffer = pvrDataBuffer.slice(); - - pGL.glTexImage2D(GL10.GL_TEXTURE_2D, mipmapLevel, glFormat, width, height, 0, glFormat, glType, pixelBuffer); - - currentPixelDataOffset += currentPixelDataSize; - - /* Prepare next mipmap level. */ - width = Math.max(width >> 1, 1); - height = Math.max(height >> 1, 1); - - mipmapLevel++; - } - } - - // =========================================================== - // Methods - // =========================================================== - - protected ByteBuffer getPVRDataBuffer() throws IOException { - final InputStream inputStream = this.getInputStream(); - try { - final ByteBufferOutputStream os = new ByteBufferOutputStream(DataConstants.BYTES_PER_KILOBYTE, DataConstants.BYTES_PER_MEGABYTE / 2); - StreamUtils.copy(inputStream, os); - return os.toByteBuffer(); - } finally { - StreamUtils.close(inputStream); - } - } - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== - - public static class PVRTextureHeader { - // =========================================================== - // Constants - // =========================================================== - - public static final byte[] MAGIC_IDENTIFIER = { - (byte)'P', - (byte)'V', - (byte)'R', - (byte)'!' - }; - - public static final int SIZE = 13 * DataConstants.BYTES_PER_INT; - private static final int FORMAT_FLAG_MASK = 0x0FF; - - // =========================================================== - // Fields - // =========================================================== - - private final ByteBuffer mDataByteBuffer; - private final PVRTextureFormat mPVRTextureFormat; - - // =========================================================== - // Constructors - // =========================================================== - - public PVRTextureHeader(final byte[] pData) { - this.mDataByteBuffer = ByteBuffer.wrap(pData); - this.mDataByteBuffer.rewind(); - 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)) { - throw new IllegalArgumentException("Invalid " + this.getClass().getSimpleName() + "!"); - } - - this.mPVRTextureFormat = PVRTextureFormat.fromID(this.getFlags() & PVRTextureHeader.FORMAT_FLAG_MASK); - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - public PVRTextureFormat getPVRTextureFormat() { - return this.mPVRTextureFormat; - } - - public int headerLength() { - return this.mDataByteBuffer.getInt(0 * DataConstants.BYTES_PER_INT); // TODO Constants - } - - public int getHeight() { - return this.mDataByteBuffer.getInt(1 * DataConstants.BYTES_PER_INT); - } - - public int getWidth() { - return this.mDataByteBuffer.getInt(2 * DataConstants.BYTES_PER_INT); - } - - public int getNumMipmaps() { - return this.mDataByteBuffer.getInt(3 * DataConstants.BYTES_PER_INT); - } - - public int getFlags() { - return this.mDataByteBuffer.getInt(4 * DataConstants.BYTES_PER_INT); - } - - public int getDataLength() { - return this.mDataByteBuffer.getInt(5 * DataConstants.BYTES_PER_INT); - } - - public int getBitsPerPixel() { - return this.mDataByteBuffer.getInt(6 * DataConstants.BYTES_PER_INT); - } - - public int getBitmaskRed() { - return this.mDataByteBuffer.getInt(7 * DataConstants.BYTES_PER_INT); - } - - public int getBitmaskGreen() { - return this.mDataByteBuffer.getInt(8 * DataConstants.BYTES_PER_INT); - } - - public int getBitmaskBlue() { - return this.mDataByteBuffer.getInt(9 * DataConstants.BYTES_PER_INT); - } - - public int getBitmaskAlpha() { - return this.mDataByteBuffer.getInt(10 * DataConstants.BYTES_PER_INT); - } - - public boolean hasAlpha() { - return this.getBitmaskAlpha() != 0; - } - - public int getPVRTag() { - return this.mDataByteBuffer.getInt(11 * DataConstants.BYTES_PER_INT); - } - - public int numSurfs() { - return this.mDataByteBuffer.getInt(12 * DataConstants.BYTES_PER_INT); - } - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== - } - - public static enum PVRTextureFormat { - // =========================================================== - // Elements - // =========================================================== - - RGBA_4444(0x10, false, PixelFormat.RGBA_4444), - RGBA_5551(0x11, false, PixelFormat.RGBA_5551), - RGBA_8888(0x12, false, PixelFormat.RGBA_8888), - RGB_565(0x13, false, PixelFormat.RGB_565), - // RGB_555( 0x14, ...), - // RGB_888( 0x15, ...), - I_8(0x16, false, PixelFormat.I_8), - AI_88(0x17, false, PixelFormat.AI_88), - // PVRTC_2(0x18, GL10.GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG, true, TextureFormat.???), - // PVRTC_4(0x19, GL10.GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG, true, TextureFormat.???), - // BGRA_8888(0x1A, GL10.GL_RGBA, TextureFormat.???), - A_8(0x1B, false, PixelFormat.A_8); - - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - private final int mID; - private final boolean mCompressed; - private final PixelFormat mPixelFormat; - - // =========================================================== - // Constructors - // =========================================================== - - private PVRTextureFormat(final int pID, final boolean pCompressed, final PixelFormat pPixelFormat) { - this.mID = pID; - this.mCompressed = pCompressed; - this.mPixelFormat = pPixelFormat; - } - - public static PVRTextureFormat fromID(final int pID) { - final PVRTextureFormat[] pvrTextureFormats = PVRTextureFormat.values(); - final int pvrTextureFormatCount = pvrTextureFormats.length; - for(int i = 0; i < pvrTextureFormatCount; i++) { - final PVRTextureFormat pvrTextureFormat = pvrTextureFormats[i]; - if(pvrTextureFormat.mID == pID) { - return pvrTextureFormat; - } - } - throw new IllegalArgumentException("Unexpected " + PVRTextureFormat.class.getSimpleName() + "-ID: '" + pID + "'."); - } - - public static PVRTextureFormat fromPixelFormat(final PixelFormat pPixelFormat) throws IllegalArgumentException { - switch(pPixelFormat) { - case RGBA_8888: - return PVRTextureFormat.RGBA_8888; - case RGBA_4444: - return PVRTextureFormat.RGBA_4444; - case RGB_565: - return PVRTextureFormat.RGB_565; - default: - throw new IllegalArgumentException("Unsupported " + PixelFormat.class.getName() + ": '" + pPixelFormat + "'."); - } - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - public int getID() { - return this.mID; - } - - public boolean isCompressed() { - return this.mCompressed; - } - - public PixelFormat getPixelFormat() { - return this.mPixelFormat; - } - - // =========================================================== - // Methods from SuperClass/Interfaces - // =========================================================== - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== - } + InputStream inputStream = null; + try { + inputStream = this.getInputStream(); + this.mPVRTextureHeader = new PVRTextureHeader(StreamUtils.streamToBytes(inputStream, PVRTextureHeader.SIZE)); + } finally { + StreamUtils.close(inputStream); + } + + if(!MathUtils.isPowerOfTwo(this.getWidth()) || !MathUtils.isPowerOfTwo(this.getHeight())) { // TODO GLHelper.EXTENSIONS_NON_POWER_OF_TWO + throw new IllegalArgumentException("mWidth and mHeight must be a power of 2!"); + } + + 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] ) { + throw new IllegalArgumentException("Invalid PVRTextureFormat: '" + this.mPVRTextureHeader.getPVRTextureFormat() + "'."); + } + + this.mUpdateOnHardwareNeeded = true; + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + @Override + public int getWidth() { + return this.mPVRTextureHeader.getWidth(); + } + + @Override + public int getHeight() { + return this.mPVRTextureHeader.getHeight(); + } + + public PVRTextureHeader getPVRTextureHeader() { + return this.mPVRTextureHeader; + } + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + protected abstract InputStream onGetInputStream() throws IOException; + + protected InputStream getInputStream() throws IOException { + return this.onGetInputStream(); + } + + @Override + protected void generateHardwareTextureID(final GL10 pGL) { + // // TODO + // if(this.mMipMapCount > 0) { + pGL.glPixelStorei(GL10.GL_UNPACK_ALIGNMENT, 1); + // } + + super.generateHardwareTextureID(pGL); + } + + @Override + protected void writeTextureToHardware(final GL10 pGL) throws IOException { + final ByteBuffer pvrDataBuffer = this.getPVRDataBuffer(); + + int width = this.getWidth(); + int height = this.getHeight(); + + final int dataLength = this.mPVRTextureHeader.getDataLength(); + final int glFormat = this.mPixelFormat.getGLFormat(); + final int glType = this.mPixelFormat.getGLType(); + + final int bytesPerPixel = this.mPVRTextureHeader.getBitsPerPixel() / DataConstants.BITS_PER_BYTE; + + /* Calculate the data size for each texture level and respect the minimum number of blocks. */ + int mipmapLevel = 0; + int currentPixelDataOffset = 0; + while (currentPixelDataOffset < dataLength) { + final int currentPixelDataSize = width * height * bytesPerPixel; + + if (mipmapLevel > 0 && (width != height || MathUtils.nextPowerOfTwo(width) != width)) { + Debug.w(String.format("Mipmap level '%u' is not squared. Width: '%u', height: '%u'. Texture won't render correctly.", mipmapLevel, width, height)); + } + + pvrDataBuffer.position(PVRTextureHeader.SIZE + currentPixelDataOffset); + pvrDataBuffer.limit(PVRTextureHeader.SIZE + currentPixelDataOffset + currentPixelDataSize); + ByteBuffer pixelBuffer = pvrDataBuffer.slice(); + + pGL.glTexImage2D(GL10.GL_TEXTURE_2D, mipmapLevel, glFormat, width, height, 0, glFormat, glType, pixelBuffer); + + currentPixelDataOffset += currentPixelDataSize; + + /* Prepare next mipmap level. */ + width = Math.max(width >> 1, 1); + height = Math.max(height >> 1, 1); + + mipmapLevel++; + } + } + + // =========================================================== + // Methods + // =========================================================== + + protected ByteBuffer getPVRDataBuffer() throws IOException { + final InputStream inputStream = this.getInputStream(); + try { + final ByteBufferOutputStream os = new ByteBufferOutputStream(DataConstants.BYTES_PER_KILOBYTE, DataConstants.BYTES_PER_MEGABYTE / 2); + StreamUtils.copy(inputStream, os); + return os.toByteBuffer(); + } finally { + StreamUtils.close(inputStream); + } + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== + + public static class PVRTextureHeader { + // =========================================================== + // Constants + // =========================================================== + + public static final byte[] MAGIC_IDENTIFIER = { + (byte)'P', + (byte)'V', + (byte)'R', + (byte)'!' + }; + + public static final int SIZE = 13 * DataConstants.BYTES_PER_INT; + private static final int FORMAT_FLAG_MASK = 0x0FF; + + // =========================================================== + // Fields + // =========================================================== + + private final ByteBuffer mDataByteBuffer; + private final PVRTextureFormat mPVRTextureFormat; + + // =========================================================== + // Constructors + // =========================================================== + + public PVRTextureHeader(final byte[] pData) { + this.mDataByteBuffer = ByteBuffer.wrap(pData); + this.mDataByteBuffer.rewind(); + 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)) { + throw new IllegalArgumentException("Invalid " + this.getClass().getSimpleName() + "!"); + } + + this.mPVRTextureFormat = PVRTextureFormat.fromID(this.getFlags() & PVRTextureHeader.FORMAT_FLAG_MASK); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + public PVRTextureFormat getPVRTextureFormat() { + return this.mPVRTextureFormat; + } + + public int headerLength() { + return this.mDataByteBuffer.getInt(0 * DataConstants.BYTES_PER_INT); // TODO Constants + } + + public int getHeight() { + return this.mDataByteBuffer.getInt(1 * DataConstants.BYTES_PER_INT); + } + + public int getWidth() { + return this.mDataByteBuffer.getInt(2 * DataConstants.BYTES_PER_INT); + } + + public int getNumMipmaps() { + return this.mDataByteBuffer.getInt(3 * DataConstants.BYTES_PER_INT); + } + + public int getFlags() { + return this.mDataByteBuffer.getInt(4 * DataConstants.BYTES_PER_INT); + } + + public int getDataLength() { + return this.mDataByteBuffer.getInt(5 * DataConstants.BYTES_PER_INT); + } + + public int getBitsPerPixel() { + return this.mDataByteBuffer.getInt(6 * DataConstants.BYTES_PER_INT); + } + + public int getBitmaskRed() { + return this.mDataByteBuffer.getInt(7 * DataConstants.BYTES_PER_INT); + } + + public int getBitmaskGreen() { + return this.mDataByteBuffer.getInt(8 * DataConstants.BYTES_PER_INT); + } + + public int getBitmaskBlue() { + return this.mDataByteBuffer.getInt(9 * DataConstants.BYTES_PER_INT); + } + + public int getBitmaskAlpha() { + return this.mDataByteBuffer.getInt(10 * DataConstants.BYTES_PER_INT); + } + + public boolean hasAlpha() { + return this.getBitmaskAlpha() != 0; + } + + public int getPVRTag() { + return this.mDataByteBuffer.getInt(11 * DataConstants.BYTES_PER_INT); + } + + public int numSurfs() { + return this.mDataByteBuffer.getInt(12 * DataConstants.BYTES_PER_INT); + } + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== + } + + public static enum PVRTextureFormat { + // =========================================================== + // Elements + // =========================================================== + + RGBA_4444(0x10, false, PixelFormat.RGBA_4444), + RGBA_5551(0x11, false, PixelFormat.RGBA_5551), + RGBA_8888(0x12, false, PixelFormat.RGBA_8888), + RGB_565(0x13, false, PixelFormat.RGB_565), + // RGB_555( 0x14, ...), + // RGB_888( 0x15, ...), + I_8(0x16, false, PixelFormat.I_8), + AI_88(0x17, false, PixelFormat.AI_88), + // PVRTC_2(0x18, GL10.GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG, true, TextureFormat.???), + // PVRTC_4(0x19, GL10.GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG, true, TextureFormat.???), + // BGRA_8888(0x1A, GL10.GL_RGBA, TextureFormat.???), + A_8(0x1B, false, PixelFormat.A_8); + + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + private final int mID; + private final boolean mCompressed; + private final PixelFormat mPixelFormat; + + // =========================================================== + // Constructors + // =========================================================== + + private PVRTextureFormat(final int pID, final boolean pCompressed, final PixelFormat pPixelFormat) { + this.mID = pID; + this.mCompressed = pCompressed; + this.mPixelFormat = pPixelFormat; + } + + public static PVRTextureFormat fromID(final int pID) { + final PVRTextureFormat[] pvrTextureFormats = PVRTextureFormat.values(); + final int pvrTextureFormatCount = pvrTextureFormats.length; + for(int i = 0; i < pvrTextureFormatCount; i++) { + final PVRTextureFormat pvrTextureFormat = pvrTextureFormats[i]; + if(pvrTextureFormat.mID == pID) { + return pvrTextureFormat; + } + } + throw new IllegalArgumentException("Unexpected " + PVRTextureFormat.class.getSimpleName() + "-ID: '" + pID + "'."); + } + + public static PVRTextureFormat fromPixelFormat(final PixelFormat pPixelFormat) throws IllegalArgumentException { + switch(pPixelFormat) { + case RGBA_8888: + return PVRTextureFormat.RGBA_8888; + case RGBA_4444: + return PVRTextureFormat.RGBA_4444; + case RGB_565: + return PVRTextureFormat.RGB_565; + default: + throw new IllegalArgumentException("Unsupported " + PixelFormat.class.getName() + ": '" + pPixelFormat + "'."); + } + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + public int getID() { + return this.mID; + } + + public boolean isCompressed() { + return this.mCompressed; + } + + public PixelFormat getPixelFormat() { + return this.mPixelFormat; + } + + // =========================================================== + // Methods from SuperClass/Interfaces + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== + } } diff --git a/AndEngine/src/org/anddev/andengine/opengl/texture/region/BaseTextureRegion.java b/AndEngine/src/org/anddev/andengine/opengl/texture/region/BaseTextureRegion.java index 64359983..b214900d 100644 --- a/AndEngine/src/org/anddev/andengine/opengl/texture/region/BaseTextureRegion.java +++ b/AndEngine/src/org/anddev/andengine/opengl/texture/region/BaseTextureRegion.java @@ -17,148 +17,148 @@ * @since 14:29:59 - 08.03.2010 */ public abstract class BaseTextureRegion { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== - - protected final ITexture mTexture; - - protected final TextureRegionBuffer mTextureRegionBuffer; - - protected int mWidth; - protected int mHeight; + // =========================================================== + // Fields + // =========================================================== + + protected final ITexture mTexture; + + protected final TextureRegionBuffer mTextureRegionBuffer; + + protected int mWidth; + protected int mHeight; - protected int mTexturePositionX; - protected int mTexturePositionY; - - // =========================================================== - // Constructors - // =========================================================== - - public BaseTextureRegion(final ITexture pTexture, final int pTexturePositionX, final int pTexturePositionY, final int pWidth, final int pHeight) { - this.mTexture = pTexture; - this.mTexturePositionX = pTexturePositionX; - this.mTexturePositionY = pTexturePositionY; - this.mWidth = pWidth; - this.mHeight = pHeight; - - this.mTextureRegionBuffer = new TextureRegionBuffer(this, GL11.GL_STATIC_DRAW, true); + protected int mTexturePositionX; + protected int mTexturePositionY; + + // =========================================================== + // Constructors + // =========================================================== + + public BaseTextureRegion(final ITexture pTexture, final int pTexturePositionX, final int pTexturePositionY, final int pWidth, final int pHeight) { + this.mTexture = pTexture; + this.mTexturePositionX = pTexturePositionX; + this.mTexturePositionY = pTexturePositionY; + this.mWidth = pWidth; + this.mHeight = pHeight; + + this.mTextureRegionBuffer = new TextureRegionBuffer(this, GL11.GL_STATIC_DRAW, true); - this.initTextureBuffer(); - } + this.initTextureBuffer(); + } - protected void initTextureBuffer() { - this.updateTextureRegionBuffer(); - } - - protected abstract BaseTextureRegion deepCopy() throws DeepCopyNotSupportedException; - - // =========================================================== - // Getter & Setter - // =========================================================== - - public int getWidth() { - return this.mWidth; - } - - public int getHeight() { - return this.mHeight; - } - - public void setWidth(final int pWidth) { - this.mWidth = pWidth; - this.updateTextureRegionBuffer(); - } - - public void setHeight(final int pHeight) { - this.mHeight = pHeight; - this.updateTextureRegionBuffer(); - } - - public void setTexturePosition(final int pTexturePositionX, final int pTexturePositionY) { - this.mTexturePositionX = pTexturePositionX; - this.mTexturePositionY = pTexturePositionY; - this.updateTextureRegionBuffer(); - } - - public int getTexturePositionX() { - return this.mTexturePositionX; - } - - public int getTexturePositionY() { - return this.mTexturePositionY; - } - - public ITexture getTexture() { - return this.mTexture; - } - - public TextureRegionBuffer getTextureBuffer() { - return this.mTextureRegionBuffer; - } - - public boolean isFlippedHorizontal() { - return this.mTextureRegionBuffer.isFlippedHorizontal(); - } - - public void setFlippedHorizontal(final boolean pFlippedHorizontal) { - this.mTextureRegionBuffer.setFlippedHorizontal(pFlippedHorizontal); - } - - public boolean isFlippedVertical() { - return this.mTextureRegionBuffer.isFlippedVertical(); - } - - public void setFlippedVertical(final boolean pFlippedVertical) { - this.mTextureRegionBuffer.setFlippedVertical(pFlippedVertical); - } - - public boolean isTextureRegionBufferManaged() { - return this.mTextureRegionBuffer.isManaged(); - } - - /** - * @param pVertexBufferManaged when passing true this {@link BaseTextureRegion} will make its {@link TextureRegionBuffer} unload itself from the active {@link BufferObjectManager}, when this {@link BaseTextureRegion} is finalized/garbage-collected.WARNING: When passing false one needs to take care of that by oneself! - */ - public void setTextureRegionBufferManaged(final boolean pTextureRegionBufferManaged) { - this.mTextureRegionBuffer.setManaged(pTextureRegionBufferManaged); - } - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - public abstract float getTextureCoordinateX1(); - public abstract float getTextureCoordinateY1(); - public abstract float getTextureCoordinateX2(); - public abstract float getTextureCoordinateY2(); - - // =========================================================== - // Methods - // =========================================================== - - protected void updateTextureRegionBuffer() { - this.mTextureRegionBuffer.update(); - } - - public void onApply(final GL10 pGL) { - this.mTexture.bind(pGL); - - if(GLHelper.EXTENSIONS_VERTEXBUFFEROBJECTS) { - final GL11 gl11 = (GL11)pGL; - - this.mTextureRegionBuffer.selectOnHardware(gl11); - GLHelper.texCoordZeroPointer(gl11); - } else { - GLHelper.texCoordPointer(pGL, this.mTextureRegionBuffer.getFloatBuffer()); - } - } - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + protected void initTextureBuffer() { + this.updateTextureRegionBuffer(); + } + + protected abstract BaseTextureRegion deepCopy() throws DeepCopyNotSupportedException; + + // =========================================================== + // Getter & Setter + // =========================================================== + + public int getWidth() { + return this.mWidth; + } + + public int getHeight() { + return this.mHeight; + } + + public void setWidth(final int pWidth) { + this.mWidth = pWidth; + this.updateTextureRegionBuffer(); + } + + public void setHeight(final int pHeight) { + this.mHeight = pHeight; + this.updateTextureRegionBuffer(); + } + + public void setTexturePosition(final int pTexturePositionX, final int pTexturePositionY) { + this.mTexturePositionX = pTexturePositionX; + this.mTexturePositionY = pTexturePositionY; + this.updateTextureRegionBuffer(); + } + + public int getTexturePositionX() { + return this.mTexturePositionX; + } + + public int getTexturePositionY() { + return this.mTexturePositionY; + } + + public ITexture getTexture() { + return this.mTexture; + } + + public TextureRegionBuffer getTextureBuffer() { + return this.mTextureRegionBuffer; + } + + public boolean isFlippedHorizontal() { + return this.mTextureRegionBuffer.isFlippedHorizontal(); + } + + public void setFlippedHorizontal(final boolean pFlippedHorizontal) { + this.mTextureRegionBuffer.setFlippedHorizontal(pFlippedHorizontal); + } + + public boolean isFlippedVertical() { + return this.mTextureRegionBuffer.isFlippedVertical(); + } + + public void setFlippedVertical(final boolean pFlippedVertical) { + this.mTextureRegionBuffer.setFlippedVertical(pFlippedVertical); + } + + public boolean isTextureRegionBufferManaged() { + return this.mTextureRegionBuffer.isManaged(); + } + + /** + * @param pVertexBufferManaged when passing true this {@link BaseTextureRegion} will make its {@link TextureRegionBuffer} unload itself from the active {@link BufferObjectManager}, when this {@link BaseTextureRegion} is finalized/garbage-collected.WARNING: When passing false one needs to take care of that by oneself! + */ + public void setTextureRegionBufferManaged(final boolean pTextureRegionBufferManaged) { + this.mTextureRegionBuffer.setManaged(pTextureRegionBufferManaged); + } + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + public abstract float getTextureCoordinateX1(); + public abstract float getTextureCoordinateY1(); + public abstract float getTextureCoordinateX2(); + public abstract float getTextureCoordinateY2(); + + // =========================================================== + // Methods + // =========================================================== + + protected void updateTextureRegionBuffer() { + this.mTextureRegionBuffer.update(); + } + + public void onApply(final GL10 pGL) { + this.mTexture.bind(pGL); + + if(GLHelper.EXTENSIONS_VERTEXBUFFEROBJECTS) { + final GL11 gl11 = (GL11)pGL; + + this.mTextureRegionBuffer.selectOnHardware(gl11); + GLHelper.texCoordZeroPointer(gl11); + } else { + GLHelper.texCoordPointer(pGL, this.mTextureRegionBuffer.getFloatBuffer()); + } + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/opengl/texture/region/TextureRegion.java b/AndEngine/src/org/anddev/andengine/opengl/texture/region/TextureRegion.java index d4215f89..6eb25f1f 100644 --- a/AndEngine/src/org/anddev/andengine/opengl/texture/region/TextureRegion.java +++ b/AndEngine/src/org/anddev/andengine/opengl/texture/region/TextureRegion.java @@ -10,60 +10,60 @@ * @since 14:29:59 - 08.03.2010 */ public class TextureRegion extends BaseTextureRegion { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - public TextureRegion(final ITexture pTexture, final int pTexturePositionX, final int pTexturePositionY, final int pWidth, final int pHeight) { - super(pTexture, pTexturePositionX, pTexturePositionY, pWidth, pHeight); - } + public TextureRegion(final ITexture pTexture, final int pTexturePositionX, final int pTexturePositionY, final int pWidth, final int pHeight) { + super(pTexture, pTexturePositionX, pTexturePositionY, pWidth, pHeight); + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - @Override - public TextureRegion deepCopy() { - return new TextureRegion(this.mTexture, this.mTexturePositionX, this.mTexturePositionY, this.mWidth, this.mHeight); - } + @Override + public TextureRegion deepCopy() { + return new TextureRegion(this.mTexture, this.mTexturePositionX, this.mTexturePositionY, this.mWidth, this.mHeight); + } - @Override - public float getTextureCoordinateX1() { - return (float) this.mTexturePositionX / this.mTexture.getWidth(); - } + @Override + public float getTextureCoordinateX1() { + return (float) this.mTexturePositionX / this.mTexture.getWidth(); + } - @Override - public float getTextureCoordinateY1() { - return (float) this.mTexturePositionY / this.mTexture.getHeight(); - } + @Override + public float getTextureCoordinateY1() { + return (float) this.mTexturePositionY / this.mTexture.getHeight(); + } - @Override - public float getTextureCoordinateX2() { - return (float) (this.mTexturePositionX + this.mWidth) / this.mTexture.getWidth(); - } + @Override + public float getTextureCoordinateX2() { + return (float) (this.mTexturePositionX + this.mWidth) / this.mTexture.getWidth(); + } - @Override - public float getTextureCoordinateY2() { - return (float) (this.mTexturePositionY + this.mHeight) / this.mTexture.getHeight(); - } + @Override + public float getTextureCoordinateY2() { + return (float) (this.mTexturePositionY + this.mHeight) / this.mTexture.getHeight(); + } - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/opengl/texture/region/TextureRegionFactory.java b/AndEngine/src/org/anddev/andengine/opengl/texture/region/TextureRegionFactory.java index da3167c1..1cc830e7 100644 --- a/AndEngine/src/org/anddev/andengine/opengl/texture/region/TextureRegionFactory.java +++ b/AndEngine/src/org/anddev/andengine/opengl/texture/region/TextureRegionFactory.java @@ -14,51 +14,51 @@ * @since 18:15:14 - 09.03.2010 */ public class TextureRegionFactory { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - // =========================================================== - // Methods - // =========================================================== - - public static TextureRegion extractFromTexture(final ITexture pTexture, final int pTexturePositionX, final int pTexturePositionY, final int pWidth, final int pHeight, final boolean pTextureRegionBufferManaged) { - final TextureRegion textureRegion = new TextureRegion(pTexture, pTexturePositionX, pTexturePositionY, pWidth, pHeight); - textureRegion.setTextureRegionBufferManaged(pTextureRegionBufferManaged); - return textureRegion; - } + // =========================================================== + // Methods + // =========================================================== + + public static TextureRegion extractFromTexture(final ITexture pTexture, final int pTexturePositionX, final int pTexturePositionY, final int pWidth, final int pHeight, final boolean pTextureRegionBufferManaged) { + final TextureRegion textureRegion = new TextureRegion(pTexture, pTexturePositionX, pTexturePositionY, pWidth, pHeight); + textureRegion.setTextureRegionBufferManaged(pTextureRegionBufferManaged); + return textureRegion; + } - public static TextureRegion createFromSource(final ITextureAtlas pTextureAtlas, final T pTextureAtlasSource, final int pTexturePositionX, final int pTexturePositionY, final boolean pCreateTextureRegionBuffersManaged) { - final TextureRegion textureRegion = new TextureRegion(pTextureAtlas, pTexturePositionX, pTexturePositionY, pTextureAtlasSource.getWidth(), pTextureAtlasSource.getHeight()); - pTextureAtlas.addTextureAtlasSource(pTextureAtlasSource, textureRegion.getTexturePositionX(), textureRegion.getTexturePositionY()); - textureRegion.setTextureRegionBufferManaged(pCreateTextureRegionBuffersManaged); - return textureRegion; - } + public static TextureRegion createFromSource(final ITextureAtlas pTextureAtlas, final T pTextureAtlasSource, final int pTexturePositionX, final int pTexturePositionY, final boolean pCreateTextureRegionBuffersManaged) { + final TextureRegion textureRegion = new TextureRegion(pTextureAtlas, pTexturePositionX, pTexturePositionY, pTextureAtlasSource.getWidth(), pTextureAtlasSource.getHeight()); + pTextureAtlas.addTextureAtlasSource(pTextureAtlasSource, textureRegion.getTexturePositionX(), textureRegion.getTexturePositionY()); + textureRegion.setTextureRegionBufferManaged(pCreateTextureRegionBuffersManaged); + return textureRegion; + } - public static TiledTextureRegion createTiledFromSource(final ITextureAtlas pTextureAtlas, final T pTextureAtlasSource, final int pTexturePositionX, final int pTexturePositionY, final int pTileColumns, final int pTileRows, final boolean pCreateTextureRegionBuffersManaged) { - final TiledTextureRegion tiledTextureRegion = new TiledTextureRegion(pTextureAtlas, pTexturePositionX, pTexturePositionY, pTextureAtlasSource.getWidth(), pTextureAtlasSource.getHeight(), pTileColumns, pTileRows); - pTextureAtlas.addTextureAtlasSource(pTextureAtlasSource, tiledTextureRegion.getTexturePositionX(), tiledTextureRegion.getTexturePositionY()); - tiledTextureRegion.setTextureRegionBufferManaged(pCreateTextureRegionBuffersManaged); - return tiledTextureRegion; - } + public static TiledTextureRegion createTiledFromSource(final ITextureAtlas pTextureAtlas, final T pTextureAtlasSource, final int pTexturePositionX, final int pTexturePositionY, final int pTileColumns, final int pTileRows, final boolean pCreateTextureRegionBuffersManaged) { + final TiledTextureRegion tiledTextureRegion = new TiledTextureRegion(pTextureAtlas, pTexturePositionX, pTexturePositionY, pTextureAtlasSource.getWidth(), pTextureAtlasSource.getHeight(), pTileColumns, pTileRows); + pTextureAtlas.addTextureAtlasSource(pTextureAtlasSource, tiledTextureRegion.getTexturePositionX(), tiledTextureRegion.getTexturePositionY()); + tiledTextureRegion.setTextureRegionBufferManaged(pCreateTextureRegionBuffersManaged); + return tiledTextureRegion; + } - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/opengl/texture/region/TextureRegionLibrary.java b/AndEngine/src/org/anddev/andengine/opengl/texture/region/TextureRegionLibrary.java index 877d7e16..e1350f04 100644 --- a/AndEngine/src/org/anddev/andengine/opengl/texture/region/TextureRegionLibrary.java +++ b/AndEngine/src/org/anddev/andengine/opengl/texture/region/TextureRegionLibrary.java @@ -10,44 +10,44 @@ * @since 11:52:26 - 20.08.2010 */ public class TextureRegionLibrary extends Library { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - // =========================================================== - // Constructors - // =========================================================== - - public TextureRegionLibrary(final int pInitialCapacity) { - super(pInitialCapacity); - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - @Override - public TextureRegion get(final int pID) { - return (TextureRegion) super.get(pID); - } - - public TiledTextureRegion getTiled(final int pID) { - return (TiledTextureRegion) this.mItems.get(pID); - } - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + // =========================================================== + // Constructors + // =========================================================== + + public TextureRegionLibrary(final int pInitialCapacity) { + super(pInitialCapacity); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + @Override + public TextureRegion get(final int pID) { + return (TextureRegion) super.get(pID); + } + + public TiledTextureRegion getTiled(final int pID) { + return (TiledTextureRegion) this.mItems.get(pID); + } + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/opengl/texture/region/TiledTextureRegion.java b/AndEngine/src/org/anddev/andengine/opengl/texture/region/TiledTextureRegion.java index edcf7541..a83f4b51 100644 --- a/AndEngine/src/org/anddev/andengine/opengl/texture/region/TiledTextureRegion.java +++ b/AndEngine/src/org/anddev/andengine/opengl/texture/region/TiledTextureRegion.java @@ -10,134 +10,134 @@ * @since 18:14:42 - 09.03.2010 */ public class TiledTextureRegion extends BaseTextureRegion { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - private final int mTileColumns; - private final int mTileRows; - private int mCurrentTileColumn; - private int mCurrentTileRow; - private final int mTileCount; - - // =========================================================== - // Constructors - // =========================================================== - - public TiledTextureRegion(final ITexture pTexture, final int pTexturePositionX, final int pTexturePositionY, final int pWidth, final int pHeight, final int pTileColumns, final int pTileRows) { - super(pTexture, pTexturePositionX, pTexturePositionY, pWidth, pHeight); - this.mTileColumns = pTileColumns; - this.mTileRows = pTileRows; - this.mTileCount = this.mTileColumns * this.mTileRows; - this.mCurrentTileColumn = 0; - this.mCurrentTileRow = 0; - - this.initTextureBuffer(); - } - - @Override - protected void initTextureBuffer() { - if(this.mTileRows != 0 && this.mTileColumns != 0) { - super.initTextureBuffer(); - } - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - public int getTileCount() { - return this.mTileCount; - } - - public int getTileWidth() { - return super.getWidth() / this.mTileColumns; - } - - public int getTileHeight() { - return super.getHeight() / this.mTileRows; - } - - public int getCurrentTileColumn() { - return this.mCurrentTileColumn; - } - - public int getCurrentTileRow() { - return this.mCurrentTileRow; - } - - public int getCurrentTileIndex() { - return this.mCurrentTileRow * this.mTileColumns + this.mCurrentTileColumn; - } - - public void setCurrentTileIndex(final int pTileColumn, final int pTileRow) { - if(pTileColumn != this.mCurrentTileColumn || pTileRow != this.mCurrentTileRow) { - this.mCurrentTileColumn = pTileColumn; - this.mCurrentTileRow = pTileRow; - super.updateTextureRegionBuffer(); - } - } - - public void setCurrentTileIndex(final int pTileIndex) { - if(pTileIndex < this.mTileCount) { - final int tileColumns = this.mTileColumns; - this.setCurrentTileIndex(pTileIndex % tileColumns, pTileIndex / tileColumns); - } - } - - public int getTexturePositionOfCurrentTileX() { - return super.getTexturePositionX() + this.mCurrentTileColumn * this.getTileWidth(); - } - - public int getTexturePositionOfCurrentTileY() { - return super.getTexturePositionY() + this.mCurrentTileRow * this.getTileHeight(); - } - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - public TiledTextureRegion deepCopy() { - final TiledTextureRegion deepCopy = new TiledTextureRegion(this.mTexture, this.getTexturePositionX(), this.getTexturePositionY(), this.getWidth(), this.getHeight(), this.mTileColumns, this.mTileRows); - deepCopy.setCurrentTileIndex(this.mCurrentTileColumn, this.mCurrentTileRow); - return deepCopy; - } - - @Override - public float getTextureCoordinateX1() { - return (float)this.getTexturePositionOfCurrentTileX() / this.mTexture.getWidth(); - } - - @Override - public float getTextureCoordinateY1() { - return (float)this.getTexturePositionOfCurrentTileY() / this.mTexture.getHeight(); - } - - @Override - public float getTextureCoordinateX2() { - return (float)(this.getTexturePositionOfCurrentTileX() + this.getTileWidth()) / this.mTexture.getWidth(); - } - - @Override - public float getTextureCoordinateY2() { - return (float)(this.getTexturePositionOfCurrentTileY() + this.getTileHeight()) / this.mTexture.getHeight(); - } - - // =========================================================== - // Methods - // =========================================================== - - public void nextTile() { - final int tileIndex = (this.getCurrentTileIndex() + 1) % this.getTileCount(); - this.setCurrentTileIndex(tileIndex); - } - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + private final int mTileColumns; + private final int mTileRows; + private int mCurrentTileColumn; + private int mCurrentTileRow; + private final int mTileCount; + + // =========================================================== + // Constructors + // =========================================================== + + public TiledTextureRegion(final ITexture pTexture, final int pTexturePositionX, final int pTexturePositionY, final int pWidth, final int pHeight, final int pTileColumns, final int pTileRows) { + super(pTexture, pTexturePositionX, pTexturePositionY, pWidth, pHeight); + this.mTileColumns = pTileColumns; + this.mTileRows = pTileRows; + this.mTileCount = this.mTileColumns * this.mTileRows; + this.mCurrentTileColumn = 0; + this.mCurrentTileRow = 0; + + this.initTextureBuffer(); + } + + @Override + protected void initTextureBuffer() { + if(this.mTileRows != 0 && this.mTileColumns != 0) { + super.initTextureBuffer(); + } + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + public int getTileCount() { + return this.mTileCount; + } + + public int getTileWidth() { + return super.getWidth() / this.mTileColumns; + } + + public int getTileHeight() { + return super.getHeight() / this.mTileRows; + } + + public int getCurrentTileColumn() { + return this.mCurrentTileColumn; + } + + public int getCurrentTileRow() { + return this.mCurrentTileRow; + } + + public int getCurrentTileIndex() { + return this.mCurrentTileRow * this.mTileColumns + this.mCurrentTileColumn; + } + + public void setCurrentTileIndex(final int pTileColumn, final int pTileRow) { + if(pTileColumn != this.mCurrentTileColumn || pTileRow != this.mCurrentTileRow) { + this.mCurrentTileColumn = pTileColumn; + this.mCurrentTileRow = pTileRow; + super.updateTextureRegionBuffer(); + } + } + + public void setCurrentTileIndex(final int pTileIndex) { + if(pTileIndex < this.mTileCount) { + final int tileColumns = this.mTileColumns; + this.setCurrentTileIndex(pTileIndex % tileColumns, pTileIndex / tileColumns); + } + } + + public int getTexturePositionOfCurrentTileX() { + return super.getTexturePositionX() + this.mCurrentTileColumn * this.getTileWidth(); + } + + public int getTexturePositionOfCurrentTileY() { + return super.getTexturePositionY() + this.mCurrentTileRow * this.getTileHeight(); + } + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + public TiledTextureRegion deepCopy() { + final TiledTextureRegion deepCopy = new TiledTextureRegion(this.mTexture, this.getTexturePositionX(), this.getTexturePositionY(), this.getWidth(), this.getHeight(), this.mTileColumns, this.mTileRows); + deepCopy.setCurrentTileIndex(this.mCurrentTileColumn, this.mCurrentTileRow); + return deepCopy; + } + + @Override + public float getTextureCoordinateX1() { + return (float)this.getTexturePositionOfCurrentTileX() / this.mTexture.getWidth(); + } + + @Override + public float getTextureCoordinateY1() { + return (float)this.getTexturePositionOfCurrentTileY() / this.mTexture.getHeight(); + } + + @Override + public float getTextureCoordinateX2() { + return (float)(this.getTexturePositionOfCurrentTileX() + this.getTileWidth()) / this.mTexture.getWidth(); + } + + @Override + public float getTextureCoordinateY2() { + return (float)(this.getTexturePositionOfCurrentTileY() + this.getTileHeight()) / this.mTexture.getHeight(); + } + + // =========================================================== + // Methods + // =========================================================== + + public void nextTile() { + final int tileIndex = (this.getCurrentTileIndex() + 1) % this.getTileCount(); + this.setCurrentTileIndex(tileIndex); + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/opengl/texture/region/buffer/SpriteBatchTextureRegionBuffer.java b/AndEngine/src/org/anddev/andengine/opengl/texture/region/buffer/SpriteBatchTextureRegionBuffer.java index a69bde25..b0c47140 100644 --- a/AndEngine/src/org/anddev/andengine/opengl/texture/region/buffer/SpriteBatchTextureRegionBuffer.java +++ b/AndEngine/src/org/anddev/andengine/opengl/texture/region/buffer/SpriteBatchTextureRegionBuffer.java @@ -14,89 +14,89 @@ * @since 12:32:14 - 14.06.2011 */ public class SpriteBatchTextureRegionBuffer extends BufferObject { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - protected int mIndex; + protected int mIndex; - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - public SpriteBatchTextureRegionBuffer(final int pCapacity, final int pDrawType, final boolean pManaged) { - super(pCapacity * 2 * SpriteBatchVertexBuffer.VERTICES_PER_RECTANGLE, pDrawType, pManaged); - } + public SpriteBatchTextureRegionBuffer(final int pCapacity, final int pDrawType, final boolean pManaged) { + super(pCapacity * 2 * SpriteBatchVertexBuffer.VERTICES_PER_RECTANGLE, pDrawType, pManaged); + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - public int getIndex() { - return this.mIndex; - } + public int getIndex() { + return this.mIndex; + } - public void setIndex(final int pIndex) { - this.mIndex = pIndex; - } + public void setIndex(final int pIndex) { + this.mIndex = pIndex; + } - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - public void add(final BaseTextureRegion pTextureRegion) { - final ITexture texture = pTextureRegion.getTexture(); + public void add(final BaseTextureRegion pTextureRegion) { + final ITexture texture = pTextureRegion.getTexture(); - if(texture == null) { // TODO Check really needed? - return; - } + if(texture == null) { // TODO Check really needed? + return; + } - final int x1 = Float.floatToRawIntBits(pTextureRegion.getTextureCoordinateX1()); - final int y1 = Float.floatToRawIntBits(pTextureRegion.getTextureCoordinateY1()); - final int x2 = Float.floatToRawIntBits(pTextureRegion.getTextureCoordinateX2()); - final int y2 = Float.floatToRawIntBits(pTextureRegion.getTextureCoordinateY2()); + final int x1 = Float.floatToRawIntBits(pTextureRegion.getTextureCoordinateX1()); + final int y1 = Float.floatToRawIntBits(pTextureRegion.getTextureCoordinateY1()); + final int x2 = Float.floatToRawIntBits(pTextureRegion.getTextureCoordinateX2()); + final int y2 = Float.floatToRawIntBits(pTextureRegion.getTextureCoordinateY2()); - final int[] bufferData = this.mBufferData; + final int[] bufferData = this.mBufferData; - int index = this.mIndex; - bufferData[index++] = x1; - bufferData[index++] = y1; + int index = this.mIndex; + bufferData[index++] = x1; + bufferData[index++] = y1; - bufferData[index++] = x1; - bufferData[index++] = y2; + bufferData[index++] = x1; + bufferData[index++] = y2; - bufferData[index++] = x2; - bufferData[index++] = y1; + bufferData[index++] = x2; + bufferData[index++] = y1; - bufferData[index++] = x2; - bufferData[index++] = y1; + bufferData[index++] = x2; + bufferData[index++] = y1; - bufferData[index++] = x1; - bufferData[index++] = y2; + bufferData[index++] = x1; + bufferData[index++] = y2; - bufferData[index++] = x2; - bufferData[index++] = y2; - this.mIndex = index; - } + bufferData[index++] = x2; + bufferData[index++] = y2; + this.mIndex = index; + } - public void submit() { - final FastFloatBuffer buffer = this.mFloatBuffer; - buffer.position(0); - buffer.put(this.mBufferData); - buffer.position(0); + public void submit() { + final FastFloatBuffer buffer = this.mFloatBuffer; + buffer.position(0); + buffer.put(this.mBufferData); + buffer.position(0); - super.setHardwareBufferNeedsUpdate(); - } + super.setHardwareBufferNeedsUpdate(); + } - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/opengl/texture/region/buffer/TextureRegionBuffer.java b/AndEngine/src/org/anddev/andengine/opengl/texture/region/buffer/TextureRegionBuffer.java index 788beab7..1d98ffa0 100644 --- a/AndEngine/src/org/anddev/andengine/opengl/texture/region/buffer/TextureRegionBuffer.java +++ b/AndEngine/src/org/anddev/andengine/opengl/texture/region/buffer/TextureRegionBuffer.java @@ -14,138 +14,138 @@ * @since 19:05:50 - 09.03.2010 */ public class TextureRegionBuffer extends BufferObject { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - protected final BaseTextureRegion mTextureRegion; - private boolean mFlippedVertical; - private boolean mFlippedHorizontal; - - // =========================================================== - // Constructors - // =========================================================== - - public TextureRegionBuffer(final BaseTextureRegion pBaseTextureRegion, final int pDrawType, final boolean pManaged) { - super(2 * VERTICES_PER_RECTANGLE, pDrawType, pManaged); - this.mTextureRegion = pBaseTextureRegion; - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - public BaseTextureRegion getTextureRegion() { - return this.mTextureRegion; - } - - public boolean isFlippedHorizontal() { - return this.mFlippedHorizontal; - } - - public void setFlippedHorizontal(final boolean pFlippedHorizontal) { - if(this.mFlippedHorizontal != pFlippedHorizontal) { - this.mFlippedHorizontal = pFlippedHorizontal; - this.update(); - } - } - - public boolean isFlippedVertical() { - return this.mFlippedVertical; - } - - public void setFlippedVertical(final boolean pFlippedVertical) { - if(this.mFlippedVertical != pFlippedVertical) { - this.mFlippedVertical = pFlippedVertical; - this.update(); - } - } - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - // =========================================================== - // Methods - // =========================================================== - - public synchronized void update() { - final BaseTextureRegion textureRegion = this.mTextureRegion; - - final int x1 = Float.floatToRawIntBits(textureRegion.getTextureCoordinateX1()); - final int y1 = Float.floatToRawIntBits(textureRegion.getTextureCoordinateY1()); - final int x2 = Float.floatToRawIntBits(textureRegion.getTextureCoordinateX2()); - final int y2 = Float.floatToRawIntBits(textureRegion.getTextureCoordinateY2()); - - final int[] bufferData = this.mBufferData; - - if(this.mFlippedVertical) { - if(this.mFlippedHorizontal) { - bufferData[0] = x2; - bufferData[1] = y2; - - bufferData[2] = x2; - bufferData[3] = y1; - - bufferData[4] = x1; - bufferData[5] = y2; - - bufferData[6] = x1; - bufferData[7] = y1; - } else { - bufferData[0] = x1; - bufferData[1] = y2; - - bufferData[2] = x1; - bufferData[3] = y1; - - bufferData[4] = x2; - bufferData[5] = y2; - - bufferData[6] = x2; - bufferData[7] = y1; - } - } else { - if(this.mFlippedHorizontal) { - bufferData[0] = x2; - bufferData[1] = y1; - - bufferData[2] = x2; - bufferData[3] = y2; - - bufferData[4] = x1; - bufferData[5] = y1; - - bufferData[6] = x1; - bufferData[7] = y2; - } else { - bufferData[0] = x1; - bufferData[1] = y1; - - bufferData[2] = x1; - bufferData[3] = y2; - - bufferData[4] = x2; - bufferData[5] = y1; - - bufferData[6] = x2; - bufferData[7] = y2; - } - } - - final FastFloatBuffer buffer = this.mFloatBuffer; - buffer.position(0); - buffer.put(bufferData); - buffer.position(0); - - super.setHardwareBufferNeedsUpdate(); - } - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + protected final BaseTextureRegion mTextureRegion; + private boolean mFlippedVertical; + private boolean mFlippedHorizontal; + + // =========================================================== + // Constructors + // =========================================================== + + public TextureRegionBuffer(final BaseTextureRegion pBaseTextureRegion, final int pDrawType, final boolean pManaged) { + super(2 * VERTICES_PER_RECTANGLE, pDrawType, pManaged); + this.mTextureRegion = pBaseTextureRegion; + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + public BaseTextureRegion getTextureRegion() { + return this.mTextureRegion; + } + + public boolean isFlippedHorizontal() { + return this.mFlippedHorizontal; + } + + public void setFlippedHorizontal(final boolean pFlippedHorizontal) { + if(this.mFlippedHorizontal != pFlippedHorizontal) { + this.mFlippedHorizontal = pFlippedHorizontal; + this.update(); + } + } + + public boolean isFlippedVertical() { + return this.mFlippedVertical; + } + + public void setFlippedVertical(final boolean pFlippedVertical) { + if(this.mFlippedVertical != pFlippedVertical) { + this.mFlippedVertical = pFlippedVertical; + this.update(); + } + } + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + public synchronized void update() { + final BaseTextureRegion textureRegion = this.mTextureRegion; + + final int x1 = Float.floatToRawIntBits(textureRegion.getTextureCoordinateX1()); + final int y1 = Float.floatToRawIntBits(textureRegion.getTextureCoordinateY1()); + final int x2 = Float.floatToRawIntBits(textureRegion.getTextureCoordinateX2()); + final int y2 = Float.floatToRawIntBits(textureRegion.getTextureCoordinateY2()); + + final int[] bufferData = this.mBufferData; + + if(this.mFlippedVertical) { + if(this.mFlippedHorizontal) { + bufferData[0] = x2; + bufferData[1] = y2; + + bufferData[2] = x2; + bufferData[3] = y1; + + bufferData[4] = x1; + bufferData[5] = y2; + + bufferData[6] = x1; + bufferData[7] = y1; + } else { + bufferData[0] = x1; + bufferData[1] = y2; + + bufferData[2] = x1; + bufferData[3] = y1; + + bufferData[4] = x2; + bufferData[5] = y2; + + bufferData[6] = x2; + bufferData[7] = y1; + } + } else { + if(this.mFlippedHorizontal) { + bufferData[0] = x2; + bufferData[1] = y1; + + bufferData[2] = x2; + bufferData[3] = y2; + + bufferData[4] = x1; + bufferData[5] = y1; + + bufferData[6] = x1; + bufferData[7] = y2; + } else { + bufferData[0] = x1; + bufferData[1] = y1; + + bufferData[2] = x1; + bufferData[3] = y2; + + bufferData[4] = x2; + bufferData[5] = y1; + + bufferData[6] = x2; + bufferData[7] = y2; + } + } + + final FastFloatBuffer buffer = this.mFloatBuffer; + buffer.position(0); + buffer.put(bufferData); + buffer.position(0); + + super.setHardwareBufferNeedsUpdate(); + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/opengl/texture/source/BaseTextureAtlasSource.java b/AndEngine/src/org/anddev/andengine/opengl/texture/source/BaseTextureAtlasSource.java index fe39d9d7..600f1192 100644 --- a/AndEngine/src/org/anddev/andengine/opengl/texture/source/BaseTextureAtlasSource.java +++ b/AndEngine/src/org/anddev/andengine/opengl/texture/source/BaseTextureAtlasSource.java @@ -10,64 +10,64 @@ * @since 13:55:12 - 12.07.2011 */ public abstract class BaseTextureAtlasSource implements ITextureAtlasSource { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - protected int mTexturePositionX; - protected int mTexturePositionY; - - // =========================================================== - // Constructors - // =========================================================== - - public BaseTextureAtlasSource(final int pTexturePositionX, final int pTexturePositionY) { - this.mTexturePositionX = pTexturePositionX; - this.mTexturePositionY = pTexturePositionY; - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - @Override - public int getTexturePositionX() { - return this.mTexturePositionX; - } - - @Override - public int getTexturePositionY() { - return this.mTexturePositionY; - } - - @Override - public void setTexturePositionX(final int pTexturePositionX) { - this.mTexturePositionX = pTexturePositionX; - } - - @Override - public void setTexturePositionY(final int pTexturePositionY) { - this.mTexturePositionY = pTexturePositionY; - } - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - public String toString() { - return this.getClass().getSimpleName() + "( " + this.getWidth() + "x" + this.getHeight() + " @ "+ this.mTexturePositionX + "/" + this.mTexturePositionY + " )"; - } - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== -} \ No newline at end of file + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + protected int mTexturePositionX; + protected int mTexturePositionY; + + // =========================================================== + // Constructors + // =========================================================== + + public BaseTextureAtlasSource(final int pTexturePositionX, final int pTexturePositionY) { + this.mTexturePositionX = pTexturePositionX; + this.mTexturePositionY = pTexturePositionY; + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + @Override + public int getTexturePositionX() { + return this.mTexturePositionX; + } + + @Override + public int getTexturePositionY() { + return this.mTexturePositionY; + } + + @Override + public void setTexturePositionX(final int pTexturePositionX) { + this.mTexturePositionX = pTexturePositionX; + } + + @Override + public void setTexturePositionY(final int pTexturePositionY) { + this.mTexturePositionY = pTexturePositionY; + } + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + public String toString() { + return this.getClass().getSimpleName() + "( " + this.getWidth() + "x" + this.getHeight() + " @ "+ this.mTexturePositionX + "/" + this.mTexturePositionY + " )"; + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== +} diff --git a/AndEngine/src/org/anddev/andengine/opengl/texture/source/ITextureAtlasSource.java b/AndEngine/src/org/anddev/andengine/opengl/texture/source/ITextureAtlasSource.java index 18283e60..37b6ca31 100644 --- a/AndEngine/src/org/anddev/andengine/opengl/texture/source/ITextureAtlasSource.java +++ b/AndEngine/src/org/anddev/andengine/opengl/texture/source/ITextureAtlasSource.java @@ -11,21 +11,21 @@ * @since 11:46:56 - 12.07.2011 */ public interface ITextureAtlasSource { - // =========================================================== - // Final Fields - // =========================================================== + // =========================================================== + // Final Fields + // =========================================================== - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - public int getTexturePositionX(); - public int getTexturePositionY(); - public void setTexturePositionX(final int pTexturePositionX); - public void setTexturePositionY(final int pTexturePositionY); + public int getTexturePositionX(); + public int getTexturePositionY(); + public void setTexturePositionX(final int pTexturePositionX); + public void setTexturePositionY(final int pTexturePositionY); - public int getWidth(); - public int getHeight(); + public int getWidth(); + public int getHeight(); - public ITextureAtlasSource deepCopy() throws DeepCopyNotSupportedException; -} \ No newline at end of file + public ITextureAtlasSource deepCopy() throws DeepCopyNotSupportedException; +} diff --git a/AndEngine/src/org/anddev/andengine/opengl/util/FastFloatBuffer.java b/AndEngine/src/org/anddev/andengine/opengl/util/FastFloatBuffer.java index 30c06bb7..a4da7651 100644 --- a/AndEngine/src/org/anddev/andengine/opengl/util/FastFloatBuffer.java +++ b/AndEngine/src/org/anddev/andengine/opengl/util/FastFloatBuffer.java @@ -16,194 +16,194 @@ * @author ryanm */ public class FastFloatBuffer { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - /** - * Use a {@link SoftReference} so that the array can be collected if - * necessary - */ - private static SoftReference sWeakIntArray = new SoftReference(new int[0]); - - /** - * Underlying data - give this to OpenGL - */ - public final ByteBuffer mByteBuffer; - private final FloatBuffer mFloatBuffer; - private final IntBuffer mIntBuffer; - - // =========================================================== - // Constructors - // =========================================================== - - /** - * Constructs a new direct native-ordered buffer - */ - public FastFloatBuffer(final int pCapacity) { - this.mByteBuffer = ByteBuffer.allocateDirect(pCapacity * BYTES_PER_FLOAT).order(ByteOrder.nativeOrder()); - this.mFloatBuffer = this.mByteBuffer.asFloatBuffer(); - this.mIntBuffer = this.mByteBuffer.asIntBuffer(); - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - // =========================================================== - // Methods - // =========================================================== - - /** - * See {@link FloatBuffer#flip()} - */ - public void flip() { - this.mByteBuffer.flip(); - this.mFloatBuffer.flip(); - this.mIntBuffer.flip(); - } - - /** - * See {@link FloatBuffer#put(float)} - */ - public void put(final float f) { - final ByteBuffer byteBuffer = this.mByteBuffer; - final IntBuffer intBuffer = this.mIntBuffer; - - byteBuffer.position(byteBuffer.position() + BYTES_PER_FLOAT); - this.mFloatBuffer.put(f); - intBuffer.position(intBuffer.position() + 1); - } - - /** - * It'MAGIC_CONSTANT like {@link FloatBuffer#put(float[])}, but about 10 times faster - */ - public void put(final float[] data) { - final int length = data.length; - - int[] ia = sWeakIntArray.get(); - if(ia == null || ia.length < length) { - ia = new int[length]; - sWeakIntArray = new SoftReference(ia); - } - - for(int i = 0; i < length; i++) { - ia[i] = Float.floatToRawIntBits(data[i]); - } - - final ByteBuffer byteBuffer = this.mByteBuffer; - byteBuffer.position(byteBuffer.position() + BYTES_PER_FLOAT * length); - final FloatBuffer floatBuffer = this.mFloatBuffer; - floatBuffer.position(floatBuffer.position() + length); - this.mIntBuffer.put(ia, 0, length); - } - - /** - * For use with pre-converted data. This is 50x faster than - * {@link #put(float[])}, and 500x faster than - * {@link FloatBuffer#put(float[])}, so if you've got float[] data that - * won't change, {@link #convert(float...)} it to an int[] once and use this - * method to put it in the buffer - * - * @param data floats that have been converted with {@link Float#floatToIntBits(float)} - */ - public void put(final int[] data) { - final ByteBuffer byteBuffer = this.mByteBuffer; - byteBuffer.position(byteBuffer.position() + BYTES_PER_FLOAT * data.length); - final FloatBuffer floatBuffer = this.mFloatBuffer; - floatBuffer.position(floatBuffer.position() + data.length); - this.mIntBuffer.put(data, 0, data.length); - } - - /** - * Converts float data to a format that can be quickly added to the buffer - * with {@link #put(int[])} - * - * @param data - * @return the int-formatted data - */ - public static int[] convert(final float ... data) { - final int length = data.length; - final int[] id = new int[length]; - for(int i = 0; i < length; i++) { - id[i] = Float.floatToRawIntBits(data[i]); - } - - return id; - } - - /** - * See {@link FloatBuffer#put(FloatBuffer)} - */ - public void put(final FastFloatBuffer b) { - final ByteBuffer byteBuffer = this.mByteBuffer; - byteBuffer.put(b.mByteBuffer); - this.mFloatBuffer.position(byteBuffer.position() >> 2); - this.mIntBuffer.position(byteBuffer.position() >> 2); - } - - /** - * @return See {@link FloatBuffer#capacity()} - */ - public int capacity() { - return this.mFloatBuffer.capacity(); - } - - /** - * @return See {@link FloatBuffer#position()} - */ - public int position() { - return this.mFloatBuffer.position(); - } - - /** - * See {@link FloatBuffer#position(int)} - */ - public void position(final int p) { - this.mByteBuffer.position(p * BYTES_PER_FLOAT); - this.mFloatBuffer.position(p); - this.mIntBuffer.position(p); - } - - /** - * @return See {@link FloatBuffer#slice()} - */ - public FloatBuffer slice() { - return this.mFloatBuffer.slice(); - } - - /** - * @return See {@link FloatBuffer#remaining()} - */ - public int remaining() { - return this.mFloatBuffer.remaining(); - } - - /** - * @return See {@link FloatBuffer#limit()} - */ - public int limit() { - return this.mFloatBuffer.limit(); - } - - /** - * See {@link FloatBuffer#clear()} - */ - public void clear() { - this.mByteBuffer.clear(); - this.mFloatBuffer.clear(); - this.mIntBuffer.clear(); - } - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + /** + * Use a {@link SoftReference} so that the array can be collected if + * necessary + */ + private static SoftReference sWeakIntArray = new SoftReference(new int[0]); + + /** + * Underlying data - give this to OpenGL + */ + public final ByteBuffer mByteBuffer; + private final FloatBuffer mFloatBuffer; + private final IntBuffer mIntBuffer; + + // =========================================================== + // Constructors + // =========================================================== + + /** + * Constructs a new direct native-ordered buffer + */ + public FastFloatBuffer(final int pCapacity) { + this.mByteBuffer = ByteBuffer.allocateDirect(pCapacity * BYTES_PER_FLOAT).order(ByteOrder.nativeOrder()); + this.mFloatBuffer = this.mByteBuffer.asFloatBuffer(); + this.mIntBuffer = this.mByteBuffer.asIntBuffer(); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + /** + * See {@link FloatBuffer#flip()} + */ + public void flip() { + this.mByteBuffer.flip(); + this.mFloatBuffer.flip(); + this.mIntBuffer.flip(); + } + + /** + * See {@link FloatBuffer#put(float)} + */ + public void put(final float f) { + final ByteBuffer byteBuffer = this.mByteBuffer; + final IntBuffer intBuffer = this.mIntBuffer; + + byteBuffer.position(byteBuffer.position() + BYTES_PER_FLOAT); + this.mFloatBuffer.put(f); + intBuffer.position(intBuffer.position() + 1); + } + + /** + * It'MAGIC_CONSTANT like {@link FloatBuffer#put(float[])}, but about 10 times faster + */ + public void put(final float[] data) { + final int length = data.length; + + int[] ia = sWeakIntArray.get(); + if(ia == null || ia.length < length) { + ia = new int[length]; + sWeakIntArray = new SoftReference(ia); + } + + for(int i = 0; i < length; i++) { + ia[i] = Float.floatToRawIntBits(data[i]); + } + + final ByteBuffer byteBuffer = this.mByteBuffer; + byteBuffer.position(byteBuffer.position() + BYTES_PER_FLOAT * length); + final FloatBuffer floatBuffer = this.mFloatBuffer; + floatBuffer.position(floatBuffer.position() + length); + this.mIntBuffer.put(ia, 0, length); + } + + /** + * For use with pre-converted data. This is 50x faster than + * {@link #put(float[])}, and 500x faster than + * {@link FloatBuffer#put(float[])}, so if you've got float[] data that + * won't change, {@link #convert(float...)} it to an int[] once and use this + * method to put it in the buffer + * + * @param data floats that have been converted with {@link Float#floatToIntBits(float)} + */ + public void put(final int[] data) { + final ByteBuffer byteBuffer = this.mByteBuffer; + byteBuffer.position(byteBuffer.position() + BYTES_PER_FLOAT * data.length); + final FloatBuffer floatBuffer = this.mFloatBuffer; + floatBuffer.position(floatBuffer.position() + data.length); + this.mIntBuffer.put(data, 0, data.length); + } + + /** + * Converts float data to a format that can be quickly added to the buffer + * with {@link #put(int[])} + * + * @param data + * @return the int-formatted data + */ + public static int[] convert(final float ... data) { + final int length = data.length; + final int[] id = new int[length]; + for(int i = 0; i < length; i++) { + id[i] = Float.floatToRawIntBits(data[i]); + } + + return id; + } + + /** + * See {@link FloatBuffer#put(FloatBuffer)} + */ + public void put(final FastFloatBuffer b) { + final ByteBuffer byteBuffer = this.mByteBuffer; + byteBuffer.put(b.mByteBuffer); + this.mFloatBuffer.position(byteBuffer.position() >> 2); + this.mIntBuffer.position(byteBuffer.position() >> 2); + } + + /** + * @return See {@link FloatBuffer#capacity()} + */ + public int capacity() { + return this.mFloatBuffer.capacity(); + } + + /** + * @return See {@link FloatBuffer#position()} + */ + public int position() { + return this.mFloatBuffer.position(); + } + + /** + * See {@link FloatBuffer#position(int)} + */ + public void position(final int p) { + this.mByteBuffer.position(p * BYTES_PER_FLOAT); + this.mFloatBuffer.position(p); + this.mIntBuffer.position(p); + } + + /** + * @return See {@link FloatBuffer#slice()} + */ + public FloatBuffer slice() { + return this.mFloatBuffer.slice(); + } + + /** + * @return See {@link FloatBuffer#remaining()} + */ + public int remaining() { + return this.mFloatBuffer.remaining(); + } + + /** + * @return See {@link FloatBuffer#limit()} + */ + public int limit() { + return this.mFloatBuffer.limit(); + } + + /** + * See {@link FloatBuffer#clear()} + */ + public void clear() { + this.mByteBuffer.clear(); + this.mFloatBuffer.clear(); + this.mIntBuffer.clear(); + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/opengl/util/GLHelper.java b/AndEngine/src/org/anddev/andengine/opengl/util/GLHelper.java index ada12c22..d9675efb 100644 --- a/AndEngine/src/org/anddev/andengine/opengl/util/GLHelper.java +++ b/AndEngine/src/org/anddev/andengine/opengl/util/GLHelper.java @@ -26,572 +26,572 @@ * @since 18:00:43 - 08.03.2010 */ public class GLHelper { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - public static final int BYTES_PER_FLOAT = 4; - public static final int BYTES_PER_PIXEL_RGBA = 4; + public static final int BYTES_PER_FLOAT = 4; + public static final int BYTES_PER_PIXEL_RGBA = 4; - private static final boolean IS_LITTLE_ENDIAN = ByteOrder.nativeOrder() == ByteOrder.LITTLE_ENDIAN; + private static final boolean IS_LITTLE_ENDIAN = ByteOrder.nativeOrder() == ByteOrder.LITTLE_ENDIAN; - private static final int[] HARDWARETEXTUREID_CONTAINER = new int[1]; - private static final int[] HARDWAREBUFFERID_CONTAINER = new int[1]; - - // =========================================================== - // Fields - // =========================================================== - - private static int sCurrentHardwareBufferID = -1; - private static int sCurrentHardwareTextureID = -1; - private static int sCurrentMatrix = -1; - - private static int sCurrentSourceBlendMode = -1; - private static int sCurrentDestinationBlendMode = -1; - - private static FastFloatBuffer sCurrentVertexFloatBuffer = null; - private static FastFloatBuffer sCurrentTextureFloatBuffer = null; - - private static boolean sEnableDither = true; - private static boolean sEnableLightning = true; - private static boolean sEnableDepthTest = true; - private static boolean sEnableMultisample = true; - - private static boolean sEnableScissorTest = false; - private static boolean sEnableBlend = false; - private static boolean sEnableCulling = false; - private static boolean sEnableTextures = false; - private static boolean sEnableTexCoordArray = false; - private static boolean sEnableVertexArray = false; - - private static float sLineWidth = 1; - - private static float sRed = -1; - private static float sGreen = -1; - private static float sBlue = -1; - private static float sAlpha = -1; - - public static boolean EXTENSIONS_VERTEXBUFFEROBJECTS = false; - public static boolean EXTENSIONS_DRAWTEXTURE = false; - public static boolean EXTENSIONS_TEXTURE_NON_POWER_OF_TWO = false; - - public static int GlMaxTextureWidth = 0; - - // =========================================================== - // Methods - // =========================================================== - - public static void reset(final GL10 pGL) { - int[] b = new int[1]; - pGL.glGetIntegerv(GL10.GL_MAX_TEXTURE_SIZE, b, 0); - GlMaxTextureWidth = b[0]; - - GLHelper.sCurrentHardwareBufferID = -1; - GLHelper.sCurrentHardwareTextureID = -1; - GLHelper.sCurrentMatrix = -1; - - GLHelper.sCurrentSourceBlendMode = -1; - GLHelper.sCurrentDestinationBlendMode = -1; - - GLHelper.sCurrentVertexFloatBuffer = null; - GLHelper.sCurrentTextureFloatBuffer = null; - - GLHelper.enableDither(pGL); - GLHelper.enableLightning(pGL); - GLHelper.enableDepthTest(pGL); - GLHelper.enableMultisample(pGL); - - GLHelper.disableBlend(pGL); - GLHelper.disableCulling(pGL); - GLHelper.disableTextures(pGL); - GLHelper.disableTexCoordArray(pGL); - GLHelper.disableVertexArray(pGL); - - GLHelper.sLineWidth = 1; - - GLHelper.sRed = -1; - GLHelper.sGreen = -1; - GLHelper.sBlue = -1; - GLHelper.sAlpha = -1; - - GLHelper.EXTENSIONS_VERTEXBUFFEROBJECTS = false; - GLHelper.EXTENSIONS_DRAWTEXTURE = false; - GLHelper.EXTENSIONS_TEXTURE_NON_POWER_OF_TWO = false; - } - - public static void enableExtensions(final GL10 pGL, final RenderOptions pRenderOptions) { - final String version = pGL.glGetString(GL10.GL_VERSION); - final String renderer = pGL.glGetString(GL10.GL_RENDERER); - final String extensions = pGL.glGetString(GL10.GL_EXTENSIONS); - - Debug.d("RENDERER: " + renderer); - Debug.d("VERSION: " + version); - Debug.d("EXTENSIONS: " + extensions); - - final boolean isOpenGL10 = version.contains("1.0"); - final boolean isOpenGL2X = version.contains("2."); - final boolean isSoftwareRenderer = renderer.contains("PixelFlinger"); - final boolean isVBOCapable = extensions.contains("_vertex_buffer_object"); - final boolean isDrawTextureCapable = extensions.contains("draw_texture"); - final boolean isTextureNonPowerOfTwoCapable = extensions.contains("texture_npot"); - - GLHelper.EXTENSIONS_VERTEXBUFFEROBJECTS = !pRenderOptions.isDisableExtensionVertexBufferObjects() && !isSoftwareRenderer && (isVBOCapable || !isOpenGL10); - GLHelper.EXTENSIONS_DRAWTEXTURE = !pRenderOptions.isDisableExtensionVertexBufferObjects() && (isDrawTextureCapable || !isOpenGL10); - GLHelper.EXTENSIONS_TEXTURE_NON_POWER_OF_TWO = isTextureNonPowerOfTwoCapable || isOpenGL2X; - - GLHelper.hackBrokenDevices(); - Debug.d("EXTENSIONS_VERXTEXBUFFEROBJECTS = " + GLHelper.EXTENSIONS_VERTEXBUFFEROBJECTS); - Debug.d("EXTENSIONS_DRAWTEXTURE = " + GLHelper.EXTENSIONS_DRAWTEXTURE); - } - - private static void hackBrokenDevices() { - if (Build.PRODUCT.contains("morrison")) { - // This is the Motorola Cliq. This device LIES and says it supports - // VBOs, which it actually does not (or, more likely, the extensions string - // is correct and the GL JNI glue is broken). - GLHelper.EXTENSIONS_VERTEXBUFFEROBJECTS = false; - // TODO: if Motorola fixes this, I should switch to using the fingerprint - // (blur/morrison/morrison/morrison:1.5/CUPCAKE/091007:user/ota-rel-keys,release-keys) - // instead of the product name so that newer versions use VBOs - } - } - - public static void setColor(final GL10 pGL, final float pRed, final float pGreen, final float pBlue, final float pAlpha) { - if(pAlpha != GLHelper.sAlpha || pRed != GLHelper.sRed || pGreen != GLHelper.sGreen || pBlue != GLHelper.sBlue) { - GLHelper.sAlpha = pAlpha; - GLHelper.sRed = pRed; - GLHelper.sGreen = pGreen; - GLHelper.sBlue = pBlue; - pGL.glColor4f(pRed, pGreen, pBlue, pAlpha); - } - } - - public static void enableVertexArray(final GL10 pGL) { - if(!GLHelper.sEnableVertexArray) { - GLHelper.sEnableVertexArray = true; - pGL.glEnableClientState(GL10.GL_VERTEX_ARRAY); - } - } - public static void disableVertexArray(final GL10 pGL) { - if(GLHelper.sEnableVertexArray) { - GLHelper.sEnableVertexArray = false; - pGL.glDisableClientState(GL10.GL_VERTEX_ARRAY); - } - } - - public static void enableTexCoordArray(final GL10 pGL) { - if(!GLHelper.sEnableTexCoordArray) { - GLHelper.sEnableTexCoordArray = true; - pGL.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY); - } - } - public static void disableTexCoordArray(final GL10 pGL) { - if(GLHelper.sEnableTexCoordArray) { - GLHelper.sEnableTexCoordArray = false; - pGL.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY); - } - } - - public static void enableScissorTest(final GL10 pGL) { - if(!GLHelper.sEnableScissorTest) { - GLHelper.sEnableScissorTest = true; - pGL.glEnable(GL10.GL_SCISSOR_TEST); - } - } - public static void disableScissorTest(final GL10 pGL) { - if(GLHelper.sEnableScissorTest) { - GLHelper.sEnableScissorTest = false; - pGL.glDisable(GL10.GL_SCISSOR_TEST); - } - } - - public static void enableBlend(final GL10 pGL) { - if(!GLHelper.sEnableBlend) { - GLHelper.sEnableBlend = true; - pGL.glEnable(GL10.GL_BLEND); - } - } - public static void disableBlend(final GL10 pGL) { - if(GLHelper.sEnableBlend) { - GLHelper.sEnableBlend = false; - pGL.glDisable(GL10.GL_BLEND); - } - } - - public static void enableCulling(final GL10 pGL) { - if(!GLHelper.sEnableCulling) { - GLHelper.sEnableCulling = true; - pGL.glEnable(GL10.GL_CULL_FACE); - } - } - public static void disableCulling(final GL10 pGL) { - if(GLHelper.sEnableCulling) { - GLHelper.sEnableCulling = false; - pGL.glDisable(GL10.GL_CULL_FACE); - } - } - - public static void enableTextures(final GL10 pGL) { - if(!GLHelper.sEnableTextures) { - GLHelper.sEnableTextures = true; - pGL.glEnable(GL10.GL_TEXTURE_2D); - } - } - public static void disableTextures(final GL10 pGL) { - if(GLHelper.sEnableTextures) { - GLHelper.sEnableTextures = false; - pGL.glDisable(GL10.GL_TEXTURE_2D); - } - } - - public static void enableLightning(final GL10 pGL) { - if(!GLHelper.sEnableLightning) { - GLHelper.sEnableLightning = true; - pGL.glEnable(GL10.GL_LIGHTING); - } - } - public static void disableLightning(final GL10 pGL) { - if(GLHelper.sEnableLightning) { - GLHelper.sEnableLightning = false; - pGL.glDisable(GL10.GL_LIGHTING); - } - } - - public static void enableDither(final GL10 pGL) { - if(!GLHelper.sEnableDither) { - GLHelper.sEnableDither = true; - pGL.glEnable(GL10.GL_DITHER); - } - } - public static void disableDither(final GL10 pGL) { - if(GLHelper.sEnableDither) { - GLHelper.sEnableDither = false; - pGL.glDisable(GL10.GL_DITHER); - } - } - - public static boolean isEnableDepthTest() { - return sEnableDepthTest; - } - - public static void setDepthTest(GL10 pGL,boolean depthTest) { - if (sEnableDepthTest != depthTest) { - sEnableDepthTest = depthTest; - if (depthTest) { - pGL.glEnable(GL10.GL_DEPTH_TEST); - } else { - pGL.glDisable(GL10.GL_DEPTH_TEST); - } - } - } - - public static void enableDepthTest(final GL10 pGL) { - if(!GLHelper.sEnableDepthTest) { - GLHelper.sEnableDepthTest = true; - pGL.glEnable(GL10.GL_DEPTH_TEST); - } - } - public static void disableDepthTest(final GL10 pGL) { - if(GLHelper.sEnableDepthTest) { - GLHelper.sEnableDepthTest = false; - pGL.glDisable(GL10.GL_DEPTH_TEST); - } - } - - public static void enableMultisample(final GL10 pGL) { - if(!GLHelper.sEnableMultisample) { - GLHelper.sEnableMultisample = true; - pGL.glEnable(GL10.GL_MULTISAMPLE); - } - } - public static void disableMultisample(final GL10 pGL) { - if(GLHelper.sEnableMultisample) { - GLHelper.sEnableMultisample = false; - pGL.glDisable(GL10.GL_MULTISAMPLE); - } - } - - public static void bindBuffer(final GL11 pGL11, final int pHardwareBufferID) { - /* Reduce unnecessary buffer switching calls. */ - if(GLHelper.sCurrentHardwareBufferID != pHardwareBufferID) { - GLHelper.sCurrentHardwareBufferID = pHardwareBufferID; - pGL11.glBindBuffer(GL11.GL_ARRAY_BUFFER, pHardwareBufferID); - } - } - - public static void deleteBuffer(final GL11 pGL11, final int pHardwareBufferID) { - GLHelper.HARDWAREBUFFERID_CONTAINER[0] = pHardwareBufferID; - pGL11.glDeleteBuffers(1, GLHelper.HARDWAREBUFFERID_CONTAINER, 0); - } - - /** - * @see {@link GLHelper#forceBindTexture(GL10, int)} - * @param pGL - * @param pHardwareTextureID - */ - public static void bindTexture(final GL10 pGL, final int pHardwareTextureID) { - /* Reduce unnecessary texture switching calls. */ - if(GLHelper.sCurrentHardwareTextureID != pHardwareTextureID) { - GLHelper.sCurrentHardwareTextureID = pHardwareTextureID; - pGL.glBindTexture(GL10.GL_TEXTURE_2D, pHardwareTextureID); - } - } - - /** - * @see {@link GLHelper#bindTexture(GL10, int)} - * @param pGL - * @param pHardwareTextureID - */ - public static void forceBindTexture(final GL10 pGL, final int pHardwareTextureID) { - GLHelper.sCurrentHardwareTextureID = pHardwareTextureID; - pGL.glBindTexture(GL10.GL_TEXTURE_2D, pHardwareTextureID); - } - - public static void deleteTexture(final GL10 pGL, final int pHardwareTextureID) { - GLHelper.HARDWARETEXTUREID_CONTAINER[0] = pHardwareTextureID; - pGL.glDeleteTextures(1, GLHelper.HARDWARETEXTUREID_CONTAINER, 0); - } - - public static void texCoordPointer(final GL10 pGL, final FastFloatBuffer pTextureFloatBuffer) { - if(GLHelper.sCurrentTextureFloatBuffer != pTextureFloatBuffer) { - GLHelper.sCurrentTextureFloatBuffer = pTextureFloatBuffer; - pGL.glTexCoordPointer(2, GL10.GL_FLOAT, 0, pTextureFloatBuffer.mByteBuffer); - } - } - - public static void texCoordZeroPointer(final GL11 pGL11) { - pGL11.glTexCoordPointer(2, GL10.GL_FLOAT, 0, 0); - } - - public static void vertexPointer(final GL10 pGL, final FastFloatBuffer pVertexFloatBuffer) { - if(GLHelper.sCurrentVertexFloatBuffer != pVertexFloatBuffer) { - GLHelper.sCurrentVertexFloatBuffer = pVertexFloatBuffer; - pGL.glVertexPointer(2, GL10.GL_FLOAT, 0, pVertexFloatBuffer.mByteBuffer); - } - } - - public static void vertexZeroPointer(final GL11 pGL11) { - pGL11.glVertexPointer(2, GL10.GL_FLOAT, 0, 0); - } - - public static void blendFunction(final GL10 pGL, final int pSourceBlendMode, final int pDestinationBlendMode) { - if(GLHelper.sCurrentSourceBlendMode != pSourceBlendMode || GLHelper.sCurrentDestinationBlendMode != pDestinationBlendMode) { - GLHelper.sCurrentSourceBlendMode = pSourceBlendMode; - GLHelper.sCurrentDestinationBlendMode = pDestinationBlendMode; - pGL.glBlendFunc(pSourceBlendMode, pDestinationBlendMode); - } - } - - public static void lineWidth(final GL10 pGL, final float pLineWidth) { - if(GLHelper.sLineWidth != pLineWidth) { - GLHelper.sLineWidth = pLineWidth; - pGL.glLineWidth(pLineWidth); - } - } - - public static int getCurrentMatrixType() { - return sCurrentMatrix; - } - - public static void switchToModelViewMatrix(final GL10 pGL) { - /* Reduce unnecessary matrix switching calls. */ - if(GLHelper.sCurrentMatrix != GL10.GL_MODELVIEW) { - GLHelper.sCurrentMatrix = GL10.GL_MODELVIEW; - pGL.glMatrixMode(GL10.GL_MODELVIEW); - } - } - - public static void switchToProjectionMatrix(final GL10 pGL) { - /* Reduce unnecessary matrix switching calls. */ - if(GLHelper.sCurrentMatrix != GL10.GL_PROJECTION) { - GLHelper.sCurrentMatrix = GL10.GL_PROJECTION; - pGL.glMatrixMode(GL10.GL_PROJECTION); - } - } - - public static void setProjectionIdentityMatrix(final GL10 pGL) { - GLHelper.switchToProjectionMatrix(pGL); - pGL.glLoadIdentity(); - } - - public static void setModelViewIdentityMatrix(final GL10 pGL) { - GLHelper.switchToModelViewMatrix(pGL); - pGL.glLoadIdentity(); - } - - public static void setShadeModelFlat(final GL10 pGL) { - pGL.glShadeModel(GL10.GL_FLAT); - } - - public static void setPerspectiveCorrectionHintFastest(final GL10 pGL) { - pGL.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, GL10.GL_FASTEST); - } - - public static void bufferData(final GL11 pGL11, final ByteBuffer pByteBuffer, final int pUsage) { - pGL11.glBufferData(GL11.GL_ARRAY_BUFFER, pByteBuffer.capacity(), pByteBuffer, pUsage); - } - - /** - * Note: does not pre-multiply the alpha channel!
- * Except that difference, same as: {@link GLUtils#texSubImage2D(int, int, int, int, Bitmap, int, int)}
- *
- * See topic: 'PNG loading that doesn't premultiply alpha?' - * @param pBorder - */ - public static void glTexImage2D(final GL10 pGL, final int pTarget, final int pLevel, final Bitmap pBitmap, final int pBorder, final PixelFormat pPixelFormat) { - final Buffer pixelBuffer = GLHelper.getPixels(pBitmap, pPixelFormat); - - pGL.glTexImage2D(pTarget, pLevel, pPixelFormat.getGLFormat(), pBitmap.getWidth(), pBitmap.getHeight(), pBorder, pPixelFormat.getGLFormat(), pPixelFormat.getGLType(), pixelBuffer); - } - - /** - * Note: does not pre-multiply the alpha channel!
- * Except that difference, same as: {@link GLUtils#texSubImage2D(int, int, int, int, Bitmap, int, int)}
- *
- * See topic: 'PNG loading that doesn't premultiply alpha?' - */ - public static void glTexSubImage2D(final GL10 pGL, final int pTarget, final int pLevel, final int pXOffset, final int pYOffset, final Bitmap pBitmap, final PixelFormat pPixelFormat) { - final Buffer pixelBuffer = GLHelper.getPixels(pBitmap, pPixelFormat); - - pGL.glTexSubImage2D(pTarget, pLevel, pXOffset, pYOffset, pBitmap.getWidth(), pBitmap.getHeight(), pPixelFormat.getGLFormat(), pPixelFormat.getGLType(), pixelBuffer); - } - - private static Buffer getPixels(final Bitmap pBitmap, final PixelFormat pPixelFormat) { - final int[] pixelsARGB_8888 = GLHelper.getPixelsARGB_8888(pBitmap); - - switch(pPixelFormat) { - case RGB_565: - return ByteBuffer.wrap(GLHelper.convertARGB_8888toRGB_565(pixelsARGB_8888)); - case RGBA_8888: - return IntBuffer.wrap(GLHelper.convertARGB_8888toRGBA_8888(pixelsARGB_8888)); - case RGBA_4444: - return ByteBuffer.wrap(GLHelper.convertARGB_8888toARGB_4444(pixelsARGB_8888)); - case A_8: - return ByteBuffer.wrap(GLHelper.convertARGB_8888toA_8(pixelsARGB_8888)); - default: - throw new IllegalArgumentException("Unexpected " + PixelFormat.class.getSimpleName() + ": '" + pPixelFormat + "'."); - } - } - - private static int[] convertARGB_8888toRGBA_8888(final int[] pPixelsARGB_8888) { - if(GLHelper.IS_LITTLE_ENDIAN) { - for(int i = pPixelsARGB_8888.length - 1; i >= 0; i--) { - final int pixel = pPixelsARGB_8888[i]; - /* ARGB to ABGR */ - pPixelsARGB_8888[i] = pixel & 0xFF00FF00 | (pixel & 0x000000FF) << 16 | (pixel & 0x00FF0000) >> 16; - } - } else { - for(int i = pPixelsARGB_8888.length - 1; i >= 0; i--) { - final int pixel = pPixelsARGB_8888[i]; - /* ARGB to RGBA */ - pPixelsARGB_8888[i] = (pixel & 0x00FFFFFF) << 8 | (pixel & 0xFF000000) >> 24; - } - } - return pPixelsARGB_8888; - } - - private static byte[] convertARGB_8888toRGB_565(final int[] pPixelsARGB_8888) { - final byte[] pixelsRGB_565 = new byte[pPixelsARGB_8888.length * 2]; - if(GLHelper.IS_LITTLE_ENDIAN) { - for(int i = pPixelsARGB_8888.length - 1, j = pixelsRGB_565.length - 1; i >= 0; i--) { - final int pixel = pPixelsARGB_8888[i]; - - final int red = (pixel >> 16) & 0xFF; - final int green = (pixel >> 8) & 0xFF; - final int blue = (pixel) & 0xFF; - - /* Byte1: [R1 R2 R3 R4 R5 G1 G2 G3] - * Byte2: [G4 G5 G6 B1 B2 B3 B4 B5] */ - - pixelsRGB_565[j--] = (byte)((red & 0xF8) | (green >> 5)); - pixelsRGB_565[j--] = (byte)(((green << 3) & 0xE0) | (blue >> 3)); - } - } else { - for(int i = pPixelsARGB_8888.length - 1, j = pixelsRGB_565.length - 1; i >= 0; i--) { - final int pixel = pPixelsARGB_8888[i]; - - final int red = (pixel >> 16) & 0xFF; - final int green = (pixel >> 8) & 0xFF; - final int blue = (pixel) & 0xFF; - - /* Byte2: [G4 G5 G6 B1 B2 B3 B4 B5] - * Byte1: [R1 R2 R3 R4 R5 G1 G2 G3]*/ - - pixelsRGB_565[j--] = (byte)(((green << 3) & 0xE0) | (blue >> 3)); - pixelsRGB_565[j--] = (byte)((red & 0xF8) | (green >> 5)); - } - } - return pixelsRGB_565; - } - - private static byte[] convertARGB_8888toARGB_4444(final int[] pPixelsARGB_8888) { - final byte[] pixelsARGB_4444 = new byte[pPixelsARGB_8888.length * 2]; - if(GLHelper.IS_LITTLE_ENDIAN) { - for(int i = pPixelsARGB_8888.length - 1, j = pixelsARGB_4444.length - 1; i >= 0; i--) { - final int pixel = pPixelsARGB_8888[i]; - - final int alpha = (pixel >> 28) & 0x0F; - final int red = (pixel >> 16) & 0xF0; - final int green = (pixel >> 8) & 0xF0; - final int blue = ((pixel) & 0x0F); - - /* Byte1: [A1 A2 A3 A4 R1 R2 R3 R4] - * Byte2: [G1 G2 G3 G4 G2 G2 G3 G4] */ - - pixelsARGB_4444[j--] = (byte)(alpha | red); - pixelsARGB_4444[j--] = (byte)(green | blue); - } - } else { - for(int i = pPixelsARGB_8888.length - 1, j = pixelsARGB_4444.length - 1; i >= 0; i--) { - final int pixel = pPixelsARGB_8888[i]; - - final int alpha = (pixel >> 28) & 0x0F; - final int red = (pixel >> 16) & 0xF0; - final int green = (pixel >> 8) & 0xF0; - final int blue = (pixel) & 0x0F; - - /* Byte2: [G1 G2 G3 G4 G2 G2 G3 G4] - * Byte1: [A1 A2 A3 A4 R1 R2 R3 R4] */ - - pixelsARGB_4444[j--] = (byte)(green | blue); - pixelsARGB_4444[j--] = (byte)(alpha | red); - } - } - return pixelsARGB_4444; - } - - private static byte[] convertARGB_8888toA_8(final int[] pPixelsARGB_8888) { - final byte[] pixelsA_8 = new byte[pPixelsARGB_8888.length]; - if(GLHelper.IS_LITTLE_ENDIAN) { - for(int i = pPixelsARGB_8888.length - 1; i >= 0; i--) { - pixelsA_8[i] = (byte) (pPixelsARGB_8888[i] >> 24); - } - } else { - for(int i = pPixelsARGB_8888.length - 1; i >= 0; i--) { - pixelsA_8[i] = (byte) (pPixelsARGB_8888[i] & 0xFF); - } - } - return pixelsA_8; - } - - public static int[] getPixelsARGB_8888(final Bitmap pBitmap) { - final int w = pBitmap.getWidth(); - final int h = pBitmap.getHeight(); - - final int[] pixelsARGB_8888 = new int[w * h]; - pBitmap.getPixels(pixelsARGB_8888, 0, w, 0, 0, w, h); - - return pixelsARGB_8888; - } - - public static void checkGLError(final GL10 pGL) throws GLException { // TODO Use more often! - final int err = pGL.glGetError(); - if (err != GL10.GL_NO_ERROR) { - throw new GLException(err); - } - } - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + private static final int[] HARDWARETEXTUREID_CONTAINER = new int[1]; + private static final int[] HARDWAREBUFFERID_CONTAINER = new int[1]; + + // =========================================================== + // Fields + // =========================================================== + + private static int sCurrentHardwareBufferID = -1; + private static int sCurrentHardwareTextureID = -1; + private static int sCurrentMatrix = -1; + + private static int sCurrentSourceBlendMode = -1; + private static int sCurrentDestinationBlendMode = -1; + + private static FastFloatBuffer sCurrentVertexFloatBuffer = null; + private static FastFloatBuffer sCurrentTextureFloatBuffer = null; + + private static boolean sEnableDither = true; + private static boolean sEnableLightning = true; + private static boolean sEnableDepthTest = true; + private static boolean sEnableMultisample = true; + + private static boolean sEnableScissorTest = false; + private static boolean sEnableBlend = false; + private static boolean sEnableCulling = false; + private static boolean sEnableTextures = false; + private static boolean sEnableTexCoordArray = false; + private static boolean sEnableVertexArray = false; + + private static float sLineWidth = 1; + + private static float sRed = -1; + private static float sGreen = -1; + private static float sBlue = -1; + private static float sAlpha = -1; + + public static boolean EXTENSIONS_VERTEXBUFFEROBJECTS = false; + public static boolean EXTENSIONS_DRAWTEXTURE = false; + public static boolean EXTENSIONS_TEXTURE_NON_POWER_OF_TWO = false; + + public static int GlMaxTextureWidth = 0; + + // =========================================================== + // Methods + // =========================================================== + + public static void reset(final GL10 pGL) { + int[] b = new int[1]; + pGL.glGetIntegerv(GL10.GL_MAX_TEXTURE_SIZE, b, 0); + GlMaxTextureWidth = b[0]; + + GLHelper.sCurrentHardwareBufferID = -1; + GLHelper.sCurrentHardwareTextureID = -1; + GLHelper.sCurrentMatrix = -1; + + GLHelper.sCurrentSourceBlendMode = -1; + GLHelper.sCurrentDestinationBlendMode = -1; + + GLHelper.sCurrentVertexFloatBuffer = null; + GLHelper.sCurrentTextureFloatBuffer = null; + + GLHelper.enableDither(pGL); + GLHelper.enableLightning(pGL); + GLHelper.enableDepthTest(pGL); + GLHelper.enableMultisample(pGL); + + GLHelper.disableBlend(pGL); + GLHelper.disableCulling(pGL); + GLHelper.disableTextures(pGL); + GLHelper.disableTexCoordArray(pGL); + GLHelper.disableVertexArray(pGL); + + GLHelper.sLineWidth = 1; + + GLHelper.sRed = -1; + GLHelper.sGreen = -1; + GLHelper.sBlue = -1; + GLHelper.sAlpha = -1; + + GLHelper.EXTENSIONS_VERTEXBUFFEROBJECTS = false; + GLHelper.EXTENSIONS_DRAWTEXTURE = false; + GLHelper.EXTENSIONS_TEXTURE_NON_POWER_OF_TWO = false; + } + + public static void enableExtensions(final GL10 pGL, final RenderOptions pRenderOptions) { + final String version = pGL.glGetString(GL10.GL_VERSION); + final String renderer = pGL.glGetString(GL10.GL_RENDERER); + final String extensions = pGL.glGetString(GL10.GL_EXTENSIONS); + + Debug.d("RENDERER: " + renderer); + Debug.d("VERSION: " + version); + Debug.d("EXTENSIONS: " + extensions); + + final boolean isOpenGL10 = version.contains("1.0"); + final boolean isOpenGL2X = version.contains("2."); + final boolean isSoftwareRenderer = renderer.contains("PixelFlinger"); + final boolean isVBOCapable = extensions.contains("_vertex_buffer_object"); + final boolean isDrawTextureCapable = extensions.contains("draw_texture"); + final boolean isTextureNonPowerOfTwoCapable = extensions.contains("texture_npot"); + + GLHelper.EXTENSIONS_VERTEXBUFFEROBJECTS = !pRenderOptions.isDisableExtensionVertexBufferObjects() && !isSoftwareRenderer && (isVBOCapable || !isOpenGL10); + GLHelper.EXTENSIONS_DRAWTEXTURE = !pRenderOptions.isDisableExtensionVertexBufferObjects() && (isDrawTextureCapable || !isOpenGL10); + GLHelper.EXTENSIONS_TEXTURE_NON_POWER_OF_TWO = isTextureNonPowerOfTwoCapable || isOpenGL2X; + + GLHelper.hackBrokenDevices(); + Debug.d("EXTENSIONS_VERXTEXBUFFEROBJECTS = " + GLHelper.EXTENSIONS_VERTEXBUFFEROBJECTS); + Debug.d("EXTENSIONS_DRAWTEXTURE = " + GLHelper.EXTENSIONS_DRAWTEXTURE); + } + + private static void hackBrokenDevices() { + if (Build.PRODUCT.contains("morrison")) { + // This is the Motorola Cliq. This device LIES and says it supports + // VBOs, which it actually does not (or, more likely, the extensions string + // is correct and the GL JNI glue is broken). + GLHelper.EXTENSIONS_VERTEXBUFFEROBJECTS = false; + // TODO: if Motorola fixes this, I should switch to using the fingerprint + // (blur/morrison/morrison/morrison:1.5/CUPCAKE/091007:user/ota-rel-keys,release-keys) + // instead of the product name so that newer versions use VBOs + } + } + + public static void setColor(final GL10 pGL, final float pRed, final float pGreen, final float pBlue, final float pAlpha) { + if(pAlpha != GLHelper.sAlpha || pRed != GLHelper.sRed || pGreen != GLHelper.sGreen || pBlue != GLHelper.sBlue) { + GLHelper.sAlpha = pAlpha; + GLHelper.sRed = pRed; + GLHelper.sGreen = pGreen; + GLHelper.sBlue = pBlue; + pGL.glColor4f(pRed, pGreen, pBlue, pAlpha); + } + } + + public static void enableVertexArray(final GL10 pGL) { + if(!GLHelper.sEnableVertexArray) { + GLHelper.sEnableVertexArray = true; + pGL.glEnableClientState(GL10.GL_VERTEX_ARRAY); + } + } + public static void disableVertexArray(final GL10 pGL) { + if(GLHelper.sEnableVertexArray) { + GLHelper.sEnableVertexArray = false; + pGL.glDisableClientState(GL10.GL_VERTEX_ARRAY); + } + } + + public static void enableTexCoordArray(final GL10 pGL) { + if(!GLHelper.sEnableTexCoordArray) { + GLHelper.sEnableTexCoordArray = true; + pGL.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY); + } + } + public static void disableTexCoordArray(final GL10 pGL) { + if(GLHelper.sEnableTexCoordArray) { + GLHelper.sEnableTexCoordArray = false; + pGL.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY); + } + } + + public static void enableScissorTest(final GL10 pGL) { + if(!GLHelper.sEnableScissorTest) { + GLHelper.sEnableScissorTest = true; + pGL.glEnable(GL10.GL_SCISSOR_TEST); + } + } + public static void disableScissorTest(final GL10 pGL) { + if(GLHelper.sEnableScissorTest) { + GLHelper.sEnableScissorTest = false; + pGL.glDisable(GL10.GL_SCISSOR_TEST); + } + } + + public static void enableBlend(final GL10 pGL) { + if(!GLHelper.sEnableBlend) { + GLHelper.sEnableBlend = true; + pGL.glEnable(GL10.GL_BLEND); + } + } + public static void disableBlend(final GL10 pGL) { + if(GLHelper.sEnableBlend) { + GLHelper.sEnableBlend = false; + pGL.glDisable(GL10.GL_BLEND); + } + } + + public static void enableCulling(final GL10 pGL) { + if(!GLHelper.sEnableCulling) { + GLHelper.sEnableCulling = true; + pGL.glEnable(GL10.GL_CULL_FACE); + } + } + public static void disableCulling(final GL10 pGL) { + if(GLHelper.sEnableCulling) { + GLHelper.sEnableCulling = false; + pGL.glDisable(GL10.GL_CULL_FACE); + } + } + + public static void enableTextures(final GL10 pGL) { + if(!GLHelper.sEnableTextures) { + GLHelper.sEnableTextures = true; + pGL.glEnable(GL10.GL_TEXTURE_2D); + } + } + public static void disableTextures(final GL10 pGL) { + if(GLHelper.sEnableTextures) { + GLHelper.sEnableTextures = false; + pGL.glDisable(GL10.GL_TEXTURE_2D); + } + } + + public static void enableLightning(final GL10 pGL) { + if(!GLHelper.sEnableLightning) { + GLHelper.sEnableLightning = true; + pGL.glEnable(GL10.GL_LIGHTING); + } + } + public static void disableLightning(final GL10 pGL) { + if(GLHelper.sEnableLightning) { + GLHelper.sEnableLightning = false; + pGL.glDisable(GL10.GL_LIGHTING); + } + } + + public static void enableDither(final GL10 pGL) { + if(!GLHelper.sEnableDither) { + GLHelper.sEnableDither = true; + pGL.glEnable(GL10.GL_DITHER); + } + } + public static void disableDither(final GL10 pGL) { + if(GLHelper.sEnableDither) { + GLHelper.sEnableDither = false; + pGL.glDisable(GL10.GL_DITHER); + } + } + + public static boolean isEnableDepthTest() { + return sEnableDepthTest; + } + + public static void setDepthTest(GL10 pGL,boolean depthTest) { + if (sEnableDepthTest != depthTest) { + sEnableDepthTest = depthTest; + if (depthTest) { + pGL.glEnable(GL10.GL_DEPTH_TEST); + } else { + pGL.glDisable(GL10.GL_DEPTH_TEST); + } + } + } + + public static void enableDepthTest(final GL10 pGL) { + if(!GLHelper.sEnableDepthTest) { + GLHelper.sEnableDepthTest = true; + pGL.glEnable(GL10.GL_DEPTH_TEST); + } + } + public static void disableDepthTest(final GL10 pGL) { + if(GLHelper.sEnableDepthTest) { + GLHelper.sEnableDepthTest = false; + pGL.glDisable(GL10.GL_DEPTH_TEST); + } + } + + public static void enableMultisample(final GL10 pGL) { + if(!GLHelper.sEnableMultisample) { + GLHelper.sEnableMultisample = true; + pGL.glEnable(GL10.GL_MULTISAMPLE); + } + } + public static void disableMultisample(final GL10 pGL) { + if(GLHelper.sEnableMultisample) { + GLHelper.sEnableMultisample = false; + pGL.glDisable(GL10.GL_MULTISAMPLE); + } + } + + public static void bindBuffer(final GL11 pGL11, final int pHardwareBufferID) { + /* Reduce unnecessary buffer switching calls. */ + if(GLHelper.sCurrentHardwareBufferID != pHardwareBufferID) { + GLHelper.sCurrentHardwareBufferID = pHardwareBufferID; + pGL11.glBindBuffer(GL11.GL_ARRAY_BUFFER, pHardwareBufferID); + } + } + + public static void deleteBuffer(final GL11 pGL11, final int pHardwareBufferID) { + GLHelper.HARDWAREBUFFERID_CONTAINER[0] = pHardwareBufferID; + pGL11.glDeleteBuffers(1, GLHelper.HARDWAREBUFFERID_CONTAINER, 0); + } + + /** + * @see {@link GLHelper#forceBindTexture(GL10, int)} + * @param pGL + * @param pHardwareTextureID + */ + public static void bindTexture(final GL10 pGL, final int pHardwareTextureID) { + /* Reduce unnecessary texture switching calls. */ + if(GLHelper.sCurrentHardwareTextureID != pHardwareTextureID) { + GLHelper.sCurrentHardwareTextureID = pHardwareTextureID; + pGL.glBindTexture(GL10.GL_TEXTURE_2D, pHardwareTextureID); + } + } + + /** + * @see {@link GLHelper#bindTexture(GL10, int)} + * @param pGL + * @param pHardwareTextureID + */ + public static void forceBindTexture(final GL10 pGL, final int pHardwareTextureID) { + GLHelper.sCurrentHardwareTextureID = pHardwareTextureID; + pGL.glBindTexture(GL10.GL_TEXTURE_2D, pHardwareTextureID); + } + + public static void deleteTexture(final GL10 pGL, final int pHardwareTextureID) { + GLHelper.HARDWARETEXTUREID_CONTAINER[0] = pHardwareTextureID; + pGL.glDeleteTextures(1, GLHelper.HARDWARETEXTUREID_CONTAINER, 0); + } + + public static void texCoordPointer(final GL10 pGL, final FastFloatBuffer pTextureFloatBuffer) { + if(GLHelper.sCurrentTextureFloatBuffer != pTextureFloatBuffer) { + GLHelper.sCurrentTextureFloatBuffer = pTextureFloatBuffer; + pGL.glTexCoordPointer(2, GL10.GL_FLOAT, 0, pTextureFloatBuffer.mByteBuffer); + } + } + + public static void texCoordZeroPointer(final GL11 pGL11) { + pGL11.glTexCoordPointer(2, GL10.GL_FLOAT, 0, 0); + } + + public static void vertexPointer(final GL10 pGL, final FastFloatBuffer pVertexFloatBuffer) { + if(GLHelper.sCurrentVertexFloatBuffer != pVertexFloatBuffer) { + GLHelper.sCurrentVertexFloatBuffer = pVertexFloatBuffer; + pGL.glVertexPointer(2, GL10.GL_FLOAT, 0, pVertexFloatBuffer.mByteBuffer); + } + } + + public static void vertexZeroPointer(final GL11 pGL11) { + pGL11.glVertexPointer(2, GL10.GL_FLOAT, 0, 0); + } + + public static void blendFunction(final GL10 pGL, final int pSourceBlendMode, final int pDestinationBlendMode) { + if(GLHelper.sCurrentSourceBlendMode != pSourceBlendMode || GLHelper.sCurrentDestinationBlendMode != pDestinationBlendMode) { + GLHelper.sCurrentSourceBlendMode = pSourceBlendMode; + GLHelper.sCurrentDestinationBlendMode = pDestinationBlendMode; + pGL.glBlendFunc(pSourceBlendMode, pDestinationBlendMode); + } + } + + public static void lineWidth(final GL10 pGL, final float pLineWidth) { + if(GLHelper.sLineWidth != pLineWidth) { + GLHelper.sLineWidth = pLineWidth; + pGL.glLineWidth(pLineWidth); + } + } + + public static int getCurrentMatrixType() { + return sCurrentMatrix; + } + + public static void switchToModelViewMatrix(final GL10 pGL) { + /* Reduce unnecessary matrix switching calls. */ + if(GLHelper.sCurrentMatrix != GL10.GL_MODELVIEW) { + GLHelper.sCurrentMatrix = GL10.GL_MODELVIEW; + pGL.glMatrixMode(GL10.GL_MODELVIEW); + } + } + + public static void switchToProjectionMatrix(final GL10 pGL) { + /* Reduce unnecessary matrix switching calls. */ + if(GLHelper.sCurrentMatrix != GL10.GL_PROJECTION) { + GLHelper.sCurrentMatrix = GL10.GL_PROJECTION; + pGL.glMatrixMode(GL10.GL_PROJECTION); + } + } + + public static void setProjectionIdentityMatrix(final GL10 pGL) { + GLHelper.switchToProjectionMatrix(pGL); + pGL.glLoadIdentity(); + } + + public static void setModelViewIdentityMatrix(final GL10 pGL) { + GLHelper.switchToModelViewMatrix(pGL); + pGL.glLoadIdentity(); + } + + public static void setShadeModelFlat(final GL10 pGL) { + pGL.glShadeModel(GL10.GL_FLAT); + } + + public static void setPerspectiveCorrectionHintFastest(final GL10 pGL) { + pGL.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, GL10.GL_FASTEST); + } + + public static void bufferData(final GL11 pGL11, final ByteBuffer pByteBuffer, final int pUsage) { + pGL11.glBufferData(GL11.GL_ARRAY_BUFFER, pByteBuffer.capacity(), pByteBuffer, pUsage); + } + + /** + * Note: does not pre-multiply the alpha channel!
+ * Except that difference, same as: {@link GLUtils#texSubImage2D(int, int, int, int, Bitmap, int, int)}
+ *
+ * See topic: 'PNG loading that doesn't premultiply alpha?' + * @param pBorder + */ + public static void glTexImage2D(final GL10 pGL, final int pTarget, final int pLevel, final Bitmap pBitmap, final int pBorder, final PixelFormat pPixelFormat) { + final Buffer pixelBuffer = GLHelper.getPixels(pBitmap, pPixelFormat); + + pGL.glTexImage2D(pTarget, pLevel, pPixelFormat.getGLFormat(), pBitmap.getWidth(), pBitmap.getHeight(), pBorder, pPixelFormat.getGLFormat(), pPixelFormat.getGLType(), pixelBuffer); + } + + /** + * Note: does not pre-multiply the alpha channel!
+ * Except that difference, same as: {@link GLUtils#texSubImage2D(int, int, int, int, Bitmap, int, int)}
+ *
+ * See topic: 'PNG loading that doesn't premultiply alpha?' + */ + public static void glTexSubImage2D(final GL10 pGL, final int pTarget, final int pLevel, final int pXOffset, final int pYOffset, final Bitmap pBitmap, final PixelFormat pPixelFormat) { + final Buffer pixelBuffer = GLHelper.getPixels(pBitmap, pPixelFormat); + + pGL.glTexSubImage2D(pTarget, pLevel, pXOffset, pYOffset, pBitmap.getWidth(), pBitmap.getHeight(), pPixelFormat.getGLFormat(), pPixelFormat.getGLType(), pixelBuffer); + } + + private static Buffer getPixels(final Bitmap pBitmap, final PixelFormat pPixelFormat) { + final int[] pixelsARGB_8888 = GLHelper.getPixelsARGB_8888(pBitmap); + + switch(pPixelFormat) { + case RGB_565: + return ByteBuffer.wrap(GLHelper.convertARGB_8888toRGB_565(pixelsARGB_8888)); + case RGBA_8888: + return IntBuffer.wrap(GLHelper.convertARGB_8888toRGBA_8888(pixelsARGB_8888)); + case RGBA_4444: + return ByteBuffer.wrap(GLHelper.convertARGB_8888toARGB_4444(pixelsARGB_8888)); + case A_8: + return ByteBuffer.wrap(GLHelper.convertARGB_8888toA_8(pixelsARGB_8888)); + default: + throw new IllegalArgumentException("Unexpected " + PixelFormat.class.getSimpleName() + ": '" + pPixelFormat + "'."); + } + } + + private static int[] convertARGB_8888toRGBA_8888(final int[] pPixelsARGB_8888) { + if(GLHelper.IS_LITTLE_ENDIAN) { + for(int i = pPixelsARGB_8888.length - 1; i >= 0; i--) { + final int pixel = pPixelsARGB_8888[i]; + /* ARGB to ABGR */ + pPixelsARGB_8888[i] = pixel & 0xFF00FF00 | (pixel & 0x000000FF) << 16 | (pixel & 0x00FF0000) >> 16; + } + } else { + for(int i = pPixelsARGB_8888.length - 1; i >= 0; i--) { + final int pixel = pPixelsARGB_8888[i]; + /* ARGB to RGBA */ + pPixelsARGB_8888[i] = (pixel & 0x00FFFFFF) << 8 | (pixel & 0xFF000000) >> 24; + } + } + return pPixelsARGB_8888; + } + + private static byte[] convertARGB_8888toRGB_565(final int[] pPixelsARGB_8888) { + final byte[] pixelsRGB_565 = new byte[pPixelsARGB_8888.length * 2]; + if(GLHelper.IS_LITTLE_ENDIAN) { + for(int i = pPixelsARGB_8888.length - 1, j = pixelsRGB_565.length - 1; i >= 0; i--) { + final int pixel = pPixelsARGB_8888[i]; + + final int red = (pixel >> 16) & 0xFF; + final int green = (pixel >> 8) & 0xFF; + final int blue = (pixel) & 0xFF; + + /* Byte1: [R1 R2 R3 R4 R5 G1 G2 G3] + * Byte2: [G4 G5 G6 B1 B2 B3 B4 B5] */ + + pixelsRGB_565[j--] = (byte)((red & 0xF8) | (green >> 5)); + pixelsRGB_565[j--] = (byte)(((green << 3) & 0xE0) | (blue >> 3)); + } + } else { + for(int i = pPixelsARGB_8888.length - 1, j = pixelsRGB_565.length - 1; i >= 0; i--) { + final int pixel = pPixelsARGB_8888[i]; + + final int red = (pixel >> 16) & 0xFF; + final int green = (pixel >> 8) & 0xFF; + final int blue = (pixel) & 0xFF; + + /* Byte2: [G4 G5 G6 B1 B2 B3 B4 B5] + * Byte1: [R1 R2 R3 R4 R5 G1 G2 G3]*/ + + pixelsRGB_565[j--] = (byte)(((green << 3) & 0xE0) | (blue >> 3)); + pixelsRGB_565[j--] = (byte)((red & 0xF8) | (green >> 5)); + } + } + return pixelsRGB_565; + } + + private static byte[] convertARGB_8888toARGB_4444(final int[] pPixelsARGB_8888) { + final byte[] pixelsARGB_4444 = new byte[pPixelsARGB_8888.length * 2]; + if(GLHelper.IS_LITTLE_ENDIAN) { + for(int i = pPixelsARGB_8888.length - 1, j = pixelsARGB_4444.length - 1; i >= 0; i--) { + final int pixel = pPixelsARGB_8888[i]; + + final int alpha = (pixel >> 28) & 0x0F; + final int red = (pixel >> 16) & 0xF0; + final int green = (pixel >> 8) & 0xF0; + final int blue = ((pixel) & 0x0F); + + /* Byte1: [A1 A2 A3 A4 R1 R2 R3 R4] + * Byte2: [G1 G2 G3 G4 G2 G2 G3 G4] */ + + pixelsARGB_4444[j--] = (byte)(alpha | red); + pixelsARGB_4444[j--] = (byte)(green | blue); + } + } else { + for(int i = pPixelsARGB_8888.length - 1, j = pixelsARGB_4444.length - 1; i >= 0; i--) { + final int pixel = pPixelsARGB_8888[i]; + + final int alpha = (pixel >> 28) & 0x0F; + final int red = (pixel >> 16) & 0xF0; + final int green = (pixel >> 8) & 0xF0; + final int blue = (pixel) & 0x0F; + + /* Byte2: [G1 G2 G3 G4 G2 G2 G3 G4] + * Byte1: [A1 A2 A3 A4 R1 R2 R3 R4] */ + + pixelsARGB_4444[j--] = (byte)(green | blue); + pixelsARGB_4444[j--] = (byte)(alpha | red); + } + } + return pixelsARGB_4444; + } + + private static byte[] convertARGB_8888toA_8(final int[] pPixelsARGB_8888) { + final byte[] pixelsA_8 = new byte[pPixelsARGB_8888.length]; + if(GLHelper.IS_LITTLE_ENDIAN) { + for(int i = pPixelsARGB_8888.length - 1; i >= 0; i--) { + pixelsA_8[i] = (byte) (pPixelsARGB_8888[i] >> 24); + } + } else { + for(int i = pPixelsARGB_8888.length - 1; i >= 0; i--) { + pixelsA_8[i] = (byte) (pPixelsARGB_8888[i] & 0xFF); + } + } + return pixelsA_8; + } + + public static int[] getPixelsARGB_8888(final Bitmap pBitmap) { + final int w = pBitmap.getWidth(); + final int h = pBitmap.getHeight(); + + final int[] pixelsARGB_8888 = new int[w * h]; + pBitmap.getPixels(pixelsARGB_8888, 0, w, 0, 0, w, h); + + return pixelsARGB_8888; + } + + public static void checkGLError(final GL10 pGL) throws GLException { // TODO Use more often! + final int err = pGL.glGetError(); + if (err != GL10.GL_NO_ERROR) { + throw new GLException(err); + } + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/opengl/vertex/LineVertexBuffer.java b/AndEngine/src/org/anddev/andengine/opengl/vertex/LineVertexBuffer.java index f963ad62..281f283e 100644 --- a/AndEngine/src/org/anddev/andengine/opengl/vertex/LineVertexBuffer.java +++ b/AndEngine/src/org/anddev/andengine/opengl/vertex/LineVertexBuffer.java @@ -10,54 +10,54 @@ * @since 13:07:25 - 13.03.2010 */ public class LineVertexBuffer extends VertexBuffer { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - public static final int VERTICES_PER_LINE = 2; + public static final int VERTICES_PER_LINE = 2; - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - public LineVertexBuffer(final int pDrawType, final boolean pManaged) { - super(2 * VERTICES_PER_LINE, pDrawType, pManaged); - } + public LineVertexBuffer(final int pDrawType, final boolean pManaged) { + super(2 * VERTICES_PER_LINE, pDrawType, pManaged); + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - public synchronized void update(final float pX1, final float pY1, final float pX2, final float pY2) { - final int[] bufferData = this.mBufferData; + public synchronized void update(final float pX1, final float pY1, final float pX2, final float pY2) { + final int[] bufferData = this.mBufferData; - bufferData[0] = Float.floatToRawIntBits(pX1); - bufferData[1] = Float.floatToRawIntBits(pY1); + bufferData[0] = Float.floatToRawIntBits(pX1); + bufferData[1] = Float.floatToRawIntBits(pY1); - bufferData[2] = Float.floatToRawIntBits(pX2); - bufferData[3] = Float.floatToRawIntBits(pY2); + bufferData[2] = Float.floatToRawIntBits(pX2); + bufferData[3] = Float.floatToRawIntBits(pY2); - final FastFloatBuffer buffer = this.mFloatBuffer; - buffer.position(0); - buffer.put(bufferData); - buffer.position(0); + final FastFloatBuffer buffer = this.mFloatBuffer; + buffer.position(0); + buffer.put(bufferData); + buffer.position(0); - super.setHardwareBufferNeedsUpdate(); - } + super.setHardwareBufferNeedsUpdate(); + } - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/opengl/vertex/RectangleVertexBuffer.java b/AndEngine/src/org/anddev/andengine/opengl/vertex/RectangleVertexBuffer.java index aef99219..632a5d16 100644 --- a/AndEngine/src/org/anddev/andengine/opengl/vertex/RectangleVertexBuffer.java +++ b/AndEngine/src/org/anddev/andengine/opengl/vertex/RectangleVertexBuffer.java @@ -10,66 +10,66 @@ * @since 13:07:25 - 13.03.2010 */ public class RectangleVertexBuffer extends VertexBuffer { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - public static final int VERTICES_PER_RECTANGLE = 4; + public static final int VERTICES_PER_RECTANGLE = 4; - private static final int FLOAT_TO_RAW_INT_BITS_ZERO = Float.floatToRawIntBits(0); + private static final int FLOAT_TO_RAW_INT_BITS_ZERO = Float.floatToRawIntBits(0); - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - public RectangleVertexBuffer(final int pDrawType, final boolean pManaged) { - super(2 * VERTICES_PER_RECTANGLE, pDrawType, pManaged); - } + public RectangleVertexBuffer(final int pDrawType, final boolean pManaged) { + super(2 * VERTICES_PER_RECTANGLE, pDrawType, pManaged); + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - public synchronized void update(final float pWidth, final float pHeight) { - final int x = FLOAT_TO_RAW_INT_BITS_ZERO; - final int y = FLOAT_TO_RAW_INT_BITS_ZERO; - final int x2 = Float.floatToRawIntBits(pWidth); - final int y2 = Float.floatToRawIntBits(pHeight); + public synchronized void update(final float pWidth, final float pHeight) { + final int x = FLOAT_TO_RAW_INT_BITS_ZERO; + final int y = FLOAT_TO_RAW_INT_BITS_ZERO; + final int x2 = Float.floatToRawIntBits(pWidth); + final int y2 = Float.floatToRawIntBits(pHeight); - final int[] bufferData = this.mBufferData; - bufferData[0] = x; - bufferData[1] = y; + final int[] bufferData = this.mBufferData; + bufferData[0] = x; + bufferData[1] = y; - bufferData[2] = x; - bufferData[3] = y2; + bufferData[2] = x; + bufferData[3] = y2; - bufferData[4] = x2; - bufferData[5] = y; + bufferData[4] = x2; + bufferData[5] = y; - bufferData[6] = x2; - bufferData[7] = y2; + bufferData[6] = x2; + bufferData[7] = y2; - final FastFloatBuffer buffer = this.getFloatBuffer(); - buffer.position(0); - buffer.put(bufferData); - buffer.position(0); + final FastFloatBuffer buffer = this.getFloatBuffer(); + buffer.position(0); + buffer.put(bufferData); + buffer.position(0); - super.setHardwareBufferNeedsUpdate(); - } + super.setHardwareBufferNeedsUpdate(); + } - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/opengl/vertex/SpriteBatchVertexBuffer.java b/AndEngine/src/org/anddev/andengine/opengl/vertex/SpriteBatchVertexBuffer.java index 06fca3ee..c268de5a 100644 --- a/AndEngine/src/org/anddev/andengine/opengl/vertex/SpriteBatchVertexBuffer.java +++ b/AndEngine/src/org/anddev/andengine/opengl/vertex/SpriteBatchVertexBuffer.java @@ -12,228 +12,228 @@ * @since 11:53:48 - 14.06.2011 */ public class SpriteBatchVertexBuffer extends VertexBuffer { - // =========================================================== - // Constants - // =========================================================== - - public static final int VERTICES_PER_RECTANGLE = 6; - - private static final float[] VERTICES_TMP = new float[8]; - - private static final Transformation TRANSFORATION_TMP = new Transformation(); - - // =========================================================== - // Fields - // =========================================================== - - protected int mIndex; - - // =========================================================== - // Constructors - // =========================================================== - - public SpriteBatchVertexBuffer(final int pCapacity, final int pDrawType, final boolean pManaged) { - super(pCapacity * 2 * VERTICES_PER_RECTANGLE, pDrawType, pManaged); - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - public int getIndex() { - return this.mIndex; - } - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - // =========================================================== - // Methods - // =========================================================== - - public void setIndex(final int pIndex) { - this.mIndex = pIndex; - } - - /** - * @param pX - * @param pY - * @param pWidth - * @param pHeight - * @param pRotation around the center (pWidth * 0.5f, pHeight * 0.5f) - */ - public void add(final float pX, final float pY, final float pWidth, final float pHeight, final float pRotation) { - final float widthHalf = pWidth * 0.5f; - final float heightHalf = pHeight * 0.5f; - - TRANSFORATION_TMP.setToIdentity(); - - TRANSFORATION_TMP.postTranslate(-widthHalf, -heightHalf); - TRANSFORATION_TMP.postRotate(pRotation); - TRANSFORATION_TMP.postTranslate(widthHalf, heightHalf); - TRANSFORATION_TMP.postTranslate(pX, pY); - - this.add(pWidth, pHeight, TRANSFORATION_TMP); - } - - /** - * @param pX - * @param pY - * @param pWidth - * @param pHeight - * @param pRotation around the center (pWidth * 0.5f, pHeight * 0.5f) - * @param pScaleX around the center (pWidth * 0.5f, pHeight * 0.5f) - * @param pScaleY around the center (pWidth * 0.5f, pHeight * 0.5f) - */ - public void add(final float pX, final float pY, final float pWidth, final float pHeight, final float pScaleX, final float pScaleY) { - final float widthHalf = pWidth * 0.5f; - final float heightHalf = pHeight * 0.5f; - - TRANSFORATION_TMP.setToIdentity(); - - TRANSFORATION_TMP.postTranslate(-widthHalf, -heightHalf); - TRANSFORATION_TMP.postScale(pScaleX, pScaleY); - TRANSFORATION_TMP.postTranslate(widthHalf, heightHalf); - TRANSFORATION_TMP.postTranslate(pX, pY); - - this.add(pWidth, pHeight, TRANSFORATION_TMP); - } - - /** - * @param pX - * @param pY - * @param pWidth - * @param pHeight - * @param pRotation around the center (pWidth * 0.5f, pHeight * 0.5f) - * @param pScaleX around the center (pWidth * 0.5f, pHeight * 0.5f) - * @param pScaleY around the center (pWidth * 0.5f, pHeight * 0.5f) - */ - public void add(final float pX, final float pY, final float pWidth, final float pHeight, final float pRotation, final float pScaleX, final float pScaleY) { - final float widthHalf = pWidth * 0.5f; - final float heightHalf = pHeight * 0.5f; - - TRANSFORATION_TMP.setToIdentity(); - - TRANSFORATION_TMP.postTranslate(-widthHalf, -heightHalf); - TRANSFORATION_TMP.postScale(pScaleX, pScaleY); - TRANSFORATION_TMP.postRotate(pRotation); - TRANSFORATION_TMP.postTranslate(widthHalf, heightHalf); - TRANSFORATION_TMP.postTranslate(pX, pY); - - this.add(pWidth, pHeight, TRANSFORATION_TMP); - } - - /** - * - * @param pX - * @param pY - * @param pWidth - * @param pHeight - * @param pTransformation - */ - public void add(final float pWidth, final float pHeight, final Transformation pTransformation) { - VERTICES_TMP[0] = 0; - VERTICES_TMP[1] = 0; - - VERTICES_TMP[2] = 0; - VERTICES_TMP[3] = pHeight; - - VERTICES_TMP[4] = pWidth; - VERTICES_TMP[5] = 0; - - VERTICES_TMP[6] = pWidth; - VERTICES_TMP[7] = pHeight; - - pTransformation.transform(VERTICES_TMP); - - this.addInner(VERTICES_TMP[0], VERTICES_TMP[1], VERTICES_TMP[2], VERTICES_TMP[3], VERTICES_TMP[4], VERTICES_TMP[5], VERTICES_TMP[6], VERTICES_TMP[7]); - } - - public void add(final float pX, final float pY, final float pWidth, final float pHeight) { - this.addInner(pX, pY, pX + pWidth, pY + pHeight); - } - - /** - * 1-+ - * |X| - * +-2 - */ - public void addInner(final float pX1, final float pY1, final float pX2, final float pY2) { - final int x1 = Float.floatToRawIntBits(pX1); - final int y1 = Float.floatToRawIntBits(pY1); - final int x2 = Float.floatToRawIntBits(pX2); - final int y2 = Float.floatToRawIntBits(pY2); - - final int[] bufferData = this.mBufferData; - int index = this.mIndex; - bufferData[index++] = x1; - bufferData[index++] = y1; - - bufferData[index++] = x1; - bufferData[index++] = y2; - - bufferData[index++] = x2; - bufferData[index++] = y1; - - bufferData[index++] = x2; - bufferData[index++] = y1; - - bufferData[index++] = x1; - bufferData[index++] = y2; - - bufferData[index++] = x2; - bufferData[index++] = y2; - this.mIndex = index; - } - - /** - * 1-3 - * |X| - * 2-4 - */ - public void addInner(final float pX1, final float pY1, final float pX2, final float pY2, final float pX3, final float pY3, final float pX4, final float pY4) { - final int x1 = Float.floatToRawIntBits(pX1); - final int y1 = Float.floatToRawIntBits(pY1); - final int x2 = Float.floatToRawIntBits(pX2); - final int y2 = Float.floatToRawIntBits(pY2); - final int x3 = Float.floatToRawIntBits(pX3); - final int y3 = Float.floatToRawIntBits(pY3); - final int x4 = Float.floatToRawIntBits(pX4); - final int y4 = Float.floatToRawIntBits(pY4); - - final int[] bufferData = this.mBufferData; - int index = this.mIndex; - bufferData[index++] = x1; - bufferData[index++] = y1; - - bufferData[index++] = x2; - bufferData[index++] = y2; - - bufferData[index++] = x3; - bufferData[index++] = y3; - - bufferData[index++] = x3; - bufferData[index++] = y3; - - bufferData[index++] = x2; - bufferData[index++] = y2; - - bufferData[index++] = x4; - bufferData[index++] = y4; - this.mIndex = index; - } - - public void submit() { - final FastFloatBuffer buffer = this.mFloatBuffer; - buffer.position(0); - buffer.put(this.mBufferData); - buffer.position(0); - - super.setHardwareBufferNeedsUpdate(); - } - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + public static final int VERTICES_PER_RECTANGLE = 6; + + private static final float[] VERTICES_TMP = new float[8]; + + private static final Transformation TRANSFORATION_TMP = new Transformation(); + + // =========================================================== + // Fields + // =========================================================== + + protected int mIndex; + + // =========================================================== + // Constructors + // =========================================================== + + public SpriteBatchVertexBuffer(final int pCapacity, final int pDrawType, final boolean pManaged) { + super(pCapacity * 2 * VERTICES_PER_RECTANGLE, pDrawType, pManaged); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + public int getIndex() { + return this.mIndex; + } + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + public void setIndex(final int pIndex) { + this.mIndex = pIndex; + } + + /** + * @param pX + * @param pY + * @param pWidth + * @param pHeight + * @param pRotation around the center (pWidth * 0.5f, pHeight * 0.5f) + */ + public void add(final float pX, final float pY, final float pWidth, final float pHeight, final float pRotation) { + final float widthHalf = pWidth * 0.5f; + final float heightHalf = pHeight * 0.5f; + + TRANSFORATION_TMP.setToIdentity(); + + TRANSFORATION_TMP.postTranslate(-widthHalf, -heightHalf); + TRANSFORATION_TMP.postRotate(pRotation); + TRANSFORATION_TMP.postTranslate(widthHalf, heightHalf); + TRANSFORATION_TMP.postTranslate(pX, pY); + + this.add(pWidth, pHeight, TRANSFORATION_TMP); + } + + /** + * @param pX + * @param pY + * @param pWidth + * @param pHeight + * @param pRotation around the center (pWidth * 0.5f, pHeight * 0.5f) + * @param pScaleX around the center (pWidth * 0.5f, pHeight * 0.5f) + * @param pScaleY around the center (pWidth * 0.5f, pHeight * 0.5f) + */ + public void add(final float pX, final float pY, final float pWidth, final float pHeight, final float pScaleX, final float pScaleY) { + final float widthHalf = pWidth * 0.5f; + final float heightHalf = pHeight * 0.5f; + + TRANSFORATION_TMP.setToIdentity(); + + TRANSFORATION_TMP.postTranslate(-widthHalf, -heightHalf); + TRANSFORATION_TMP.postScale(pScaleX, pScaleY); + TRANSFORATION_TMP.postTranslate(widthHalf, heightHalf); + TRANSFORATION_TMP.postTranslate(pX, pY); + + this.add(pWidth, pHeight, TRANSFORATION_TMP); + } + + /** + * @param pX + * @param pY + * @param pWidth + * @param pHeight + * @param pRotation around the center (pWidth * 0.5f, pHeight * 0.5f) + * @param pScaleX around the center (pWidth * 0.5f, pHeight * 0.5f) + * @param pScaleY around the center (pWidth * 0.5f, pHeight * 0.5f) + */ + public void add(final float pX, final float pY, final float pWidth, final float pHeight, final float pRotation, final float pScaleX, final float pScaleY) { + final float widthHalf = pWidth * 0.5f; + final float heightHalf = pHeight * 0.5f; + + TRANSFORATION_TMP.setToIdentity(); + + TRANSFORATION_TMP.postTranslate(-widthHalf, -heightHalf); + TRANSFORATION_TMP.postScale(pScaleX, pScaleY); + TRANSFORATION_TMP.postRotate(pRotation); + TRANSFORATION_TMP.postTranslate(widthHalf, heightHalf); + TRANSFORATION_TMP.postTranslate(pX, pY); + + this.add(pWidth, pHeight, TRANSFORATION_TMP); + } + + /** + * + * @param pX + * @param pY + * @param pWidth + * @param pHeight + * @param pTransformation + */ + public void add(final float pWidth, final float pHeight, final Transformation pTransformation) { + VERTICES_TMP[0] = 0; + VERTICES_TMP[1] = 0; + + VERTICES_TMP[2] = 0; + VERTICES_TMP[3] = pHeight; + + VERTICES_TMP[4] = pWidth; + VERTICES_TMP[5] = 0; + + VERTICES_TMP[6] = pWidth; + VERTICES_TMP[7] = pHeight; + + pTransformation.transform(VERTICES_TMP); + + this.addInner(VERTICES_TMP[0], VERTICES_TMP[1], VERTICES_TMP[2], VERTICES_TMP[3], VERTICES_TMP[4], VERTICES_TMP[5], VERTICES_TMP[6], VERTICES_TMP[7]); + } + + public void add(final float pX, final float pY, final float pWidth, final float pHeight) { + this.addInner(pX, pY, pX + pWidth, pY + pHeight); + } + + /** + * 1-+ + * |X| + * +-2 + */ + public void addInner(final float pX1, final float pY1, final float pX2, final float pY2) { + final int x1 = Float.floatToRawIntBits(pX1); + final int y1 = Float.floatToRawIntBits(pY1); + final int x2 = Float.floatToRawIntBits(pX2); + final int y2 = Float.floatToRawIntBits(pY2); + + final int[] bufferData = this.mBufferData; + int index = this.mIndex; + bufferData[index++] = x1; + bufferData[index++] = y1; + + bufferData[index++] = x1; + bufferData[index++] = y2; + + bufferData[index++] = x2; + bufferData[index++] = y1; + + bufferData[index++] = x2; + bufferData[index++] = y1; + + bufferData[index++] = x1; + bufferData[index++] = y2; + + bufferData[index++] = x2; + bufferData[index++] = y2; + this.mIndex = index; + } + + /** + * 1-3 + * |X| + * 2-4 + */ + public void addInner(final float pX1, final float pY1, final float pX2, final float pY2, final float pX3, final float pY3, final float pX4, final float pY4) { + final int x1 = Float.floatToRawIntBits(pX1); + final int y1 = Float.floatToRawIntBits(pY1); + final int x2 = Float.floatToRawIntBits(pX2); + final int y2 = Float.floatToRawIntBits(pY2); + final int x3 = Float.floatToRawIntBits(pX3); + final int y3 = Float.floatToRawIntBits(pY3); + final int x4 = Float.floatToRawIntBits(pX4); + final int y4 = Float.floatToRawIntBits(pY4); + + final int[] bufferData = this.mBufferData; + int index = this.mIndex; + bufferData[index++] = x1; + bufferData[index++] = y1; + + bufferData[index++] = x2; + bufferData[index++] = y2; + + bufferData[index++] = x3; + bufferData[index++] = y3; + + bufferData[index++] = x3; + bufferData[index++] = y3; + + bufferData[index++] = x2; + bufferData[index++] = y2; + + bufferData[index++] = x4; + bufferData[index++] = y4; + this.mIndex = index; + } + + public void submit() { + final FastFloatBuffer buffer = this.mFloatBuffer; + buffer.position(0); + buffer.put(this.mBufferData); + buffer.position(0); + + super.setHardwareBufferNeedsUpdate(); + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/opengl/vertex/TextVertexBuffer.java b/AndEngine/src/org/anddev/andengine/opengl/vertex/TextVertexBuffer.java index 677810f7..b7fd04c8 100644 --- a/AndEngine/src/org/anddev/andengine/opengl/vertex/TextVertexBuffer.java +++ b/AndEngine/src/org/anddev/andengine/opengl/vertex/TextVertexBuffer.java @@ -13,108 +13,108 @@ * @since 18:05:08 - 07.04.2010 */ public class TextVertexBuffer extends VertexBuffer { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - public static final int VERTICES_PER_CHARACTER = 6; + public static final int VERTICES_PER_CHARACTER = 6; - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - private final HorizontalAlign mHorizontalAlign; + private final HorizontalAlign mHorizontalAlign; - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - public TextVertexBuffer(final int pCharacterCount, final HorizontalAlign pHorizontalAlign, final int pDrawType, final boolean pManaged) { - super(2 * VERTICES_PER_CHARACTER * pCharacterCount, pDrawType, pManaged); + public TextVertexBuffer(final int pCharacterCount, final HorizontalAlign pHorizontalAlign, final int pDrawType, final boolean pManaged) { + super(2 * VERTICES_PER_CHARACTER * pCharacterCount, pDrawType, pManaged); - this.mHorizontalAlign = pHorizontalAlign; - } + this.mHorizontalAlign = pHorizontalAlign; + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - public synchronized void update(final Font font, final int pMaximumLineWidth, final int[] pWidths, final String[] pLines) { - final int[] bufferData = this.mBufferData; - int i = 0; + public synchronized void update(final Font font, final int pMaximumLineWidth, final int[] pWidths, final String[] pLines) { + final int[] bufferData = this.mBufferData; + int i = 0; - final int lineHeight = font.getLineHeight(); + final int lineHeight = font.getLineHeight(); - final int lineCount = pLines.length; - for (int lineIndex = 0; lineIndex < lineCount; lineIndex++) { - final String line = pLines[lineIndex]; + final int lineCount = pLines.length; + for (int lineIndex = 0; lineIndex < lineCount; lineIndex++) { + final String line = pLines[lineIndex]; - int lineX; - switch(this.mHorizontalAlign) { - case RIGHT: - lineX = pMaximumLineWidth - pWidths[lineIndex]; - break; - case CENTER: - lineX = (pMaximumLineWidth - pWidths[lineIndex]) >> 1; - break; - case LEFT: - default: - lineX = 0; - } + int lineX; + switch(this.mHorizontalAlign) { + case RIGHT: + lineX = pMaximumLineWidth - pWidths[lineIndex]; + break; + case CENTER: + lineX = (pMaximumLineWidth - pWidths[lineIndex]) >> 1; + break; + case LEFT: + default: + lineX = 0; + } - final int lineY = lineIndex * (font.getLineHeight() + font.getLineGap()); - final int lineYBits = Float.floatToRawIntBits(lineY); + final int lineY = lineIndex * (font.getLineHeight() + font.getLineGap()); + final int lineYBits = Float.floatToRawIntBits(lineY); - final int lineLength = line.length(); - for (int letterIndex = 0; letterIndex < lineLength; letterIndex++) { - final Letter letter = font.getLetter(line.charAt(letterIndex)); + final int lineLength = line.length(); + for (int letterIndex = 0; letterIndex < lineLength; letterIndex++) { + final Letter letter = font.getLetter(line.charAt(letterIndex)); - final int lineY2 = lineY + lineHeight; - final int lineX2 = lineX + letter.mWidth; + final int lineY2 = lineY + lineHeight; + final int lineX2 = lineX + letter.mWidth; - final int lineXBits = Float.floatToRawIntBits(lineX); - final int lineX2Bits = Float.floatToRawIntBits(lineX2); - final int lineY2Bits = Float.floatToRawIntBits(lineY2); + final int lineXBits = Float.floatToRawIntBits(lineX); + final int lineX2Bits = Float.floatToRawIntBits(lineX2); + final int lineY2Bits = Float.floatToRawIntBits(lineY2); - bufferData[i++] = lineXBits; - bufferData[i++] = lineYBits; + bufferData[i++] = lineXBits; + bufferData[i++] = lineYBits; - bufferData[i++] = lineXBits; - bufferData[i++] = lineY2Bits; + bufferData[i++] = lineXBits; + bufferData[i++] = lineY2Bits; - bufferData[i++] = lineX2Bits; - bufferData[i++] = lineY2Bits; + bufferData[i++] = lineX2Bits; + bufferData[i++] = lineY2Bits; - bufferData[i++] = lineX2Bits; - bufferData[i++] = lineY2Bits; + bufferData[i++] = lineX2Bits; + bufferData[i++] = lineY2Bits; - bufferData[i++] = lineX2Bits; - bufferData[i++] = lineYBits; + bufferData[i++] = lineX2Bits; + bufferData[i++] = lineYBits; - bufferData[i++] = lineXBits; - bufferData[i++] = lineYBits; + bufferData[i++] = lineXBits; + bufferData[i++] = lineYBits; - lineX += letter.mAdvance; - } - } + lineX += letter.mAdvance; + } + } - final FastFloatBuffer vertexFloatBuffer = this.mFloatBuffer; - vertexFloatBuffer.position(0); - vertexFloatBuffer.put(bufferData); - vertexFloatBuffer.position(0); + final FastFloatBuffer vertexFloatBuffer = this.mFloatBuffer; + vertexFloatBuffer.position(0); + vertexFloatBuffer.put(bufferData); + vertexFloatBuffer.position(0); - super.setHardwareBufferNeedsUpdate(); - } + super.setHardwareBufferNeedsUpdate(); + } - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/opengl/vertex/VertexBuffer.java b/AndEngine/src/org/anddev/andengine/opengl/vertex/VertexBuffer.java index 43dbb3bb..d4864255 100644 --- a/AndEngine/src/org/anddev/andengine/opengl/vertex/VertexBuffer.java +++ b/AndEngine/src/org/anddev/andengine/opengl/vertex/VertexBuffer.java @@ -10,35 +10,35 @@ * @since 12:16:18 - 09.03.2010 */ public abstract class VertexBuffer extends BufferObject { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - public VertexBuffer(final int pCapacity, final int pDrawType, final boolean pManaged) { - super(pCapacity, pDrawType, pManaged); - } + public VertexBuffer(final int pCapacity, final int pDrawType, final boolean pManaged) { + super(pCapacity, pDrawType, pManaged); + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/opengl/view/BaseConfigChooser.java b/AndEngine/src/org/anddev/andengine/opengl/view/BaseConfigChooser.java index 7afabafe..abb81e2a 100644 --- a/AndEngine/src/org/anddev/andengine/opengl/view/BaseConfigChooser.java +++ b/AndEngine/src/org/anddev/andengine/opengl/view/BaseConfigChooser.java @@ -15,59 +15,59 @@ * @since 20:42:29 - 28.06.2010 */ abstract class BaseConfigChooser implements EGLConfigChooser { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - protected final int[] mConfigSpec; + protected final int[] mConfigSpec; - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - public BaseConfigChooser(final int[] pConfigSpec) { - this.mConfigSpec = pConfigSpec; - } + public BaseConfigChooser(final int[] pConfigSpec) { + this.mConfigSpec = pConfigSpec; + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - abstract EGLConfig chooseConfig(final EGL10 pEGL, final EGLDisplay pEGLDisplay, final EGLConfig[] pEGLConfigs); + abstract EGLConfig chooseConfig(final EGL10 pEGL, final EGLDisplay pEGLDisplay, final EGLConfig[] pEGLConfigs); - @Override - public EGLConfig chooseConfig(final EGL10 pEGL, final EGLDisplay pEGLDisplay) { - final int[] num_config = new int[1]; - pEGL.eglChooseConfig(pEGLDisplay, this.mConfigSpec, null, 0, num_config); + @Override + public EGLConfig chooseConfig(final EGL10 pEGL, final EGLDisplay pEGLDisplay) { + final int[] num_config = new int[1]; + pEGL.eglChooseConfig(pEGLDisplay, this.mConfigSpec, null, 0, num_config); - final int numConfigs = num_config[0]; + final int numConfigs = num_config[0]; - if(numConfigs <= 0) { - throw new IllegalArgumentException("No configs match configSpec"); - } + if(numConfigs <= 0) { + throw new IllegalArgumentException("No configs match configSpec"); + } - final EGLConfig[] configs = new EGLConfig[numConfigs]; - pEGL.eglChooseConfig(pEGLDisplay, this.mConfigSpec, configs, numConfigs, num_config); - final EGLConfig config = this.chooseConfig(pEGL, pEGLDisplay, configs); - if(config == null) { - throw new IllegalArgumentException("No config chosen"); - } - return config; - } + final EGLConfig[] configs = new EGLConfig[numConfigs]; + pEGL.eglChooseConfig(pEGLDisplay, this.mConfigSpec, configs, numConfigs, num_config); + final EGLConfig config = this.chooseConfig(pEGL, pEGLDisplay, configs); + if(config == null) { + throw new IllegalArgumentException("No config chosen"); + } + return config; + } - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== -} \ No newline at end of file + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== +} diff --git a/AndEngine/src/org/anddev/andengine/opengl/view/ComponentSizeChooser.java b/AndEngine/src/org/anddev/andengine/opengl/view/ComponentSizeChooser.java index 957942ca..6d0ea6d3 100644 --- a/AndEngine/src/org/anddev/andengine/opengl/view/ComponentSizeChooser.java +++ b/AndEngine/src/org/anddev/andengine/opengl/view/ComponentSizeChooser.java @@ -12,78 +12,78 @@ * @since 20:54:06 - 28.06.2010 */ public class ComponentSizeChooser extends BaseConfigChooser { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - private final int[] mValue; - // Subclasses can adjust these values: - protected int mRedSize; - protected int mGreenSize; - protected int mBlueSize; - protected int mAlphaSize; - protected int mDepthSize; - protected int mStencilSize; + private final int[] mValue; + // Subclasses can adjust these values: + protected int mRedSize; + protected int mGreenSize; + protected int mBlueSize; + protected int mAlphaSize; + protected int mDepthSize; + protected int mStencilSize; - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - public ComponentSizeChooser(final int pRedSize, final int pGreenSize, final int pBlueSize, final int pAlphaSize, final int pDepthSize, final int pStencilSize) { - super(new int[] { EGL10.EGL_RED_SIZE, pRedSize, EGL10.EGL_GREEN_SIZE, pGreenSize, EGL10.EGL_BLUE_SIZE, pBlueSize, EGL10.EGL_ALPHA_SIZE, pAlphaSize, EGL10.EGL_DEPTH_SIZE, pDepthSize, EGL10.EGL_STENCIL_SIZE, pStencilSize, EGL10.EGL_NONE }); - this.mValue = new int[1]; - this.mRedSize = pRedSize; - this.mGreenSize = pGreenSize; - this.mBlueSize = pBlueSize; - this.mAlphaSize = pAlphaSize; - this.mDepthSize = pDepthSize; - this.mStencilSize = pStencilSize; - } + public ComponentSizeChooser(final int pRedSize, final int pGreenSize, final int pBlueSize, final int pAlphaSize, final int pDepthSize, final int pStencilSize) { + super(new int[] { EGL10.EGL_RED_SIZE, pRedSize, EGL10.EGL_GREEN_SIZE, pGreenSize, EGL10.EGL_BLUE_SIZE, pBlueSize, EGL10.EGL_ALPHA_SIZE, pAlphaSize, EGL10.EGL_DEPTH_SIZE, pDepthSize, EGL10.EGL_STENCIL_SIZE, pStencilSize, EGL10.EGL_NONE }); + this.mValue = new int[1]; + this.mRedSize = pRedSize; + this.mGreenSize = pGreenSize; + this.mBlueSize = pBlueSize; + this.mAlphaSize = pAlphaSize; + this.mDepthSize = pDepthSize; + this.mStencilSize = pStencilSize; + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - @Override - public EGLConfig chooseConfig(final EGL10 pEGL, final EGLDisplay pEGLDisplay, final EGLConfig[] pEGLConfigs) { - EGLConfig closestConfig = null; - int closestDistance = 1000; - for(final EGLConfig config : pEGLConfigs) { - final int r = this.findConfigAttrib(pEGL, pEGLDisplay, config, EGL10.EGL_RED_SIZE, 0); - final int g = this.findConfigAttrib(pEGL, pEGLDisplay, config, EGL10.EGL_GREEN_SIZE, 0); - final int b = this.findConfigAttrib(pEGL, pEGLDisplay, config, EGL10.EGL_BLUE_SIZE, 0); - final int a = this.findConfigAttrib(pEGL, pEGLDisplay, config, EGL10.EGL_ALPHA_SIZE, 0); - final int d = this.findConfigAttrib(pEGL, pEGLDisplay, config, EGL10.EGL_DEPTH_SIZE, 0); - final int s = this.findConfigAttrib(pEGL, pEGLDisplay, config, EGL10.EGL_STENCIL_SIZE, 0); - final int distance = Math.abs(r - this.mRedSize) + Math.abs(g - this.mGreenSize) + Math.abs(b - this.mBlueSize) + Math.abs(a - this.mAlphaSize) + Math.abs(d - this.mDepthSize) + Math.abs(s - this.mStencilSize); - if(distance < closestDistance) { - closestDistance = distance; - closestConfig = config; - } - } - return closestConfig; - } + @Override + public EGLConfig chooseConfig(final EGL10 pEGL, final EGLDisplay pEGLDisplay, final EGLConfig[] pEGLConfigs) { + EGLConfig closestConfig = null; + int closestDistance = 1000; + for(final EGLConfig config : pEGLConfigs) { + final int r = this.findConfigAttrib(pEGL, pEGLDisplay, config, EGL10.EGL_RED_SIZE, 0); + final int g = this.findConfigAttrib(pEGL, pEGLDisplay, config, EGL10.EGL_GREEN_SIZE, 0); + final int b = this.findConfigAttrib(pEGL, pEGLDisplay, config, EGL10.EGL_BLUE_SIZE, 0); + final int a = this.findConfigAttrib(pEGL, pEGLDisplay, config, EGL10.EGL_ALPHA_SIZE, 0); + final int d = this.findConfigAttrib(pEGL, pEGLDisplay, config, EGL10.EGL_DEPTH_SIZE, 0); + final int s = this.findConfigAttrib(pEGL, pEGLDisplay, config, EGL10.EGL_STENCIL_SIZE, 0); + final int distance = Math.abs(r - this.mRedSize) + Math.abs(g - this.mGreenSize) + Math.abs(b - this.mBlueSize) + Math.abs(a - this.mAlphaSize) + Math.abs(d - this.mDepthSize) + Math.abs(s - this.mStencilSize); + if(distance < closestDistance) { + closestDistance = distance; + closestConfig = config; + } + } + return closestConfig; + } - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - private int findConfigAttrib(final EGL10 pEGL, final EGLDisplay pEGLDisplay, final EGLConfig pEGLConfig, final int pAttribute, final int pDefaultValue) { - if(pEGL.eglGetConfigAttrib(pEGLDisplay, pEGLConfig, pAttribute, this.mValue)) { - return this.mValue[0]; - } - return pDefaultValue; - } + private int findConfigAttrib(final EGL10 pEGL, final EGLDisplay pEGLDisplay, final EGLConfig pEGLConfig, final int pAttribute, final int pDefaultValue) { + if(pEGL.eglGetConfigAttrib(pEGLDisplay, pEGLConfig, pAttribute, this.mValue)) { + return this.mValue[0]; + } + return pDefaultValue; + } - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== -} \ No newline at end of file + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== +} diff --git a/AndEngine/src/org/anddev/andengine/opengl/view/EGLConfigChooser.java b/AndEngine/src/org/anddev/andengine/opengl/view/EGLConfigChooser.java index e575b837..6bd438dd 100644 --- a/AndEngine/src/org/anddev/andengine/opengl/view/EGLConfigChooser.java +++ b/AndEngine/src/org/anddev/andengine/opengl/view/EGLConfigChooser.java @@ -18,24 +18,24 @@ * @since 20:53:49 - 28.06.2010 */ public interface EGLConfigChooser { - // =========================================================== - // Final Fields - // =========================================================== + // =========================================================== + // Final Fields + // =========================================================== - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - /** - * Choose a configuration from the list. Implementors typically - * implement this method by calling {@link EGL10#eglChooseConfig} and - * iterating through the results. Please consult the EGL specification - * available from The Khronos Group to learn how to call - * eglChooseConfig. - * - * @param pEGL the EGL10 for the current display. - * @param pEGLDisplay the current display. - * @return the chosen configuration. - */ - public EGLConfig chooseConfig(final EGL10 pEGL, final EGLDisplay pEGLDisplay); -} \ No newline at end of file + /** + * Choose a configuration from the list. Implementors typically + * implement this method by calling {@link EGL10#eglChooseConfig} and + * iterating through the results. Please consult the EGL specification + * available from The Khronos Group to learn how to call + * eglChooseConfig. + * + * @param pEGL the EGL10 for the current display. + * @param pEGLDisplay the current display. + * @return the chosen configuration. + */ + public EGLConfig chooseConfig(final EGL10 pEGL, final EGLDisplay pEGLDisplay); +} diff --git a/AndEngine/src/org/anddev/andengine/opengl/view/GLSurfaceView.java b/AndEngine/src/org/anddev/andengine/opengl/view/GLSurfaceView.java index f2f735dd..08bdfea9 100644 --- a/AndEngine/src/org/anddev/andengine/opengl/view/GLSurfaceView.java +++ b/AndEngine/src/org/anddev/andengine/opengl/view/GLSurfaceView.java @@ -118,874 +118,874 @@ *
  * class MyGLSurfaceView extends GLSurfaceView {
  * 
- * 	private MyRenderer mMyRenderer;
+ *     private MyRenderer mMyRenderer;
  * 
- * 	public void start() {
+ *     public void start() {
  *         mMyRenderer = ...;
  *         setRenderer(mMyRenderer);
  *     }
  * 
- * 	public boolean onKeyDown(int keyCode, KeyEvent event) {
- * 		if(keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
- * 			queueEvent(new Runnable() {
- * 				// This method will be called on the rendering
- * 				// thread:
- * 				public void run() {
- * 					mMyRenderer.handleDpadCenter();
- * 				}
- * 			});
- * 			return true;
- * 		}
- * 		return super.onKeyDown(keyCode, event);
- * 	}
+ *     public boolean onKeyDown(int keyCode, KeyEvent event) {
+ *         if(keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
+ *             queueEvent(new Runnable() {
+ *                 // This method will be called on the rendering
+ *                 // thread:
+ *                 public void run() {
+ *                     mMyRenderer.handleDpadCenter();
+ *                 }
+ *             });
+ *             return true;
+ *         }
+ *         return super.onKeyDown(keyCode, event);
+ *     }
  * }
  * 
* */ public class GLSurfaceView extends SurfaceView implements SurfaceHolder.Callback { - // =========================================================== - // Constants - // =========================================================== - - /** - * The renderer only renders when the surface is created, or when - * {@link #requestRender} is called. - * - * @see #getRenderMode() - * @see #setRenderMode(int) - */ - public final static int RENDERMODE_WHEN_DIRTY = 0; - /** - * The renderer is called continuously to re-render the scene. - * - * @see #getRenderMode() - * @see #setRenderMode(int) - * @see #requestRender() - */ - public final static int RENDERMODE_CONTINUOUSLY = 1; - - /** - * Check glError() after every GL call and throw an exception if glError - * indicates that an error has occurred. This can be used to help track down - * which OpenGL ES call is causing an error. - * - * @see #getDebugFlags - * @see #setDebugFlags - */ - public final static int DEBUG_CHECK_GL_ERROR = 1; - - /** - * Log GL calls to the system log at "verbose" level with tag - * "GLSurfaceView". - * - * @see #getDebugFlags - * @see #setDebugFlags - */ - public final static int DEBUG_LOG_GL_CALLS = 2; - - private static final Semaphore sEglSemaphore = new Semaphore(1); - - // =========================================================== - // Fields - // =========================================================== - - private GLThread mGLThread; - private EGLConfigChooser mEGLConfigChooser; - private GLWrapper mGLWrapper; - private int mDebugFlags; - private int mRenderMode; - private Renderer mRenderer; - private int mSurfaceWidth; - private int mSurfaceHeight; - private boolean mHasSurface; - - // =========================================================== - // Constructors - // =========================================================== - - /** - * Standard View constructor. In order to render something, you must call - * {@link #setRenderer} to register a renderer. - */ - public GLSurfaceView(final Context context) { - super(context); - this.init(); - } - - /** - * Standard View constructor. In order to render something, you must call - * {@link #setRenderer} to register a renderer. - */ - public GLSurfaceView(final Context context, final AttributeSet attrs) { - super(context, attrs); - this.init(); - } - - private void init() { - // Install a SurfaceHolder.Callback so we get notified when the - // underlying surface is created and destroyed - final SurfaceHolder holder = this.getHolder(); - holder.addCallback(this); - holder.setType(SurfaceHolder.SURFACE_TYPE_GPU); - this.mRenderMode = RENDERMODE_CONTINUOUSLY; - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - /** - * Set the glWrapper. If the glWrapper is not null, its - * {@link GLWrapper#wrap(GL)} method is called whenever a surface is - * created. A GLWrapper can be used to wrap the GL object that'MAGIC_CONSTANT passed to - * the renderer. Wrapping a GL object enables examining and modifying the - * behavior of the GL calls made by the renderer. - *

- * Wrapping is typically used for debugging purposes. - *

- * The default value is null. - * - * @param glWrapper - * the new GLWrapper - */ - public void setGLWrapper(final GLWrapper glWrapper) { - this.mGLWrapper = glWrapper; - } - - /** - * Set the debug flags to a new value. The value is constructed by - * OR-together zero or more of the DEBUG_CHECK_* constants. The debug flags - * take effect whenever a surface is created. The default value is zero. - * - * @param debugFlags - * the new debug flags - * @see #DEBUG_CHECK_GL_ERROR - * @see #DEBUG_LOG_GL_CALLS - */ - public void setDebugFlags(final int debugFlags) { - this.mDebugFlags = debugFlags; - } - - /** - * Get the current value of the debug flags. - * - * @return the current value of the debug flags. - */ - public int getDebugFlags() { - return this.mDebugFlags; - } - - /** - * Set the renderer associated with this view. Also starts the thread that - * will call the renderer, which in turn causes the rendering to start. - *

- * This method should be called once and only once in the life-cycle of a - * GLSurfaceView. - *

- * The following GLSurfaceView methods can only be called before - * setRenderer is called: - *

    - *
  • {@link #setEGLConfigChooser(boolean)} - *
  • {@link #setEGLConfigChooser(EGLConfigChooser)} - *
  • {@link #setEGLConfigChooser(int, int, int, int, int, int)} - *
- *

- * The following GLSurfaceView methods can only be called after - * setRenderer is called: - *

    - *
  • {@link #getRenderMode()} - *
  • {@link #onPause()} - *
  • {@link #onResume()} - *
  • {@link #queueEvent(Runnable)} - *
  • {@link #requestRender()} - *
  • {@link #setRenderMode(int)} - *
- * - * @param renderer - * the renderer to use to perform OpenGL drawing. - */ - public void setRenderer(final Renderer renderer) { - if(this.mRenderer != null) { - throw new IllegalStateException("setRenderer has already been called for this instance."); - } - - this.mRenderer = renderer; - } - - /** - * Install a custom EGLConfigChooser. - *

- * If this method is called, it must be called before - * {@link #setRenderer(Renderer)} is called. - *

- * If no setEGLConfigChooser method is called, then by default the view will - * choose a config as close to 16-bit RGB as possible, with a depth buffer - * as close to 16 bits as possible. - * - * @param configChooser - */ - public void setEGLConfigChooser(final EGLConfigChooser configChooser) { - if(this.mRenderer != null) { - throw new IllegalStateException("setRenderer has already been called for this instance."); - } - this.mEGLConfigChooser = configChooser; - } - - /** - * Install a config chooser which will choose a config as close to 16-bit - * RGB as possible, with or without an optional depth buffer as close to - * 16-bits as possible. - *

- * If this method is called, it must be called before - * {@link #setRenderer(Renderer)} is called. - *

- * If no setEGLConfigChooser method is called, then by default the view will - * choose a config as close to 16-bit RGB as possible, with a depth buffer - * as close to 16 bits as possible. - * - * @param needDepth - */ - public void setEGLConfigChooser(final boolean needDepth) { - this.setEGLConfigChooser(new SimpleEGLConfigChooser(needDepth)); - } - - /** - * Install a config chooser which will choose a config with at least the - * specified component sizes, and as close to the specified component sizes - * as possible. - *

- * If this method is called, it must be called before - * {@link #setRenderer(Renderer)} is called. - *

- * If no setEGLConfigChooser method is called, then by default the view will - * choose a config as close to 16-bit RGB as possible, with a depth buffer - * as close to 16 bits as possible. - * - */ - public void setEGLConfigChooser(final int redSize, final int greenSize, final int blueSize, final int alphaSize, final int depthSize, final int stencilSize) { - this.setEGLConfigChooser(new ComponentSizeChooser(redSize, greenSize, blueSize, alphaSize, depthSize, stencilSize)); - } - - /** - * Set the rendering mode. When renderMode is RENDERMODE_CONTINUOUSLY, the - * renderer is called repeatedly to re-render the scene. When renderMode is - * RENDERMODE_WHEN_DIRTY, the renderer only rendered when the surface is - * created, or when {@link #requestRender} is called. Defaults to - * RENDERMODE_CONTINUOUSLY. - *

- * Using RENDERMODE_WHEN_DIRTY can improve battery life and overall system - * performance by allowing the GPU and CPU to idle when the view does not - * need to be updated. - *

- * This method can only be called after {@link #setRenderer(Renderer)} - * - * @param renderMode - * one of the RENDERMODE_X constants - * @see #RENDERMODE_CONTINUOUSLY - * @see #RENDERMODE_WHEN_DIRTY - */ - public void setRenderMode(final int renderMode) { - this.mRenderMode = renderMode; - if(this.mGLThread != null) { - this.mGLThread.setRenderMode(renderMode); - } - } - - /** - * Get the current rendering mode. May be called from any thread. Must not - * be called before a renderer has been set. - * - * @return the current rendering mode. - * @see #RENDERMODE_CONTINUOUSLY - * @see #RENDERMODE_WHEN_DIRTY - */ - public int getRenderMode() { - return this.mRenderMode; - } - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - /** - * Request that the renderer render a frame. This method is typically used - * when the render mode has been set to {@link #RENDERMODE_WHEN_DIRTY}, so - * that frames are only rendered on demand. May be called from any thread. - * Must be called after onResume() and before onPause(). - */ - public void requestRender() { - this.mGLThread.requestRender(); - } - - /** - * This method is part of the SurfaceHolder.Callback interface, and is not - * normally called or subclassed by clients of GLSurfaceView. - */ - @Override - public void surfaceCreated(final SurfaceHolder holder) { - if(this.mGLThread != null) { - this.mGLThread.surfaceCreated(); - } - this.mHasSurface = true; - } - - /** - * This method is part of the SurfaceHolder.Callback interface, and is not - * normally called or subclassed by clients of GLSurfaceView. - */ - @Override - public void surfaceDestroyed(final SurfaceHolder holder) { - // Surface will be destroyed when we return - if(this.mGLThread != null) { - this.mGLThread.surfaceDestroyed(); - } - this.mHasSurface = false; - } - - /** - * This method is part of the SurfaceHolder.Callback interface, and is not - * normally called or subclassed by clients of GLSurfaceView. - */ - @Override - public void surfaceChanged(final SurfaceHolder holder, final int format, final int w, final int h) { - if(this.mGLThread != null) { - this.mGLThread.onWindowResize(w, h); - } - this.mSurfaceWidth = w; - this.mSurfaceHeight = h; - } - - /** - * Inform the view that the activity is paused. The owner of this view must - * call this method when the activity is paused. Calling this method will - * pause the rendering thread. Must not be called before a renderer has been - * set. - */ - public void onPause() { - this.mGLThread.onPause(); - this.mGLThread.requestExitAndWait(); - this.mGLThread = null; - } - - /** - * Inform the view that the activity is resumed. The owner of this view must - * call this method when the activity is resumed. Calling this method will - * recreate the OpenGL display and resume the rendering thread. Must not be - * called before a renderer has been set. - */ - public void onResume() { - if(this.mEGLConfigChooser == null) { - this.mEGLConfigChooser = new SimpleEGLConfigChooser(true); - } - this.mGLThread = new GLThread(this.mRenderer); - this.mGLThread.start(); - this.mGLThread.setRenderMode(this.mRenderMode); - if(this.mHasSurface) { - this.mGLThread.surfaceCreated(); - } - if(this.mSurfaceWidth > 0 && this.mSurfaceHeight > 0) { - this.mGLThread.onWindowResize(this.mSurfaceWidth, this.mSurfaceHeight); - } - this.mGLThread.onResume(); - } - - /** - * Queue a runnable to be run on the GL rendering thread. This can be used - * to communicate with the Renderer on the rendering thread. Must be called - * after onResume() and before onPause(). - * - * @param r - * the runnable to be run on the GL rendering thread. - */ - public void queueEvent(final Runnable r) { - if(this.mGLThread != null) { - this.mGLThread.queueEvent(r); - } - } - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== - - /** - * A generic GL Thread. Takes care of initializing EGL and GL. Delegates to - * a Renderer instance to do the actual drawing. Can be configured to render - * continuously or on request. - * - */ - class GLThread extends Thread { - GLThread(final Renderer renderer) { - super(); - this.mDone = false; - this.mWidth = 0; - this.mHeight = 0; - this.mRequestRender = true; - this.mRenderMode = RENDERMODE_CONTINUOUSLY; - this.mRenderer = renderer; - this.mSizeChanged = true; - this.setName("GLThread"); - } - - @Override - public void run() { - /* - * When the android framework launches a second instance of an - * activity, the new instance'MAGIC_CONSTANT onCreate() method may be called - * before the first instance returns from onDestroy(). - * - * This semaphore ensures that only one instance at a time accesses - * EGL. - */ - try { - try { - sEglSemaphore.acquire(); - } catch (final InterruptedException e) { - return; - } - this.guardedRun(); - } catch (final InterruptedException e) { - // fall thru and exit normally - } finally { - sEglSemaphore.release(); - } - } - - private void guardedRun() throws InterruptedException { - this.mEglHelper = new EglHelper(); - this.mEglHelper.start(); - - GL10 gl = null; - boolean tellRendererSurfaceCreated = true; - boolean tellRendererSurfaceChanged = true; - - /* - * This is our main activity thread'MAGIC_CONSTANT loop, we go until asked to - * quit. - */ - while(!this.mDone) { - - /* - * Update the asynchronous state (window size) - */ - int w, h; - boolean changed; - boolean needStart = false; - synchronized (this) { - Runnable r; - while((r = this.getEvent()) != null) { - r.run(); - } - if(this.mPaused) { - this.mEglHelper.finish(); - needStart = true; - } - while(this.needToWait()) { - this.wait(); - } - if(this.mDone) { - break; - } - changed = this.mSizeChanged; - w = this.mWidth; - h = this.mHeight; - this.mSizeChanged = false; - this.mRequestRender = false; - } - if(needStart) { - this.mEglHelper.start(); - tellRendererSurfaceCreated = true; - changed = true; - } - if(changed) { - gl = (GL10) this.mEglHelper.createSurface(GLSurfaceView.this.getHolder()); - tellRendererSurfaceChanged = true; - } - if(tellRendererSurfaceCreated) { - this.mRenderer.onSurfaceCreated(gl, this.mEglHelper.mEglConfig); - tellRendererSurfaceCreated = false; - } - if(tellRendererSurfaceChanged) { - this.mRenderer.onSurfaceChanged(gl, w, h); - tellRendererSurfaceChanged = false; - } - if((w > 0) && (h > 0)) { - /* draw a frame here */ - this.mRenderer.onDrawFrame(gl); - - /* - * Once we're done with GL, we need to call swapBuffers() to - * instruct the system to display the rendered frame - */ - this.mEglHelper.swap(); - } - } - - /* - * clean-up everything... - */ - this.mEglHelper.finish(); - } - - private boolean needToWait() { - if(this.mDone) { - return false; - } - - if(this.mPaused || (!this.mHasSurface)) { - return true; - } - - if((this.mWidth > 0) && (this.mHeight > 0) && (this.mRequestRender || (this.mRenderMode == RENDERMODE_CONTINUOUSLY))) { - return false; - } - - return true; - } - - public void setRenderMode(final int renderMode) { - if(!((RENDERMODE_WHEN_DIRTY <= renderMode) && (renderMode <= RENDERMODE_CONTINUOUSLY))) { - throw new IllegalArgumentException("renderMode"); - } - synchronized (this) { - this.mRenderMode = renderMode; - if(renderMode == RENDERMODE_CONTINUOUSLY) { - this.notify(); - } - } - } - - public int getRenderMode() { - synchronized (this) { - return this.mRenderMode; - } - } - - public void requestRender() { - synchronized (this) { - this.mRequestRender = true; - this.notify(); - } - } - - public void surfaceCreated() { - synchronized (this) { - this.mHasSurface = true; - this.notify(); - } - } - - public void surfaceDestroyed() { - synchronized (this) { - this.mHasSurface = false; - this.notify(); - } - } - - public void onPause() { - synchronized (this) { - this.mPaused = true; - } - } - - public void onResume() { - synchronized (this) { - this.mPaused = false; - this.notify(); - } - } - - public void onWindowResize(final int w, final int h) { - synchronized (this) { - this.mWidth = w; - this.mHeight = h; - this.mSizeChanged = true; - this.notify(); - } - } - - public void requestExitAndWait() { - // don't call this from GLThread thread or it is a guaranteed - // deadlock! - synchronized (this) { - this.mDone = true; - this.notify(); - } - try { - this.join(); - } catch (final InterruptedException ex) { - Thread.currentThread().interrupt(); - } - } - - /** - * Queue an "event" to be run on the GL rendering thread. - * - * @param r - * the runnable to be run on the GL rendering thread. - */ - public void queueEvent(final Runnable r) { - synchronized (this) { - this.mEventQueue.add(r); - } - } - - private Runnable getEvent() { - synchronized (this) { - if(this.mEventQueue.size() > 0) { - return this.mEventQueue.remove(0); - } - - } - return null; - } - - private boolean mDone; - private boolean mPaused; - private boolean mHasSurface; - private int mWidth; - private int mHeight; - private int mRenderMode; - private boolean mRequestRender; - private final Renderer mRenderer; - private final ArrayList mEventQueue = new ArrayList(); - private EglHelper mEglHelper; - private boolean mSizeChanged; - } - - /** - * An EGL helper class. - */ - - class EglHelper { - public EglHelper() { - - } - - /** - * Initialize EGL for a given configuration spec. - * - * @param configSpec - */ - public void start() { - /* - * Get an EGL instance - */ - this.mEgl = (EGL10) EGLContext.getEGL(); - - /* - * Get to the default display. - */ - this.mEglDisplay = this.mEgl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY); - - /* - * We can now initialize EGL for that display - */ - final int[] version = new int[2]; - this.mEgl.eglInitialize(this.mEglDisplay, version); - this.mEglConfig = GLSurfaceView.this.mEGLConfigChooser.chooseConfig(this.mEgl, this.mEglDisplay); - - /* - * Create an OpenGL ES context. This must be done only once, an - * OpenGL context is a somewhat heavy object. - */ - this.mEglContext = this.mEgl.eglCreateContext(this.mEglDisplay, this.mEglConfig, EGL10.EGL_NO_CONTEXT, null); - - this.mEglSurface = null; - } - - /* - * React to the creation of a new surface by creating and returning an - * OpenGL interface that renders to that surface. - */ - public GL createSurface(final SurfaceHolder holder) { - /* - * The window size has changed, so we need to create a new surface. - */ - if(this.mEglSurface != null) { - - /* - * Unbind and destroy the old EGL surface, if there is one. - */ - this.mEgl.eglMakeCurrent(this.mEglDisplay, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_CONTEXT); - this.mEgl.eglDestroySurface(this.mEglDisplay, this.mEglSurface); - } - - /* - * Create an EGL surface we can render into. - */ - this.mEglSurface = this.mEgl.eglCreateWindowSurface(this.mEglDisplay, this.mEglConfig, holder, null); - - /* - * Before we can issue GL commands, we need to make sure the context - * is current and bound to a surface. - */ - this.mEgl.eglMakeCurrent(this.mEglDisplay, this.mEglSurface, this.mEglSurface, this.mEglContext); - - GL gl = this.mEglContext.getGL(); - if(GLSurfaceView.this.mGLWrapper != null) { - gl = GLSurfaceView.this.mGLWrapper.wrap(gl); - } - - /* Debugging disabled */ - /* - * if ((mDebugFlags & (DEBUG_CHECK_GL_ERROR | DEBUG_LOG_GL_CALLS))!= - * 0) { int configFlags = 0; Writer log = null; if ((mDebugFlags & - * DEBUG_CHECK_GL_ERROR) != 0) { configFlags |= - * GLDebugHelper.CONFIG_CHECK_GL_ERROR; } if ((mDebugFlags & - * DEBUG_LOG_GL_CALLS) != 0) { log = new LogWriter(); } gl = - * GLDebugHelper.wrap(gl, configFlags, log); } - */ - return gl; - } - - /** - * Display the current render surface. - * - * @return false if the context has been lost. - */ - public boolean swap() { - this.mEgl.eglSwapBuffers(this.mEglDisplay, this.mEglSurface); - - /* - * Always check for EGL_CONTEXT_LOST, which means the context and - * all associated data were lost (For instance because the device - * went to sleep). We need to sleep until we get a new surface. - */ - return this.mEgl.eglGetError() != EGL11.EGL_CONTEXT_LOST; - } - - public void finish() { - if(this.mEglSurface != null) { - this.mEgl.eglMakeCurrent(this.mEglDisplay, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_CONTEXT); - this.mEgl.eglDestroySurface(this.mEglDisplay, this.mEglSurface); - this.mEglSurface = null; - } - if(this.mEglContext != null) { - this.mEgl.eglDestroyContext(this.mEglDisplay, this.mEglContext); - this.mEglContext = null; - } - if(this.mEglDisplay != null) { - this.mEgl.eglTerminate(this.mEglDisplay); - this.mEglDisplay = null; - } - } - - EGL10 mEgl; - EGLDisplay mEglDisplay; - EGLSurface mEglSurface; - EGLConfig mEglConfig; - EGLContext mEglContext; - } - - /** - * A generic renderer interface. - *

- * The renderer is responsible for making OpenGL calls to render a frame. - *

- * GLSurfaceView clients typically create their own classes that implement - * this interface, and then call {@link GLSurfaceView#setRenderer} to - * register the renderer with the GLSurfaceView. - *

- *

Threading

- * The renderer will be called on a separate thread, so that rendering - * performance is decoupled from the UI thread. Clients typically need to - * communicate with the renderer from the UI thread, because that'MAGIC_CONSTANT where - * input events are received. Clients can communicate using any of the - * standard Java techniques for cross-thread communication, or they can use - * the {@link GLSurfaceView#queueEvent(Runnable)} convenience method. - *

- *

EGL Context Lost

- * There are situations where the EGL rendering context will be lost. This - * typically happens when device wakes up after going to sleep. When the EGL - * context is lost, all OpenGL resources (such as textures) that are - * associated with that context will be automatically deleted. In order to - * keep rendering correctly, a renderer must recreate any lost resources - * that it still needs. The {@link #onSurfaceCreated(GL10, EGLConfig)} - * method is a convenient place to do this. - * - * - * @see #setRenderer(Renderer) - */ - public interface Renderer { - /** - * Called when the surface is created or recreated. - *

- * Called when the rendering thread starts and whenever the EGL context - * is lost. The context will typically be lost when the Android device - * awakes after going to sleep. - *

- * Since this method is called at the beginning of rendering, as well as - * every time the EGL context is lost, this method is a convenient place - * to put code to create resources that need to be created when the - * rendering starts, and that need to be recreated when the EGL context - * is lost. Textures are an example of a resource that you might want to - * create here. - *

- * Note that when the EGL context is lost, all OpenGL resources - * associated with that context will be automatically deleted. You do - * not need to call the corresponding "glDelete" methods such as - * glDeleteTextures to manually delete these lost resources. - *

- * - * @param gl - * the GL interface. Use instanceof to test if - * the interface supports GL11 or higher interfaces. - * @param config - * the EGLConfig of the created surface. Can be used to - * create matching pbuffers. - */ - void onSurfaceCreated(GL10 gl, EGLConfig config); - - /** - * Called when the surface changed size. - *

- * Called after the surface is created and whenever the OpenGL ES - * surface size changes. - *

- * Typically you will set your viewport here. If your camera is fixed - * then you could also set your projection matrix here: - * - *

-		 * void onSurfaceChanged(GL10 gl, int width, int height) {
-		 * 	gl.glViewport(0, 0, width, height);
-		 * 	// for a fixed camera, set the projection too
-		 * 	float ratio = (float) width / height;
-		 * 	gl.glMatrixMode(GL10.GL_PROJECTION);
-		 * 	gl.glLoadIdentity();
-		 * 	gl.glFrustumf(-ratio, ratio, -1, 1, 1, 10);
-		 * }
-		 * 
- * - * @param gl - * the GL interface. Use instanceof to test if - * the interface supports GL11 or higher interfaces. - * @param width - * @param height - */ - void onSurfaceChanged(GL10 gl, int width, int height); - - /** - * Called to draw the current frame. - *

- * This method is responsible for drawing the current frame. - *

- * The implementation of this method typically looks like this: - * - *

-		 * void onDrawFrame(GL10 gl) {
-		 * 	gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
-		 * 	//... other gl calls to render the scene ...
-		 * }
-		 * 
- * - * @param gl - * the GL interface. Use instanceof to test if - * the interface supports GL11 or higher interfaces. - */ - void onDrawFrame(GL10 gl); - } + // =========================================================== + // Constants + // =========================================================== + + /** + * The renderer only renders when the surface is created, or when + * {@link #requestRender} is called. + * + * @see #getRenderMode() + * @see #setRenderMode(int) + */ + public final static int RENDERMODE_WHEN_DIRTY = 0; + /** + * The renderer is called continuously to re-render the scene. + * + * @see #getRenderMode() + * @see #setRenderMode(int) + * @see #requestRender() + */ + public final static int RENDERMODE_CONTINUOUSLY = 1; + + /** + * Check glError() after every GL call and throw an exception if glError + * indicates that an error has occurred. This can be used to help track down + * which OpenGL ES call is causing an error. + * + * @see #getDebugFlags + * @see #setDebugFlags + */ + public final static int DEBUG_CHECK_GL_ERROR = 1; + + /** + * Log GL calls to the system log at "verbose" level with tag + * "GLSurfaceView". + * + * @see #getDebugFlags + * @see #setDebugFlags + */ + public final static int DEBUG_LOG_GL_CALLS = 2; + + private static final Semaphore sEglSemaphore = new Semaphore(1); + + // =========================================================== + // Fields + // =========================================================== + + private GLThread mGLThread; + private EGLConfigChooser mEGLConfigChooser; + private GLWrapper mGLWrapper; + private int mDebugFlags; + private int mRenderMode; + private Renderer mRenderer; + private int mSurfaceWidth; + private int mSurfaceHeight; + private boolean mHasSurface; + + // =========================================================== + // Constructors + // =========================================================== + + /** + * Standard View constructor. In order to render something, you must call + * {@link #setRenderer} to register a renderer. + */ + public GLSurfaceView(final Context context) { + super(context); + this.init(); + } + + /** + * Standard View constructor. In order to render something, you must call + * {@link #setRenderer} to register a renderer. + */ + public GLSurfaceView(final Context context, final AttributeSet attrs) { + super(context, attrs); + this.init(); + } + + private void init() { + // Install a SurfaceHolder.Callback so we get notified when the + // underlying surface is created and destroyed + final SurfaceHolder holder = this.getHolder(); + holder.addCallback(this); + holder.setType(SurfaceHolder.SURFACE_TYPE_GPU); + this.mRenderMode = RENDERMODE_CONTINUOUSLY; + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + /** + * Set the glWrapper. If the glWrapper is not null, its + * {@link GLWrapper#wrap(GL)} method is called whenever a surface is + * created. A GLWrapper can be used to wrap the GL object that'MAGIC_CONSTANT passed to + * the renderer. Wrapping a GL object enables examining and modifying the + * behavior of the GL calls made by the renderer. + *

+ * Wrapping is typically used for debugging purposes. + *

+ * The default value is null. + * + * @param glWrapper + * the new GLWrapper + */ + public void setGLWrapper(final GLWrapper glWrapper) { + this.mGLWrapper = glWrapper; + } + + /** + * Set the debug flags to a new value. The value is constructed by + * OR-together zero or more of the DEBUG_CHECK_* constants. The debug flags + * take effect whenever a surface is created. The default value is zero. + * + * @param debugFlags + * the new debug flags + * @see #DEBUG_CHECK_GL_ERROR + * @see #DEBUG_LOG_GL_CALLS + */ + public void setDebugFlags(final int debugFlags) { + this.mDebugFlags = debugFlags; + } + + /** + * Get the current value of the debug flags. + * + * @return the current value of the debug flags. + */ + public int getDebugFlags() { + return this.mDebugFlags; + } + + /** + * Set the renderer associated with this view. Also starts the thread that + * will call the renderer, which in turn causes the rendering to start. + *

+ * This method should be called once and only once in the life-cycle of a + * GLSurfaceView. + *

+ * The following GLSurfaceView methods can only be called before + * setRenderer is called: + *

    + *
  • {@link #setEGLConfigChooser(boolean)} + *
  • {@link #setEGLConfigChooser(EGLConfigChooser)} + *
  • {@link #setEGLConfigChooser(int, int, int, int, int, int)} + *
+ *

+ * The following GLSurfaceView methods can only be called after + * setRenderer is called: + *

    + *
  • {@link #getRenderMode()} + *
  • {@link #onPause()} + *
  • {@link #onResume()} + *
  • {@link #queueEvent(Runnable)} + *
  • {@link #requestRender()} + *
  • {@link #setRenderMode(int)} + *
+ * + * @param renderer + * the renderer to use to perform OpenGL drawing. + */ + public void setRenderer(final Renderer renderer) { + if(this.mRenderer != null) { + throw new IllegalStateException("setRenderer has already been called for this instance."); + } + + this.mRenderer = renderer; + } + + /** + * Install a custom EGLConfigChooser. + *

+ * If this method is called, it must be called before + * {@link #setRenderer(Renderer)} is called. + *

+ * If no setEGLConfigChooser method is called, then by default the view will + * choose a config as close to 16-bit RGB as possible, with a depth buffer + * as close to 16 bits as possible. + * + * @param configChooser + */ + public void setEGLConfigChooser(final EGLConfigChooser configChooser) { + if(this.mRenderer != null) { + throw new IllegalStateException("setRenderer has already been called for this instance."); + } + this.mEGLConfigChooser = configChooser; + } + + /** + * Install a config chooser which will choose a config as close to 16-bit + * RGB as possible, with or without an optional depth buffer as close to + * 16-bits as possible. + *

+ * If this method is called, it must be called before + * {@link #setRenderer(Renderer)} is called. + *

+ * If no setEGLConfigChooser method is called, then by default the view will + * choose a config as close to 16-bit RGB as possible, with a depth buffer + * as close to 16 bits as possible. + * + * @param needDepth + */ + public void setEGLConfigChooser(final boolean needDepth) { + this.setEGLConfigChooser(new SimpleEGLConfigChooser(needDepth)); + } + + /** + * Install a config chooser which will choose a config with at least the + * specified component sizes, and as close to the specified component sizes + * as possible. + *

+ * If this method is called, it must be called before + * {@link #setRenderer(Renderer)} is called. + *

+ * If no setEGLConfigChooser method is called, then by default the view will + * choose a config as close to 16-bit RGB as possible, with a depth buffer + * as close to 16 bits as possible. + * + */ + public void setEGLConfigChooser(final int redSize, final int greenSize, final int blueSize, final int alphaSize, final int depthSize, final int stencilSize) { + this.setEGLConfigChooser(new ComponentSizeChooser(redSize, greenSize, blueSize, alphaSize, depthSize, stencilSize)); + } + + /** + * Set the rendering mode. When renderMode is RENDERMODE_CONTINUOUSLY, the + * renderer is called repeatedly to re-render the scene. When renderMode is + * RENDERMODE_WHEN_DIRTY, the renderer only rendered when the surface is + * created, or when {@link #requestRender} is called. Defaults to + * RENDERMODE_CONTINUOUSLY. + *

+ * Using RENDERMODE_WHEN_DIRTY can improve battery life and overall system + * performance by allowing the GPU and CPU to idle when the view does not + * need to be updated. + *

+ * This method can only be called after {@link #setRenderer(Renderer)} + * + * @param renderMode + * one of the RENDERMODE_X constants + * @see #RENDERMODE_CONTINUOUSLY + * @see #RENDERMODE_WHEN_DIRTY + */ + public void setRenderMode(final int renderMode) { + this.mRenderMode = renderMode; + if(this.mGLThread != null) { + this.mGLThread.setRenderMode(renderMode); + } + } + + /** + * Get the current rendering mode. May be called from any thread. Must not + * be called before a renderer has been set. + * + * @return the current rendering mode. + * @see #RENDERMODE_CONTINUOUSLY + * @see #RENDERMODE_WHEN_DIRTY + */ + public int getRenderMode() { + return this.mRenderMode; + } + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + /** + * Request that the renderer render a frame. This method is typically used + * when the render mode has been set to {@link #RENDERMODE_WHEN_DIRTY}, so + * that frames are only rendered on demand. May be called from any thread. + * Must be called after onResume() and before onPause(). + */ + public void requestRender() { + this.mGLThread.requestRender(); + } + + /** + * This method is part of the SurfaceHolder.Callback interface, and is not + * normally called or subclassed by clients of GLSurfaceView. + */ + @Override + public void surfaceCreated(final SurfaceHolder holder) { + if(this.mGLThread != null) { + this.mGLThread.surfaceCreated(); + } + this.mHasSurface = true; + } + + /** + * This method is part of the SurfaceHolder.Callback interface, and is not + * normally called or subclassed by clients of GLSurfaceView. + */ + @Override + public void surfaceDestroyed(final SurfaceHolder holder) { + // Surface will be destroyed when we return + if(this.mGLThread != null) { + this.mGLThread.surfaceDestroyed(); + } + this.mHasSurface = false; + } + + /** + * This method is part of the SurfaceHolder.Callback interface, and is not + * normally called or subclassed by clients of GLSurfaceView. + */ + @Override + public void surfaceChanged(final SurfaceHolder holder, final int format, final int w, final int h) { + if(this.mGLThread != null) { + this.mGLThread.onWindowResize(w, h); + } + this.mSurfaceWidth = w; + this.mSurfaceHeight = h; + } + + /** + * Inform the view that the activity is paused. The owner of this view must + * call this method when the activity is paused. Calling this method will + * pause the rendering thread. Must not be called before a renderer has been + * set. + */ + public void onPause() { + this.mGLThread.onPause(); + this.mGLThread.requestExitAndWait(); + this.mGLThread = null; + } + + /** + * Inform the view that the activity is resumed. The owner of this view must + * call this method when the activity is resumed. Calling this method will + * recreate the OpenGL display and resume the rendering thread. Must not be + * called before a renderer has been set. + */ + public void onResume() { + if(this.mEGLConfigChooser == null) { + this.mEGLConfigChooser = new SimpleEGLConfigChooser(true); + } + this.mGLThread = new GLThread(this.mRenderer); + this.mGLThread.start(); + this.mGLThread.setRenderMode(this.mRenderMode); + if(this.mHasSurface) { + this.mGLThread.surfaceCreated(); + } + if(this.mSurfaceWidth > 0 && this.mSurfaceHeight > 0) { + this.mGLThread.onWindowResize(this.mSurfaceWidth, this.mSurfaceHeight); + } + this.mGLThread.onResume(); + } + + /** + * Queue a runnable to be run on the GL rendering thread. This can be used + * to communicate with the Renderer on the rendering thread. Must be called + * after onResume() and before onPause(). + * + * @param r + * the runnable to be run on the GL rendering thread. + */ + public void queueEvent(final Runnable r) { + if(this.mGLThread != null) { + this.mGLThread.queueEvent(r); + } + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== + + /** + * A generic GL Thread. Takes care of initializing EGL and GL. Delegates to + * a Renderer instance to do the actual drawing. Can be configured to render + * continuously or on request. + * + */ + class GLThread extends Thread { + GLThread(final Renderer renderer) { + super(); + this.mDone = false; + this.mWidth = 0; + this.mHeight = 0; + this.mRequestRender = true; + this.mRenderMode = RENDERMODE_CONTINUOUSLY; + this.mRenderer = renderer; + this.mSizeChanged = true; + this.setName("GLThread"); + } + + @Override + public void run() { + /* + * When the android framework launches a second instance of an + * activity, the new instance'MAGIC_CONSTANT onCreate() method may be called + * before the first instance returns from onDestroy(). + * + * This semaphore ensures that only one instance at a time accesses + * EGL. + */ + try { + try { + sEglSemaphore.acquire(); + } catch (final InterruptedException e) { + return; + } + this.guardedRun(); + } catch (final InterruptedException e) { + // fall thru and exit normally + } finally { + sEglSemaphore.release(); + } + } + + private void guardedRun() throws InterruptedException { + this.mEglHelper = new EglHelper(); + this.mEglHelper.start(); + + GL10 gl = null; + boolean tellRendererSurfaceCreated = true; + boolean tellRendererSurfaceChanged = true; + + /* + * This is our main activity thread'MAGIC_CONSTANT loop, we go until asked to + * quit. + */ + while(!this.mDone) { + + /* + * Update the asynchronous state (window size) + */ + int w, h; + boolean changed; + boolean needStart = false; + synchronized (this) { + Runnable r; + while((r = this.getEvent()) != null) { + r.run(); + } + if(this.mPaused) { + this.mEglHelper.finish(); + needStart = true; + } + while(this.needToWait()) { + this.wait(); + } + if(this.mDone) { + break; + } + changed = this.mSizeChanged; + w = this.mWidth; + h = this.mHeight; + this.mSizeChanged = false; + this.mRequestRender = false; + } + if(needStart) { + this.mEglHelper.start(); + tellRendererSurfaceCreated = true; + changed = true; + } + if(changed) { + gl = (GL10) this.mEglHelper.createSurface(GLSurfaceView.this.getHolder()); + tellRendererSurfaceChanged = true; + } + if(tellRendererSurfaceCreated) { + this.mRenderer.onSurfaceCreated(gl, this.mEglHelper.mEglConfig); + tellRendererSurfaceCreated = false; + } + if(tellRendererSurfaceChanged) { + this.mRenderer.onSurfaceChanged(gl, w, h); + tellRendererSurfaceChanged = false; + } + if((w > 0) && (h > 0)) { + /* draw a frame here */ + this.mRenderer.onDrawFrame(gl); + + /* + * Once we're done with GL, we need to call swapBuffers() to + * instruct the system to display the rendered frame + */ + this.mEglHelper.swap(); + } + } + + /* + * clean-up everything... + */ + this.mEglHelper.finish(); + } + + private boolean needToWait() { + if(this.mDone) { + return false; + } + + if(this.mPaused || (!this.mHasSurface)) { + return true; + } + + if((this.mWidth > 0) && (this.mHeight > 0) && (this.mRequestRender || (this.mRenderMode == RENDERMODE_CONTINUOUSLY))) { + return false; + } + + return true; + } + + public void setRenderMode(final int renderMode) { + if(!((RENDERMODE_WHEN_DIRTY <= renderMode) && (renderMode <= RENDERMODE_CONTINUOUSLY))) { + throw new IllegalArgumentException("renderMode"); + } + synchronized (this) { + this.mRenderMode = renderMode; + if(renderMode == RENDERMODE_CONTINUOUSLY) { + this.notify(); + } + } + } + + public int getRenderMode() { + synchronized (this) { + return this.mRenderMode; + } + } + + public void requestRender() { + synchronized (this) { + this.mRequestRender = true; + this.notify(); + } + } + + public void surfaceCreated() { + synchronized (this) { + this.mHasSurface = true; + this.notify(); + } + } + + public void surfaceDestroyed() { + synchronized (this) { + this.mHasSurface = false; + this.notify(); + } + } + + public void onPause() { + synchronized (this) { + this.mPaused = true; + } + } + + public void onResume() { + synchronized (this) { + this.mPaused = false; + this.notify(); + } + } + + public void onWindowResize(final int w, final int h) { + synchronized (this) { + this.mWidth = w; + this.mHeight = h; + this.mSizeChanged = true; + this.notify(); + } + } + + public void requestExitAndWait() { + // don't call this from GLThread thread or it is a guaranteed + // deadlock! + synchronized (this) { + this.mDone = true; + this.notify(); + } + try { + this.join(); + } catch (final InterruptedException ex) { + Thread.currentThread().interrupt(); + } + } + + /** + * Queue an "event" to be run on the GL rendering thread. + * + * @param r + * the runnable to be run on the GL rendering thread. + */ + public void queueEvent(final Runnable r) { + synchronized (this) { + this.mEventQueue.add(r); + } + } + + private Runnable getEvent() { + synchronized (this) { + if(this.mEventQueue.size() > 0) { + return this.mEventQueue.remove(0); + } + + } + return null; + } + + private boolean mDone; + private boolean mPaused; + private boolean mHasSurface; + private int mWidth; + private int mHeight; + private int mRenderMode; + private boolean mRequestRender; + private final Renderer mRenderer; + private final ArrayList mEventQueue = new ArrayList(); + private EglHelper mEglHelper; + private boolean mSizeChanged; + } + + /** + * An EGL helper class. + */ + + class EglHelper { + public EglHelper() { + + } + + /** + * Initialize EGL for a given configuration spec. + * + * @param configSpec + */ + public void start() { + /* + * Get an EGL instance + */ + this.mEgl = (EGL10) EGLContext.getEGL(); + + /* + * Get to the default display. + */ + this.mEglDisplay = this.mEgl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY); + + /* + * We can now initialize EGL for that display + */ + final int[] version = new int[2]; + this.mEgl.eglInitialize(this.mEglDisplay, version); + this.mEglConfig = GLSurfaceView.this.mEGLConfigChooser.chooseConfig(this.mEgl, this.mEglDisplay); + + /* + * Create an OpenGL ES context. This must be done only once, an + * OpenGL context is a somewhat heavy object. + */ + this.mEglContext = this.mEgl.eglCreateContext(this.mEglDisplay, this.mEglConfig, EGL10.EGL_NO_CONTEXT, null); + + this.mEglSurface = null; + } + + /* + * React to the creation of a new surface by creating and returning an + * OpenGL interface that renders to that surface. + */ + public GL createSurface(final SurfaceHolder holder) { + /* + * The window size has changed, so we need to create a new surface. + */ + if(this.mEglSurface != null) { + + /* + * Unbind and destroy the old EGL surface, if there is one. + */ + this.mEgl.eglMakeCurrent(this.mEglDisplay, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_CONTEXT); + this.mEgl.eglDestroySurface(this.mEglDisplay, this.mEglSurface); + } + + /* + * Create an EGL surface we can render into. + */ + this.mEglSurface = this.mEgl.eglCreateWindowSurface(this.mEglDisplay, this.mEglConfig, holder, null); + + /* + * Before we can issue GL commands, we need to make sure the context + * is current and bound to a surface. + */ + this.mEgl.eglMakeCurrent(this.mEglDisplay, this.mEglSurface, this.mEglSurface, this.mEglContext); + + GL gl = this.mEglContext.getGL(); + if(GLSurfaceView.this.mGLWrapper != null) { + gl = GLSurfaceView.this.mGLWrapper.wrap(gl); + } + + /* Debugging disabled */ + /* + * if ((mDebugFlags & (DEBUG_CHECK_GL_ERROR | DEBUG_LOG_GL_CALLS))!= + * 0) { int configFlags = 0; Writer log = null; if ((mDebugFlags & + * DEBUG_CHECK_GL_ERROR) != 0) { configFlags |= + * GLDebugHelper.CONFIG_CHECK_GL_ERROR; } if ((mDebugFlags & + * DEBUG_LOG_GL_CALLS) != 0) { log = new LogWriter(); } gl = + * GLDebugHelper.wrap(gl, configFlags, log); } + */ + return gl; + } + + /** + * Display the current render surface. + * + * @return false if the context has been lost. + */ + public boolean swap() { + this.mEgl.eglSwapBuffers(this.mEglDisplay, this.mEglSurface); + + /* + * Always check for EGL_CONTEXT_LOST, which means the context and + * all associated data were lost (For instance because the device + * went to sleep). We need to sleep until we get a new surface. + */ + return this.mEgl.eglGetError() != EGL11.EGL_CONTEXT_LOST; + } + + public void finish() { + if(this.mEglSurface != null) { + this.mEgl.eglMakeCurrent(this.mEglDisplay, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_CONTEXT); + this.mEgl.eglDestroySurface(this.mEglDisplay, this.mEglSurface); + this.mEglSurface = null; + } + if(this.mEglContext != null) { + this.mEgl.eglDestroyContext(this.mEglDisplay, this.mEglContext); + this.mEglContext = null; + } + if(this.mEglDisplay != null) { + this.mEgl.eglTerminate(this.mEglDisplay); + this.mEglDisplay = null; + } + } + + EGL10 mEgl; + EGLDisplay mEglDisplay; + EGLSurface mEglSurface; + EGLConfig mEglConfig; + EGLContext mEglContext; + } + + /** + * A generic renderer interface. + *

+ * The renderer is responsible for making OpenGL calls to render a frame. + *

+ * GLSurfaceView clients typically create their own classes that implement + * this interface, and then call {@link GLSurfaceView#setRenderer} to + * register the renderer with the GLSurfaceView. + *

+ *

Threading

+ * The renderer will be called on a separate thread, so that rendering + * performance is decoupled from the UI thread. Clients typically need to + * communicate with the renderer from the UI thread, because that'MAGIC_CONSTANT where + * input events are received. Clients can communicate using any of the + * standard Java techniques for cross-thread communication, or they can use + * the {@link GLSurfaceView#queueEvent(Runnable)} convenience method. + *

+ *

EGL Context Lost

+ * There are situations where the EGL rendering context will be lost. This + * typically happens when device wakes up after going to sleep. When the EGL + * context is lost, all OpenGL resources (such as textures) that are + * associated with that context will be automatically deleted. In order to + * keep rendering correctly, a renderer must recreate any lost resources + * that it still needs. The {@link #onSurfaceCreated(GL10, EGLConfig)} + * method is a convenient place to do this. + * + * + * @see #setRenderer(Renderer) + */ + public interface Renderer { + /** + * Called when the surface is created or recreated. + *

+ * Called when the rendering thread starts and whenever the EGL context + * is lost. The context will typically be lost when the Android device + * awakes after going to sleep. + *

+ * Since this method is called at the beginning of rendering, as well as + * every time the EGL context is lost, this method is a convenient place + * to put code to create resources that need to be created when the + * rendering starts, and that need to be recreated when the EGL context + * is lost. Textures are an example of a resource that you might want to + * create here. + *

+ * Note that when the EGL context is lost, all OpenGL resources + * associated with that context will be automatically deleted. You do + * not need to call the corresponding "glDelete" methods such as + * glDeleteTextures to manually delete these lost resources. + *

+ * + * @param gl + * the GL interface. Use instanceof to test if + * the interface supports GL11 or higher interfaces. + * @param config + * the EGLConfig of the created surface. Can be used to + * create matching pbuffers. + */ + void onSurfaceCreated(GL10 gl, EGLConfig config); + + /** + * Called when the surface changed size. + *

+ * Called after the surface is created and whenever the OpenGL ES + * surface size changes. + *

+ * Typically you will set your viewport here. If your camera is fixed + * then you could also set your projection matrix here: + * + *

+         * void onSurfaceChanged(GL10 gl, int width, int height) {
+         *     gl.glViewport(0, 0, width, height);
+         *     // for a fixed camera, set the projection too
+         *     float ratio = (float) width / height;
+         *     gl.glMatrixMode(GL10.GL_PROJECTION);
+         *     gl.glLoadIdentity();
+         *     gl.glFrustumf(-ratio, ratio, -1, 1, 1, 10);
+         * }
+         * 
+ * + * @param gl + * the GL interface. Use instanceof to test if + * the interface supports GL11 or higher interfaces. + * @param width + * @param height + */ + void onSurfaceChanged(GL10 gl, int width, int height); + + /** + * Called to draw the current frame. + *

+ * This method is responsible for drawing the current frame. + *

+ * The implementation of this method typically looks like this: + * + *

+         * void onDrawFrame(GL10 gl) {
+         *     gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
+         *     //... other gl calls to render the scene ...
+         * }
+         * 
+ * + * @param gl + * the GL interface. Use instanceof to test if + * the interface supports GL11 or higher interfaces. + */ + void onDrawFrame(GL10 gl); + } } diff --git a/AndEngine/src/org/anddev/andengine/opengl/view/GLWrapper.java b/AndEngine/src/org/anddev/andengine/opengl/view/GLWrapper.java index b340c9e1..de8a5028 100644 --- a/AndEngine/src/org/anddev/andengine/opengl/view/GLWrapper.java +++ b/AndEngine/src/org/anddev/andengine/opengl/view/GLWrapper.java @@ -31,20 +31,20 @@ * @since 20:53:38 - 28.06.2010 */ public interface GLWrapper { - // =========================================================== - // Final Fields - // =========================================================== + // =========================================================== + // Final Fields + // =========================================================== - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - /** - * Wraps a gl interface in another gl interface. - * - * @param pGL a GL interface that is to be wrapped. - * @return either the input argument or another GL object that wraps the - * input argument. - */ - public GL wrap(final GL pGL); -} \ No newline at end of file + /** + * Wraps a gl interface in another gl interface. + * + * @param pGL a GL interface that is to be wrapped. + * @return either the input argument or another GL object that wraps the + * input argument. + */ + public GL wrap(final GL pGL); +} diff --git a/AndEngine/src/org/anddev/andengine/opengl/view/LogWriter.java b/AndEngine/src/org/anddev/andengine/opengl/view/LogWriter.java index 59a8dffe..69eaa631 100644 --- a/AndEngine/src/org/anddev/andengine/opengl/view/LogWriter.java +++ b/AndEngine/src/org/anddev/andengine/opengl/view/LogWriter.java @@ -15,62 +15,62 @@ * @since 20:42:02 - 28.06.2010 */ class LogWriter extends Writer { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - private final StringBuilder mBuilder = new StringBuilder(); + private final StringBuilder mBuilder = new StringBuilder(); - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - @Override - public void close() { - this.flushBuilder(); - } + @Override + public void close() { + this.flushBuilder(); + } - @Override - public void flush() { - this.flushBuilder(); - } + @Override + public void flush() { + this.flushBuilder(); + } - @Override - public void write(final char[] buf, final int offset, final int count) { - for(int i = 0; i < count; i++) { - final char c = buf[offset + i]; - if(c == '\n') { - this.flushBuilder(); - } else { - this.mBuilder.append(c); - } - } - } + @Override + public void write(final char[] buf, final int offset, final int count) { + for(int i = 0; i < count; i++) { + final char c = buf[offset + i]; + if(c == '\n') { + this.flushBuilder(); + } else { + this.mBuilder.append(c); + } + } + } - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - private void flushBuilder() { - if(this.mBuilder.length() > 0) { - Log.v("GLSurfaceView", this.mBuilder.toString()); - this.mBuilder.delete(0, this.mBuilder.length()); - } - } + private void flushBuilder() { + if(this.mBuilder.length() > 0) { + Log.v("GLSurfaceView", this.mBuilder.toString()); + this.mBuilder.delete(0, this.mBuilder.length()); + } + } - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== -} \ No newline at end of file + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== +} diff --git a/AndEngine/src/org/anddev/andengine/opengl/view/RenderSurfaceView.java b/AndEngine/src/org/anddev/andengine/opengl/view/RenderSurfaceView.java index b3f4c0e2..dd4abe8a 100644 --- a/AndEngine/src/org/anddev/andengine/opengl/view/RenderSurfaceView.java +++ b/AndEngine/src/org/anddev/andengine/opengl/view/RenderSurfaceView.java @@ -18,158 +18,158 @@ * @since 11:57:29 - 08.03.2010 */ public class RenderSurfaceView extends GLSurfaceView { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - private Renderer mRenderer; - - // =========================================================== - // Constructors - // =========================================================== - - public RenderSurfaceView(final Context pContext) { - super(pContext); - } - - public RenderSurfaceView(final Context pContext, final AttributeSet pAttrs) { - super(pContext, pAttrs); - } - - public void setRenderer(final Engine pEngine) { - this.setOnTouchListener(pEngine); - this.mRenderer = new Renderer(pEngine); - this.setRenderer(this.mRenderer); - } - - /** - * @see android.view.View#measure(int, int) - */ - @Override - protected void onMeasure(final int pWidthMeasureSpec, final int pHeightMeasureSpec) { - if (this.mRenderer.mEngine.getEngineOptions().getResolutionPolicy() == null) { - super.onMeasure(pWidthMeasureSpec, pHeightMeasureSpec); - } else { - this.mRenderer.mEngine.getEngineOptions().getResolutionPolicy().onMeasure(this, pWidthMeasureSpec, pHeightMeasureSpec); - } - } - - public void setMeasuredDimensionProxy(final int pMeasuredWidth, final int pMeasuredHeight) { - this.setMeasuredDimension(pMeasuredWidth, pMeasuredHeight); - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== - - /** - * (c) 2010 Nicolas Gramlich + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + private Renderer mRenderer; + + // =========================================================== + // Constructors + // =========================================================== + + public RenderSurfaceView(final Context pContext) { + super(pContext); + } + + public RenderSurfaceView(final Context pContext, final AttributeSet pAttrs) { + super(pContext, pAttrs); + } + + public void setRenderer(final Engine pEngine) { + this.setOnTouchListener(pEngine); + this.mRenderer = new Renderer(pEngine); + this.setRenderer(this.mRenderer); + } + + /** + * @see android.view.View#measure(int, int) + */ + @Override + protected void onMeasure(final int pWidthMeasureSpec, final int pHeightMeasureSpec) { + if (this.mRenderer.mEngine.getEngineOptions().getResolutionPolicy() == null) { + super.onMeasure(pWidthMeasureSpec, pHeightMeasureSpec); + } else { + this.mRenderer.mEngine.getEngineOptions().getResolutionPolicy().onMeasure(this, pWidthMeasureSpec, pHeightMeasureSpec); + } + } + + public void setMeasuredDimensionProxy(final int pMeasuredWidth, final int pMeasuredHeight) { + this.setMeasuredDimension(pMeasuredWidth, pMeasuredHeight); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== + + /** + * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich - * @since 11:45:59 - 08.03.2010 - */ - public static class Renderer implements GLSurfaceView.Renderer { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - private final Engine mEngine; - - // =========================================================== - // Constructors - // =========================================================== - - public Renderer(final Engine pEngine) { - this.mEngine = pEngine; - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - public void onSurfaceChanged(final GL10 pGL, final int pWidth, final int pHeight) { - //Debug.d( - //System.out.println( - //"onSurfaceChanged: pWidth=" + pWidth + " pHeight=" + pHeight); - this.mEngine.setSurfaceSize(pWidth, pHeight); - pGL.glViewport(0, 0, pWidth, pHeight); - pGL.glLoadIdentity(); - } - - @Override - public void onSurfaceCreated(final GL10 pGL, final EGLConfig pConfig) { - Debug.d("onSurfaceCreated"); - GLHelper.reset(pGL); - - GLHelper.setPerspectiveCorrectionHintFastest(pGL); - // pGL.glEnable(GL10.GL_POLYGON_SMOOTH); - // pGL.glHint(GL10.GL_POLYGON_SMOOTH_HINT, GL10.GL_NICEST); - // pGL.glEnable(GL10.GL_LINE_SMOOTH); - // pGL.glHint(GL10.GL_LINE_SMOOTH_HINT, GL10.GL_NICEST); - // pGL.glEnable(GL10.GL_POINT_SMOOTH); - // pGL.glHint(GL10.GL_POINT_SMOOTH_HINT, GL10.GL_NICEST); - - GLHelper.setShadeModelFlat(pGL); - - GLHelper.disableLightning(pGL); - GLHelper.disableDither(pGL); - GLHelper.disableDepthTest(pGL); - GLHelper.disableMultisample(pGL); - - GLHelper.enableBlend(pGL); - GLHelper.enableTextures(pGL); - GLHelper.enableTexCoordArray(pGL); - GLHelper.enableVertexArray(pGL); - - GLHelper.enableCulling(pGL); - pGL.glFrontFace(GL10.GL_CCW); - pGL.glCullFace(GL10.GL_BACK); - - GLHelper.enableExtensions(pGL, this.mEngine.getEngineOptions().getRenderOptions()); - } - - @Override - public void onDrawFrame(final GL10 pGL) { - try { - pGL.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT); - this.mEngine.onDrawFrame(pGL); - } catch (final InterruptedException e) { - Debug.e("GLThread interrupted!", e); - } - } - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== - } + * @since 11:45:59 - 08.03.2010 + */ + public static class Renderer implements GLSurfaceView.Renderer { + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + private final Engine mEngine; + + // =========================================================== + // Constructors + // =========================================================== + + public Renderer(final Engine pEngine) { + this.mEngine = pEngine; + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + public void onSurfaceChanged(final GL10 pGL, final int pWidth, final int pHeight) { + //Debug.d( + //System.out.println( + //"onSurfaceChanged: pWidth=" + pWidth + " pHeight=" + pHeight); + this.mEngine.setSurfaceSize(pWidth, pHeight); + pGL.glViewport(0, 0, pWidth, pHeight); + pGL.glLoadIdentity(); + } + + @Override + public void onSurfaceCreated(final GL10 pGL, final EGLConfig pConfig) { + Debug.d("onSurfaceCreated"); + GLHelper.reset(pGL); + + GLHelper.setPerspectiveCorrectionHintFastest(pGL); + // pGL.glEnable(GL10.GL_POLYGON_SMOOTH); + // pGL.glHint(GL10.GL_POLYGON_SMOOTH_HINT, GL10.GL_NICEST); + // pGL.glEnable(GL10.GL_LINE_SMOOTH); + // pGL.glHint(GL10.GL_LINE_SMOOTH_HINT, GL10.GL_NICEST); + // pGL.glEnable(GL10.GL_POINT_SMOOTH); + // pGL.glHint(GL10.GL_POINT_SMOOTH_HINT, GL10.GL_NICEST); + + GLHelper.setShadeModelFlat(pGL); + + GLHelper.disableLightning(pGL); + GLHelper.disableDither(pGL); + GLHelper.disableDepthTest(pGL); + GLHelper.disableMultisample(pGL); + + GLHelper.enableBlend(pGL); + GLHelper.enableTextures(pGL); + GLHelper.enableTexCoordArray(pGL); + GLHelper.enableVertexArray(pGL); + + GLHelper.enableCulling(pGL); + pGL.glFrontFace(GL10.GL_CCW); + pGL.glCullFace(GL10.GL_BACK); + + GLHelper.enableExtensions(pGL, this.mEngine.getEngineOptions().getRenderOptions()); + } + + @Override + public void onDrawFrame(final GL10 pGL) { + try { + pGL.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT); + this.mEngine.onDrawFrame(pGL); + } catch (final InterruptedException e) { + Debug.e("GLThread interrupted!", e); + } + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== + } } diff --git a/AndEngine/src/org/anddev/andengine/opengl/view/SimpleEGLConfigChooser.java b/AndEngine/src/org/anddev/andengine/opengl/view/SimpleEGLConfigChooser.java index 7845feeb..b7d22d5c 100644 --- a/AndEngine/src/org/anddev/andengine/opengl/view/SimpleEGLConfigChooser.java +++ b/AndEngine/src/org/anddev/andengine/opengl/view/SimpleEGLConfigChooser.java @@ -12,40 +12,40 @@ * @since 20:53:29 - 28.06.2010 */ class SimpleEGLConfigChooser extends ComponentSizeChooser { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - // =========================================================== - // Constructors - // =========================================================== - - public SimpleEGLConfigChooser(final boolean pWithDepthBuffer) { - super(4, 4, 4, 0, pWithDepthBuffer ? 16 : 0, 0); - // Adjust target values. This way we'll accept a 4444 or - // 555 buffer if there'MAGIC_CONSTANT no 565 buffer available. - this.mRedSize = 5; - this.mGreenSize = 6; - this.mBlueSize = 5; - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== -} \ No newline at end of file + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + // =========================================================== + // Constructors + // =========================================================== + + public SimpleEGLConfigChooser(final boolean pWithDepthBuffer) { + super(4, 4, 4, 0, pWithDepthBuffer ? 16 : 0, 0); + // Adjust target values. This way we'll accept a 4444 or + // 555 buffer if there'MAGIC_CONSTANT no 565 buffer available. + this.mRedSize = 5; + this.mGreenSize = 6; + this.mBlueSize = 5; + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== +} diff --git a/AndEngine/src/org/anddev/andengine/sensor/BaseSensorData.java b/AndEngine/src/org/anddev/andengine/sensor/BaseSensorData.java index 481c93d5..c28dfa49 100644 --- a/AndEngine/src/org/anddev/andengine/sensor/BaseSensorData.java +++ b/AndEngine/src/org/anddev/andengine/sensor/BaseSensorData.java @@ -10,62 +10,62 @@ * @since 16:50:44 - 10.03.2010 */ public class BaseSensorData { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - protected final float[] mValues; - protected int mAccuracy; - protected int mDisplayRotation; + protected final float[] mValues; + protected int mAccuracy; + protected int mDisplayRotation; - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - public BaseSensorData(final int pValueCount, int pDisplayRotation) { - this.mValues = new float[pValueCount]; + public BaseSensorData(final int pValueCount, int pDisplayRotation) { + this.mValues = new float[pValueCount]; - this.mDisplayRotation = pDisplayRotation; - } + this.mDisplayRotation = pDisplayRotation; + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - public float[] getValues() { - return this.mValues; - } + public float[] getValues() { + return this.mValues; + } - public void setValues(final float[] pValues) { - System.arraycopy(pValues, 0, this.mValues, 0, pValues.length); - } + public void setValues(final float[] pValues) { + System.arraycopy(pValues, 0, this.mValues, 0, pValues.length); + } - public void setAccuracy(final int pAccuracy) { - this.mAccuracy = pAccuracy; - } + public void setAccuracy(final int pAccuracy) { + this.mAccuracy = pAccuracy; + } - public int getAccuracy() { - return this.mAccuracy; - } + public int getAccuracy() { + return this.mAccuracy; + } - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - @Override - public String toString() { - return "Values: " + Arrays.toString(this.mValues); - } + @Override + public String toString() { + return "Values: " + Arrays.toString(this.mValues); + } - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/sensor/SensorDelay.java b/AndEngine/src/org/anddev/andengine/sensor/SensorDelay.java index 36d1a2ad..a2e84ce2 100644 --- a/AndEngine/src/org/anddev/andengine/sensor/SensorDelay.java +++ b/AndEngine/src/org/anddev/andengine/sensor/SensorDelay.java @@ -11,50 +11,50 @@ * @since 11:14:38 - 31.10.2010 */ public enum SensorDelay { - // =========================================================== - // Elements - // =========================================================== + // =========================================================== + // Elements + // =========================================================== - NORMAL(SensorManager.SENSOR_DELAY_NORMAL), - UI(SensorManager.SENSOR_DELAY_UI), - GAME(SensorManager.SENSOR_DELAY_GAME), - FASTEST(SensorManager.SENSOR_DELAY_FASTEST); + NORMAL(SensorManager.SENSOR_DELAY_NORMAL), + UI(SensorManager.SENSOR_DELAY_UI), + GAME(SensorManager.SENSOR_DELAY_GAME), + FASTEST(SensorManager.SENSOR_DELAY_FASTEST); - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - private final int mDelay; + private final int mDelay; - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - private SensorDelay(final int pDelay) { - this.mDelay = pDelay; - } + private SensorDelay(final int pDelay) { + this.mDelay = pDelay; + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - public int getDelay() { - return this.mDelay; - } + public int getDelay() { + return this.mDelay; + } - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/sensor/accelerometer/AccelerometerData.java b/AndEngine/src/org/anddev/andengine/sensor/accelerometer/AccelerometerData.java index 6bf10393..d4f67126 100644 --- a/AndEngine/src/org/anddev/andengine/sensor/accelerometer/AccelerometerData.java +++ b/AndEngine/src/org/anddev/andengine/sensor/accelerometer/AccelerometerData.java @@ -15,127 +15,127 @@ * @since 16:50:44 - 10.03.2010 */ public class AccelerometerData extends BaseSensorData { - // =========================================================== - // Constants - // =========================================================== - - private static final IAxisSwap[] AXISSWAPS = new IAxisSwap[4]; - - static { - AXISSWAPS[Surface.ROTATION_0] = new IAxisSwap() { - @Override - public void swapAxis(final float[] pValues) { - final float x = -pValues[SensorManager.DATA_X]; - final float y = pValues[SensorManager.DATA_Y]; - pValues[SensorManager.DATA_X] = x; - pValues[SensorManager.DATA_Y] = y; - } - }; - - AXISSWAPS[Surface.ROTATION_90] = new IAxisSwap() { - @Override - public void swapAxis(final float[] pValues) { - final float x = pValues[SensorManager.DATA_Y]; - final float y = pValues[SensorManager.DATA_X]; - pValues[SensorManager.DATA_X] = x; - pValues[SensorManager.DATA_Y] = y; - } - }; - - AXISSWAPS[Surface.ROTATION_180] = new IAxisSwap() { - @Override - public void swapAxis(final float[] pValues) { - final float x = pValues[SensorManager.DATA_X]; - final float y = -pValues[SensorManager.DATA_Y]; - pValues[SensorManager.DATA_X] = x; - pValues[SensorManager.DATA_Y] = y; - } - }; - - AXISSWAPS[Surface.ROTATION_270] = new IAxisSwap() { - @Override - public void swapAxis(final float[] pValues) { - final float x = -pValues[SensorManager.DATA_Y]; - final float y = -pValues[SensorManager.DATA_X]; - pValues[SensorManager.DATA_X] = x; - pValues[SensorManager.DATA_Y] = y; - } - }; - } - - // =========================================================== - // Fields - // =========================================================== - - // =========================================================== - // Constructors - // =========================================================== - - public AccelerometerData(final int pDisplayOrientation) { - super(3, pDisplayOrientation); - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - public float getX() { - return this.mValues[SensorManager.DATA_X]; - } - - public float getY() { - return this.mValues[SensorManager.DATA_Y]; - } - - public float getZ() { - return this.mValues[SensorManager.DATA_Z]; - } - - public void setX(final float pX) { - this.mValues[SensorManager.DATA_X] = pX; - } - - public void setY(final float pY) { - this.mValues[SensorManager.DATA_Y] = pY; - } - - public void setZ(final float pZ) { - this.mValues[SensorManager.DATA_Z] = pZ; - } - - @Override - public void setValues(final float[] pValues) { - super.setValues(pValues); - - AccelerometerData.AXISSWAPS[this.mDisplayRotation].swapAxis(this.mValues); - } - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - public String toString() { - return "Accelerometer: " + Arrays.toString(this.mValues); - } - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== - - private static interface IAxisSwap { - // =========================================================== - // Final Fields - // =========================================================== - - // =========================================================== - // Methods - // =========================================================== - - public void swapAxis(final float[] pValues); - } + // =========================================================== + // Constants + // =========================================================== + + private static final IAxisSwap[] AXISSWAPS = new IAxisSwap[4]; + + static { + AXISSWAPS[Surface.ROTATION_0] = new IAxisSwap() { + @Override + public void swapAxis(final float[] pValues) { + final float x = -pValues[SensorManager.DATA_X]; + final float y = pValues[SensorManager.DATA_Y]; + pValues[SensorManager.DATA_X] = x; + pValues[SensorManager.DATA_Y] = y; + } + }; + + AXISSWAPS[Surface.ROTATION_90] = new IAxisSwap() { + @Override + public void swapAxis(final float[] pValues) { + final float x = pValues[SensorManager.DATA_Y]; + final float y = pValues[SensorManager.DATA_X]; + pValues[SensorManager.DATA_X] = x; + pValues[SensorManager.DATA_Y] = y; + } + }; + + AXISSWAPS[Surface.ROTATION_180] = new IAxisSwap() { + @Override + public void swapAxis(final float[] pValues) { + final float x = pValues[SensorManager.DATA_X]; + final float y = -pValues[SensorManager.DATA_Y]; + pValues[SensorManager.DATA_X] = x; + pValues[SensorManager.DATA_Y] = y; + } + }; + + AXISSWAPS[Surface.ROTATION_270] = new IAxisSwap() { + @Override + public void swapAxis(final float[] pValues) { + final float x = -pValues[SensorManager.DATA_Y]; + final float y = -pValues[SensorManager.DATA_X]; + pValues[SensorManager.DATA_X] = x; + pValues[SensorManager.DATA_Y] = y; + } + }; + } + + // =========================================================== + // Fields + // =========================================================== + + // =========================================================== + // Constructors + // =========================================================== + + public AccelerometerData(final int pDisplayOrientation) { + super(3, pDisplayOrientation); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + public float getX() { + return this.mValues[SensorManager.DATA_X]; + } + + public float getY() { + return this.mValues[SensorManager.DATA_Y]; + } + + public float getZ() { + return this.mValues[SensorManager.DATA_Z]; + } + + public void setX(final float pX) { + this.mValues[SensorManager.DATA_X] = pX; + } + + public void setY(final float pY) { + this.mValues[SensorManager.DATA_Y] = pY; + } + + public void setZ(final float pZ) { + this.mValues[SensorManager.DATA_Z] = pZ; + } + + @Override + public void setValues(final float[] pValues) { + super.setValues(pValues); + + AccelerometerData.AXISSWAPS[this.mDisplayRotation].swapAxis(this.mValues); + } + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + public String toString() { + return "Accelerometer: " + Arrays.toString(this.mValues); + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== + + private static interface IAxisSwap { + // =========================================================== + // Final Fields + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + public void swapAxis(final float[] pValues); + } } diff --git a/AndEngine/src/org/anddev/andengine/sensor/accelerometer/AccelerometerSensorOptions.java b/AndEngine/src/org/anddev/andengine/sensor/accelerometer/AccelerometerSensorOptions.java index faf0f7a8..57018937 100644 --- a/AndEngine/src/org/anddev/andengine/sensor/accelerometer/AccelerometerSensorOptions.java +++ b/AndEngine/src/org/anddev/andengine/sensor/accelerometer/AccelerometerSensorOptions.java @@ -10,41 +10,41 @@ * @since 11:10:34 - 31.10.2010 */ public class AccelerometerSensorOptions { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - final SensorDelay mSensorDelay; + final SensorDelay mSensorDelay; - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - public AccelerometerSensorOptions(final SensorDelay pSensorDelay) { - this.mSensorDelay = pSensorDelay; - } + public AccelerometerSensorOptions(final SensorDelay pSensorDelay) { + this.mSensorDelay = pSensorDelay; + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - public SensorDelay getSensorDelay() { - return this.mSensorDelay; - } + public SensorDelay getSensorDelay() { + return this.mSensorDelay; + } - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/sensor/accelerometer/IAccelerometerListener.java b/AndEngine/src/org/anddev/andengine/sensor/accelerometer/IAccelerometerListener.java index 229623fb..6a9c3146 100644 --- a/AndEngine/src/org/anddev/andengine/sensor/accelerometer/IAccelerometerListener.java +++ b/AndEngine/src/org/anddev/andengine/sensor/accelerometer/IAccelerometerListener.java @@ -8,13 +8,13 @@ * @since 16:58:38 - 10.03.2010 */ public interface IAccelerometerListener { - // =========================================================== - // Final Fields - // =========================================================== + // =========================================================== + // Final Fields + // =========================================================== - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - public void onAccelerometerChanged(final AccelerometerData pAccelerometerData); + public void onAccelerometerChanged(final AccelerometerData pAccelerometerData); } diff --git a/AndEngine/src/org/anddev/andengine/sensor/location/ILocationListener.java b/AndEngine/src/org/anddev/andengine/sensor/location/ILocationListener.java index cd6726da..2477a76e 100644 --- a/AndEngine/src/org/anddev/andengine/sensor/location/ILocationListener.java +++ b/AndEngine/src/org/anddev/andengine/sensor/location/ILocationListener.java @@ -12,33 +12,33 @@ * @since 10:39:23 - 31.10.2010 */ public interface ILocationListener { - // =========================================================== - // Final Fields - // =========================================================== - - // =========================================================== - // Methods - // =========================================================== - - /** - * @see {@link LocationListener#onProviderEnabled(String)} - */ - public void onLocationProviderEnabled(); - - /** - * @see {@link LocationListener#onLocationChanged(Location)} - */ - public void onLocationChanged(final Location pLocation); - - public void onLocationLost(); - - /** - * @see {@link LocationListener#onProviderDisabled(String)} - */ - public void onLocationProviderDisabled(); - - /** - * @see {@link LocationListener#onStatusChanged(String, int, android.os.Bundle)} - */ - public void onLocationProviderStatusChanged(final LocationProviderStatus pLocationProviderStatus, final Bundle pBundle); + // =========================================================== + // Final Fields + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + /** + * @see {@link LocationListener#onProviderEnabled(String)} + */ + public void onLocationProviderEnabled(); + + /** + * @see {@link LocationListener#onLocationChanged(Location)} + */ + public void onLocationChanged(final Location pLocation); + + public void onLocationLost(); + + /** + * @see {@link LocationListener#onProviderDisabled(String)} + */ + public void onLocationProviderDisabled(); + + /** + * @see {@link LocationListener#onStatusChanged(String, int, android.os.Bundle)} + */ + public void onLocationProviderStatusChanged(final LocationProviderStatus pLocationProviderStatus, final Bundle pBundle); } diff --git a/AndEngine/src/org/anddev/andengine/sensor/location/LocationProviderStatus.java b/AndEngine/src/org/anddev/andengine/sensor/location/LocationProviderStatus.java index eeb8d4fe..8f5502fe 100644 --- a/AndEngine/src/org/anddev/andengine/sensor/location/LocationProviderStatus.java +++ b/AndEngine/src/org/anddev/andengine/sensor/location/LocationProviderStatus.java @@ -8,39 +8,39 @@ * @since 10:55:57 - 31.10.2010 */ public enum LocationProviderStatus { - // =========================================================== - // Elements - // =========================================================== + // =========================================================== + // Elements + // =========================================================== - AVAILABLE, - OUT_OF_SERVICE, - TEMPORARILY_UNAVAILABLE; + AVAILABLE, + OUT_OF_SERVICE, + TEMPORARILY_UNAVAILABLE; - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods from SuperClass/Interfaces + // =========================================================== - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/sensor/location/LocationSensorOptions.java b/AndEngine/src/org/anddev/andengine/sensor/location/LocationSensorOptions.java index 6c29db38..2e258e6c 100644 --- a/AndEngine/src/org/anddev/andengine/sensor/location/LocationSensorOptions.java +++ b/AndEngine/src/org/anddev/andengine/sensor/location/LocationSensorOptions.java @@ -12,102 +12,102 @@ * @since 11:02:12 - 31.10.2010 */ public class LocationSensorOptions extends Criteria { - // =========================================================== - // Constants - // =========================================================== - - private static final long MINIMUMTRIGGERTIME_DEFAULT = 1 * TimeConstants.MILLISECONDSPERSECOND; - private static final long MINIMUMTRIGGERDISTANCE_DEFAULT = 10; - - // =========================================================== - // Fields - // =========================================================== - - private boolean mEnabledOnly = true; - - private long mMinimumTriggerTime = MINIMUMTRIGGERTIME_DEFAULT; - private long mMinimumTriggerDistance = MINIMUMTRIGGERDISTANCE_DEFAULT; - - // =========================================================== - // Constructors - // =========================================================== - - /** - * @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)}. - */ - public LocationSensorOptions() { - - } - - /** - * @param pAccuracy - * @param pAltitudeRequired - * @param pBearingRequired - * @param pCostAllowed - * @param pPowerRequirement - * @param pSpeedRequired - * @param pEnabledOnly - * @param pMinimumTriggerTime - * @param pMinimumTriggerDistance - */ - public LocationSensorOptions(final int pAccuracy, final boolean pAltitudeRequired, final boolean pBearingRequired, final boolean pCostAllowed, final int pPowerRequirement, final boolean pSpeedRequired, final boolean pEnabledOnly, final long pMinimumTriggerTime, final long pMinimumTriggerDistance) { - this.mEnabledOnly = pEnabledOnly; - this.mMinimumTriggerTime = pMinimumTriggerTime; - this.mMinimumTriggerDistance = pMinimumTriggerDistance; - - this.setAccuracy(pAccuracy); - this.setAltitudeRequired(pAltitudeRequired); - this.setBearingRequired(pBearingRequired); - this.setCostAllowed(pCostAllowed); - this.setPowerRequirement(pPowerRequirement); - this.setSpeedRequired(pSpeedRequired); - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - public void setEnabledOnly(final boolean pEnabledOnly) { - this.mEnabledOnly = pEnabledOnly; - } - - public boolean isEnabledOnly() { - return this.mEnabledOnly; - } - - public long getMinimumTriggerTime() { - return this.mMinimumTriggerTime; - } - - public void setMinimumTriggerTime(final long pMinimumTriggerTime) { - this.mMinimumTriggerTime = pMinimumTriggerTime; - } - - public long getMinimumTriggerDistance() { - return this.mMinimumTriggerDistance; - } - - public void setMinimumTriggerDistance(final long pMinimumTriggerDistance) { - this.mMinimumTriggerDistance = pMinimumTriggerDistance; - } - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + private static final long MINIMUMTRIGGERTIME_DEFAULT = 1 * TimeConstants.MILLISECONDSPERSECOND; + private static final long MINIMUMTRIGGERDISTANCE_DEFAULT = 10; + + // =========================================================== + // Fields + // =========================================================== + + private boolean mEnabledOnly = true; + + private long mMinimumTriggerTime = MINIMUMTRIGGERTIME_DEFAULT; + private long mMinimumTriggerDistance = MINIMUMTRIGGERDISTANCE_DEFAULT; + + // =========================================================== + // Constructors + // =========================================================== + + /** + * @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)}. + */ + public LocationSensorOptions() { + + } + + /** + * @param pAccuracy + * @param pAltitudeRequired + * @param pBearingRequired + * @param pCostAllowed + * @param pPowerRequirement + * @param pSpeedRequired + * @param pEnabledOnly + * @param pMinimumTriggerTime + * @param pMinimumTriggerDistance + */ + public LocationSensorOptions(final int pAccuracy, final boolean pAltitudeRequired, final boolean pBearingRequired, final boolean pCostAllowed, final int pPowerRequirement, final boolean pSpeedRequired, final boolean pEnabledOnly, final long pMinimumTriggerTime, final long pMinimumTriggerDistance) { + this.mEnabledOnly = pEnabledOnly; + this.mMinimumTriggerTime = pMinimumTriggerTime; + this.mMinimumTriggerDistance = pMinimumTriggerDistance; + + this.setAccuracy(pAccuracy); + this.setAltitudeRequired(pAltitudeRequired); + this.setBearingRequired(pBearingRequired); + this.setCostAllowed(pCostAllowed); + this.setPowerRequirement(pPowerRequirement); + this.setSpeedRequired(pSpeedRequired); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + public void setEnabledOnly(final boolean pEnabledOnly) { + this.mEnabledOnly = pEnabledOnly; + } + + public boolean isEnabledOnly() { + return this.mEnabledOnly; + } + + public long getMinimumTriggerTime() { + return this.mMinimumTriggerTime; + } + + public void setMinimumTriggerTime(final long pMinimumTriggerTime) { + this.mMinimumTriggerTime = pMinimumTriggerTime; + } + + public long getMinimumTriggerDistance() { + return this.mMinimumTriggerDistance; + } + + public void setMinimumTriggerDistance(final long pMinimumTriggerDistance) { + this.mMinimumTriggerDistance = pMinimumTriggerDistance; + } + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/sensor/orientation/IOrientationListener.java b/AndEngine/src/org/anddev/andengine/sensor/orientation/IOrientationListener.java index 02e0d597..3b347287 100644 --- a/AndEngine/src/org/anddev/andengine/sensor/orientation/IOrientationListener.java +++ b/AndEngine/src/org/anddev/andengine/sensor/orientation/IOrientationListener.java @@ -8,13 +8,13 @@ * @since 11:30:42 - 25.05.2010 */ public interface IOrientationListener { - // =========================================================== - // Final Fields - // =========================================================== + // =========================================================== + // Final Fields + // =========================================================== - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - public void onOrientationChanged(final OrientationData pOrientationData); + public void onOrientationChanged(final OrientationData pOrientationData); } diff --git a/AndEngine/src/org/anddev/andengine/sensor/orientation/OrientationData.java b/AndEngine/src/org/anddev/andengine/sensor/orientation/OrientationData.java index f35aa3d8..d7827c64 100644 --- a/AndEngine/src/org/anddev/andengine/sensor/orientation/OrientationData.java +++ b/AndEngine/src/org/anddev/andengine/sensor/orientation/OrientationData.java @@ -16,123 +16,123 @@ * @since 11:30:33 - 25.05.2010 */ public class OrientationData extends BaseSensorData { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - private final float[] mAccelerometerValues = new float[3]; - private final float[] mMagneticFieldValues = new float[3]; - private final float[] mRotationMatrix = new float[16]; - - private int mMagneticFieldAccuracy; - - // =========================================================== - // Constructors - // =========================================================== - - public OrientationData(final int pDisplayRotation) { - super(3, pDisplayRotation); - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - public float getRoll() { - return super.mValues[SensorManager.DATA_Z]; - } - - public float getPitch() { - return super.mValues[SensorManager.DATA_Y]; - } - - public float getYaw() { - return super.mValues[SensorManager.DATA_X]; - } - - @Override - @Deprecated - public void setValues(final float[] pValues) { - super.setValues(pValues); - } - - @Override - @Deprecated - public void setAccuracy(final int pAccuracy) { - super.setAccuracy(pAccuracy); - } - - public void setAccelerometerValues(final float[] pValues) { - System.arraycopy(pValues, 0, this.mAccelerometerValues, 0, pValues.length); - this.updateOrientation(); - } - - public void setMagneticFieldValues(final float[] pValues) { - System.arraycopy(pValues, 0, this.mMagneticFieldValues, 0, pValues.length); - this.updateOrientation(); - } - - private void updateOrientation() { - SensorManager.getRotationMatrix(this.mRotationMatrix, null, this.mAccelerometerValues, this.mMagneticFieldValues); - - // TODO Use dont't use identical matrixes in remapCoordinateSystem, due to performance reasons. - switch(this.mDisplayRotation) { - case Surface.ROTATION_0: - /* Nothing. */ - break; - case Surface.ROTATION_90: - SensorManager.remapCoordinateSystem(this.mRotationMatrix, SensorManager.AXIS_Y, SensorManager.AXIS_MINUS_X, this.mRotationMatrix); - break; -// case Surface.ROTATION_180: -// SensorManager.remapCoordinateSystem(this.mRotationMatrix, SensorManager.AXIS_?, SensorManager.AXIS_?, this.mRotationMatrix); -// break; -// case Surface.ROTATION_270: -// SensorManager.remapCoordinateSystem(this.mRotationMatrix, SensorManager.AXIS_?, SensorManager.AXIS_?, this.mRotationMatrix); -// break; - } - - final float[] values = this.mValues; - SensorManager.getOrientation(this.mRotationMatrix, values); - - for(int i = values.length - 1; i >= 0; i--) { - values[i] = values[i] * MathConstants.RAD_TO_DEG; - } - } - - public int getAccelerometerAccuracy() { - return this.getAccuracy(); - } - - public void setAccelerometerAccuracy(final int pAccelerometerAccuracy) { - super.setAccuracy(pAccelerometerAccuracy); - } - - public int getMagneticFieldAccuracy() { - return this.mMagneticFieldAccuracy; - } - - public void setMagneticFieldAccuracy(final int pMagneticFieldAccuracy) { - this.mMagneticFieldAccuracy = pMagneticFieldAccuracy; - } - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - public String toString() { - return "Orientation: " + Arrays.toString(this.mValues); - } - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + private final float[] mAccelerometerValues = new float[3]; + private final float[] mMagneticFieldValues = new float[3]; + private final float[] mRotationMatrix = new float[16]; + + private int mMagneticFieldAccuracy; + + // =========================================================== + // Constructors + // =========================================================== + + public OrientationData(final int pDisplayRotation) { + super(3, pDisplayRotation); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + public float getRoll() { + return super.mValues[SensorManager.DATA_Z]; + } + + public float getPitch() { + return super.mValues[SensorManager.DATA_Y]; + } + + public float getYaw() { + return super.mValues[SensorManager.DATA_X]; + } + + @Override + @Deprecated + public void setValues(final float[] pValues) { + super.setValues(pValues); + } + + @Override + @Deprecated + public void setAccuracy(final int pAccuracy) { + super.setAccuracy(pAccuracy); + } + + public void setAccelerometerValues(final float[] pValues) { + System.arraycopy(pValues, 0, this.mAccelerometerValues, 0, pValues.length); + this.updateOrientation(); + } + + public void setMagneticFieldValues(final float[] pValues) { + System.arraycopy(pValues, 0, this.mMagneticFieldValues, 0, pValues.length); + this.updateOrientation(); + } + + private void updateOrientation() { + SensorManager.getRotationMatrix(this.mRotationMatrix, null, this.mAccelerometerValues, this.mMagneticFieldValues); + + // TODO Use dont't use identical matrixes in remapCoordinateSystem, due to performance reasons. + switch(this.mDisplayRotation) { + case Surface.ROTATION_0: + /* Nothing. */ + break; + case Surface.ROTATION_90: + SensorManager.remapCoordinateSystem(this.mRotationMatrix, SensorManager.AXIS_Y, SensorManager.AXIS_MINUS_X, this.mRotationMatrix); + break; +// case Surface.ROTATION_180: +// SensorManager.remapCoordinateSystem(this.mRotationMatrix, SensorManager.AXIS_?, SensorManager.AXIS_?, this.mRotationMatrix); +// break; +// case Surface.ROTATION_270: +// SensorManager.remapCoordinateSystem(this.mRotationMatrix, SensorManager.AXIS_?, SensorManager.AXIS_?, this.mRotationMatrix); +// break; + } + + final float[] values = this.mValues; + SensorManager.getOrientation(this.mRotationMatrix, values); + + for(int i = values.length - 1; i >= 0; i--) { + values[i] = values[i] * MathConstants.RAD_TO_DEG; + } + } + + public int getAccelerometerAccuracy() { + return this.getAccuracy(); + } + + public void setAccelerometerAccuracy(final int pAccelerometerAccuracy) { + super.setAccuracy(pAccelerometerAccuracy); + } + + public int getMagneticFieldAccuracy() { + return this.mMagneticFieldAccuracy; + } + + public void setMagneticFieldAccuracy(final int pMagneticFieldAccuracy) { + this.mMagneticFieldAccuracy = pMagneticFieldAccuracy; + } + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + public String toString() { + return "Orientation: " + Arrays.toString(this.mValues); + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/sensor/orientation/OrientationSensorOptions.java b/AndEngine/src/org/anddev/andengine/sensor/orientation/OrientationSensorOptions.java index b231b9d0..fb3a6ae5 100644 --- a/AndEngine/src/org/anddev/andengine/sensor/orientation/OrientationSensorOptions.java +++ b/AndEngine/src/org/anddev/andengine/sensor/orientation/OrientationSensorOptions.java @@ -10,41 +10,41 @@ * @since 11:12:36 - 31.10.2010 */ public class OrientationSensorOptions { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - final SensorDelay mSensorDelay; + final SensorDelay mSensorDelay; - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - public OrientationSensorOptions(final SensorDelay pSensorDelay) { - this.mSensorDelay = pSensorDelay; - } + public OrientationSensorOptions(final SensorDelay pSensorDelay) { + this.mSensorDelay = pSensorDelay; + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - public SensorDelay getSensorDelay() { - return this.mSensorDelay; - } + public SensorDelay getSensorDelay() { + return this.mSensorDelay; + } - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/ui/IGameInterface.java b/AndEngine/src/org/anddev/andengine/ui/IGameInterface.java index 6b1403eb..b499621f 100644 --- a/AndEngine/src/org/anddev/andengine/ui/IGameInterface.java +++ b/AndEngine/src/org/anddev/andengine/ui/IGameInterface.java @@ -11,20 +11,20 @@ * @since 12:03:08 - 14.03.2010 */ public interface IGameInterface { - // =========================================================== - // Final Fields - // =========================================================== + // =========================================================== + // Final Fields + // =========================================================== - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - public Engine onLoadEngine(); - public void onLoadResources(); - public void onUnloadResources(); - public Scene onLoadScene(); - public void onLoadComplete(); + public Engine onLoadEngine(); + public void onLoadResources(); + public void onUnloadResources(); + public Scene onLoadScene(); + public void onLoadComplete(); - public void onPauseGame(); - public void onResumeGame(); + public void onPauseGame(); + public void onResumeGame(); } diff --git a/AndEngine/src/org/anddev/andengine/ui/activity/BaseActivity.java b/AndEngine/src/org/anddev/andengine/ui/activity/BaseActivity.java index 106bd83c..2b261340 100644 --- a/AndEngine/src/org/anddev/andengine/ui/activity/BaseActivity.java +++ b/AndEngine/src/org/anddev/andengine/ui/activity/BaseActivity.java @@ -18,104 +18,104 @@ * @since 18:35:28 - 29.08.2009 */ public abstract class BaseActivity extends AppCompatActivity { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - // =========================================================== - // Constructors - // =========================================================== - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - // =========================================================== - // Methods - // =========================================================== - - /** - * Performs a task in the background, showing a {@link ProgressDialog}, - * while the {@link Callable} is being processed. - * - * @param - * @param pTitleResID - * @param pMessageResID - * @param pCallable - * @param pCallback - */ - protected void doAsync(final int pTitleResID, final int pMessageResID, final Callable pCallable, final Callback pCallback) { - this.doAsync(pTitleResID, pMessageResID, pCallable, pCallback, null); - } - - /** - * Performs a task in the background, showing a indeterminate {@link ProgressDialog}, - * while the {@link Callable} is being processed. - * - * @param - * @param pTitleResID - * @param pMessageResID - * @param pCallable - * @param pCallback - * @param pExceptionCallback - */ - protected void doAsync(final int pTitleResID, final int pMessageResID, final Callable pCallable, final Callback pCallback, final Callback pExceptionCallback) { - ActivityUtils.doAsync(this, pTitleResID, pMessageResID, pCallable, pCallback, pExceptionCallback); - } - - /** - * Performs a task in the background, showing a {@link ProgressDialog} with an ProgressBar, - * while the {@link AsyncCallable} is being processed. - * - * @param - * @param pTitleResID - * @param pCallback - */ - protected void doProgressAsync(final int pTitleResID, final ProgressCallable pCallable, final Callback pCallback) { - this.doProgressAsync(pTitleResID, pCallable, pCallback, null); - } - - /** - * Performs a task in the background, showing a {@link ProgressDialog} with a ProgressBar, - * while the {@link AsyncCallable} is being processed. - * - * @param - * @param pTitleResID - * @param pCallback - * @param pExceptionCallback - */ - protected void doProgressAsync(final int pTitleResID, final ProgressCallable pCallable, final Callback pCallback, final Callback pExceptionCallback) { - ActivityUtils.doProgressAsync(this, pTitleResID, pCallable, pCallback, pExceptionCallback); - } - - /** - * Performs a task in the background, showing an indeterminate {@link ProgressDialog}, - * while the {@link AsyncCallable} is being processed. - * - * @param - * @param pTitleResID - * @param pMessageResID - * @param pAsyncCallable - * @param pCallback - * @param pExceptionCallback - */ - protected void doAsync(final int pTitleResID, final int pMessageResID, final AsyncCallable pAsyncCallable, final Callback pCallback, final Callback pExceptionCallback) { - ActivityUtils.doAsync(this, pTitleResID, pMessageResID, pAsyncCallable, pCallback, pExceptionCallback); - } - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== - - public static class CancelledException extends Exception { - private static final long serialVersionUID = -78123211381435596L; - } + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + // =========================================================== + // Constructors + // =========================================================== + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + /** + * Performs a task in the background, showing a {@link ProgressDialog}, + * while the {@link Callable} is being processed. + * + * @param + * @param pTitleResID + * @param pMessageResID + * @param pCallable + * @param pCallback + */ + protected void doAsync(final int pTitleResID, final int pMessageResID, final Callable pCallable, final Callback pCallback) { + this.doAsync(pTitleResID, pMessageResID, pCallable, pCallback, null); + } + + /** + * Performs a task in the background, showing a indeterminate {@link ProgressDialog}, + * while the {@link Callable} is being processed. + * + * @param + * @param pTitleResID + * @param pMessageResID + * @param pCallable + * @param pCallback + * @param pExceptionCallback + */ + protected void doAsync(final int pTitleResID, final int pMessageResID, final Callable pCallable, final Callback pCallback, final Callback pExceptionCallback) { + ActivityUtils.doAsync(this, pTitleResID, pMessageResID, pCallable, pCallback, pExceptionCallback); + } + + /** + * Performs a task in the background, showing a {@link ProgressDialog} with an ProgressBar, + * while the {@link AsyncCallable} is being processed. + * + * @param + * @param pTitleResID + * @param pCallback + */ + protected void doProgressAsync(final int pTitleResID, final ProgressCallable pCallable, final Callback pCallback) { + this.doProgressAsync(pTitleResID, pCallable, pCallback, null); + } + + /** + * Performs a task in the background, showing a {@link ProgressDialog} with a ProgressBar, + * while the {@link AsyncCallable} is being processed. + * + * @param + * @param pTitleResID + * @param pCallback + * @param pExceptionCallback + */ + protected void doProgressAsync(final int pTitleResID, final ProgressCallable pCallable, final Callback pCallback, final Callback pExceptionCallback) { + ActivityUtils.doProgressAsync(this, pTitleResID, pCallable, pCallback, pExceptionCallback); + } + + /** + * Performs a task in the background, showing an indeterminate {@link ProgressDialog}, + * while the {@link AsyncCallable} is being processed. + * + * @param + * @param pTitleResID + * @param pMessageResID + * @param pAsyncCallable + * @param pCallback + * @param pExceptionCallback + */ + protected void doAsync(final int pTitleResID, final int pMessageResID, final AsyncCallable pAsyncCallable, final Callback pCallback, final Callback pExceptionCallback) { + ActivityUtils.doAsync(this, pTitleResID, pMessageResID, pAsyncCallable, pCallback, pExceptionCallback); + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== + + public static class CancelledException extends Exception { + private static final long serialVersionUID = -78123211381435596L; + } } diff --git a/AndEngine/src/org/anddev/andengine/ui/activity/BaseGameActivity.java b/AndEngine/src/org/anddev/andengine/ui/activity/BaseGameActivity.java index 9f2e9fe8..b6f0fb8d 100644 --- a/AndEngine/src/org/anddev/andengine/ui/activity/BaseGameActivity.java +++ b/AndEngine/src/org/anddev/andengine/ui/activity/BaseGameActivity.java @@ -30,250 +30,250 @@ * @since 11:27:06 - 08.03.2010 */ public abstract class BaseGameActivity extends BaseActivity implements IGameInterface { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - protected Engine mEngine; - private WakeLock mWakeLock; - protected RenderSurfaceView mRenderSurfaceView; - protected boolean mHasWindowFocused; - private boolean mPaused; - private boolean mGameLoaded; - - // =========================================================== - // Constructors - // =========================================================== - - @Override - protected void onCreate(final Bundle pSavedInstanceState) { - super.onCreate(pSavedInstanceState); - this.mPaused = true; - - this.mEngine = this.onLoadEngine(); - if (this.mEngine == null) { - return; - } - - this.applyEngineOptions(this.mEngine.getEngineOptions()); - - this.onSetContentView(); - } - - @Override - protected void onResume() { - super.onResume(); - if (this.mEngine == null) { - return; - } - if(this.mPaused && this.mHasWindowFocused) { - this.doResume(); - } - } - - @Override - public void onWindowFocusChanged(final boolean pHasWindowFocus) { - super.onWindowFocusChanged(pHasWindowFocus); - if (this.mEngine == null) { - return; - } - if(pHasWindowFocus) { - if(this.mPaused) { - this.doResume(); - } - this.mHasWindowFocused = true; - } else { - /* if(!this.mPaused) { - this.doPause(); - } */ - this.mHasWindowFocused = false; - } - } - - @Override - protected void onPause() { - super.onPause(); - if (this.mEngine == null) { - return; - } - if(!this.mPaused) { - this.doPause(); - } - } - - @Override - protected void onDestroy() { - super.onDestroy(); + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + protected Engine mEngine; + private WakeLock mWakeLock; + protected RenderSurfaceView mRenderSurfaceView; + protected boolean mHasWindowFocused; + private boolean mPaused; + private boolean mGameLoaded; + + // =========================================================== + // Constructors + // =========================================================== + + @Override + protected void onCreate(final Bundle pSavedInstanceState) { + super.onCreate(pSavedInstanceState); + this.mPaused = true; + + this.mEngine = this.onLoadEngine(); if (this.mEngine == null) { return; } - android.os.Process.killProcess(android.os.Process.myPid()); - - this.mEngine.interruptUpdateThread(); - - this.onUnloadResources(); - } - - @Override - public void onUnloadResources() { - if (this.mEngine == null) { - return; - } - if(this.mEngine.getEngineOptions().needsMusic()) { - this.getMusicManager().releaseAll(); - } - if(this.mEngine.getEngineOptions().needsSound()) { - this.getSoundManager().releaseAll(); - } - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - public Engine getEngine() { - return this.mEngine; - } - - public TextureManager getTextureManager() { - return this.mEngine.getTextureManager(); - } - - public FontManager getFontManager() { - return this.mEngine.getFontManager(); - } - - public SoundManager getSoundManager() { - return this.mEngine.getSoundManager(); - } - - public MusicManager getMusicManager() { - return this.mEngine.getMusicManager(); - } - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - public void onResumeGame() { - - } - - @Override - public void onPauseGame() { - - } - - // =========================================================== - // Methods - // =========================================================== - - private void doResume() { - if (this.mEngine == null) { - return; - } - if(!this.mGameLoaded) { - this.onLoadResources(); - final Scene scene = this.onLoadScene(); - this.mEngine.onLoadComplete(scene); - this.onLoadComplete(); - this.mGameLoaded = true; - } - - this.mPaused = false; - this.acquireWakeLock(this.mEngine.getEngineOptions().getWakeLockOptions()); - this.mEngine.onResume(); - - this.mRenderSurfaceView.onResume(); - this.mEngine.start(); - this.onResumeGame(); - } - - private void doPause() { - if (this.mEngine == null) { - return; - } - this.mPaused = true; - this.releaseWakeLock(); - - this.mEngine.onPause(); - this.mEngine.stop(); - this.mRenderSurfaceView.onPause(); - this.onPauseGame(); - } - - public void runOnUpdateThread(final Runnable pRunnable) { - if (this.mEngine == null) { - return; - } - this.mEngine.runOnUpdateThread(pRunnable); - } - - protected void onSetContentView() { - if (this.mEngine == null) { - return; - } - this.mRenderSurfaceView = new RenderSurfaceView(this); - this.mRenderSurfaceView.setEGLConfigChooser(false); - this.mRenderSurfaceView.setRenderer(this.mEngine); - - this.setContentView(this.mRenderSurfaceView, this.createSurfaceViewLayoutParams()); - } - - private void acquireWakeLock(final WakeLockOptions pWakeLockOptions) { - if(pWakeLockOptions == WakeLockOptions.SCREEN_ON) { - ActivityUtils.keepScreenOn(this); - } else { - final PowerManager pm = (PowerManager) this.getSystemService(Context.POWER_SERVICE); - this.mWakeLock = pm.newWakeLock(pWakeLockOptions.getFlag() | PowerManager.ON_AFTER_RELEASE, "andengine:AndEngine"); - try { - this.mWakeLock.acquire(); - } catch (final SecurityException e) { - Debug.e("You have to add\n\t\nto your AndroidManifest.xml !", e); - } - } - } - - private void releaseWakeLock() { - if(this.mWakeLock != null && this.mWakeLock.isHeld()) { - this.mWakeLock.release(); - } - } - - private void applyEngineOptions(final EngineOptions pEngineOptions) { - if(pEngineOptions.isFullscreen()) { - ActivityUtils.requestFullscreen(this); - } - - if(pEngineOptions.needsMusic() || pEngineOptions.needsSound()) { - this.setVolumeControlStream(AudioManager.STREAM_MUSIC); - } - - if (pEngineOptions.getScreenOrientation() != null) { - switch (pEngineOptions.getScreenOrientation()) { - - case LANDSCAPE: - this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); - break; - case PORTRAIT: - this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); - break; - } - } - } - - protected LayoutParams createSurfaceViewLayoutParams() { - final LayoutParams layoutParams = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT); - layoutParams.gravity = Gravity.CENTER; - return layoutParams; - } - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + + this.applyEngineOptions(this.mEngine.getEngineOptions()); + + this.onSetContentView(); + } + + @Override + protected void onResume() { + super.onResume(); + if (this.mEngine == null) { + return; + } + if(this.mPaused && this.mHasWindowFocused) { + this.doResume(); + } + } + + @Override + public void onWindowFocusChanged(final boolean pHasWindowFocus) { + super.onWindowFocusChanged(pHasWindowFocus); + if (this.mEngine == null) { + return; + } + if(pHasWindowFocus) { + if(this.mPaused) { + this.doResume(); + } + this.mHasWindowFocused = true; + } else { + /* if(!this.mPaused) { + this.doPause(); + } */ + this.mHasWindowFocused = false; + } + } + + @Override + protected void onPause() { + super.onPause(); + if (this.mEngine == null) { + return; + } + if(!this.mPaused) { + this.doPause(); + } + } + + @Override + protected void onDestroy() { + super.onDestroy(); + if (this.mEngine == null) { + return; + } + android.os.Process.killProcess(android.os.Process.myPid()); + + this.mEngine.interruptUpdateThread(); + + this.onUnloadResources(); + } + + @Override + public void onUnloadResources() { + if (this.mEngine == null) { + return; + } + if(this.mEngine.getEngineOptions().needsMusic()) { + this.getMusicManager().releaseAll(); + } + if(this.mEngine.getEngineOptions().needsSound()) { + this.getSoundManager().releaseAll(); + } + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + public Engine getEngine() { + return this.mEngine; + } + + public TextureManager getTextureManager() { + return this.mEngine.getTextureManager(); + } + + public FontManager getFontManager() { + return this.mEngine.getFontManager(); + } + + public SoundManager getSoundManager() { + return this.mEngine.getSoundManager(); + } + + public MusicManager getMusicManager() { + return this.mEngine.getMusicManager(); + } + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + public void onResumeGame() { + + } + + @Override + public void onPauseGame() { + + } + + // =========================================================== + // Methods + // =========================================================== + + private void doResume() { + if (this.mEngine == null) { + return; + } + if(!this.mGameLoaded) { + this.onLoadResources(); + final Scene scene = this.onLoadScene(); + this.mEngine.onLoadComplete(scene); + this.onLoadComplete(); + this.mGameLoaded = true; + } + + this.mPaused = false; + this.acquireWakeLock(this.mEngine.getEngineOptions().getWakeLockOptions()); + this.mEngine.onResume(); + + this.mRenderSurfaceView.onResume(); + this.mEngine.start(); + this.onResumeGame(); + } + + private void doPause() { + if (this.mEngine == null) { + return; + } + this.mPaused = true; + this.releaseWakeLock(); + + this.mEngine.onPause(); + this.mEngine.stop(); + this.mRenderSurfaceView.onPause(); + this.onPauseGame(); + } + + public void runOnUpdateThread(final Runnable pRunnable) { + if (this.mEngine == null) { + return; + } + this.mEngine.runOnUpdateThread(pRunnable); + } + + protected void onSetContentView() { + if (this.mEngine == null) { + return; + } + this.mRenderSurfaceView = new RenderSurfaceView(this); + this.mRenderSurfaceView.setEGLConfigChooser(false); + this.mRenderSurfaceView.setRenderer(this.mEngine); + + this.setContentView(this.mRenderSurfaceView, this.createSurfaceViewLayoutParams()); + } + + private void acquireWakeLock(final WakeLockOptions pWakeLockOptions) { + if(pWakeLockOptions == WakeLockOptions.SCREEN_ON) { + ActivityUtils.keepScreenOn(this); + } else { + final PowerManager pm = (PowerManager) this.getSystemService(Context.POWER_SERVICE); + this.mWakeLock = pm.newWakeLock(pWakeLockOptions.getFlag() | PowerManager.ON_AFTER_RELEASE, "andengine:AndEngine"); + try { + this.mWakeLock.acquire(); + } catch (final SecurityException e) { + Debug.e("You have to add\n\t\nto your AndroidManifest.xml !", e); + } + } + } + + private void releaseWakeLock() { + if(this.mWakeLock != null && this.mWakeLock.isHeld()) { + this.mWakeLock.release(); + } + } + + private void applyEngineOptions(final EngineOptions pEngineOptions) { + if(pEngineOptions.isFullscreen()) { + ActivityUtils.requestFullscreen(this); + } + + if(pEngineOptions.needsMusic() || pEngineOptions.needsSound()) { + this.setVolumeControlStream(AudioManager.STREAM_MUSIC); + } + + if (pEngineOptions.getScreenOrientation() != null) { + switch (pEngineOptions.getScreenOrientation()) { + + case LANDSCAPE: + this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); + break; + case PORTRAIT: + this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); + break; + } + } + } + + protected LayoutParams createSurfaceViewLayoutParams() { + final LayoutParams layoutParams = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT); + layoutParams.gravity = Gravity.CENTER; + return layoutParams; + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/ui/activity/BaseSplashActivity.java b/AndEngine/src/org/anddev/andengine/ui/activity/BaseSplashActivity.java index 99fc7993..aae176c3 100644 --- a/AndEngine/src/org/anddev/andengine/ui/activity/BaseSplashActivity.java +++ b/AndEngine/src/org/anddev/andengine/ui/activity/BaseSplashActivity.java @@ -29,99 +29,99 @@ * @since 08:25:31 - 03.05.2010 */ public abstract class BaseSplashActivity extends BaseGameActivity { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - private Camera mCamera; - private IBitmapTextureAtlasSource mSplashTextureAtlasSource; - private TextureRegion mLoadingScreenTextureRegion; + private Camera mCamera; + private IBitmapTextureAtlasSource mSplashTextureAtlasSource; + private TextureRegion mLoadingScreenTextureRegion; - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - protected abstract ScreenOrientation getScreenOrientation(); + protected abstract ScreenOrientation getScreenOrientation(); - protected abstract IBitmapTextureAtlasSource onGetSplashTextureAtlasSource(); + protected abstract IBitmapTextureAtlasSource onGetSplashTextureAtlasSource(); - protected abstract float getSplashDuration(); + protected abstract float getSplashDuration(); - protected abstract Class getFollowUpActivity(); + protected abstract Class getFollowUpActivity(); - protected float getSplashScaleFrom() { - return 1f; - } + protected float getSplashScaleFrom() { + return 1f; + } - protected float getSplashScaleTo() { - return 1f; - } + protected float getSplashScaleTo() { + return 1f; + } - @Override - public void onLoadComplete() { - } + @Override + public void onLoadComplete() { + } - @Override - public Engine onLoadEngine() { - this.mSplashTextureAtlasSource = this.onGetSplashTextureAtlasSource(); + @Override + public Engine onLoadEngine() { + this.mSplashTextureAtlasSource = this.onGetSplashTextureAtlasSource(); - final int width = this.mSplashTextureAtlasSource.getWidth(); - final int height = this.mSplashTextureAtlasSource.getHeight(); + final int width = this.mSplashTextureAtlasSource.getWidth(); + final int height = this.mSplashTextureAtlasSource.getHeight(); - this.mCamera = this.getSplashCamera(width, height); - return new Engine(new EngineOptions(true, this.getScreenOrientation(), this.getSplashResolutionPolicy(width, height), this.mCamera)); - } + this.mCamera = this.getSplashCamera(width, height); + return new Engine(new EngineOptions(true, this.getScreenOrientation(), this.getSplashResolutionPolicy(width, height), this.mCamera)); + } - @Override - public void onLoadResources() { - final BitmapTextureAtlas loadingScreenBitmapTextureAtlas = BitmapTextureAtlasFactory.createForTextureAtlasSourceSize(BitmapTextureFormat.RGBA_8888, this.mSplashTextureAtlasSource, TextureOptions.BILINEAR_PREMULTIPLYALPHA); - this.mLoadingScreenTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromSource(loadingScreenBitmapTextureAtlas, this.mSplashTextureAtlasSource, 0, 0); + @Override + public void onLoadResources() { + final BitmapTextureAtlas loadingScreenBitmapTextureAtlas = BitmapTextureAtlasFactory.createForTextureAtlasSourceSize(BitmapTextureFormat.RGBA_8888, this.mSplashTextureAtlasSource, TextureOptions.BILINEAR_PREMULTIPLYALPHA); + this.mLoadingScreenTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromSource(loadingScreenBitmapTextureAtlas, this.mSplashTextureAtlasSource, 0, 0); - this.getEngine().getTextureManager().loadTexture(loadingScreenBitmapTextureAtlas); - } + this.getEngine().getTextureManager().loadTexture(loadingScreenBitmapTextureAtlas); + } - @Override - public Scene onLoadScene() { - final float splashDuration = this.getSplashDuration(); + @Override + public Scene onLoadScene() { + final float splashDuration = this.getSplashDuration(); - final SplashScene splashScene = new SplashScene(this.mCamera, this.mLoadingScreenTextureRegion, splashDuration, this.getSplashScaleFrom(), this.getSplashScaleTo()); + final SplashScene splashScene = new SplashScene(this.mCamera, this.mLoadingScreenTextureRegion, splashDuration, this.getSplashScaleFrom(), this.getSplashScaleTo()); - splashScene.registerUpdateHandler(new TimerHandler(splashDuration, new ITimerCallback() { - @Override - public void onTimePassed(final TimerHandler pTimerHandler) { - BaseSplashActivity.this.startActivity(new Intent(BaseSplashActivity.this, BaseSplashActivity.this.getFollowUpActivity())); - BaseSplashActivity.this.finish(); - } - })); + splashScene.registerUpdateHandler(new TimerHandler(splashDuration, new ITimerCallback() { + @Override + public void onTimePassed(final TimerHandler pTimerHandler) { + BaseSplashActivity.this.startActivity(new Intent(BaseSplashActivity.this, BaseSplashActivity.this.getFollowUpActivity())); + BaseSplashActivity.this.finish(); + } + })); - return splashScene; - } + return splashScene; + } - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - protected Camera getSplashCamera(final int pSplashwidth, final int pSplashHeight) { - return new Camera(0, 0, pSplashwidth, pSplashHeight); - } + protected Camera getSplashCamera(final int pSplashwidth, final int pSplashHeight) { + return new Camera(0, 0, pSplashwidth, pSplashHeight); + } - protected IResolutionPolicy getSplashResolutionPolicy(final int pSplashwidth, final int pSplashHeight) { - return new RatioResolutionPolicy(pSplashwidth, pSplashHeight); - } + protected IResolutionPolicy getSplashResolutionPolicy(final int pSplashwidth, final int pSplashHeight) { + return new RatioResolutionPolicy(pSplashwidth, pSplashHeight); + } - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/ui/activity/LayoutGameActivity.java b/AndEngine/src/org/anddev/andengine/ui/activity/LayoutGameActivity.java index 3a871697..505a8bef 100644 --- a/AndEngine/src/org/anddev/andengine/ui/activity/LayoutGameActivity.java +++ b/AndEngine/src/org/anddev/andengine/ui/activity/LayoutGameActivity.java @@ -10,44 +10,44 @@ * @since 10:18:50 - 06.10.2010 */ public abstract class LayoutGameActivity extends BaseGameActivity { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - protected abstract int getLayoutID(); - protected abstract int getRenderSurfaceViewID(); + protected abstract int getLayoutID(); + protected abstract int getRenderSurfaceViewID(); - @Override - protected void onSetContentView() { - super.setContentView(this.getLayoutID()); + @Override + protected void onSetContentView() { + super.setContentView(this.getLayoutID()); - this.mRenderSurfaceView = (RenderSurfaceView) this.findViewById(this.getRenderSurfaceViewID()); + this.mRenderSurfaceView = (RenderSurfaceView) this.findViewById(this.getRenderSurfaceViewID()); - this.mRenderSurfaceView.setEGLConfigChooser(false); - this.mRenderSurfaceView.setRenderer(this.mEngine); - } + this.mRenderSurfaceView.setEGLConfigChooser(false); + this.mRenderSurfaceView.setRenderer(this.mEngine); + } - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/ui/dialog/GenericInputDialogBuilder.java b/AndEngine/src/org/anddev/andengine/ui/dialog/GenericInputDialogBuilder.java index 5252f91a..b6c94d56 100644 --- a/AndEngine/src/org/anddev/andengine/ui/dialog/GenericInputDialogBuilder.java +++ b/AndEngine/src/org/anddev/andengine/ui/dialog/GenericInputDialogBuilder.java @@ -20,104 +20,104 @@ * @since 09:35:55 - 14.12.2009 */ public abstract class GenericInputDialogBuilder { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - protected final Callback mSuccessCallback; - protected final OnCancelListener mOnCancelListener; - protected final int mTitleResID; - protected final int mMessageResID; - protected final int mIconResID; - protected final Context mContext; - private final int mErrorResID; - private final String mDefaultText; - - // =========================================================== - // Constructors - // =========================================================== - - 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){ - this.mContext = pContext; - this.mTitleResID = pTitleResID; - this.mMessageResID = pMessageResID; - this.mErrorResID = pErrorResID; - this.mIconResID = pIconResID; - this.mDefaultText = pDefaultText; - this.mSuccessCallback = pSuccessCallback; - this.mOnCancelListener = pOnCancelListener; - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - protected abstract T generateResult(final String pInput); - - // =========================================================== - // Methods - // =========================================================== - - public Dialog create() { - final EditText etInput = new EditText(this.mContext); - etInput.setText(this.mDefaultText); - - final AlertDialog.Builder ab = new AlertDialog.Builder(this.mContext); - if(this.mTitleResID != 0) { - ab.setTitle(this.mTitleResID); - } - if(this.mMessageResID != 0) { - ab.setMessage(this.mMessageResID); - } - if(this.mIconResID != 0) { - ab.setIcon(this.mIconResID); - } - - this.setView(ab, etInput); - ab.setOnCancelListener(this.mOnCancelListener) - .setPositiveButton(android.R.string.ok, new OnClickListener() { - @Override - public void onClick(final DialogInterface pDialog, final int pWhich) { - final T result; - try{ - result = GenericInputDialogBuilder.this.generateResult(etInput.getText().toString()); - } catch (final IllegalArgumentException e) { - Debug.e("Error in GenericInputDialogBuilder.generateResult()", e); - Toast.makeText(GenericInputDialogBuilder.this.mContext, GenericInputDialogBuilder.this.mErrorResID, Toast.LENGTH_SHORT).show(); - return; - } - GenericInputDialogBuilder.this.mSuccessCallback.onCallback(result); - pDialog.dismiss(); - } - }) - .setNegativeButton(android.R.string.cancel, new OnClickListener() { - @Override - public void onClick(final DialogInterface pDialog, final int pWhich) { - GenericInputDialogBuilder.this.mOnCancelListener.onCancel(pDialog); - pDialog.dismiss(); - } - }); - - return ab.create(); - } - - protected void setView(final AlertDialog.Builder pBuilder, final EditText pInputEditText) { - pBuilder.setView(pInputEditText); - } - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + protected final Callback mSuccessCallback; + protected final OnCancelListener mOnCancelListener; + protected final int mTitleResID; + protected final int mMessageResID; + protected final int mIconResID; + protected final Context mContext; + private final int mErrorResID; + private final String mDefaultText; + + // =========================================================== + // Constructors + // =========================================================== + + 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){ + this.mContext = pContext; + this.mTitleResID = pTitleResID; + this.mMessageResID = pMessageResID; + this.mErrorResID = pErrorResID; + this.mIconResID = pIconResID; + this.mDefaultText = pDefaultText; + this.mSuccessCallback = pSuccessCallback; + this.mOnCancelListener = pOnCancelListener; + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + protected abstract T generateResult(final String pInput); + + // =========================================================== + // Methods + // =========================================================== + + public Dialog create() { + final EditText etInput = new EditText(this.mContext); + etInput.setText(this.mDefaultText); + + final AlertDialog.Builder ab = new AlertDialog.Builder(this.mContext); + if(this.mTitleResID != 0) { + ab.setTitle(this.mTitleResID); + } + if(this.mMessageResID != 0) { + ab.setMessage(this.mMessageResID); + } + if(this.mIconResID != 0) { + ab.setIcon(this.mIconResID); + } + + this.setView(ab, etInput); + ab.setOnCancelListener(this.mOnCancelListener) + .setPositiveButton(android.R.string.ok, new OnClickListener() { + @Override + public void onClick(final DialogInterface pDialog, final int pWhich) { + final T result; + try{ + result = GenericInputDialogBuilder.this.generateResult(etInput.getText().toString()); + } catch (final IllegalArgumentException e) { + Debug.e("Error in GenericInputDialogBuilder.generateResult()", e); + Toast.makeText(GenericInputDialogBuilder.this.mContext, GenericInputDialogBuilder.this.mErrorResID, Toast.LENGTH_SHORT).show(); + return; + } + GenericInputDialogBuilder.this.mSuccessCallback.onCallback(result); + pDialog.dismiss(); + } + }) + .setNegativeButton(android.R.string.cancel, new OnClickListener() { + @Override + public void onClick(final DialogInterface pDialog, final int pWhich) { + GenericInputDialogBuilder.this.mOnCancelListener.onCancel(pDialog); + pDialog.dismiss(); + } + }); + + return ab.create(); + } + + protected void setView(final AlertDialog.Builder pBuilder, final EditText pInputEditText) { + pBuilder.setView(pInputEditText); + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/ui/dialog/StringInputDialogBuilder.java b/AndEngine/src/org/anddev/andengine/ui/dialog/StringInputDialogBuilder.java index 7f7a2470..845235d2 100644 --- a/AndEngine/src/org/anddev/andengine/ui/dialog/StringInputDialogBuilder.java +++ b/AndEngine/src/org/anddev/andengine/ui/dialog/StringInputDialogBuilder.java @@ -13,44 +13,44 @@ * @since 09:46:00 - 14.12.2009 */ public class StringInputDialogBuilder extends GenericInputDialogBuilder { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - // =========================================================== - // Constructors - // =========================================================== - - public StringInputDialogBuilder(final Context pContext, final int pTitleResID, final int pMessageResID, final int pErrorResID, final int pIconResID, final Callback pSuccessCallback, final OnCancelListener pOnCancelListener) { - super(pContext, pTitleResID, pMessageResID, pErrorResID, pIconResID, pSuccessCallback, pOnCancelListener); - } - - public StringInputDialogBuilder(final Context pContext, final int pTitleResID, final int pMessageResID, final int pErrorResID, final int pIconResID, final String pDefaultText, final Callback pSuccessCallback, final OnCancelListener pOnCancelListener) { - super(pContext, pTitleResID, pMessageResID, pErrorResID, pIconResID, pDefaultText, pSuccessCallback, pOnCancelListener); - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - protected String generateResult(final String pInput) { - return pInput; - } - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + // =========================================================== + // Constructors + // =========================================================== + + public StringInputDialogBuilder(final Context pContext, final int pTitleResID, final int pMessageResID, final int pErrorResID, final int pIconResID, final Callback pSuccessCallback, final OnCancelListener pOnCancelListener) { + super(pContext, pTitleResID, pMessageResID, pErrorResID, pIconResID, pSuccessCallback, pOnCancelListener); + } + + public StringInputDialogBuilder(final Context pContext, final int pTitleResID, final int pMessageResID, final int pErrorResID, final int pIconResID, final String pDefaultText, final Callback pSuccessCallback, final OnCancelListener pOnCancelListener) { + super(pContext, pTitleResID, pMessageResID, pErrorResID, pIconResID, pDefaultText, pSuccessCallback, pOnCancelListener); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + protected String generateResult(final String pInput) { + return pInput; + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/util/ActivityUtils.java b/AndEngine/src/org/anddev/andengine/util/ActivityUtils.java index 1d218a64..a484b702 100644 --- a/AndEngine/src/org/anddev/andengine/util/ActivityUtils.java +++ b/AndEngine/src/org/anddev/andengine/util/ActivityUtils.java @@ -23,223 +23,223 @@ * @since 18:11:54 - 07.03.2011 */ public class ActivityUtils { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - // =========================================================== - // Constructors - // =========================================================== - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - // =========================================================== - // Methods - // =========================================================== - - public static void requestFullscreen(final Activity pActivity) { - final Window window = pActivity.getWindow(); - window.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); - window.clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN); - window.requestFeature(Window.FEATURE_NO_TITLE); - } - - /** - * @param pActivity - * @param pScreenBrightness [0..1] - */ - public static 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) { - pActivity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); - } - - public static void doAsync(final Context pContext, final int pTitleResID, final int pMessageResID, final Callable pCallable, final Callback pCallback) { - ActivityUtils.doAsync(pContext, pTitleResID, pMessageResID, pCallable, pCallback, null, false); - } - - public static 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 pTitleResID, final int pMessageResID, final Callable pCallable, final Callback pCallback, final boolean pCancelable) { - ActivityUtils.doAsync(pContext, pTitleResID, pMessageResID, 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) { - ActivityUtils.doAsync(pContext, pTitle, pMessage, pCallable, pCallback, null, pCancelable); - } - - public static void doAsync(final Context pContext, final int pTitleResID, final int pMessageResID, final Callable pCallable, final Callback pCallback, final Callback pExceptionCallback) { - ActivityUtils.doAsync(pContext, pTitleResID, pMessageResID, 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) { - ActivityUtils.doAsync(pContext, pTitle, pMessage, pCallable, pCallback, pExceptionCallback, false); - } - - public static void doAsync(final Context pContext, final int pTitleResID, final int pMessageResID, final Callable pCallable, final Callback pCallback, final Callback pExceptionCallback, final boolean pCancelable) { - ActivityUtils.doAsync(pContext, pContext.getString(pTitleResID), pContext.getString(pMessageResID), 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() { - private ProgressDialog mPD; - private Exception mException = null; - - @Override - public void onPreExecute() { - this.mPD = ProgressDialog.show(pContext, pTitle, pMessage, true, pCancelable); - if(pCancelable) { - this.mPD.setOnCancelListener(new OnCancelListener() { - @Override - public void onCancel(final DialogInterface pDialogInterface) { - pExceptionCallback.onCallback(new CancelledException()); - pDialogInterface.dismiss(); - } - }); - } - super.onPreExecute(); - } - - @Override - public T doInBackground(final Void... params) { - try { - return pCallable.call(); - } catch (final Exception e) { - this.mException = e; - } - return null; - } - - @Override - public void onPostExecute(final T result) { - try { - this.mPD.dismiss(); - } catch (final Exception e) { - Debug.e("Error", e); - } - - if(this.isCancelled()) { - this.mException = new CancelledException(); - } - - if(this.mException == null) { - pCallback.onCallback(result); - } else { - if(pExceptionCallback == null) { - Debug.e("Error", this.mException); - } else { - pExceptionCallback.onCallback(this.mException); - } - } - - super.onPostExecute(result); - } - }.execute((Void[]) null); - } - - public static void doProgressAsync(final Context pContext, final int pTitleResID, final ProgressCallable pCallable, final Callback pCallback) { - ActivityUtils.doProgressAsync(pContext, pTitleResID, pCallable, pCallback, null); - } - - public static void doProgressAsync(final Context pContext, final int pTitleResID, final ProgressCallable pCallable, final Callback pCallback, final Callback pExceptionCallback) { - new AsyncTask() { - private ProgressDialog mPD; - private Exception mException = null; - - @Override - public void onPreExecute() { - this.mPD = new ProgressDialog(pContext); - this.mPD.setTitle(pTitleResID); - this.mPD.setIcon(android.R.drawable.ic_menu_save); - this.mPD.setIndeterminate(false); - this.mPD.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); - this.mPD.show(); - super.onPreExecute(); - } - - @Override - public T doInBackground(final Void... params) { - try { - return pCallable.call(new IProgressListener() { - @Override - public void onProgressChanged(final int pProgress) { - onProgressUpdate(pProgress); - } - }); - } catch (final Exception e) { - this.mException = e; - } - return null; - } - - @Override - public void onProgressUpdate(final Integer... values) { - this.mPD.setProgress(values[0]); - } - - @Override - public void onPostExecute(final T result) { - try { - this.mPD.dismiss(); - } catch (final Exception e) { - Debug.e("Error", e); - /* Nothing. */ - } - - if(this.isCancelled()) { - this.mException = new CancelledException(); - } - - if(this.mException == null) { - pCallback.onCallback(result); - } else { - if(pExceptionCallback == null) { - Debug.e("Error", this.mException); - } else { - pExceptionCallback.onCallback(this.mException); - } - } - - super.onPostExecute(result); - } - }.execute((Void[]) null); - } - - public static void doAsync(final Context pContext, final int pTitleResID, final int pMessageResID, final AsyncCallable pAsyncCallable, final Callback pCallback, final Callback pExceptionCallback) { - final ProgressDialog pd = ProgressDialog.show(pContext, pContext.getString(pTitleResID), pContext.getString(pMessageResID)); - pAsyncCallable.call(new Callback() { - @Override - public void onCallback(final T result) { - try { - pd.dismiss(); - } catch (final Exception e) { - Debug.e("Error", e); - /* Nothing. */ - } - - pCallback.onCallback(result); - } - }, pExceptionCallback); - } - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + // =========================================================== + // Constructors + // =========================================================== + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + public static void requestFullscreen(final Activity pActivity) { + final Window window = pActivity.getWindow(); + window.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); + window.clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN); + window.requestFeature(Window.FEATURE_NO_TITLE); + } + + /** + * @param pActivity + * @param pScreenBrightness [0..1] + */ + public static 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) { + pActivity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); + } + + public static void doAsync(final Context pContext, final int pTitleResID, final int pMessageResID, final Callable pCallable, final Callback pCallback) { + ActivityUtils.doAsync(pContext, pTitleResID, pMessageResID, pCallable, pCallback, null, false); + } + + public static 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 pTitleResID, final int pMessageResID, final Callable pCallable, final Callback pCallback, final boolean pCancelable) { + ActivityUtils.doAsync(pContext, pTitleResID, pMessageResID, 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) { + ActivityUtils.doAsync(pContext, pTitle, pMessage, pCallable, pCallback, null, pCancelable); + } + + public static void doAsync(final Context pContext, final int pTitleResID, final int pMessageResID, final Callable pCallable, final Callback pCallback, final Callback pExceptionCallback) { + ActivityUtils.doAsync(pContext, pTitleResID, pMessageResID, 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) { + ActivityUtils.doAsync(pContext, pTitle, pMessage, pCallable, pCallback, pExceptionCallback, false); + } + + public static void doAsync(final Context pContext, final int pTitleResID, final int pMessageResID, final Callable pCallable, final Callback pCallback, final Callback pExceptionCallback, final boolean pCancelable) { + ActivityUtils.doAsync(pContext, pContext.getString(pTitleResID), pContext.getString(pMessageResID), 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() { + private ProgressDialog mPD; + private Exception mException = null; + + @Override + public void onPreExecute() { + this.mPD = ProgressDialog.show(pContext, pTitle, pMessage, true, pCancelable); + if(pCancelable) { + this.mPD.setOnCancelListener(new OnCancelListener() { + @Override + public void onCancel(final DialogInterface pDialogInterface) { + pExceptionCallback.onCallback(new CancelledException()); + pDialogInterface.dismiss(); + } + }); + } + super.onPreExecute(); + } + + @Override + public T doInBackground(final Void... params) { + try { + return pCallable.call(); + } catch (final Exception e) { + this.mException = e; + } + return null; + } + + @Override + public void onPostExecute(final T result) { + try { + this.mPD.dismiss(); + } catch (final Exception e) { + Debug.e("Error", e); + } + + if(this.isCancelled()) { + this.mException = new CancelledException(); + } + + if(this.mException == null) { + pCallback.onCallback(result); + } else { + if(pExceptionCallback == null) { + Debug.e("Error", this.mException); + } else { + pExceptionCallback.onCallback(this.mException); + } + } + + super.onPostExecute(result); + } + }.execute((Void[]) null); + } + + public static void doProgressAsync(final Context pContext, final int pTitleResID, final ProgressCallable pCallable, final Callback pCallback) { + ActivityUtils.doProgressAsync(pContext, pTitleResID, pCallable, pCallback, null); + } + + public static void doProgressAsync(final Context pContext, final int pTitleResID, final ProgressCallable pCallable, final Callback pCallback, final Callback pExceptionCallback) { + new AsyncTask() { + private ProgressDialog mPD; + private Exception mException = null; + + @Override + public void onPreExecute() { + this.mPD = new ProgressDialog(pContext); + this.mPD.setTitle(pTitleResID); + this.mPD.setIcon(android.R.drawable.ic_menu_save); + this.mPD.setIndeterminate(false); + this.mPD.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); + this.mPD.show(); + super.onPreExecute(); + } + + @Override + public T doInBackground(final Void... params) { + try { + return pCallable.call(new IProgressListener() { + @Override + public void onProgressChanged(final int pProgress) { + onProgressUpdate(pProgress); + } + }); + } catch (final Exception e) { + this.mException = e; + } + return null; + } + + @Override + public void onProgressUpdate(final Integer... values) { + this.mPD.setProgress(values[0]); + } + + @Override + public void onPostExecute(final T result) { + try { + this.mPD.dismiss(); + } catch (final Exception e) { + Debug.e("Error", e); + /* Nothing. */ + } + + if(this.isCancelled()) { + this.mException = new CancelledException(); + } + + if(this.mException == null) { + pCallback.onCallback(result); + } else { + if(pExceptionCallback == null) { + Debug.e("Error", this.mException); + } else { + pExceptionCallback.onCallback(this.mException); + } + } + + super.onPostExecute(result); + } + }.execute((Void[]) null); + } + + public static void doAsync(final Context pContext, final int pTitleResID, final int pMessageResID, final AsyncCallable pAsyncCallable, final Callback pCallback, final Callback pExceptionCallback) { + final ProgressDialog pd = ProgressDialog.show(pContext, pContext.getString(pTitleResID), pContext.getString(pMessageResID)); + pAsyncCallable.call(new Callback() { + @Override + public void onCallback(final T result) { + try { + pd.dismiss(); + } catch (final Exception e) { + Debug.e("Error", e); + /* Nothing. */ + } + + pCallback.onCallback(result); + } + }, pExceptionCallback); + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/util/ArrayUtils.java b/AndEngine/src/org/anddev/andengine/util/ArrayUtils.java index 1e43c6de..a389af02 100644 --- a/AndEngine/src/org/anddev/andengine/util/ArrayUtils.java +++ b/AndEngine/src/org/anddev/andengine/util/ArrayUtils.java @@ -8,167 +8,167 @@ * @since 22:35:42 - 01.05.2011 */ public class ArrayUtils { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - public static T random(final T[] pArray) { - return pArray[MathUtils.random(0, pArray.length - 1)]; - } - - public static void reverse(final byte[] pArray) { - if (pArray == null) { - return; - } - int i = 0; - int j = pArray.length - 1; - byte tmp; - while (j > i) { - tmp = pArray[j]; - pArray[j] = pArray[i]; - pArray[i] = tmp; - j--; - i++; - } - } + public static T random(final T[] pArray) { + return pArray[MathUtils.random(0, pArray.length - 1)]; + } + + public static void reverse(final byte[] pArray) { + if (pArray == null) { + return; + } + int i = 0; + int j = pArray.length - 1; + byte tmp; + while (j > i) { + tmp = pArray[j]; + pArray[j] = pArray[i]; + pArray[i] = tmp; + j--; + i++; + } + } - public static void reverse(final short[] pArray) { - if (pArray == null) { - return; - } - int i = 0; - int j = pArray.length - 1; - short tmp; - while (j > i) { - tmp = pArray[j]; - pArray[j] = pArray[i]; - pArray[i] = tmp; - j--; - i++; - } - } + public static void reverse(final short[] pArray) { + if (pArray == null) { + return; + } + int i = 0; + int j = pArray.length - 1; + short tmp; + while (j > i) { + tmp = pArray[j]; + pArray[j] = pArray[i]; + pArray[i] = tmp; + j--; + i++; + } + } - public static void reverse(final int[] pArray) { - if (pArray == null) { - return; - } - int i = 0; - int j = pArray.length - 1; - int tmp; - while (j > i) { - tmp = pArray[j]; - pArray[j] = pArray[i]; - pArray[i] = tmp; - j--; - i++; - } - } + public static void reverse(final int[] pArray) { + if (pArray == null) { + return; + } + int i = 0; + int j = pArray.length - 1; + int tmp; + while (j > i) { + tmp = pArray[j]; + pArray[j] = pArray[i]; + pArray[i] = tmp; + j--; + i++; + } + } - public static void reverse(final long[] pArray) { - if (pArray == null) { - return; - } - int i = 0; - int j = pArray.length - 1; - long tmp; - while (j > i) { - tmp = pArray[j]; - pArray[j] = pArray[i]; - pArray[i] = tmp; - j--; - i++; - } - } + public static void reverse(final long[] pArray) { + if (pArray == null) { + return; + } + int i = 0; + int j = pArray.length - 1; + long tmp; + while (j > i) { + tmp = pArray[j]; + pArray[j] = pArray[i]; + pArray[i] = tmp; + j--; + i++; + } + } - public static void reverse(final float[] pArray) { - if (pArray == null) { - return; - } - int i = 0; - int j = pArray.length - 1; - float tmp; - while (j > i) { - tmp = pArray[j]; - pArray[j] = pArray[i]; - pArray[i] = tmp; - j--; - i++; - } - } + public static void reverse(final float[] pArray) { + if (pArray == null) { + return; + } + int i = 0; + int j = pArray.length - 1; + float tmp; + while (j > i) { + tmp = pArray[j]; + pArray[j] = pArray[i]; + pArray[i] = tmp; + j--; + i++; + } + } - public static void reverse(final double[] pArray) { - if (pArray == null) { - return; - } - int i = 0; - int j = pArray.length - 1; - double tmp; - while (j > i) { - tmp = pArray[j]; - pArray[j] = pArray[i]; - pArray[i] = tmp; - j--; - i++; - } - } + public static void reverse(final double[] pArray) { + if (pArray == null) { + return; + } + int i = 0; + int j = pArray.length - 1; + double tmp; + while (j > i) { + tmp = pArray[j]; + pArray[j] = pArray[i]; + pArray[i] = tmp; + j--; + i++; + } + } - public static void reverse(final Object[] pArray) { - if (pArray == null) { - return; - } - int i = 0; - int j = pArray.length - 1; - Object tmp; - while (j > i) { - tmp = pArray[j]; - pArray[j] = pArray[i]; - pArray[i] = tmp; - j--; - i++; - } - } - - public static 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) { - throw new ArrayIndexOutOfBoundsException(pArrayA.length); - } - - final int lastIndexB = pOffsetB + pLength; - if(lastIndexB > pArrayB.length) { - throw new ArrayIndexOutOfBoundsException(pArrayB.length); - } - - for(int a = pOffsetA, b = pOffsetB; a < lastIndexA; a++, b++) { - if(pArrayA[a] != pArrayB[b]) { - return false; - } - } - - return true; - } + public static void reverse(final Object[] pArray) { + if (pArray == null) { + return; + } + int i = 0; + int j = pArray.length - 1; + Object tmp; + while (j > i) { + tmp = pArray[j]; + pArray[j] = pArray[i]; + pArray[i] = tmp; + j--; + i++; + } + } + + public static 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) { + throw new ArrayIndexOutOfBoundsException(pArrayA.length); + } + + final int lastIndexB = pOffsetB + pLength; + if(lastIndexB > pArrayB.length) { + throw new ArrayIndexOutOfBoundsException(pArrayB.length); + } + + for(int a = pOffsetA, b = pOffsetB; a < lastIndexA; a++, b++) { + if(pArrayA[a] != pArrayB[b]) { + return false; + } + } + + return true; + } - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/util/AsyncCallable.java b/AndEngine/src/org/anddev/andengine/util/AsyncCallable.java index 9c762870..1103060e 100644 --- a/AndEngine/src/org/anddev/andengine/util/AsyncCallable.java +++ b/AndEngine/src/org/anddev/andengine/util/AsyncCallable.java @@ -9,20 +9,20 @@ * @param */ public interface AsyncCallable { - // =========================================================== - // Final Fields - // =========================================================== + // =========================================================== + // Final Fields + // =========================================================== - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - /** - * Computes a result asynchronously, return values and exceptions are to be handled through the callbacks. - * This method is expected to return almost immediately, after starting a {@link Thread} or similar. - * - * @return computed result - * @throws Exception if unable to compute a result - */ - public void call(final Callback pCallback, final Callback pExceptionCallback); -} \ No newline at end of file + /** + * Computes a result asynchronously, return values and exceptions are to be handled through the callbacks. + * This method is expected to return almost immediately, after starting a {@link Thread} or similar. + * + * @return computed result + * @throws Exception if unable to compute a result + */ + public void call(final Callback pCallback, final Callback pExceptionCallback); +} diff --git a/AndEngine/src/org/anddev/andengine/util/Base64.java b/AndEngine/src/org/anddev/andengine/util/Base64.java index 58888310..f59c5c5c 100644 --- a/AndEngine/src/org/anddev/andengine/util/Base64.java +++ b/AndEngine/src/org/anddev/andengine/util/Base64.java @@ -25,735 +25,735 @@ * href="http://www.ietf.org/rfc/rfc3548.txt">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 + /** + * 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/AndEngine/src/org/anddev/andengine/util/Base64InputStream.java b/AndEngine/src/org/anddev/andengine/util/Base64InputStream.java index 2fcb7728..0b23f3ac 100644 --- a/AndEngine/src/org/anddev/andengine/util/Base64InputStream.java +++ b/AndEngine/src/org/anddev/andengine/util/Base64InputStream.java @@ -25,139 +25,139 @@ * 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; - } + 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/AndEngine/src/org/anddev/andengine/util/BetaUtils.java b/AndEngine/src/org/anddev/andengine/util/BetaUtils.java index 3475326e..eeb34e83 100644 --- a/AndEngine/src/org/anddev/andengine/util/BetaUtils.java +++ b/AndEngine/src/org/anddev/andengine/util/BetaUtils.java @@ -22,78 +22,78 @@ * @since 22:43:32 - 02.11.2010 */ public class BetaUtils implements Constants { - // =========================================================== - // Constants - // =========================================================== - - private static final String PREFERENCES_BETAUTILS_ID = "preferences.betautils.lastuse"; - - // =========================================================== - // Fields - // =========================================================== - - // =========================================================== - // Constructors - // =========================================================== - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods from SuperClass/Interfaces - // =========================================================== - - // =========================================================== - // Methods - // =========================================================== - - public static boolean finishWhenExpired(final Activity pActivity, final GregorianCalendar pExpirationDate, final int pTitleResourceID, final int pMessageResourceID) { - return BetaUtils.finishWhenExpired(pActivity, pExpirationDate, pTitleResourceID, pMessageResourceID, null, null); - } - - public static boolean finishWhenExpired(final Activity pActivity, final GregorianCalendar pExpirationDate, final int pTitleResourceID, final int pMessageResourceID, final Intent pOkIntent, final Intent pCancelIntent) { - final SharedPreferences spref = SimplePreferences.getInstance(pActivity); - - final long now = System.currentTimeMillis(); - final long lastuse = Math.max(now, spref.getLong(PREFERENCES_BETAUTILS_ID, -1)); - spref.edit().putLong(PREFERENCES_BETAUTILS_ID, lastuse).commit(); - - final GregorianCalendar lastuseDate = new GregorianCalendar(); - lastuseDate.setTimeInMillis(lastuse); - - if(lastuseDate.after(pExpirationDate)){ - final Builder alertDialogBuilder = new AlertDialog.Builder(pActivity) - .setTitle(pTitleResourceID) - .setIcon(R.drawable.ic_dialog_alert) - .setMessage(pMessageResourceID); - - alertDialogBuilder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener(){ - @Override - public void onClick(final DialogInterface pDialog, final int pWhich) { - if(pOkIntent != null) { - pActivity.startActivity(pOkIntent); - } - pActivity.finish(); - } - }); - alertDialogBuilder.setNegativeButton(android.R.string.cancel, new OnClickListener() { - @Override - public void onClick(final DialogInterface pDialog, final int pWhich) { - if(pCancelIntent != null) { - pActivity.startActivity(pCancelIntent); - } - pActivity.finish(); - } - }) - .create().show(); - return true; - }else{ - return false; - } - } - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + private static final String PREFERENCES_BETAUTILS_ID = "preferences.betautils.lastuse"; + + // =========================================================== + // Fields + // =========================================================== + + // =========================================================== + // Constructors + // =========================================================== + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods from SuperClass/Interfaces + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + public static boolean finishWhenExpired(final Activity pActivity, final GregorianCalendar pExpirationDate, final int pTitleResourceID, final int pMessageResourceID) { + return BetaUtils.finishWhenExpired(pActivity, pExpirationDate, pTitleResourceID, pMessageResourceID, null, null); + } + + public static boolean finishWhenExpired(final Activity pActivity, final GregorianCalendar pExpirationDate, final int pTitleResourceID, final int pMessageResourceID, final Intent pOkIntent, final Intent pCancelIntent) { + final SharedPreferences spref = SimplePreferences.getInstance(pActivity); + + final long now = System.currentTimeMillis(); + final long lastuse = Math.max(now, spref.getLong(PREFERENCES_BETAUTILS_ID, -1)); + spref.edit().putLong(PREFERENCES_BETAUTILS_ID, lastuse).commit(); + + final GregorianCalendar lastuseDate = new GregorianCalendar(); + lastuseDate.setTimeInMillis(lastuse); + + if(lastuseDate.after(pExpirationDate)){ + final Builder alertDialogBuilder = new AlertDialog.Builder(pActivity) + .setTitle(pTitleResourceID) + .setIcon(R.drawable.ic_dialog_alert) + .setMessage(pMessageResourceID); + + alertDialogBuilder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener(){ + @Override + public void onClick(final DialogInterface pDialog, final int pWhich) { + if(pOkIntent != null) { + pActivity.startActivity(pOkIntent); + } + pActivity.finish(); + } + }); + alertDialogBuilder.setNegativeButton(android.R.string.cancel, new OnClickListener() { + @Override + public void onClick(final DialogInterface pDialog, final int pWhich) { + if(pCancelIntent != null) { + pActivity.startActivity(pCancelIntent); + } + pActivity.finish(); + } + }) + .create().show(); + return true; + }else{ + return false; + } + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/util/ByteBufferOutputStream.java b/AndEngine/src/org/anddev/andengine/util/ByteBufferOutputStream.java index 036d26d6..33c9c6cc 100644 --- a/AndEngine/src/org/anddev/andengine/util/ByteBufferOutputStream.java +++ b/AndEngine/src/org/anddev/andengine/util/ByteBufferOutputStream.java @@ -13,92 +13,92 @@ * @since 02:19:02 - 14.08.2011 */ public class ByteBufferOutputStream extends OutputStream { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - protected final int mMaximumGrow; - - protected byte[] mData; - protected int mCount; - - // =========================================================== - // Constructors - // =========================================================== - - public ByteBufferOutputStream(final int pInitialCapacity, final int pMaximumGrow) { - this.mMaximumGrow = pMaximumGrow; - this.mData = new byte[pInitialCapacity]; - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - public void write(final int pByte) { - this.ensureCapacity(this.mCount + 1); - this.mData[this.mCount] = (byte) pByte; - this.mCount += 1; - } - - @Override - public void write(final byte[] pData, final int pOffset, final int pLength) { - this.ensureCapacity(this.mCount + pLength); - System.arraycopy(pData, pOffset, this.mData, this.mCount, pLength); - this.mCount += pLength; - } - - @Override - public void close() throws IOException { - - } - - // =========================================================== - // Methods - // =========================================================== - - private void ensureCapacity(final int pDesiredCapacity) { - if(pDesiredCapacity - this.mData.length > 0) { - this.grow(pDesiredCapacity); - } - } - - private void grow(final int pDesiredCapacity) { - final int oldCapacity = this.mData.length; - final int grow = Math.min(this.mMaximumGrow, oldCapacity); - Debug.d("Growing by: " + grow); - int newCapacity = oldCapacity + grow; - - if(newCapacity - pDesiredCapacity < 0) { - newCapacity = pDesiredCapacity; - } - if(newCapacity < 0) { - if(pDesiredCapacity < 0) { - throw new OutOfMemoryError(); - } else { - newCapacity = Integer.MAX_VALUE; - } - } - - final byte[] data = new byte[newCapacity]; - System.arraycopy(this.mData, 0, data, 0, this.mCount); - this.mData = data; - } - - public ByteBuffer toByteBuffer() { - return ByteBuffer.wrap(this.mData, 0, this.mCount).slice(); - } - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== -} \ No newline at end of file + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + protected final int mMaximumGrow; + + protected byte[] mData; + protected int mCount; + + // =========================================================== + // Constructors + // =========================================================== + + public ByteBufferOutputStream(final int pInitialCapacity, final int pMaximumGrow) { + this.mMaximumGrow = pMaximumGrow; + this.mData = new byte[pInitialCapacity]; + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + public void write(final int pByte) { + this.ensureCapacity(this.mCount + 1); + this.mData[this.mCount] = (byte) pByte; + this.mCount += 1; + } + + @Override + public void write(final byte[] pData, final int pOffset, final int pLength) { + this.ensureCapacity(this.mCount + pLength); + System.arraycopy(pData, pOffset, this.mData, this.mCount, pLength); + this.mCount += pLength; + } + + @Override + public void close() throws IOException { + + } + + // =========================================================== + // Methods + // =========================================================== + + private void ensureCapacity(final int pDesiredCapacity) { + if(pDesiredCapacity - this.mData.length > 0) { + this.grow(pDesiredCapacity); + } + } + + private void grow(final int pDesiredCapacity) { + final int oldCapacity = this.mData.length; + final int grow = Math.min(this.mMaximumGrow, oldCapacity); + Debug.d("Growing by: " + grow); + int newCapacity = oldCapacity + grow; + + if(newCapacity - pDesiredCapacity < 0) { + newCapacity = pDesiredCapacity; + } + if(newCapacity < 0) { + if(pDesiredCapacity < 0) { + throw new OutOfMemoryError(); + } else { + newCapacity = Integer.MAX_VALUE; + } + } + + final byte[] data = new byte[newCapacity]; + System.arraycopy(this.mData, 0, data, 0, this.mCount); + this.mData = data; + } + + public ByteBuffer toByteBuffer() { + return ByteBuffer.wrap(this.mData, 0, this.mCount).slice(); + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== +} diff --git a/AndEngine/src/org/anddev/andengine/util/Callable.java b/AndEngine/src/org/anddev/andengine/util/Callable.java index 28333eed..b87c05c8 100644 --- a/AndEngine/src/org/anddev/andengine/util/Callable.java +++ b/AndEngine/src/org/anddev/andengine/util/Callable.java @@ -8,19 +8,19 @@ * @since 20:52:44 - 03.01.2010 */ public interface Callable { - // =========================================================== - // Final Fields - // =========================================================== + // =========================================================== + // Final Fields + // =========================================================== - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - /** - * Computes a result, or throws an exception if unable to do so. - * - * @return the computed result. - * @throws Exception if unable to compute a result. - */ - public T call() throws Exception; -} \ No newline at end of file + /** + * Computes a result, or throws an exception if unable to do so. + * + * @return the computed result. + * @throws Exception if unable to compute a result. + */ + public T call() throws Exception; +} diff --git a/AndEngine/src/org/anddev/andengine/util/Callback.java b/AndEngine/src/org/anddev/andengine/util/Callback.java index 56a5bd4b..e9bdf715 100644 --- a/AndEngine/src/org/anddev/andengine/util/Callback.java +++ b/AndEngine/src/org/anddev/andengine/util/Callback.java @@ -8,13 +8,13 @@ * @since 09:40:55 - 14.12.2009S */ public interface Callback { - // =========================================================== - // Final Fields - // =========================================================== + // =========================================================== + // Final Fields + // =========================================================== - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - public void onCallback(final T pCallbackValue); -} \ No newline at end of file + public void onCallback(final T pCallbackValue); +} diff --git a/AndEngine/src/org/anddev/andengine/util/ColorUtils.java b/AndEngine/src/org/anddev/andengine/util/ColorUtils.java index 8bc94e48..c8424b39 100644 --- a/AndEngine/src/org/anddev/andengine/util/ColorUtils.java +++ b/AndEngine/src/org/anddev/andengine/util/ColorUtils.java @@ -10,54 +10,54 @@ * @since 11:13:45 - 04.08.2010 */ public class ColorUtils { - // =========================================================== - // Constants - // =========================================================== - - private static final float[] HSV_TO_COLOR = new float[3]; - private static final int HSV_TO_COLOR_HUE_INDEX = 0; - private static final int HSV_TO_COLOR_SATURATION_INDEX = 1; - private static final int HSV_TO_COLOR_VALUE_INDEX = 2; - - private static final int COLOR_FLOAT_TO_INT_FACTOR = 255; - - // =========================================================== - // Fields - // =========================================================== - - // =========================================================== - // Constructors - // =========================================================== - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - /** - * @param pHue [0 .. 360) - * @param pSaturation [0...1] - * @param pValue [0...1] - */ - public static int HSVToColor(final float pHue, final float pSaturation, final float pValue) { - HSV_TO_COLOR[HSV_TO_COLOR_HUE_INDEX] = pHue; - HSV_TO_COLOR[HSV_TO_COLOR_SATURATION_INDEX] = pSaturation; - HSV_TO_COLOR[HSV_TO_COLOR_VALUE_INDEX] = pValue; - return Color.HSVToColor(HSV_TO_COLOR); - } - - public static int RGBToColor(final float pRed, final float pGreen, final float pBlue) { - return Color.rgb((int)(pRed * COLOR_FLOAT_TO_INT_FACTOR), (int)(pGreen * COLOR_FLOAT_TO_INT_FACTOR), (int)(pBlue * COLOR_FLOAT_TO_INT_FACTOR)); - } - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + private static final float[] HSV_TO_COLOR = new float[3]; + private static final int HSV_TO_COLOR_HUE_INDEX = 0; + private static final int HSV_TO_COLOR_SATURATION_INDEX = 1; + private static final int HSV_TO_COLOR_VALUE_INDEX = 2; + + private static final int COLOR_FLOAT_TO_INT_FACTOR = 255; + + // =========================================================== + // Fields + // =========================================================== + + // =========================================================== + // Constructors + // =========================================================== + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + /** + * @param pHue [0 .. 360) + * @param pSaturation [0...1] + * @param pValue [0...1] + */ + public static int HSVToColor(final float pHue, final float pSaturation, final float pValue) { + HSV_TO_COLOR[HSV_TO_COLOR_HUE_INDEX] = pHue; + HSV_TO_COLOR[HSV_TO_COLOR_SATURATION_INDEX] = pSaturation; + HSV_TO_COLOR[HSV_TO_COLOR_VALUE_INDEX] = pValue; + return Color.HSVToColor(HSV_TO_COLOR); + } + + public static int RGBToColor(final float pRed, final float pGreen, final float pBlue) { + return Color.rgb((int)(pRed * COLOR_FLOAT_TO_INT_FACTOR), (int)(pGreen * COLOR_FLOAT_TO_INT_FACTOR), (int)(pBlue * COLOR_FLOAT_TO_INT_FACTOR)); + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/util/DataUtils.java b/AndEngine/src/org/anddev/andengine/util/DataUtils.java index 557a018f..0a1d18a4 100644 --- a/AndEngine/src/org/anddev/andengine/util/DataUtils.java +++ b/AndEngine/src/org/anddev/andengine/util/DataUtils.java @@ -10,35 +10,35 @@ * @since 15:01:49 - 20.03.2011 */ public class DataUtils implements DataConstants { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - public static int unsignedByteToInt(final byte bByte) { - return bByte & 0xFF; - } + public static int unsignedByteToInt(final byte bByte) { + return bByte & 0xFF; + } - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/util/Debug.java b/AndEngine/src/org/anddev/andengine/util/Debug.java index 99f0296c..51d07bc7 100644 --- a/AndEngine/src/org/anddev/andengine/util/Debug.java +++ b/AndEngine/src/org/anddev/andengine/util/Debug.java @@ -13,146 +13,146 @@ * @since 13:29:16 - 08.03.2010 */ public class Debug implements Constants { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - private static String sDebugTag = DEBUGTAG; - private static DebugLevel sDebugLevel = DebugLevel.VERBOSE; - - // =========================================================== - // Constructors - // =========================================================== - - // =========================================================== - // Getter & Setter - // =========================================================== - - public static String getDebugTag() { - return Debug.sDebugTag; - } - - public static void setDebugTag(final String pDebugTag) { - Debug.sDebugTag = pDebugTag; - } - - public static DebugLevel getDebugLevel() { - return Debug.sDebugLevel; - } - - public static void setDebugLevel(final DebugLevel pDebugLevel) { - if(pDebugLevel == null) { - throw new IllegalArgumentException("pDebugLevel must not be null!"); - } - Debug.sDebugLevel = pDebugLevel; - } - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - // =========================================================== - // Methods - // =========================================================== - - public static void v(final String pMessage) { - if(!BuildConfig.DEBUG) return; - Debug.v(pMessage, null); - } - - public static void v(final String pMessage, final Throwable pThrowable) { - if(!BuildConfig.DEBUG) return; - if(sDebugLevel.isSameOrLessThan(DebugLevel.VERBOSE)) { - Log.v(sDebugTag, pMessage, pThrowable); - } - } - - public static void d(final String pMessage) { - if(!BuildConfig.DEBUG) return; - Debug.d(pMessage, null); - } - - public static void d(final String pMessage, final Throwable pThrowable) { - if(!BuildConfig.DEBUG) return; - if(sDebugLevel.isSameOrLessThan(DebugLevel.DEBUG)) { - Log.d(sDebugTag, pMessage, pThrowable); - } - } - - public static void i(final String pMessage) { - if(!BuildConfig.DEBUG) return; - Debug.i(pMessage, null); - } - - public static void i(final String pMessage, final Throwable pThrowable) { - if(!BuildConfig.DEBUG) return; - if(sDebugLevel.isSameOrLessThan(DebugLevel.INFO)) { - Log.i(sDebugTag, pMessage, pThrowable); - } - } - - public static void w(final String pMessage) { - if(!BuildConfig.DEBUG) return; - Debug.w(pMessage, null); - } - - public static void w(final Throwable pThrowable) { - if(!BuildConfig.DEBUG) return; - Debug.w("", pThrowable); - } - - public static void w(final String pMessage, final Throwable pThrowable) { - if(!BuildConfig.DEBUG) return; - if(sDebugLevel.isSameOrLessThan(DebugLevel.WARNING)) { - if(pThrowable == null) { - Log.w(sDebugTag, pMessage, new Exception()); - } else { - Log.w(sDebugTag, pMessage, pThrowable); - } - } - } - - public static void e(final String pMessage) { - if(!BuildConfig.DEBUG) return; - Debug.e(pMessage, null); - } - - public static void e(final Throwable pThrowable) { - if(!BuildConfig.DEBUG) return; - Debug.e(sDebugTag, pThrowable); - } - - public static void e(final String pMessage, final Throwable pThrowable) { - if(!BuildConfig.DEBUG) return; - if(sDebugLevel.isSameOrLessThan(DebugLevel.ERROR)) { - if(pThrowable == null) { - Log.e(sDebugTag, pMessage, new Exception()); - } else { - Log.e(sDebugTag, pMessage, pThrowable); - } - } - } - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== - - public static enum DebugLevel implements Comparable { - NONE, - ERROR, - WARNING, - INFO, - DEBUG, - VERBOSE; - - public static final DebugLevel ALL = DebugLevel.VERBOSE; - - private boolean isSameOrLessThan(final DebugLevel pDebugLevel) { - return this.compareTo(pDebugLevel) >= 0; - } - } + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + private static String sDebugTag = DEBUGTAG; + private static DebugLevel sDebugLevel = DebugLevel.VERBOSE; + + // =========================================================== + // Constructors + // =========================================================== + + // =========================================================== + // Getter & Setter + // =========================================================== + + public static String getDebugTag() { + return Debug.sDebugTag; + } + + public static void setDebugTag(final String pDebugTag) { + Debug.sDebugTag = pDebugTag; + } + + public static DebugLevel getDebugLevel() { + return Debug.sDebugLevel; + } + + public static void setDebugLevel(final DebugLevel pDebugLevel) { + if(pDebugLevel == null) { + throw new IllegalArgumentException("pDebugLevel must not be null!"); + } + Debug.sDebugLevel = pDebugLevel; + } + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + public static void v(final String pMessage) { + if(!BuildConfig.DEBUG) return; + Debug.v(pMessage, null); + } + + public static void v(final String pMessage, final Throwable pThrowable) { + if(!BuildConfig.DEBUG) return; + if(sDebugLevel.isSameOrLessThan(DebugLevel.VERBOSE)) { + Log.v(sDebugTag, pMessage, pThrowable); + } + } + + public static void d(final String pMessage) { + if(!BuildConfig.DEBUG) return; + Debug.d(pMessage, null); + } + + public static void d(final String pMessage, final Throwable pThrowable) { + if(!BuildConfig.DEBUG) return; + if(sDebugLevel.isSameOrLessThan(DebugLevel.DEBUG)) { + Log.d(sDebugTag, pMessage, pThrowable); + } + } + + public static void i(final String pMessage) { + if(!BuildConfig.DEBUG) return; + Debug.i(pMessage, null); + } + + public static void i(final String pMessage, final Throwable pThrowable) { + if(!BuildConfig.DEBUG) return; + if(sDebugLevel.isSameOrLessThan(DebugLevel.INFO)) { + Log.i(sDebugTag, pMessage, pThrowable); + } + } + + public static void w(final String pMessage) { + if(!BuildConfig.DEBUG) return; + Debug.w(pMessage, null); + } + + public static void w(final Throwable pThrowable) { + if(!BuildConfig.DEBUG) return; + Debug.w("", pThrowable); + } + + public static void w(final String pMessage, final Throwable pThrowable) { + if(!BuildConfig.DEBUG) return; + if(sDebugLevel.isSameOrLessThan(DebugLevel.WARNING)) { + if(pThrowable == null) { + Log.w(sDebugTag, pMessage, new Exception()); + } else { + Log.w(sDebugTag, pMessage, pThrowable); + } + } + } + + public static void e(final String pMessage) { + if(!BuildConfig.DEBUG) return; + Debug.e(pMessage, null); + } + + public static void e(final Throwable pThrowable) { + if(!BuildConfig.DEBUG) return; + Debug.e(sDebugTag, pThrowable); + } + + public static void e(final String pMessage, final Throwable pThrowable) { + if(!BuildConfig.DEBUG) return; + if(sDebugLevel.isSameOrLessThan(DebugLevel.ERROR)) { + if(pThrowable == null) { + Log.e(sDebugTag, pMessage, new Exception()); + } else { + Log.e(sDebugTag, pMessage, pThrowable); + } + } + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== + + public static enum DebugLevel implements Comparable { + NONE, + ERROR, + WARNING, + INFO, + DEBUG, + VERBOSE; + + public static final DebugLevel ALL = DebugLevel.VERBOSE; + + private boolean isSameOrLessThan(final DebugLevel pDebugLevel) { + return this.compareTo(pDebugLevel) >= 0; + } + } } diff --git a/AndEngine/src/org/anddev/andengine/util/DialogUtils.java b/AndEngine/src/org/anddev/andengine/util/DialogUtils.java index 4c95e17e..d9fde4c9 100644 --- a/AndEngine/src/org/anddev/andengine/util/DialogUtils.java +++ b/AndEngine/src/org/anddev/andengine/util/DialogUtils.java @@ -11,35 +11,35 @@ * @since 13:04:09 - 12.05.2011 */ public class DialogUtils { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - public static void keepScreenOn(final Dialog pDialog) { - pDialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); - } + public static void keepScreenOn(final Dialog pDialog) { + pDialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); + } - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/util/FileUtils.java b/AndEngine/src/org/anddev/andengine/util/FileUtils.java index e3ad1891..bfc515af 100644 --- a/AndEngine/src/org/anddev/andengine/util/FileUtils.java +++ b/AndEngine/src/org/anddev/andengine/util/FileUtils.java @@ -19,160 +19,160 @@ * @since 13:53:33 - 20.06.2010 */ public class FileUtils { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - // =========================================================== - // Constructors - // =========================================================== - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - // =========================================================== - // Methods - // =========================================================== - - public static void copyToExternalStorage(final Context pContext, final int pSourceResourceID, final String pFilename) throws FileNotFoundException { - FileUtils.copyToExternalStorage(pContext, pContext.getResources().openRawResource(pSourceResourceID), pFilename); - } - - public static void copyToInternalStorage(final Context pContext, final int pSourceResourceID, final String pFilename) throws FileNotFoundException { - FileUtils.copyToInternalStorage(pContext, pContext.getResources().openRawResource(pSourceResourceID), pFilename); - } - - public static void copyToExternalStorage(final Context pContext, final String pSourceAssetPath, final String pFilename) throws IOException { - FileUtils.copyToExternalStorage(pContext, pContext.getAssets().open(pSourceAssetPath), pFilename); - } - - public static void copyToInternalStorage(final Context pContext, final String pSourceAssetPath, final String pFilename) throws IOException { - FileUtils.copyToInternalStorage(pContext, pContext.getAssets().open(pSourceAssetPath), pFilename); - } - - private static void copyToInternalStorage(final Context pContext, final InputStream pInputStream, final String pFilename) throws FileNotFoundException { - StreamUtils.copyAndClose(pInputStream, new FileOutputStream(new File(pContext.getFilesDir(), pFilename))); - } - - public static void copyToExternalStorage(final Context pContext, final InputStream pInputStream, final String pFilePath) throws FileNotFoundException { - if (FileUtils.isExternalStorageWriteable()) { - final String absoluteFilePath = FileUtils.getAbsolutePathOnExternalStorage(pContext, pFilePath); - StreamUtils.copyAndClose(pInputStream, new FileOutputStream(absoluteFilePath)); - } else { - throw new IllegalStateException("External Storage is not writeable."); - } - } - - public static boolean isFileExistingOnExternalStorage(final Context pContext, final String pFilePath) { - if (FileUtils.isExternalStorageReadable()) { - final String absoluteFilePath = FileUtils.getAbsolutePathOnExternalStorage(pContext, pFilePath); - final File file = new File(absoluteFilePath); - return file.exists()&& file.isFile(); - } else { - throw new IllegalStateException("External Storage is not readable."); - } - } - - public static boolean isDirectoryExistingOnExternalStorage(final Context pContext, final String pDirectory) { - if (FileUtils.isExternalStorageReadable()) { - final String absoluteFilePath = FileUtils.getAbsolutePathOnExternalStorage(pContext, pDirectory); - final File file = new File(absoluteFilePath); - return file.exists() && file.isDirectory(); - } else { - throw new IllegalStateException("External Storage is not readable."); - } - } - - public static boolean ensureDirectoriesExistOnExternalStorage(final Context pContext, final String pDirectory) { - if(FileUtils.isDirectoryExistingOnExternalStorage(pContext, pDirectory)) { - return true; - } - - if (FileUtils.isExternalStorageWriteable()) { - final String absoluteDirectoryPath = FileUtils.getAbsolutePathOnExternalStorage(pContext, pDirectory); - return new File(absoluteDirectoryPath).mkdirs(); - } else { - throw new IllegalStateException("External Storage is not writeable."); - } - } - - public static InputStream openOnExternalStorage(final Context pContext, final String pFilePath) throws FileNotFoundException { - final String absoluteFilePath = FileUtils.getAbsolutePathOnExternalStorage(pContext, pFilePath); - return new FileInputStream(absoluteFilePath); - } - - public static String[] getDirectoryListOnExternalStorage(final Context pContext, final String pFilePath) throws FileNotFoundException { - final String absoluteFilePath = FileUtils.getAbsolutePathOnExternalStorage(pContext, pFilePath); - return new File(absoluteFilePath).list(); - } - - public static String[] getDirectoryListOnExternalStorage(final Context pContext, final String pFilePath, final FilenameFilter pFilenameFilter) throws FileNotFoundException { - final String absoluteFilePath = FileUtils.getAbsolutePathOnExternalStorage(pContext, pFilePath); - return new File(absoluteFilePath).list(pFilenameFilter); - } - - public static String getAbsolutePathOnInternalStorage(final Context pContext, final String pFilePath) { - return pContext.getFilesDir().getAbsolutePath() + pFilePath; - } - - public static String getAbsolutePathOnExternalStorage(final Context pContext, final String pFilePath) { - return Environment.getExternalStorageDirectory() + "/Android/data/" + pContext.getApplicationInfo().packageName + "/files/" + pFilePath; - } - - public static boolean isExternalStorageWriteable() { - return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED); - } - - public static boolean isExternalStorageReadable() { - final String state = Environment.getExternalStorageState(); - return state.equals(Environment.MEDIA_MOUNTED) || state.equals(Environment.MEDIA_MOUNTED_READ_ONLY); - } - - public static void copyFile(final File pIn, final File pOut) throws IOException { - final FileInputStream fis = new FileInputStream(pIn); - final FileOutputStream fos = new FileOutputStream(pOut); - try { - StreamUtils.copy(fis, fos); - } finally { - StreamUtils.close(fis); - StreamUtils.close(fos); - } - } - - /** - * 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. - * - * @param pFileOrDirectory - * @return - */ - public static boolean deleteDirectory(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) { - return false; - } - } - } - - // The directory is now empty so delete it - return pFileOrDirectory.delete(); - } - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + // =========================================================== + // Constructors + // =========================================================== + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + public static void copyToExternalStorage(final Context pContext, final int pSourceResourceID, final String pFilename) throws FileNotFoundException { + FileUtils.copyToExternalStorage(pContext, pContext.getResources().openRawResource(pSourceResourceID), pFilename); + } + + public static void copyToInternalStorage(final Context pContext, final int pSourceResourceID, final String pFilename) throws FileNotFoundException { + FileUtils.copyToInternalStorage(pContext, pContext.getResources().openRawResource(pSourceResourceID), pFilename); + } + + public static void copyToExternalStorage(final Context pContext, final String pSourceAssetPath, final String pFilename) throws IOException { + FileUtils.copyToExternalStorage(pContext, pContext.getAssets().open(pSourceAssetPath), pFilename); + } + + public static void copyToInternalStorage(final Context pContext, final String pSourceAssetPath, final String pFilename) throws IOException { + FileUtils.copyToInternalStorage(pContext, pContext.getAssets().open(pSourceAssetPath), pFilename); + } + + private static void copyToInternalStorage(final Context pContext, final InputStream pInputStream, final String pFilename) throws FileNotFoundException { + StreamUtils.copyAndClose(pInputStream, new FileOutputStream(new File(pContext.getFilesDir(), pFilename))); + } + + public static void copyToExternalStorage(final Context pContext, final InputStream pInputStream, final String pFilePath) throws FileNotFoundException { + if (FileUtils.isExternalStorageWriteable()) { + final String absoluteFilePath = FileUtils.getAbsolutePathOnExternalStorage(pContext, pFilePath); + StreamUtils.copyAndClose(pInputStream, new FileOutputStream(absoluteFilePath)); + } else { + throw new IllegalStateException("External Storage is not writeable."); + } + } + + public static boolean isFileExistingOnExternalStorage(final Context pContext, final String pFilePath) { + if (FileUtils.isExternalStorageReadable()) { + final String absoluteFilePath = FileUtils.getAbsolutePathOnExternalStorage(pContext, pFilePath); + final File file = new File(absoluteFilePath); + return file.exists()&& file.isFile(); + } else { + throw new IllegalStateException("External Storage is not readable."); + } + } + + public static boolean isDirectoryExistingOnExternalStorage(final Context pContext, final String pDirectory) { + if (FileUtils.isExternalStorageReadable()) { + final String absoluteFilePath = FileUtils.getAbsolutePathOnExternalStorage(pContext, pDirectory); + final File file = new File(absoluteFilePath); + return file.exists() && file.isDirectory(); + } else { + throw new IllegalStateException("External Storage is not readable."); + } + } + + public static boolean ensureDirectoriesExistOnExternalStorage(final Context pContext, final String pDirectory) { + if(FileUtils.isDirectoryExistingOnExternalStorage(pContext, pDirectory)) { + return true; + } + + if (FileUtils.isExternalStorageWriteable()) { + final String absoluteDirectoryPath = FileUtils.getAbsolutePathOnExternalStorage(pContext, pDirectory); + return new File(absoluteDirectoryPath).mkdirs(); + } else { + throw new IllegalStateException("External Storage is not writeable."); + } + } + + public static InputStream openOnExternalStorage(final Context pContext, final String pFilePath) throws FileNotFoundException { + final String absoluteFilePath = FileUtils.getAbsolutePathOnExternalStorage(pContext, pFilePath); + return new FileInputStream(absoluteFilePath); + } + + public static String[] getDirectoryListOnExternalStorage(final Context pContext, final String pFilePath) throws FileNotFoundException { + final String absoluteFilePath = FileUtils.getAbsolutePathOnExternalStorage(pContext, pFilePath); + return new File(absoluteFilePath).list(); + } + + public static String[] getDirectoryListOnExternalStorage(final Context pContext, final String pFilePath, final FilenameFilter pFilenameFilter) throws FileNotFoundException { + final String absoluteFilePath = FileUtils.getAbsolutePathOnExternalStorage(pContext, pFilePath); + return new File(absoluteFilePath).list(pFilenameFilter); + } + + public static String getAbsolutePathOnInternalStorage(final Context pContext, final String pFilePath) { + return pContext.getFilesDir().getAbsolutePath() + pFilePath; + } + + public static String getAbsolutePathOnExternalStorage(final Context pContext, final String pFilePath) { + return Environment.getExternalStorageDirectory() + "/Android/data/" + pContext.getApplicationInfo().packageName + "/files/" + pFilePath; + } + + public static boolean isExternalStorageWriteable() { + return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED); + } + + public static boolean isExternalStorageReadable() { + final String state = Environment.getExternalStorageState(); + return state.equals(Environment.MEDIA_MOUNTED) || state.equals(Environment.MEDIA_MOUNTED_READ_ONLY); + } + + public static void copyFile(final File pIn, final File pOut) throws IOException { + final FileInputStream fis = new FileInputStream(pIn); + final FileOutputStream fos = new FileOutputStream(pOut); + try { + StreamUtils.copy(fis, fos); + } finally { + StreamUtils.close(fis); + StreamUtils.close(fos); + } + } + + /** + * 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. + * + * @param pFileOrDirectory + * @return + */ + public static boolean deleteDirectory(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) { + return false; + } + } + } + + // The directory is now empty so delete it + return pFileOrDirectory.delete(); + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/util/HorizontalAlign.java b/AndEngine/src/org/anddev/andengine/util/HorizontalAlign.java index d70642ca..a077d907 100644 --- a/AndEngine/src/org/anddev/andengine/util/HorizontalAlign.java +++ b/AndEngine/src/org/anddev/andengine/util/HorizontalAlign.java @@ -8,39 +8,39 @@ * @since 10:47:33 - 11.05.2010 */ public enum HorizontalAlign { - // =========================================================== - // Elements - // =========================================================== + // =========================================================== + // Elements + // =========================================================== - LEFT, - CENTER, - RIGHT; + LEFT, + CENTER, + RIGHT; - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods from SuperClass/Interfaces + // =========================================================== - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/util/IMatcher.java b/AndEngine/src/org/anddev/andengine/util/IMatcher.java index cc1a29b5..7cdc51b6 100644 --- a/AndEngine/src/org/anddev/andengine/util/IMatcher.java +++ b/AndEngine/src/org/anddev/andengine/util/IMatcher.java @@ -8,14 +8,14 @@ * @since 12:32:22 - 26.12.2010 */ public interface IMatcher { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - public boolean matches(final T pObject); + public boolean matches(final T pObject); } diff --git a/AndEngine/src/org/anddev/andengine/util/Library.java b/AndEngine/src/org/anddev/andengine/util/Library.java index 25568452..adc3d581 100644 --- a/AndEngine/src/org/anddev/andengine/util/Library.java +++ b/AndEngine/src/org/anddev/andengine/util/Library.java @@ -11,58 +11,58 @@ * @param */ public class Library { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - protected final SparseArray mItems; + protected final SparseArray mItems; - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - public Library() { - this.mItems = new SparseArray(); - } + public Library() { + this.mItems = new SparseArray(); + } - public Library(final int pInitialCapacity) { - this.mItems = new SparseArray(pInitialCapacity); - } + public Library(final int pInitialCapacity) { + this.mItems = new SparseArray(pInitialCapacity); + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - public void put(final int pID, final T pItem) { - final T existingItem = this.mItems.get(pID); - if(existingItem == null) { - this.mItems.put(pID, pItem); - } else { - throw new IllegalArgumentException("ID: '" + pID + "' is already associated with item: '" + existingItem.toString() + "'."); - } - } + public void put(final int pID, final T pItem) { + final T existingItem = this.mItems.get(pID); + if(existingItem == null) { + this.mItems.put(pID, pItem); + } else { + throw new IllegalArgumentException("ID: '" + pID + "' is already associated with item: '" + existingItem.toString() + "'."); + } + } - public void remove(final int pID) { - this.mItems.remove(pID); - } + public void remove(final int pID) { + this.mItems.remove(pID); + } - public T get(final int pID) { - return this.mItems.get(pID); - } + public T get(final int pID) { + return this.mItems.get(pID); + } - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/util/ListUtils.java b/AndEngine/src/org/anddev/andengine/util/ListUtils.java index c941ab3c..f0a0ae02 100644 --- a/AndEngine/src/org/anddev/andengine/util/ListUtils.java +++ b/AndEngine/src/org/anddev/andengine/util/ListUtils.java @@ -10,46 +10,46 @@ * @since 12:43:39 - 11.03.2010 */ public class ListUtils { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - // =========================================================== - // Constructors - // =========================================================== - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - // =========================================================== - // Methods - // =========================================================== - - public static ArrayList toList(final T pItem) { - final ArrayList out = new ArrayList(); - out.add(pItem); - return out; - } - - public static ArrayList toList(final T ... pItems) { - final ArrayList out = new ArrayList(); - final int itemCount = pItems.length; - for(int i = 0; i < itemCount; i++) { - out.add(pItems[i]); - } - return out; - } - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + // =========================================================== + // Constructors + // =========================================================== + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + public static ArrayList toList(final T pItem) { + final ArrayList out = new ArrayList(); + out.add(pItem); + return out; + } + + public static ArrayList toList(final T ... pItems) { + final ArrayList out = new ArrayList(); + final int itemCount = pItems.length; + for(int i = 0; i < itemCount; i++) { + out.add(pItems[i]); + } + return out; + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/util/MathUtils.java b/AndEngine/src/org/anddev/andengine/util/MathUtils.java index e2f78c89..c61940f3 100644 --- a/AndEngine/src/org/anddev/andengine/util/MathUtils.java +++ b/AndEngine/src/org/anddev/andengine/util/MathUtils.java @@ -14,201 +14,201 @@ * @since 20:42:15 - 17.12.2009 */ public class MathUtils implements MathConstants { - // =========================================================== - // Constants - // =========================================================== - - public static final Random RANDOM = new Random(System.nanoTime()); - - // =========================================================== - // Fields - // =========================================================== - - // =========================================================== - // Constructors - // =========================================================== - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - // =========================================================== - // Methods - // =========================================================== - - public static float atan2(final float dY, final float dX) { - return (float)Math.atan2(dY, dX); - } - - public static final float radToDeg(final float pRad) { - return RAD_TO_DEG * pRad; - } - - public static final float degToRad(final float pDegree) { - return DEG_TO_RAD * pDegree; - } - - public static final int randomSign() { - if(RANDOM.nextBoolean()) { - return 1; - } else { - return -1; - } - } - - public static final float random(final float pMin, final float pMax) { - return pMin + RANDOM.nextFloat() * (pMax - pMin); - } - - /** - * @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); - } - - public static final boolean isPowerOfTwo(final int n) { - return (n != 0) && (n & (n - 1)) == 0; - } - - public static final int nextPowerOfTwo(final float f) { - return MathUtils.nextPowerOfTwo((int)(Math.ceil(f))); - } - - public static final int nextPowerOfTwo(final int n) { - int k = n; - - if (k == 0) { - return 1; - } - - k--; - - for (int i = 1; i < 32; i <<= 1) { - k = k | k >> i; - } - - return k + 1; - } - - public static final int sum(final int[] pValues) { - int sum = 0; - 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) { - final float rotationRad = MathUtils.degToRad(pRotation); - final float sinRotationRad = (float) Math.sin(rotationRad); - final float cosRotationInRad = (float) Math.cos(rotationRad); - - 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)); - } - } - 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; - } - } - - return pVertices; - } - - public static float[] rotateAndScaleAroundCenter(final float[] pVertices, final float pRotation, final float pRotationCenterX, final float pRotationCenterY, final float pScaleX, final float pScaleY, final float pScaleCenterX, final float pScaleCenterY) { - MathUtils.rotateAroundCenter(pVertices, pRotation, pRotationCenterX, pRotationCenterY); - return MathUtils.scaleAroundCenter(pVertices, pScaleX, pScaleY, pScaleCenterX, pScaleCenterY); - } - - public static float[] revertScaleAroundCenter(final float[] pVertices, final float pScaleX, final float pScaleY, final float pScaleCenterX, final float pScaleCenterY) { - return MathUtils.scaleAroundCenter(pVertices, 1 / pScaleX, 1 / pScaleY, pScaleCenterX, pScaleCenterY); - } - - public static float[] revertRotateAroundCenter(final float[] pVertices, final float pRotation, final float pRotationCenterX, final float pRotationCenterY) { - return MathUtils.rotateAroundCenter(pVertices, -pRotation, pRotationCenterX, pRotationCenterY); - } - - public static float[] revertRotateAndScaleAroundCenter(final float[] pVertices, final float pRotation, final float pRotationCenterX, final float pRotationCenterY, final float pScaleX, final float pScaleY, final float pScaleCenterX, final float pScaleCenterY) { - MathUtils.revertScaleAroundCenter(pVertices, pScaleX, pScaleY, pScaleCenterX, pScaleCenterY); - return MathUtils.revertRotateAroundCenter(pVertices, pRotation, pRotationCenterX, pRotationCenterY); - } - - public static int bringToBounds(final int pMinValue, final int pMaxValue, final int pValue) { - return Math.max(pMinValue, Math.min(pMaxValue, pValue)); - } - - public static float bringToBounds(final float pMinValue, final float pMaxValue, final float pValue) { - return Math.max(pMinValue, Math.min(pMaxValue, pValue)); - } - - public static 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 (float) Math.sqrt((dX * dX) + (dY * dY)); - } - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + public static final Random RANDOM = new Random(System.nanoTime()); + + // =========================================================== + // Fields + // =========================================================== + + // =========================================================== + // Constructors + // =========================================================== + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + public static float atan2(final float dY, final float dX) { + return (float)Math.atan2(dY, dX); + } + + public static final float radToDeg(final float pRad) { + return RAD_TO_DEG * pRad; + } + + public static final float degToRad(final float pDegree) { + return DEG_TO_RAD * pDegree; + } + + public static final int randomSign() { + if(RANDOM.nextBoolean()) { + return 1; + } else { + return -1; + } + } + + public static final float random(final float pMin, final float pMax) { + return pMin + RANDOM.nextFloat() * (pMax - pMin); + } + + /** + * @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); + } + + public static final boolean isPowerOfTwo(final int n) { + return (n != 0) && (n & (n - 1)) == 0; + } + + public static final int nextPowerOfTwo(final float f) { + return MathUtils.nextPowerOfTwo((int)(Math.ceil(f))); + } + + public static final int nextPowerOfTwo(final int n) { + int k = n; + + if (k == 0) { + return 1; + } + + k--; + + for (int i = 1; i < 32; i <<= 1) { + k = k | k >> i; + } + + return k + 1; + } + + public static final int sum(final int[] pValues) { + int sum = 0; + 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) { + final float rotationRad = MathUtils.degToRad(pRotation); + final float sinRotationRad = (float) Math.sin(rotationRad); + final float cosRotationInRad = (float) Math.cos(rotationRad); + + 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)); + } + } + 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; + } + } + + return pVertices; + } + + public static float[] rotateAndScaleAroundCenter(final float[] pVertices, final float pRotation, final float pRotationCenterX, final float pRotationCenterY, final float pScaleX, final float pScaleY, final float pScaleCenterX, final float pScaleCenterY) { + MathUtils.rotateAroundCenter(pVertices, pRotation, pRotationCenterX, pRotationCenterY); + return MathUtils.scaleAroundCenter(pVertices, pScaleX, pScaleY, pScaleCenterX, pScaleCenterY); + } + + public static float[] revertScaleAroundCenter(final float[] pVertices, final float pScaleX, final float pScaleY, final float pScaleCenterX, final float pScaleCenterY) { + return MathUtils.scaleAroundCenter(pVertices, 1 / pScaleX, 1 / pScaleY, pScaleCenterX, pScaleCenterY); + } + + public static float[] revertRotateAroundCenter(final float[] pVertices, final float pRotation, final float pRotationCenterX, final float pRotationCenterY) { + return MathUtils.rotateAroundCenter(pVertices, -pRotation, pRotationCenterX, pRotationCenterY); + } + + public static float[] revertRotateAndScaleAroundCenter(final float[] pVertices, final float pRotation, final float pRotationCenterX, final float pRotationCenterY, final float pScaleX, final float pScaleY, final float pScaleCenterX, final float pScaleCenterY) { + MathUtils.revertScaleAroundCenter(pVertices, pScaleX, pScaleY, pScaleCenterX, pScaleCenterY); + return MathUtils.revertRotateAroundCenter(pVertices, pRotation, pRotationCenterX, pRotationCenterY); + } + + public static int bringToBounds(final int pMinValue, final int pMaxValue, final int pValue) { + return Math.max(pMinValue, Math.min(pMaxValue, pValue)); + } + + public static float bringToBounds(final float pMinValue, final float pMaxValue, final float pValue) { + return Math.max(pMinValue, Math.min(pMaxValue, pValue)); + } + + public static 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 (float) Math.sqrt((dX * dX) + (dY * dY)); + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/util/MultiKey.java b/AndEngine/src/org/anddev/andengine/util/MultiKey.java index 2c4c7854..7108b829 100644 --- a/AndEngine/src/org/anddev/andengine/util/MultiKey.java +++ b/AndEngine/src/org/anddev/andengine/util/MultiKey.java @@ -10,85 +10,85 @@ * @since 16:54:24 - 07.11.2010 */ public class MultiKey { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - private final K[] mKeys; - private final int mCachedHashCode; - - // =========================================================== - // Constructors - // =========================================================== - - public MultiKey(final K... pKeys) { - this.mKeys = pKeys; - - this.mCachedHashCode = MultiKey.hash(pKeys); - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - public K[] getKeys() { - return this.mKeys; - } - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - public boolean equals(final Object pOther) { - if(pOther == this) { - return true; - } - if(pOther instanceof MultiKey) { - final MultiKey otherMultiKey = (MultiKey) pOther; - return Arrays.equals(this.mKeys, otherMultiKey.mKeys); - } - return false; - } - - public static int hash(final Object ... pKeys) { - int hashCode = 0; - for(final Object key : pKeys) { - if(key != null) { - hashCode ^= key.hashCode(); - } - } - return hashCode; - } - - - @Override - public int hashCode() { - return this.mCachedHashCode; - } - - @Override - public String toString() { - return "MultiKey" + Arrays.asList(this.mKeys).toString(); - } - - // =========================================================== - // Methods - // =========================================================== - - public K getKey(final int pIndex) { - return this.mKeys[pIndex]; - } - - public int size() { - return this.mKeys.length; - } - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + private final K[] mKeys; + private final int mCachedHashCode; + + // =========================================================== + // Constructors + // =========================================================== + + public MultiKey(final K... pKeys) { + this.mKeys = pKeys; + + this.mCachedHashCode = MultiKey.hash(pKeys); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + public K[] getKeys() { + return this.mKeys; + } + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + public boolean equals(final Object pOther) { + if(pOther == this) { + return true; + } + if(pOther instanceof MultiKey) { + final MultiKey otherMultiKey = (MultiKey) pOther; + return Arrays.equals(this.mKeys, otherMultiKey.mKeys); + } + return false; + } + + public static int hash(final Object ... pKeys) { + int hashCode = 0; + for(final Object key : pKeys) { + if(key != null) { + hashCode ^= key.hashCode(); + } + } + return hashCode; + } + + + @Override + public int hashCode() { + return this.mCachedHashCode; + } + + @Override + public String toString() { + return "MultiKey" + Arrays.asList(this.mKeys).toString(); + } + + // =========================================================== + // Methods + // =========================================================== + + public K getKey(final int pIndex) { + return this.mKeys[pIndex]; + } + + public int size() { + return this.mKeys.length; + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/util/MultiKeyHashMap.java b/AndEngine/src/org/anddev/andengine/util/MultiKeyHashMap.java index b9650634..f2b3c313 100644 --- a/AndEngine/src/org/anddev/andengine/util/MultiKeyHashMap.java +++ b/AndEngine/src/org/anddev/andengine/util/MultiKeyHashMap.java @@ -11,68 +11,68 @@ * @since 16:54:24 - 07.11.2010 */ public class MultiKeyHashMap extends HashMap, V> { - // =========================================================== - // Constants - // ========================================================== + // =========================================================== + // Constants + // ========================================================== - private static final long serialVersionUID = -6262447639526561122L; + private static final long serialVersionUID = -6262447639526561122L; - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - public V get(final K ... pKeys) { - final int hashCode = MultiKey.hash(pKeys); + public V get(final K ... pKeys) { + final int hashCode = MultiKey.hash(pKeys); - final Iterator, V>> it = this.entrySet().iterator(); - while(it.hasNext()) { - final Entry, V> entry = it.next(); - final MultiKey entryKey = entry.getKey(); - if (entryKey.hashCode() == hashCode && this.isEqualKey(entryKey.getKeys(), pKeys)) { - return entry.getValue(); - } - } - return null; - } + final Iterator, V>> it = this.entrySet().iterator(); + while(it.hasNext()) { + final Entry, V> entry = it.next(); + final MultiKey entryKey = entry.getKey(); + if (entryKey.hashCode() == hashCode && this.isEqualKey(entryKey.getKeys(), pKeys)) { + return entry.getValue(); + } + } + return null; + } - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - private boolean isEqualKey(final K[] pKeysA, final K[] pKeysB) { - if (pKeysA.length != pKeysB.length) { - return false; - } else { - for (int i = 0; i < pKeysA.length; i++) { - final K keyA = pKeysA[i]; - final K keyB = pKeysB[i]; - if(keyA == null) { - if(keyB != null) { - return false; - } - } else { - if(!keyA.equals(keyB)) { - return false; - } - } - } - } - return true; - } + private boolean isEqualKey(final K[] pKeysA, final K[] pKeysB) { + if (pKeysA.length != pKeysB.length) { + return false; + } else { + for (int i = 0; i < pKeysA.length; i++) { + final K keyA = pKeysA[i]; + final K keyB = pKeysB[i]; + if(keyA == null) { + if(keyB != null) { + return false; + } + } else { + if(!keyA.equals(keyB)) { + return false; + } + } + } + } + return true; + } - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/util/ParameterCallable.java b/AndEngine/src/org/anddev/andengine/util/ParameterCallable.java index 409c7096..7774afe7 100644 --- a/AndEngine/src/org/anddev/andengine/util/ParameterCallable.java +++ b/AndEngine/src/org/anddev/andengine/util/ParameterCallable.java @@ -8,13 +8,13 @@ * @since 23:40:42 - 27.12.2010 */ public interface ParameterCallable { - // =========================================================== - // Final Fields - // =========================================================== + // =========================================================== + // Final Fields + // =========================================================== - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - public void call(final T pParameter); -} \ No newline at end of file + public void call(final T pParameter); +} diff --git a/AndEngine/src/org/anddev/andengine/util/ProbabilityGenerator.java b/AndEngine/src/org/anddev/andengine/util/ProbabilityGenerator.java index 178d520a..27630324 100644 --- a/AndEngine/src/org/anddev/andengine/util/ProbabilityGenerator.java +++ b/AndEngine/src/org/anddev/andengine/util/ProbabilityGenerator.java @@ -10,107 +10,107 @@ * @since 16:54:24 - 07.11.2010 */ public class ProbabilityGenerator { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - private float mProbabilitySum; - private final ArrayList> mEntries = new ArrayList>(); - - // =========================================================== - // Constructors - // =========================================================== - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - // =========================================================== - // Methods - // =========================================================== - - public void add(final float pFactor, final T ... pElements){ - this.mProbabilitySum += pFactor; - this.mEntries.add(new Entry(pFactor, pElements)); - } - - public T next() { - float random = MathUtils.random(0, this.mProbabilitySum); - - final ArrayList> factors = this.mEntries; - - for(int i = factors.size() - 1; i >= 0; i--){ - final Entry entry = factors.get(i); - random -= entry.mFactor; - if(random <= 0){ - return entry.getReturnValue(); - } - } - - final Entry lastEntry = factors.get(factors.size() - 1); - return lastEntry.getReturnValue(); - } - - public void clear() { - this.mProbabilitySum = 0; - this.mEntries.clear(); - } - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== - - private static class Entry { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - public final float mFactor; - public final T[] mData; - - // =========================================================== - // Constructors - // =========================================================== - - public Entry(final float pFactor, final T[] pData){ - this.mFactor = pFactor; - this.mData = pData; - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - public T getReturnValue() { - if(this.mData.length == 1){ - return this.mData[0]; - }else{ - return ArrayUtils.random(mData); - } - } - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== - } + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + private float mProbabilitySum; + private final ArrayList> mEntries = new ArrayList>(); + + // =========================================================== + // Constructors + // =========================================================== + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + public void add(final float pFactor, final T ... pElements){ + this.mProbabilitySum += pFactor; + this.mEntries.add(new Entry(pFactor, pElements)); + } + + public T next() { + float random = MathUtils.random(0, this.mProbabilitySum); + + final ArrayList> factors = this.mEntries; + + for(int i = factors.size() - 1; i >= 0; i--){ + final Entry entry = factors.get(i); + random -= entry.mFactor; + if(random <= 0){ + return entry.getReturnValue(); + } + } + + final Entry lastEntry = factors.get(factors.size() - 1); + return lastEntry.getReturnValue(); + } + + public void clear() { + this.mProbabilitySum = 0; + this.mEntries.clear(); + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== + + private static class Entry { + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + public final float mFactor; + public final T[] mData; + + // =========================================================== + // Constructors + // =========================================================== + + public Entry(final float pFactor, final T[] pData){ + this.mFactor = pFactor; + this.mData = pData; + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + public T getReturnValue() { + if(this.mData.length == 1){ + return this.mData[0]; + }else{ + return ArrayUtils.random(mData); + } + } + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== + } } diff --git a/AndEngine/src/org/anddev/andengine/util/SAXUtils.java b/AndEngine/src/org/anddev/andengine/util/SAXUtils.java index cd5da165..b7691fb0 100644 --- a/AndEngine/src/org/anddev/andengine/util/SAXUtils.java +++ b/AndEngine/src/org/anddev/andengine/util/SAXUtils.java @@ -10,146 +10,146 @@ * @since 22:02:09 - 21.07.2010 */ public class SAXUtils { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - public static String getAttribute(final Attributes pAttributes, final String pAttributeName, final String pDefaultValue) { - final String value = pAttributes.getValue("", pAttributeName); - return (value != null) ? value : pDefaultValue; - } + public static String getAttribute(final Attributes pAttributes, final String pAttributeName, final String pDefaultValue) { + final String value = pAttributes.getValue("", pAttributeName); + return (value != null) ? value : pDefaultValue; + } - public static String getAttributeOrThrow(final Attributes pAttributes, final String pAttributeName) { - final String value = pAttributes.getValue("", pAttributeName); - if(value != null) { - return value; - } else { - throw new IllegalArgumentException("No value found for attribute: '" + pAttributeName + "'"); - } - } + public static String getAttributeOrThrow(final Attributes pAttributes, final String pAttributeName) { + final String value = pAttributes.getValue("", pAttributeName); + if(value != null) { + return value; + } else { + throw new IllegalArgumentException("No value found for attribute: '" + pAttributeName + "'"); + } + } - public static boolean getBooleanAttribute(final Attributes pAttributes, final String pAttributeName, final boolean pDefaultValue) { - final String value = pAttributes.getValue("", pAttributeName); - return (value != null) ? Boolean.parseBoolean(value) : pDefaultValue; - } + public static boolean getBooleanAttribute(final Attributes pAttributes, final String pAttributeName, final boolean pDefaultValue) { + final String value = pAttributes.getValue("", pAttributeName); + return (value != null) ? Boolean.parseBoolean(value) : pDefaultValue; + } - public static boolean getBooleanAttributeOrThrow(final Attributes pAttributes, final String pAttributeName) { - return Boolean.parseBoolean(SAXUtils.getAttributeOrThrow(pAttributes, pAttributeName)); - } + public static boolean getBooleanAttributeOrThrow(final Attributes pAttributes, final String pAttributeName) { + return Boolean.parseBoolean(SAXUtils.getAttributeOrThrow(pAttributes, pAttributeName)); + } - public static byte getByteAttribute(final Attributes pAttributes, final String pAttributeName, final byte pDefaultValue) { - final String value = pAttributes.getValue("", pAttributeName); - return (value != null) ? Byte.parseByte(value) : pDefaultValue; - } + public static byte getByteAttribute(final Attributes pAttributes, final String pAttributeName, final byte pDefaultValue) { + final String value = pAttributes.getValue("", pAttributeName); + return (value != null) ? Byte.parseByte(value) : pDefaultValue; + } - public static byte getByteAttributeOrThrow(final Attributes pAttributes, final String pAttributeName) { - return Byte.parseByte(SAXUtils.getAttributeOrThrow(pAttributes, pAttributeName)); - } + public static byte getByteAttributeOrThrow(final Attributes pAttributes, final String pAttributeName) { + return Byte.parseByte(SAXUtils.getAttributeOrThrow(pAttributes, pAttributeName)); + } - public static short getShortAttribute(final Attributes pAttributes, final String pAttributeName, final short pDefaultValue) { - final String value = pAttributes.getValue("", pAttributeName); - return (value != null) ? Short.parseShort(value) : pDefaultValue; - } + public static short getShortAttribute(final Attributes pAttributes, final String pAttributeName, final short pDefaultValue) { + final String value = pAttributes.getValue("", pAttributeName); + return (value != null) ? Short.parseShort(value) : pDefaultValue; + } - public static short getShortAttributeOrThrow(final Attributes pAttributes, final String pAttributeName) { - return Short.parseShort(SAXUtils.getAttributeOrThrow(pAttributes, pAttributeName)); - } + public static short getShortAttributeOrThrow(final Attributes pAttributes, final String pAttributeName) { + return Short.parseShort(SAXUtils.getAttributeOrThrow(pAttributes, pAttributeName)); + } - public static int getIntAttribute(final Attributes pAttributes, final String pAttributeName, final int pDefaultValue) { - final String value = pAttributes.getValue("", pAttributeName); - return (value != null) ? Integer.parseInt(value) : pDefaultValue; - } + public static int getIntAttribute(final Attributes pAttributes, final String pAttributeName, final int pDefaultValue) { + final String value = pAttributes.getValue("", pAttributeName); + return (value != null) ? Integer.parseInt(value) : pDefaultValue; + } - public static int getIntAttributeOrThrow(final Attributes pAttributes, final String pAttributeName) { - return Integer.parseInt(SAXUtils.getAttributeOrThrow(pAttributes, pAttributeName)); - } + public static int getIntAttributeOrThrow(final Attributes pAttributes, final String pAttributeName) { + return Integer.parseInt(SAXUtils.getAttributeOrThrow(pAttributes, pAttributeName)); + } - public static long getLongAttribute(final Attributes pAttributes, final String pAttributeName, final long pDefaultValue) { - final String value = pAttributes.getValue("", pAttributeName); - return (value != null) ? Long.parseLong(value) : pDefaultValue; - } + public static long getLongAttribute(final Attributes pAttributes, final String pAttributeName, final long pDefaultValue) { + final String value = pAttributes.getValue("", pAttributeName); + return (value != null) ? Long.parseLong(value) : pDefaultValue; + } - public static long getLongAttributeOrThrow(final Attributes pAttributes, final String pAttributeName) { - return Long.parseLong(SAXUtils.getAttributeOrThrow(pAttributes, pAttributeName)); - } + public static long getLongAttributeOrThrow(final Attributes pAttributes, final String pAttributeName) { + return Long.parseLong(SAXUtils.getAttributeOrThrow(pAttributes, pAttributeName)); + } - public static float getFloatAttribute(final Attributes pAttributes, final String pAttributeName, final float pDefaultValue) { - final String value = pAttributes.getValue("", pAttributeName); - return (value != null) ? Float.parseFloat(value) : pDefaultValue; - } + public static float getFloatAttribute(final Attributes pAttributes, final String pAttributeName, final float pDefaultValue) { + final String value = pAttributes.getValue("", pAttributeName); + return (value != null) ? Float.parseFloat(value) : pDefaultValue; + } - public static float getFloatAttributeOrThrow(final Attributes pAttributes, final String pAttributeName) { - return Float.parseFloat(SAXUtils.getAttributeOrThrow(pAttributes, pAttributeName)); - } + public static float getFloatAttributeOrThrow(final Attributes pAttributes, final String pAttributeName) { + return Float.parseFloat(SAXUtils.getAttributeOrThrow(pAttributes, pAttributeName)); + } - public static double getDoubleAttribute(final Attributes pAttributes, final String pAttributeName, final double pDefaultValue) { - final String value = pAttributes.getValue("", pAttributeName); - return (value != null) ? Double.parseDouble(value) : pDefaultValue; - } + public static double getDoubleAttribute(final Attributes pAttributes, final String pAttributeName, final double pDefaultValue) { + final String value = pAttributes.getValue("", pAttributeName); + return (value != null) ? Double.parseDouble(value) : pDefaultValue; + } - public static double getDoubleAttributeOrThrow(final Attributes pAttributes, final String pAttributeName) { - return Double.parseDouble(SAXUtils.getAttributeOrThrow(pAttributes, pAttributeName)); - } + public static double getDoubleAttributeOrThrow(final Attributes pAttributes, final String pAttributeName) { + return Double.parseDouble(SAXUtils.getAttributeOrThrow(pAttributes, pAttributeName)); + } - public static void appendAttribute(final StringBuilder pStringBuilder, final String pName, final boolean pValue) { - SAXUtils.appendAttribute(pStringBuilder, pName, String.valueOf(pValue)); - } + public static void appendAttribute(final StringBuilder pStringBuilder, final String pName, final boolean pValue) { + SAXUtils.appendAttribute(pStringBuilder, pName, String.valueOf(pValue)); + } - public static void appendAttribute(final StringBuilder pStringBuilder, final String pName, final byte pValue) { - SAXUtils.appendAttribute(pStringBuilder, pName, String.valueOf(pValue)); - } + public static void appendAttribute(final StringBuilder pStringBuilder, final String pName, final byte pValue) { + SAXUtils.appendAttribute(pStringBuilder, pName, String.valueOf(pValue)); + } - public static void appendAttribute(final StringBuilder pStringBuilder, final String pName, final short pValue) { - SAXUtils.appendAttribute(pStringBuilder, pName, String.valueOf(pValue)); - } + public static void appendAttribute(final StringBuilder pStringBuilder, final String pName, final short pValue) { + SAXUtils.appendAttribute(pStringBuilder, pName, String.valueOf(pValue)); + } - public static void appendAttribute(final StringBuilder pStringBuilder, final String pName, final int pValue) { - SAXUtils.appendAttribute(pStringBuilder, pName, String.valueOf(pValue)); - } + public static void appendAttribute(final StringBuilder pStringBuilder, final String pName, final int pValue) { + SAXUtils.appendAttribute(pStringBuilder, pName, String.valueOf(pValue)); + } - public static void appendAttribute(final StringBuilder pStringBuilder, final String pName, final long pValue) { - SAXUtils.appendAttribute(pStringBuilder, pName, String.valueOf(pValue)); - } + public static void appendAttribute(final StringBuilder pStringBuilder, final String pName, final long pValue) { + SAXUtils.appendAttribute(pStringBuilder, pName, String.valueOf(pValue)); + } - public static void appendAttribute(final StringBuilder pStringBuilder, final String pName, final float pValue) { - SAXUtils.appendAttribute(pStringBuilder, pName, String.valueOf(pValue)); - } + public static void appendAttribute(final StringBuilder pStringBuilder, final String pName, final float pValue) { + SAXUtils.appendAttribute(pStringBuilder, pName, String.valueOf(pValue)); + } - public static void appendAttribute(final StringBuilder pStringBuilder, final String pName, final double pValue) { - SAXUtils.appendAttribute(pStringBuilder, pName, String.valueOf(pValue)); - } + public static void appendAttribute(final StringBuilder pStringBuilder, final String pName, final double pValue) { + SAXUtils.appendAttribute(pStringBuilder, pName, String.valueOf(pValue)); + } - public static void appendAttribute(final StringBuilder pStringBuilder, final String pName, final String pValue) { - pStringBuilder.append(' ').append(pName).append('=').append('\"').append(pValue).append('\"'); - } + public static void appendAttribute(final StringBuilder pStringBuilder, final String pName, final String pValue) { + pStringBuilder.append(' ').append(pName).append('=').append('\"').append(pValue).append('\"'); + } - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/util/SimplePreferences.java b/AndEngine/src/org/anddev/andengine/util/SimplePreferences.java index 9eb2b36d..1ee1e930 100644 --- a/AndEngine/src/org/anddev/andengine/util/SimplePreferences.java +++ b/AndEngine/src/org/anddev/andengine/util/SimplePreferences.java @@ -15,66 +15,66 @@ * @since 18:55:12 - 02.08.2010 */ public class SimplePreferences implements Constants { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - private static SharedPreferences INSTANCE; - private static Editor EDITORINSTANCE; - - // =========================================================== - // Constructors - // =========================================================== - - public static SharedPreferences getInstance(final Context pContext) { - if(SimplePreferences.INSTANCE == null) { - SimplePreferences.INSTANCE = PreferenceManager.getDefaultSharedPreferences(pContext); - } - return SimplePreferences.INSTANCE; - } - - public static Editor getEditorInstance(final Context pContext) { - if(SimplePreferences.EDITORINSTANCE == null) { - SimplePreferences.EDITORINSTANCE = SimplePreferences.getInstance(pContext).edit(); - } - return SimplePreferences.EDITORINSTANCE; - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - // =========================================================== - // Methods - // =========================================================== - - public static int incrementAccessCount(final Context pContext, final String pKey) { - return SimplePreferences.incrementAccessCount(pContext, pKey, 1); - } - - public static int incrementAccessCount(final Context pContext, final String pKey, final int pIncrement) { - final SharedPreferences prefs = SimplePreferences.getInstance(pContext); - final int accessCount = prefs.getInt(pKey, 0); - - final int newAccessCount = accessCount + pIncrement; - prefs.edit().putInt(pKey, newAccessCount).commit(); - - return newAccessCount; - } - - public static int getAccessCount(final Context pCtx, final String pKey) { - return SimplePreferences.getInstance(pCtx).getInt(pKey, 0); - } - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + private static SharedPreferences INSTANCE; + private static Editor EDITORINSTANCE; + + // =========================================================== + // Constructors + // =========================================================== + + public static SharedPreferences getInstance(final Context pContext) { + if(SimplePreferences.INSTANCE == null) { + SimplePreferences.INSTANCE = PreferenceManager.getDefaultSharedPreferences(pContext); + } + return SimplePreferences.INSTANCE; + } + + public static Editor getEditorInstance(final Context pContext) { + if(SimplePreferences.EDITORINSTANCE == null) { + SimplePreferences.EDITORINSTANCE = SimplePreferences.getInstance(pContext).edit(); + } + return SimplePreferences.EDITORINSTANCE; + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + public static int incrementAccessCount(final Context pContext, final String pKey) { + return SimplePreferences.incrementAccessCount(pContext, pKey, 1); + } + + public static int incrementAccessCount(final Context pContext, final String pKey, final int pIncrement) { + final SharedPreferences prefs = SimplePreferences.getInstance(pContext); + final int accessCount = prefs.getInt(pKey, 0); + + final int newAccessCount = accessCount + pIncrement; + prefs.edit().putInt(pKey, newAccessCount).commit(); + + return newAccessCount; + } + + public static int getAccessCount(final Context pCtx, final String pKey) { + return SimplePreferences.getInstance(pCtx).getInt(pKey, 0); + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/util/SmartList.java b/AndEngine/src/org/anddev/andengine/util/SmartList.java index f51a855c..a5f70035 100644 --- a/AndEngine/src/org/anddev/andengine/util/SmartList.java +++ b/AndEngine/src/org/anddev/andengine/util/SmartList.java @@ -11,166 +11,166 @@ * @since 22:20:08 - 27.12.2010 */ public class SmartList extends ArrayList { - // =========================================================== - // Constants - // =========================================================== - - private static final long serialVersionUID = -8335986399182700102L; - - // =========================================================== - // Fields - // =========================================================== - - // =========================================================== - // Constructors - // =========================================================== - - public SmartList() { - - } - - public SmartList(final int pCapacity) { - super(pCapacity); - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - /** - * @param pItem the item to remove. - * @param pParameterCallable to be called with the removed item, if it was removed. - */ - public boolean remove(final T pItem, final ParameterCallable pParameterCallable) { - final boolean removed = this.remove(pItem); - 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))) { - return this.remove(i); - } - } - return null; - } - - public T remove(final IMatcher pMatcher, final ParameterCallable pParameterCallable) { - 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; - } - } - return null; - } - - public boolean removeAll(final IMatcher pMatcher) { - boolean result = false; - for(int i = this.size() - 1; i >= 0; i--) { - if(pMatcher.matches(this.get(i))) { - this.remove(i); - result = true; - } - } - return result; - } - - /** - * @param pMatcher to find the items. - * @param pParameterCallable to be called with each matched item after it was removed. - */ - 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))) { - final T removed = this.remove(i); - pParameterCallable.call(removed); - result = true; - } - } - return result; - } - - public void clear(final ParameterCallable pParameterCallable) { - for(int i = this.size() - 1; i >= 0; i--) { - final T removed = this.remove(i); - pParameterCallable.call(removed); - } - } - - public T find(final IMatcher pMatcher) { - for(int i = this.size() - 1; i >= 0; i--) { - final T item = this.get(i); - if(pMatcher.matches(item)) { - return item; - } - } - return null; - } - - public ArrayList query(final IMatcher pMatcher) { - return this.query(pMatcher, new ArrayList()); - } - - public > L query(final IMatcher pMatcher, final L pResult) { - final int size = this.size(); - for(int i = 0; i < size; i++) { - final T item = this.get(i); - if(pMatcher.matches(item)) { - pResult.add(item); - } - } - - return pResult; - } - - public ArrayList queryForSubclass(final IMatcher pMatcher) { - return this.queryForSubclass(pMatcher, new ArrayList()); - } - - @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++) { - final T item = this.get(i); - if(pMatcher.matches(item)) { - pResult.add((S)item); - } - } - - return pResult; - } - - public void call(final ParameterCallable pParameterCallable) { - 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--) { - final T item = this.get(i); - if(pMatcher.matches(item)) { - pParameterCallable.call(item); - } - } - } - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + private static final long serialVersionUID = -8335986399182700102L; + + // =========================================================== + // Fields + // =========================================================== + + // =========================================================== + // Constructors + // =========================================================== + + public SmartList() { + + } + + public SmartList(final int pCapacity) { + super(pCapacity); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + /** + * @param pItem the item to remove. + * @param pParameterCallable to be called with the removed item, if it was removed. + */ + public boolean remove(final T pItem, final ParameterCallable pParameterCallable) { + final boolean removed = this.remove(pItem); + 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))) { + return this.remove(i); + } + } + return null; + } + + public T remove(final IMatcher pMatcher, final ParameterCallable pParameterCallable) { + 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; + } + } + return null; + } + + public boolean removeAll(final IMatcher pMatcher) { + boolean result = false; + for(int i = this.size() - 1; i >= 0; i--) { + if(pMatcher.matches(this.get(i))) { + this.remove(i); + result = true; + } + } + return result; + } + + /** + * @param pMatcher to find the items. + * @param pParameterCallable to be called with each matched item after it was removed. + */ + 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))) { + final T removed = this.remove(i); + pParameterCallable.call(removed); + result = true; + } + } + return result; + } + + public void clear(final ParameterCallable pParameterCallable) { + for(int i = this.size() - 1; i >= 0; i--) { + final T removed = this.remove(i); + pParameterCallable.call(removed); + } + } + + public T find(final IMatcher pMatcher) { + for(int i = this.size() - 1; i >= 0; i--) { + final T item = this.get(i); + if(pMatcher.matches(item)) { + return item; + } + } + return null; + } + + public ArrayList query(final IMatcher pMatcher) { + return this.query(pMatcher, new ArrayList()); + } + + public > L query(final IMatcher pMatcher, final L pResult) { + final int size = this.size(); + for(int i = 0; i < size; i++) { + final T item = this.get(i); + if(pMatcher.matches(item)) { + pResult.add(item); + } + } + + return pResult; + } + + public ArrayList queryForSubclass(final IMatcher pMatcher) { + return this.queryForSubclass(pMatcher, new ArrayList()); + } + + @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++) { + final T item = this.get(i); + if(pMatcher.matches(item)) { + pResult.add((S)item); + } + } + + return pResult; + } + + public void call(final ParameterCallable pParameterCallable) { + 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--) { + final T item = this.get(i); + if(pMatcher.matches(item)) { + pParameterCallable.call(item); + } + } + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/util/SocketUtils.java b/AndEngine/src/org/anddev/andengine/util/SocketUtils.java index 43e5fcae..d87b8ed6 100644 --- a/AndEngine/src/org/anddev/andengine/util/SocketUtils.java +++ b/AndEngine/src/org/anddev/andengine/util/SocketUtils.java @@ -13,57 +13,57 @@ * @since 14:42:15 - 18.09.2009 */ public class SocketUtils { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - public static void closeSocket(final DatagramSocket pDatagramSocket) { - if(pDatagramSocket != null && !pDatagramSocket.isClosed()) { - pDatagramSocket.close(); - } - } + public static void closeSocket(final DatagramSocket pDatagramSocket) { + if(pDatagramSocket != null && !pDatagramSocket.isClosed()) { + pDatagramSocket.close(); + } + } - public static void closeSocket(final Socket pSocket) { - if(pSocket != null && !pSocket.isClosed()) { - try { - pSocket.close(); - } catch (final IOException e) { - Debug.e(e); - } - } - } + public static void closeSocket(final Socket pSocket) { + if(pSocket != null && !pSocket.isClosed()) { + try { + pSocket.close(); + } catch (final IOException e) { + Debug.e(e); + } + } + } - public static void closeSocket(final ServerSocket pServerSocket) { - if(pServerSocket != null && !pServerSocket.isClosed()) { - try { - pServerSocket.close(); - } catch (final IOException e) { - Debug.e(e); - } - } - } + public static void closeSocket(final ServerSocket pServerSocket) { + if(pServerSocket != null && !pServerSocket.isClosed()) { + try { + pServerSocket.close(); + } catch (final IOException e) { + Debug.e(e); + } + } + } - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/util/StreamUtils.java b/AndEngine/src/org/anddev/andengine/util/StreamUtils.java index e2dd07d3..95f734d8 100644 --- a/AndEngine/src/org/anddev/andengine/util/StreamUtils.java +++ b/AndEngine/src/org/anddev/andengine/util/StreamUtils.java @@ -17,172 +17,172 @@ * @since 15:48:56 - 03.09.2009 */ public class StreamUtils { - // =========================================================== - // Constants - // =========================================================== - - public static final int IO_BUFFER_SIZE = 8 * 1024; - - // =========================================================== - // Fields - // =========================================================== - - // =========================================================== - // Constructors - // =========================================================== - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods from SuperClass/Interfaces - // =========================================================== - - // =========================================================== - // Methods - // =========================================================== - - public static final String readFully(final InputStream pInputStream) throws IOException { - /*final StringBuilder sb = new StringBuilder(); - final Scanner sc = new Scanner(pInputStream); - while(sc.hasNextLine()) { - sb.append(sc.nextLine()); - } - return sb.toString();*/ - return new String(streamToBytes(pInputStream), "UTF-8"); - } - - public static byte[] streamToBytes(final InputStream pInputStream) throws IOException { - return StreamUtils.streamToBytes(pInputStream, -1); - } - - public static byte[] streamToBytes(final InputStream pInputStream, final int pReadLimit) throws IOException { - final ByteArrayOutputStream os = new ByteArrayOutputStream((pReadLimit == -1) ? IO_BUFFER_SIZE : pReadLimit); - StreamUtils.copy(pInputStream, os, pReadLimit); - return os.toByteArray(); - } - - public static void copy(final InputStream pInputStream, final OutputStream pOutputStream) throws IOException { - StreamUtils.copy(pInputStream, pOutputStream, -1); - } - - public static void copy(final InputStream pInputStream, final byte[] pData) throws IOException { - int dataOffset = 0; - final byte[] buf = new byte[IO_BUFFER_SIZE]; - int read; - while((read = pInputStream.read(buf)) != -1) { - System.arraycopy(buf, 0, pData, dataOffset, read); - dataOffset += read; - } - } - - public static void copy(final InputStream pInputStream, final ByteBuffer pByteBuffer) throws IOException { - final byte[] buf = new byte[IO_BUFFER_SIZE]; - int read; - while((read = pInputStream.read(buf)) != -1) { - pByteBuffer.put(buf, 0, read); - } - } - - /** - * Copy the content of the input stream into the output stream, using a temporary - * byte array buffer whose size is defined by {@link #IO_BUFFER_SIZE}. - * - * @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 smaller than 0. - * - * @throws IOException If any error occurs during the copy. - */ - public static void copy(final InputStream pInputStream, final OutputStream pOutputStream, final long pByteLimit) throws IOException { - if(pByteLimit < 0) { - final byte[] buf = new byte[IO_BUFFER_SIZE]; - int read; - while((read = pInputStream.read(buf)) != -1) { - pOutputStream.write(buf, 0, read); - } - } else { - final byte[] buf = new byte[IO_BUFFER_SIZE]; - final int bufferReadLimit = Math.min((int)pByteLimit, IO_BUFFER_SIZE); - long pBytesLeftToRead = pByteLimit; - - int read; - while((read = pInputStream.read(buf, 0, bufferReadLimit)) != -1) { - if(pBytesLeftToRead > read) { - pOutputStream.write(buf, 0, read); - pBytesLeftToRead -= read; - } else { - pOutputStream.write(buf, 0, (int) pBytesLeftToRead); - break; - } - } - } - pOutputStream.flush(); - } - - public static boolean copyAndClose(final InputStream pInputStream, final OutputStream pOutputStream) { - try { - StreamUtils.copy(pInputStream, pOutputStream, -1); - return true; - } catch (final IOException e) { - return false; - } finally { - StreamUtils.close(pInputStream); - StreamUtils.close(pOutputStream); - } - } - - /** - * Closes the specified stream. - * - * @param pCloseable The stream to close. - */ - public static void close(final Closeable pCloseable) { - if(pCloseable != null) { - try { - pCloseable.close(); - } catch (final IOException e) { - e.printStackTrace(); - } - } - } - - /** - * Flushes and closes the specified stream. - * - * @param pOutputStream The stream to close. - */ - public static void flushCloseStream(final OutputStream pOutputStream) { - if(pOutputStream != null) { - try { - pOutputStream.flush(); - } catch (final IOException e) { - e.printStackTrace(); - } finally { - StreamUtils.close(pOutputStream); - } - } - } - - /** - * Flushes and closes the specified stream. - * - * @param pWriter The Writer to close. - */ - public static void flushCloseWriter(final Writer pWriter) { - if(pWriter != null) { - try { - pWriter.flush(); - } catch (final IOException e) { - e.printStackTrace(); - } finally { - StreamUtils.close(pWriter); - } - } - } - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + public static final int IO_BUFFER_SIZE = 8 * 1024; + + // =========================================================== + // Fields + // =========================================================== + + // =========================================================== + // Constructors + // =========================================================== + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods from SuperClass/Interfaces + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + public static final String readFully(final InputStream pInputStream) throws IOException { + /*final StringBuilder sb = new StringBuilder(); + final Scanner sc = new Scanner(pInputStream); + while(sc.hasNextLine()) { + sb.append(sc.nextLine()); + } + return sb.toString();*/ + return new String(streamToBytes(pInputStream), "UTF-8"); + } + + public static byte[] streamToBytes(final InputStream pInputStream) throws IOException { + return StreamUtils.streamToBytes(pInputStream, -1); + } + + public static byte[] streamToBytes(final InputStream pInputStream, final int pReadLimit) throws IOException { + final ByteArrayOutputStream os = new ByteArrayOutputStream((pReadLimit == -1) ? IO_BUFFER_SIZE : pReadLimit); + StreamUtils.copy(pInputStream, os, pReadLimit); + return os.toByteArray(); + } + + public static void copy(final InputStream pInputStream, final OutputStream pOutputStream) throws IOException { + StreamUtils.copy(pInputStream, pOutputStream, -1); + } + + public static void copy(final InputStream pInputStream, final byte[] pData) throws IOException { + int dataOffset = 0; + final byte[] buf = new byte[IO_BUFFER_SIZE]; + int read; + while((read = pInputStream.read(buf)) != -1) { + System.arraycopy(buf, 0, pData, dataOffset, read); + dataOffset += read; + } + } + + public static void copy(final InputStream pInputStream, final ByteBuffer pByteBuffer) throws IOException { + final byte[] buf = new byte[IO_BUFFER_SIZE]; + int read; + while((read = pInputStream.read(buf)) != -1) { + pByteBuffer.put(buf, 0, read); + } + } + + /** + * Copy the content of the input stream into the output stream, using a temporary + * byte array buffer whose size is defined by {@link #IO_BUFFER_SIZE}. + * + * @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 smaller than 0. + * + * @throws IOException If any error occurs during the copy. + */ + public static void copy(final InputStream pInputStream, final OutputStream pOutputStream, final long pByteLimit) throws IOException { + if(pByteLimit < 0) { + final byte[] buf = new byte[IO_BUFFER_SIZE]; + int read; + while((read = pInputStream.read(buf)) != -1) { + pOutputStream.write(buf, 0, read); + } + } else { + final byte[] buf = new byte[IO_BUFFER_SIZE]; + final int bufferReadLimit = Math.min((int)pByteLimit, IO_BUFFER_SIZE); + long pBytesLeftToRead = pByteLimit; + + int read; + while((read = pInputStream.read(buf, 0, bufferReadLimit)) != -1) { + if(pBytesLeftToRead > read) { + pOutputStream.write(buf, 0, read); + pBytesLeftToRead -= read; + } else { + pOutputStream.write(buf, 0, (int) pBytesLeftToRead); + break; + } + } + } + pOutputStream.flush(); + } + + public static boolean copyAndClose(final InputStream pInputStream, final OutputStream pOutputStream) { + try { + StreamUtils.copy(pInputStream, pOutputStream, -1); + return true; + } catch (final IOException e) { + return false; + } finally { + StreamUtils.close(pInputStream); + StreamUtils.close(pOutputStream); + } + } + + /** + * Closes the specified stream. + * + * @param pCloseable The stream to close. + */ + public static void close(final Closeable pCloseable) { + if(pCloseable != null) { + try { + pCloseable.close(); + } catch (final IOException e) { + e.printStackTrace(); + } + } + } + + /** + * Flushes and closes the specified stream. + * + * @param pOutputStream The stream to close. + */ + public static void flushCloseStream(final OutputStream pOutputStream) { + if(pOutputStream != null) { + try { + pOutputStream.flush(); + } catch (final IOException e) { + e.printStackTrace(); + } finally { + StreamUtils.close(pOutputStream); + } + } + } + + /** + * Flushes and closes the specified stream. + * + * @param pWriter The Writer to close. + */ + public static void flushCloseWriter(final Writer pWriter) { + if(pWriter != null) { + try { + pWriter.flush(); + } catch (final IOException e) { + e.printStackTrace(); + } finally { + StreamUtils.close(pWriter); + } + } + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/util/StringUtils.java b/AndEngine/src/org/anddev/andengine/util/StringUtils.java index 7b71f2d0..f098b0ad 100644 --- a/AndEngine/src/org/anddev/andengine/util/StringUtils.java +++ b/AndEngine/src/org/anddev/andengine/util/StringUtils.java @@ -8,105 +8,105 @@ * @since 19:01:08 - 03.04.2010 */ public class StringUtils { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - // =========================================================== - // Constructors - // =========================================================== - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - // =========================================================== - // Methods - // =========================================================== - - public static String padFront(final String pString, final char pPadChar, final int pLength) { - final int padCount = pLength - pString.length(); - if(padCount <= 0) { - return pString; - } else { - final StringBuilder sb = new StringBuilder(); - - for(int i = padCount - 1; i >= 0; i--) { - sb.append(pPadChar); - } - sb.append(pString); - - return sb.toString(); - } - } - - public static int countOccurrences(final String pString, final char pCharacter) { - int count = 0; - - int lastOccurrence = pString.indexOf(pCharacter, 0); - - while (lastOccurrence != -1) { - count++; - lastOccurrence = pString.indexOf(pCharacter, lastOccurrence + 1); - } - - return count; - } - - /** - * Split a String by a Character, i.e. Split lines by using '\n'.
- * Same behavior as String.split("" + pCharacter); . - * - * @param pString - * @param pCharacter - * @return - */ - public static String[] split(final String pString, final char pCharacter) { - return StringUtils.split(pString, pCharacter, null); - } - - /** - * Split a String by a Character, i.e. Split lines by using '\n'.
- * Same behavior as String.split("" + pCharacter); . - * - * @param pString - * @param pCharacter - * @param pReuse tries to reuse the String[] if the length is the same as the length needed. - * @return - */ - public static String[] split(final String pString, final char pCharacter, final String[] pReuse) { - final int partCount = StringUtils.countOccurrences(pString, pCharacter) + 1; - - final boolean reuseable = pReuse != null && pReuse.length == partCount; - final String[] out = reuseable ? pReuse : new String[partCount]; - - if(partCount == 0) { - out[0] = pString; - } else { - int from = 0; - int to; - - for (int i = 0; i < partCount - 1; i++) { - to = pString.indexOf(pCharacter, from); - out[i] = pString.substring(from, to); - from = to + 1; - } - - out[partCount - 1] = pString.substring(from, pString.length()); - } - - return out; - } - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + // =========================================================== + // Constructors + // =========================================================== + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + public static String padFront(final String pString, final char pPadChar, final int pLength) { + final int padCount = pLength - pString.length(); + if(padCount <= 0) { + return pString; + } else { + final StringBuilder sb = new StringBuilder(); + + for(int i = padCount - 1; i >= 0; i--) { + sb.append(pPadChar); + } + sb.append(pString); + + return sb.toString(); + } + } + + public static int countOccurrences(final String pString, final char pCharacter) { + int count = 0; + + int lastOccurrence = pString.indexOf(pCharacter, 0); + + while (lastOccurrence != -1) { + count++; + lastOccurrence = pString.indexOf(pCharacter, lastOccurrence + 1); + } + + return count; + } + + /** + * Split a String by a Character, i.e. Split lines by using '\n'.
+ * Same behavior as String.split("" + pCharacter); . + * + * @param pString + * @param pCharacter + * @return + */ + public static String[] split(final String pString, final char pCharacter) { + return StringUtils.split(pString, pCharacter, null); + } + + /** + * Split a String by a Character, i.e. Split lines by using '\n'.
+ * Same behavior as String.split("" + pCharacter); . + * + * @param pString + * @param pCharacter + * @param pReuse tries to reuse the String[] if the length is the same as the length needed. + * @return + */ + public static String[] split(final String pString, final char pCharacter, final String[] pReuse) { + final int partCount = StringUtils.countOccurrences(pString, pCharacter) + 1; + + final boolean reuseable = pReuse != null && pReuse.length == partCount; + final String[] out = reuseable ? pReuse : new String[partCount]; + + if(partCount == 0) { + out[0] = pString; + } else { + int from = 0; + int to; + + for (int i = 0; i < partCount - 1; i++) { + to = pString.indexOf(pCharacter, from); + out[i] = pString.substring(from, to); + from = to + 1; + } + + out[partCount - 1] = pString.substring(from, pString.length()); + } + + return out; + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/util/SystemUtils.java b/AndEngine/src/org/anddev/andengine/util/SystemUtils.java index 0ae097aa..96588dbd 100644 --- a/AndEngine/src/org/anddev/andengine/util/SystemUtils.java +++ b/AndEngine/src/org/anddev/andengine/util/SystemUtils.java @@ -20,216 +20,216 @@ * @since 15:50:31 - 14.07.2010 */ public class SystemUtils { - // =========================================================== - // Constants - // =========================================================== - - private static final String BOGOMIPS_PATTERN = "BogoMIPS[\\s]*:[\\s]*(\\d+\\.\\d+)[\\s]*\n"; - private static final String MEMTOTAL_PATTERN = "MemTotal[\\s]*:[\\s]*(\\d+)[\\s]*kB\n"; - private static final String MEMFREE_PATTERN = "MemFree[\\s]*:[\\s]*(\\d+)[\\s]*kB\n"; - - // =========================================================== - // Fields - // =========================================================== - - // =========================================================== - // Constructors - // =========================================================== - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - // =========================================================== - // Methods - // =========================================================== - - public static int getPackageVersionCode(final Context pContext) { - return SystemUtils.getPackageInfo(pContext).versionCode; - } - - public static String getPackageVersionName(final Context pContext) { - return SystemUtils.getPackageInfo(pContext).versionName; - } - - private static PackageInfo getPackageInfo(final Context pContext) { - try { - return pContext.getPackageManager().getPackageInfo(pContext.getPackageName(), 0); - } catch (final NameNotFoundException e) { - Debug.e(e); - return null; - } - } - - public static boolean hasSystemFeature(final Context pContext, final String pFeature) { - 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); - } catch (final Throwable t) { - return false; - } - } - - /** - * @param pBuildVersionCode taken from {@link Build.VERSION_CODES}. - */ - public static boolean isAndroidVersionOrHigher(final int pBuildVersionCode) { - return Integer.parseInt(Build.VERSION.SDK) >= pBuildVersionCode; - } - - public static float getCPUBogoMips() throws SystemUtilsException { - final MatchResult matchResult = SystemUtils.matchSystemFile("/proc/cpuinfo", BOGOMIPS_PATTERN, 1000); - - try { - if(matchResult.groupCount() > 0) { - return Float.parseFloat(matchResult.group(1)); - } else { - throw new SystemUtilsException(); - } - } catch (final NumberFormatException e) { - throw new SystemUtilsException(e); - } - } - - /** - * @return in kiloBytes. - * @throws SystemUtilsException - */ - public static int getMemoryTotal() throws SystemUtilsException { - final MatchResult matchResult = SystemUtils.matchSystemFile("/proc/meminfo", MEMTOTAL_PATTERN, 1000); - - try { - if(matchResult.groupCount() > 0) { - return Integer.parseInt(matchResult.group(1)); - } else { - throw new SystemUtilsException(); - } - } catch (final NumberFormatException e) { - throw new SystemUtilsException(e); - } - } - - /** - * @return in kiloBytes. - * @throws SystemUtilsException - */ - public static int getMemoryFree() throws SystemUtilsException { - final MatchResult matchResult = SystemUtils.matchSystemFile("/proc/meminfo", MEMFREE_PATTERN, 1000); - - try { - if(matchResult.groupCount() > 0) { - return Integer.parseInt(matchResult.group(1)); - } else { - throw new SystemUtilsException(); - } - } catch (final NumberFormatException e) { - throw new SystemUtilsException(e); - } - } - - /** - * @return in kiloHertz. - * @throws SystemUtilsException - */ - public static int getCPUFrequencyCurrent() throws SystemUtilsException { - return SystemUtils.readSystemFileAsInt("/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"); - } - - /** - * @return in kiloHertz. - * @throws SystemUtilsException - */ - public static int getCPUFrequencyMax() throws SystemUtilsException { - return SystemUtils.readSystemFileAsInt("/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"); - } - - /** - * @return in kiloHertz. - * @throws SystemUtilsException - */ - public static int getCPUFrequencyMaxScaling() throws SystemUtilsException { - return SystemUtils.readSystemFileAsInt("/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(); - - in = process.getInputStream(); - final Scanner scanner = new Scanner(in); - - final boolean matchFound = scanner.findWithinHorizon(pPattern, pHorizon) != null; - if(matchFound) { - return scanner.match(); - } else { - throw new SystemUtilsException(); - } - } catch (final IOException e) { - throw new SystemUtilsException(e); - } finally { - StreamUtils.close(in); - } - } - - private static int readSystemFileAsInt(final String pSystemFile) throws SystemUtilsException { - InputStream in = null; - try { - 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); - } catch (final IOException e) { - throw new SystemUtilsException(e); - } catch (final NumberFormatException e) { - throw new SystemUtilsException(e); - } finally { - StreamUtils.close(in); - } - } - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== - - public static class SystemUtilsException extends Exception { - // =========================================================== - // Constants - // =========================================================== - - private static final long serialVersionUID = -7256483361095147596L; - - // =========================================================== - // Methods - // =========================================================== - - public SystemUtilsException() { - - } - - public SystemUtilsException(final Throwable pThrowable) { - super(pThrowable); - } - } + // =========================================================== + // Constants + // =========================================================== + + private static final String BOGOMIPS_PATTERN = "BogoMIPS[\\s]*:[\\s]*(\\d+\\.\\d+)[\\s]*\n"; + private static final String MEMTOTAL_PATTERN = "MemTotal[\\s]*:[\\s]*(\\d+)[\\s]*kB\n"; + private static final String MEMFREE_PATTERN = "MemFree[\\s]*:[\\s]*(\\d+)[\\s]*kB\n"; + + // =========================================================== + // Fields + // =========================================================== + + // =========================================================== + // Constructors + // =========================================================== + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + public static int getPackageVersionCode(final Context pContext) { + return SystemUtils.getPackageInfo(pContext).versionCode; + } + + public static String getPackageVersionName(final Context pContext) { + return SystemUtils.getPackageInfo(pContext).versionName; + } + + private static PackageInfo getPackageInfo(final Context pContext) { + try { + return pContext.getPackageManager().getPackageInfo(pContext.getPackageName(), 0); + } catch (final NameNotFoundException e) { + Debug.e(e); + return null; + } + } + + public static boolean hasSystemFeature(final Context pContext, final String pFeature) { + 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); + } catch (final Throwable t) { + return false; + } + } + + /** + * @param pBuildVersionCode taken from {@link Build.VERSION_CODES}. + */ + public static boolean isAndroidVersionOrHigher(final int pBuildVersionCode) { + return Integer.parseInt(Build.VERSION.SDK) >= pBuildVersionCode; + } + + public static float getCPUBogoMips() throws SystemUtilsException { + final MatchResult matchResult = SystemUtils.matchSystemFile("/proc/cpuinfo", BOGOMIPS_PATTERN, 1000); + + try { + if(matchResult.groupCount() > 0) { + return Float.parseFloat(matchResult.group(1)); + } else { + throw new SystemUtilsException(); + } + } catch (final NumberFormatException e) { + throw new SystemUtilsException(e); + } + } + + /** + * @return in kiloBytes. + * @throws SystemUtilsException + */ + public static int getMemoryTotal() throws SystemUtilsException { + final MatchResult matchResult = SystemUtils.matchSystemFile("/proc/meminfo", MEMTOTAL_PATTERN, 1000); + + try { + if(matchResult.groupCount() > 0) { + return Integer.parseInt(matchResult.group(1)); + } else { + throw new SystemUtilsException(); + } + } catch (final NumberFormatException e) { + throw new SystemUtilsException(e); + } + } + + /** + * @return in kiloBytes. + * @throws SystemUtilsException + */ + public static int getMemoryFree() throws SystemUtilsException { + final MatchResult matchResult = SystemUtils.matchSystemFile("/proc/meminfo", MEMFREE_PATTERN, 1000); + + try { + if(matchResult.groupCount() > 0) { + return Integer.parseInt(matchResult.group(1)); + } else { + throw new SystemUtilsException(); + } + } catch (final NumberFormatException e) { + throw new SystemUtilsException(e); + } + } + + /** + * @return in kiloHertz. + * @throws SystemUtilsException + */ + public static int getCPUFrequencyCurrent() throws SystemUtilsException { + return SystemUtils.readSystemFileAsInt("/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"); + } + + /** + * @return in kiloHertz. + * @throws SystemUtilsException + */ + public static int getCPUFrequencyMax() throws SystemUtilsException { + return SystemUtils.readSystemFileAsInt("/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"); + } + + /** + * @return in kiloHertz. + * @throws SystemUtilsException + */ + public static int getCPUFrequencyMaxScaling() throws SystemUtilsException { + return SystemUtils.readSystemFileAsInt("/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(); + + in = process.getInputStream(); + final Scanner scanner = new Scanner(in); + + final boolean matchFound = scanner.findWithinHorizon(pPattern, pHorizon) != null; + if(matchFound) { + return scanner.match(); + } else { + throw new SystemUtilsException(); + } + } catch (final IOException e) { + throw new SystemUtilsException(e); + } finally { + StreamUtils.close(in); + } + } + + private static int readSystemFileAsInt(final String pSystemFile) throws SystemUtilsException { + InputStream in = null; + try { + 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); + } catch (final IOException e) { + throw new SystemUtilsException(e); + } catch (final NumberFormatException e) { + throw new SystemUtilsException(e); + } finally { + StreamUtils.close(in); + } + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== + + public static class SystemUtilsException extends Exception { + // =========================================================== + // Constants + // =========================================================== + + private static final long serialVersionUID = -7256483361095147596L; + + // =========================================================== + // Methods + // =========================================================== + + public SystemUtilsException() { + + } + + public SystemUtilsException(final Throwable pThrowable) { + super(pThrowable); + } + } } diff --git a/AndEngine/src/org/anddev/andengine/util/TimeUtils.java b/AndEngine/src/org/anddev/andengine/util/TimeUtils.java index 02ffb460..307c5edb 100644 --- a/AndEngine/src/org/anddev/andengine/util/TimeUtils.java +++ b/AndEngine/src/org/anddev/andengine/util/TimeUtils.java @@ -10,50 +10,50 @@ * @since 22:48:49 - 04.04.2011 */ public class TimeUtils implements TimeConstants { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - // =========================================================== - // Constructors - // =========================================================== - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - // =========================================================== - // Methods - // =========================================================== - - public static String formatSeconds(final int pSecondsTotal) { - return formatSeconds(pSecondsTotal, new StringBuilder()); - } - - public static String formatSeconds(final int pSecondsTotal, final StringBuilder pStringBuilder) { - final int minutes = pSecondsTotal / SECONDSPERMINUTE; - final int seconds = pSecondsTotal % SECONDSPERMINUTE; - - pStringBuilder.append(minutes); - pStringBuilder.append(':'); - - if(seconds < 10) { - pStringBuilder.append('0'); - } - pStringBuilder.append(seconds); - - return pStringBuilder.toString(); - } - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + // =========================================================== + // Constructors + // =========================================================== + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + public static String formatSeconds(final int pSecondsTotal) { + return formatSeconds(pSecondsTotal, new StringBuilder()); + } + + public static String formatSeconds(final int pSecondsTotal, final StringBuilder pStringBuilder) { + final int minutes = pSecondsTotal / SECONDSPERMINUTE; + final int seconds = pSecondsTotal % SECONDSPERMINUTE; + + pStringBuilder.append(minutes); + pStringBuilder.append(':'); + + if(seconds < 10) { + pStringBuilder.append('0'); + } + pStringBuilder.append(seconds); + + return pStringBuilder.toString(); + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/util/Transformation.java b/AndEngine/src/org/anddev/andengine/util/Transformation.java index 9df098ff..4ba2f0aa 100644 --- a/AndEngine/src/org/anddev/andengine/util/Transformation.java +++ b/AndEngine/src/org/anddev/andengine/util/Transformation.java @@ -29,225 +29,225 @@ * @since 15:47:18 - 23.12.2010 */ public class Transformation { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - private float a = 1.0f; /* x scale */ - private float b = 0.0f; /* y skew */ - private float c = 0.0f; /* x skew */ - private float d = 1.0f; /* y scale */ - private float tx = 0.0f; /* x translation */ - private float ty = 0.0f; /* y translation */ - - // =========================================================== - // Constructors - // =========================================================== - - public Transformation() { - - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - public String toString() { - return "Transformation{[" + this.a + ", " + this.c + ", " + this.tx + "][" + this.b + ", " + this.d + ", " + this.ty + "][0.0, 0.0, 1.0]}"; - } - - // =========================================================== - // Methods - // =========================================================== - - public void reset() { - this.setToIdentity(); - } - - public void setToIdentity() { - this.a = 1.0f; - this.d = 1.0f; - - this.b = 0.0f; - this.c = 0.0f; - this.tx = 0.0f; - this.ty = 0.0f; - } - - public void setTo(final Transformation pTransformation) { - this.a = pTransformation.a; - this.d = pTransformation.d; - - this.b = pTransformation.b; - this.c = pTransformation.c; - this.tx = pTransformation.tx; - this.ty = pTransformation.ty; - } - - public void preTranslate(final float pX, final float pY) { - this.tx += pX * this.a + pY * this.c; - this.ty += pX * this.b + pY * this.d; - } - - public void postTranslate(final float pX, final float pY) { - this.tx += pX; - this.ty += pY; - } - - public Transformation setToTranslate(final float pX, final float pY) { - this.a = 1.0f; - this.b = 0.0f; - this.c = 0.0f; - this.d = 1.0f; - this.tx = pX; - this.ty = pY; - - return this; - } - - public void preScale(final float pScaleX, final float pScaleY) { - this.a *= pScaleX; - this.b *= pScaleX; - this.c *= pScaleY; - this.d *= pScaleY; - } - - public void postScale(final float pScaleX, final float pScaleY) { - this.a = this.a * pScaleX; - this.b = this.b * pScaleY; - this.c = this.c * pScaleX; - this.d = this.d * pScaleY; - this.tx = this.tx * pScaleX; - this.ty = this.ty * pScaleY; - } - - public Transformation setToScale(final float pScaleX, final float pScaleY) { - this.a = pScaleX; - this.b = 0.0f; - this.c = 0.0f; - this.d = pScaleY; - this.tx = 0.0f; - this.ty = 0.0f; - - return this; - } - - public void preRotate(final float pAngle) { - final float angleRad = MathUtils.degToRad(pAngle); - - final float sin = (float) Math.sin(angleRad); - final float cos = (float) Math.cos(angleRad); - - final float a = this.a; - final float b = this.b; - final float c = this.c; - final float d = this.d; - - this.a = cos * a + sin * c; - this.b = cos * b + sin * d; - this.c = cos * c - sin * a; - this.d = cos * d - sin * b; - } - - public void postRotate(final float pAngle) { - final float angleRad = MathUtils.degToRad(pAngle); - - final float sin = (float) Math.sin(angleRad); - final float cos = (float) Math.cos(angleRad); - - final float a = this.a; - final float b = this.b; - final float c = this.c; - final float d = this.d; - final float tx = this.tx; - final float ty = this.ty; - - this.a = a * cos - b * sin; - this.b = a * sin + b * cos; - this.c = c * cos - d * sin; - this.d = c * sin + d * cos; - this.tx = tx * cos - ty * sin; - this.ty = tx * sin + ty * cos; - } - - public Transformation setToRotate(final float pAngle) { - final float angleRad = MathUtils.degToRad(pAngle); - - final float sin = (float) Math.sin(angleRad); - final float cos = (float) Math.cos(angleRad); - - this.a = cos; - this.b = sin; - this.c = -sin; - this.d = cos; - this.tx = 0.0f; - this.ty = 0.0f; - - return this; - } - - public void postConcat(final Transformation pTransformation) { - this.postConcat(pTransformation.a, pTransformation.b, pTransformation.c, pTransformation.d, pTransformation.tx, pTransformation.ty); - } - - private void postConcat(final float pA, final float pB, final float pC, final float pD, final float pTX, final float pTY) { - final float a = this.a; - final float b = this.b; - final float c = this.c; - final float d = this.d; - final float tx = this.tx; - final float ty = this.ty; - - this.a = a * pA + b * pC; - this.b = a * pB + b * pD; - this.c = c * pA + d * pC; - this.d = c * pB + d * pD; - this.tx = tx * pA + ty * pC + pTX; - this.ty = tx * pB + ty * pD + pTY; - } - - public void preConcat(final Transformation pTransformation) { - this.preConcat(pTransformation.a, pTransformation.b, pTransformation.c, pTransformation.d, pTransformation.tx, pTransformation.ty); - } - - private void preConcat(final float pA, final float pB, final float pC, final float pD, final float pTX, final float pTY) { - final float a = this.a; - final float b = this.b; - final float c = this.c; - final float d = this.d; - final float tx = this.tx; - final float ty = this.ty; - - this.a = pA * a + pB * c; - this.b = pA * b + pB * d; - this.c = pC * a + pD * c; - this.d = pC * b + pD * d; - this.tx = pTX * a + pTY * c + tx; - this.ty = pTX * b + pTY * d + ty; - } - - public void transform(final float[] pVertices) { - int count = pVertices.length >> 1; - int i = 0; - int j = 0; - while(--count >= 0) { - final float x = pVertices[i++]; - final float y = pVertices[i++]; - pVertices[j++] = x * this.a + y * this.c + this.tx; - pVertices[j++] = x * this.b + y * this.d + this.ty; - } - } - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== -} \ No newline at end of file + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + private float a = 1.0f; /* x scale */ + private float b = 0.0f; /* y skew */ + private float c = 0.0f; /* x skew */ + private float d = 1.0f; /* y scale */ + private float tx = 0.0f; /* x translation */ + private float ty = 0.0f; /* y translation */ + + // =========================================================== + // Constructors + // =========================================================== + + public Transformation() { + + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + public String toString() { + return "Transformation{[" + this.a + ", " + this.c + ", " + this.tx + "][" + this.b + ", " + this.d + ", " + this.ty + "][0.0, 0.0, 1.0]}"; + } + + // =========================================================== + // Methods + // =========================================================== + + public void reset() { + this.setToIdentity(); + } + + public void setToIdentity() { + this.a = 1.0f; + this.d = 1.0f; + + this.b = 0.0f; + this.c = 0.0f; + this.tx = 0.0f; + this.ty = 0.0f; + } + + public void setTo(final Transformation pTransformation) { + this.a = pTransformation.a; + this.d = pTransformation.d; + + this.b = pTransformation.b; + this.c = pTransformation.c; + this.tx = pTransformation.tx; + this.ty = pTransformation.ty; + } + + public void preTranslate(final float pX, final float pY) { + this.tx += pX * this.a + pY * this.c; + this.ty += pX * this.b + pY * this.d; + } + + public void postTranslate(final float pX, final float pY) { + this.tx += pX; + this.ty += pY; + } + + public Transformation setToTranslate(final float pX, final float pY) { + this.a = 1.0f; + this.b = 0.0f; + this.c = 0.0f; + this.d = 1.0f; + this.tx = pX; + this.ty = pY; + + return this; + } + + public void preScale(final float pScaleX, final float pScaleY) { + this.a *= pScaleX; + this.b *= pScaleX; + this.c *= pScaleY; + this.d *= pScaleY; + } + + public void postScale(final float pScaleX, final float pScaleY) { + this.a = this.a * pScaleX; + this.b = this.b * pScaleY; + this.c = this.c * pScaleX; + this.d = this.d * pScaleY; + this.tx = this.tx * pScaleX; + this.ty = this.ty * pScaleY; + } + + public Transformation setToScale(final float pScaleX, final float pScaleY) { + this.a = pScaleX; + this.b = 0.0f; + this.c = 0.0f; + this.d = pScaleY; + this.tx = 0.0f; + this.ty = 0.0f; + + return this; + } + + public void preRotate(final float pAngle) { + final float angleRad = MathUtils.degToRad(pAngle); + + final float sin = (float) Math.sin(angleRad); + final float cos = (float) Math.cos(angleRad); + + final float a = this.a; + final float b = this.b; + final float c = this.c; + final float d = this.d; + + this.a = cos * a + sin * c; + this.b = cos * b + sin * d; + this.c = cos * c - sin * a; + this.d = cos * d - sin * b; + } + + public void postRotate(final float pAngle) { + final float angleRad = MathUtils.degToRad(pAngle); + + final float sin = (float) Math.sin(angleRad); + final float cos = (float) Math.cos(angleRad); + + final float a = this.a; + final float b = this.b; + final float c = this.c; + final float d = this.d; + final float tx = this.tx; + final float ty = this.ty; + + this.a = a * cos - b * sin; + this.b = a * sin + b * cos; + this.c = c * cos - d * sin; + this.d = c * sin + d * cos; + this.tx = tx * cos - ty * sin; + this.ty = tx * sin + ty * cos; + } + + public Transformation setToRotate(final float pAngle) { + final float angleRad = MathUtils.degToRad(pAngle); + + final float sin = (float) Math.sin(angleRad); + final float cos = (float) Math.cos(angleRad); + + this.a = cos; + this.b = sin; + this.c = -sin; + this.d = cos; + this.tx = 0.0f; + this.ty = 0.0f; + + return this; + } + + public void postConcat(final Transformation pTransformation) { + this.postConcat(pTransformation.a, pTransformation.b, pTransformation.c, pTransformation.d, pTransformation.tx, pTransformation.ty); + } + + private void postConcat(final float pA, final float pB, final float pC, final float pD, final float pTX, final float pTY) { + final float a = this.a; + final float b = this.b; + final float c = this.c; + final float d = this.d; + final float tx = this.tx; + final float ty = this.ty; + + this.a = a * pA + b * pC; + this.b = a * pB + b * pD; + this.c = c * pA + d * pC; + this.d = c * pB + d * pD; + this.tx = tx * pA + ty * pC + pTX; + this.ty = tx * pB + ty * pD + pTY; + } + + public void preConcat(final Transformation pTransformation) { + this.preConcat(pTransformation.a, pTransformation.b, pTransformation.c, pTransformation.d, pTransformation.tx, pTransformation.ty); + } + + private void preConcat(final float pA, final float pB, final float pC, final float pD, final float pTX, final float pTY) { + final float a = this.a; + final float b = this.b; + final float c = this.c; + final float d = this.d; + final float tx = this.tx; + final float ty = this.ty; + + this.a = pA * a + pB * c; + this.b = pA * b + pB * d; + this.c = pC * a + pD * c; + this.d = pC * b + pD * d; + this.tx = pTX * a + pTY * c + tx; + this.ty = pTX * b + pTY * d + ty; + } + + public void transform(final float[] pVertices) { + int count = pVertices.length >> 1; + int i = 0; + int j = 0; + while(--count >= 0) { + final float x = pVertices[i++]; + final float y = pVertices[i++]; + pVertices[j++] = x * this.a + y * this.c + this.tx; + pVertices[j++] = x * this.b + y * this.d + this.ty; + } + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== +} diff --git a/AndEngine/src/org/anddev/andengine/util/TransformationPool.java b/AndEngine/src/org/anddev/andengine/util/TransformationPool.java index fd8dd5b0..fe9e5ad6 100644 --- a/AndEngine/src/org/anddev/andengine/util/TransformationPool.java +++ b/AndEngine/src/org/anddev/andengine/util/TransformationPool.java @@ -10,47 +10,47 @@ * @since 23:07:53 - 23.02.2011 */ public class TransformationPool { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - private static final GenericPool POOL = new GenericPool() { - @Override - protected Transformation onAllocatePoolItem() { - return new Transformation(); - } - }; - - // =========================================================== - // Constructors - // =========================================================== - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - public static Transformation obtain() { - return POOL.obtainPoolItem(); - } - - public static void recycle(final Transformation pTransformation) { - pTransformation.setToIdentity(); - POOL.recyclePoolItem(pTransformation); - } - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== -} \ No newline at end of file + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + private static final GenericPool POOL = new GenericPool() { + @Override + protected Transformation onAllocatePoolItem() { + return new Transformation(); + } + }; + + // =========================================================== + // Constructors + // =========================================================== + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + public static Transformation obtain() { + return POOL.obtainPoolItem(); + } + + public static void recycle(final Transformation pTransformation) { + pTransformation.setToIdentity(); + POOL.recyclePoolItem(pTransformation); + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== +} diff --git a/AndEngine/src/org/anddev/andengine/util/VerticalAlign.java b/AndEngine/src/org/anddev/andengine/util/VerticalAlign.java index deaca256..1baa6a85 100644 --- a/AndEngine/src/org/anddev/andengine/util/VerticalAlign.java +++ b/AndEngine/src/org/anddev/andengine/util/VerticalAlign.java @@ -8,39 +8,39 @@ * @since 15:15:23 - 24.07.2010 */ public enum VerticalAlign { - // =========================================================== - // Elements - // =========================================================== + // =========================================================== + // Elements + // =========================================================== - TOP, - CENTER, - BOTTOM; + TOP, + CENTER, + BOTTOM; - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods from SuperClass/Interfaces + // =========================================================== - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/util/ViewUtils.java b/AndEngine/src/org/anddev/andengine/util/ViewUtils.java index 342bc8b7..fe5f0bd1 100644 --- a/AndEngine/src/org/anddev/andengine/util/ViewUtils.java +++ b/AndEngine/src/org/anddev/andengine/util/ViewUtils.java @@ -13,39 +13,39 @@ * @since 20:55:35 - 08.09.2009 */ public class ViewUtils { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - public static View inflate(final Context pContext, final int pLayoutID){ - return LayoutInflater.from(pContext).inflate(pLayoutID, null); - } + public static View inflate(final Context pContext, final int pLayoutID){ + return LayoutInflater.from(pContext).inflate(pLayoutID, null); + } - public static View inflate(final Context pContext, final int pLayoutID, final ViewGroup pViewGroup){ - return LayoutInflater.from(pContext).inflate(pLayoutID, pViewGroup, true); - } + public static View inflate(final Context pContext, final int pLayoutID, final ViewGroup pViewGroup){ + return LayoutInflater.from(pContext).inflate(pLayoutID, pViewGroup, true); + } - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/util/cache/RectangleVertexBufferCache.java b/AndEngine/src/org/anddev/andengine/util/cache/RectangleVertexBufferCache.java index f0bbc959..3a5db936 100644 --- a/AndEngine/src/org/anddev/andengine/util/cache/RectangleVertexBufferCache.java +++ b/AndEngine/src/org/anddev/andengine/util/cache/RectangleVertexBufferCache.java @@ -15,59 +15,59 @@ * @since 21:10:05 - 09.01.2011 */ public class RectangleVertexBufferCache { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - private final int mDrawType; + private final int mDrawType; - private final MultiKeyHashMap mRectangleVertexBufferCache = new MultiKeyHashMap(); + private final MultiKeyHashMap mRectangleVertexBufferCache = new MultiKeyHashMap(); - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - public RectangleVertexBufferCache() { - this(GL11.GL_STATIC_DRAW); - } + public RectangleVertexBufferCache() { + this(GL11.GL_STATIC_DRAW); + } - public RectangleVertexBufferCache(final int pDrawType) { - this.mDrawType = pDrawType; - } + public RectangleVertexBufferCache(final int pDrawType) { + this.mDrawType = pDrawType; + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - public RectangleVertexBuffer get(final int pWidth, final int pHeight) { - final RectangleVertexBuffer cachedRectangleVertexBuffer = this.mRectangleVertexBufferCache.get(pWidth, pHeight); - if(cachedRectangleVertexBuffer != null) { - return cachedRectangleVertexBuffer; - } else { - return this.put(pWidth, pHeight, new RectangleVertexBuffer(this.mDrawType, false)); - } - } + public RectangleVertexBuffer get(final int pWidth, final int pHeight) { + final RectangleVertexBuffer cachedRectangleVertexBuffer = this.mRectangleVertexBufferCache.get(pWidth, pHeight); + if(cachedRectangleVertexBuffer != null) { + return cachedRectangleVertexBuffer; + } else { + return this.put(pWidth, pHeight, new RectangleVertexBuffer(this.mDrawType, false)); + } + } - public RectangleVertexBuffer put(final int pWidth, final int pHeight, final RectangleVertexBuffer pRectangleVertexBuffer) { - pRectangleVertexBuffer.update(pWidth, pHeight); - BufferObjectManager.getActiveInstance().loadBufferObject(pRectangleVertexBuffer); - this.mRectangleVertexBufferCache.put(new MultiKey(pWidth, pHeight), pRectangleVertexBuffer); - return pRectangleVertexBuffer; - } + public RectangleVertexBuffer put(final int pWidth, final int pHeight, final RectangleVertexBuffer pRectangleVertexBuffer) { + pRectangleVertexBuffer.update(pWidth, pHeight); + BufferObjectManager.getActiveInstance().loadBufferObject(pRectangleVertexBuffer); + this.mRectangleVertexBufferCache.put(new MultiKey(pWidth, pHeight), pRectangleVertexBuffer); + return pRectangleVertexBuffer; + } - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/util/constants/ColorConstants.java b/AndEngine/src/org/anddev/andengine/util/constants/ColorConstants.java index 12b5e846..096c2a45 100644 --- a/AndEngine/src/org/anddev/andengine/util/constants/ColorConstants.java +++ b/AndEngine/src/org/anddev/andengine/util/constants/ColorConstants.java @@ -8,13 +8,13 @@ * @since 10:21:46 - 19.07.2010 */ public interface ColorConstants { - // =========================================================== - // Final Fields - // =========================================================== + // =========================================================== + // Final Fields + // =========================================================== - public static final float COLOR_FACTOR_INT_TO_FLOAT = 255.0f; + public static final float COLOR_FACTOR_INT_TO_FLOAT = 255.0f; - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/util/constants/Constants.java b/AndEngine/src/org/anddev/andengine/util/constants/Constants.java index 4bf1d81f..3d040add 100644 --- a/AndEngine/src/org/anddev/andengine/util/constants/Constants.java +++ b/AndEngine/src/org/anddev/andengine/util/constants/Constants.java @@ -8,16 +8,16 @@ * @since 13:52:21 - 08.03.2010 */ public interface Constants { - // =========================================================== - // Final Fields - // =========================================================== + // =========================================================== + // Final Fields + // =========================================================== - public static final String DEBUGTAG = "AndEngine"; + public static final String DEBUGTAG = "AndEngine"; - public static final int VERTEX_INDEX_X = 0; - public static final int VERTEX_INDEX_Y = 1; + public static final int VERTEX_INDEX_X = 0; + public static final int VERTEX_INDEX_Y = 1; - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/util/constants/DataConstants.java b/AndEngine/src/org/anddev/andengine/util/constants/DataConstants.java index 5aeb0b09..ebfcca8a 100644 --- a/AndEngine/src/org/anddev/andengine/util/constants/DataConstants.java +++ b/AndEngine/src/org/anddev/andengine/util/constants/DataConstants.java @@ -9,22 +9,22 @@ * @since 17:59:55 - 14.07.2011 */ public interface DataConstants { - // =========================================================== - // Final Fields - // =========================================================== + // =========================================================== + // Final Fields + // =========================================================== - public static final int BITS_PER_BYTE = 8; + public static final int BITS_PER_BYTE = 8; - 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_INT = Integer.SIZE / Byte.SIZE; - public static final int BYTES_PER_FLOAT = Float.SIZE / Byte.SIZE; - public static final int BYTES_PER_LONG = Long.SIZE / Byte.SIZE; + 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_INT = Integer.SIZE / Byte.SIZE; + public static final int BYTES_PER_FLOAT = Float.SIZE / Byte.SIZE; + public static final int BYTES_PER_LONG = Long.SIZE / Byte.SIZE; - public static final int BYTES_PER_KILOBYTE = 1024; - public static final int BYTES_PER_MEGABYTE = 1024 * DataConstants.BYTES_PER_KILOBYTE; + public static final int BYTES_PER_KILOBYTE = 1024; + public static final int BYTES_PER_MEGABYTE = 1024 * DataConstants.BYTES_PER_KILOBYTE; - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/util/constants/MIMETypes.java b/AndEngine/src/org/anddev/andengine/util/constants/MIMETypes.java index 2fc24391..2776c54c 100644 --- a/AndEngine/src/org/anddev/andengine/util/constants/MIMETypes.java +++ b/AndEngine/src/org/anddev/andengine/util/constants/MIMETypes.java @@ -8,15 +8,15 @@ * @since 14:58:20 - 10.01.2011 */ public interface MIMETypes { - // =========================================================== - // Final Fields - // =========================================================== + // =========================================================== + // Final Fields + // =========================================================== - public static final String JPEG = "image/jpeg"; - public static final String GIF = "image/gif"; - public static final String PNG = "image/png"; + public static final String JPEG = "image/jpeg"; + public static final String GIF = "image/gif"; + public static final String PNG = "image/png"; - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/util/constants/MathConstants.java b/AndEngine/src/org/anddev/andengine/util/constants/MathConstants.java index 88ff5f5b..efc931cc 100644 --- a/AndEngine/src/org/anddev/andengine/util/constants/MathConstants.java +++ b/AndEngine/src/org/anddev/andengine/util/constants/MathConstants.java @@ -8,19 +8,19 @@ * @since 16:49:25 - 26.07.2010 */ public interface MathConstants { - // =========================================================== - // Final Fields - // =========================================================== + // =========================================================== + // Final Fields + // =========================================================== - public static final float PI = (float) Math.PI; + public static final float PI = (float) Math.PI; - public static float PI_TWICE = PI * 2.0f; - public static float PI_HALF = PI * 0.5f; + public static float PI_TWICE = PI * 2.0f; + public static float PI_HALF = PI * 0.5f; - public static final float DEG_TO_RAD = PI / 180.0f; - public static final float RAD_TO_DEG = 180.0f / PI; + public static final float DEG_TO_RAD = PI / 180.0f; + public static final float RAD_TO_DEG = 180.0f / PI; - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/util/constants/TimeConstants.java b/AndEngine/src/org/anddev/andengine/util/constants/TimeConstants.java index d10433c2..ad8fff81 100644 --- a/AndEngine/src/org/anddev/andengine/util/constants/TimeConstants.java +++ b/AndEngine/src/org/anddev/andengine/util/constants/TimeConstants.java @@ -8,39 +8,39 @@ * @since 16:49:25 - 26.07.2010 */ public interface TimeConstants { - // =========================================================== - // Final Fields - // =========================================================== + // =========================================================== + // Final Fields + // =========================================================== - public static final int MONTHSPERYEAR = 12; + public static final int MONTHSPERYEAR = 12; - public static final int DAYSPERWEEK = 7; + public static final int DAYSPERWEEK = 7; - public static final int DAYSPERMONTH = 30; + public static final int DAYSPERMONTH = 30; - public static final int HOURSPERDAY = 24; + public static final int HOURSPERDAY = 24; - public static final int MINUTESPERHOUR = 60; + public static final int MINUTESPERHOUR = 60; - public static final int MILLISECONDSPERSECOND = 1000; - public static final int MICROSECONDSPERSECOND = 1000000; - public static final long NANOSECONDSPERSECOND = 1000000000; + public static final int MILLISECONDSPERSECOND = 1000; + public static final int MICROSECONDSPERSECOND = 1000000; + public static final long NANOSECONDSPERSECOND = 1000000000; - public static final long MICROSECONDSPERMILLISECOND = MICROSECONDSPERSECOND / MILLISECONDSPERSECOND; + public static final long MICROSECONDSPERMILLISECOND = MICROSECONDSPERSECOND / MILLISECONDSPERSECOND; - public static final long NANOSECONDSPERMICROSECOND = NANOSECONDSPERSECOND / MICROSECONDSPERSECOND; - public static final long NANOSECONDSPERMILLISECOND = NANOSECONDSPERSECOND / MILLISECONDSPERSECOND; + public static final long NANOSECONDSPERMICROSECOND = NANOSECONDSPERSECOND / MICROSECONDSPERSECOND; + public static final long NANOSECONDSPERMILLISECOND = NANOSECONDSPERSECOND / MILLISECONDSPERSECOND; - public static final float SECONDSPERNANOSECOND = 1f / NANOSECONDSPERSECOND; - public static final float SECONDSPERMICROSECOND = 1f / MICROSECONDSPERSECOND; - public static final float SECONDSPERMILLISECOND = 1f / MILLISECONDSPERSECOND; - public static final int SECONDSPERMINUTE = 60; - public static final int SECONDSPERHOUR = SECONDSPERMINUTE * MINUTESPERHOUR; - public static final int SECONDSPERDAY = SECONDSPERHOUR * HOURSPERDAY; - public static final int SECONDSPERWEEK = SECONDSPERDAY * DAYSPERWEEK; - public static final int SECONDSPERMONTH = SECONDSPERDAY * DAYSPERMONTH; - public static final int SECONDSPERYEAR = SECONDSPERMONTH * MONTHSPERYEAR; - // =========================================================== - // Methods - // =========================================================== + public static final float SECONDSPERNANOSECOND = 1f / NANOSECONDSPERSECOND; + public static final float SECONDSPERMICROSECOND = 1f / MICROSECONDSPERSECOND; + public static final float SECONDSPERMILLISECOND = 1f / MILLISECONDSPERSECOND; + public static final int SECONDSPERMINUTE = 60; + public static final int SECONDSPERHOUR = SECONDSPERMINUTE * MINUTESPERHOUR; + public static final int SECONDSPERDAY = SECONDSPERHOUR * HOURSPERDAY; + public static final int SECONDSPERWEEK = SECONDSPERDAY * DAYSPERWEEK; + public static final int SECONDSPERMONTH = SECONDSPERDAY * DAYSPERMONTH; + public static final int SECONDSPERYEAR = SECONDSPERMONTH * MONTHSPERYEAR; + // =========================================================== + // Methods + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/util/levelstats/LevelStatsDBConnector.java b/AndEngine/src/org/anddev/andengine/util/levelstats/LevelStatsDBConnector.java index abe77ac0..77007a8a 100644 --- a/AndEngine/src/org/anddev/andengine/util/levelstats/LevelStatsDBConnector.java +++ b/AndEngine/src/org/anddev/andengine/util/levelstats/LevelStatsDBConnector.java @@ -29,106 +29,106 @@ * @since 21:13:55 - 18.10.2010 */ public class LevelStatsDBConnector { - // =========================================================== - // Constants - // =========================================================== - - private static final String PREFERENCES_LEVELSTATSDBCONNECTOR_PLAYERID_ID = "preferences.levelstatsdbconnector.playerid"; - - // =========================================================== - // Fields - // =========================================================== - - private final String mSecret; - private final String mSubmitURL; - private final int mPlayerID; - - // =========================================================== - // Constructors - // =========================================================== - - public LevelStatsDBConnector(final Context pContext, final String pSecret, final String pSubmitURL) { - this.mSecret = pSecret; - this.mSubmitURL = pSubmitURL; - - final SharedPreferences simplePreferences = SimplePreferences.getInstance(pContext); - final int playerID = simplePreferences.getInt(PREFERENCES_LEVELSTATSDBCONNECTOR_PLAYERID_ID, -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(); - } - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - public void submitAsync(final int pLevelID, final boolean pSolved, final int pSecondsElapsed) { - this.submitAsync(pLevelID, pSolved, pSecondsElapsed, null); - } - - public void submitAsync(final int pLevelID, final boolean pSolved, final int pSecondsElapsed, final Callback pCallback) { - new Thread(new Runnable() { - @Override - public void run() { - try{ - /* Create a new HttpClient and Post Header. */ - final HttpClient httpClient = new DefaultHttpClient(); - final HttpPost httpPost = new HttpPost(LevelStatsDBConnector.this.mSubmitURL); - - /* Append POST data. */ - final List nameValuePairs = new ArrayList(5); - - nameValuePairs.add(new BasicNameValuePair("level_id", String.valueOf(pLevelID))); - nameValuePairs.add(new BasicNameValuePair("solved", (pSolved) ? "1" : "0")); - nameValuePairs.add(new BasicNameValuePair("secondsplayed", String.valueOf(pSecondsElapsed))); - nameValuePairs.add(new BasicNameValuePair("player_id", String.valueOf(LevelStatsDBConnector.this.mPlayerID))); - nameValuePairs.add(new BasicNameValuePair("secret", String.valueOf(LevelStatsDBConnector.this.mSecret))); - - httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); - - /* Execute HTTP Post Request. */ - final HttpResponse httpResponse = httpClient.execute(httpPost); - - final int statusCode = httpResponse.getStatusLine().getStatusCode(); - if(statusCode == HttpStatus.SC_OK) { - final String response = StreamUtils.readFully(httpResponse.getEntity().getContent()); - - if(response.equals("")) { - if(pCallback != null) { - pCallback.onCallback(true); - } - } else { - if(pCallback != null) { - pCallback.onCallback(false); - } - } - } else { - if(pCallback != null) { - pCallback.onCallback(false); - } - } - }catch(final IOException e) { - Debug.e(e); - if(pCallback != null) { - pCallback.onCallback(false); - } - } - } - }).start(); - } - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + private static final String PREFERENCES_LEVELSTATSDBCONNECTOR_PLAYERID_ID = "preferences.levelstatsdbconnector.playerid"; + + // =========================================================== + // Fields + // =========================================================== + + private final String mSecret; + private final String mSubmitURL; + private final int mPlayerID; + + // =========================================================== + // Constructors + // =========================================================== + + public LevelStatsDBConnector(final Context pContext, final String pSecret, final String pSubmitURL) { + this.mSecret = pSecret; + this.mSubmitURL = pSubmitURL; + + final SharedPreferences simplePreferences = SimplePreferences.getInstance(pContext); + final int playerID = simplePreferences.getInt(PREFERENCES_LEVELSTATSDBCONNECTOR_PLAYERID_ID, -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(); + } + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + public void submitAsync(final int pLevelID, final boolean pSolved, final int pSecondsElapsed) { + this.submitAsync(pLevelID, pSolved, pSecondsElapsed, null); + } + + public void submitAsync(final int pLevelID, final boolean pSolved, final int pSecondsElapsed, final Callback pCallback) { + new Thread(new Runnable() { + @Override + public void run() { + try{ + /* Create a new HttpClient and Post Header. */ + final HttpClient httpClient = new DefaultHttpClient(); + final HttpPost httpPost = new HttpPost(LevelStatsDBConnector.this.mSubmitURL); + + /* Append POST data. */ + final List nameValuePairs = new ArrayList(5); + + nameValuePairs.add(new BasicNameValuePair("level_id", String.valueOf(pLevelID))); + nameValuePairs.add(new BasicNameValuePair("solved", (pSolved) ? "1" : "0")); + nameValuePairs.add(new BasicNameValuePair("secondsplayed", String.valueOf(pSecondsElapsed))); + nameValuePairs.add(new BasicNameValuePair("player_id", String.valueOf(LevelStatsDBConnector.this.mPlayerID))); + nameValuePairs.add(new BasicNameValuePair("secret", String.valueOf(LevelStatsDBConnector.this.mSecret))); + + httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); + + /* Execute HTTP Post Request. */ + final HttpResponse httpResponse = httpClient.execute(httpPost); + + final int statusCode = httpResponse.getStatusLine().getStatusCode(); + if(statusCode == HttpStatus.SC_OK) { + final String response = StreamUtils.readFully(httpResponse.getEntity().getContent()); + + if(response.equals("")) { + if(pCallback != null) { + pCallback.onCallback(true); + } + } else { + if(pCallback != null) { + pCallback.onCallback(false); + } + } + } else { + if(pCallback != null) { + pCallback.onCallback(false); + } + } + }catch(final IOException e) { + Debug.e(e); + if(pCallback != null) { + pCallback.onCallback(false); + } + } + } + }).start(); + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/util/modifier/BaseDoubleValueChangeModifier.java b/AndEngine/src/org/anddev/andengine/util/modifier/BaseDoubleValueChangeModifier.java index bd08877d..fbfa99e4 100644 --- a/AndEngine/src/org/anddev/andengine/util/modifier/BaseDoubleValueChangeModifier.java +++ b/AndEngine/src/org/anddev/andengine/util/modifier/BaseDoubleValueChangeModifier.java @@ -8,56 +8,56 @@ * @since 14:17:30 - 10.08.2011 */ public abstract class BaseDoubleValueChangeModifier extends BaseSingleValueChangeModifier { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - private float mValueChangeBPerSecond; + private float mValueChangeBPerSecond; - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - public BaseDoubleValueChangeModifier(final float pDuration, final float pValueChangeA, final float pValueChangeB) { - this(pDuration, pValueChangeA, pValueChangeB, null); - } + public BaseDoubleValueChangeModifier(final float pDuration, final float pValueChangeA, final float pValueChangeB) { + this(pDuration, pValueChangeA, pValueChangeB, null); + } - public BaseDoubleValueChangeModifier(final float pDuration, final float pValueChangeA, final float pValueChangeB, final IModifierListener pModifierListener) { - super(pDuration, pValueChangeA, pModifierListener); + public BaseDoubleValueChangeModifier(final float pDuration, final float pValueChangeA, final float pValueChangeB, final IModifierListener pModifierListener) { + super(pDuration, pValueChangeA, pModifierListener); - this.mValueChangeBPerSecond = pValueChangeB / pDuration; - } + this.mValueChangeBPerSecond = pValueChangeB / pDuration; + } - protected BaseDoubleValueChangeModifier(final BaseDoubleValueChangeModifier pBaseDoubleValueChangeModifier) { - super(pBaseDoubleValueChangeModifier); + protected BaseDoubleValueChangeModifier(final BaseDoubleValueChangeModifier pBaseDoubleValueChangeModifier) { + super(pBaseDoubleValueChangeModifier); - this.mValueChangeBPerSecond = pBaseDoubleValueChangeModifier.mValueChangeBPerSecond; - } + this.mValueChangeBPerSecond = pBaseDoubleValueChangeModifier.mValueChangeBPerSecond; + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - @Override - protected void onChangeValue(final float pSecondsElapsed, final T pItem, final float pValueA) { - this.onChangeValues(pSecondsElapsed, pItem, pValueA, pSecondsElapsed * this.mValueChangeBPerSecond); - } + @Override + protected void onChangeValue(final float pSecondsElapsed, final T pItem, final float pValueA) { + this.onChangeValues(pSecondsElapsed, pItem, pValueA, pSecondsElapsed * this.mValueChangeBPerSecond); + } - protected abstract void onChangeValues(float pSecondsElapsed, T pItem, float pValueA, float pValueB); + protected abstract void onChangeValues(float pSecondsElapsed, T pItem, float pValueA, float pValueB); - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/util/modifier/BaseDoubleValueSpanModifier.java b/AndEngine/src/org/anddev/andengine/util/modifier/BaseDoubleValueSpanModifier.java index cc093e9d..e879e322 100644 --- a/AndEngine/src/org/anddev/andengine/util/modifier/BaseDoubleValueSpanModifier.java +++ b/AndEngine/src/org/anddev/andengine/util/modifier/BaseDoubleValueSpanModifier.java @@ -11,71 +11,71 @@ * @param */ public abstract class BaseDoubleValueSpanModifier extends BaseSingleValueSpanModifier { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - private final float mFromValueB; - private final float mValueSpanB; - - // =========================================================== - // Constructors - // =========================================================== - - public BaseDoubleValueSpanModifier(final float pDuration, final float pFromValueA, final float pToValueA, final float pFromValueB, final float pToValueB) { - this(pDuration, pFromValueA, pToValueA, pFromValueB, pToValueB, null, IEaseFunction.DEFAULT); - } - - public BaseDoubleValueSpanModifier(final float pDuration, final float pFromValueA, final float pToValueA, final float pFromValueB, final float pToValueB, final IEaseFunction pEaseFunction) { - this(pDuration, pFromValueA, pToValueA, pFromValueB, pToValueB, null, pEaseFunction); - } - - public BaseDoubleValueSpanModifier(final float pDuration, final float pFromValueA, final float pToValueA, final float pFromValueB, final float pToValueB, final IModifierListener pModifierListener) { - this(pDuration, pFromValueA, pToValueA, pFromValueB, pToValueB, pModifierListener, IEaseFunction.DEFAULT); - } - - public BaseDoubleValueSpanModifier(final float pDuration, final float pFromValueA, final float pToValueA, final float pFromValueB, final float pToValueB, final IModifierListener pModifierListener, final IEaseFunction pEaseFunction) { - super(pDuration, pFromValueA, pToValueA, pModifierListener, pEaseFunction); - this.mFromValueB = pFromValueB; - this.mValueSpanB = pToValueB - pFromValueB; - } - - protected BaseDoubleValueSpanModifier(final BaseDoubleValueSpanModifier pBaseDoubleValueSpanModifier) { - super(pBaseDoubleValueSpanModifier); - this.mFromValueB = pBaseDoubleValueSpanModifier.mFromValueB; - this.mValueSpanB = pBaseDoubleValueSpanModifier.mValueSpanB; - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - protected abstract void onSetInitialValues(final T pItem, final float pValueA, final float pValueB); - protected abstract void onSetValues(final T pItem, final float pPercentageDone, final float pValueA, final float pValueB); - - @Override - protected void onSetInitialValue(final T pItem, final float pValueA) { - this.onSetInitialValues(pItem, pValueA, this.mFromValueB); - } - - @Override - protected void onSetValue(final T pItem, final float pPercentageDone, final float pValueA) { - this.onSetValues(pItem, pPercentageDone, pValueA, this.mFromValueB + pPercentageDone * this.mValueSpanB); - } - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + private final float mFromValueB; + private final float mValueSpanB; + + // =========================================================== + // Constructors + // =========================================================== + + public BaseDoubleValueSpanModifier(final float pDuration, final float pFromValueA, final float pToValueA, final float pFromValueB, final float pToValueB) { + this(pDuration, pFromValueA, pToValueA, pFromValueB, pToValueB, null, IEaseFunction.DEFAULT); + } + + public BaseDoubleValueSpanModifier(final float pDuration, final float pFromValueA, final float pToValueA, final float pFromValueB, final float pToValueB, final IEaseFunction pEaseFunction) { + this(pDuration, pFromValueA, pToValueA, pFromValueB, pToValueB, null, pEaseFunction); + } + + public BaseDoubleValueSpanModifier(final float pDuration, final float pFromValueA, final float pToValueA, final float pFromValueB, final float pToValueB, final IModifierListener pModifierListener) { + this(pDuration, pFromValueA, pToValueA, pFromValueB, pToValueB, pModifierListener, IEaseFunction.DEFAULT); + } + + public BaseDoubleValueSpanModifier(final float pDuration, final float pFromValueA, final float pToValueA, final float pFromValueB, final float pToValueB, final IModifierListener pModifierListener, final IEaseFunction pEaseFunction) { + super(pDuration, pFromValueA, pToValueA, pModifierListener, pEaseFunction); + this.mFromValueB = pFromValueB; + this.mValueSpanB = pToValueB - pFromValueB; + } + + protected BaseDoubleValueSpanModifier(final BaseDoubleValueSpanModifier pBaseDoubleValueSpanModifier) { + super(pBaseDoubleValueSpanModifier); + this.mFromValueB = pBaseDoubleValueSpanModifier.mFromValueB; + this.mValueSpanB = pBaseDoubleValueSpanModifier.mValueSpanB; + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + protected abstract void onSetInitialValues(final T pItem, final float pValueA, final float pValueB); + protected abstract void onSetValues(final T pItem, final float pPercentageDone, final float pValueA, final float pValueB); + + @Override + protected void onSetInitialValue(final T pItem, final float pValueA) { + this.onSetInitialValues(pItem, pValueA, this.mFromValueB); + } + + @Override + protected void onSetValue(final T pItem, final float pPercentageDone, final float pValueA) { + this.onSetValues(pItem, pPercentageDone, pValueA, this.mFromValueB + pPercentageDone * this.mValueSpanB); + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/util/modifier/BaseDurationModifier.java b/AndEngine/src/org/anddev/andengine/util/modifier/BaseDurationModifier.java index 509f8b6b..dbfcdda1 100644 --- a/AndEngine/src/org/anddev/andengine/util/modifier/BaseDurationModifier.java +++ b/AndEngine/src/org/anddev/andengine/util/modifier/BaseDurationModifier.java @@ -11,96 +11,96 @@ * @param */ public abstract class BaseDurationModifier extends BaseModifier { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - private float mSecondsElapsed; - protected float mDuration; - - // =========================================================== - // Constructors - // =========================================================== - - public BaseDurationModifier(final float pDuration) { - this.mDuration = pDuration; - } - - public BaseDurationModifier(final float pDuration, final IModifierListener pModifierListener) { - super(pModifierListener); - this.mDuration = pDuration; - } - - protected BaseDurationModifier(final BaseDurationModifier pBaseModifier) { - this(pBaseModifier.mDuration); - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - @Override - public float getSecondsElapsed() { - return this.mSecondsElapsed; - } - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - public float getDuration() { - return this.mDuration; - } - - protected abstract void onManagedUpdate(final float pSecondsElapsed, final T pItem); - - protected abstract void onManagedInitialize(final T pItem); - - @Override - public final float onUpdate(final float pSecondsElapsed, final T pItem) { - if(this.mFinished){ - return 0; - } else { - if(this.mSecondsElapsed == 0) { - this.onManagedInitialize(pItem); - this.onModifierStarted(pItem); - } - - final float secondsElapsedUsed; - if(this.mSecondsElapsed + pSecondsElapsed < this.mDuration) { - secondsElapsedUsed = pSecondsElapsed; - } else { - secondsElapsedUsed = this.mDuration - this.mSecondsElapsed; - } - - this.mSecondsElapsed += secondsElapsedUsed; - this.onManagedUpdate(secondsElapsedUsed, pItem); - - if(this.mDuration != -1 && this.mSecondsElapsed >= this.mDuration) { - this.mSecondsElapsed = this.mDuration; - this.mFinished = true; - this.onModifierFinished(pItem); - } - return secondsElapsedUsed; - } - } - - @Override - public void reset() { - this.mFinished = false; - this.mSecondsElapsed = 0; - } - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + private float mSecondsElapsed; + protected float mDuration; + + // =========================================================== + // Constructors + // =========================================================== + + public BaseDurationModifier(final float pDuration) { + this.mDuration = pDuration; + } + + public BaseDurationModifier(final float pDuration, final IModifierListener pModifierListener) { + super(pModifierListener); + this.mDuration = pDuration; + } + + protected BaseDurationModifier(final BaseDurationModifier pBaseModifier) { + this(pBaseModifier.mDuration); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + @Override + public float getSecondsElapsed() { + return this.mSecondsElapsed; + } + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + public float getDuration() { + return this.mDuration; + } + + protected abstract void onManagedUpdate(final float pSecondsElapsed, final T pItem); + + protected abstract void onManagedInitialize(final T pItem); + + @Override + public final float onUpdate(final float pSecondsElapsed, final T pItem) { + if(this.mFinished){ + return 0; + } else { + if(this.mSecondsElapsed == 0) { + this.onManagedInitialize(pItem); + this.onModifierStarted(pItem); + } + + final float secondsElapsedUsed; + if(this.mSecondsElapsed + pSecondsElapsed < this.mDuration) { + secondsElapsedUsed = pSecondsElapsed; + } else { + secondsElapsedUsed = this.mDuration - this.mSecondsElapsed; + } + + this.mSecondsElapsed += secondsElapsedUsed; + this.onManagedUpdate(secondsElapsedUsed, pItem); + + if(this.mDuration != -1 && this.mSecondsElapsed >= this.mDuration) { + this.mSecondsElapsed = this.mDuration; + this.mFinished = true; + this.onModifierFinished(pItem); + } + return secondsElapsedUsed; + } + } + + @Override + public void reset() { + this.mFinished = false; + this.mSecondsElapsed = 0; + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/util/modifier/BaseModifier.java b/AndEngine/src/org/anddev/andengine/util/modifier/BaseModifier.java index 2ee70d5c..044cb641 100644 --- a/AndEngine/src/org/anddev/andengine/util/modifier/BaseModifier.java +++ b/AndEngine/src/org/anddev/andengine/util/modifier/BaseModifier.java @@ -12,93 +12,93 @@ * @param */ public abstract class BaseModifier implements IModifier { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - protected boolean mFinished; - private boolean mRemoveWhenFinished = true; - protected final SmartList> mModifierListeners = new SmartList>(2); - - // =========================================================== - // Constructors - // =========================================================== - - public BaseModifier() { - - } - - public BaseModifier(final IModifierListener pModifierListener) { - this.addModifierListener(pModifierListener); - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - public boolean isFinished() { - return this.mFinished; - } - - @Override - public final boolean isRemoveWhenFinished() { - return this.mRemoveWhenFinished; - } - - @Override - public final void setRemoveWhenFinished(final boolean pRemoveWhenFinished) { - this.mRemoveWhenFinished = pRemoveWhenFinished; - } - - @Override - public void addModifierListener(final IModifierListener pModifierListener) { - if(pModifierListener != null) { - this.mModifierListeners.add(pModifierListener); - } - } - - @Override - public boolean removeModifierListener(final IModifierListener pModifierListener) { - if(pModifierListener == null) { - return false; - } else { - return this.mModifierListeners.remove(pModifierListener); - } - } - - @Override - public abstract IModifier deepCopy() throws DeepCopyNotSupportedException; - - // =========================================================== - // Methods - // =========================================================== - - protected void onModifierStarted(final T pItem) { - final SmartList> modifierListeners = this.mModifierListeners; - final int modifierListenerCount = modifierListeners.size(); - for(int i = modifierListenerCount - 1; i >= 0; i--) { - modifierListeners.get(i).onModifierStarted(this, 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--) { - modifierListeners.get(i).onModifierFinished(this, pItem); - } - } - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + protected boolean mFinished; + private boolean mRemoveWhenFinished = true; + protected final SmartList> mModifierListeners = new SmartList>(2); + + // =========================================================== + // Constructors + // =========================================================== + + public BaseModifier() { + + } + + public BaseModifier(final IModifierListener pModifierListener) { + this.addModifierListener(pModifierListener); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + public boolean isFinished() { + return this.mFinished; + } + + @Override + public final boolean isRemoveWhenFinished() { + return this.mRemoveWhenFinished; + } + + @Override + public final void setRemoveWhenFinished(final boolean pRemoveWhenFinished) { + this.mRemoveWhenFinished = pRemoveWhenFinished; + } + + @Override + public void addModifierListener(final IModifierListener pModifierListener) { + if(pModifierListener != null) { + this.mModifierListeners.add(pModifierListener); + } + } + + @Override + public boolean removeModifierListener(final IModifierListener pModifierListener) { + if(pModifierListener == null) { + return false; + } else { + return this.mModifierListeners.remove(pModifierListener); + } + } + + @Override + public abstract IModifier deepCopy() throws DeepCopyNotSupportedException; + + // =========================================================== + // Methods + // =========================================================== + + protected void onModifierStarted(final T pItem) { + final SmartList> modifierListeners = this.mModifierListeners; + final int modifierListenerCount = modifierListeners.size(); + for(int i = modifierListenerCount - 1; i >= 0; i--) { + modifierListeners.get(i).onModifierStarted(this, 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--) { + modifierListeners.get(i).onModifierFinished(this, pItem); + } + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/util/modifier/BaseSingleValueChangeModifier.java b/AndEngine/src/org/anddev/andengine/util/modifier/BaseSingleValueChangeModifier.java index 670841cb..181dc814 100644 --- a/AndEngine/src/org/anddev/andengine/util/modifier/BaseSingleValueChangeModifier.java +++ b/AndEngine/src/org/anddev/andengine/util/modifier/BaseSingleValueChangeModifier.java @@ -10,59 +10,59 @@ * @param */ public abstract class BaseSingleValueChangeModifier extends BaseDurationModifier { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - private final float mValueChangePerSecond; + private final float mValueChangePerSecond; - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - public BaseSingleValueChangeModifier(final float pDuration, final float pValueChange) { - this(pDuration, pValueChange, null); - } + public BaseSingleValueChangeModifier(final float pDuration, final float pValueChange) { + this(pDuration, pValueChange, null); + } - public BaseSingleValueChangeModifier(final float pDuration, final float pValueChange, final IModifierListener pModifierListener) { - super(pDuration, pModifierListener); - this.mValueChangePerSecond = pValueChange / pDuration; - } + public BaseSingleValueChangeModifier(final float pDuration, final float pValueChange, final IModifierListener pModifierListener) { + super(pDuration, pModifierListener); + this.mValueChangePerSecond = pValueChange / pDuration; + } - protected BaseSingleValueChangeModifier(final BaseSingleValueChangeModifier pBaseSingleValueChangeModifier) { - super(pBaseSingleValueChangeModifier); - this.mValueChangePerSecond = pBaseSingleValueChangeModifier.mValueChangePerSecond; - } + protected BaseSingleValueChangeModifier(final BaseSingleValueChangeModifier pBaseSingleValueChangeModifier) { + super(pBaseSingleValueChangeModifier); + this.mValueChangePerSecond = pBaseSingleValueChangeModifier.mValueChangePerSecond; + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - protected abstract void onChangeValue(final float pSecondsElapsed, final T pItem, final float pValue); + protected abstract void onChangeValue(final float pSecondsElapsed, final T pItem, final float pValue); - @Override - protected void onManagedInitialize(final T pItem) { + @Override + protected void onManagedInitialize(final T pItem) { - } + } - @Override - protected void onManagedUpdate(final float pSecondsElapsed, final T pItem) { - this.onChangeValue(pSecondsElapsed, pItem, this.mValueChangePerSecond * pSecondsElapsed); - } + @Override + protected void onManagedUpdate(final float pSecondsElapsed, final T pItem) { + this.onChangeValue(pSecondsElapsed, pItem, this.mValueChangePerSecond * pSecondsElapsed); + } - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/util/modifier/BaseSingleValueSpanModifier.java b/AndEngine/src/org/anddev/andengine/util/modifier/BaseSingleValueSpanModifier.java index 6857979b..9355d8c8 100644 --- a/AndEngine/src/org/anddev/andengine/util/modifier/BaseSingleValueSpanModifier.java +++ b/AndEngine/src/org/anddev/andengine/util/modifier/BaseSingleValueSpanModifier.java @@ -10,77 +10,77 @@ * @since 23:29:22 - 19.03.2010 */ public abstract class BaseSingleValueSpanModifier extends BaseDurationModifier { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - protected float mFromValue; - protected float mValueSpan; - - protected final IEaseFunction mEaseFunction; - - // =========================================================== - // Constructors - // =========================================================== - - public BaseSingleValueSpanModifier(final float pDuration, final float pFromValue, final float pToValue) { - this(pDuration, pFromValue, pToValue, null, IEaseFunction.DEFAULT); - } - - public BaseSingleValueSpanModifier(final float pDuration, final float pFromValue, final float pToValue, final IEaseFunction pEaseFunction) { - this(pDuration, pFromValue, pToValue, null, pEaseFunction); - } - - public BaseSingleValueSpanModifier(final float pDuration, final float pFromValue, final float pToValue, final IModifierListener pModifierListener) { - this(pDuration, pFromValue, pToValue, pModifierListener, IEaseFunction.DEFAULT); - } - - public BaseSingleValueSpanModifier(final float pDuration, final float pFromValue, final float pToValue, final IModifierListener pModifierListener, final IEaseFunction pEaseFunction) { - super(pDuration, pModifierListener); - this.mFromValue = pFromValue; - this.mValueSpan = pToValue - pFromValue; - this.mEaseFunction = pEaseFunction; - } - - protected BaseSingleValueSpanModifier(final BaseSingleValueSpanModifier pBaseSingleValueSpanModifier) { - super(pBaseSingleValueSpanModifier); - this.mFromValue = pBaseSingleValueSpanModifier.mFromValue; - this.mValueSpan = pBaseSingleValueSpanModifier.mValueSpan; - this.mEaseFunction = pBaseSingleValueSpanModifier.mEaseFunction; - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - protected abstract void onSetInitialValue(final T pItem, final float pValue); - protected abstract void onSetValue(final T pItem, final float pPercentageDone, final float pValue); - - @Override - protected void onManagedInitialize(final T pItem) { - this.onSetInitialValue(pItem, this.mFromValue); - } - - @Override - protected void onManagedUpdate(final float pSecondsElapsed, final T pItem) { - final float percentageDone = this.mEaseFunction.getPercentage(this.getSecondsElapsed(), this.mDuration); - - this.onSetValue(pItem, percentageDone, this.mFromValue + percentageDone * this.mValueSpan); - } - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + protected float mFromValue; + protected float mValueSpan; + + protected final IEaseFunction mEaseFunction; + + // =========================================================== + // Constructors + // =========================================================== + + public BaseSingleValueSpanModifier(final float pDuration, final float pFromValue, final float pToValue) { + this(pDuration, pFromValue, pToValue, null, IEaseFunction.DEFAULT); + } + + public BaseSingleValueSpanModifier(final float pDuration, final float pFromValue, final float pToValue, final IEaseFunction pEaseFunction) { + this(pDuration, pFromValue, pToValue, null, pEaseFunction); + } + + public BaseSingleValueSpanModifier(final float pDuration, final float pFromValue, final float pToValue, final IModifierListener pModifierListener) { + this(pDuration, pFromValue, pToValue, pModifierListener, IEaseFunction.DEFAULT); + } + + public BaseSingleValueSpanModifier(final float pDuration, final float pFromValue, final float pToValue, final IModifierListener pModifierListener, final IEaseFunction pEaseFunction) { + super(pDuration, pModifierListener); + this.mFromValue = pFromValue; + this.mValueSpan = pToValue - pFromValue; + this.mEaseFunction = pEaseFunction; + } + + protected BaseSingleValueSpanModifier(final BaseSingleValueSpanModifier pBaseSingleValueSpanModifier) { + super(pBaseSingleValueSpanModifier); + this.mFromValue = pBaseSingleValueSpanModifier.mFromValue; + this.mValueSpan = pBaseSingleValueSpanModifier.mValueSpan; + this.mEaseFunction = pBaseSingleValueSpanModifier.mEaseFunction; + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + protected abstract void onSetInitialValue(final T pItem, final float pValue); + protected abstract void onSetValue(final T pItem, final float pPercentageDone, final float pValue); + + @Override + protected void onManagedInitialize(final T pItem) { + this.onSetInitialValue(pItem, this.mFromValue); + } + + @Override + protected void onManagedUpdate(final float pSecondsElapsed, final T pItem) { + final float percentageDone = this.mEaseFunction.getPercentage(this.getSecondsElapsed(), this.mDuration); + + this.onSetValue(pItem, percentageDone, this.mFromValue + percentageDone * this.mValueSpan); + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/util/modifier/BaseTripleValueSpanModifier.java b/AndEngine/src/org/anddev/andengine/util/modifier/BaseTripleValueSpanModifier.java index 44bdf020..2786e989 100644 --- a/AndEngine/src/org/anddev/andengine/util/modifier/BaseTripleValueSpanModifier.java +++ b/AndEngine/src/org/anddev/andengine/util/modifier/BaseTripleValueSpanModifier.java @@ -11,63 +11,63 @@ * @param */ public abstract class BaseTripleValueSpanModifier extends BaseDoubleValueSpanModifier { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - private final float mFromValueC; - private final float mValueSpanC; + private final float mFromValueC; + private final float mValueSpanC; - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - public BaseTripleValueSpanModifier(final float pDuration, final float pFromValueA, final float pToValueA, final float pFromValueB, final float pToValueB, final float pFromValueC, final float pToValueC, final IEaseFunction pEaseFunction) { - this(pDuration, pFromValueA, pToValueA, pFromValueB, pToValueB, pFromValueC, pToValueC, null, pEaseFunction); - } + public BaseTripleValueSpanModifier(final float pDuration, final float pFromValueA, final float pToValueA, final float pFromValueB, final float pToValueB, final float pFromValueC, final float pToValueC, final IEaseFunction pEaseFunction) { + this(pDuration, pFromValueA, pToValueA, pFromValueB, pToValueB, pFromValueC, pToValueC, null, pEaseFunction); + } - public BaseTripleValueSpanModifier(final float pDuration, final float pFromValueA, final float pToValueA, final float pFromValueB, final float pToValueB, final float pFromValueC, final float pToValueC, final IModifierListener pModifierListener, final IEaseFunction pEaseFunction) { - super(pDuration, pFromValueA, pToValueA, pFromValueB, pToValueB, pModifierListener, pEaseFunction); - this.mFromValueC = pFromValueC; - this.mValueSpanC = pToValueC - pFromValueC; - } + public BaseTripleValueSpanModifier(final float pDuration, final float pFromValueA, final float pToValueA, final float pFromValueB, final float pToValueB, final float pFromValueC, final float pToValueC, final IModifierListener pModifierListener, final IEaseFunction pEaseFunction) { + super(pDuration, pFromValueA, pToValueA, pFromValueB, pToValueB, pModifierListener, pEaseFunction); + this.mFromValueC = pFromValueC; + this.mValueSpanC = pToValueC - pFromValueC; + } - protected BaseTripleValueSpanModifier(final BaseTripleValueSpanModifier pBaseTripleValueSpanModifier) { - super(pBaseTripleValueSpanModifier); - this.mFromValueC = pBaseTripleValueSpanModifier.mFromValueC; - this.mValueSpanC = pBaseTripleValueSpanModifier.mValueSpanC; - } + protected BaseTripleValueSpanModifier(final BaseTripleValueSpanModifier pBaseTripleValueSpanModifier) { + super(pBaseTripleValueSpanModifier); + this.mFromValueC = pBaseTripleValueSpanModifier.mFromValueC; + this.mValueSpanC = pBaseTripleValueSpanModifier.mValueSpanC; + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - protected abstract void onSetInitialValues(final T pItem, final float pValueA, final float pValueB, final float pValueC); - protected abstract void onSetValues(final T pItem, final float pPerctentageDone, final float pValueA, final float pValueB, final float pValueC); + protected abstract void onSetInitialValues(final T pItem, final float pValueA, final float pValueB, final float pValueC); + protected abstract void onSetValues(final T pItem, final float pPerctentageDone, final float pValueA, final float pValueB, final float pValueC); - @Override - protected void onSetInitialValues(final T pItem, final float pValueA, final float pValueB) { - this.onSetInitialValues(pItem, pValueA, pValueB, this.mFromValueC); - } + @Override + protected void onSetInitialValues(final T pItem, final float pValueA, final float pValueB) { + this.onSetInitialValues(pItem, pValueA, pValueB, this.mFromValueC); + } - @Override - protected void onSetValues(final T pItem, final float pPercentageDone, final float pValueA, final float pValueB) { - this.onSetValues(pItem, pPercentageDone, pValueA, pValueB, this.mFromValueC + pPercentageDone * this.mValueSpanC); - } + @Override + protected void onSetValues(final T pItem, final float pPercentageDone, final float pValueA, final float pValueB) { + this.onSetValues(pItem, pPercentageDone, pValueA, pValueB, this.mFromValueC + pPercentageDone * this.mValueSpanC); + } - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/util/modifier/IModifier.java b/AndEngine/src/org/anddev/andengine/util/modifier/IModifier.java index e66da029..19feeeda 100644 --- a/AndEngine/src/org/anddev/andengine/util/modifier/IModifier.java +++ b/AndEngine/src/org/anddev/andengine/util/modifier/IModifier.java @@ -11,92 +11,92 @@ * @since 11:17:50 - 19.03.2010 */ public interface IModifier { - // =========================================================== - // Final Fields - // =========================================================== - - public static final Comparator> MODIFIER_COMPARATOR_DURATION_DESCENDING = new Comparator>() { - @Override - public int compare(final IModifier pModifierA, final IModifier pModifierB) { - final float durationA = pModifierA.getDuration(); - final float durationB = pModifierB.getDuration(); - - if (durationA < durationB) { - return 1; - } else if (durationA > durationB) { - return -1; - } else { - return 0; - } - } - }; - - // =========================================================== - // Methods - // =========================================================== - - public void reset(); - - public boolean isFinished(); - public boolean isRemoveWhenFinished(); - public void setRemoveWhenFinished(final boolean pRemoveWhenFinished); - - public IModifier deepCopy() throws DeepCopyNotSupportedException; - - public float getSecondsElapsed(); - public float getDuration(); - - public float onUpdate(final float pSecondsElapsed, final T pItem); - - public void addModifierListener(final IModifierListener pModifierListener); - public boolean removeModifierListener(final IModifierListener pModifierListener); - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== - - public static interface IModifierListener { - // =========================================================== - // Final Fields - // =========================================================== - - // =========================================================== - // Methods - // =========================================================== - - public void onModifierStarted(final IModifier pModifier, final T pItem); - public void onModifierFinished(final IModifier pModifier, final T pItem); - } - - public static class DeepCopyNotSupportedException extends RuntimeException { - // =========================================================== - // Constants - // =========================================================== - - private static final long serialVersionUID = -5838035434002587320L; - - // =========================================================== - // Fields - // =========================================================== - - // =========================================================== - // Constructors - // =========================================================== - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== - } + // =========================================================== + // Final Fields + // =========================================================== + + public static final Comparator> MODIFIER_COMPARATOR_DURATION_DESCENDING = new Comparator>() { + @Override + public int compare(final IModifier pModifierA, final IModifier pModifierB) { + final float durationA = pModifierA.getDuration(); + final float durationB = pModifierB.getDuration(); + + if (durationA < durationB) { + return 1; + } else if (durationA > durationB) { + return -1; + } else { + return 0; + } + } + }; + + // =========================================================== + // Methods + // =========================================================== + + public void reset(); + + public boolean isFinished(); + public boolean isRemoveWhenFinished(); + public void setRemoveWhenFinished(final boolean pRemoveWhenFinished); + + public IModifier deepCopy() throws DeepCopyNotSupportedException; + + public float getSecondsElapsed(); + public float getDuration(); + + public float onUpdate(final float pSecondsElapsed, final T pItem); + + public void addModifierListener(final IModifierListener pModifierListener); + public boolean removeModifierListener(final IModifierListener pModifierListener); + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== + + public static interface IModifierListener { + // =========================================================== + // Final Fields + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + public void onModifierStarted(final IModifier pModifier, final T pItem); + public void onModifierFinished(final IModifier pModifier, final T pItem); + } + + public static class DeepCopyNotSupportedException extends RuntimeException { + // =========================================================== + // Constants + // =========================================================== + + private static final long serialVersionUID = -5838035434002587320L; + + // =========================================================== + // Fields + // =========================================================== + + // =========================================================== + // Constructors + // =========================================================== + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== + } } diff --git a/AndEngine/src/org/anddev/andengine/util/modifier/LoopModifier.java b/AndEngine/src/org/anddev/andengine/util/modifier/LoopModifier.java index 597ebf42..e892b005 100644 --- a/AndEngine/src/org/anddev/andengine/util/modifier/LoopModifier.java +++ b/AndEngine/src/org/anddev/andengine/util/modifier/LoopModifier.java @@ -12,167 +12,167 @@ * @param */ public class LoopModifier extends BaseModifier implements IModifierListener { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - public static final int LOOP_CONTINUOUS = -1; + public static final int LOOP_CONTINUOUS = -1; - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - private float mSecondsElapsed; - private final float mDuration; - - private final IModifier mModifier; + private float mSecondsElapsed; + private final float mDuration; + + private final IModifier mModifier; - private ILoopModifierListener mLoopModifierListener; - - private final int mLoopCount; - private int mLoop; - - private boolean mModifierStartedCalled; - private boolean mFinishedCached; + private ILoopModifierListener mLoopModifierListener; + + private final int mLoopCount; + private int mLoop; + + private boolean mModifierStartedCalled; + private boolean mFinishedCached; - // =========================================================== - // Constructors - // =========================================================== - - public LoopModifier(final IModifier pModifier) { - this(pModifier, LOOP_CONTINUOUS); - } - - public LoopModifier(final IModifier pModifier, final int pLoopCount) { - this(pModifier, pLoopCount, null, (IModifierListener)null); - } - - public LoopModifier(final IModifier pModifier, final int pLoopCount, final IModifierListener pModifierListener) { - this(pModifier, pLoopCount, null, pModifierListener); - } - - public LoopModifier(final IModifier pModifier, final int pLoopCount, final ILoopModifierListener pLoopModifierListener) { - this(pModifier, pLoopCount, pLoopModifierListener, (IModifierListener)null); - } - - public LoopModifier(final IModifier pModifier, final int pLoopCount, final ILoopModifierListener pLoopModifierListener, final IModifierListener pModifierListener) { - super(pModifierListener); - this.mModifier = pModifier; - this.mLoopCount = pLoopCount; - this.mLoopModifierListener = pLoopModifierListener; - - this.mLoop = 0; - this.mDuration = pLoopCount == LOOP_CONTINUOUS ? Float.POSITIVE_INFINITY : pModifier.getDuration() * pLoopCount; // TODO Check if POSITIVE_INFINITY works correct with i.e. SequenceModifier - - this.mModifier.addModifierListener(this); - } - - protected LoopModifier(final LoopModifier pLoopModifier) throws DeepCopyNotSupportedException { - this(pLoopModifier.mModifier.deepCopy(), pLoopModifier.mLoopCount); - } - - @Override - public LoopModifier deepCopy() throws DeepCopyNotSupportedException { - return new LoopModifier(this); - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - public ILoopModifierListener getLoopModifierListener() { - return this.mLoopModifierListener; - } - - public void setLoopModifierListener(final ILoopModifierListener pLoopModifierListener) { - this.mLoopModifierListener = pLoopModifierListener; - } - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - public float getSecondsElapsed() { - return this.mSecondsElapsed; - } - - @Override - public float getDuration() { - return this.mDuration; - } - - @Override - public float onUpdate(final float pSecondsElapsed, final T pItem) { - if(this.mFinished){ - return 0; - } else { - float secondsElapsedRemaining = pSecondsElapsed; - - this.mFinishedCached = false; - while(secondsElapsedRemaining > 0 && !this.mFinishedCached) { - secondsElapsedRemaining -= this.mModifier.onUpdate(secondsElapsedRemaining, pItem); - } - this.mFinishedCached = false; - - final float secondsElapsedUsed = pSecondsElapsed - secondsElapsedRemaining; - this.mSecondsElapsed += secondsElapsedUsed; - return secondsElapsedUsed; - } - } - - @Override - public void reset() { - this.mLoop = 0; - this.mSecondsElapsed = 0; - this.mModifierStartedCalled = false; - - this.mModifier.reset(); - } - - // =========================================================== - // Methods - // =========================================================== - - @Override - public void onModifierStarted(final IModifier pModifier, final T pItem) { - if(!this.mModifierStartedCalled) { - this.mModifierStartedCalled = true; - this.onModifierStarted(pItem); - } - 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) { - this.mLoopModifierListener.onLoopFinished(this, this.mLoop, this.mLoopCount); - } - - if(this.mLoopCount == LOOP_CONTINUOUS) { - this.mSecondsElapsed = 0; - this.mModifier.reset(); - } else { - this.mLoop++; - if(this.mLoop >= this.mLoopCount) { - this.mFinished = true; - this.mFinishedCached = true; - this.onModifierFinished(pItem); - } else { - this.mSecondsElapsed = 0; - this.mModifier.reset(); - } - } - } - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== - - public interface ILoopModifierListener { - public void onLoopStarted(final LoopModifier pLoopModifier, final int pLoop, final int pLoopCount); - public void onLoopFinished(final LoopModifier pLoopModifier, final int pLoop, final int pLoopCount); - } + // =========================================================== + // Constructors + // =========================================================== + + public LoopModifier(final IModifier pModifier) { + this(pModifier, LOOP_CONTINUOUS); + } + + public LoopModifier(final IModifier pModifier, final int pLoopCount) { + this(pModifier, pLoopCount, null, (IModifierListener)null); + } + + public LoopModifier(final IModifier pModifier, final int pLoopCount, final IModifierListener pModifierListener) { + this(pModifier, pLoopCount, null, pModifierListener); + } + + public LoopModifier(final IModifier pModifier, final int pLoopCount, final ILoopModifierListener pLoopModifierListener) { + this(pModifier, pLoopCount, pLoopModifierListener, (IModifierListener)null); + } + + public LoopModifier(final IModifier pModifier, final int pLoopCount, final ILoopModifierListener pLoopModifierListener, final IModifierListener pModifierListener) { + super(pModifierListener); + this.mModifier = pModifier; + this.mLoopCount = pLoopCount; + this.mLoopModifierListener = pLoopModifierListener; + + this.mLoop = 0; + this.mDuration = pLoopCount == LOOP_CONTINUOUS ? Float.POSITIVE_INFINITY : pModifier.getDuration() * pLoopCount; // TODO Check if POSITIVE_INFINITY works correct with i.e. SequenceModifier + + this.mModifier.addModifierListener(this); + } + + protected LoopModifier(final LoopModifier pLoopModifier) throws DeepCopyNotSupportedException { + this(pLoopModifier.mModifier.deepCopy(), pLoopModifier.mLoopCount); + } + + @Override + public LoopModifier deepCopy() throws DeepCopyNotSupportedException { + return new LoopModifier(this); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + public ILoopModifierListener getLoopModifierListener() { + return this.mLoopModifierListener; + } + + public void setLoopModifierListener(final ILoopModifierListener pLoopModifierListener) { + this.mLoopModifierListener = pLoopModifierListener; + } + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + public float getSecondsElapsed() { + return this.mSecondsElapsed; + } + + @Override + public float getDuration() { + return this.mDuration; + } + + @Override + public float onUpdate(final float pSecondsElapsed, final T pItem) { + if(this.mFinished){ + return 0; + } else { + float secondsElapsedRemaining = pSecondsElapsed; + + this.mFinishedCached = false; + while(secondsElapsedRemaining > 0 && !this.mFinishedCached) { + secondsElapsedRemaining -= this.mModifier.onUpdate(secondsElapsedRemaining, pItem); + } + this.mFinishedCached = false; + + final float secondsElapsedUsed = pSecondsElapsed - secondsElapsedRemaining; + this.mSecondsElapsed += secondsElapsedUsed; + return secondsElapsedUsed; + } + } + + @Override + public void reset() { + this.mLoop = 0; + this.mSecondsElapsed = 0; + this.mModifierStartedCalled = false; + + this.mModifier.reset(); + } + + // =========================================================== + // Methods + // =========================================================== + + @Override + public void onModifierStarted(final IModifier pModifier, final T pItem) { + if(!this.mModifierStartedCalled) { + this.mModifierStartedCalled = true; + this.onModifierStarted(pItem); + } + 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) { + this.mLoopModifierListener.onLoopFinished(this, this.mLoop, this.mLoopCount); + } + + if(this.mLoopCount == LOOP_CONTINUOUS) { + this.mSecondsElapsed = 0; + this.mModifier.reset(); + } else { + this.mLoop++; + if(this.mLoop >= this.mLoopCount) { + this.mFinished = true; + this.mFinishedCached = true; + this.onModifierFinished(pItem); + } else { + this.mSecondsElapsed = 0; + this.mModifier.reset(); + } + } + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== + + public interface ILoopModifierListener { + public void onLoopStarted(final LoopModifier pLoopModifier, final int pLoop, final int pLoopCount); + public void onLoopFinished(final LoopModifier pLoopModifier, final int pLoop, final int pLoopCount); + } } diff --git a/AndEngine/src/org/anddev/andengine/util/modifier/ModifierList.java b/AndEngine/src/org/anddev/andengine/util/modifier/ModifierList.java index faac4b6f..f6f9d5af 100644 --- a/AndEngine/src/org/anddev/andengine/util/modifier/ModifierList.java +++ b/AndEngine/src/org/anddev/andengine/util/modifier/ModifierList.java @@ -13,71 +13,71 @@ * @since 14:34:57 - 03.09.2010 */ public class ModifierList extends SmartList> implements IUpdateHandler { - // =========================================================== - // Constants - // =========================================================== - - private static final long serialVersionUID = 1610345592534873475L; - - // =========================================================== - // Fields - // =========================================================== - - private final T mTarget; - - // =========================================================== - // Constructors - // =========================================================== - - public ModifierList(final T pTarget) { - this.mTarget = pTarget; - } - - public ModifierList(final T pTarget, final int pCapacity){ - super(pCapacity); - this.mTarget = pTarget; - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - public T getTarget() { - return this.mTarget; - } - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - public void onUpdate(final float pSecondsElapsed) { - final ArrayList> modifiers = this; - final int modifierCount = this.size(); - if(modifierCount > 0) { - for(int i = modifierCount - 1; i >= 0; i--) { - final IModifier modifier = modifiers.get(i); - modifier.onUpdate(pSecondsElapsed, this.mTarget); - if(modifier.isFinished() && modifier.isRemoveWhenFinished()) { - modifiers.remove(i); - } - } - } - } - - @Override - public void reset() { - final ArrayList> modifiers = this; - for(int i = modifiers.size() - 1; i >= 0; i--) { - modifiers.get(i).reset(); - } - } - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + private static final long serialVersionUID = 1610345592534873475L; + + // =========================================================== + // Fields + // =========================================================== + + private final T mTarget; + + // =========================================================== + // Constructors + // =========================================================== + + public ModifierList(final T pTarget) { + this.mTarget = pTarget; + } + + public ModifierList(final T pTarget, final int pCapacity){ + super(pCapacity); + this.mTarget = pTarget; + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + public T getTarget() { + return this.mTarget; + } + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + public void onUpdate(final float pSecondsElapsed) { + final ArrayList> modifiers = this; + final int modifierCount = this.size(); + if(modifierCount > 0) { + for(int i = modifierCount - 1; i >= 0; i--) { + final IModifier modifier = modifiers.get(i); + modifier.onUpdate(pSecondsElapsed, this.mTarget); + if(modifier.isFinished() && modifier.isRemoveWhenFinished()) { + modifiers.remove(i); + } + } + } + } + + @Override + public void reset() { + final ArrayList> modifiers = this; + for(int i = modifiers.size() - 1; i >= 0; i--) { + modifiers.get(i).reset(); + } + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/util/modifier/ParallelModifier.java b/AndEngine/src/org/anddev/andengine/util/modifier/ParallelModifier.java index 39ce99ff..eecfe174 100644 --- a/AndEngine/src/org/anddev/andengine/util/modifier/ParallelModifier.java +++ b/AndEngine/src/org/anddev/andengine/util/modifier/ParallelModifier.java @@ -13,132 +13,132 @@ * @param */ public class ParallelModifier extends BaseModifier implements IModifierListener { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - private float mSecondsElapsed; - private final float mDuration; - - private final IModifier[] mModifiers; - private boolean mFinishedCached; - - // =========================================================== - // Constructors - // =========================================================== - - public ParallelModifier(final IModifier ... pModifiers) throws IllegalArgumentException { - this(null, pModifiers); - } - - public ParallelModifier(final IModifierListener pModifierListener, final IModifier ... pModifiers) throws IllegalArgumentException { - super(pModifierListener); - if(pModifiers.length == 0) { - throw new IllegalArgumentException("pModifiers must not be empty!"); - } - Arrays.sort(pModifiers, MODIFIER_COMPARATOR_DURATION_DESCENDING); - this.mModifiers = pModifiers; - - final IModifier modifierWithLongestDuration = pModifiers[0]; - this.mDuration = modifierWithLongestDuration.getDuration(); - modifierWithLongestDuration.addModifierListener(this); - } - - @SuppressWarnings("unchecked") - protected ParallelModifier(final ParallelModifier pParallelModifier) throws DeepCopyNotSupportedException { - final IModifier[] otherModifiers = pParallelModifier.mModifiers; - this.mModifiers = new IModifier[otherModifiers.length]; - - final IModifier[] modifiers = this.mModifiers; - for(int i = modifiers.length - 1; i >= 0; i--) { - modifiers[i] = otherModifiers[i].deepCopy(); - } - - final IModifier modifierWithLongestDuration = modifiers[0]; - this.mDuration = modifierWithLongestDuration.getDuration(); - modifierWithLongestDuration.addModifierListener(this); - } - - @Override - public ParallelModifier deepCopy() throws DeepCopyNotSupportedException{ - return new ParallelModifier(this); - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - public float getSecondsElapsed() { - return this.mSecondsElapsed; - } - - @Override - public float getDuration() { - return this.mDuration; - } - - @Override - public float onUpdate(final float pSecondsElapsed, final T pItem) { - if(this.mFinished){ - return 0; - } else { - float secondsElapsedRemaining = pSecondsElapsed; - - final IModifier[] shapeModifiers = this.mModifiers; - - this.mFinishedCached = false; - while(secondsElapsedRemaining > 0 && !this.mFinishedCached) { - float secondsElapsedUsed = 0; - for(int i = shapeModifiers.length - 1; i >= 0; i--) { - secondsElapsedUsed = Math.max(secondsElapsedUsed, shapeModifiers[i].onUpdate(pSecondsElapsed, pItem)); - } - secondsElapsedRemaining -= secondsElapsedUsed; - } - this.mFinishedCached = false; - - final float secondsElapsedUsed = pSecondsElapsed - secondsElapsedRemaining; - this.mSecondsElapsed += secondsElapsedUsed; - return secondsElapsedUsed; - } - } - - @Override - public void reset() { - this.mFinished = false; - this.mSecondsElapsed = 0; - - final IModifier[] shapeModifiers = this.mModifiers; - for(int i = shapeModifiers.length - 1; i >= 0; i--) { - shapeModifiers[i].reset(); - } - } - - @Override - public void onModifierStarted(final IModifier pModifier, final T pItem) { - this.onModifierStarted(pItem); - } - - @Override - public void onModifierFinished(final IModifier pModifier, final T pItem) { - this.mFinished = true; - this.mFinishedCached = true; - this.onModifierFinished(pItem); - } - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + private float mSecondsElapsed; + private final float mDuration; + + private final IModifier[] mModifiers; + private boolean mFinishedCached; + + // =========================================================== + // Constructors + // =========================================================== + + public ParallelModifier(final IModifier ... pModifiers) throws IllegalArgumentException { + this(null, pModifiers); + } + + public ParallelModifier(final IModifierListener pModifierListener, final IModifier ... pModifiers) throws IllegalArgumentException { + super(pModifierListener); + if(pModifiers.length == 0) { + throw new IllegalArgumentException("pModifiers must not be empty!"); + } + Arrays.sort(pModifiers, MODIFIER_COMPARATOR_DURATION_DESCENDING); + this.mModifiers = pModifiers; + + final IModifier modifierWithLongestDuration = pModifiers[0]; + this.mDuration = modifierWithLongestDuration.getDuration(); + modifierWithLongestDuration.addModifierListener(this); + } + + @SuppressWarnings("unchecked") + protected ParallelModifier(final ParallelModifier pParallelModifier) throws DeepCopyNotSupportedException { + final IModifier[] otherModifiers = pParallelModifier.mModifiers; + this.mModifiers = new IModifier[otherModifiers.length]; + + final IModifier[] modifiers = this.mModifiers; + for(int i = modifiers.length - 1; i >= 0; i--) { + modifiers[i] = otherModifiers[i].deepCopy(); + } + + final IModifier modifierWithLongestDuration = modifiers[0]; + this.mDuration = modifierWithLongestDuration.getDuration(); + modifierWithLongestDuration.addModifierListener(this); + } + + @Override + public ParallelModifier deepCopy() throws DeepCopyNotSupportedException{ + return new ParallelModifier(this); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + public float getSecondsElapsed() { + return this.mSecondsElapsed; + } + + @Override + public float getDuration() { + return this.mDuration; + } + + @Override + public float onUpdate(final float pSecondsElapsed, final T pItem) { + if(this.mFinished){ + return 0; + } else { + float secondsElapsedRemaining = pSecondsElapsed; + + final IModifier[] shapeModifiers = this.mModifiers; + + this.mFinishedCached = false; + while(secondsElapsedRemaining > 0 && !this.mFinishedCached) { + float secondsElapsedUsed = 0; + for(int i = shapeModifiers.length - 1; i >= 0; i--) { + secondsElapsedUsed = Math.max(secondsElapsedUsed, shapeModifiers[i].onUpdate(pSecondsElapsed, pItem)); + } + secondsElapsedRemaining -= secondsElapsedUsed; + } + this.mFinishedCached = false; + + final float secondsElapsedUsed = pSecondsElapsed - secondsElapsedRemaining; + this.mSecondsElapsed += secondsElapsedUsed; + return secondsElapsedUsed; + } + } + + @Override + public void reset() { + this.mFinished = false; + this.mSecondsElapsed = 0; + + final IModifier[] shapeModifiers = this.mModifiers; + for(int i = shapeModifiers.length - 1; i >= 0; i--) { + shapeModifiers[i].reset(); + } + } + + @Override + public void onModifierStarted(final IModifier pModifier, final T pItem) { + this.onModifierStarted(pItem); + } + + @Override + public void onModifierFinished(final IModifier pModifier, final T pItem) { + this.mFinished = true; + this.mFinishedCached = true; + this.onModifierFinished(pItem); + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/util/modifier/SequenceModifier.java b/AndEngine/src/org/anddev/andengine/util/modifier/SequenceModifier.java index 9f7c192c..00fe83ee 100644 --- a/AndEngine/src/org/anddev/andengine/util/modifier/SequenceModifier.java +++ b/AndEngine/src/org/anddev/andengine/util/modifier/SequenceModifier.java @@ -12,179 +12,179 @@ * @since 19:39:25 - 19.03.2010 */ public class SequenceModifier extends BaseModifier implements IModifierListener { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - private ISubSequenceModifierListener mSubSequenceModifierListener; - - private final IModifier[] mSubSequenceModifiers; - private int mCurrentSubSequenceModifierIndex; - - private float mSecondsElapsed; - private final float mDuration; - - private boolean mFinishedCached; - - // =========================================================== - // Constructors - // =========================================================== - - public SequenceModifier(final IModifier ... pModifiers) throws IllegalArgumentException { - this(null, null, pModifiers); - } - - public SequenceModifier(final ISubSequenceModifierListener pSubSequenceModifierListener, final IModifier ... pModifiers) throws IllegalArgumentException { - this(pSubSequenceModifierListener, null, pModifiers); - } - - public SequenceModifier(final IModifierListener pModifierListener, final IModifier ... pModifiers) throws IllegalArgumentException { - this(null, pModifierListener, pModifiers); - } - - public SequenceModifier(final ISubSequenceModifierListener pSubSequenceModifierListener, final IModifierListener pModifierListener, final IModifier ... pModifiers) throws IllegalArgumentException { - super(pModifierListener); - if (pModifiers.length == 0) { - throw new IllegalArgumentException("pModifiers must not be empty!"); - } - - this.mSubSequenceModifierListener = pSubSequenceModifierListener; - this.mSubSequenceModifiers = pModifiers; - - this.mDuration = ModifierUtils.getSequenceDurationOfModifier(pModifiers); - - pModifiers[0].addModifierListener(this); - } - - @SuppressWarnings("unchecked") - protected SequenceModifier(final SequenceModifier pSequenceModifier) throws DeepCopyNotSupportedException { - this.mDuration = pSequenceModifier.mDuration; - - final IModifier[] otherModifiers = pSequenceModifier.mSubSequenceModifiers; - this.mSubSequenceModifiers = new IModifier[otherModifiers.length]; - - final IModifier[] shapeModifiers = this.mSubSequenceModifiers; - for(int i = shapeModifiers.length - 1; i >= 0; i--) { - shapeModifiers[i] = otherModifiers[i].deepCopy(); - } - - shapeModifiers[0].addModifierListener(this); - } - - @Override - public SequenceModifier deepCopy() throws DeepCopyNotSupportedException{ - return new SequenceModifier(this); - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - public ISubSequenceModifierListener getSubSequenceModifierListener() { - return this.mSubSequenceModifierListener; - } - - public void setSubSequenceModifierListener(final ISubSequenceModifierListener pSubSequenceModifierListener) { - this.mSubSequenceModifierListener = pSubSequenceModifierListener; - } - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - public float getSecondsElapsed() { - return this.mSecondsElapsed; - } - - @Override - public float getDuration() { - return this.mDuration; - } - - @Override - public float onUpdate(final float pSecondsElapsed, final T pItem) { - if(this.mFinished){ - return 0; - } else { - float secondsElapsedRemaining = pSecondsElapsed; - this.mFinishedCached = false; - while(secondsElapsedRemaining > 0 && !this.mFinishedCached) { - secondsElapsedRemaining -= this.mSubSequenceModifiers[this.mCurrentSubSequenceModifierIndex].onUpdate(secondsElapsedRemaining, pItem); - } - this.mFinishedCached = false; - - final float secondsElapsedUsed = pSecondsElapsed - secondsElapsedRemaining; - this.mSecondsElapsed += secondsElapsedUsed; - return secondsElapsedUsed; - } - } - - @Override - public void reset() { - if(this.isFinished()) { - this.mSubSequenceModifiers[this.mSubSequenceModifiers.length - 1].removeModifierListener(this); - } else { - this.mSubSequenceModifiers[this.mCurrentSubSequenceModifierIndex].removeModifierListener(this); - } - - this.mCurrentSubSequenceModifierIndex = 0; - this.mFinished = false; - this.mSecondsElapsed = 0; - - this.mSubSequenceModifiers[0].addModifierListener(this); - - final IModifier[] shapeModifiers = this.mSubSequenceModifiers; - for(int i = shapeModifiers.length - 1; i >= 0; i--) { - shapeModifiers[i].reset(); - } - } - - @Override - public void onModifierStarted(final IModifier pModifier, final T pItem) { - if(this.mCurrentSubSequenceModifierIndex == 0) { - this.onModifierStarted(pItem); - } - - 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) { - this.mSubSequenceModifierListener.onSubSequenceFinished(pModifier, pItem, this.mCurrentSubSequenceModifierIndex); - } - pModifier.removeModifierListener(this); - - this.mCurrentSubSequenceModifierIndex++; - - if(this.mCurrentSubSequenceModifierIndex < this.mSubSequenceModifiers.length) { - final IModifier nextSubSequenceModifier = this.mSubSequenceModifiers[this.mCurrentSubSequenceModifierIndex]; - nextSubSequenceModifier.addModifierListener(this); - } else { - this.mFinished = true; - this.mFinishedCached = true; - - this.onModifierFinished(pItem); - } - } - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== - - public interface ISubSequenceModifierListener { - public void onSubSequenceStarted(final IModifier pModifier, final T pItem, final int pIndex); - public void onSubSequenceFinished(final IModifier pModifier, final T pItem, final int pIndex); - } + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + private ISubSequenceModifierListener mSubSequenceModifierListener; + + private final IModifier[] mSubSequenceModifiers; + private int mCurrentSubSequenceModifierIndex; + + private float mSecondsElapsed; + private final float mDuration; + + private boolean mFinishedCached; + + // =========================================================== + // Constructors + // =========================================================== + + public SequenceModifier(final IModifier ... pModifiers) throws IllegalArgumentException { + this(null, null, pModifiers); + } + + public SequenceModifier(final ISubSequenceModifierListener pSubSequenceModifierListener, final IModifier ... pModifiers) throws IllegalArgumentException { + this(pSubSequenceModifierListener, null, pModifiers); + } + + public SequenceModifier(final IModifierListener pModifierListener, final IModifier ... pModifiers) throws IllegalArgumentException { + this(null, pModifierListener, pModifiers); + } + + public SequenceModifier(final ISubSequenceModifierListener pSubSequenceModifierListener, final IModifierListener pModifierListener, final IModifier ... pModifiers) throws IllegalArgumentException { + super(pModifierListener); + if (pModifiers.length == 0) { + throw new IllegalArgumentException("pModifiers must not be empty!"); + } + + this.mSubSequenceModifierListener = pSubSequenceModifierListener; + this.mSubSequenceModifiers = pModifiers; + + this.mDuration = ModifierUtils.getSequenceDurationOfModifier(pModifiers); + + pModifiers[0].addModifierListener(this); + } + + @SuppressWarnings("unchecked") + protected SequenceModifier(final SequenceModifier pSequenceModifier) throws DeepCopyNotSupportedException { + this.mDuration = pSequenceModifier.mDuration; + + final IModifier[] otherModifiers = pSequenceModifier.mSubSequenceModifiers; + this.mSubSequenceModifiers = new IModifier[otherModifiers.length]; + + final IModifier[] shapeModifiers = this.mSubSequenceModifiers; + for(int i = shapeModifiers.length - 1; i >= 0; i--) { + shapeModifiers[i] = otherModifiers[i].deepCopy(); + } + + shapeModifiers[0].addModifierListener(this); + } + + @Override + public SequenceModifier deepCopy() throws DeepCopyNotSupportedException{ + return new SequenceModifier(this); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + public ISubSequenceModifierListener getSubSequenceModifierListener() { + return this.mSubSequenceModifierListener; + } + + public void setSubSequenceModifierListener(final ISubSequenceModifierListener pSubSequenceModifierListener) { + this.mSubSequenceModifierListener = pSubSequenceModifierListener; + } + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + public float getSecondsElapsed() { + return this.mSecondsElapsed; + } + + @Override + public float getDuration() { + return this.mDuration; + } + + @Override + public float onUpdate(final float pSecondsElapsed, final T pItem) { + if(this.mFinished){ + return 0; + } else { + float secondsElapsedRemaining = pSecondsElapsed; + this.mFinishedCached = false; + while(secondsElapsedRemaining > 0 && !this.mFinishedCached) { + secondsElapsedRemaining -= this.mSubSequenceModifiers[this.mCurrentSubSequenceModifierIndex].onUpdate(secondsElapsedRemaining, pItem); + } + this.mFinishedCached = false; + + final float secondsElapsedUsed = pSecondsElapsed - secondsElapsedRemaining; + this.mSecondsElapsed += secondsElapsedUsed; + return secondsElapsedUsed; + } + } + + @Override + public void reset() { + if(this.isFinished()) { + this.mSubSequenceModifiers[this.mSubSequenceModifiers.length - 1].removeModifierListener(this); + } else { + this.mSubSequenceModifiers[this.mCurrentSubSequenceModifierIndex].removeModifierListener(this); + } + + this.mCurrentSubSequenceModifierIndex = 0; + this.mFinished = false; + this.mSecondsElapsed = 0; + + this.mSubSequenceModifiers[0].addModifierListener(this); + + final IModifier[] shapeModifiers = this.mSubSequenceModifiers; + for(int i = shapeModifiers.length - 1; i >= 0; i--) { + shapeModifiers[i].reset(); + } + } + + @Override + public void onModifierStarted(final IModifier pModifier, final T pItem) { + if(this.mCurrentSubSequenceModifierIndex == 0) { + this.onModifierStarted(pItem); + } + + 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) { + this.mSubSequenceModifierListener.onSubSequenceFinished(pModifier, pItem, this.mCurrentSubSequenceModifierIndex); + } + pModifier.removeModifierListener(this); + + this.mCurrentSubSequenceModifierIndex++; + + if(this.mCurrentSubSequenceModifierIndex < this.mSubSequenceModifiers.length) { + final IModifier nextSubSequenceModifier = this.mSubSequenceModifiers[this.mCurrentSubSequenceModifierIndex]; + nextSubSequenceModifier.addModifierListener(this); + } else { + this.mFinished = true; + this.mFinishedCached = true; + + this.onModifierFinished(pItem); + } + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== + + public interface ISubSequenceModifierListener { + public void onSubSequenceStarted(final IModifier pModifier, final T pItem, final int pIndex); + public void onSubSequenceFinished(final IModifier pModifier, final T pItem, final int pIndex); + } } diff --git a/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseBackIn.java b/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseBackIn.java index 5971dea4..3eec047b 100644 --- a/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseBackIn.java +++ b/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseBackIn.java @@ -9,55 +9,55 @@ * @since 16:52:11 - 26.07.2010 */ public class EaseBackIn implements IEaseFunction { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - private static final float OVERSHOOT_CONSTANT = 1.70158f; + private static final float OVERSHOOT_CONSTANT = 1.70158f; - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - private static EaseBackIn INSTANCE; + private static EaseBackIn INSTANCE; - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - private EaseBackIn() { + private EaseBackIn() { - } + } - public static EaseBackIn getInstance() { - if(null == INSTANCE) { - INSTANCE = new EaseBackIn(); - } - return INSTANCE; - } + public static EaseBackIn getInstance() { + if(null == INSTANCE) { + INSTANCE = new EaseBackIn(); + } + return INSTANCE; + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - @Override - public float getPercentage(final float pSecondsElapsed, final float pDuration) { - return EaseBackIn.getValue(pSecondsElapsed / pDuration); - } + @Override + public float getPercentage(final float pSecondsElapsed, final float pDuration) { + return EaseBackIn.getValue(pSecondsElapsed / pDuration); + } - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - public static float getValue(final float pPercentage) { - return pPercentage * pPercentage * ((OVERSHOOT_CONSTANT + 1) * pPercentage - OVERSHOOT_CONSTANT); - } + public static float getValue(final float pPercentage) { + return pPercentage * pPercentage * ((OVERSHOOT_CONSTANT + 1) * pPercentage - OVERSHOOT_CONSTANT); + } - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseBackInOut.java b/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseBackInOut.java index dd9c2ddf..cef1c797 100644 --- a/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseBackInOut.java +++ b/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseBackInOut.java @@ -9,55 +9,55 @@ * @since 16:52:11 - 26.07.2010 */ public class EaseBackInOut implements IEaseFunction { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - private static EaseBackInOut INSTANCE; + private static EaseBackInOut INSTANCE; - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - private EaseBackInOut() { + private EaseBackInOut() { - } + } - public static EaseBackInOut getInstance() { - if(INSTANCE == null) { - INSTANCE = new EaseBackInOut(); - } - return INSTANCE; - } + public static EaseBackInOut getInstance() { + if(INSTANCE == null) { + INSTANCE = new EaseBackInOut(); + } + return INSTANCE; + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - @Override - public float getPercentage(final float pSecondsElapsed, final float pDuration) { - final float percentage = pSecondsElapsed / pDuration; + @Override + public float getPercentage(final float pSecondsElapsed, final float pDuration) { + final float percentage = pSecondsElapsed / pDuration; - if(percentage < 0.5f) { - return 0.5f * EaseBackIn.getValue(2 * percentage); - } else { - return 0.5f + 0.5f * EaseBackOut.getValue(percentage * 2 - 1); - } - } + if(percentage < 0.5f) { + return 0.5f * EaseBackIn.getValue(2 * percentage); + } else { + return 0.5f + 0.5f * EaseBackOut.getValue(percentage * 2 - 1); + } + } - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseBackOut.java b/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseBackOut.java index 99add175..7f27b3fb 100644 --- a/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseBackOut.java +++ b/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseBackOut.java @@ -9,54 +9,54 @@ * @since 16:52:11 - 26.07.2010 */ public class EaseBackOut implements IEaseFunction { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - private static EaseBackOut INSTANCE; + private static EaseBackOut INSTANCE; - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - private EaseBackOut() { + private EaseBackOut() { - } + } - public static EaseBackOut getInstance() { - if(INSTANCE == null) { - INSTANCE = new EaseBackOut(); - } - return INSTANCE; - } + public static EaseBackOut getInstance() { + if(INSTANCE == null) { + INSTANCE = new EaseBackOut(); + } + return INSTANCE; + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - @Override - public float getPercentage(final float pSecondsElapsed, final float pDuration) { - return EaseBackOut.getValue(pSecondsElapsed / pDuration); - } + @Override + public float getPercentage(final float pSecondsElapsed, final float pDuration) { + return EaseBackOut.getValue(pSecondsElapsed / pDuration); + } - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - public static float getValue(final float pPercentage) { - final float t = pPercentage - 1; - return 1 + t * t * ((1.70158f + 1) * t + 1.70158f); - } + public static float getValue(final float pPercentage) { + final float t = pPercentage - 1; + return 1 + t * t * ((1.70158f + 1) * t + 1.70158f); + } - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseBounceIn.java b/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseBounceIn.java index 046a70dc..5de1072b 100644 --- a/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseBounceIn.java +++ b/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseBounceIn.java @@ -9,54 +9,54 @@ * @since 16:52:11 - 26.07.2010 */ public class EaseBounceIn implements IEaseFunction { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - private static EaseBounceIn INSTANCE; + private static EaseBounceIn INSTANCE; - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - private EaseBounceIn() { + private EaseBounceIn() { - } + } - public static EaseBounceIn getInstance() { - if(INSTANCE == null) { - INSTANCE = new EaseBounceIn(); - } - return INSTANCE; - } + public static EaseBounceIn getInstance() { + if(INSTANCE == null) { + INSTANCE = new EaseBounceIn(); + } + return INSTANCE; + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - @Override - public float getPercentage(final float pSecondsElapsed, final float pDuration) { - return EaseBounceIn.getValue(pSecondsElapsed / pDuration); - } + @Override + public float getPercentage(final float pSecondsElapsed, final float pDuration) { + return EaseBounceIn.getValue(pSecondsElapsed / pDuration); + } - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - public static float getValue(final float pPercentage) { - // TODO Inline? - return 1 - EaseBounceOut.getValue(1 - pPercentage); - } + public static float getValue(final float pPercentage) { + // TODO Inline? + return 1 - EaseBounceOut.getValue(1 - pPercentage); + } - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseBounceInOut.java b/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseBounceInOut.java index eb447bd4..b392d785 100644 --- a/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseBounceInOut.java +++ b/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseBounceInOut.java @@ -9,55 +9,55 @@ * @since 16:52:11 - 26.07.2010 */ public class EaseBounceInOut implements IEaseFunction { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - private static EaseBounceInOut INSTANCE; + private static EaseBounceInOut INSTANCE; - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - private EaseBounceInOut() { + private EaseBounceInOut() { - } + } - public static EaseBounceInOut getInstance() { - if(INSTANCE == null) { - INSTANCE = new EaseBounceInOut(); - } - return INSTANCE; - } + public static EaseBounceInOut getInstance() { + if(INSTANCE == null) { + INSTANCE = new EaseBounceInOut(); + } + return INSTANCE; + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - @Override - public float getPercentage(final float pSecondsElapsed, final float pDuration) { - final float percentage = pSecondsElapsed / pDuration; + @Override + public float getPercentage(final float pSecondsElapsed, final float pDuration) { + final float percentage = pSecondsElapsed / pDuration; - if(percentage < 0.5f) { - return 0.5f * EaseBounceIn.getValue(2 * percentage); - } else { - return 0.5f + 0.5f * EaseBounceOut.getValue(percentage * 2 - 1); - } - } + if(percentage < 0.5f) { + return 0.5f * EaseBounceIn.getValue(2 * percentage); + } else { + return 0.5f + 0.5f * EaseBounceOut.getValue(percentage * 2 - 1); + } + } - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseBounceOut.java b/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseBounceOut.java index 902ba77b..0364cc09 100644 --- a/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseBounceOut.java +++ b/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseBounceOut.java @@ -9,64 +9,64 @@ * @since 16:52:11 - 26.07.2010 */ public class EaseBounceOut implements IEaseFunction { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - private static EaseBounceOut INSTANCE; + private static EaseBounceOut INSTANCE; - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - private EaseBounceOut() { + private EaseBounceOut() { - } + } - public static EaseBounceOut getInstance() { - if(INSTANCE == null) { - INSTANCE = new EaseBounceOut(); - } - return INSTANCE; - } + public static EaseBounceOut getInstance() { + if(INSTANCE == null) { + INSTANCE = new EaseBounceOut(); + } + return INSTANCE; + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - @Override - public float getPercentage(final float pSecondsElapsed, final float pDuration) { - return EaseBounceOut.getValue(pSecondsElapsed / pDuration); - } + @Override + public float getPercentage(final float pSecondsElapsed, final float pDuration) { + return EaseBounceOut.getValue(pSecondsElapsed / pDuration); + } - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - public static float getValue(final float pPercentage) { - if(pPercentage < (1f / 2.75f)) { - return 7.5625f * pPercentage * pPercentage; - } 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)) { - final float t = pPercentage - (2.25f / 2.75f); - return 7.5625f * t * t + 0.9375f; - } else { - final float t = pPercentage - (2.625f / 2.75f); - return 7.5625f * t * t + 0.984375f; - } - } + public static float getValue(final float pPercentage) { + if(pPercentage < (1f / 2.75f)) { + return 7.5625f * pPercentage * pPercentage; + } 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)) { + final float t = pPercentage - (2.25f / 2.75f); + return 7.5625f * t * t + 0.9375f; + } else { + final float t = pPercentage - (2.625f / 2.75f); + return 7.5625f * t * t + 0.984375f; + } + } - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseCircularIn.java b/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseCircularIn.java index 8b106eb3..63d63b10 100644 --- a/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseCircularIn.java +++ b/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseCircularIn.java @@ -11,53 +11,53 @@ * @since 16:52:11 - 26.07.2010 */ public class EaseCircularIn implements IEaseFunction { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - private static EaseCircularIn INSTANCE; + private static EaseCircularIn INSTANCE; - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - private EaseCircularIn() { + private EaseCircularIn() { - } + } - public static EaseCircularIn getInstance() { - if(INSTANCE == null) { - INSTANCE = new EaseCircularIn(); - } - return INSTANCE; - } + public static EaseCircularIn getInstance() { + if(INSTANCE == null) { + INSTANCE = new EaseCircularIn(); + } + return INSTANCE; + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - @Override - public float getPercentage(final float pSecondsElapsed, final float pDuration) { - return EaseCircularIn.getValue(pSecondsElapsed / pDuration); - } + @Override + public float getPercentage(final float pSecondsElapsed, final float pDuration) { + return EaseCircularIn.getValue(pSecondsElapsed / pDuration); + } - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - public static float getValue(final float pPercentage) { - return -((float)Math.sqrt(1 - pPercentage * pPercentage) - 1.0f); - } + public static float getValue(final float pPercentage) { + return -((float)Math.sqrt(1 - pPercentage * pPercentage) - 1.0f); + } - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseCircularInOut.java b/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseCircularInOut.java index 83a14a19..906283aa 100644 --- a/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseCircularInOut.java +++ b/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseCircularInOut.java @@ -10,54 +10,54 @@ * @since 16:52:11 - 26.07.2010 */ public class EaseCircularInOut implements IEaseFunction { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - private static EaseCircularInOut INSTANCE; - - // =========================================================== - // Constructors - // =========================================================== - - private EaseCircularInOut() { - } - - public static EaseCircularInOut getInstance() { - if(INSTANCE == null) { - INSTANCE = new EaseCircularInOut(); - } - return INSTANCE; - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - public float getPercentage(final float pSecondsElapsed, final float pDuration) { - final float percentage = pSecondsElapsed / pDuration; - - if(percentage < 0.5f) { - return 0.5f * EaseCircularIn.getValue(2 * percentage); - } else { - return 0.5f + 0.5f * EaseCircularOut.getValue(percentage * 2 - 1); - } - } - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + private static EaseCircularInOut INSTANCE; + + // =========================================================== + // Constructors + // =========================================================== + + private EaseCircularInOut() { + } + + public static EaseCircularInOut getInstance() { + if(INSTANCE == null) { + INSTANCE = new EaseCircularInOut(); + } + return INSTANCE; + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + public float getPercentage(final float pSecondsElapsed, final float pDuration) { + final float percentage = pSecondsElapsed / pDuration; + + if(percentage < 0.5f) { + return 0.5f * EaseCircularIn.getValue(2 * percentage); + } else { + return 0.5f + 0.5f * EaseCircularOut.getValue(percentage * 2 - 1); + } + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseCircularOut.java b/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseCircularOut.java index 48f7fc04..5fb42147 100644 --- a/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseCircularOut.java +++ b/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseCircularOut.java @@ -11,54 +11,54 @@ * @since 16:52:11 - 26.07.2010 */ public class EaseCircularOut implements IEaseFunction { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - private static EaseCircularOut INSTANCE; + private static EaseCircularOut INSTANCE; - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - private EaseCircularOut() { + private EaseCircularOut() { - } + } - public static EaseCircularOut getInstance() { - if(INSTANCE == null) { - INSTANCE = new EaseCircularOut(); - } - return INSTANCE; - } + public static EaseCircularOut getInstance() { + if(INSTANCE == null) { + INSTANCE = new EaseCircularOut(); + } + return INSTANCE; + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - @Override - public float getPercentage(final float pSecondsElapsed, final float pDuration) { - return EaseCircularOut.getValue(pSecondsElapsed / pDuration); - } + @Override + public float getPercentage(final float pSecondsElapsed, final float pDuration) { + return EaseCircularOut.getValue(pSecondsElapsed / pDuration); + } - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - public static float getValue(final float pPercentage) { - final float t = pPercentage - 1; - return (float) Math.sqrt(1 - t * t); - } + public static float getValue(final float pPercentage) { + final float t = pPercentage - 1; + return (float) Math.sqrt(1 - t * t); + } - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseCubicIn.java b/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseCubicIn.java index 78edb3e5..0f85f30e 100644 --- a/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseCubicIn.java +++ b/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseCubicIn.java @@ -9,53 +9,53 @@ * @since 16:52:11 - 26.07.2010 */ public class EaseCubicIn implements IEaseFunction { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - private static EaseCubicIn INSTANCE; + private static EaseCubicIn INSTANCE; - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - private EaseCubicIn() { + private EaseCubicIn() { - } + } - public static EaseCubicIn getInstance() { - if(INSTANCE == null) { - INSTANCE = new EaseCubicIn(); - } - return INSTANCE; - } + public static EaseCubicIn getInstance() { + if(INSTANCE == null) { + INSTANCE = new EaseCubicIn(); + } + return INSTANCE; + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - @Override - public float getPercentage(final float pSecondsElapsed, final float pDuration) { - return EaseCubicIn.getValue(pSecondsElapsed / pDuration); - } + @Override + public float getPercentage(final float pSecondsElapsed, final float pDuration) { + return EaseCubicIn.getValue(pSecondsElapsed / pDuration); + } - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - public static float getValue(final float pPercentage) { - return pPercentage * pPercentage * pPercentage; - } + public static float getValue(final float pPercentage) { + return pPercentage * pPercentage * pPercentage; + } - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseCubicInOut.java b/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseCubicInOut.java index c7c8cda8..07344ed8 100644 --- a/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseCubicInOut.java +++ b/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseCubicInOut.java @@ -9,55 +9,55 @@ * @since 16:52:11 - 26.07.2010 */ public class EaseCubicInOut implements IEaseFunction { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - private static EaseCubicInOut INSTANCE; + private static EaseCubicInOut INSTANCE; - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - private EaseCubicInOut() { + private EaseCubicInOut() { - } + } - public static EaseCubicInOut getInstance() { - if(INSTANCE == null) { - INSTANCE = new EaseCubicInOut(); - } - return INSTANCE; - } + public static EaseCubicInOut getInstance() { + if(INSTANCE == null) { + INSTANCE = new EaseCubicInOut(); + } + return INSTANCE; + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - @Override - public float getPercentage(final float pSecondsElapsed, final float pDuration) { - final float percentage = pSecondsElapsed / pDuration; + @Override + public float getPercentage(final float pSecondsElapsed, final float pDuration) { + final float percentage = pSecondsElapsed / pDuration; - if(percentage < 0.5f) { - return 0.5f * EaseCubicIn.getValue(2 * percentage); - } else { - return 0.5f + 0.5f * EaseCubicOut.getValue(percentage * 2 - 1); - } - } + if(percentage < 0.5f) { + return 0.5f * EaseCubicIn.getValue(2 * percentage); + } else { + return 0.5f + 0.5f * EaseCubicOut.getValue(percentage * 2 - 1); + } + } - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseCubicOut.java b/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseCubicOut.java index 56a6b35a..25ef7a1e 100644 --- a/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseCubicOut.java +++ b/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseCubicOut.java @@ -9,54 +9,54 @@ * @since 16:52:11 - 26.07.2010 */ public class EaseCubicOut implements IEaseFunction { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - private static EaseCubicOut INSTANCE; + private static EaseCubicOut INSTANCE; - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - private EaseCubicOut() { + private EaseCubicOut() { - } + } - public static EaseCubicOut getInstance() { - if(INSTANCE == null) { - INSTANCE = new EaseCubicOut(); - } - return INSTANCE; - } + public static EaseCubicOut getInstance() { + if(INSTANCE == null) { + INSTANCE = new EaseCubicOut(); + } + return INSTANCE; + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - @Override - public float getPercentage(final float pSecondsElapsed, final float pDuration) { - return EaseCubicOut.getValue(pSecondsElapsed / pDuration); - } + @Override + public float getPercentage(final float pSecondsElapsed, final float pDuration) { + return EaseCubicOut.getValue(pSecondsElapsed / pDuration); + } - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - public static float getValue(final float pPercentage) { - final float t = pPercentage - 1; - return 1 + (t * t * t); - } + public static float getValue(final float pPercentage) { + final float t = pPercentage - 1; + return 1 + (t * t * t); + } - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseElasticIn.java b/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseElasticIn.java index 2043dfba..61c9bc36 100644 --- a/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseElasticIn.java +++ b/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseElasticIn.java @@ -13,64 +13,64 @@ * @since 16:52:11 - 26.07.2010 */ public class EaseElasticIn implements IEaseFunction, MathConstants { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - private static EaseElasticIn INSTANCE; - - // =========================================================== - // Constructors - // =========================================================== - - private EaseElasticIn() { - - } - - public static EaseElasticIn getInstance() { - if(INSTANCE == null) { - INSTANCE = new EaseElasticIn(); - } - return INSTANCE; - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - public float getPercentage(final float pSecondsElapsed, final float pDuration) { - return EaseElasticIn.getValue(pSecondsElapsed, pDuration, pSecondsElapsed / pDuration); - } - - // =========================================================== - // Methods - // =========================================================== - - public static float getValue(final float pSecondsElapsed, final float pDuration, final float pPercentage) { - if(pSecondsElapsed == 0) { - return 0; - } - if(pSecondsElapsed == pDuration) { - return 1; - } - - final float p = pDuration * 0.3f; - final float s = p / 4; - - final float t = pPercentage - 1; - return -(float)Math.pow(2, 10 * t) * (float) Math.sin((t * pDuration - s) * PI_TWICE / p); - } - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + private static EaseElasticIn INSTANCE; + + // =========================================================== + // Constructors + // =========================================================== + + private EaseElasticIn() { + + } + + public static EaseElasticIn getInstance() { + if(INSTANCE == null) { + INSTANCE = new EaseElasticIn(); + } + return INSTANCE; + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + public float getPercentage(final float pSecondsElapsed, final float pDuration) { + return EaseElasticIn.getValue(pSecondsElapsed, pDuration, pSecondsElapsed / pDuration); + } + + // =========================================================== + // Methods + // =========================================================== + + public static float getValue(final float pSecondsElapsed, final float pDuration, final float pPercentage) { + if(pSecondsElapsed == 0) { + return 0; + } + if(pSecondsElapsed == pDuration) { + return 1; + } + + final float p = pDuration * 0.3f; + final float s = p / 4; + + final float t = pPercentage - 1; + return -(float)Math.pow(2, 10 * t) * (float) Math.sin((t * pDuration - s) * PI_TWICE / p); + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseElasticInOut.java b/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseElasticInOut.java index 2f6fb073..03d3e6a5 100644 --- a/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseElasticInOut.java +++ b/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseElasticInOut.java @@ -11,55 +11,55 @@ * @since 16:52:11 - 26.07.2010 */ public class EaseElasticInOut implements IEaseFunction, MathConstants { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - private static EaseElasticInOut INSTANCE; + private static EaseElasticInOut INSTANCE; - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - private EaseElasticInOut() { + private EaseElasticInOut() { - } + } - public static EaseElasticInOut getInstance() { - if(INSTANCE == null) { - INSTANCE = new EaseElasticInOut(); - } - return INSTANCE; - } + public static EaseElasticInOut getInstance() { + if(INSTANCE == null) { + INSTANCE = new EaseElasticInOut(); + } + return INSTANCE; + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - @Override - public float getPercentage(final float pSecondsElapsed, final float pDuration) { - final float percentage = pSecondsElapsed / pDuration; + @Override + public float getPercentage(final float pSecondsElapsed, final float pDuration) { + final float percentage = pSecondsElapsed / pDuration; - 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); - } - } + 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); + } + } - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseElasticOut.java b/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseElasticOut.java index 3194d899..2021f126 100644 --- a/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseElasticOut.java +++ b/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseElasticOut.java @@ -13,63 +13,63 @@ * @since 16:52:11 - 26.07.2010 */ public class EaseElasticOut implements IEaseFunction, MathConstants { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - private static EaseElasticOut INSTANCE; + private static EaseElasticOut INSTANCE; - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - private EaseElasticOut() { + private EaseElasticOut() { - } + } - public static EaseElasticOut getInstance() { - if(INSTANCE == null) { - INSTANCE = new EaseElasticOut(); - } - return INSTANCE; - } + public static EaseElasticOut getInstance() { + if(INSTANCE == null) { + INSTANCE = new EaseElasticOut(); + } + return INSTANCE; + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - @Override - public float getPercentage(final float pSecondsElapsed, final float pDuration) { - return EaseElasticOut.getValue(pSecondsElapsed, pDuration, pSecondsElapsed / pDuration); - } + @Override + public float getPercentage(final float pSecondsElapsed, final float pDuration) { + return EaseElasticOut.getValue(pSecondsElapsed, pDuration, pSecondsElapsed / pDuration); + } - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - public static float getValue(final float pSecondsElapsed, final float pDuration, final float pPercentageDone) { - if(pSecondsElapsed == 0) { - return 0; - } - if(pSecondsElapsed == pDuration) { - return 1; - } + public static float getValue(final float pSecondsElapsed, final float pDuration, final float pPercentageDone) { + if(pSecondsElapsed == 0) { + return 0; + } + if(pSecondsElapsed == pDuration) { + return 1; + } - final float p = pDuration * 0.3f; - final float s = p / 4; + final float p = pDuration * 0.3f; + final float s = p / 4; - return 1 + (float)Math.pow(2, -10 * pPercentageDone) * (float) Math.sin((pPercentageDone * pDuration - s) * PI_TWICE / p); - } + return 1 + (float)Math.pow(2, -10 * pPercentageDone) * (float) Math.sin((pPercentageDone * pDuration - s) * PI_TWICE / p); + } - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseExponentialIn.java b/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseExponentialIn.java index 31e642b2..c55a6b28 100644 --- a/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseExponentialIn.java +++ b/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseExponentialIn.java @@ -9,54 +9,54 @@ * @since 16:52:11 - 26.07.2010 */ public class EaseExponentialIn implements IEaseFunction { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - private static EaseExponentialIn INSTANCE; + private static EaseExponentialIn INSTANCE; - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - private EaseExponentialIn() { + private EaseExponentialIn() { - } + } - public static EaseExponentialIn getInstance() { - if(INSTANCE == null) { - INSTANCE = new EaseExponentialIn(); - } - return INSTANCE; - } + public static EaseExponentialIn getInstance() { + if(INSTANCE == null) { + INSTANCE = new EaseExponentialIn(); + } + return INSTANCE; + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - @Override - public float getPercentage(final float pSecondsElapsed, final float pDuration) { - return EaseExponentialIn.getValue(pSecondsElapsed / pDuration); + @Override + public float getPercentage(final float pSecondsElapsed, final float pDuration) { + return EaseExponentialIn.getValue(pSecondsElapsed / pDuration); - } + } - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - public static float getValue(final float pPercentage) { - return (float) ((pPercentage == 0) ? 0 : Math.pow(2, 10 * (pPercentage - 1)) - 0.001f); - } + public static float getValue(final float pPercentage) { + return (float) ((pPercentage == 0) ? 0 : Math.pow(2, 10 * (pPercentage - 1)) - 0.001f); + } - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseExponentialInOut.java b/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseExponentialInOut.java index f66c5af0..92cbe9fd 100644 --- a/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseExponentialInOut.java +++ b/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseExponentialInOut.java @@ -9,55 +9,55 @@ * @since 16:52:11 - 26.07.2010 */ public class EaseExponentialInOut implements IEaseFunction { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - private static EaseExponentialInOut INSTANCE; + private static EaseExponentialInOut INSTANCE; - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - private EaseExponentialInOut() { + private EaseExponentialInOut() { - } + } - public static EaseExponentialInOut getInstance() { - if(INSTANCE == null) { - INSTANCE = new EaseExponentialInOut(); - } - return INSTANCE; - } + public static EaseExponentialInOut getInstance() { + if(INSTANCE == null) { + INSTANCE = new EaseExponentialInOut(); + } + return INSTANCE; + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - @Override - public float getPercentage(final float pSecondsElapsed, final float pDuration) { - final float percentage = pSecondsElapsed / pDuration; + @Override + public float getPercentage(final float pSecondsElapsed, final float pDuration) { + final float percentage = pSecondsElapsed / pDuration; - if(percentage < 0.5f) { - return 0.5f * EaseExponentialIn.getValue(2 * percentage); - } else { - return 0.5f + 0.5f * EaseExponentialOut.getValue(percentage * 2 - 1); - } - } + if(percentage < 0.5f) { + return 0.5f * EaseExponentialIn.getValue(2 * percentage); + } else { + return 0.5f + 0.5f * EaseExponentialOut.getValue(percentage * 2 - 1); + } + } - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseExponentialOut.java b/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseExponentialOut.java index 512b251a..c12022b6 100644 --- a/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseExponentialOut.java +++ b/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseExponentialOut.java @@ -9,53 +9,53 @@ * @since 16:52:11 - 26.07.2010 */ public class EaseExponentialOut implements IEaseFunction { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - private static EaseExponentialOut INSTANCE; + private static EaseExponentialOut INSTANCE; - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - private EaseExponentialOut() { + private EaseExponentialOut() { - } + } - public static EaseExponentialOut getInstance() { - if(INSTANCE == null) { - INSTANCE = new EaseExponentialOut(); - } - return INSTANCE; - } + public static EaseExponentialOut getInstance() { + if(INSTANCE == null) { + INSTANCE = new EaseExponentialOut(); + } + return INSTANCE; + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - @Override - public float getPercentage(final float pSecondsElapsed, final float pDuration) { - return EaseExponentialOut.getValue(pSecondsElapsed / pDuration); - } + @Override + public float getPercentage(final float pSecondsElapsed, final float pDuration) { + return EaseExponentialOut.getValue(pSecondsElapsed / pDuration); + } - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - public static float getValue(final float pPercentage) { - return (pPercentage == 1) ? 1 : (-(float)Math.pow(2, -10 * pPercentage) + 1); - } + public static float getValue(final float pPercentage) { + return (pPercentage == 1) ? 1 : (-(float)Math.pow(2, -10 * pPercentage) + 1); + } - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseLinear.java b/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseLinear.java index aeb391dc..0cf3c1e7 100644 --- a/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseLinear.java +++ b/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseLinear.java @@ -9,49 +9,49 @@ * @since 16:50:40 - 26.07.2010 */ public class EaseLinear implements IEaseFunction { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - private static EaseLinear INSTANCE; + private static EaseLinear INSTANCE; - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - private EaseLinear() { + private EaseLinear() { - } + } - public static EaseLinear getInstance() { - if(INSTANCE == null) { - INSTANCE = new EaseLinear(); - } - return INSTANCE; - } + public static EaseLinear getInstance() { + if(INSTANCE == null) { + INSTANCE = new EaseLinear(); + } + return INSTANCE; + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - @Override - public float getPercentage(final float pSecondsElapsed, final float pDuration) { - return pSecondsElapsed / pDuration; - } + @Override + public float getPercentage(final float pSecondsElapsed, final float pDuration) { + return pSecondsElapsed / pDuration; + } - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseQuadIn.java b/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseQuadIn.java index 9222c9ad..946b65a6 100644 --- a/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseQuadIn.java +++ b/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseQuadIn.java @@ -9,53 +9,53 @@ * @since 16:52:11 - 26.07.2010 */ public class EaseQuadIn implements IEaseFunction { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - private static EaseQuadIn INSTANCE; + private static EaseQuadIn INSTANCE; - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - private EaseQuadIn() { + private EaseQuadIn() { - } + } - public static EaseQuadIn getInstance() { - if(INSTANCE == null) { - INSTANCE = new EaseQuadIn(); - } - return INSTANCE; - } + public static EaseQuadIn getInstance() { + if(INSTANCE == null) { + INSTANCE = new EaseQuadIn(); + } + return INSTANCE; + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - @Override - public float getPercentage(final float pSecondsElapsed, final float pDuration) { - return EaseQuadIn.getValue(pSecondsElapsed / pDuration); - } + @Override + public float getPercentage(final float pSecondsElapsed, final float pDuration) { + return EaseQuadIn.getValue(pSecondsElapsed / pDuration); + } - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - public static float getValue(final float pPercentage) { - return pPercentage * pPercentage; - } + public static float getValue(final float pPercentage) { + return pPercentage * pPercentage; + } - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseQuadInOut.java b/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseQuadInOut.java index 6cccb8bc..7c9032ef 100644 --- a/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseQuadInOut.java +++ b/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseQuadInOut.java @@ -9,55 +9,55 @@ * @since 16:52:11 - 26.07.2010 */ public class EaseQuadInOut implements IEaseFunction { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - private static EaseQuadInOut INSTANCE; + private static EaseQuadInOut INSTANCE; - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - private EaseQuadInOut() { + private EaseQuadInOut() { - } + } - public static EaseQuadInOut getInstance() { - if(INSTANCE == null) { - INSTANCE = new EaseQuadInOut(); - } - return INSTANCE; - } + public static EaseQuadInOut getInstance() { + if(INSTANCE == null) { + INSTANCE = new EaseQuadInOut(); + } + return INSTANCE; + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - @Override - public float getPercentage(final float pSecondsElapsed, final float pDuration) { - final float percentage = pSecondsElapsed / pDuration; + @Override + public float getPercentage(final float pSecondsElapsed, final float pDuration) { + final float percentage = pSecondsElapsed / pDuration; - if(percentage < 0.5f) { - return 0.5f * EaseQuadIn.getValue(2 * percentage); - } else { - return 0.5f + 0.5f * EaseQuadOut.getValue(percentage * 2 - 1); - } - } + if(percentage < 0.5f) { + return 0.5f * EaseQuadIn.getValue(2 * percentage); + } else { + return 0.5f + 0.5f * EaseQuadOut.getValue(percentage * 2 - 1); + } + } - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseQuadOut.java b/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseQuadOut.java index 73271a7e..25476d01 100644 --- a/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseQuadOut.java +++ b/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseQuadOut.java @@ -9,53 +9,53 @@ * @since 16:52:11 - 26.07.2010 */ public class EaseQuadOut implements IEaseFunction { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - private static EaseQuadOut INSTANCE; + private static EaseQuadOut INSTANCE; - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - private EaseQuadOut() { + private EaseQuadOut() { - } + } - public static EaseQuadOut getInstance() { - if(INSTANCE == null) { - INSTANCE = new EaseQuadOut(); - } - return INSTANCE; - } + public static EaseQuadOut getInstance() { + if(INSTANCE == null) { + INSTANCE = new EaseQuadOut(); + } + return INSTANCE; + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - @Override - public float getPercentage(final float pSecondsElapsed, final float pDuration) { - return EaseQuadOut.getValue(pSecondsElapsed / pDuration); - } + @Override + public float getPercentage(final float pSecondsElapsed, final float pDuration) { + return EaseQuadOut.getValue(pSecondsElapsed / pDuration); + } - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - public static float getValue(final float pPercentage) { - return -pPercentage * (pPercentage - 2); - } + public static float getValue(final float pPercentage) { + return -pPercentage * (pPercentage - 2); + } - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseQuartIn.java b/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseQuartIn.java index 96ab9366..e7febd86 100644 --- a/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseQuartIn.java +++ b/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseQuartIn.java @@ -9,53 +9,53 @@ * @since 16:52:11 - 26.07.2010 */ public class EaseQuartIn implements IEaseFunction { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - private static EaseQuartIn INSTANCE; + private static EaseQuartIn INSTANCE; - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - private EaseQuartIn() { + private EaseQuartIn() { - } + } - public static EaseQuartIn getInstance() { - if(INSTANCE == null) { - INSTANCE = new EaseQuartIn(); - } - return INSTANCE; - } + public static EaseQuartIn getInstance() { + if(INSTANCE == null) { + INSTANCE = new EaseQuartIn(); + } + return INSTANCE; + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - @Override - public float getPercentage(final float pSecondsElapsed, final float pDuration) { - return EaseQuartIn.getValue(pSecondsElapsed / pDuration); - } + @Override + public float getPercentage(final float pSecondsElapsed, final float pDuration) { + return EaseQuartIn.getValue(pSecondsElapsed / pDuration); + } - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - public static float getValue(final float pPercentage) { - return pPercentage * pPercentage * pPercentage * pPercentage; - } + public static float getValue(final float pPercentage) { + return pPercentage * pPercentage * pPercentage * pPercentage; + } - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseQuartInOut.java b/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseQuartInOut.java index f8c51a07..0da89460 100644 --- a/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseQuartInOut.java +++ b/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseQuartInOut.java @@ -9,55 +9,55 @@ * @since 16:52:11 - 26.07.2010 */ public class EaseQuartInOut implements IEaseFunction { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - private static EaseQuartInOut INSTANCE; + private static EaseQuartInOut INSTANCE; - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - private EaseQuartInOut() { + private EaseQuartInOut() { - } + } - public static EaseQuartInOut getInstance() { - if(INSTANCE == null) { - INSTANCE = new EaseQuartInOut(); - } - return INSTANCE; - } + public static EaseQuartInOut getInstance() { + if(INSTANCE == null) { + INSTANCE = new EaseQuartInOut(); + } + return INSTANCE; + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - @Override - public float getPercentage(final float pSecondsElapsed, final float pDuration) { - final float percentage = pSecondsElapsed / pDuration; + @Override + public float getPercentage(final float pSecondsElapsed, final float pDuration) { + final float percentage = pSecondsElapsed / pDuration; - if(percentage < 0.5f) { - return 0.5f * EaseQuartIn.getValue(2 * percentage); - } else { - return 0.5f + 0.5f * EaseQuartOut.getValue(percentage * 2 - 1); - } - } + if(percentage < 0.5f) { + return 0.5f * EaseQuartIn.getValue(2 * percentage); + } else { + return 0.5f + 0.5f * EaseQuartOut.getValue(percentage * 2 - 1); + } + } - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseQuartOut.java b/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseQuartOut.java index f304c740..5e8856d3 100644 --- a/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseQuartOut.java +++ b/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseQuartOut.java @@ -9,54 +9,54 @@ * @since 16:52:11 - 26.07.2010 */ public class EaseQuartOut implements IEaseFunction { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - private static EaseQuartOut INSTANCE; + private static EaseQuartOut INSTANCE; - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - private EaseQuartOut() { + private EaseQuartOut() { - } + } - public static EaseQuartOut getInstance() { - if(INSTANCE == null) { - INSTANCE = new EaseQuartOut(); - } - return INSTANCE; - } + public static EaseQuartOut getInstance() { + if(INSTANCE == null) { + INSTANCE = new EaseQuartOut(); + } + return INSTANCE; + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - @Override - public float getPercentage(final float pSecondsElapsed, final float pDuration) { - return EaseQuartOut.getValue(pSecondsElapsed / pDuration); - } + @Override + public float getPercentage(final float pSecondsElapsed, final float pDuration) { + return EaseQuartOut.getValue(pSecondsElapsed / pDuration); + } - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - public static float getValue(final float pPercentage) { - final float t = pPercentage - 1; - return 1 - (t * t * t * t); - } + public static float getValue(final float pPercentage) { + final float t = pPercentage - 1; + return 1 - (t * t * t * t); + } - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseQuintIn.java b/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseQuintIn.java index bab5f64c..16d6cdad 100644 --- a/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseQuintIn.java +++ b/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseQuintIn.java @@ -9,53 +9,53 @@ * @since 16:52:11 - 26.07.2010 */ public class EaseQuintIn implements IEaseFunction { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - private static EaseQuintIn INSTANCE; + private static EaseQuintIn INSTANCE; - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - private EaseQuintIn() { + private EaseQuintIn() { - } + } - public static EaseQuintIn getInstance() { - if(INSTANCE == null) { - INSTANCE = new EaseQuintIn(); - } - return INSTANCE; - } + public static EaseQuintIn getInstance() { + if(INSTANCE == null) { + INSTANCE = new EaseQuintIn(); + } + return INSTANCE; + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - @Override - public float getPercentage(final float pSecondsElapsed, final float pDuration) { - return EaseQuintIn.getValue(pSecondsElapsed / pDuration); - } + @Override + public float getPercentage(final float pSecondsElapsed, final float pDuration) { + return EaseQuintIn.getValue(pSecondsElapsed / pDuration); + } - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - public static float getValue(final float pPercentage) { - return pPercentage * pPercentage * pPercentage * pPercentage * pPercentage; - } + public static float getValue(final float pPercentage) { + return pPercentage * pPercentage * pPercentage * pPercentage * pPercentage; + } - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseQuintInOut.java b/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseQuintInOut.java index 3fab345d..eddbd643 100644 --- a/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseQuintInOut.java +++ b/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseQuintInOut.java @@ -9,55 +9,55 @@ * @since 16:52:11 - 26.07.2010 */ public class EaseQuintInOut implements IEaseFunction { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - private static EaseQuintInOut INSTANCE; + private static EaseQuintInOut INSTANCE; - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - private EaseQuintInOut() { + private EaseQuintInOut() { - } + } - public static EaseQuintInOut getInstance() { - if(INSTANCE == null) { - INSTANCE = new EaseQuintInOut(); - } - return INSTANCE; - } + public static EaseQuintInOut getInstance() { + if(INSTANCE == null) { + INSTANCE = new EaseQuintInOut(); + } + return INSTANCE; + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - @Override - public float getPercentage(final float pSecondsElapsed, final float pDuration) { - final float percentage = pSecondsElapsed / pDuration; + @Override + public float getPercentage(final float pSecondsElapsed, final float pDuration) { + final float percentage = pSecondsElapsed / pDuration; - if(percentage < 0.5f) { - return 0.5f * EaseQuintIn.getValue(2 * percentage); - } else { - return 0.5f + 0.5f * EaseQuintOut.getValue(percentage * 2 - 1); - } - } + if(percentage < 0.5f) { + return 0.5f * EaseQuintIn.getValue(2 * percentage); + } else { + return 0.5f + 0.5f * EaseQuintOut.getValue(percentage * 2 - 1); + } + } - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseQuintOut.java b/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseQuintOut.java index d1c2adc4..dee6eef9 100644 --- a/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseQuintOut.java +++ b/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseQuintOut.java @@ -9,54 +9,54 @@ * @since 16:52:11 - 26.07.2010 */ public class EaseQuintOut implements IEaseFunction { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - private static EaseQuintOut INSTANCE; + private static EaseQuintOut INSTANCE; - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - private EaseQuintOut() { + private EaseQuintOut() { - } + } - public static EaseQuintOut getInstance() { - if(INSTANCE == null) { - INSTANCE = new EaseQuintOut(); - } - return INSTANCE; - } + public static EaseQuintOut getInstance() { + if(INSTANCE == null) { + INSTANCE = new EaseQuintOut(); + } + return INSTANCE; + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - @Override - public float getPercentage(final float pSecondsElapsed, final float pDuration) { - return EaseQuintOut.getValue(pSecondsElapsed / pDuration); - } + @Override + public float getPercentage(final float pSecondsElapsed, final float pDuration) { + return EaseQuintOut.getValue(pSecondsElapsed / pDuration); + } - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - public static float getValue(final float pPercentage) { - final float t = pPercentage - 1; - return 1 + (t * t * t * t * t); - } + public static float getValue(final float pPercentage) { + final float t = pPercentage - 1; + return 1 + (t * t * t * t * t); + } - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseSineIn.java b/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseSineIn.java index 06663aa1..752fe54d 100644 --- a/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseSineIn.java +++ b/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseSineIn.java @@ -13,53 +13,53 @@ * @since 16:52:11 - 26.07.2010 */ public class EaseSineIn implements IEaseFunction, MathConstants { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - private static EaseSineIn INSTANCE; + private static EaseSineIn INSTANCE; - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - private EaseSineIn() { + private EaseSineIn() { - } + } - public static EaseSineIn getInstance() { - if(INSTANCE == null) { - INSTANCE = new EaseSineIn(); - } - return INSTANCE; - } + public static EaseSineIn getInstance() { + if(INSTANCE == null) { + INSTANCE = new EaseSineIn(); + } + return INSTANCE; + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - @Override - public float getPercentage(final float pSecondsElapsed, final float pDuration) { - return EaseSineIn.getValue(pSecondsElapsed / pDuration); - } + @Override + public float getPercentage(final float pSecondsElapsed, final float pDuration) { + return EaseSineIn.getValue(pSecondsElapsed / pDuration); + } - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - public static float getValue(final float pPercentage) { - return -(float)Math.cos(pPercentage * PI_HALF) + 1; - } + public static float getValue(final float pPercentage) { + return -(float)Math.cos(pPercentage * PI_HALF) + 1; + } - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseSineInOut.java b/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseSineInOut.java index 69c0ba44..8d75349f 100644 --- a/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseSineInOut.java +++ b/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseSineInOut.java @@ -12,51 +12,51 @@ * @since 16:52:11 - 26.07.2010 */ public class EaseSineInOut implements IEaseFunction { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - private static EaseSineInOut INSTANCE; + private static EaseSineInOut INSTANCE; - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - private EaseSineInOut() { + private EaseSineInOut() { - } + } - public static EaseSineInOut getInstance() { - if(INSTANCE == null) { - INSTANCE = new EaseSineInOut(); - } - return INSTANCE; - } + public static EaseSineInOut getInstance() { + if(INSTANCE == null) { + INSTANCE = new EaseSineInOut(); + } + return INSTANCE; + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - @Override - public float getPercentage(final float pSecondsElapsed, final float pDuration) { - final float percentage = pSecondsElapsed / pDuration; + @Override + public float getPercentage(final float pSecondsElapsed, final float pDuration) { + final float percentage = pSecondsElapsed / pDuration; - return -0.5f * ((float) Math.cos(percentage * PI) - 1); - } + return -0.5f * ((float) Math.cos(percentage * PI) - 1); + } - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseSineOut.java b/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseSineOut.java index 09a2526e..89e6f05e 100644 --- a/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseSineOut.java +++ b/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseSineOut.java @@ -13,53 +13,53 @@ * @since 16:52:11 - 26.07.2010 */ public class EaseSineOut implements IEaseFunction, MathConstants { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - private static EaseSineOut INSTANCE; + private static EaseSineOut INSTANCE; - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - private EaseSineOut() { + private EaseSineOut() { - } + } - public static EaseSineOut getInstance() { - if(INSTANCE == null) { - INSTANCE = new EaseSineOut(); - } - return INSTANCE; - } + public static EaseSineOut getInstance() { + if(INSTANCE == null) { + INSTANCE = new EaseSineOut(); + } + return INSTANCE; + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - @Override - public float getPercentage(final float pSecondsElapsed, final float pDuration) { - return EaseSineOut.getValue(pSecondsElapsed / pDuration); - } + @Override + public float getPercentage(final float pSecondsElapsed, final float pDuration) { + return EaseSineOut.getValue(pSecondsElapsed / pDuration); + } - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - public static float getValue(final float pPercentage) { - return (float) Math.sin(pPercentage * PI_HALF); - } + public static float getValue(final float pPercentage) { + return (float) Math.sin(pPercentage * PI_HALF); + } - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseStrongIn.java b/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseStrongIn.java index bf9e3d4c..e0b35b5f 100644 --- a/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseStrongIn.java +++ b/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseStrongIn.java @@ -9,53 +9,53 @@ * @since 16:52:11 - 26.07.2010 */ public class EaseStrongIn implements IEaseFunction { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - private static EaseStrongIn INSTANCE; + private static EaseStrongIn INSTANCE; - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - private EaseStrongIn() { + private EaseStrongIn() { - } + } - public static EaseStrongIn getInstance() { - if(INSTANCE == null) { - INSTANCE = new EaseStrongIn(); - } - return INSTANCE; - } + public static EaseStrongIn getInstance() { + if(INSTANCE == null) { + INSTANCE = new EaseStrongIn(); + } + return INSTANCE; + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - @Override - public float getPercentage(final float pSecondsElapsed, final float pDuration) { - return EaseStrongIn.getValue(pSecondsElapsed / pDuration); - } + @Override + public float getPercentage(final float pSecondsElapsed, final float pDuration) { + return EaseStrongIn.getValue(pSecondsElapsed / pDuration); + } - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - public static float getValue(final float pPercentage) { - return pPercentage * pPercentage * pPercentage * pPercentage * pPercentage; - } + public static float getValue(final float pPercentage) { + return pPercentage * pPercentage * pPercentage * pPercentage * pPercentage; + } - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseStrongInOut.java b/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseStrongInOut.java index 704ae155..cbe2716a 100644 --- a/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseStrongInOut.java +++ b/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseStrongInOut.java @@ -9,55 +9,55 @@ * @since 16:52:11 - 26.07.2010 */ public class EaseStrongInOut implements IEaseFunction { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - private static EaseStrongInOut INSTANCE; + private static EaseStrongInOut INSTANCE; - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - private EaseStrongInOut() { + private EaseStrongInOut() { - } + } - public static EaseStrongInOut getInstance() { - if(INSTANCE == null) { - INSTANCE = new EaseStrongInOut(); - } - return INSTANCE; - } + public static EaseStrongInOut getInstance() { + if(INSTANCE == null) { + INSTANCE = new EaseStrongInOut(); + } + return INSTANCE; + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - @Override - public float getPercentage(final float pSecondsElapsed, final float pDuration) { - final float percentage = pSecondsElapsed / pDuration; + @Override + public float getPercentage(final float pSecondsElapsed, final float pDuration) { + final float percentage = pSecondsElapsed / pDuration; - if(percentage < 0.5f) { - return 0.5f * EaseStrongIn.getValue(2 * percentage); - } else { - return 0.5f + 0.5f * EaseStrongOut.getValue(percentage * 2 - 1); - } - } + if(percentage < 0.5f) { + return 0.5f * EaseStrongIn.getValue(2 * percentage); + } else { + return 0.5f + 0.5f * EaseStrongOut.getValue(percentage * 2 - 1); + } + } - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseStrongOut.java b/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseStrongOut.java index 71bc182d..159e4f03 100644 --- a/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseStrongOut.java +++ b/AndEngine/src/org/anddev/andengine/util/modifier/ease/EaseStrongOut.java @@ -9,54 +9,54 @@ * @since 16:52:11 - 26.07.2010 */ public class EaseStrongOut implements IEaseFunction { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - private static EaseStrongOut INSTANCE; + private static EaseStrongOut INSTANCE; - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - private EaseStrongOut() { + private EaseStrongOut() { - } + } - public static EaseStrongOut getInstance() { - if(INSTANCE == null) { - INSTANCE = new EaseStrongOut(); - } - return INSTANCE; - } + public static EaseStrongOut getInstance() { + if(INSTANCE == null) { + INSTANCE = new EaseStrongOut(); + } + return INSTANCE; + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - @Override - public float getPercentage(final float pSecondsElapsed, final float pDuration) { - return EaseStrongOut.getValue(pSecondsElapsed / pDuration); - } + @Override + public float getPercentage(final float pSecondsElapsed, final float pDuration) { + return EaseStrongOut.getValue(pSecondsElapsed / pDuration); + } - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - public static float getValue(final float pPercentage) { - final float t = pPercentage - 1; - return 1 + (t * t * t * t * t); - } + public static float getValue(final float pPercentage) { + final float t = pPercentage - 1; + return 1 + (t * t * t * t * t); + } - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/util/modifier/ease/IEaseFunction.java b/AndEngine/src/org/anddev/andengine/util/modifier/ease/IEaseFunction.java index 61a31d44..4e1c2f78 100644 --- a/AndEngine/src/org/anddev/andengine/util/modifier/ease/IEaseFunction.java +++ b/AndEngine/src/org/anddev/andengine/util/modifier/ease/IEaseFunction.java @@ -9,15 +9,15 @@ * @since 17:13:17 - 26.07.2010 */ public interface IEaseFunction { - // =========================================================== - // Final Fields - // =========================================================== + // =========================================================== + // Final Fields + // =========================================================== - public static final IEaseFunction DEFAULT = EaseLinear.getInstance(); + public static final IEaseFunction DEFAULT = EaseLinear.getInstance(); - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - public float getPercentage(final float pSecondsElapsed, final float pDuration); + public float getPercentage(final float pSecondsElapsed, final float pDuration); } diff --git a/AndEngine/src/org/anddev/andengine/util/modifier/util/ModifierUtils.java b/AndEngine/src/org/anddev/andengine/util/modifier/util/ModifierUtils.java index 0d35f29b..8bd7851a 100644 --- a/AndEngine/src/org/anddev/andengine/util/modifier/util/ModifierUtils.java +++ b/AndEngine/src/org/anddev/andengine/util/modifier/util/ModifierUtils.java @@ -10,41 +10,41 @@ * @since 11:16:36 - 03.09.2010 */ public class ModifierUtils { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - public static float getSequenceDurationOfModifier(final IModifier[] pModifiers){ - float duration = Float.MIN_VALUE; + public static float getSequenceDurationOfModifier(final IModifier[] pModifiers){ + float duration = Float.MIN_VALUE; - for(int i = pModifiers.length - 1; i >= 0; i--) { - duration += pModifiers[i].getDuration(); - } + for(int i = pModifiers.length - 1; i >= 0; i--) { + duration += pModifiers[i].getDuration(); + } - return duration; - } + return duration; + } - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/util/path/Direction.java b/AndEngine/src/org/anddev/andengine/util/path/Direction.java index ab6b9675..f3b4cc43 100644 --- a/AndEngine/src/org/anddev/andengine/util/path/Direction.java +++ b/AndEngine/src/org/anddev/andengine/util/path/Direction.java @@ -8,169 +8,169 @@ * @since 15:19:11 - 17.08.2010 */ public enum Direction { - // =========================================================== - // Elements - // =========================================================== - - 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); - - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - private final int mDeltaX; - private final int mDeltaY; - - // =========================================================== - // Constructors - // =========================================================== - - private Direction(final int pDeltaX, final int pDeltaY) { - this.mDeltaX = pDeltaX; - this.mDeltaY = pDeltaY; - } - - public static Direction fromDelta(final int pDeltaX, final int pDeltaY) { - switch(pDeltaX) { - case -1: - switch(pDeltaY) { - case -1: - return UP_LEFT; - case 0: - return LEFT; - case 1: - return DOWN_LEFT; - } - break; - case 0: - switch(pDeltaY) { - case -1: - return UP; - case 1: - return DOWN; - } - break; - case 1: - switch(pDeltaY) { - case -1: - return UP_RIGHT; - case 0: - return RIGHT; - case 1: - return DOWN_RIGHT; - } - break; - } - throw new IllegalArgumentException("Unexpected deltaX: '" + pDeltaX + "' deltaY: '" + pDeltaY + "'."); - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - public boolean isHorizontal() { - return this.mDeltaY == 0; - } - - public boolean isVertical() { - return this.mDeltaX == 0; - } - - public int getDeltaX() { - return this.mDeltaX; - } - - public int getDeltaY() { - return this.mDeltaY; - } - - public Direction rotateLeft() { - switch(this) { - case UP: - return LEFT; - case UP_RIGHT: - return UP_LEFT; - case RIGHT: - return UP; - case DOWN_RIGHT: - return UP_RIGHT; - case DOWN: - return UP; - case DOWN_LEFT: - return DOWN_RIGHT; - case LEFT: - return DOWN; - case UP_LEFT: - return DOWN_LEFT; - } - throw new IllegalArgumentException(); - } - - public Direction rotateRight() { - switch(this) { - case UP: - return RIGHT; - case UP_RIGHT: - return DOWN_RIGHT; - case RIGHT: - return DOWN; - case DOWN_RIGHT: - return DOWN_LEFT; - case DOWN: - return LEFT; - case DOWN_LEFT: - return UP_LEFT; - case LEFT: - return UP; - case UP_LEFT: - return UP_RIGHT; - } - throw new IllegalArgumentException(); - } - - public Direction opposite() { - switch(this) { - case UP: - return DOWN; - case UP_RIGHT: - return DOWN_LEFT; - case RIGHT: - return LEFT; - case DOWN_RIGHT: - return UP_LEFT; - case DOWN: - return UP; - case DOWN_LEFT: - return UP_RIGHT; - case LEFT: - return RIGHT; - case UP_LEFT: - return DOWN_RIGHT; - } - throw new IllegalArgumentException(); - } - - // =========================================================== - // Methods from SuperClass/Interfaces - // =========================================================== - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Elements + // =========================================================== + + 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); + + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + private final int mDeltaX; + private final int mDeltaY; + + // =========================================================== + // Constructors + // =========================================================== + + private Direction(final int pDeltaX, final int pDeltaY) { + this.mDeltaX = pDeltaX; + this.mDeltaY = pDeltaY; + } + + public static Direction fromDelta(final int pDeltaX, final int pDeltaY) { + switch(pDeltaX) { + case -1: + switch(pDeltaY) { + case -1: + return UP_LEFT; + case 0: + return LEFT; + case 1: + return DOWN_LEFT; + } + break; + case 0: + switch(pDeltaY) { + case -1: + return UP; + case 1: + return DOWN; + } + break; + case 1: + switch(pDeltaY) { + case -1: + return UP_RIGHT; + case 0: + return RIGHT; + case 1: + return DOWN_RIGHT; + } + break; + } + throw new IllegalArgumentException("Unexpected deltaX: '" + pDeltaX + "' deltaY: '" + pDeltaY + "'."); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + public boolean isHorizontal() { + return this.mDeltaY == 0; + } + + public boolean isVertical() { + return this.mDeltaX == 0; + } + + public int getDeltaX() { + return this.mDeltaX; + } + + public int getDeltaY() { + return this.mDeltaY; + } + + public Direction rotateLeft() { + switch(this) { + case UP: + return LEFT; + case UP_RIGHT: + return UP_LEFT; + case RIGHT: + return UP; + case DOWN_RIGHT: + return UP_RIGHT; + case DOWN: + return UP; + case DOWN_LEFT: + return DOWN_RIGHT; + case LEFT: + return DOWN; + case UP_LEFT: + return DOWN_LEFT; + } + throw new IllegalArgumentException(); + } + + public Direction rotateRight() { + switch(this) { + case UP: + return RIGHT; + case UP_RIGHT: + return DOWN_RIGHT; + case RIGHT: + return DOWN; + case DOWN_RIGHT: + return DOWN_LEFT; + case DOWN: + return LEFT; + case DOWN_LEFT: + return UP_LEFT; + case LEFT: + return UP; + case UP_LEFT: + return UP_RIGHT; + } + throw new IllegalArgumentException(); + } + + public Direction opposite() { + switch(this) { + case UP: + return DOWN; + case UP_RIGHT: + return DOWN_LEFT; + case RIGHT: + return LEFT; + case DOWN_RIGHT: + return UP_LEFT; + case DOWN: + return UP; + case DOWN_LEFT: + return UP_RIGHT; + case LEFT: + return RIGHT; + case UP_LEFT: + return DOWN_RIGHT; + } + throw new IllegalArgumentException(); + } + + // =========================================================== + // Methods from SuperClass/Interfaces + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/util/path/IPathFinder.java b/AndEngine/src/org/anddev/andengine/util/path/IPathFinder.java index 40e30478..36188c5f 100644 --- a/AndEngine/src/org/anddev/andengine/util/path/IPathFinder.java +++ b/AndEngine/src/org/anddev/andengine/util/path/IPathFinder.java @@ -8,13 +8,13 @@ * @since 22:57:13 - 16.08.2010 */ public interface IPathFinder { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - public Path findPath(final T pEntity, final int pMaxCost, final int pFromTileColumn, final int pFromTileRow, final int pToTileColumn, final int pToTileRow); + public Path findPath(final T pEntity, final int pMaxCost, final int pFromTileColumn, final int pFromTileRow, final int pToTileColumn, final int pToTileRow); } diff --git a/AndEngine/src/org/anddev/andengine/util/path/ITiledMap.java b/AndEngine/src/org/anddev/andengine/util/path/ITiledMap.java index d3edcfac..343bfb56 100644 --- a/AndEngine/src/org/anddev/andengine/util/path/ITiledMap.java +++ b/AndEngine/src/org/anddev/andengine/util/path/ITiledMap.java @@ -8,20 +8,20 @@ * @since 23:00:24 - 16.08.2010 */ public interface ITiledMap { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - public int getTileColumns(); - public int getTileRows(); + public int getTileColumns(); + public int getTileRows(); - public void onTileVisitedByPathFinder(final int pTileColumn, int pTileRow); + public void onTileVisitedByPathFinder(final int pTileColumn, int pTileRow); - public boolean isTileBlocked(final T pEntity, final int pTileColumn, final int pTileRow); + public boolean isTileBlocked(final T pEntity, final int pTileColumn, final int pTileRow); - public float getStepCost(final T pEntity, final int pFromTileColumn, final int pFromTileRow, final int pToTileColumn, final int pToTileRow); + public float getStepCost(final T pEntity, final int pFromTileColumn, final int pFromTileRow, final int pToTileColumn, final int pToTileRow); } diff --git a/AndEngine/src/org/anddev/andengine/util/path/Path.java b/AndEngine/src/org/anddev/andengine/util/path/Path.java index 7fd2fda2..268f993c 100644 --- a/AndEngine/src/org/anddev/andengine/util/path/Path.java +++ b/AndEngine/src/org/anddev/andengine/util/path/Path.java @@ -10,185 +10,185 @@ * @since 23:00:24 - 16.08.2010 */ public class Path { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - private final ArrayList mSteps = new ArrayList(); - - // =========================================================== - // Constructors - // =========================================================== - - // =========================================================== - // Getter & Setter - // =========================================================== - - public int getLength() { - return this.mSteps.size(); - } - - public Step getStep(final int pIndex) { - return this.mSteps.get(pIndex); - } - - public Direction getDirectionToPreviousStep(final int pIndex) { - if(pIndex == 0) { - return null; - } else { - final int dX = this.getTileColumn(pIndex - 1) - this.getTileColumn(pIndex); - final int dY = this.getTileRow(pIndex - 1) - this.getTileRow(pIndex); - return Direction.fromDelta(dX, dY); - } - } - - public Direction getDirectionToNextStep(final int pIndex) { - if(pIndex == this.getLength() - 1) { - return null; - } else { - final int dX = this.getTileColumn(pIndex + 1) - this.getTileColumn(pIndex); - final int dY = this.getTileRow(pIndex + 1) - this.getTileRow(pIndex); - return Direction.fromDelta(dX, dY); - } - } - - public int getTileColumn(final int pIndex) { - return this.getStep(pIndex).getTileColumn(); - } - - public int getTileRow(final int pIndex) { - return this.getStep(pIndex).getTileRow(); - } - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - // =========================================================== - // Methods - // =========================================================== - - public void append(final int pTileColumn, final int pTileRow) { - this.append(new Step(pTileColumn, pTileRow)); - } - - public void append(final Step pStep) { - this.mSteps.add(pStep); - } - - public void prepend(final int pTileColumn, final int pTileRow) { - this.prepend(new Step(pTileColumn, pTileRow)); - } - - public void prepend(final Step pStep) { - this.mSteps.add(0, pStep); - } - - public boolean contains(final int pTileColumn, final int pTileRow) { - final ArrayList steps = this.mSteps; - for(int i = steps.size() - 1; i >= 0; i--) { - final Step step = steps.get(i); - if(step.getTileColumn() == pTileColumn && step.getTileRow() == pTileRow) { - return true; - } - } - return false; - } - - public int getFromTileRow() { - return this.getTileRow(0); - } - - public int getFromTileColumn() { - return this.getTileColumn(0); - } - - public int getToTileRow() { - return this.getTileRow(this.mSteps.size() - 1); - } - - public int getToTileColumn() { - return this.getTileColumn(this.mSteps.size() - 1); - } - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== - - public class Step { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - private final int mTileColumn; - private final int mTileRow; - - // =========================================================== - // Constructors - // =========================================================== - - public Step(final int pTileColumn, final int pTileRow) { - this.mTileColumn = pTileColumn; - this.mTileRow = pTileRow; - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - public int getTileColumn() { - return this.mTileColumn; - } - - public int getTileRow() { - return this.mTileRow; - } - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - public int hashCode() { - return this.mTileColumn << 16 + this.mTileRow; - } - - @Override - public boolean equals(final Object pOther) { - if(this == pOther) { - return true; - } - if(pOther == null) { - return false; - } - if(this.getClass() != pOther.getClass()) { - return false; - } - final Step other = (Step) pOther; - if(this.mTileColumn != other.mTileColumn) { - return false; - } - if(this.mTileRow != other.mTileRow) { - return false; - } - return true; - } - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== - } + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + private final ArrayList mSteps = new ArrayList(); + + // =========================================================== + // Constructors + // =========================================================== + + // =========================================================== + // Getter & Setter + // =========================================================== + + public int getLength() { + return this.mSteps.size(); + } + + public Step getStep(final int pIndex) { + return this.mSteps.get(pIndex); + } + + public Direction getDirectionToPreviousStep(final int pIndex) { + if(pIndex == 0) { + return null; + } else { + final int dX = this.getTileColumn(pIndex - 1) - this.getTileColumn(pIndex); + final int dY = this.getTileRow(pIndex - 1) - this.getTileRow(pIndex); + return Direction.fromDelta(dX, dY); + } + } + + public Direction getDirectionToNextStep(final int pIndex) { + if(pIndex == this.getLength() - 1) { + return null; + } else { + final int dX = this.getTileColumn(pIndex + 1) - this.getTileColumn(pIndex); + final int dY = this.getTileRow(pIndex + 1) - this.getTileRow(pIndex); + return Direction.fromDelta(dX, dY); + } + } + + public int getTileColumn(final int pIndex) { + return this.getStep(pIndex).getTileColumn(); + } + + public int getTileRow(final int pIndex) { + return this.getStep(pIndex).getTileRow(); + } + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + public void append(final int pTileColumn, final int pTileRow) { + this.append(new Step(pTileColumn, pTileRow)); + } + + public void append(final Step pStep) { + this.mSteps.add(pStep); + } + + public void prepend(final int pTileColumn, final int pTileRow) { + this.prepend(new Step(pTileColumn, pTileRow)); + } + + public void prepend(final Step pStep) { + this.mSteps.add(0, pStep); + } + + public boolean contains(final int pTileColumn, final int pTileRow) { + final ArrayList steps = this.mSteps; + for(int i = steps.size() - 1; i >= 0; i--) { + final Step step = steps.get(i); + if(step.getTileColumn() == pTileColumn && step.getTileRow() == pTileRow) { + return true; + } + } + return false; + } + + public int getFromTileRow() { + return this.getTileRow(0); + } + + public int getFromTileColumn() { + return this.getTileColumn(0); + } + + public int getToTileRow() { + return this.getTileRow(this.mSteps.size() - 1); + } + + public int getToTileColumn() { + return this.getTileColumn(this.mSteps.size() - 1); + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== + + public class Step { + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + private final int mTileColumn; + private final int mTileRow; + + // =========================================================== + // Constructors + // =========================================================== + + public Step(final int pTileColumn, final int pTileRow) { + this.mTileColumn = pTileColumn; + this.mTileRow = pTileRow; + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + public int getTileColumn() { + return this.mTileColumn; + } + + public int getTileRow() { + return this.mTileRow; + } + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + public int hashCode() { + return this.mTileColumn << 16 + this.mTileRow; + } + + @Override + public boolean equals(final Object pOther) { + if(this == pOther) { + return true; + } + if(pOther == null) { + return false; + } + if(this.getClass() != pOther.getClass()) { + return false; + } + final Step other = (Step) pOther; + if(this.mTileColumn != other.mTileColumn) { + return false; + } + if(this.mTileRow != other.mTileRow) { + return false; + } + return true; + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== + } } diff --git a/AndEngine/src/org/anddev/andengine/util/path/astar/AStarPathFinder.java b/AndEngine/src/org/anddev/andengine/util/path/astar/AStarPathFinder.java index b001d5e3..ff62af7a 100644 --- a/AndEngine/src/org/anddev/andengine/util/path/astar/AStarPathFinder.java +++ b/AndEngine/src/org/anddev/andengine/util/path/astar/AStarPathFinder.java @@ -15,241 +15,241 @@ * @since 23:16:17 - 16.08.2010 */ public class AStarPathFinder implements IPathFinder { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - private final ArrayList mVisitedNodes = new ArrayList(); - private final ArrayList mOpenNodes = new ArrayList(); - - private final ITiledMap mTiledMap; - private final int mMaxSearchDepth; - - private final Node[][] mNodes; - private final boolean mAllowDiagonalMovement; - - private final IAStarHeuristic mAStarHeuristic; - - // =========================================================== - // Constructors - // =========================================================== - - public AStarPathFinder(final ITiledMap pTiledMap, final int pMaxSearchDepth, final boolean pAllowDiagonalMovement) { - this(pTiledMap, pMaxSearchDepth, pAllowDiagonalMovement, new EuclideanHeuristic()); - } - - public AStarPathFinder(final ITiledMap pTiledMap, final int pMaxSearchDepth, final boolean pAllowDiagonalMovement, final IAStarHeuristic pAStarHeuristic) { - this.mAStarHeuristic = pAStarHeuristic; - this.mTiledMap = pTiledMap; - this.mMaxSearchDepth = pMaxSearchDepth; - this.mAllowDiagonalMovement = pAllowDiagonalMovement; - - this.mNodes = new Node[pTiledMap.getTileRows()][pTiledMap.getTileColumns()]; - final Node[][] nodes = this.mNodes; - for(int x = pTiledMap.getTileColumns() - 1; x >= 0; x--) { - for(int y = pTiledMap.getTileRows() - 1; y >= 0; y--) { - nodes[y][x] = new Node(x, y); - } - } - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - public Path findPath(final T pEntity, final int pMaxCost, final int pFromTileColumn, final int pFromTileRow, final int pToTileColumn, final int pToTileRow) { - final ITiledMap tiledMap = this.mTiledMap; - if(tiledMap.isTileBlocked(pEntity, pToTileColumn, pToTileRow)) { - return null; - } - - /* Drag some fields to local variables. */ - final ArrayList openNodes = this.mOpenNodes; - final ArrayList visitedNodes = this.mVisitedNodes; - - final Node[][] nodes = this.mNodes; - final Node fromNode = nodes[pFromTileRow][pFromTileColumn]; - final Node toNode = nodes[pToTileRow][pToTileColumn]; - - final IAStarHeuristic aStarHeuristic = this.mAStarHeuristic; - final boolean allowDiagonalMovement = this.mAllowDiagonalMovement; - final int maxSearchDepth = this.mMaxSearchDepth; - - /* Initialize algorithm. */ - fromNode.mCost = 0; - fromNode.mDepth = 0; - toNode.mParent = null; - - visitedNodes.clear(); - - openNodes.clear(); - openNodes.add(fromNode); - - int currentDepth = 0; - while(currentDepth < maxSearchDepth && !openNodes.isEmpty()) { - /* The first Node in the open list is the one with the lowest cost. */ - final Node current = openNodes.remove(0); - if(current == toNode) { - break; - } - - visitedNodes.add(current); - - /* Loop over all neighbors of this tile. */ - for(int dX = -1; dX <= 1; dX++) { - for(int dY = -1; dY <= 1; dY++) { - if((dX == 0) && (dY == 0)) { - continue; - } - - if(!allowDiagonalMovement) { - if((dX != 0) && (dY != 0)) { - continue; - } - } - - final int neighborTileColumn = dX + current.mTileColumn; - final int neighborTileRow = dY + current.mTileRow; - - if(!this.isTileBlocked(pEntity, pFromTileColumn, pFromTileRow, neighborTileColumn, neighborTileRow)) { - final float neighborCost = current.mCost + tiledMap.getStepCost(pEntity, current.mTileColumn, current.mTileRow, neighborTileColumn, neighborTileRow); - final Node neighbor = nodes[neighborTileRow][neighborTileColumn]; - tiledMap.onTileVisitedByPathFinder(neighborTileColumn, neighborTileRow); - - /* Re-evaluate if there is a better path. */ - if(neighborCost < neighbor.mCost) { - // TODO Is this ever possible with AStar ?? - if(openNodes.contains(neighbor)) { - openNodes.remove(neighbor); - } - if(visitedNodes.contains(neighbor)) { - visitedNodes.remove(neighbor); - } - } - - if(!openNodes.contains(neighbor) && !(visitedNodes.contains(neighbor))) { - neighbor.mCost = neighborCost; - if(neighbor.mCost <= pMaxCost) { - neighbor.mExpectedRestCost = aStarHeuristic.getExpectedRestCost(tiledMap, pEntity, neighborTileColumn, neighborTileRow, pToTileColumn, pToTileRow); - currentDepth = Math.max(currentDepth, neighbor.setParent(current)); - openNodes.add(neighbor); - - /* Ensure always the node with the lowest cost+heuristic - * will be used next, simply by sorting. */ - Collections.sort(openNodes); - } - } - } - } - } - } - - /* Check if a path was found. */ - if(toNode.mParent == null) { - return null; - } - - /* Traceback path. */ - final Path path = new Path(); - Node tmp = nodes[pToTileRow][pToTileColumn]; - while(tmp != fromNode) { - path.prepend(tmp.mTileColumn, tmp.mTileRow); - tmp = tmp.mParent; - } - path.prepend(pFromTileColumn, pFromTileRow); - - return path; - } - - // =========================================================== - // Methods - // =========================================================== - - protected boolean isTileBlocked(final T pEntity, final int pFromTileColumn, final int pFromTileRow, final int pToTileColumn, final int pToTileRow) { - if((pToTileColumn < 0) || (pToTileRow < 0) || (pToTileColumn >= this.mTiledMap.getTileColumns()) || (pToTileRow >= this.mTiledMap.getTileRows())) { - return true; - } else if((pFromTileColumn == pToTileColumn) && (pFromTileRow == pToTileRow)) { - return true; - } - - return this.mTiledMap.isTileBlocked(pEntity, pToTileColumn, pToTileRow); - } - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== - - private static class Node implements Comparable { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - Node mParent; - int mDepth; - - final int mTileColumn; - final int mTileRow; - - float mCost; - float mExpectedRestCost; - - // =========================================================== - // Constructors - // =========================================================== - - public Node(final int pTileColumn, final int pTileRow) { - this.mTileColumn = pTileColumn; - this.mTileRow = pTileRow; - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - public int setParent(final Node parent) { - this.mDepth = parent.mDepth + 1; - this.mParent = parent; - - return this.mDepth; - } - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - public int compareTo(final Node pOther) { - final float totalCost = this.mExpectedRestCost + this.mCost; - final float totalCostOther = pOther.mExpectedRestCost + pOther.mCost; - - if (totalCost < totalCostOther) { - return -1; - } else if (totalCost > totalCostOther) { - return 1; - } else { - return 0; - } - } - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== - } + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + private final ArrayList mVisitedNodes = new ArrayList(); + private final ArrayList mOpenNodes = new ArrayList(); + + private final ITiledMap mTiledMap; + private final int mMaxSearchDepth; + + private final Node[][] mNodes; + private final boolean mAllowDiagonalMovement; + + private final IAStarHeuristic mAStarHeuristic; + + // =========================================================== + // Constructors + // =========================================================== + + public AStarPathFinder(final ITiledMap pTiledMap, final int pMaxSearchDepth, final boolean pAllowDiagonalMovement) { + this(pTiledMap, pMaxSearchDepth, pAllowDiagonalMovement, new EuclideanHeuristic()); + } + + public AStarPathFinder(final ITiledMap pTiledMap, final int pMaxSearchDepth, final boolean pAllowDiagonalMovement, final IAStarHeuristic pAStarHeuristic) { + this.mAStarHeuristic = pAStarHeuristic; + this.mTiledMap = pTiledMap; + this.mMaxSearchDepth = pMaxSearchDepth; + this.mAllowDiagonalMovement = pAllowDiagonalMovement; + + this.mNodes = new Node[pTiledMap.getTileRows()][pTiledMap.getTileColumns()]; + final Node[][] nodes = this.mNodes; + for(int x = pTiledMap.getTileColumns() - 1; x >= 0; x--) { + for(int y = pTiledMap.getTileRows() - 1; y >= 0; y--) { + nodes[y][x] = new Node(x, y); + } + } + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + public Path findPath(final T pEntity, final int pMaxCost, final int pFromTileColumn, final int pFromTileRow, final int pToTileColumn, final int pToTileRow) { + final ITiledMap tiledMap = this.mTiledMap; + if(tiledMap.isTileBlocked(pEntity, pToTileColumn, pToTileRow)) { + return null; + } + + /* Drag some fields to local variables. */ + final ArrayList openNodes = this.mOpenNodes; + final ArrayList visitedNodes = this.mVisitedNodes; + + final Node[][] nodes = this.mNodes; + final Node fromNode = nodes[pFromTileRow][pFromTileColumn]; + final Node toNode = nodes[pToTileRow][pToTileColumn]; + + final IAStarHeuristic aStarHeuristic = this.mAStarHeuristic; + final boolean allowDiagonalMovement = this.mAllowDiagonalMovement; + final int maxSearchDepth = this.mMaxSearchDepth; + + /* Initialize algorithm. */ + fromNode.mCost = 0; + fromNode.mDepth = 0; + toNode.mParent = null; + + visitedNodes.clear(); + + openNodes.clear(); + openNodes.add(fromNode); + + int currentDepth = 0; + while(currentDepth < maxSearchDepth && !openNodes.isEmpty()) { + /* The first Node in the open list is the one with the lowest cost. */ + final Node current = openNodes.remove(0); + if(current == toNode) { + break; + } + + visitedNodes.add(current); + + /* Loop over all neighbors of this tile. */ + for(int dX = -1; dX <= 1; dX++) { + for(int dY = -1; dY <= 1; dY++) { + if((dX == 0) && (dY == 0)) { + continue; + } + + if(!allowDiagonalMovement) { + if((dX != 0) && (dY != 0)) { + continue; + } + } + + final int neighborTileColumn = dX + current.mTileColumn; + final int neighborTileRow = dY + current.mTileRow; + + if(!this.isTileBlocked(pEntity, pFromTileColumn, pFromTileRow, neighborTileColumn, neighborTileRow)) { + final float neighborCost = current.mCost + tiledMap.getStepCost(pEntity, current.mTileColumn, current.mTileRow, neighborTileColumn, neighborTileRow); + final Node neighbor = nodes[neighborTileRow][neighborTileColumn]; + tiledMap.onTileVisitedByPathFinder(neighborTileColumn, neighborTileRow); + + /* Re-evaluate if there is a better path. */ + if(neighborCost < neighbor.mCost) { + // TODO Is this ever possible with AStar ?? + if(openNodes.contains(neighbor)) { + openNodes.remove(neighbor); + } + if(visitedNodes.contains(neighbor)) { + visitedNodes.remove(neighbor); + } + } + + if(!openNodes.contains(neighbor) && !(visitedNodes.contains(neighbor))) { + neighbor.mCost = neighborCost; + if(neighbor.mCost <= pMaxCost) { + neighbor.mExpectedRestCost = aStarHeuristic.getExpectedRestCost(tiledMap, pEntity, neighborTileColumn, neighborTileRow, pToTileColumn, pToTileRow); + currentDepth = Math.max(currentDepth, neighbor.setParent(current)); + openNodes.add(neighbor); + + /* Ensure always the node with the lowest cost+heuristic + * will be used next, simply by sorting. */ + Collections.sort(openNodes); + } + } + } + } + } + } + + /* Check if a path was found. */ + if(toNode.mParent == null) { + return null; + } + + /* Traceback path. */ + final Path path = new Path(); + Node tmp = nodes[pToTileRow][pToTileColumn]; + while(tmp != fromNode) { + path.prepend(tmp.mTileColumn, tmp.mTileRow); + tmp = tmp.mParent; + } + path.prepend(pFromTileColumn, pFromTileRow); + + return path; + } + + // =========================================================== + // Methods + // =========================================================== + + protected boolean isTileBlocked(final T pEntity, final int pFromTileColumn, final int pFromTileRow, final int pToTileColumn, final int pToTileRow) { + if((pToTileColumn < 0) || (pToTileRow < 0) || (pToTileColumn >= this.mTiledMap.getTileColumns()) || (pToTileRow >= this.mTiledMap.getTileRows())) { + return true; + } else if((pFromTileColumn == pToTileColumn) && (pFromTileRow == pToTileRow)) { + return true; + } + + return this.mTiledMap.isTileBlocked(pEntity, pToTileColumn, pToTileRow); + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== + + private static class Node implements Comparable { + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + Node mParent; + int mDepth; + + final int mTileColumn; + final int mTileRow; + + float mCost; + float mExpectedRestCost; + + // =========================================================== + // Constructors + // =========================================================== + + public Node(final int pTileColumn, final int pTileRow) { + this.mTileColumn = pTileColumn; + this.mTileRow = pTileRow; + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + public int setParent(final Node parent) { + this.mDepth = parent.mDepth + 1; + this.mParent = parent; + + return this.mDepth; + } + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + public int compareTo(final Node pOther) { + final float totalCost = this.mExpectedRestCost + this.mCost; + final float totalCostOther = pOther.mExpectedRestCost + pOther.mCost; + + if (totalCost < totalCostOther) { + return -1; + } else if (totalCost > totalCostOther) { + return 1; + } else { + return 0; + } + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== + } } diff --git a/AndEngine/src/org/anddev/andengine/util/path/astar/EuclideanHeuristic.java b/AndEngine/src/org/anddev/andengine/util/path/astar/EuclideanHeuristic.java index 7239255a..e945d511 100644 --- a/AndEngine/src/org/anddev/andengine/util/path/astar/EuclideanHeuristic.java +++ b/AndEngine/src/org/anddev/andengine/util/path/astar/EuclideanHeuristic.java @@ -12,39 +12,39 @@ * @since 22:58:01 - 16.08.2010 */ public class EuclideanHeuristic implements IAStarHeuristic { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - @Override - public float getExpectedRestCost(final ITiledMap pTileMap, final T pEntity, final int pTileFromX, final int pTileFromY, final int pTileToX, final int pTileToY) { - final float dX = pTileToX - pTileFromX; - final float dY = pTileToY - pTileFromY; + @Override + public float getExpectedRestCost(final ITiledMap pTileMap, final T pEntity, final int pTileFromX, final int pTileFromY, final int pTileToX, final int pTileToY) { + final float dX = pTileToX - pTileFromX; + final float dY = pTileToY - pTileFromY; - return (float) Math.sqrt(dX * dX + dY * dY); - } + return (float) Math.sqrt(dX * dX + dY * dY); + } - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/util/path/astar/IAStarHeuristic.java b/AndEngine/src/org/anddev/andengine/util/path/astar/IAStarHeuristic.java index 7d34358c..0ffc1a26 100644 --- a/AndEngine/src/org/anddev/andengine/util/path/astar/IAStarHeuristic.java +++ b/AndEngine/src/org/anddev/andengine/util/path/astar/IAStarHeuristic.java @@ -10,13 +10,13 @@ * @since 22:59:20 - 16.08.2010 */ public interface IAStarHeuristic { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - public float getExpectedRestCost(final ITiledMap pTiledMap, final T pEntity, final int pFromTileColumn, final int pFromTileRow, final int pToTileColumn, final int pToTileRow); + public float getExpectedRestCost(final ITiledMap pTiledMap, final T pEntity, final int pFromTileColumn, final int pFromTileRow, final int pToTileColumn, final int pToTileRow); } diff --git a/AndEngine/src/org/anddev/andengine/util/path/astar/ManhattanHeuristic.java b/AndEngine/src/org/anddev/andengine/util/path/astar/ManhattanHeuristic.java index fc64f8a0..5e436431 100644 --- a/AndEngine/src/org/anddev/andengine/util/path/astar/ManhattanHeuristic.java +++ b/AndEngine/src/org/anddev/andengine/util/path/astar/ManhattanHeuristic.java @@ -10,36 +10,36 @@ * @since 22:58:01 - 16.08.2010 */ public class ManhattanHeuristic implements IAStarHeuristic { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - // =========================================================== - // Constructors - // =========================================================== - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - public float getExpectedRestCost(final ITiledMap pTiledMap, final T pEntity, final int pTileFromX, final int pTileFromY, final int pTileToX, final int pTileToY) { - return Math.abs(pTileFromX - pTileToX) + Math.abs(pTileFromY - pTileToY); - } - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + // =========================================================== + // Constructors + // =========================================================== + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + public float getExpectedRestCost(final ITiledMap pTiledMap, final T pEntity, final int pTileFromX, final int pTileFromY, final int pTileToX, final int pTileToY) { + return Math.abs(pTileFromX - pTileToX) + Math.abs(pTileFromY - pTileToY); + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/util/path/astar/NullHeuristic.java b/AndEngine/src/org/anddev/andengine/util/path/astar/NullHeuristic.java index fa6f3024..4870af7a 100644 --- a/AndEngine/src/org/anddev/andengine/util/path/astar/NullHeuristic.java +++ b/AndEngine/src/org/anddev/andengine/util/path/astar/NullHeuristic.java @@ -10,36 +10,36 @@ * @since 22:58:01 - 16.08.2010 */ public class NullHeuristic implements IAStarHeuristic { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - // =========================================================== - // Constructors - // =========================================================== - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - public float getExpectedRestCost(final ITiledMap pTiledMap, final T pEntity, final int pTileFromX, final int pTileFromY, final int pTileToX, final int pTileToY) { - return 0; - } - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + // =========================================================== + // Constructors + // =========================================================== + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + public float getExpectedRestCost(final ITiledMap pTiledMap, final T pEntity, final int pTileFromX, final int pTileFromY, final int pTileToX, final int pTileToY) { + return 0; + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/util/pool/EntityDetachRunnablePoolItem.java b/AndEngine/src/org/anddev/andengine/util/pool/EntityDetachRunnablePoolItem.java index e39d886b..faf82a36 100644 --- a/AndEngine/src/org/anddev/andengine/util/pool/EntityDetachRunnablePoolItem.java +++ b/AndEngine/src/org/anddev/andengine/util/pool/EntityDetachRunnablePoolItem.java @@ -10,42 +10,42 @@ * @since 00:53:22 - 28.08.2010 */ public class EntityDetachRunnablePoolItem extends RunnablePoolItem { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - protected IEntity mEntity; + protected IEntity mEntity; - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - public void setEntity(final IEntity pEntity) { - this.mEntity = pEntity; - } + public void setEntity(final IEntity pEntity) { + this.mEntity = pEntity; + } - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - @Override - public void run() { - this.mEntity.detachSelf(); - } + @Override + public void run() { + this.mEntity.detachSelf(); + } - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== -} \ No newline at end of file + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== +} diff --git a/AndEngine/src/org/anddev/andengine/util/pool/EntityDetachRunnablePoolUpdateHandler.java b/AndEngine/src/org/anddev/andengine/util/pool/EntityDetachRunnablePoolUpdateHandler.java index b7fc8e2e..12445bb8 100644 --- a/AndEngine/src/org/anddev/andengine/util/pool/EntityDetachRunnablePoolUpdateHandler.java +++ b/AndEngine/src/org/anddev/andengine/util/pool/EntityDetachRunnablePoolUpdateHandler.java @@ -8,36 +8,36 @@ * @since 23:16:25 - 31.08.2010 */ public class EntityDetachRunnablePoolUpdateHandler extends RunnablePoolUpdateHandler { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - // =========================================================== - // Constructors - // =========================================================== - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - protected EntityDetachRunnablePoolItem onAllocatePoolItem() { - return new EntityDetachRunnablePoolItem(); - } - - // =========================================================== - // Methods - // =========================================================== - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + // =========================================================== + // Constructors + // =========================================================== + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + protected EntityDetachRunnablePoolItem onAllocatePoolItem() { + return new EntityDetachRunnablePoolItem(); + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/util/pool/GenericPool.java b/AndEngine/src/org/anddev/andengine/util/pool/GenericPool.java index fead1932..bb14ea77 100644 --- a/AndEngine/src/org/anddev/andengine/util/pool/GenericPool.java +++ b/AndEngine/src/org/anddev/andengine/util/pool/GenericPool.java @@ -16,126 +16,126 @@ * @param */ public abstract class GenericPool { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - private final Stack mAvailableItems = new Stack(); - private int mUnrecycledCount; - private final int mGrowth; - - // =========================================================== - // Constructors - // =========================================================== - - public GenericPool() { - this(0); - } - - public GenericPool(final int pInitialSize) { - this(pInitialSize, 1); - } - - public GenericPool(final int pInitialSize, final int pGrowth) { - if(pGrowth < 0) { - throw new IllegalArgumentException("pGrowth must be at least 0!"); - } - - this.mGrowth = pGrowth; - - if(pInitialSize > 0) { - this.batchAllocatePoolItems(pInitialSize); - } - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - public synchronized int getUnrecycledCount() { - return this.mUnrecycledCount; - } - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - protected abstract T onAllocatePoolItem(); - - // =========================================================== - // Methods - // =========================================================== - - /** - * @param pItem every item passes this method just before it gets recycled. - */ - protected void onHandleRecycleItem(final T pItem) { - - } - - protected T onHandleAllocatePoolItem() { - return this.onAllocatePoolItem(); - } - - /** - * @param pItem every item that was just obtained from the pool, passes this method. - */ - protected void onHandleObtainItem(final T pItem) { - - } - - public synchronized void batchAllocatePoolItems(final int pCount) { - final Stack availableItems = this.mAvailableItems; - for(int i = pCount - 1; i >= 0; i--) { - availableItems.push(this.onHandleAllocatePoolItem()); - } - } - - public synchronized T obtainPoolItem() { - final T item; - - if(this.mAvailableItems.size() > 0) { - item = this.mAvailableItems.pop(); - } else { - if(this.mGrowth == 1) { - item = this.onHandleAllocatePoolItem(); - } else { - this.batchAllocatePoolItems(this.mGrowth); - item = this.mAvailableItems.pop(); - } - Debug.i(this.getClass().getName() + "<" + item.getClass().getSimpleName() +"> was exhausted, with " + this.mUnrecycledCount + " item not yet recycled. Allocated " + this.mGrowth + " more."); - } - this.onHandleObtainItem(item); - - this.mUnrecycledCount++; - return item; - } - - public synchronized void recyclePoolItem(final T pItem) { - if(pItem == null) { - throw new IllegalArgumentException("Cannot recycle null item!"); - } + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + private final Stack mAvailableItems = new Stack(); + private int mUnrecycledCount; + private final int mGrowth; + + // =========================================================== + // Constructors + // =========================================================== + + public GenericPool() { + this(0); + } + + public GenericPool(final int pInitialSize) { + this(pInitialSize, 1); + } + + public GenericPool(final int pInitialSize, final int pGrowth) { + if(pGrowth < 0) { + throw new IllegalArgumentException("pGrowth must be at least 0!"); + } + + this.mGrowth = pGrowth; + + if(pInitialSize > 0) { + this.batchAllocatePoolItems(pInitialSize); + } + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + public synchronized int getUnrecycledCount() { + return this.mUnrecycledCount; + } + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + protected abstract T onAllocatePoolItem(); + + // =========================================================== + // Methods + // =========================================================== + + /** + * @param pItem every item passes this method just before it gets recycled. + */ + protected void onHandleRecycleItem(final T pItem) { + + } + + protected T onHandleAllocatePoolItem() { + return this.onAllocatePoolItem(); + } + + /** + * @param pItem every item that was just obtained from the pool, passes this method. + */ + protected void onHandleObtainItem(final T pItem) { + + } + + public synchronized void batchAllocatePoolItems(final int pCount) { + final Stack availableItems = this.mAvailableItems; + for(int i = pCount - 1; i >= 0; i--) { + availableItems.push(this.onHandleAllocatePoolItem()); + } + } + + public synchronized T obtainPoolItem() { + final T item; + + if(this.mAvailableItems.size() > 0) { + item = this.mAvailableItems.pop(); + } else { + if(this.mGrowth == 1) { + item = this.onHandleAllocatePoolItem(); + } else { + this.batchAllocatePoolItems(this.mGrowth); + item = this.mAvailableItems.pop(); + } + Debug.i(this.getClass().getName() + "<" + item.getClass().getSimpleName() +"> was exhausted, with " + this.mUnrecycledCount + " item not yet recycled. Allocated " + this.mGrowth + " more."); + } + this.onHandleObtainItem(item); + + this.mUnrecycledCount++; + return item; + } + + public synchronized void recyclePoolItem(final T pItem) { + if(pItem == null) { + throw new IllegalArgumentException("Cannot recycle null item!"); + } - this.onHandleRecycleItem(pItem); - - this.mAvailableItems.push(pItem); + this.onHandleRecycleItem(pItem); + + this.mAvailableItems.push(pItem); - this.mUnrecycledCount--; - - if(this.mUnrecycledCount < 0) { - Debug.e("More items recycled than obtained!"); - } - } - - public synchronized void shufflePoolItems() { - Collections.shuffle(this.mAvailableItems); - } - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + this.mUnrecycledCount--; + + if(this.mUnrecycledCount < 0) { + Debug.e("More items recycled than obtained!"); + } + } + + public synchronized void shufflePoolItems() { + Collections.shuffle(this.mAvailableItems); + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/util/pool/MultiPool.java b/AndEngine/src/org/anddev/andengine/util/pool/MultiPool.java index 84323a80..85f72d2b 100644 --- a/AndEngine/src/org/anddev/andengine/util/pool/MultiPool.java +++ b/AndEngine/src/org/anddev/andengine/util/pool/MultiPool.java @@ -10,53 +10,53 @@ * @since 10:13:26 - 02.03.2011 */ public class MultiPool { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - private final SparseArray> mPools = new SparseArray>(); - - // =========================================================== - // Constructors - // =========================================================== - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - // =========================================================== - // Methods - // =========================================================== - - public void registerPool(final int pID, final GenericPool pPool) { - this.mPools.put(pID, pPool); - } - - public T obtainPoolItem(final int pID) { - final GenericPool pool = this.mPools.get(pID); - if(pool == null) { - return null; - } else { - return pool.obtainPoolItem(); - } - } - - public void recyclePoolItem(final int pID, final T pItem) { - final GenericPool pool = this.mPools.get(pID); - if(pool != null) { - pool.recyclePoolItem(pItem); - } - } - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + private final SparseArray> mPools = new SparseArray>(); + + // =========================================================== + // Constructors + // =========================================================== + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + public void registerPool(final int pID, final GenericPool pPool) { + this.mPools.put(pID, pPool); + } + + public T obtainPoolItem(final int pID) { + final GenericPool pool = this.mPools.get(pID); + if(pool == null) { + return null; + } else { + return pool.obtainPoolItem(); + } + } + + public void recyclePoolItem(final int pID, final T pItem) { + final GenericPool pool = this.mPools.get(pID); + if(pool != null) { + pool.recyclePoolItem(pItem); + } + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/util/pool/Pool.java b/AndEngine/src/org/anddev/andengine/util/pool/Pool.java index ed689efd..12ec742f 100644 --- a/AndEngine/src/org/anddev/andengine/util/pool/Pool.java +++ b/AndEngine/src/org/anddev/andengine/util/pool/Pool.java @@ -12,84 +12,84 @@ * @param */ public abstract class Pool extends GenericPool{ - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - // =========================================================== - // Constructors - // =========================================================== - - public Pool() { - super(); - } - - public Pool(final int pInitialSize) { - super(pInitialSize); - } - - public Pool(final int pInitialSize, final int pGrowth) { - super(pInitialSize, pGrowth); - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - protected T onHandleAllocatePoolItem() { - final T poolItem = super.onHandleAllocatePoolItem(); - poolItem.mParent = this; - return poolItem; - } - - @Override - protected void onHandleObtainItem(final T pPoolItem) { - pPoolItem.mRecycled = false; - pPoolItem.onObtain(); - } - - @Override - protected void onHandleRecycleItem(final T pPoolItem) { - pPoolItem.onRecycle(); - pPoolItem.mRecycled = true; - } - - @Override - public synchronized void recyclePoolItem(final T pPoolItem) { - if(pPoolItem.mParent == null) { - throw new IllegalArgumentException("PoolItem not assigned to a pool!"); - } else if(!pPoolItem.isFromPool(this)) { - throw new IllegalArgumentException("PoolItem from another pool!"); - } else if(pPoolItem.isRecycled()) { - throw new IllegalArgumentException("PoolItem already recycled!"); - } - - super.recyclePoolItem(pPoolItem); - } - - // =========================================================== - // Methods - // =========================================================== - - public synchronized boolean ownsPoolItem(final T pPoolItem) { - return pPoolItem.mParent == this; - } - - @SuppressWarnings("unchecked") - void recycle(final PoolItem pPoolItem) { - this.recyclePoolItem((T) pPoolItem); - } - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + // =========================================================== + // Constructors + // =========================================================== + + public Pool() { + super(); + } + + public Pool(final int pInitialSize) { + super(pInitialSize); + } + + public Pool(final int pInitialSize, final int pGrowth) { + super(pInitialSize, pGrowth); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + protected T onHandleAllocatePoolItem() { + final T poolItem = super.onHandleAllocatePoolItem(); + poolItem.mParent = this; + return poolItem; + } + + @Override + protected void onHandleObtainItem(final T pPoolItem) { + pPoolItem.mRecycled = false; + pPoolItem.onObtain(); + } + + @Override + protected void onHandleRecycleItem(final T pPoolItem) { + pPoolItem.onRecycle(); + pPoolItem.mRecycled = true; + } + + @Override + public synchronized void recyclePoolItem(final T pPoolItem) { + if(pPoolItem.mParent == null) { + throw new IllegalArgumentException("PoolItem not assigned to a pool!"); + } else if(!pPoolItem.isFromPool(this)) { + throw new IllegalArgumentException("PoolItem from another pool!"); + } else if(pPoolItem.isRecycled()) { + throw new IllegalArgumentException("PoolItem already recycled!"); + } + + super.recyclePoolItem(pPoolItem); + } + + // =========================================================== + // Methods + // =========================================================== + + public synchronized boolean ownsPoolItem(final T pPoolItem) { + return pPoolItem.mParent == this; + } + + @SuppressWarnings("unchecked") + void recycle(final PoolItem pPoolItem) { + this.recyclePoolItem((T) pPoolItem); + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/util/pool/PoolItem.java b/AndEngine/src/org/anddev/andengine/util/pool/PoolItem.java index 78ee38c5..c1fa3b17 100644 --- a/AndEngine/src/org/anddev/andengine/util/pool/PoolItem.java +++ b/AndEngine/src/org/anddev/andengine/util/pool/PoolItem.java @@ -10,62 +10,62 @@ * @since 23:02:47 - 21.08.2010 */ public abstract class PoolItem { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - Pool mParent; - boolean mRecycled = true; + Pool mParent; + boolean mRecycled = true; - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - public Pool getParent() { - return this.mParent; - } + public Pool getParent() { + return this.mParent; + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - public boolean isRecycled() { - return this.mRecycled; - } + public boolean isRecycled() { + return this.mRecycled; + } - public boolean isFromPool(final Pool pPool) { - return pPool == this.mParent; - } + public boolean isFromPool(final Pool pPool) { + return pPool == this.mParent; + } - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - protected void onRecycle() { + protected void onRecycle() { - } + } - protected void onObtain() { + protected void onObtain() { - } + } - public void recycle() { - if(this.mParent == null) { - throw new IllegalStateException("Item already recycled!"); - } + public void recycle() { + if(this.mParent == null) { + throw new IllegalStateException("Item already recycled!"); + } - this.mParent.recycle(this); - } + this.mParent.recycle(this); + } - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== -} \ No newline at end of file + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== +} diff --git a/AndEngine/src/org/anddev/andengine/util/pool/PoolUpdateHandler.java b/AndEngine/src/org/anddev/andengine/util/pool/PoolUpdateHandler.java index dd1008b6..512db92c 100644 --- a/AndEngine/src/org/anddev/andengine/util/pool/PoolUpdateHandler.java +++ b/AndEngine/src/org/anddev/andengine/util/pool/PoolUpdateHandler.java @@ -15,118 +15,118 @@ * @param */ public abstract class PoolUpdateHandler implements IUpdateHandler { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - private final Pool mPool; - private final ArrayList mScheduledPoolItems = new ArrayList(); - - // =========================================================== - // Constructors - // =========================================================== - - public PoolUpdateHandler() { - this.mPool = new Pool() { - @Override - protected T onAllocatePoolItem() { - return PoolUpdateHandler.this.onAllocatePoolItem(); - } - }; - } - - public PoolUpdateHandler(final int pInitialPoolSize) { - this.mPool = new Pool(pInitialPoolSize) { - @Override - protected T onAllocatePoolItem() { - return PoolUpdateHandler.this.onAllocatePoolItem(); - } - }; - } - - public PoolUpdateHandler(final int pInitialPoolSize, final int pGrowth) { - this.mPool = new Pool(pInitialPoolSize, pGrowth) { - @Override - protected T onAllocatePoolItem() { - return PoolUpdateHandler.this.onAllocatePoolItem(); - } - }; - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - protected abstract T onAllocatePoolItem(); - - protected abstract void onHandlePoolItem(final T pPoolItem); - - @Override - public void onUpdate(final float pSecondsElapsed) { - final ArrayList scheduledPoolItems = this.mScheduledPoolItems; - - synchronized (scheduledPoolItems) { - final int count = scheduledPoolItems.size(); - - if(count > 0) { - final Pool pool = this.mPool; - T item; - - for(int i = 0; i < count; i++) { - item = scheduledPoolItems.get(i); - this.onHandlePoolItem(item); - pool.recyclePoolItem(item); - } - - scheduledPoolItems.clear(); - } - } - } - - @Override - public void reset() { - final ArrayList scheduledPoolItems = this.mScheduledPoolItems; - synchronized (scheduledPoolItems) { - final int count = scheduledPoolItems.size(); - - final Pool pool = this.mPool; - for(int i = count - 1; i >= 0; i--) { - pool.recyclePoolItem(scheduledPoolItems.get(i)); - } - - scheduledPoolItems.clear(); - } - } - - // =========================================================== - // Methods - // =========================================================== - - public T obtainPoolItem() { - return this.mPool.obtainPoolItem(); - } - - public void postPoolItem(final T pPoolItem) { - synchronized (this.mScheduledPoolItems) { - if(pPoolItem == null) { - throw new IllegalArgumentException("PoolItem already recycled!"); - } else if(!this.mPool.ownsPoolItem(pPoolItem)) { - throw new IllegalArgumentException("PoolItem from another pool!"); - } - - this.mScheduledPoolItems.add(pPoolItem); - } - } - - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + private final Pool mPool; + private final ArrayList mScheduledPoolItems = new ArrayList(); + + // =========================================================== + // Constructors + // =========================================================== + + public PoolUpdateHandler() { + this.mPool = new Pool() { + @Override + protected T onAllocatePoolItem() { + return PoolUpdateHandler.this.onAllocatePoolItem(); + } + }; + } + + public PoolUpdateHandler(final int pInitialPoolSize) { + this.mPool = new Pool(pInitialPoolSize) { + @Override + protected T onAllocatePoolItem() { + return PoolUpdateHandler.this.onAllocatePoolItem(); + } + }; + } + + public PoolUpdateHandler(final int pInitialPoolSize, final int pGrowth) { + this.mPool = new Pool(pInitialPoolSize, pGrowth) { + @Override + protected T onAllocatePoolItem() { + return PoolUpdateHandler.this.onAllocatePoolItem(); + } + }; + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + protected abstract T onAllocatePoolItem(); + + protected abstract void onHandlePoolItem(final T pPoolItem); + + @Override + public void onUpdate(final float pSecondsElapsed) { + final ArrayList scheduledPoolItems = this.mScheduledPoolItems; + + synchronized (scheduledPoolItems) { + final int count = scheduledPoolItems.size(); + + if(count > 0) { + final Pool pool = this.mPool; + T item; + + for(int i = 0; i < count; i++) { + item = scheduledPoolItems.get(i); + this.onHandlePoolItem(item); + pool.recyclePoolItem(item); + } + + scheduledPoolItems.clear(); + } + } + } + + @Override + public void reset() { + final ArrayList scheduledPoolItems = this.mScheduledPoolItems; + synchronized (scheduledPoolItems) { + final int count = scheduledPoolItems.size(); + + final Pool pool = this.mPool; + for(int i = count - 1; i >= 0; i--) { + pool.recyclePoolItem(scheduledPoolItems.get(i)); + } + + scheduledPoolItems.clear(); + } + } + + // =========================================================== + // Methods + // =========================================================== + + public T obtainPoolItem() { + return this.mPool.obtainPoolItem(); + } + + public void postPoolItem(final T pPoolItem) { + synchronized (this.mScheduledPoolItems) { + if(pPoolItem == null) { + throw new IllegalArgumentException("PoolItem already recycled!"); + } else if(!this.mPool.ownsPoolItem(pPoolItem)) { + throw new IllegalArgumentException("PoolItem from another pool!"); + } + + this.mScheduledPoolItems.add(pPoolItem); + } + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/util/pool/RunnablePoolItem.java b/AndEngine/src/org/anddev/andengine/util/pool/RunnablePoolItem.java index 9893c217..22db236a 100644 --- a/AndEngine/src/org/anddev/andengine/util/pool/RunnablePoolItem.java +++ b/AndEngine/src/org/anddev/andengine/util/pool/RunnablePoolItem.java @@ -8,31 +8,31 @@ * @since 23:46:50 - 27.08.2010 */ public abstract class RunnablePoolItem extends PoolItem implements Runnable { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== -} \ No newline at end of file + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== +} diff --git a/AndEngine/src/org/anddev/andengine/util/pool/RunnablePoolUpdateHandler.java b/AndEngine/src/org/anddev/andengine/util/pool/RunnablePoolUpdateHandler.java index 17c8eb5e..a49f9f66 100644 --- a/AndEngine/src/org/anddev/andengine/util/pool/RunnablePoolUpdateHandler.java +++ b/AndEngine/src/org/anddev/andengine/util/pool/RunnablePoolUpdateHandler.java @@ -11,47 +11,47 @@ * @param */ public abstract class RunnablePoolUpdateHandler extends PoolUpdateHandler { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - public RunnablePoolUpdateHandler() { + public RunnablePoolUpdateHandler() { - } + } - public RunnablePoolUpdateHandler(final int pInitialPoolSize) { - super(pInitialPoolSize); - } + public RunnablePoolUpdateHandler(final int pInitialPoolSize) { + super(pInitialPoolSize); + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - @Override - protected abstract T onAllocatePoolItem(); + @Override + protected abstract T onAllocatePoolItem(); - @Override - protected void onHandlePoolItem(final T pRunnablePoolItem) { - pRunnablePoolItem.run(); - } + @Override + protected void onHandlePoolItem(final T pRunnablePoolItem) { + pRunnablePoolItem.run(); + } - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/AndEngine/src/org/anddev/andengine/util/progress/IProgressListener.java b/AndEngine/src/org/anddev/andengine/util/progress/IProgressListener.java index 42a61743..ded634e0 100644 --- a/AndEngine/src/org/anddev/andengine/util/progress/IProgressListener.java +++ b/AndEngine/src/org/anddev/andengine/util/progress/IProgressListener.java @@ -8,16 +8,16 @@ * @since 18:07:35 - 09.07.2009 */ public interface IProgressListener { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - /** - * @param pProgress between 0 and 100. - */ - public void onProgressChanged(final int pProgress); -} \ No newline at end of file + /** + * @param pProgress between 0 and 100. + */ + public void onProgressChanged(final int pProgress); +} diff --git a/AndEngine/src/org/anddev/andengine/util/progress/ProgressCallable.java b/AndEngine/src/org/anddev/andengine/util/progress/ProgressCallable.java index 2799df89..0be17bbb 100644 --- a/AndEngine/src/org/anddev/andengine/util/progress/ProgressCallable.java +++ b/AndEngine/src/org/anddev/andengine/util/progress/ProgressCallable.java @@ -9,19 +9,19 @@ * @since 20:52:44 - 03.01.2010 */ public interface ProgressCallable { - // =========================================================== - // Final Fields - // =========================================================== + // =========================================================== + // Final Fields + // =========================================================== - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - /** - * Computes a result, or throws an exception if unable to do so. - * @param pProgressListener - * @return computed result - * @throws Exception if unable to compute a result - */ - public T call(final IProgressListener pProgressListener) throws Exception; -} \ No newline at end of file + /** + * Computes a result, or throws an exception if unable to do so. + * @param pProgressListener + * @return computed result + * @throws Exception if unable to compute a result + */ + public T call(final IProgressListener pProgressListener) throws Exception; +} diff --git a/AndEngine/src/org/anddev/andengine/util/progress/ProgressMonitor.java b/AndEngine/src/org/anddev/andengine/util/progress/ProgressMonitor.java index d880bd3e..c7270a3d 100644 --- a/AndEngine/src/org/anddev/andengine/util/progress/ProgressMonitor.java +++ b/AndEngine/src/org/anddev/andengine/util/progress/ProgressMonitor.java @@ -8,78 +8,78 @@ * @since 18:07:35 - 09.07.2009 */ public class ProgressMonitor implements IProgressListener { - // =========================================================== - // Constants - // =========================================================== - - // =========================================================== - // Fields - // =========================================================== - - private final ProgressMonitor mParentProgressMonitor; - private final IProgressListener mListener; - - private int mSubMonitorRangeFrom = 0; - private int mSubMonitorRangeTo = 100; - - private int mProgress = 0; - - // =========================================================== - // Constructors - // =========================================================== - - public ProgressMonitor(final IProgressListener pListener) { - this.mListener = pListener; - this.mParentProgressMonitor = null; - } - - public ProgressMonitor(final ProgressMonitor pParent){ - this.mListener = null; - this.mParentProgressMonitor = pParent; - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - public ProgressMonitor getParentProgressMonitor() { - return this.mParentProgressMonitor; - } - - public int getProgress() { - return this.mProgress; - } - - public void setSubMonitorRange(final int pSubMonitorRangeFrom, final int pSubMonitorRangeTo) { - this.mSubMonitorRangeFrom = pSubMonitorRangeFrom; - this.mSubMonitorRangeTo = pSubMonitorRangeTo; - } - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - /** - * @param pProgress between 0 and 100. - */ - @Override - public void onProgressChanged(final int pProgress){ - this.mProgress = pProgress; - if(this.mParentProgressMonitor != null) { - this.mParentProgressMonitor.onSubProgressChanged(pProgress); - } else { - this.mListener.onProgressChanged(pProgress); - } - } - - private void onSubProgressChanged(final int pSubProgress){ - final int subRange = this.mSubMonitorRangeTo- this.mSubMonitorRangeFrom; - final int subProgressInRange = this.mSubMonitorRangeFrom + (int)(subRange * pSubProgress / 100f); - - if(this.mParentProgressMonitor != null) { - this.mParentProgressMonitor.onSubProgressChanged(subProgressInRange); - }else{ - this.mListener.onProgressChanged(subProgressInRange); - } - } + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + + private final ProgressMonitor mParentProgressMonitor; + private final IProgressListener mListener; + + private int mSubMonitorRangeFrom = 0; + private int mSubMonitorRangeTo = 100; + + private int mProgress = 0; + + // =========================================================== + // Constructors + // =========================================================== + + public ProgressMonitor(final IProgressListener pListener) { + this.mListener = pListener; + this.mParentProgressMonitor = null; + } + + public ProgressMonitor(final ProgressMonitor pParent){ + this.mListener = null; + this.mParentProgressMonitor = pParent; + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + public ProgressMonitor getParentProgressMonitor() { + return this.mParentProgressMonitor; + } + + public int getProgress() { + return this.mProgress; + } + + public void setSubMonitorRange(final int pSubMonitorRangeFrom, final int pSubMonitorRangeTo) { + this.mSubMonitorRangeFrom = pSubMonitorRangeFrom; + this.mSubMonitorRangeTo = pSubMonitorRangeTo; + } + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + /** + * @param pProgress between 0 and 100. + */ + @Override + public void onProgressChanged(final int pProgress){ + this.mProgress = pProgress; + if(this.mParentProgressMonitor != null) { + this.mParentProgressMonitor.onSubProgressChanged(pProgress); + } else { + this.mListener.onProgressChanged(pProgress); + } + } + + private void onSubProgressChanged(final int pSubProgress){ + final int subRange = this.mSubMonitorRangeTo- this.mSubMonitorRangeFrom; + final int subProgressInRange = this.mSubMonitorRangeFrom + (int)(subRange * pSubProgress / 100f); + + if(this.mParentProgressMonitor != null) { + this.mParentProgressMonitor.onSubProgressChanged(subProgressInRange); + }else{ + this.mListener.onProgressChanged(subProgressInRange); + } + } } diff --git a/AndEngine/src/org/anddev/andengine/util/sort/InsertionSorter.java b/AndEngine/src/org/anddev/andengine/util/sort/InsertionSorter.java index 765778fb..925ad5fd 100644 --- a/AndEngine/src/org/anddev/andengine/util/sort/InsertionSorter.java +++ b/AndEngine/src/org/anddev/andengine/util/sort/InsertionSorter.java @@ -12,63 +12,63 @@ * @param */ public class InsertionSorter extends Sorter { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - @Override - public void sort(final T[] pArray, final int pStart, final int pEnd, final Comparator pComparator) { - for(int i = pStart + 1; i < pEnd; i++) { - final T current = pArray[i]; - T prev = pArray[i - 1]; - if(pComparator.compare(current, prev) < 0) { - int j = i; - do { - pArray[j--] = prev; - } while(j > pStart && pComparator.compare(current, prev = pArray[j - 1]) < 0); - pArray[j] = current; - } - } - return; - } + @Override + public void sort(final T[] pArray, final int pStart, final int pEnd, final Comparator pComparator) { + for(int i = pStart + 1; i < pEnd; i++) { + final T current = pArray[i]; + T prev = pArray[i - 1]; + if(pComparator.compare(current, prev) < 0) { + int j = i; + do { + pArray[j--] = prev; + } while(j > pStart && pComparator.compare(current, prev = pArray[j - 1]) < 0); + pArray[j] = current; + } + } + return; + } - @Override - public void sort(final List pList, final int pStart, final int pEnd, final Comparator pComparator) { - 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) { - int j = i; - do { - pList.set(j--, prev); - } while(j > pStart && pComparator.compare(current, prev = pList.get(j - 1)) < 0); - pList.set(j, current); - } - } - return; - } + @Override + public void sort(final List pList, final int pStart, final int pEnd, final Comparator pComparator) { + 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) { + int j = i; + do { + pList.set(j--, prev); + } while(j > pStart && pComparator.compare(current, prev = pList.get(j - 1)) < 0); + pList.set(j, current); + } + } + return; + } - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== -} \ No newline at end of file + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== +} diff --git a/AndEngine/src/org/anddev/andengine/util/sort/Sorter.java b/AndEngine/src/org/anddev/andengine/util/sort/Sorter.java index b8cf5685..e47e7497 100644 --- a/AndEngine/src/org/anddev/andengine/util/sort/Sorter.java +++ b/AndEngine/src/org/anddev/andengine/util/sort/Sorter.java @@ -12,43 +12,43 @@ * @param */ public abstract class Sorter { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - public abstract void sort(final T[] pArray, final int pStart, final int pEnd, final Comparator pComparator); + public abstract void sort(final T[] pArray, final int pStart, final int pEnd, final Comparator pComparator); - public abstract void sort(final List pList, final int pStart, final int pEnd, final Comparator pComparator); + public abstract void sort(final List pList, final int pStart, final int pEnd, final Comparator pComparator); - // =========================================================== - // Methods - // =========================================================== + // =========================================================== + // Methods + // =========================================================== - public final void sort(final T[] pArray, final Comparator pComparator){ - this.sort(pArray, 0, pArray.length, 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){ - this.sort(pList, 0, pList.size(), pComparator); - } + public final void sort(final List pList, final Comparator pComparator){ + this.sort(pList, 0, pList.size(), pComparator); + } - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== } diff --git a/LibBASS/src/main/java/com/un4seen/bass/BASS.java b/LibBASS/src/main/java/com/un4seen/bass/BASS.java index cf631cb4..7728cd8e 100644 --- a/LibBASS/src/main/java/com/un4seen/bass/BASS.java +++ b/LibBASS/src/main/java/com/un4seen/bass/BASS.java @@ -1,8 +1,8 @@ /* - BASS 2.4 Java class - Copyright (c) 1999-2021 Un4seen Developments Ltd. + BASS 2.4 Java class + Copyright (c) 1999-2021 Un4seen Developments Ltd. - See the BASS.CHM file for more detailed documentation + See the BASS.CHM file for more detailed documentation */ package com.un4seen.bass; @@ -14,778 +14,778 @@ @SuppressWarnings({"all"}) public class BASS { - public static final int BASSVERSION = 0x204; // API version - public static final String BASSVERSIONTEXT = "2.4"; - - // Error codes returned by BASS_ErrorGetCode - public static final int BASS_OK = 0; // all is OK - public static final int BASS_ERROR_MEM = 1; // memory error - public static final int BASS_ERROR_FILEOPEN = 2; // can't open the file - public static final int BASS_ERROR_DRIVER = 3; // can't find a free/valid driver - public static final int BASS_ERROR_BUFLOST = 4; // the sample buffer was lost - public static final int BASS_ERROR_HANDLE = 5; // invalid handle - public static final int BASS_ERROR_FORMAT = 6; // unsupported sample format - public static final int BASS_ERROR_POSITION = 7; // invalid position - public static final int BASS_ERROR_INIT = 8; // BASS_Init has not been successfully called - public static final int BASS_ERROR_START = 9; // BASS_Start has not been successfully called - public static final int BASS_ERROR_SSL = 10; // SSL/HTTPS support isn't available - public static final int BASS_ERROR_REINIT = 11; // device needs to be reinitialized - public static final int BASS_ERROR_ALREADY = 14; // already initialized/paused/whatever - public static final int BASS_ERROR_NOTAUDIO = 17; // file does not contain audio - public static final int BASS_ERROR_NOCHAN = 18; // can't get a free channel - public static final int BASS_ERROR_ILLTYPE = 19; // an illegal type was specified - public static final int BASS_ERROR_ILLPARAM = 20; // an illegal parameter was specified - public static final int BASS_ERROR_NO3D = 21; // no 3D support - public static final int BASS_ERROR_NOEAX = 22; // no EAX support - public static final int BASS_ERROR_DEVICE = 23; // illegal device number - public static final int BASS_ERROR_NOPLAY = 24; // not playing - public static final int BASS_ERROR_FREQ = 25; // illegal sample rate - public static final int BASS_ERROR_NOTFILE = 27; // the stream is not a file stream - public static final int BASS_ERROR_NOHW = 29; // no hardware voices available - public static final int BASS_ERROR_EMPTY = 31; // the MOD music has no sequence data - public static final int BASS_ERROR_NONET = 32; // no internet connection could be opened - public static final int BASS_ERROR_CREATE = 33; // couldn't create the file - public static final int BASS_ERROR_NOFX = 34; // effects are not available - public static final int BASS_ERROR_NOTAVAIL = 37; // requested data/action is not available - public static final int BASS_ERROR_DECODE = 38; // the channel is a "decoding channel" - public static final int BASS_ERROR_DX = 39; // a sufficient DirectX version is not installed - public static final int BASS_ERROR_TIMEOUT = 40; // connection timedout - public static final int BASS_ERROR_FILEFORM = 41; // unsupported file format - public static final int BASS_ERROR_SPEAKER = 42; // unavailable speaker - public static final int BASS_ERROR_VERSION = 43; // invalid BASS version (used by add-ons) - public static final int BASS_ERROR_CODEC = 44; // codec is not available/supported - public static final int BASS_ERROR_ENDED = 45; // the channel/file has ended - public static final int BASS_ERROR_BUSY = 46; // the device is busy - public static final int BASS_ERROR_UNSTREAMABLE = 47; // unstreamable file - public static final int BASS_ERROR_PROTOCOL = 48; // unsupported protocol - public static final int BASS_ERROR_UNKNOWN = -1; // some other mystery problem - - public static final int BASS_ERROR_JAVA_CLASS = 500; // object class problem - - // BASS_SetConfig options - public static final int BASS_CONFIG_BUFFER = 0; - public static final int BASS_CONFIG_UPDATEPERIOD = 1; - public static final int BASS_CONFIG_GVOL_SAMPLE = 4; - public static final int BASS_CONFIG_GVOL_STREAM = 5; - public static final int BASS_CONFIG_GVOL_MUSIC = 6; - public static final int BASS_CONFIG_CURVE_VOL = 7; - public static final int BASS_CONFIG_CURVE_PAN = 8; - public static final int BASS_CONFIG_FLOATDSP = 9; - public static final int BASS_CONFIG_3DALGORITHM = 10; - public static final int BASS_CONFIG_NET_TIMEOUT = 11; - public static final int BASS_CONFIG_NET_BUFFER = 12; - public static final int BASS_CONFIG_PAUSE_NOPLAY = 13; - public static final int BASS_CONFIG_NET_PREBUF = 15; - public static final int BASS_CONFIG_NET_PASSIVE = 18; - public static final int BASS_CONFIG_REC_BUFFER = 19; - public static final int BASS_CONFIG_NET_PLAYLIST = 21; - public static final int BASS_CONFIG_MUSIC_VIRTUAL = 22; - public static final int BASS_CONFIG_VERIFY = 23; - public static final int BASS_CONFIG_UPDATETHREADS = 24; - public static final int BASS_CONFIG_DEV_BUFFER = 27; - public static final int BASS_CONFIG_DEV_DEFAULT = 36; - public static final int BASS_CONFIG_NET_READTIMEOUT = 37; - public static final int BASS_CONFIG_HANDLES = 41; - public static final int BASS_CONFIG_SRC = 43; - public static final int BASS_CONFIG_SRC_SAMPLE = 44; - public static final int BASS_CONFIG_ASYNCFILE_BUFFER = 45; - public static final int BASS_CONFIG_OGG_PRESCAN = 47; - public static final int BASS_CONFIG_DEV_NONSTOP = 50; - public static final int BASS_CONFIG_VERIFY_NET = 52; - public static final int BASS_CONFIG_DEV_PERIOD = 53; - public static final int BASS_CONFIG_FLOAT = 54; - public static final int BASS_CONFIG_NET_SEEK = 56; - public static final int BASS_CONFIG_AM_DISABLE = 58; - public static final int BASS_CONFIG_NET_PLAYLIST_DEPTH = 59; - public static final int BASS_CONFIG_NET_PREBUF_WAIT = 60; - public static final int BASS_CONFIG_ANDROID_SESSIONID = 62; - public static final int BASS_CONFIG_ANDROID_AAUDIO = 67; - public static final int BASS_CONFIG_SAMPLE_ONEHANDLE = 69; - public static final int BASS_CONFIG_DEV_TIMEOUT = 70; - public static final int BASS_CONFIG_NET_META = 71; - public static final int BASS_CONFIG_NET_RESTRATE = 72; - - // BASS_SetConfigPtr options - public static final int BASS_CONFIG_NET_AGENT = 16; - public static final int BASS_CONFIG_NET_PROXY = 17; - public static final int BASS_CONFIG_LIBSSL = 64; - - public static final int BASS_CONFIG_THREAD = 0x40000000; // flag: thread-specific setting - - // BASS_Init flags - public static final int BASS_DEVICE_8BITS = 1; // unused - public static final int BASS_DEVICE_MONO = 2; // mono - public static final int BASS_DEVICE_3D = 4; // unused - public static final int BASS_DEVICE_16BITS = 8; // limit output to 16-bit - public static final int BASS_DEVICE_REINIT = 128; // reinitialize - public static final int BASS_DEVICE_LATENCY = 0x100; // unused - public static final int BASS_DEVICE_SPEAKERS = 0x800; // force enabling of speaker assignment - public static final int BASS_DEVICE_NOSPEAKER = 0x1000; // ignore speaker arrangement - public static final int BASS_DEVICE_FREQ = 0x4000; // set device sample rate - public static final int BASS_DEVICE_AUDIOTRACK = 0x20000; // use AudioTrack output - public static final int BASS_DEVICE_SOFTWARE = 0x80000; // disable hardware/fastpath output - - // Device info structure - public static class BASS_DEVICEINFO { - public String name; // description - public String driver; // driver - public int flags; - } - - // BASS_DEVICEINFO flags - public static final int BASS_DEVICE_ENABLED = 1; - public static final int BASS_DEVICE_DEFAULT = 2; - public static final int BASS_DEVICE_INIT = 4; - - public static class BASS_INFO { - public int flags; // device capabilities (DSCAPS_xxx flags) - public int hwsize; // unused - public int hwfree; // unused - public int freesam; // unused - public int free3d; // unused - public int minrate; // unused - public int maxrate; // unused - public int eax; // unused - public int minbuf; // recommended minimum buffer length in ms - public int dsver; // DirectSound version - public int latency; // average delay (in ms) before start of playback - public int initflags; // BASS_Init "flags" parameter - public int speakers; // number of speakers available - public int freq; // current output rate - } - - // Recording device info structure - public static class BASS_RECORDINFO { - public int flags; // device capabilities (DSCCAPS_xxx flags) - public int formats; // supported standard formats (WAVE_FORMAT_xxx flags) - public int inputs; // number of inputs - public boolean singlein; // TRUE = only 1 input can be set at a time - public int freq; // current input rate - } - - // Sample info structure - public static class BASS_SAMPLE { - public int freq; // default playback rate - public float volume; // default volume (0-1) - public float pan; // default pan (-1=left, 0=middle, 1=right) - public int flags; // BASS_SAMPLE_xxx flags - public int length; // length (in bytes) - public int max; // maximum simultaneous playbacks - public int origres; // original resolution bits - public int chans; // number of channels - public int mingap; // minimum gap (ms) between creating channels - public int mode3d; // BASS_3DMODE_xxx mode - public float mindist; // minimum distance - public float maxdist; // maximum distance - public int iangle; // angle of inside projection cone - public int oangle; // angle of outside projection cone - public float outvol; // delta-volume outside the projection cone - public int vam; // unused - public int priority; // unused - } - - public static final int BASS_SAMPLE_8BITS = 1; // 8 bit - public static final int BASS_SAMPLE_FLOAT = 256; // 32-bit floating-point - public static final int BASS_SAMPLE_MONO = 2; // mono - public static final int BASS_SAMPLE_LOOP = 4; // looped - public static final int BASS_SAMPLE_3D = 8; // 3D functionality - public static final int BASS_SAMPLE_SOFTWARE = 16; // unused - public static final int BASS_SAMPLE_MUTEMAX = 32; // mute at max distance (3D only) - public static final int BASS_SAMPLE_VAM = 64; // unused - public static final int BASS_SAMPLE_FX = 128; // unused - public static final int BASS_SAMPLE_OVER_VOL = 0x10000; // override lowest volume - public static final int BASS_SAMPLE_OVER_POS = 0x20000; // override longest playing - public static final int BASS_SAMPLE_OVER_DIST = 0x30000; // override furthest from listener (3D only) - - public static final int BASS_STREAM_PRESCAN = 0x20000; // scan file for accurate seeking and length - public static final int BASS_STREAM_AUTOFREE = 0x40000; // automatically free the stream when it stops/ends - public static final int BASS_STREAM_RESTRATE = 0x80000; // restrict the download rate of internet file streams - public static final int BASS_STREAM_BLOCK = 0x100000; // download/play internet file stream in small blocks - public static final int BASS_STREAM_DECODE = 0x200000; // don't play the stream, only decode (BASS_ChannelGetData) - public static final int BASS_STREAM_STATUS = 0x800000; // give server status info (HTTP/ICY tags) in DOWNLOADPROC - - public static final int BASS_MP3_IGNOREDELAY = 0x200; // ignore LAME/Xing/VBRI/iTunes delay & padding info - public static final int BASS_MP3_SETPOS = BASS_STREAM_PRESCAN; - - public static final int BASS_MUSIC_FLOAT = BASS_SAMPLE_FLOAT; - public static final int BASS_MUSIC_MONO = BASS_SAMPLE_MONO; - public static final int BASS_MUSIC_LOOP = BASS_SAMPLE_LOOP; - public static final int BASS_MUSIC_3D = BASS_SAMPLE_3D; - public static final int BASS_MUSIC_FX = BASS_SAMPLE_FX; - public static final int BASS_MUSIC_AUTOFREE = BASS_STREAM_AUTOFREE; - public static final int BASS_MUSIC_DECODE = BASS_STREAM_DECODE; - public static final int BASS_MUSIC_PRESCAN = BASS_STREAM_PRESCAN; // calculate playback length - public static final int BASS_MUSIC_CALCLEN = BASS_MUSIC_PRESCAN; - public static final int BASS_MUSIC_RAMP = 0x200; // normal ramping - public static final int BASS_MUSIC_RAMPS = 0x400; // sensitive ramping - public static final int BASS_MUSIC_SURROUND = 0x800; // surround sound - public static final int BASS_MUSIC_SURROUND2 = 0x1000; // surround sound (mode 2) - public static final int BASS_MUSIC_FT2PAN = 0x2000; // apply FastTracker 2 panning to XM files - public static final int BASS_MUSIC_FT2MOD = 0x2000; // play .MOD as FastTracker 2 does - public static final int BASS_MUSIC_PT1MOD = 0x4000; // play .MOD as ProTracker 1 does - public static final int BASS_MUSIC_NONINTER = 0x10000; // non-interpolated sample mixing - public static final int BASS_MUSIC_SINCINTER = 0x800000; // sinc interpolated sample mixing - public static final int BASS_MUSIC_POSRESET = 0x8000; // stop all notes when moving position - public static final int BASS_MUSIC_POSRESETEX = 0x400000; // stop all notes and reset bmp/etc when moving position - public static final int BASS_MUSIC_STOPBACK = 0x80000; // stop the music on a backwards jump effect - public static final int BASS_MUSIC_NOSAMPLE = 0x100000; // don't load the samples - - // Speaker assignment flags - public static final int BASS_SPEAKER_FRONT = 0x1000000; // front speakers - public static final int BASS_SPEAKER_REAR = 0x2000000; // rear/side speakers - public static final int BASS_SPEAKER_CENLFE = 0x3000000; // center & LFE speakers (5.1) - public static final int BASS_SPEAKER_REAR2 = 0x4000000; // rear center speakers (7.1) - public static int BASS_SPEAKER_N(int n) { return n<<24; } // n'th pair of speakers (max 15) - public static final int BASS_SPEAKER_LEFT = 0x10000000; // modifier: left - public static final int BASS_SPEAKER_RIGHT = 0x20000000; // modifier: right - public static final int BASS_SPEAKER_FRONTLEFT = BASS_SPEAKER_FRONT|BASS_SPEAKER_LEFT; - public static final int BASS_SPEAKER_FRONTRIGHT = BASS_SPEAKER_FRONT|BASS_SPEAKER_RIGHT; - public static final int BASS_SPEAKER_REARLEFT = BASS_SPEAKER_REAR|BASS_SPEAKER_LEFT; - public static final int BASS_SPEAKER_REARRIGHT = BASS_SPEAKER_REAR|BASS_SPEAKER_RIGHT; - public static final int BASS_SPEAKER_CENTER = BASS_SPEAKER_CENLFE|BASS_SPEAKER_LEFT; - public static final int BASS_SPEAKER_LFE = BASS_SPEAKER_CENLFE|BASS_SPEAKER_RIGHT; - public static final int BASS_SPEAKER_REAR2LEFT = BASS_SPEAKER_REAR2|BASS_SPEAKER_LEFT; - public static final int BASS_SPEAKER_REAR2RIGHT = BASS_SPEAKER_REAR2|BASS_SPEAKER_RIGHT; - - public static final int BASS_ASYNCFILE = 0x40000000; // read file asynchronously - - public static final int BASS_RECORD_PAUSE = 0x8000; // start recording paused - - // Channel info structure - public static class BASS_CHANNELINFO { - public int freq; // default playback rate - public int chans; // channels - public int flags; - public int ctype; // type of channel - public int origres; // original resolution - public int plugin; - public int sample; - public String filename; - } - - public static final int BASS_ORIGRES_FLOAT = 0x10000; - - // BASS_CHANNELINFO types - public static final int BASS_CTYPE_SAMPLE = 1; - public static final int BASS_CTYPE_RECORD = 2; - public static final int BASS_CTYPE_STREAM = 0x10000; - public static final int BASS_CTYPE_STREAM_VORBIS = 0x10002; - public static final int BASS_CTYPE_STREAM_OGG = 0x10002; - public static final int BASS_CTYPE_STREAM_MP1 = 0x10003; - public static final int BASS_CTYPE_STREAM_MP2 = 0x10004; - public static final int BASS_CTYPE_STREAM_MP3 = 0x10005; - public static final int BASS_CTYPE_STREAM_AIFF = 0x10006; - public static final int BASS_CTYPE_STREAM_CA = 0x10007; - public static final int BASS_CTYPE_STREAM_MF = 0x10008; - public static final int BASS_CTYPE_STREAM_AM = 0x10009; - public static final int BASS_CTYPE_STREAM_SAMPLE = 0x1000a; - public static final int BASS_CTYPE_STREAM_DUMMY = 0x18000; - public static final int BASS_CTYPE_STREAM_DEVICE = 0x18001; - public static final int BASS_CTYPE_STREAM_WAV = 0x40000; // WAVE flag (LOWORD=codec) - public static final int BASS_CTYPE_STREAM_WAV_PCM = 0x50001; - public static final int BASS_CTYPE_STREAM_WAV_FLOAT = 0x50003; - public static final int BASS_CTYPE_MUSIC_MOD = 0x20000; - public static final int BASS_CTYPE_MUSIC_MTM = 0x20001; - public static final int BASS_CTYPE_MUSIC_S3M = 0x20002; - public static final int BASS_CTYPE_MUSIC_XM = 0x20003; - public static final int BASS_CTYPE_MUSIC_IT = 0x20004; - public static final int BASS_CTYPE_MUSIC_MO3 = 0x00100; // MO3 flag - - public static class BASS_PLUGINFORM { - public int ctype; // channel type - public String name; // format description - public String exts; // file extension filter (*.ext1;*.ext2;etc...) - } - - public static class BASS_PLUGININFO { - public int version; // version (same form as BASS_GetVersion) - public int formatc; // number of formats - public BASS_PLUGINFORM[] formats; // the array of formats - } - - // 3D vector (for 3D positions/velocities/orientations) - public static class BASS_3DVECTOR { - public BASS_3DVECTOR() {} - public BASS_3DVECTOR(float _x, float _y, float _z) { x=_x; y=_y; z=_z; } - public float x; // +=right, -=left - public float y; // +=up, -=down - public float z; // +=front, -=behind - } - - // 3D channel modes - public static final int BASS_3DMODE_NORMAL = 0; // normal 3D processing - public static final int BASS_3DMODE_RELATIVE = 1; // position is relative to the listener - public static final int BASS_3DMODE_OFF = 2; // no 3D processing - - // software 3D mixing algorithms (used with BASS_CONFIG_3DALGORITHM) - public static final int BASS_3DALG_DEFAULT = 0; - public static final int BASS_3DALG_OFF = 1; - public static final int BASS_3DALG_FULL = 2; - public static final int BASS_3DALG_LIGHT = 3; - - // BASS_SampleGetChannel flags - public static final int BASS_SAMCHAN_NEW = 1; // get a new playback channel - public static final int BASS_SAMCHAN_STREAM = 2; // create a stream - - public interface STREAMPROC - { - int STREAMPROC(int handle, ByteBuffer buffer, int length, Object user); - /* User stream callback function. - handle : The stream that needs writing - buffer : Buffer to write the samples in - length : Number of bytes to write - user : The 'user' parameter value given when calling BASS_StreamCreate - RETURN : Number of bytes written. Set the BASS_STREAMPROC_END flag to end - the stream. */ - } - - public static final int BASS_STREAMPROC_END = 0x80000000; // end of user stream flag - - // Special STREAMPROCs - public static final int STREAMPROC_DUMMY = 0; // "dummy" stream - public static final int STREAMPROC_PUSH = -1; // push stream - public static final int STREAMPROC_DEVICE = -2; // device mix stream - public static final int STREAMPROC_DEVICE_3D = -3; // device 3D mix stream - - // BASS_StreamCreateFileUser file systems - public static final int STREAMFILE_NOBUFFER = 0; - public static final int STREAMFILE_BUFFER = 1; - public static final int STREAMFILE_BUFFERPUSH = 2; - - public interface BASS_FILEPROCS - { - // User file stream callback functions - void FILECLOSEPROC(Object user); - long FILELENPROC(Object user); - int FILEREADPROC(ByteBuffer buffer, int length, Object user); - boolean FILESEEKPROC(long offset, Object user); - } - - // BASS_StreamPutFileData options - public static final int BASS_FILEDATA_END = 0; // end & close the file - - // BASS_StreamGetFilePosition modes - public static final int BASS_FILEPOS_CURRENT = 0; - public static final int BASS_FILEPOS_DECODE = BASS_FILEPOS_CURRENT; - public static final int BASS_FILEPOS_DOWNLOAD = 1; - public static final int BASS_FILEPOS_END = 2; - public static final int BASS_FILEPOS_START = 3; - public static final int BASS_FILEPOS_CONNECTED = 4; - public static final int BASS_FILEPOS_BUFFER = 5; - public static final int BASS_FILEPOS_SOCKET = 6; - public static final int BASS_FILEPOS_ASYNCBUF = 7; - public static final int BASS_FILEPOS_SIZE = 8; - public static final int BASS_FILEPOS_BUFFERING = 9; - public static final int BASS_FILEPOS_AVAILABLE = 10; - - public interface DOWNLOADPROC - { - void DOWNLOADPROC(ByteBuffer buffer, int length, Object user); - /* Internet stream download callback function. - buffer : Buffer containing the downloaded data... NULL=end of download - length : Number of bytes in the buffer - user : The 'user' parameter value given when calling BASS_StreamCreateURL */ - } - - // BASS_ChannelSetSync types - public static final int BASS_SYNC_POS = 0; - public static final int BASS_SYNC_END = 2; - public static final int BASS_SYNC_META = 4; - public static final int BASS_SYNC_SLIDE = 5; - public static final int BASS_SYNC_STALL = 6; - public static final int BASS_SYNC_DOWNLOAD = 7; - public static final int BASS_SYNC_FREE = 8; - public static final int BASS_SYNC_SETPOS = 11; - public static final int BASS_SYNC_MUSICPOS = 10; - public static final int BASS_SYNC_MUSICINST = 1; - public static final int BASS_SYNC_MUSICFX = 3; - public static final int BASS_SYNC_OGG_CHANGE = 12; - public static final int BASS_SYNC_DEV_FAIL = 14; - public static final int BASS_SYNC_DEV_FORMAT = 15; - public static final int BASS_SYNC_THREAD = 0x20000000; // flag: call sync in other thread - public static final int BASS_SYNC_MIXTIME = 0x40000000; // flag: sync at mixtime, else at playtime - public static final int BASS_SYNC_ONETIME = 0x80000000; // flag: sync only once, else continuously - - public interface SYNCPROC - { - void SYNCPROC(int handle, int channel, int data, Object user); - /* Sync callback function. - handle : The sync that has occured - channel: Channel that the sync occured in - data : Additional data associated with the sync's occurance - user : The 'user' parameter given when calling BASS_ChannelSetSync */ - } - - public interface DSPPROC - { - void DSPPROC(int handle, int channel, ByteBuffer buffer, int length, Object user); - /* DSP callback function. - handle : The DSP handle - channel: Channel that the DSP is being applied to - buffer : Buffer to apply the DSP to - length : Number of bytes in the buffer - user : The 'user' parameter given when calling BASS_ChannelSetDSP */ - } - - public interface RECORDPROC - { - boolean RECORDPROC(int handle, ByteBuffer buffer, int length, Object user); - /* Recording callback function. - handle : The recording handle - buffer : Buffer containing the recorded sample data - length : Number of bytes - user : The 'user' parameter value given when calling BASS_RecordStart - RETURN : true = continue recording, false = stop */ - } - - // BASS_ChannelIsActive return values - public static final int BASS_ACTIVE_STOPPED = 0; - public static final int BASS_ACTIVE_PLAYING =1; - public static final int BASS_ACTIVE_STALLED = 2; - public static final int BASS_ACTIVE_PAUSED = 3; - public static final int BASS_ACTIVE_PAUSED_DEVICE = 4; - - // Channel attributes - public static final int BASS_ATTRIB_FREQ = 1; - public static final int BASS_ATTRIB_VOL = 2; - public static final int BASS_ATTRIB_PAN = 3; - public static final int BASS_ATTRIB_EAXMIX = 4; - public static final int BASS_ATTRIB_NOBUFFER = 5; - public static final int BASS_ATTRIB_VBR = 6; - public static final int BASS_ATTRIB_CPU = 7; - public static final int BASS_ATTRIB_SRC = 8; - public static final int BASS_ATTRIB_NET_RESUME = 9; - public static final int BASS_ATTRIB_SCANINFO = 10; - public static final int BASS_ATTRIB_NORAMP = 11; - public static final int BASS_ATTRIB_BITRATE = 12; - public static final int BASS_ATTRIB_BUFFER = 13; - public static final int BASS_ATTRIB_GRANULE = 14; - public static final int BASS_ATTRIB_USER = 15; - public static final int BASS_ATTRIB_TAIL = 16; - public static final int BASS_ATTRIB_PUSH_LIMIT = 17; - public static final int BASS_ATTRIB_MUSIC_AMPLIFY = 0x100; - public static final int BASS_ATTRIB_MUSIC_PANSEP = 0x101; - public static final int BASS_ATTRIB_MUSIC_PSCALER = 0x102; - public static final int BASS_ATTRIB_MUSIC_BPM = 0x103; - public static final int BASS_ATTRIB_MUSIC_SPEED = 0x104; - public static final int BASS_ATTRIB_MUSIC_VOL_GLOBAL = 0x105; - public static final int BASS_ATTRIB_MUSIC_VOL_CHAN = 0x200; // + channel # - public static final int BASS_ATTRIB_MUSIC_VOL_INST = 0x300; // + instrument # - - // BASS_ChannelSlideAttribute flags - public static final int BASS_SLIDE_LOG = 0x1000000; - - // BASS_ChannelGetData flags - public static final int BASS_DATA_AVAILABLE = 0; // query how much data is buffered - public static final int BASS_DATA_NOREMOVE = 0x10000000; // flag: don't remove data from recording buffer - public static final int BASS_DATA_FIXED = 0x20000000; // flag: return 8.24 fixed-point data - public static final int BASS_DATA_FLOAT = 0x40000000; // flag: return floating-point sample data - public static final int BASS_DATA_FFT256 = 0x80000000; // 256 sample FFT - public static final int BASS_DATA_FFT512 = 0x80000001; // 512 FFT - public static final int BASS_DATA_FFT1024 = 0x80000002; // 1024 FFT - public static final int BASS_DATA_FFT2048 = 0x80000003; // 2048 FFT - public static final int BASS_DATA_FFT4096 = 0x80000004; // 4096 FFT - public static final int BASS_DATA_FFT8192 = 0x80000005; // 8192 FFT - public static final int BASS_DATA_FFT16384 = 0x80000006; // 16384 FFT - public static final int BASS_DATA_FFT32768 = 0x80000007; // 32768 FFT - public static final int BASS_DATA_FFT_INDIVIDUAL = 0x10; // FFT flag: FFT for each channel, else all combined - public static final int BASS_DATA_FFT_NOWINDOW = 0x20; // FFT flag: no Hanning window - public static final int BASS_DATA_FFT_REMOVEDC = 0x40; // FFT flag: pre-remove DC bias - public static final int BASS_DATA_FFT_COMPLEX = 0x80; // FFT flag: return complex data - public static final int BASS_DATA_FFT_NYQUIST = 0x100; // FFT flag: return extra Nyquist value - - // BASS_ChannelGetLevelEx flags - public static final int BASS_LEVEL_MONO = 1; // get mono level - public static final int BASS_LEVEL_STEREO = 2; // get stereo level - public static final int BASS_LEVEL_RMS = 4; // get RMS levels - public static final int BASS_LEVEL_VOLPAN = 8; // apply VOL/PAN attributes to the levels - public static final int BASS_LEVEL_NOREMOVE = 16; // don't remove data from recording buffer - - // BASS_ChannelGetTags types : what's returned - public static final int BASS_TAG_ID3 = 0; // ID3v1 tags : TAG_ID3 - public static final int BASS_TAG_ID3V2 = 1; // ID3v2 tags : ByteBuffer - public static final int BASS_TAG_OGG = 2; // OGG comments : String array - public static final int BASS_TAG_HTTP = 3; // HTTP headers : String array - public static final int BASS_TAG_ICY = 4; // ICY headers : String array - public static final int BASS_TAG_META = 5; // ICY metadata : String - public static final int BASS_TAG_APE = 6; // APE tags : String array - public static final int BASS_TAG_MP4 = 7; // MP4/iTunes metadata : String array - public static final int BASS_TAG_VENDOR = 9; // OGG encoder : String - public static final int BASS_TAG_LYRICS3 = 10; // Lyric3v2 tag : String - public static final int BASS_TAG_WAVEFORMAT = 14; // WAVE format : ByteBuffer containing WAVEFORMATEEX structure - public static final int BASS_TAG_AM_NAME = 16; // Android Media codec name : String - public static final int BASS_TAG_ID3V2_2 = 17; // ID3v2 tags (2nd block) : ByteBuffer - public static final int BASS_TAG_AM_MIME = 18; // Android Media MIME type : String - public static final int BASS_TAG_LOCATION = 19; // redirected URL : String - public static final int BASS_TAG_RIFF_INFO = 0x100; // RIFF "INFO" tags : String array - public static final int BASS_TAG_RIFF_BEXT = 0x101; // RIFF/BWF "bext" tags : TAG_BEXT - public static final int BASS_TAG_RIFF_CART = 0x102; // RIFF/BWF "cart" tags : TAG_CART - public static final int BASS_TAG_RIFF_DISP = 0x103; // RIFF "DISP" text tag : String - public static final int BASS_TAG_RIFF_CUE = 0x104; // RIFF "cue " chunk : TAG_CUE structure - public static final int BASS_TAG_RIFF_SMPL = 0x105; // RIFF "smpl" chunk : TAG_SMPL structure - public static final int BASS_TAG_APE_BINARY = 0x1000; // + index #, binary APE tag : TAG_APE_BINARY - public static final int BASS_TAG_MUSIC_NAME = 0x10000; // MOD music name : String - public static final int BASS_TAG_MUSIC_MESSAGE = 0x10001; // MOD message : String - public static final int BASS_TAG_MUSIC_ORDERS = 0x10002; // MOD order list : ByteBuffer - public static final int BASS_TAG_MUSIC_AUTH = 0x10003; // MOD author : UTF-8 string - public static final int BASS_TAG_MUSIC_INST = 0x10100; // + instrument #, MOD instrument name : String - public static final int BASS_TAG_MUSIC_CHAN = 0x10200; // + channel #, MOD channel name : String - public static final int BASS_TAG_MUSIC_SAMPLE = 0x10300; // + sample #, MOD sample name : String - public static final int BASS_TAG_BYTEBUFFER = 0x10000000; // flag: return a ByteBuffer instead of a String or TAG_ID3 - - // ID3v1 tag structure - public static class TAG_ID3 { - public String id; - public String title; - public String artist; - public String album; - public String year; - public String comment; - public byte genre; - public byte track; - } - - // Binary APE tag structure - public static class TAG_APE_BINARY { - public String key; - public ByteBuffer data; - public int length; - } - - // BASS_ChannelGetLength/GetPosition/SetPosition modes - public static final int BASS_POS_BYTE = 0; // byte position - public static final int BASS_POS_MUSIC_ORDER = 1; // order.row position, MAKELONG(order,row) - public static final int BASS_POS_OGG = 3; // OGG bitstream number - public static final int BASS_POS_END = 0x10; // trimmed end position - public static final int BASS_POS_LOOP = 0x11; // loop start positiom - public static final int BASS_POS_FLUSH = 0x1000000; // flag: flush decoder/FX buffers - public static final int BASS_POS_RESET = 0x2000000; // flag: reset user file buffers - public static final int BASS_POS_RELATIVE = 0x4000000; // flag: seek relative to the current position - public static final int BASS_POS_INEXACT = 0x8000000; // flag: allow seeking to inexact position - public static final int BASS_POS_DECODE = 0x10000000; // flag: get the decoding (not playing) position - public static final int BASS_POS_DECODETO = 0x20000000; // flag: decode to the position instead of seeking - public static final int BASS_POS_SCAN = 0x40000000; // flag: scan to the position - - // BASS_ChannelSetDevice/GetDevice option - public static final int BASS_NODEVICE = 0x20000; - - // DX8 effect types, use with BASS_ChannelSetFX - public static final int BASS_FX_DX8_CHORUS = 0; - public static final int BASS_FX_DX8_COMPRESSOR = 1; - public static final int BASS_FX_DX8_DISTORTION = 2; - public static final int BASS_FX_DX8_ECHO = 3; - public static final int BASS_FX_DX8_FLANGER = 4; - public static final int BASS_FX_DX8_GARGLE = 5; - public static final int BASS_FX_DX8_I3DL2REVERB = 6; - public static final int BASS_FX_DX8_PARAMEQ = 7; - public static final int BASS_FX_DX8_REVERB = 8; - public static final int BASS_FX_VOLUME = 9; - - public static class BASS_DX8_CHORUS { - public float fWetDryMix; - public float fDepth; - public float fFeedback; - public float fFrequency; - public int lWaveform; // 0=triangle, 1=sine - public float fDelay; - public int lPhase; // BASS_DX8_PHASE_xxx - } - - public static class BASS_DX8_DISTORTION { - public float fGain; - public float fEdge; - public float fPostEQCenterFrequency; - public float fPostEQBandwidth; - public float fPreLowpassCutoff; - } - - public static class BASS_DX8_ECHO { - public float fWetDryMix; - public float fFeedback; - public float fLeftDelay; - public float fRightDelay; - public boolean lPanDelay; - } - - public static class BASS_DX8_FLANGER { - public float fWetDryMix; - public float fDepth; - public float fFeedback; - public float fFrequency; - public int lWaveform; // 0=triangle, 1=sine - public float fDelay; - public int lPhase; // BASS_DX8_PHASE_xxx - } - - public static class BASS_DX8_PARAMEQ { - public float fCenter; - public float fBandwidth; - public float fGain; - } - - public static class BASS_DX8_REVERB { - public float fInGain; - public float fReverbMix; - public float fReverbTime; - public float fHighFreqRTRatio; - } - - public static final int BASS_DX8_PHASE_NEG_180 = 0; - public static final int BASS_DX8_PHASE_NEG_90 = 1; - public static final int BASS_DX8_PHASE_ZERO = 2; - public static final int BASS_DX8_PHASE_90 = 3; - public static final int BASS_DX8_PHASE_180 = 4; - - public static class BASS_FX_VOLUME_PARAM { - public float fTarget; - public float fCurrent; - public float fTime; - public int lCurve; - } - - public static class Asset { - public Asset() {} - public Asset(AssetManager m, String f) { manager=m; file=f; } - public AssetManager manager; - public String file; - } - - public static class FloatValue { - public float value; - } - - public static native boolean BASS_SetConfig(int option, int value); - public static native int BASS_GetConfig(int option); - public static native boolean BASS_SetConfigPtr(int option, Object value); - public static native Object BASS_GetConfigPtr(int option); - public static native int BASS_GetVersion(); - public static native int BASS_ErrorGetCode(); - public static native boolean BASS_GetDeviceInfo(int device, BASS_DEVICEINFO info); - public static native boolean BASS_Init(int device, int freq, int flags); - public static native boolean BASS_Free(); - public static native boolean BASS_SetDevice(int device); - public static native int BASS_GetDevice(); - public static native boolean BASS_GetInfo(BASS_INFO info); - public static native boolean BASS_Start(); - public static native boolean BASS_Stop(); - public static native boolean BASS_Pause(); - public static native int BASS_IsStarted(); - public static native boolean BASS_Update(int length); - public static native float BASS_GetCPU(); - public static native boolean BASS_SetVolume(float volume); - public static native float BASS_GetVolume(); - - public static native boolean BASS_Set3DFactors(float distf, float rollf, float doppf); - public static native boolean BASS_Get3DFactors(FloatValue distf, FloatValue rollf, FloatValue doppf); - public static native boolean BASS_Set3DPosition(BASS_3DVECTOR pos, BASS_3DVECTOR vel, BASS_3DVECTOR front, BASS_3DVECTOR top); - public static native boolean BASS_Get3DPosition(BASS_3DVECTOR pos, BASS_3DVECTOR vel, BASS_3DVECTOR front, BASS_3DVECTOR top); - public static native void BASS_Apply3D(); - - public static native int BASS_PluginLoad(String file, int flags); - public static native boolean BASS_PluginFree(int handle); - public static native boolean BASS_PluginEnable(int handle, boolean enable); - public static native BASS_PLUGININFO BASS_PluginGetInfo(int handle); - - public static native int BASS_SampleLoad(String file, long offset, int length, int max, int flags); - public static native int BASS_SampleLoad(ByteBuffer file, long offset, int length, int max, int flags); - public static native int BASS_SampleLoad(Asset file, long offset, int length, int max, int flags); - public static native int BASS_SampleLoad(ParcelFileDescriptor file, long offset, int length, int max, int flags); - public static native int BASS_SampleCreate(int length, int freq, int chans, int max, int flags); - public static native boolean BASS_SampleFree(int handle); - public static native boolean BASS_SampleSetData(int handle, ByteBuffer buffer); - public static native boolean BASS_SampleGetData(int handle, ByteBuffer buffer); - public static native boolean BASS_SampleGetInfo(int handle, BASS_SAMPLE info); - public static native boolean BASS_SampleSetInfo(int handle, BASS_SAMPLE info); - public static native int BASS_SampleGetChannel(int handle, boolean onlynew); - public static native int BASS_SampleGetChannels(int handle, int[] channels); - public static native boolean BASS_SampleStop(int handle); - - public static native int BASS_StreamCreate(int freq, int chans, int flags, STREAMPROC proc, Object user); - public static native int BASS_StreamCreateFile(String file, long offset, long length, int flags); - public static native int BASS_StreamCreateFile(ByteBuffer file, long offset, long length, int flags); - public static native int BASS_StreamCreateFile(ParcelFileDescriptor file, long offset, long length, int flags); - public static native int BASS_StreamCreateFile(Asset asset, long offset, long length, int flags); - public static native int BASS_StreamCreateURL(String url, int offset, int flags, DOWNLOADPROC proc, Object user); - public static native int BASS_StreamCreateFileUser(int system, int flags, BASS_FILEPROCS procs, Object user); - public static native boolean BASS_StreamFree(int handle); - public static native long BASS_StreamGetFilePosition(int handle, int mode); - public static native int BASS_StreamPutData(int handle, ByteBuffer buffer, int length); - public static native int BASS_StreamPutFileData(int handle, ByteBuffer buffer, int length); - - public static native int BASS_MusicLoad(String file, long offset, int length, int flags, int freq); - public static native int BASS_MusicLoad(ByteBuffer file, long offset, int length, int flags, int freq); - public static native int BASS_MusicLoad(Asset asset, long offset, int length, int flags, int freq); - public static native int BASS_MusicLoad(ParcelFileDescriptor asset, long offset, int length, int flags, int freq); - public static native boolean BASS_MusicFree(int handle); - - public static native boolean BASS_RecordGetDeviceInfo(int device, BASS_DEVICEINFO info); - public static native boolean BASS_RecordInit(int device); - public static native boolean BASS_RecordFree(); - public static native boolean BASS_RecordSetDevice(int device); - public static native int BASS_RecordGetDevice(); - public static native boolean BASS_RecordGetInfo(BASS_RECORDINFO info); - public static native String BASS_RecordGetInputName(int input); - public static native boolean BASS_RecordSetInput(int input, int flags, float volume); - public static native int BASS_RecordGetInput(int input, FloatValue volume); - public static native int BASS_RecordStart(int freq, int chans, int flags, RECORDPROC proc, Object user); - - public static native double BASS_ChannelBytes2Seconds(int handle, long pos); - public static native long BASS_ChannelSeconds2Bytes(int handle, double pos); - public static native int BASS_ChannelGetDevice(int handle); - public static native boolean BASS_ChannelSetDevice(int handle, int device); - public static native int BASS_ChannelIsActive(int handle); - public static native boolean BASS_ChannelGetInfo(int handle, BASS_CHANNELINFO info); - public static native Object BASS_ChannelGetTags(int handle, int tags); - public static native long BASS_ChannelFlags(int handle, int flags, int mask); - public static native boolean BASS_ChannelLock(int handle, boolean lock); - public static native boolean BASS_ChannelFree(int handle); - public static native boolean BASS_ChannelPlay(int handle, boolean restart); - public static native boolean BASS_ChannelStop(int handle); - public static native boolean BASS_ChannelPause(int handle); - public static native boolean BASS_ChannelUpdate(int handle, int length); - public static native boolean BASS_ChannelSetAttribute(int handle, int attrib, float value); - public static native boolean BASS_ChannelGetAttribute(int handle, int attrib, FloatValue value); - public static native boolean BASS_ChannelSlideAttribute(int handle, int attrib, float value, int time); - public static native boolean BASS_ChannelIsSliding(int handle, int attrib); - public static native boolean BASS_ChannelSetAttributeEx(int handle, int attrib, ByteBuffer value, int size); - public static native int BASS_ChannelGetAttributeEx(int handle, int attrib, ByteBuffer value, int size); - public static native boolean BASS_ChannelSet3DAttributes(int handle, int mode, float min, float max, int iangle, int oangle, float outvol); - public static native boolean BASS_ChannelGet3DAttributes(int handle, Integer mode, FloatValue min, FloatValue max, Integer iangle, Integer oangle, FloatValue outvol); - public static native boolean BASS_ChannelSet3DPosition(int handle, BASS_3DVECTOR pos, BASS_3DVECTOR orient, BASS_3DVECTOR vel); - public static native boolean BASS_ChannelGet3DPosition(int handle, BASS_3DVECTOR pos, BASS_3DVECTOR orient, BASS_3DVECTOR vel); - public static native long BASS_ChannelGetLength(int handle, int mode); - public static native boolean BASS_ChannelSetPosition(int handle, long pos, int mode); - public static native long BASS_ChannelGetPosition(int handle, int mode); - public static native int BASS_ChannelGetLevel(int handle); - public static native boolean BASS_ChannelGetLevelEx(int handle, float[] levels, float length, int flags); - public static native int BASS_ChannelGetData(int handle, ByteBuffer buffer, int length); - public static native int BASS_ChannelSetSync(int handle, int type, long param, SYNCPROC proc, Object user); - public static native boolean BASS_ChannelRemoveSync(int handle, int sync); - public static native boolean BASS_ChannelSetLink(int handle, int chan); - public static native boolean BASS_ChannelRemoveLink(int handle, int chan); - public static native int BASS_ChannelSetDSP(int handle, DSPPROC proc, Object user, int priority); - public static native boolean BASS_ChannelRemoveDSP(int handle, int dsp); - public static native int BASS_ChannelSetFX(int handle, int type, int priority); - public static native boolean BASS_ChannelRemoveFX(int handle, int fx); - - public static native boolean BASS_FXSetParameters(int handle, Object params); - public static native boolean BASS_FXGetParameters(int handle, Object params); - public static native boolean BASS_FXSetPriority(int handle, int priority); - public static native boolean BASS_FXReset(int handle); - - static native int BASS_StreamCreateConst(int freq, int chans, int flags, int proc, Object user); - public static int BASS_StreamCreate(int freq, int chans, int flags, int proc, Object user) { - return BASS_StreamCreateConst(freq, chans, flags, proc, user); - } - - public static class Utils { - public static int LOBYTE(int n) { return n&0xff; } - public static int HIBYTE(int n) { return (n>>8)&0xff; } - public static int LOWORD(int n) { return n&0xffff; } - public static int HIWORD(int n) { return (n>>16)&0xffff; } - public static int MAKEWORD(int a, int b) { return (a&0xff)|((b&0xff)<<8); } - public static int MAKELONG(int a, int b) { return (a&0xffff)|(b<<16); } - } + public static final int BASSVERSION = 0x204; // API version + public static final String BASSVERSIONTEXT = "2.4"; + + // Error codes returned by BASS_ErrorGetCode + public static final int BASS_OK = 0; // all is OK + public static final int BASS_ERROR_MEM = 1; // memory error + public static final int BASS_ERROR_FILEOPEN = 2; // can't open the file + public static final int BASS_ERROR_DRIVER = 3; // can't find a free/valid driver + public static final int BASS_ERROR_BUFLOST = 4; // the sample buffer was lost + public static final int BASS_ERROR_HANDLE = 5; // invalid handle + public static final int BASS_ERROR_FORMAT = 6; // unsupported sample format + public static final int BASS_ERROR_POSITION = 7; // invalid position + public static final int BASS_ERROR_INIT = 8; // BASS_Init has not been successfully called + public static final int BASS_ERROR_START = 9; // BASS_Start has not been successfully called + public static final int BASS_ERROR_SSL = 10; // SSL/HTTPS support isn't available + public static final int BASS_ERROR_REINIT = 11; // device needs to be reinitialized + public static final int BASS_ERROR_ALREADY = 14; // already initialized/paused/whatever + public static final int BASS_ERROR_NOTAUDIO = 17; // file does not contain audio + public static final int BASS_ERROR_NOCHAN = 18; // can't get a free channel + public static final int BASS_ERROR_ILLTYPE = 19; // an illegal type was specified + public static final int BASS_ERROR_ILLPARAM = 20; // an illegal parameter was specified + public static final int BASS_ERROR_NO3D = 21; // no 3D support + public static final int BASS_ERROR_NOEAX = 22; // no EAX support + public static final int BASS_ERROR_DEVICE = 23; // illegal device number + public static final int BASS_ERROR_NOPLAY = 24; // not playing + public static final int BASS_ERROR_FREQ = 25; // illegal sample rate + public static final int BASS_ERROR_NOTFILE = 27; // the stream is not a file stream + public static final int BASS_ERROR_NOHW = 29; // no hardware voices available + public static final int BASS_ERROR_EMPTY = 31; // the MOD music has no sequence data + public static final int BASS_ERROR_NONET = 32; // no internet connection could be opened + public static final int BASS_ERROR_CREATE = 33; // couldn't create the file + public static final int BASS_ERROR_NOFX = 34; // effects are not available + public static final int BASS_ERROR_NOTAVAIL = 37; // requested data/action is not available + public static final int BASS_ERROR_DECODE = 38; // the channel is a "decoding channel" + public static final int BASS_ERROR_DX = 39; // a sufficient DirectX version is not installed + public static final int BASS_ERROR_TIMEOUT = 40; // connection timedout + public static final int BASS_ERROR_FILEFORM = 41; // unsupported file format + public static final int BASS_ERROR_SPEAKER = 42; // unavailable speaker + public static final int BASS_ERROR_VERSION = 43; // invalid BASS version (used by add-ons) + public static final int BASS_ERROR_CODEC = 44; // codec is not available/supported + public static final int BASS_ERROR_ENDED = 45; // the channel/file has ended + public static final int BASS_ERROR_BUSY = 46; // the device is busy + public static final int BASS_ERROR_UNSTREAMABLE = 47; // unstreamable file + public static final int BASS_ERROR_PROTOCOL = 48; // unsupported protocol + public static final int BASS_ERROR_UNKNOWN = -1; // some other mystery problem + + public static final int BASS_ERROR_JAVA_CLASS = 500; // object class problem + + // BASS_SetConfig options + public static final int BASS_CONFIG_BUFFER = 0; + public static final int BASS_CONFIG_UPDATEPERIOD = 1; + public static final int BASS_CONFIG_GVOL_SAMPLE = 4; + public static final int BASS_CONFIG_GVOL_STREAM = 5; + public static final int BASS_CONFIG_GVOL_MUSIC = 6; + public static final int BASS_CONFIG_CURVE_VOL = 7; + public static final int BASS_CONFIG_CURVE_PAN = 8; + public static final int BASS_CONFIG_FLOATDSP = 9; + public static final int BASS_CONFIG_3DALGORITHM = 10; + public static final int BASS_CONFIG_NET_TIMEOUT = 11; + public static final int BASS_CONFIG_NET_BUFFER = 12; + public static final int BASS_CONFIG_PAUSE_NOPLAY = 13; + public static final int BASS_CONFIG_NET_PREBUF = 15; + public static final int BASS_CONFIG_NET_PASSIVE = 18; + public static final int BASS_CONFIG_REC_BUFFER = 19; + public static final int BASS_CONFIG_NET_PLAYLIST = 21; + public static final int BASS_CONFIG_MUSIC_VIRTUAL = 22; + public static final int BASS_CONFIG_VERIFY = 23; + public static final int BASS_CONFIG_UPDATETHREADS = 24; + public static final int BASS_CONFIG_DEV_BUFFER = 27; + public static final int BASS_CONFIG_DEV_DEFAULT = 36; + public static final int BASS_CONFIG_NET_READTIMEOUT = 37; + public static final int BASS_CONFIG_HANDLES = 41; + public static final int BASS_CONFIG_SRC = 43; + public static final int BASS_CONFIG_SRC_SAMPLE = 44; + public static final int BASS_CONFIG_ASYNCFILE_BUFFER = 45; + public static final int BASS_CONFIG_OGG_PRESCAN = 47; + public static final int BASS_CONFIG_DEV_NONSTOP = 50; + public static final int BASS_CONFIG_VERIFY_NET = 52; + public static final int BASS_CONFIG_DEV_PERIOD = 53; + public static final int BASS_CONFIG_FLOAT = 54; + public static final int BASS_CONFIG_NET_SEEK = 56; + public static final int BASS_CONFIG_AM_DISABLE = 58; + public static final int BASS_CONFIG_NET_PLAYLIST_DEPTH = 59; + public static final int BASS_CONFIG_NET_PREBUF_WAIT = 60; + public static final int BASS_CONFIG_ANDROID_SESSIONID = 62; + public static final int BASS_CONFIG_ANDROID_AAUDIO = 67; + public static final int BASS_CONFIG_SAMPLE_ONEHANDLE = 69; + public static final int BASS_CONFIG_DEV_TIMEOUT = 70; + public static final int BASS_CONFIG_NET_META = 71; + public static final int BASS_CONFIG_NET_RESTRATE = 72; + + // BASS_SetConfigPtr options + public static final int BASS_CONFIG_NET_AGENT = 16; + public static final int BASS_CONFIG_NET_PROXY = 17; + public static final int BASS_CONFIG_LIBSSL = 64; + + public static final int BASS_CONFIG_THREAD = 0x40000000; // flag: thread-specific setting + + // BASS_Init flags + public static final int BASS_DEVICE_8BITS = 1; // unused + public static final int BASS_DEVICE_MONO = 2; // mono + public static final int BASS_DEVICE_3D = 4; // unused + public static final int BASS_DEVICE_16BITS = 8; // limit output to 16-bit + public static final int BASS_DEVICE_REINIT = 128; // reinitialize + public static final int BASS_DEVICE_LATENCY = 0x100; // unused + public static final int BASS_DEVICE_SPEAKERS = 0x800; // force enabling of speaker assignment + public static final int BASS_DEVICE_NOSPEAKER = 0x1000; // ignore speaker arrangement + public static final int BASS_DEVICE_FREQ = 0x4000; // set device sample rate + public static final int BASS_DEVICE_AUDIOTRACK = 0x20000; // use AudioTrack output + public static final int BASS_DEVICE_SOFTWARE = 0x80000; // disable hardware/fastpath output + + // Device info structure + public static class BASS_DEVICEINFO { + public String name; // description + public String driver; // driver + public int flags; + } + + // BASS_DEVICEINFO flags + public static final int BASS_DEVICE_ENABLED = 1; + public static final int BASS_DEVICE_DEFAULT = 2; + public static final int BASS_DEVICE_INIT = 4; + + public static class BASS_INFO { + public int flags; // device capabilities (DSCAPS_xxx flags) + public int hwsize; // unused + public int hwfree; // unused + public int freesam; // unused + public int free3d; // unused + public int minrate; // unused + public int maxrate; // unused + public int eax; // unused + public int minbuf; // recommended minimum buffer length in ms + public int dsver; // DirectSound version + public int latency; // average delay (in ms) before start of playback + public int initflags; // BASS_Init "flags" parameter + public int speakers; // number of speakers available + public int freq; // current output rate + } + + // Recording device info structure + public static class BASS_RECORDINFO { + public int flags; // device capabilities (DSCCAPS_xxx flags) + public int formats; // supported standard formats (WAVE_FORMAT_xxx flags) + public int inputs; // number of inputs + public boolean singlein; // TRUE = only 1 input can be set at a time + public int freq; // current input rate + } + + // Sample info structure + public static class BASS_SAMPLE { + public int freq; // default playback rate + public float volume; // default volume (0-1) + public float pan; // default pan (-1=left, 0=middle, 1=right) + public int flags; // BASS_SAMPLE_xxx flags + public int length; // length (in bytes) + public int max; // maximum simultaneous playbacks + public int origres; // original resolution bits + public int chans; // number of channels + public int mingap; // minimum gap (ms) between creating channels + public int mode3d; // BASS_3DMODE_xxx mode + public float mindist; // minimum distance + public float maxdist; // maximum distance + public int iangle; // angle of inside projection cone + public int oangle; // angle of outside projection cone + public float outvol; // delta-volume outside the projection cone + public int vam; // unused + public int priority; // unused + } + + public static final int BASS_SAMPLE_8BITS = 1; // 8 bit + public static final int BASS_SAMPLE_FLOAT = 256; // 32-bit floating-point + public static final int BASS_SAMPLE_MONO = 2; // mono + public static final int BASS_SAMPLE_LOOP = 4; // looped + public static final int BASS_SAMPLE_3D = 8; // 3D functionality + public static final int BASS_SAMPLE_SOFTWARE = 16; // unused + public static final int BASS_SAMPLE_MUTEMAX = 32; // mute at max distance (3D only) + public static final int BASS_SAMPLE_VAM = 64; // unused + public static final int BASS_SAMPLE_FX = 128; // unused + public static final int BASS_SAMPLE_OVER_VOL = 0x10000; // override lowest volume + public static final int BASS_SAMPLE_OVER_POS = 0x20000; // override longest playing + public static final int BASS_SAMPLE_OVER_DIST = 0x30000; // override furthest from listener (3D only) + + public static final int BASS_STREAM_PRESCAN = 0x20000; // scan file for accurate seeking and length + public static final int BASS_STREAM_AUTOFREE = 0x40000; // automatically free the stream when it stops/ends + public static final int BASS_STREAM_RESTRATE = 0x80000; // restrict the download rate of internet file streams + public static final int BASS_STREAM_BLOCK = 0x100000; // download/play internet file stream in small blocks + public static final int BASS_STREAM_DECODE = 0x200000; // don't play the stream, only decode (BASS_ChannelGetData) + public static final int BASS_STREAM_STATUS = 0x800000; // give server status info (HTTP/ICY tags) in DOWNLOADPROC + + public static final int BASS_MP3_IGNOREDELAY = 0x200; // ignore LAME/Xing/VBRI/iTunes delay & padding info + public static final int BASS_MP3_SETPOS = BASS_STREAM_PRESCAN; + + public static final int BASS_MUSIC_FLOAT = BASS_SAMPLE_FLOAT; + public static final int BASS_MUSIC_MONO = BASS_SAMPLE_MONO; + public static final int BASS_MUSIC_LOOP = BASS_SAMPLE_LOOP; + public static final int BASS_MUSIC_3D = BASS_SAMPLE_3D; + public static final int BASS_MUSIC_FX = BASS_SAMPLE_FX; + public static final int BASS_MUSIC_AUTOFREE = BASS_STREAM_AUTOFREE; + public static final int BASS_MUSIC_DECODE = BASS_STREAM_DECODE; + public static final int BASS_MUSIC_PRESCAN = BASS_STREAM_PRESCAN; // calculate playback length + public static final int BASS_MUSIC_CALCLEN = BASS_MUSIC_PRESCAN; + public static final int BASS_MUSIC_RAMP = 0x200; // normal ramping + public static final int BASS_MUSIC_RAMPS = 0x400; // sensitive ramping + public static final int BASS_MUSIC_SURROUND = 0x800; // surround sound + public static final int BASS_MUSIC_SURROUND2 = 0x1000; // surround sound (mode 2) + public static final int BASS_MUSIC_FT2PAN = 0x2000; // apply FastTracker 2 panning to XM files + public static final int BASS_MUSIC_FT2MOD = 0x2000; // play .MOD as FastTracker 2 does + public static final int BASS_MUSIC_PT1MOD = 0x4000; // play .MOD as ProTracker 1 does + public static final int BASS_MUSIC_NONINTER = 0x10000; // non-interpolated sample mixing + public static final int BASS_MUSIC_SINCINTER = 0x800000; // sinc interpolated sample mixing + public static final int BASS_MUSIC_POSRESET = 0x8000; // stop all notes when moving position + public static final int BASS_MUSIC_POSRESETEX = 0x400000; // stop all notes and reset bmp/etc when moving position + public static final int BASS_MUSIC_STOPBACK = 0x80000; // stop the music on a backwards jump effect + public static final int BASS_MUSIC_NOSAMPLE = 0x100000; // don't load the samples + + // Speaker assignment flags + public static final int BASS_SPEAKER_FRONT = 0x1000000; // front speakers + public static final int BASS_SPEAKER_REAR = 0x2000000; // rear/side speakers + public static final int BASS_SPEAKER_CENLFE = 0x3000000; // center & LFE speakers (5.1) + public static final int BASS_SPEAKER_REAR2 = 0x4000000; // rear center speakers (7.1) + public static int BASS_SPEAKER_N(int n) { return n<<24; } // n'th pair of speakers (max 15) + public static final int BASS_SPEAKER_LEFT = 0x10000000; // modifier: left + public static final int BASS_SPEAKER_RIGHT = 0x20000000; // modifier: right + public static final int BASS_SPEAKER_FRONTLEFT = BASS_SPEAKER_FRONT|BASS_SPEAKER_LEFT; + public static final int BASS_SPEAKER_FRONTRIGHT = BASS_SPEAKER_FRONT|BASS_SPEAKER_RIGHT; + public static final int BASS_SPEAKER_REARLEFT = BASS_SPEAKER_REAR|BASS_SPEAKER_LEFT; + public static final int BASS_SPEAKER_REARRIGHT = BASS_SPEAKER_REAR|BASS_SPEAKER_RIGHT; + public static final int BASS_SPEAKER_CENTER = BASS_SPEAKER_CENLFE|BASS_SPEAKER_LEFT; + public static final int BASS_SPEAKER_LFE = BASS_SPEAKER_CENLFE|BASS_SPEAKER_RIGHT; + public static final int BASS_SPEAKER_REAR2LEFT = BASS_SPEAKER_REAR2|BASS_SPEAKER_LEFT; + public static final int BASS_SPEAKER_REAR2RIGHT = BASS_SPEAKER_REAR2|BASS_SPEAKER_RIGHT; + + public static final int BASS_ASYNCFILE = 0x40000000; // read file asynchronously + + public static final int BASS_RECORD_PAUSE = 0x8000; // start recording paused + + // Channel info structure + public static class BASS_CHANNELINFO { + public int freq; // default playback rate + public int chans; // channels + public int flags; + public int ctype; // type of channel + public int origres; // original resolution + public int plugin; + public int sample; + public String filename; + } + + public static final int BASS_ORIGRES_FLOAT = 0x10000; + + // BASS_CHANNELINFO types + public static final int BASS_CTYPE_SAMPLE = 1; + public static final int BASS_CTYPE_RECORD = 2; + public static final int BASS_CTYPE_STREAM = 0x10000; + public static final int BASS_CTYPE_STREAM_VORBIS = 0x10002; + public static final int BASS_CTYPE_STREAM_OGG = 0x10002; + public static final int BASS_CTYPE_STREAM_MP1 = 0x10003; + public static final int BASS_CTYPE_STREAM_MP2 = 0x10004; + public static final int BASS_CTYPE_STREAM_MP3 = 0x10005; + public static final int BASS_CTYPE_STREAM_AIFF = 0x10006; + public static final int BASS_CTYPE_STREAM_CA = 0x10007; + public static final int BASS_CTYPE_STREAM_MF = 0x10008; + public static final int BASS_CTYPE_STREAM_AM = 0x10009; + public static final int BASS_CTYPE_STREAM_SAMPLE = 0x1000a; + public static final int BASS_CTYPE_STREAM_DUMMY = 0x18000; + public static final int BASS_CTYPE_STREAM_DEVICE = 0x18001; + public static final int BASS_CTYPE_STREAM_WAV = 0x40000; // WAVE flag (LOWORD=codec) + public static final int BASS_CTYPE_STREAM_WAV_PCM = 0x50001; + public static final int BASS_CTYPE_STREAM_WAV_FLOAT = 0x50003; + public static final int BASS_CTYPE_MUSIC_MOD = 0x20000; + public static final int BASS_CTYPE_MUSIC_MTM = 0x20001; + public static final int BASS_CTYPE_MUSIC_S3M = 0x20002; + public static final int BASS_CTYPE_MUSIC_XM = 0x20003; + public static final int BASS_CTYPE_MUSIC_IT = 0x20004; + public static final int BASS_CTYPE_MUSIC_MO3 = 0x00100; // MO3 flag + + public static class BASS_PLUGINFORM { + public int ctype; // channel type + public String name; // format description + public String exts; // file extension filter (*.ext1;*.ext2;etc...) + } + + public static class BASS_PLUGININFO { + public int version; // version (same form as BASS_GetVersion) + public int formatc; // number of formats + public BASS_PLUGINFORM[] formats; // the array of formats + } + + // 3D vector (for 3D positions/velocities/orientations) + public static class BASS_3DVECTOR { + public BASS_3DVECTOR() {} + public BASS_3DVECTOR(float _x, float _y, float _z) { x=_x; y=_y; z=_z; } + public float x; // +=right, -=left + public float y; // +=up, -=down + public float z; // +=front, -=behind + } + + // 3D channel modes + public static final int BASS_3DMODE_NORMAL = 0; // normal 3D processing + public static final int BASS_3DMODE_RELATIVE = 1; // position is relative to the listener + public static final int BASS_3DMODE_OFF = 2; // no 3D processing + + // software 3D mixing algorithms (used with BASS_CONFIG_3DALGORITHM) + public static final int BASS_3DALG_DEFAULT = 0; + public static final int BASS_3DALG_OFF = 1; + public static final int BASS_3DALG_FULL = 2; + public static final int BASS_3DALG_LIGHT = 3; + + // BASS_SampleGetChannel flags + public static final int BASS_SAMCHAN_NEW = 1; // get a new playback channel + public static final int BASS_SAMCHAN_STREAM = 2; // create a stream + + public interface STREAMPROC + { + int STREAMPROC(int handle, ByteBuffer buffer, int length, Object user); + /* User stream callback function. + handle : The stream that needs writing + buffer : Buffer to write the samples in + length : Number of bytes to write + user : The 'user' parameter value given when calling BASS_StreamCreate + RETURN : Number of bytes written. Set the BASS_STREAMPROC_END flag to end + the stream. */ + } + + public static final int BASS_STREAMPROC_END = 0x80000000; // end of user stream flag + + // Special STREAMPROCs + public static final int STREAMPROC_DUMMY = 0; // "dummy" stream + public static final int STREAMPROC_PUSH = -1; // push stream + public static final int STREAMPROC_DEVICE = -2; // device mix stream + public static final int STREAMPROC_DEVICE_3D = -3; // device 3D mix stream + + // BASS_StreamCreateFileUser file systems + public static final int STREAMFILE_NOBUFFER = 0; + public static final int STREAMFILE_BUFFER = 1; + public static final int STREAMFILE_BUFFERPUSH = 2; + + public interface BASS_FILEPROCS + { + // User file stream callback functions + void FILECLOSEPROC(Object user); + long FILELENPROC(Object user); + int FILEREADPROC(ByteBuffer buffer, int length, Object user); + boolean FILESEEKPROC(long offset, Object user); + } + + // BASS_StreamPutFileData options + public static final int BASS_FILEDATA_END = 0; // end & close the file + + // BASS_StreamGetFilePosition modes + public static final int BASS_FILEPOS_CURRENT = 0; + public static final int BASS_FILEPOS_DECODE = BASS_FILEPOS_CURRENT; + public static final int BASS_FILEPOS_DOWNLOAD = 1; + public static final int BASS_FILEPOS_END = 2; + public static final int BASS_FILEPOS_START = 3; + public static final int BASS_FILEPOS_CONNECTED = 4; + public static final int BASS_FILEPOS_BUFFER = 5; + public static final int BASS_FILEPOS_SOCKET = 6; + public static final int BASS_FILEPOS_ASYNCBUF = 7; + public static final int BASS_FILEPOS_SIZE = 8; + public static final int BASS_FILEPOS_BUFFERING = 9; + public static final int BASS_FILEPOS_AVAILABLE = 10; + + public interface DOWNLOADPROC + { + void DOWNLOADPROC(ByteBuffer buffer, int length, Object user); + /* Internet stream download callback function. + buffer : Buffer containing the downloaded data... NULL=end of download + length : Number of bytes in the buffer + user : The 'user' parameter value given when calling BASS_StreamCreateURL */ + } + + // BASS_ChannelSetSync types + public static final int BASS_SYNC_POS = 0; + public static final int BASS_SYNC_END = 2; + public static final int BASS_SYNC_META = 4; + public static final int BASS_SYNC_SLIDE = 5; + public static final int BASS_SYNC_STALL = 6; + public static final int BASS_SYNC_DOWNLOAD = 7; + public static final int BASS_SYNC_FREE = 8; + public static final int BASS_SYNC_SETPOS = 11; + public static final int BASS_SYNC_MUSICPOS = 10; + public static final int BASS_SYNC_MUSICINST = 1; + public static final int BASS_SYNC_MUSICFX = 3; + public static final int BASS_SYNC_OGG_CHANGE = 12; + public static final int BASS_SYNC_DEV_FAIL = 14; + public static final int BASS_SYNC_DEV_FORMAT = 15; + public static final int BASS_SYNC_THREAD = 0x20000000; // flag: call sync in other thread + public static final int BASS_SYNC_MIXTIME = 0x40000000; // flag: sync at mixtime, else at playtime + public static final int BASS_SYNC_ONETIME = 0x80000000; // flag: sync only once, else continuously + + public interface SYNCPROC + { + void SYNCPROC(int handle, int channel, int data, Object user); + /* Sync callback function. + handle : The sync that has occured + channel: Channel that the sync occured in + data : Additional data associated with the sync's occurance + user : The 'user' parameter given when calling BASS_ChannelSetSync */ + } + + public interface DSPPROC + { + void DSPPROC(int handle, int channel, ByteBuffer buffer, int length, Object user); + /* DSP callback function. + handle : The DSP handle + channel: Channel that the DSP is being applied to + buffer : Buffer to apply the DSP to + length : Number of bytes in the buffer + user : The 'user' parameter given when calling BASS_ChannelSetDSP */ + } + + public interface RECORDPROC + { + boolean RECORDPROC(int handle, ByteBuffer buffer, int length, Object user); + /* Recording callback function. + handle : The recording handle + buffer : Buffer containing the recorded sample data + length : Number of bytes + user : The 'user' parameter value given when calling BASS_RecordStart + RETURN : true = continue recording, false = stop */ + } + + // BASS_ChannelIsActive return values + public static final int BASS_ACTIVE_STOPPED = 0; + public static final int BASS_ACTIVE_PLAYING =1; + public static final int BASS_ACTIVE_STALLED = 2; + public static final int BASS_ACTIVE_PAUSED = 3; + public static final int BASS_ACTIVE_PAUSED_DEVICE = 4; + + // Channel attributes + public static final int BASS_ATTRIB_FREQ = 1; + public static final int BASS_ATTRIB_VOL = 2; + public static final int BASS_ATTRIB_PAN = 3; + public static final int BASS_ATTRIB_EAXMIX = 4; + public static final int BASS_ATTRIB_NOBUFFER = 5; + public static final int BASS_ATTRIB_VBR = 6; + public static final int BASS_ATTRIB_CPU = 7; + public static final int BASS_ATTRIB_SRC = 8; + public static final int BASS_ATTRIB_NET_RESUME = 9; + public static final int BASS_ATTRIB_SCANINFO = 10; + public static final int BASS_ATTRIB_NORAMP = 11; + public static final int BASS_ATTRIB_BITRATE = 12; + public static final int BASS_ATTRIB_BUFFER = 13; + public static final int BASS_ATTRIB_GRANULE = 14; + public static final int BASS_ATTRIB_USER = 15; + public static final int BASS_ATTRIB_TAIL = 16; + public static final int BASS_ATTRIB_PUSH_LIMIT = 17; + public static final int BASS_ATTRIB_MUSIC_AMPLIFY = 0x100; + public static final int BASS_ATTRIB_MUSIC_PANSEP = 0x101; + public static final int BASS_ATTRIB_MUSIC_PSCALER = 0x102; + public static final int BASS_ATTRIB_MUSIC_BPM = 0x103; + public static final int BASS_ATTRIB_MUSIC_SPEED = 0x104; + public static final int BASS_ATTRIB_MUSIC_VOL_GLOBAL = 0x105; + public static final int BASS_ATTRIB_MUSIC_VOL_CHAN = 0x200; // + channel # + public static final int BASS_ATTRIB_MUSIC_VOL_INST = 0x300; // + instrument # + + // BASS_ChannelSlideAttribute flags + public static final int BASS_SLIDE_LOG = 0x1000000; + + // BASS_ChannelGetData flags + public static final int BASS_DATA_AVAILABLE = 0; // query how much data is buffered + public static final int BASS_DATA_NOREMOVE = 0x10000000; // flag: don't remove data from recording buffer + public static final int BASS_DATA_FIXED = 0x20000000; // flag: return 8.24 fixed-point data + public static final int BASS_DATA_FLOAT = 0x40000000; // flag: return floating-point sample data + public static final int BASS_DATA_FFT256 = 0x80000000; // 256 sample FFT + public static final int BASS_DATA_FFT512 = 0x80000001; // 512 FFT + public static final int BASS_DATA_FFT1024 = 0x80000002; // 1024 FFT + public static final int BASS_DATA_FFT2048 = 0x80000003; // 2048 FFT + public static final int BASS_DATA_FFT4096 = 0x80000004; // 4096 FFT + public static final int BASS_DATA_FFT8192 = 0x80000005; // 8192 FFT + public static final int BASS_DATA_FFT16384 = 0x80000006; // 16384 FFT + public static final int BASS_DATA_FFT32768 = 0x80000007; // 32768 FFT + public static final int BASS_DATA_FFT_INDIVIDUAL = 0x10; // FFT flag: FFT for each channel, else all combined + public static final int BASS_DATA_FFT_NOWINDOW = 0x20; // FFT flag: no Hanning window + public static final int BASS_DATA_FFT_REMOVEDC = 0x40; // FFT flag: pre-remove DC bias + public static final int BASS_DATA_FFT_COMPLEX = 0x80; // FFT flag: return complex data + public static final int BASS_DATA_FFT_NYQUIST = 0x100; // FFT flag: return extra Nyquist value + + // BASS_ChannelGetLevelEx flags + public static final int BASS_LEVEL_MONO = 1; // get mono level + public static final int BASS_LEVEL_STEREO = 2; // get stereo level + public static final int BASS_LEVEL_RMS = 4; // get RMS levels + public static final int BASS_LEVEL_VOLPAN = 8; // apply VOL/PAN attributes to the levels + public static final int BASS_LEVEL_NOREMOVE = 16; // don't remove data from recording buffer + + // BASS_ChannelGetTags types : what's returned + public static final int BASS_TAG_ID3 = 0; // ID3v1 tags : TAG_ID3 + public static final int BASS_TAG_ID3V2 = 1; // ID3v2 tags : ByteBuffer + public static final int BASS_TAG_OGG = 2; // OGG comments : String array + public static final int BASS_TAG_HTTP = 3; // HTTP headers : String array + public static final int BASS_TAG_ICY = 4; // ICY headers : String array + public static final int BASS_TAG_META = 5; // ICY metadata : String + public static final int BASS_TAG_APE = 6; // APE tags : String array + public static final int BASS_TAG_MP4 = 7; // MP4/iTunes metadata : String array + public static final int BASS_TAG_VENDOR = 9; // OGG encoder : String + public static final int BASS_TAG_LYRICS3 = 10; // Lyric3v2 tag : String + public static final int BASS_TAG_WAVEFORMAT = 14; // WAVE format : ByteBuffer containing WAVEFORMATEEX structure + public static final int BASS_TAG_AM_NAME = 16; // Android Media codec name : String + public static final int BASS_TAG_ID3V2_2 = 17; // ID3v2 tags (2nd block) : ByteBuffer + public static final int BASS_TAG_AM_MIME = 18; // Android Media MIME type : String + public static final int BASS_TAG_LOCATION = 19; // redirected URL : String + public static final int BASS_TAG_RIFF_INFO = 0x100; // RIFF "INFO" tags : String array + public static final int BASS_TAG_RIFF_BEXT = 0x101; // RIFF/BWF "bext" tags : TAG_BEXT + public static final int BASS_TAG_RIFF_CART = 0x102; // RIFF/BWF "cart" tags : TAG_CART + public static final int BASS_TAG_RIFF_DISP = 0x103; // RIFF "DISP" text tag : String + public static final int BASS_TAG_RIFF_CUE = 0x104; // RIFF "cue " chunk : TAG_CUE structure + public static final int BASS_TAG_RIFF_SMPL = 0x105; // RIFF "smpl" chunk : TAG_SMPL structure + public static final int BASS_TAG_APE_BINARY = 0x1000; // + index #, binary APE tag : TAG_APE_BINARY + public static final int BASS_TAG_MUSIC_NAME = 0x10000; // MOD music name : String + public static final int BASS_TAG_MUSIC_MESSAGE = 0x10001; // MOD message : String + public static final int BASS_TAG_MUSIC_ORDERS = 0x10002; // MOD order list : ByteBuffer + public static final int BASS_TAG_MUSIC_AUTH = 0x10003; // MOD author : UTF-8 string + public static final int BASS_TAG_MUSIC_INST = 0x10100; // + instrument #, MOD instrument name : String + public static final int BASS_TAG_MUSIC_CHAN = 0x10200; // + channel #, MOD channel name : String + public static final int BASS_TAG_MUSIC_SAMPLE = 0x10300; // + sample #, MOD sample name : String + public static final int BASS_TAG_BYTEBUFFER = 0x10000000; // flag: return a ByteBuffer instead of a String or TAG_ID3 + + // ID3v1 tag structure + public static class TAG_ID3 { + public String id; + public String title; + public String artist; + public String album; + public String year; + public String comment; + public byte genre; + public byte track; + } + + // Binary APE tag structure + public static class TAG_APE_BINARY { + public String key; + public ByteBuffer data; + public int length; + } + + // BASS_ChannelGetLength/GetPosition/SetPosition modes + public static final int BASS_POS_BYTE = 0; // byte position + public static final int BASS_POS_MUSIC_ORDER = 1; // order.row position, MAKELONG(order,row) + public static final int BASS_POS_OGG = 3; // OGG bitstream number + public static final int BASS_POS_END = 0x10; // trimmed end position + public static final int BASS_POS_LOOP = 0x11; // loop start positiom + public static final int BASS_POS_FLUSH = 0x1000000; // flag: flush decoder/FX buffers + public static final int BASS_POS_RESET = 0x2000000; // flag: reset user file buffers + public static final int BASS_POS_RELATIVE = 0x4000000; // flag: seek relative to the current position + public static final int BASS_POS_INEXACT = 0x8000000; // flag: allow seeking to inexact position + public static final int BASS_POS_DECODE = 0x10000000; // flag: get the decoding (not playing) position + public static final int BASS_POS_DECODETO = 0x20000000; // flag: decode to the position instead of seeking + public static final int BASS_POS_SCAN = 0x40000000; // flag: scan to the position + + // BASS_ChannelSetDevice/GetDevice option + public static final int BASS_NODEVICE = 0x20000; + + // DX8 effect types, use with BASS_ChannelSetFX + public static final int BASS_FX_DX8_CHORUS = 0; + public static final int BASS_FX_DX8_COMPRESSOR = 1; + public static final int BASS_FX_DX8_DISTORTION = 2; + public static final int BASS_FX_DX8_ECHO = 3; + public static final int BASS_FX_DX8_FLANGER = 4; + public static final int BASS_FX_DX8_GARGLE = 5; + public static final int BASS_FX_DX8_I3DL2REVERB = 6; + public static final int BASS_FX_DX8_PARAMEQ = 7; + public static final int BASS_FX_DX8_REVERB = 8; + public static final int BASS_FX_VOLUME = 9; + + public static class BASS_DX8_CHORUS { + public float fWetDryMix; + public float fDepth; + public float fFeedback; + public float fFrequency; + public int lWaveform; // 0=triangle, 1=sine + public float fDelay; + public int lPhase; // BASS_DX8_PHASE_xxx + } + + public static class BASS_DX8_DISTORTION { + public float fGain; + public float fEdge; + public float fPostEQCenterFrequency; + public float fPostEQBandwidth; + public float fPreLowpassCutoff; + } + + public static class BASS_DX8_ECHO { + public float fWetDryMix; + public float fFeedback; + public float fLeftDelay; + public float fRightDelay; + public boolean lPanDelay; + } + + public static class BASS_DX8_FLANGER { + public float fWetDryMix; + public float fDepth; + public float fFeedback; + public float fFrequency; + public int lWaveform; // 0=triangle, 1=sine + public float fDelay; + public int lPhase; // BASS_DX8_PHASE_xxx + } + + public static class BASS_DX8_PARAMEQ { + public float fCenter; + public float fBandwidth; + public float fGain; + } + + public static class BASS_DX8_REVERB { + public float fInGain; + public float fReverbMix; + public float fReverbTime; + public float fHighFreqRTRatio; + } + + public static final int BASS_DX8_PHASE_NEG_180 = 0; + public static final int BASS_DX8_PHASE_NEG_90 = 1; + public static final int BASS_DX8_PHASE_ZERO = 2; + public static final int BASS_DX8_PHASE_90 = 3; + public static final int BASS_DX8_PHASE_180 = 4; + + public static class BASS_FX_VOLUME_PARAM { + public float fTarget; + public float fCurrent; + public float fTime; + public int lCurve; + } + + public static class Asset { + public Asset() {} + public Asset(AssetManager m, String f) { manager=m; file=f; } + public AssetManager manager; + public String file; + } + + public static class FloatValue { + public float value; + } + + public static native boolean BASS_SetConfig(int option, int value); + public static native int BASS_GetConfig(int option); + public static native boolean BASS_SetConfigPtr(int option, Object value); + public static native Object BASS_GetConfigPtr(int option); + public static native int BASS_GetVersion(); + public static native int BASS_ErrorGetCode(); + public static native boolean BASS_GetDeviceInfo(int device, BASS_DEVICEINFO info); + public static native boolean BASS_Init(int device, int freq, int flags); + public static native boolean BASS_Free(); + public static native boolean BASS_SetDevice(int device); + public static native int BASS_GetDevice(); + public static native boolean BASS_GetInfo(BASS_INFO info); + public static native boolean BASS_Start(); + public static native boolean BASS_Stop(); + public static native boolean BASS_Pause(); + public static native int BASS_IsStarted(); + public static native boolean BASS_Update(int length); + public static native float BASS_GetCPU(); + public static native boolean BASS_SetVolume(float volume); + public static native float BASS_GetVolume(); + + public static native boolean BASS_Set3DFactors(float distf, float rollf, float doppf); + public static native boolean BASS_Get3DFactors(FloatValue distf, FloatValue rollf, FloatValue doppf); + public static native boolean BASS_Set3DPosition(BASS_3DVECTOR pos, BASS_3DVECTOR vel, BASS_3DVECTOR front, BASS_3DVECTOR top); + public static native boolean BASS_Get3DPosition(BASS_3DVECTOR pos, BASS_3DVECTOR vel, BASS_3DVECTOR front, BASS_3DVECTOR top); + public static native void BASS_Apply3D(); + + public static native int BASS_PluginLoad(String file, int flags); + public static native boolean BASS_PluginFree(int handle); + public static native boolean BASS_PluginEnable(int handle, boolean enable); + public static native BASS_PLUGININFO BASS_PluginGetInfo(int handle); + + public static native int BASS_SampleLoad(String file, long offset, int length, int max, int flags); + public static native int BASS_SampleLoad(ByteBuffer file, long offset, int length, int max, int flags); + public static native int BASS_SampleLoad(Asset file, long offset, int length, int max, int flags); + public static native int BASS_SampleLoad(ParcelFileDescriptor file, long offset, int length, int max, int flags); + public static native int BASS_SampleCreate(int length, int freq, int chans, int max, int flags); + public static native boolean BASS_SampleFree(int handle); + public static native boolean BASS_SampleSetData(int handle, ByteBuffer buffer); + public static native boolean BASS_SampleGetData(int handle, ByteBuffer buffer); + public static native boolean BASS_SampleGetInfo(int handle, BASS_SAMPLE info); + public static native boolean BASS_SampleSetInfo(int handle, BASS_SAMPLE info); + public static native int BASS_SampleGetChannel(int handle, boolean onlynew); + public static native int BASS_SampleGetChannels(int handle, int[] channels); + public static native boolean BASS_SampleStop(int handle); + + public static native int BASS_StreamCreate(int freq, int chans, int flags, STREAMPROC proc, Object user); + public static native int BASS_StreamCreateFile(String file, long offset, long length, int flags); + public static native int BASS_StreamCreateFile(ByteBuffer file, long offset, long length, int flags); + public static native int BASS_StreamCreateFile(ParcelFileDescriptor file, long offset, long length, int flags); + public static native int BASS_StreamCreateFile(Asset asset, long offset, long length, int flags); + public static native int BASS_StreamCreateURL(String url, int offset, int flags, DOWNLOADPROC proc, Object user); + public static native int BASS_StreamCreateFileUser(int system, int flags, BASS_FILEPROCS procs, Object user); + public static native boolean BASS_StreamFree(int handle); + public static native long BASS_StreamGetFilePosition(int handle, int mode); + public static native int BASS_StreamPutData(int handle, ByteBuffer buffer, int length); + public static native int BASS_StreamPutFileData(int handle, ByteBuffer buffer, int length); + + public static native int BASS_MusicLoad(String file, long offset, int length, int flags, int freq); + public static native int BASS_MusicLoad(ByteBuffer file, long offset, int length, int flags, int freq); + public static native int BASS_MusicLoad(Asset asset, long offset, int length, int flags, int freq); + public static native int BASS_MusicLoad(ParcelFileDescriptor asset, long offset, int length, int flags, int freq); + public static native boolean BASS_MusicFree(int handle); + + public static native boolean BASS_RecordGetDeviceInfo(int device, BASS_DEVICEINFO info); + public static native boolean BASS_RecordInit(int device); + public static native boolean BASS_RecordFree(); + public static native boolean BASS_RecordSetDevice(int device); + public static native int BASS_RecordGetDevice(); + public static native boolean BASS_RecordGetInfo(BASS_RECORDINFO info); + public static native String BASS_RecordGetInputName(int input); + public static native boolean BASS_RecordSetInput(int input, int flags, float volume); + public static native int BASS_RecordGetInput(int input, FloatValue volume); + public static native int BASS_RecordStart(int freq, int chans, int flags, RECORDPROC proc, Object user); + + public static native double BASS_ChannelBytes2Seconds(int handle, long pos); + public static native long BASS_ChannelSeconds2Bytes(int handle, double pos); + public static native int BASS_ChannelGetDevice(int handle); + public static native boolean BASS_ChannelSetDevice(int handle, int device); + public static native int BASS_ChannelIsActive(int handle); + public static native boolean BASS_ChannelGetInfo(int handle, BASS_CHANNELINFO info); + public static native Object BASS_ChannelGetTags(int handle, int tags); + public static native long BASS_ChannelFlags(int handle, int flags, int mask); + public static native boolean BASS_ChannelLock(int handle, boolean lock); + public static native boolean BASS_ChannelFree(int handle); + public static native boolean BASS_ChannelPlay(int handle, boolean restart); + public static native boolean BASS_ChannelStop(int handle); + public static native boolean BASS_ChannelPause(int handle); + public static native boolean BASS_ChannelUpdate(int handle, int length); + public static native boolean BASS_ChannelSetAttribute(int handle, int attrib, float value); + public static native boolean BASS_ChannelGetAttribute(int handle, int attrib, FloatValue value); + public static native boolean BASS_ChannelSlideAttribute(int handle, int attrib, float value, int time); + public static native boolean BASS_ChannelIsSliding(int handle, int attrib); + public static native boolean BASS_ChannelSetAttributeEx(int handle, int attrib, ByteBuffer value, int size); + public static native int BASS_ChannelGetAttributeEx(int handle, int attrib, ByteBuffer value, int size); + public static native boolean BASS_ChannelSet3DAttributes(int handle, int mode, float min, float max, int iangle, int oangle, float outvol); + public static native boolean BASS_ChannelGet3DAttributes(int handle, Integer mode, FloatValue min, FloatValue max, Integer iangle, Integer oangle, FloatValue outvol); + public static native boolean BASS_ChannelSet3DPosition(int handle, BASS_3DVECTOR pos, BASS_3DVECTOR orient, BASS_3DVECTOR vel); + public static native boolean BASS_ChannelGet3DPosition(int handle, BASS_3DVECTOR pos, BASS_3DVECTOR orient, BASS_3DVECTOR vel); + public static native long BASS_ChannelGetLength(int handle, int mode); + public static native boolean BASS_ChannelSetPosition(int handle, long pos, int mode); + public static native long BASS_ChannelGetPosition(int handle, int mode); + public static native int BASS_ChannelGetLevel(int handle); + public static native boolean BASS_ChannelGetLevelEx(int handle, float[] levels, float length, int flags); + public static native int BASS_ChannelGetData(int handle, ByteBuffer buffer, int length); + public static native int BASS_ChannelSetSync(int handle, int type, long param, SYNCPROC proc, Object user); + public static native boolean BASS_ChannelRemoveSync(int handle, int sync); + public static native boolean BASS_ChannelSetLink(int handle, int chan); + public static native boolean BASS_ChannelRemoveLink(int handle, int chan); + public static native int BASS_ChannelSetDSP(int handle, DSPPROC proc, Object user, int priority); + public static native boolean BASS_ChannelRemoveDSP(int handle, int dsp); + public static native int BASS_ChannelSetFX(int handle, int type, int priority); + public static native boolean BASS_ChannelRemoveFX(int handle, int fx); + + public static native boolean BASS_FXSetParameters(int handle, Object params); + public static native boolean BASS_FXGetParameters(int handle, Object params); + public static native boolean BASS_FXSetPriority(int handle, int priority); + public static native boolean BASS_FXReset(int handle); + + static native int BASS_StreamCreateConst(int freq, int chans, int flags, int proc, Object user); + public static int BASS_StreamCreate(int freq, int chans, int flags, int proc, Object user) { + return BASS_StreamCreateConst(freq, chans, flags, proc, user); + } + + public static class Utils { + public static int LOBYTE(int n) { return n&0xff; } + public static int HIBYTE(int n) { return (n>>8)&0xff; } + public static int LOWORD(int n) { return n&0xffff; } + public static int HIWORD(int n) { return (n>>16)&0xffff; } + public static int MAKEWORD(int a, int b) { return (a&0xff)|((b&0xff)<<8); } + public static int MAKELONG(int a, int b) { return (a&0xffff)|(b<<16); } + } static { System.loadLibrary("bass"); diff --git a/LibBASS/src/main/java/com/un4seen/bass/BASS_FX.java b/LibBASS/src/main/java/com/un4seen/bass/BASS_FX.java index 5ae511ad..1b5cd710 100644 --- a/LibBASS/src/main/java/com/un4seen/bass/BASS_FX.java +++ b/LibBASS/src/main/java/com/un4seen/bass/BASS_FX.java @@ -1,443 +1,443 @@ -/*=========================================================================== - BASS_FX 2.4 - Copyright (c) 2002-2018 (: JOBnik! :) [Arthur Aminov, ISRAEL] - [http://www.jobnik.org] - - bugs/suggestions/questions: - forum : http://www.un4seen.com/forum/?board=1 - http://www.jobnik.org/forums - e-mail : bass_fx@jobnik.org - -------------------------------------------------- - - NOTE: This header will work only with BASS_FX version 2.4.12 - Check www.un4seen.com or www.jobnik.org for any later versions. - - * Requires BASS 2.4 (available at http://www.un4seen.com) -===========================================================================*/ - -package com.un4seen.bass; - -public class BASS_FX -{ - // BASS_CHANNELINFO types - public static final int BASS_CTYPE_STREAM_TEMPO = 0x1f200; - public static final int BASS_CTYPE_STREAM_REVERSE = 0x1f201; - - // Tempo / Reverse / BPM / Beat flag - public static final int BASS_FX_FREESOURCE = 0x10000; // Free the source handle as well? - - // BASS_FX Version - public static native int BASS_FX_GetVersion(); - - /*=========================================================================== - DSP (Digital Signal Processing) - ===========================================================================*/ - - /* - Multi-channel order of each channel is as follows: - 3 channels left-front, right-front, center. - 4 channels left-front, right-front, left-rear/side, right-rear/side. - 5 channels left-front, right-front, center, left-rear/side, right-rear/side. - 6 channels (5.1) left-front, right-front, center, LFE, left-rear/side, right-rear/side. - 8 channels (7.1) left-front, right-front, center, LFE, left-rear/side, right-rear/side, left-rear center, right-rear center. - */ - - // DSP channels flags - public static final int BASS_BFX_CHANALL = -1; // all channels at once (as by default) - public static final int BASS_BFX_CHANNONE = 0; // disable an effect for all channels - public static final int BASS_BFX_CHAN1 = 1; // left-front channel - public static final int BASS_BFX_CHAN2 = 2; // right-front channel - public static final int BASS_BFX_CHAN3 = 4; // see above info - public static final int BASS_BFX_CHAN4 = 8; // see above info - public static final int BASS_BFX_CHAN5 = 16; // see above info - public static final int BASS_BFX_CHAN6 = 32; // see above info - public static final int BASS_BFX_CHAN7 = 64; // see above info - public static final int BASS_BFX_CHAN8 = 128; // see above info - - // if you have more than 8 channels (7.1), use this function - public static int BASS_BFX_CHANNEL_N(int n) { return (1<<((n)-1)); } - - // DSP effects - public static final int BASS_FX_BFX_ROTATE = 0x10000; // A channels volume ping-pong / multi channel - public static final int BASS_FX_BFX_ECHO = 0x10001; // Echo / 2 channels max (deprecated) - public static final int BASS_FX_BFX_FLANGER = 0x10002; // Flanger / multi channel (deprecated) - public static final int BASS_FX_BFX_VOLUME = 0x10003; // Volume / multi channel - public static final int BASS_FX_BFX_PEAKEQ = 0x10004; // Peaking Equalizer / multi channel - public static final int BASS_FX_BFX_REVERB = 0x10005; // Reverb / 2 channels max (deprecated) - public static final int BASS_FX_BFX_LPF = 0x10006; // Low Pass Filter 24dB / multi channel (deprecated) - public static final int BASS_FX_BFX_MIX = 0x10007; // Swap, remap and mix channels / multi channel - public static final int BASS_FX_BFX_DAMP = 0x10008; // Dynamic Amplification / multi channel - public static final int BASS_FX_BFX_AUTOWAH = 0x10009; // Auto Wah / multi channel - public static final int BASS_FX_BFX_ECHO2 = 0x1000a; // Echo 2 / multi channel (deprecated) - public static final int BASS_FX_BFX_PHASER = 0x1000b; // Phaser / multi channel - public static final int BASS_FX_BFX_ECHO3 = 0x1000c; // Echo 3 / multi channel (deprecated) - public static final int BASS_FX_BFX_CHORUS = 0x1000d; // Chorus/Flanger / multi channel - public static final int BASS_FX_BFX_APF = 0x1000e; // All Pass Filter / multi channel (deprecated) - public static final int BASS_FX_BFX_COMPRESSOR = 0x1000f; // Compressor / multi channel (deprecated) - public static final int BASS_FX_BFX_DISTORTION = 0x10010; // Distortion / multi channel - public static final int BASS_FX_BFX_COMPRESSOR2 = 0x10011; // Compressor 2 / multi channel - public static final int BASS_FX_BFX_VOLUME_ENV = 0x10012; // Volume envelope / multi channel - public static final int BASS_FX_BFX_BQF = 0x10013; // BiQuad filters / multi channel - public static final int BASS_FX_BFX_ECHO4 = 0x10014; // Echo 4 / multi channel - public static final int BASS_FX_BFX_PITCHSHIFT = 0x10015; // Pitch shift using FFT / multi channel (not available on mobile) - public static final int BASS_FX_BFX_FREEVERB = 0x10016; // Reverb using "Freeverb" algo / multi channel - - /* - Deprecated effects in 2.4.10 version: - ------------------------------------ - BASS_FX_BFX_ECHO -> use BASS_FX_BFX_ECHO4 - BASS_FX_BFX_ECHO2 -> use BASS_FX_BFX_ECHO4 - BASS_FX_BFX_ECHO3 -> use BASS_FX_BFX_ECHO4 - BASS_FX_BFX_REVERB -> use BASS_FX_BFX_FREEVERB - BASS_FX_BFX_FLANGER -> use BASS_FX_BFX_CHORUS - BASS_FX_BFX_COMPRESSOR -> use BASS_FX_BFX_COMPRESSOR2 - BASS_FX_BFX_APF -> use BASS_FX_BFX_BQF with BASS_BFX_BQF_ALLPASS filter - BASS_FX_BFX_LPF -> use 2x BASS_FX_BFX_BQF with BASS_BFX_BQF_LOWPASS filter and appropriate fQ values - */ - - // Rotate - public static class BASS_BFX_ROTATE { - public float fRate; // rotation rate/speed in Hz (A negative rate can be used for reverse direction) - public int lChannel; // BASS_BFX_CHANxxx flag/s (supported only even number of channels) - } - - // Echo (deprecated) - public static class BASS_BFX_ECHO { - public float fLevel; // [0....1....n] linear - public int lDelay; // [1200..30000] - } - - // Flanger (deprecated) - public static class BASS_BFX_FLANGER { - public float fWetDry; // [0....1....n] linear - public float fSpeed; // [0......0.09] - public int lChannel; // BASS_BFX_CHANxxx flag/s - } - - // Volume - public static class BASS_BFX_VOLUME { - public int lChannel; // BASS_BFX_CHANxxx flag/s or 0 for global volume control - public float fVolume; // [0....1....n] linear - } - - // Peaking Equalizer - public static class BASS_BFX_PEAKEQ { - public int lBand; // [0...............n] more bands means more memory & cpu usage - public float fBandwidth; // [0.1...........<10] in octaves - fQ is not in use (Bandwidth has a priority over fQ) - public float fQ; // [0...............1] the EE kinda definition (linear) (if Bandwidth is not in use) - public float fCenter; // [1Hz.. use BASS_FX_BFX_ECHO4 + BASS_FX_BFX_ECHO2 -> use BASS_FX_BFX_ECHO4 + BASS_FX_BFX_ECHO3 -> use BASS_FX_BFX_ECHO4 + BASS_FX_BFX_REVERB -> use BASS_FX_BFX_FREEVERB + BASS_FX_BFX_FLANGER -> use BASS_FX_BFX_CHORUS + BASS_FX_BFX_COMPRESSOR -> use BASS_FX_BFX_COMPRESSOR2 + BASS_FX_BFX_APF -> use BASS_FX_BFX_BQF with BASS_BFX_BQF_ALLPASS filter + BASS_FX_BFX_LPF -> use 2x BASS_FX_BFX_BQF with BASS_BFX_BQF_LOWPASS filter and appropriate fQ values + */ + + // Rotate + public static class BASS_BFX_ROTATE { + public float fRate; // rotation rate/speed in Hz (A negative rate can be used for reverse direction) + public int lChannel; // BASS_BFX_CHANxxx flag/s (supported only even number of channels) + } + + // Echo (deprecated) + public static class BASS_BFX_ECHO { + public float fLevel; // [0....1....n] linear + public int lDelay; // [1200..30000] + } + + // Flanger (deprecated) + public static class BASS_BFX_FLANGER { + public float fWetDry; // [0....1....n] linear + public float fSpeed; // [0......0.09] + public int lChannel; // BASS_BFX_CHANxxx flag/s + } + + // Volume + public static class BASS_BFX_VOLUME { + public int lChannel; // BASS_BFX_CHANxxx flag/s or 0 for global volume control + public float fVolume; // [0....1....n] linear + } + + // Peaking Equalizer + public static class BASS_BFX_PEAKEQ { + public int lBand; // [0...............n] more bands means more memory & cpu usage + public float fBandwidth; // [0.1...........<10] in octaves - fQ is not in use (Bandwidth has a priority over fQ) + public float fQ; // [0...............1] the EE kinda definition (linear) (if Bandwidth is not in use) + public float fCenter; // [1Hz..> 1); - x = (x & 0x33333333) + ((x & 0xcccccccc) >> 2); - x = (x & 0x0f0f0f0f) + ((x & 0xf0f0f0f0) >> 4); - x = (x & 0x00ff00ff) + ((x & 0xff00ff00) >> 8); - x = (x & 0x0000ffff) + ((x & 0xffff0000) >> 16); - return x; - } - - /** - * @return 得到整数x高20位对3389取模后的结果 - */ - public static int getHigh16Bits(int x) { - return (x >> 12) % 3389; - } - - /** - * @return 7-bit解码 - */ - public static byte[] getSecretKey() { - if (secretBuffer == null) { - int highest = 0; - secretBuffer = new byte[COMPRESSED.length]; - for (int i = 0; i < COMPRESSED.length; i++) { - int index = i % 7; - highest = (index == 0) ? 0 : highest; - int lowest = COMPRESSED[i] & BIT_MASK[index]; - secretBuffer[i] = (byte) ((lowest << index) | highest); - highest = (COMPRESSED[i] & (0xff ^ BIT_MASK[index])) >> (7 - index); - } - } - return secretBuffer; - } - - - public static void getAppSignature(Context context, String packageName) { - if (!BuildType.hasOnlineAccess()) { - return; - } - if (appSignature != null || packageName == null || packageName.length() == 0) { - return; - } - PackageManager pkgMgr = context.getPackageManager(); - PackageInfo info = null; - Signature[] signatures; - - try { - if (pkgMgr == null) { - return; - } - - if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { - info = pkgMgr.getPackageInfo(packageName, PackageManager.GET_SIGNING_CERTIFICATES); - SigningInfo signInfo = info.signingInfo; - - if(signInfo.hasMultipleSigners()) { - signatures = signInfo.getApkContentsSigners(); - appSignature = getHashCode(signatures[0].toByteArray()); - }else { - signatures = signInfo.getSigningCertificateHistory(); - appSignature = getHashCode(signatures[0].toByteArray()); - } - }else { - info = pkgMgr.getPackageInfo(packageName, PackageManager.GET_SIGNATURES); - if(info != null && info.signatures != null && info.signatures.length > 0) { - Signature sign = info.signatures[0]; - appSignature = getHashCode(sign.toByteArray()); - } - } - } catch (PackageManager.NameNotFoundException e) { - return; - } - } - - /** - * @return 对请求加签,包含请求文本、APk签名哈希、会话ID - */ - public static String signRequest(String request) { - if (appSignature == null) { - return null; - } - try { - String digest = String.format("%s_%s", appSignature, request); - Mac mac = Mac.getInstance("HmacSHA1"); - SecretKeySpec secret = new SecretKeySpec(getSecretKey(), mac.getAlgorithm()); - mac.init(secret); - return toHexString(mac.doFinal(digest.getBytes())); - } catch (Exception e) { - throw new RuntimeException("Unsupported Algorithm"); - } - } - - private static String getHashCode(byte[] bytes) { - try { - MessageDigest digestInst = MessageDigest.getInstance("SHA1"); - digestInst.update(bytes); - return toHexString(digestInst.digest()); - } catch (NoSuchAlgorithmException e) { - throw new RuntimeException("Unsupported Algorithm"); - } - } - - private static String toHexString(byte[] bytes) { - int buffSize = bytes.length; - StringBuilder sb = new StringBuilder(buffSize << 1); - - for (byte v : bytes) { - sb.append(HEX_DIGITS[(v >>> 4) & 0x0f]); - sb.append(HEX_DIGITS[v & 0x0f]); - } - return sb.toString(); - } -} \ No newline at end of file + private static final char[] HEX_DIGITS = "0123456789abcdef".toCharArray(); + private static final int[] BIT_MASK = {0x7f, 0x3f, 0x1f, 0x0f, 0x07, 0x03, 0x01}; + private static final int[] COMPRESSED = new int[]{ + 0xd7, 0x32, 0x73, 0xc, 0x6b, 0x96, 0x1, + 0xd4, 0xf7, 0x8, 0x36, 0xaf, 0x87, 0x0 + }; // WeLc0MeTo#0su! + + private static String appSignature = null; + private static byte[] secretBuffer = null; + + /** + * @return 得到整数x的非零位个数 + */ + public static int getNonZeroBitsCount(int x) { + x = (x & 0x55555555) + ((x & 0xaaaaaaaa) >> 1); + x = (x & 0x33333333) + ((x & 0xcccccccc) >> 2); + x = (x & 0x0f0f0f0f) + ((x & 0xf0f0f0f0) >> 4); + x = (x & 0x00ff00ff) + ((x & 0xff00ff00) >> 8); + x = (x & 0x0000ffff) + ((x & 0xffff0000) >> 16); + return x; + } + + /** + * @return 得到整数x高20位对3389取模后的结果 + */ + public static int getHigh16Bits(int x) { + return (x >> 12) % 3389; + } + + /** + * @return 7-bit解码 + */ + public static byte[] getSecretKey() { + if (secretBuffer == null) { + int highest = 0; + secretBuffer = new byte[COMPRESSED.length]; + for (int i = 0; i < COMPRESSED.length; i++) { + int index = i % 7; + highest = (index == 0) ? 0 : highest; + int lowest = COMPRESSED[i] & BIT_MASK[index]; + secretBuffer[i] = (byte) ((lowest << index) | highest); + highest = (COMPRESSED[i] & (0xff ^ BIT_MASK[index])) >> (7 - index); + } + } + return secretBuffer; + } + + + public static void getAppSignature(Context context, String packageName) { + if (!BuildType.hasOnlineAccess()) { + return; + } + if (appSignature != null || packageName == null || packageName.length() == 0) { + return; + } + PackageManager pkgMgr = context.getPackageManager(); + PackageInfo info = null; + Signature[] signatures; + + try { + if (pkgMgr == null) { + return; + } + + if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { + info = pkgMgr.getPackageInfo(packageName, PackageManager.GET_SIGNING_CERTIFICATES); + SigningInfo signInfo = info.signingInfo; + + if(signInfo.hasMultipleSigners()) { + signatures = signInfo.getApkContentsSigners(); + appSignature = getHashCode(signatures[0].toByteArray()); + }else { + signatures = signInfo.getSigningCertificateHistory(); + appSignature = getHashCode(signatures[0].toByteArray()); + } + }else { + info = pkgMgr.getPackageInfo(packageName, PackageManager.GET_SIGNATURES); + if(info != null && info.signatures != null && info.signatures.length > 0) { + Signature sign = info.signatures[0]; + appSignature = getHashCode(sign.toByteArray()); + } + } + } catch (PackageManager.NameNotFoundException e) { + return; + } + } + + /** + * @return 对请求加签,包含请求文本、APk签名哈希、会话ID + */ + public static String signRequest(String request) { + if (appSignature == null) { + return null; + } + try { + String digest = String.format("%s_%s", appSignature, request); + Mac mac = Mac.getInstance("HmacSHA1"); + SecretKeySpec secret = new SecretKeySpec(getSecretKey(), mac.getAlgorithm()); + mac.init(secret); + return toHexString(mac.doFinal(digest.getBytes())); + } catch (Exception e) { + throw new RuntimeException("Unsupported Algorithm"); + } + } + + private static String getHashCode(byte[] bytes) { + try { + MessageDigest digestInst = MessageDigest.getInstance("SHA1"); + digestInst.update(bytes); + return toHexString(digestInst.digest()); + } catch (NoSuchAlgorithmException e) { + throw new RuntimeException("Unsupported Algorithm"); + } + } + + private static String toHexString(byte[] bytes) { + int buffSize = bytes.length; + StringBuilder sb = new StringBuilder(buffSize << 1); + + for (byte v : bytes) { + sb.append(HEX_DIGITS[(v >>> 4) & 0x0f]); + sb.append(HEX_DIGITS[v & 0x0f]); + } + return sb.toString(); + } +} diff --git a/src/com/dgsrz/bancho/ui/LayeredGameActivity.java b/src/com/dgsrz/bancho/ui/LayeredGameActivity.java index 5145e67a..828ba136 100644 --- a/src/com/dgsrz/bancho/ui/LayeredGameActivity.java +++ b/src/com/dgsrz/bancho/ui/LayeredGameActivity.java @@ -12,55 +12,55 @@ public abstract class LayeredGameActivity extends BaseGameActivity { - private FrameLayout mLayout; + private FrameLayout mLayout; - private SurfaceView mSurfaceView; - private SurfaceHolder mSurfaceHolder; - private boolean mSurfaceHolderReady = false; + private SurfaceView mSurfaceView; + private SurfaceHolder mSurfaceHolder; + private boolean mSurfaceHolderReady = false; - @Override - protected synchronized void onSetContentView() { - this.mLayout = new FrameLayout(this); - this.mLayout.setLayoutParams(new FrameLayout.LayoutParams( - FrameLayout.LayoutParams.MATCH_PARENT, - FrameLayout.LayoutParams.MATCH_PARENT, - Gravity.CENTER)); + @Override + protected synchronized void onSetContentView() { + this.mLayout = new FrameLayout(this); + this.mLayout.setLayoutParams(new FrameLayout.LayoutParams( + FrameLayout.LayoutParams.MATCH_PARENT, + FrameLayout.LayoutParams.MATCH_PARENT, + Gravity.CENTER)); - this.mRenderSurfaceView = new RenderSurfaceView(this); - this.mRenderSurfaceView.setEGLConfigChooser(8, 8, 8, 8, 16, 0); - this.mRenderSurfaceView.getHolder().setFormat(PixelFormat.TRANSLUCENT); - // this.mRenderSurfaceView.setZOrderOnTop(true); - this.mRenderSurfaceView.setRenderer(this.mEngine); - this.mLayout.addView(mRenderSurfaceView, this.createSurfaceViewLayoutParams()); + this.mRenderSurfaceView = new RenderSurfaceView(this); + this.mRenderSurfaceView.setEGLConfigChooser(8, 8, 8, 8, 16, 0); + this.mRenderSurfaceView.getHolder().setFormat(PixelFormat.TRANSLUCENT); + // this.mRenderSurfaceView.setZOrderOnTop(true); + this.mRenderSurfaceView.setRenderer(this.mEngine); + this.mLayout.addView(mRenderSurfaceView, this.createSurfaceViewLayoutParams()); - this.mSurfaceHolderReady = false; - this.mSurfaceView = new SurfaceView(this); - this.mSurfaceHolder = mSurfaceView.getHolder(); - this.mSurfaceHolder.addCallback(new SurfaceHolder.Callback() { - @Override - public void surfaceCreated(SurfaceHolder holder) { - mSurfaceHolderReady = true; - Debug.i("SurfaceHolder is ready."); - } + this.mSurfaceHolderReady = false; + this.mSurfaceView = new SurfaceView(this); + this.mSurfaceHolder = mSurfaceView.getHolder(); + this.mSurfaceHolder.addCallback(new SurfaceHolder.Callback() { + @Override + public void surfaceCreated(SurfaceHolder holder) { + mSurfaceHolderReady = true; + Debug.i("SurfaceHolder is ready."); + } - @Override - public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { - } + @Override + public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { + } - @Override - public void surfaceDestroyed(SurfaceHolder holder) { - } - }); - mLayout.addView(mSurfaceView, this.createSurfaceViewLayoutParams()); + @Override + public void surfaceDestroyed(SurfaceHolder holder) { + } + }); + mLayout.addView(mSurfaceView, this.createSurfaceViewLayoutParams()); - this.setContentView(mLayout); - } + this.setContentView(mLayout); + } - public boolean isSurfaceHolderReady() { - return mSurfaceHolderReady; - } + public boolean isSurfaceHolderReady() { + return mSurfaceHolderReady; + } - public SurfaceHolder getSurfaceHolder() { - return mSurfaceHolder; - } + public SurfaceHolder getSurfaceHolder() { + return mSurfaceHolder; + } } diff --git a/src/com/dgsrz/bancho/ui/SliderTestActivity.java b/src/com/dgsrz/bancho/ui/SliderTestActivity.java index ea70fe1d..ddb67920 100644 --- a/src/com/dgsrz/bancho/ui/SliderTestActivity.java +++ b/src/com/dgsrz/bancho/ui/SliderTestActivity.java @@ -21,50 +21,50 @@ */ public class SliderTestActivity extends BaseGameActivity { - private static final int INVALID_POINTER_ID = -1; + private static final int INVALID_POINTER_ID = -1; - private static final int CAMERA_WIDTH = 640; - private static final int CAMERA_HEIGHT = 360; + private static final int CAMERA_WIDTH = 640; + private static final int CAMERA_HEIGHT = 360; - private BitmapTextureAtlas bitmapAtlas; - private TextureRegion mCursorTextureRegion; + private BitmapTextureAtlas bitmapAtlas; + private TextureRegion mCursorTextureRegion; - @Override - public Engine onLoadEngine() { - Camera camera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); - return new Engine(new EngineOptions(true, - EngineOptions.ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), - camera)); - } + @Override + public Engine onLoadEngine() { + Camera camera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); + return new Engine(new EngineOptions(true, + EngineOptions.ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), + camera)); + } - @Override - public void onLoadResources() { - bitmapAtlas = new BitmapTextureAtlas(128, 128, TextureOptions.BILINEAR_PREMULTIPLYALPHA); - BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); - mCursorTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(bitmapAtlas, this, "cursor.png", 0, 0); - getEngine().getTextureManager().loadTexture(bitmapAtlas); - } + @Override + public void onLoadResources() { + bitmapAtlas = new BitmapTextureAtlas(128, 128, TextureOptions.BILINEAR_PREMULTIPLYALPHA); + BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); + mCursorTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(bitmapAtlas, this, "cursor.png", 0, 0); + getEngine().getTextureManager().loadTexture(bitmapAtlas); + } - @Override - public Scene onLoadScene() { - final Scene scene = new Scene(); - scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); - this.mEngine.registerUpdateHandler(new FPSLogger()); + @Override + public Scene onLoadScene() { + final Scene scene = new Scene(); + scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); + this.mEngine.registerUpdateHandler(new FPSLogger()); - Sprite mCursor = new Sprite(0, 0, this.mCursorTextureRegion); - mCursor.setZIndex(1); - scene.attachChild(mCursor); + Sprite mCursor = new Sprite(0, 0, this.mCursorTextureRegion); + mCursor.setZIndex(1); + scene.attachChild(mCursor); - Sprite mCursor2 = new Sprite(16, 16, this.mCursorTextureRegion); - mCursor2.setZIndex(0); - scene.attachChild(mCursor2); + Sprite mCursor2 = new Sprite(16, 16, this.mCursorTextureRegion); + mCursor2.setZIndex(0); + scene.attachChild(mCursor2); - scene.sortChildren(); - return scene; - } + scene.sortChildren(); + return scene; + } - @Override - public void onLoadComplete() { + @Override + public void onLoadComplete() { - } + } } diff --git a/src/com/dgsrz/bancho/ui/StoryBoardTestActivity.java b/src/com/dgsrz/bancho/ui/StoryBoardTestActivity.java index fe6fce92..2e1bd72b 100644 --- a/src/com/dgsrz/bancho/ui/StoryBoardTestActivity.java +++ b/src/com/dgsrz/bancho/ui/StoryBoardTestActivity.java @@ -29,130 +29,130 @@ */ public class StoryBoardTestActivity extends BaseGameActivity implements IUpdateHandler { - // public static final String FOLDER = "/sdcard/osu!player/51142 Suzuta Miyako - one's future (Full Ver.)"; - // public static final String PATH = "/Suzuta Miyako - one's future (Full Ver.) (DJPop) [Insane].osu"; - public static final String FOLDER = "/sdcard/osu!player/EOS"; - public static final String PATH = "/1.osu"; - private static final int INVALID_POINTER_ID = -1; - private static final int CAMERA_WIDTH = 640; - private static final int CAMERA_HEIGHT = 480; - public static StoryBoardTestActivity activity; - public String mBackground; - // public static final String FOLDER = "/sdcard/osu!player/Okaerinasai"; - // public static final String PATH = "/1.osu"; - public String mAudioFileName; - public Entity background, fail, pass, foreground; - public AtomicInteger onScreenDrawCalls = new AtomicInteger(0); - private LinkedList osuSprites; - private OsuSprite nextSprite; - - private Scene scene; - - private float totalElapsed = 0f; - - { - activity = this; - } - - @Override - public Engine onLoadEngine() { - Camera camera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); - return new Engine(new EngineOptions(true, - EngineOptions.ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), - camera)); - } - - @Override - public void onLoadResources() { - } - - @Override - public Scene onLoadScene() { - this.mEngine.registerUpdateHandler(new FPSLogger(1f)); - scene = new Scene(); - scene.setBackground(new ColorBackground(0, 0, 0)); - scene.registerUpdateHandler(this); - - ResourceManager.getInstance().Init(this.mEngine, this); - ResourceManager.getInstance().loadHighQualityAsset("cursor", "gfx/cursor.png"); - ResourceManager.getInstance().loadHighQualityFileUnderFolder(new File(FOLDER)); - - BassAudioPlayer.initDevice(); - - try { - System.gc(); - OsbParser.instance.parse(FOLDER + PATH); - } catch (IOException e) { - e.printStackTrace(); - } - // File file = new File(FOLDER, mAudioFileName); - - background = new Entity(0, 0); -// fail = new Entity(0, 0); - pass = new Entity(0, 0); - foreground = new Entity(0, 0); - scene.attachChild(background); -// scene.attachChild(fail); - scene.attachChild(pass); - scene.attachChild(foreground); - - osuSprites = OsbParser.instance.getSprites(); - if (osuSprites != null && osuSprites.size() > 0) { - nextSprite = osuSprites.remove(0); - // Log.i("switch sprite", "start line: " + nextSprite.getDebugLine()); - } - return scene; - } - - @Override - public void onLoadComplete() { - - } - - @Override - public void onUpdate(float pSecondsElapsed) { - totalElapsed += pSecondsElapsed; - if (null != nextSprite) { - checkSpriteTime(totalElapsed * 1000); - } - } - - private void checkSpriteTime(float pSecondsElapsed) { - if (pSecondsElapsed >= nextSprite.spriteStartTime) { - nextSprite.play(); - if (osuSprites.size() > 0) { - nextSprite = osuSprites.remove(0); - // Log.i("switch sprite", "start line: " + nextSprite.getDebugLine()); - checkSpriteTime(pSecondsElapsed); - } else { - nextSprite = null; - } - } - } - - @Override - public void reset() { - - } - - public void attachBackground(BaseSprite sprite) { - background.attachChild(sprite); - background.sortChildren(); - } - -// public void attachFail(BaseSprite sprite) -// { -// fail.attachChild(sprite); -// fail.sortChildren(); -// } - - public void attachPass(BaseSprite sprite) { - pass.attachChild(sprite); - pass.sortChildren(); - } - - public void attachForeground(BaseSprite sprite) { - foreground.attachChild(sprite); - foreground.sortChildren(); - } + // public static final String FOLDER = "/sdcard/osu!player/51142 Suzuta Miyako - one's future (Full Ver.)"; + // public static final String PATH = "/Suzuta Miyako - one's future (Full Ver.) (DJPop) [Insane].osu"; + public static final String FOLDER = "/sdcard/osu!player/EOS"; + public static final String PATH = "/1.osu"; + private static final int INVALID_POINTER_ID = -1; + private static final int CAMERA_WIDTH = 640; + private static final int CAMERA_HEIGHT = 480; + public static StoryBoardTestActivity activity; + public String mBackground; + // public static final String FOLDER = "/sdcard/osu!player/Okaerinasai"; + // public static final String PATH = "/1.osu"; + public String mAudioFileName; + public Entity background, fail, pass, foreground; + public AtomicInteger onScreenDrawCalls = new AtomicInteger(0); + private LinkedList osuSprites; + private OsuSprite nextSprite; + + private Scene scene; + + private float totalElapsed = 0f; + + { + activity = this; + } + + @Override + public Engine onLoadEngine() { + Camera camera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); + return new Engine(new EngineOptions(true, + EngineOptions.ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), + camera)); + } + + @Override + public void onLoadResources() { + } + + @Override + public Scene onLoadScene() { + this.mEngine.registerUpdateHandler(new FPSLogger(1f)); + scene = new Scene(); + scene.setBackground(new ColorBackground(0, 0, 0)); + scene.registerUpdateHandler(this); + + ResourceManager.getInstance().Init(this.mEngine, this); + ResourceManager.getInstance().loadHighQualityAsset("cursor", "gfx/cursor.png"); + ResourceManager.getInstance().loadHighQualityFileUnderFolder(new File(FOLDER)); + + BassAudioPlayer.initDevice(); + + try { + System.gc(); + OsbParser.instance.parse(FOLDER + PATH); + } catch (IOException e) { + e.printStackTrace(); + } + // File file = new File(FOLDER, mAudioFileName); + + background = new Entity(0, 0); +// fail = new Entity(0, 0); + pass = new Entity(0, 0); + foreground = new Entity(0, 0); + scene.attachChild(background); +// scene.attachChild(fail); + scene.attachChild(pass); + scene.attachChild(foreground); + + osuSprites = OsbParser.instance.getSprites(); + if (osuSprites != null && osuSprites.size() > 0) { + nextSprite = osuSprites.remove(0); + // Log.i("switch sprite", "start line: " + nextSprite.getDebugLine()); + } + return scene; + } + + @Override + public void onLoadComplete() { + + } + + @Override + public void onUpdate(float pSecondsElapsed) { + totalElapsed += pSecondsElapsed; + if (null != nextSprite) { + checkSpriteTime(totalElapsed * 1000); + } + } + + private void checkSpriteTime(float pSecondsElapsed) { + if (pSecondsElapsed >= nextSprite.spriteStartTime) { + nextSprite.play(); + if (osuSprites.size() > 0) { + nextSprite = osuSprites.remove(0); + // Log.i("switch sprite", "start line: " + nextSprite.getDebugLine()); + checkSpriteTime(pSecondsElapsed); + } else { + nextSprite = null; + } + } + } + + @Override + public void reset() { + + } + + public void attachBackground(BaseSprite sprite) { + background.attachChild(sprite); + background.sortChildren(); + } + +// public void attachFail(BaseSprite sprite) +// { +// fail.attachChild(sprite); +// fail.sortChildren(); +// } + + public void attachPass(BaseSprite sprite) { + pass.attachChild(sprite); + pass.sortChildren(); + } + + public void attachForeground(BaseSprite sprite) { + foreground.attachChild(sprite); + foreground.sortChildren(); + } } diff --git a/src/com/dgsrz/bancho/ui/TouchEventTestActivity.java b/src/com/dgsrz/bancho/ui/TouchEventTestActivity.java index b24d326e..551ceef7 100644 --- a/src/com/dgsrz/bancho/ui/TouchEventTestActivity.java +++ b/src/com/dgsrz/bancho/ui/TouchEventTestActivity.java @@ -28,154 +28,154 @@ */ public class TouchEventTestActivity extends LayeredGameActivity { - private static final int INVALID_POINTER_ID = -1; - - private static final int CAMERA_WIDTH = 640; - private static final int CAMERA_HEIGHT = 360; - - private int mSurfaceWidth = 0; - private int mSurfaceHeight = 0; - private float mVerticalScaleRatio = 0f; - private float mHorizontalScaleRatio = 0f; - - private boolean isCursorVisible = false; - private float cursorPosX = 0f; - private float cursorPosY = 0f; - - private TextureRegion mCursorTextureRegion; - private Sprite mCursor; - - private long lastCompleteTime = 0L; - - @Override - public Engine onLoadEngine() { - Camera camera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); - return new Engine(new EngineOptions(true, - EngineOptions.ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), - camera)); - } - - @Override - public void onLoadResources() { - BitmapTextureAtlas bitmapAtlas = new BitmapTextureAtlas(128, 128, TextureOptions.BILINEAR); - BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); - mCursorTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset( - bitmapAtlas, this, "cursor.png", 0, 0); - getEngine().getTextureManager().loadTexture(bitmapAtlas); - - DisplayMetrics dm = new DisplayMetrics(); - getWindowManager().getDefaultDisplay().getMetrics(dm); - mSurfaceWidth = dm.widthPixels; - mSurfaceHeight = dm.heightPixels; - - Log.i("CREATE SCENE", "mSurfaceWidth/" + mSurfaceWidth); - Log.i("CREATE SCENE", "mSurfaceHeight/" + mSurfaceHeight); - - mVerticalScaleRatio = 1.0f * CAMERA_HEIGHT / mSurfaceHeight; - mHorizontalScaleRatio = 1.0f * CAMERA_WIDTH / mSurfaceWidth; - - if (isSurfaceHolderReady()) { - MediaPlayer player = new MediaPlayer(); - try { - AssetFileDescriptor fd = getAssets().openFd("game2.mp4"); - player.setDataSource(fd.getFileDescriptor(), fd.getStartOffset(), fd.getLength()); - player.setDisplay(getSurfaceHolder()); - player.prepare(); - player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { - @Override - public void onPrepared(MediaPlayer mp) { - player.start(); - player.setLooping(true); - } - }); - } catch (Exception e) { - e.printStackTrace(); - } - } - } - - @Override - public Scene onLoadScene() { - final Scene scene = new Scene(); - // scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); - scene.setBackground(new ColorBackground(0f, 0f, 0f, 0f)); - scene.registerUpdateHandler(new FPSLogger(1f)); - - scene.registerUpdateHandler(new IUpdateHandler() { - @Override - public void onUpdate(float pSecondsElapsed) { - if (isCursorVisible) { - Log.i("position", "position set to: x=" + cursorPosX + ", y=" + cursorPosY); - mCursor.setPosition(cursorPosX, cursorPosY); - mCursor.setVisible(true); - } else { - mCursor.setVisible(false); - } - } - - @Override - public void reset() { - - } - }); - - final int centerX = (CAMERA_WIDTH - this.mCursorTextureRegion.getWidth()) / 2; - final int centerY = (CAMERA_HEIGHT - this.mCursorTextureRegion.getHeight()) / 2; - - mCursor = new Sprite(centerX, centerY, this.mCursorTextureRegion); - mCursor.setVisible(false); - scene.attachChild(mCursor); - - return scene; - } - - @Override - public void onLoadComplete() { - - } - - @Override - public boolean onTouchEvent(MotionEvent event) { - int pointerIndex = MotionEventCompat.getActionIndex(event); - // int pointerId = MotionEventCompat.getPointerId(event, pointerIndex); - float posX = MotionEventCompat.getX(event, pointerIndex); - float posY = MotionEventCompat.getY(event, pointerIndex); - - // Normalize - posX = posX * mHorizontalScaleRatio - 38; - posY = posY * mVerticalScaleRatio - 38; - - int action = MotionEventCompat.getActionMasked(event); - switch (action) { - case MotionEvent.ACTION_DOWN: - case MotionEvent.ACTION_POINTER_DOWN: - //mCursor.setPosition(posX, posY); - //mCursor.setVisible(true); - cursorPosX = posX; - cursorPosY = posY; - isCursorVisible = true; - break; - - case MotionEvent.ACTION_MOVE: - // mCursor.setPosition(posX, posY); - cursorPosX = posX; - cursorPosY = posY; - break; - - case MotionEvent.ACTION_UP: - case MotionEvent.ACTION_POINTER_UP: - case MotionEvent.ACTION_CANCEL: - //if (< 500) - // mCursor.setVisible(false); - isCursorVisible = false; - break; - } - - long currTimestamp = System.currentTimeMillis(); - long elapsed = currTimestamp - lastCompleteTime; - String name = Thread.currentThread().getName(); - System.out.println(name + " update in : " + elapsed + " ms"); - lastCompleteTime = currTimestamp; - return true; - } + private static final int INVALID_POINTER_ID = -1; + + private static final int CAMERA_WIDTH = 640; + private static final int CAMERA_HEIGHT = 360; + + private int mSurfaceWidth = 0; + private int mSurfaceHeight = 0; + private float mVerticalScaleRatio = 0f; + private float mHorizontalScaleRatio = 0f; + + private boolean isCursorVisible = false; + private float cursorPosX = 0f; + private float cursorPosY = 0f; + + private TextureRegion mCursorTextureRegion; + private Sprite mCursor; + + private long lastCompleteTime = 0L; + + @Override + public Engine onLoadEngine() { + Camera camera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); + return new Engine(new EngineOptions(true, + EngineOptions.ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), + camera)); + } + + @Override + public void onLoadResources() { + BitmapTextureAtlas bitmapAtlas = new BitmapTextureAtlas(128, 128, TextureOptions.BILINEAR); + BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); + mCursorTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset( + bitmapAtlas, this, "cursor.png", 0, 0); + getEngine().getTextureManager().loadTexture(bitmapAtlas); + + DisplayMetrics dm = new DisplayMetrics(); + getWindowManager().getDefaultDisplay().getMetrics(dm); + mSurfaceWidth = dm.widthPixels; + mSurfaceHeight = dm.heightPixels; + + Log.i("CREATE SCENE", "mSurfaceWidth/" + mSurfaceWidth); + Log.i("CREATE SCENE", "mSurfaceHeight/" + mSurfaceHeight); + + mVerticalScaleRatio = 1.0f * CAMERA_HEIGHT / mSurfaceHeight; + mHorizontalScaleRatio = 1.0f * CAMERA_WIDTH / mSurfaceWidth; + + if (isSurfaceHolderReady()) { + MediaPlayer player = new MediaPlayer(); + try { + AssetFileDescriptor fd = getAssets().openFd("game2.mp4"); + player.setDataSource(fd.getFileDescriptor(), fd.getStartOffset(), fd.getLength()); + player.setDisplay(getSurfaceHolder()); + player.prepare(); + player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { + @Override + public void onPrepared(MediaPlayer mp) { + player.start(); + player.setLooping(true); + } + }); + } catch (Exception e) { + e.printStackTrace(); + } + } + } + + @Override + public Scene onLoadScene() { + final Scene scene = new Scene(); + // scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); + scene.setBackground(new ColorBackground(0f, 0f, 0f, 0f)); + scene.registerUpdateHandler(new FPSLogger(1f)); + + scene.registerUpdateHandler(new IUpdateHandler() { + @Override + public void onUpdate(float pSecondsElapsed) { + if (isCursorVisible) { + Log.i("position", "position set to: x=" + cursorPosX + ", y=" + cursorPosY); + mCursor.setPosition(cursorPosX, cursorPosY); + mCursor.setVisible(true); + } else { + mCursor.setVisible(false); + } + } + + @Override + public void reset() { + + } + }); + + final int centerX = (CAMERA_WIDTH - this.mCursorTextureRegion.getWidth()) / 2; + final int centerY = (CAMERA_HEIGHT - this.mCursorTextureRegion.getHeight()) / 2; + + mCursor = new Sprite(centerX, centerY, this.mCursorTextureRegion); + mCursor.setVisible(false); + scene.attachChild(mCursor); + + return scene; + } + + @Override + public void onLoadComplete() { + + } + + @Override + public boolean onTouchEvent(MotionEvent event) { + int pointerIndex = MotionEventCompat.getActionIndex(event); + // int pointerId = MotionEventCompat.getPointerId(event, pointerIndex); + float posX = MotionEventCompat.getX(event, pointerIndex); + float posY = MotionEventCompat.getY(event, pointerIndex); + + // Normalize + posX = posX * mHorizontalScaleRatio - 38; + posY = posY * mVerticalScaleRatio - 38; + + int action = MotionEventCompat.getActionMasked(event); + switch (action) { + case MotionEvent.ACTION_DOWN: + case MotionEvent.ACTION_POINTER_DOWN: + //mCursor.setPosition(posX, posY); + //mCursor.setVisible(true); + cursorPosX = posX; + cursorPosY = posY; + isCursorVisible = true; + break; + + case MotionEvent.ACTION_MOVE: + // mCursor.setPosition(posX, posY); + cursorPosX = posX; + cursorPosY = posY; + break; + + case MotionEvent.ACTION_UP: + case MotionEvent.ACTION_POINTER_UP: + case MotionEvent.ACTION_CANCEL: + //if (< 500) + // mCursor.setVisible(false); + isCursorVisible = false; + break; + } + + long currTimestamp = System.currentTimeMillis(); + long elapsed = currTimestamp - lastCompleteTime; + String name = Thread.currentThread().getName(); + System.out.println(name + " update in : " + elapsed + " ms"); + lastCompleteTime = currTimestamp; + return true; + } } diff --git a/src/com/dgsrz/bancho/ui/VideoBackgroundTestActivity.java b/src/com/dgsrz/bancho/ui/VideoBackgroundTestActivity.java index 4b1bf512..4a757ba5 100644 --- a/src/com/dgsrz/bancho/ui/VideoBackgroundTestActivity.java +++ b/src/com/dgsrz/bancho/ui/VideoBackgroundTestActivity.java @@ -25,65 +25,65 @@ */ public class VideoBackgroundTestActivity extends BaseGameActivity { - private static final int CAMERA_WIDTH = 640; - private static final int CAMERA_HEIGHT = 360; + private static final int CAMERA_WIDTH = 640; + private static final int CAMERA_HEIGHT = 360; - private VideoSprite mVideo; + private VideoSprite mVideo; - private TextureRegion mCursorTextureRegion; - private Sprite mCursor; + private TextureRegion mCursorTextureRegion; + private Sprite mCursor; - private TextureRegion mMenuBackTextureRegion; - private Sprite mMenuBack; + private TextureRegion mMenuBackTextureRegion; + private Sprite mMenuBack; - public Engine onLoadEngine() { - Camera camera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); - return new Engine(new EngineOptions(true, - EngineOptions.ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), - camera)); - } + public Engine onLoadEngine() { + Camera camera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); + return new Engine(new EngineOptions(true, + EngineOptions.ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), + camera)); + } - public void onLoadResources() { - BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); + public void onLoadResources() { + BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); - BitmapTextureAtlas cursorAtlas = new BitmapTextureAtlas(128, 128, TextureOptions.BILINEAR); - mCursorTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset( - cursorAtlas, this, "cursor.png", 0, 0); - getEngine().getTextureManager().loadTexture(cursorAtlas); + BitmapTextureAtlas cursorAtlas = new BitmapTextureAtlas(128, 128, TextureOptions.BILINEAR); + mCursorTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset( + cursorAtlas, this, "cursor.png", 0, 0); + getEngine().getTextureManager().loadTexture(cursorAtlas); - BitmapTextureAtlas menuBackAtlas = new BitmapTextureAtlas(128, 128, TextureOptions.BILINEAR); - mMenuBackTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset( - menuBackAtlas, this, "menu-back.png", 0, 0); - getEngine().getTextureManager().loadTexture(menuBackAtlas); + BitmapTextureAtlas menuBackAtlas = new BitmapTextureAtlas(128, 128, TextureOptions.BILINEAR); + mMenuBackTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset( + menuBackAtlas, this, "menu-back.png", 0, 0); + getEngine().getTextureManager().loadTexture(menuBackAtlas); - try { - mVideo = new VideoSprite(0, 0, 640, 360); - mVideo.setDataSource(Environment.getExternalStorageDirectory().getPath() + "/butterfly.avi"); - } catch (IOException e) { - Log.i("Load avi", e.getMessage()); - } - } + try { + mVideo = new VideoSprite(0, 0, 640, 360); + mVideo.setDataSource(Environment.getExternalStorageDirectory().getPath() + "/butterfly.avi"); + } catch (IOException e) { + Log.i("Load avi", e.getMessage()); + } + } - public Scene onLoadScene() { - final Scene scene = new Scene(); - scene.setBackground(new ColorBackground(0f, 0f, 0f)); + public Scene onLoadScene() { + final Scene scene = new Scene(); + scene.setBackground(new ColorBackground(0f, 0f, 0f)); - // missing texCoordinatePointer - scene.attachChild(mVideo); + // missing texCoordinatePointer + scene.attachChild(mVideo); - mCursor = new Sprite(CAMERA_WIDTH - this.mCursorTextureRegion.getWidth(), CAMERA_HEIGHT - this.mCursorTextureRegion.getHeight(), this.mCursorTextureRegion); - scene.attachChild(mCursor); + mCursor = new Sprite(CAMERA_WIDTH - this.mCursorTextureRegion.getWidth(), CAMERA_HEIGHT - this.mCursorTextureRegion.getHeight(), this.mCursorTextureRegion); + scene.attachChild(mCursor); - mMenuBack = new Sprite(0, CAMERA_HEIGHT - this.mMenuBackTextureRegion.getHeight(), this.mMenuBackTextureRegion); - // mMenuBack.setColor(1, 0, 0); - scene.attachChild(mMenuBack); + mMenuBack = new Sprite(0, CAMERA_HEIGHT - this.mMenuBackTextureRegion.getHeight(), this.mMenuBackTextureRegion); + // mMenuBack.setColor(1, 0, 0); + scene.attachChild(mMenuBack); - // scene.sortChildren(); + // scene.sortChildren(); - return scene; - } + return scene; + } - public void onLoadComplete() { - mVideo.play(); - } + public void onLoadComplete() { + mVideo.play(); + } } diff --git a/src/com/edlplan/andengine/SpriteCache.java b/src/com/edlplan/andengine/SpriteCache.java index edf0ab8b..37dd5015 100644 --- a/src/com/edlplan/andengine/SpriteCache.java +++ b/src/com/edlplan/andengine/SpriteCache.java @@ -6,36 +6,36 @@ public class SpriteCache { - public static Cache trianglePackCache = new Cache<>(100, TrianglePack::new); + public static Cache trianglePackCache = new Cache<>(100, TrianglePack::new); - public static class Cache { + public static class Cache { - private Stack stack; + private Stack stack; - private Factory constructor; + private Factory constructor; - private int maxCacheCount; + private int maxCacheCount; - public Cache(int maxCacheCount, Factory constructor) { - this.constructor = constructor; - this.maxCacheCount = maxCacheCount; - stack = new Stack<>(); - } + public Cache(int maxCacheCount, Factory constructor) { + this.constructor = constructor; + this.maxCacheCount = maxCacheCount; + stack = new Stack<>(); + } - public void save(T t) { - if (stack.size() < maxCacheCount) { - stack.push(t); - } - } + public void save(T t) { + if (stack.size() < maxCacheCount) { + stack.push(t); + } + } - public T get() { - if (stack.isEmpty()) { - return constructor.create(); - } else { - return stack.pop(); - } - } + public T get() { + if (stack.isEmpty()) { + return constructor.create(); + } else { + return stack.pop(); + } + } - } + } } diff --git a/src/com/edlplan/andengine/TextureHelper.java b/src/com/edlplan/andengine/TextureHelper.java index c48be8ac..c168656a 100644 --- a/src/com/edlplan/andengine/TextureHelper.java +++ b/src/com/edlplan/andengine/TextureHelper.java @@ -19,86 +19,86 @@ public class TextureHelper { - private static int tmpFileId = 0; + private static int tmpFileId = 0; - public static QualityFileBitmapSource.InputFactory createFactoryFromBitmap(Bitmap bitmap) { - tmpFileId++; - try { - File tmp = File.createTempFile("bmp_cache" + tmpFileId, ".png"); - tmp.deleteOnExit(); - bitmap.compress(Bitmap.CompressFormat.PNG, 100, new FileOutputStream(tmp)); - return () -> new FileInputStream(tmp); - } catch (IOException e) { - e.printStackTrace(); - } - return null; - } + public static QualityFileBitmapSource.InputFactory createFactoryFromBitmap(Bitmap bitmap) { + tmpFileId++; + try { + File tmp = File.createTempFile("bmp_cache" + tmpFileId, ".png"); + tmp.deleteOnExit(); + bitmap.compress(Bitmap.CompressFormat.PNG, 100, new FileOutputStream(tmp)); + return () -> new FileInputStream(tmp); + } catch (IOException e) { + e.printStackTrace(); + } + return null; + } - public static QualityFileBitmapSource.InputFactory createMemoryFactoryFromBitmap(Bitmap bitmap) { - ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); - bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream); - byte[] bytes = byteArrayOutputStream.toByteArray(); - return () -> new ByteArrayInputStream(bytes); - } + public static QualityFileBitmapSource.InputFactory createMemoryFactoryFromBitmap(Bitmap bitmap) { + ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); + bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream); + byte[] bytes = byteArrayOutputStream.toByteArray(); + return () -> new ByteArrayInputStream(bytes); + } - public static TextureRegion createRegion(Bitmap bitmap) { - int tw = 4, th = 4; - final QualityFileBitmapSource source = new QualityFileBitmapSource( - createFactoryFromBitmap(bitmap)); - if (source.getWidth() == 0 || source.getHeight() == 0) { - return null; - } - while (tw < source.getWidth()) { - tw *= 2; - } - while (th < source.getHeight()) { - th *= 2; - } + public static TextureRegion createRegion(Bitmap bitmap) { + int tw = 4, th = 4; + final QualityFileBitmapSource source = new QualityFileBitmapSource( + createFactoryFromBitmap(bitmap)); + if (source.getWidth() == 0 || source.getHeight() == 0) { + return null; + } + while (tw < source.getWidth()) { + tw *= 2; + } + while (th < source.getHeight()) { + th *= 2; + } - int errorCount = 0; - while (source.preload() == false && errorCount < 3) { - errorCount++; - } - if (errorCount >= 3) { - return null; - } - final BitmapTextureAtlas tex = new BitmapTextureAtlas(tw, th, TextureOptions.BILINEAR); + int errorCount = 0; + while (source.preload() == false && errorCount < 3) { + errorCount++; + } + if (errorCount >= 3) { + return null; + } + final BitmapTextureAtlas tex = new BitmapTextureAtlas(tw, th, TextureOptions.BILINEAR); - TextureRegion region = TextureRegionFactory.createFromSource(tex, source, 0, 0, - false); - GlobalManager.getInstance().getEngine().getTextureManager().loadTexture(tex); - return region; - } + TextureRegion region = TextureRegionFactory.createFromSource(tex, source, 0, 0, + false); + GlobalManager.getInstance().getEngine().getTextureManager().loadTexture(tex); + return region; + } - public static TextureRegion create1xRegion(int color) { - Bitmap bmp = Bitmap.createBitmap(8, 8, Bitmap.Config.ARGB_8888); - bmp.eraseColor(color); - int tw = 4, th = 4; - final QualityFileBitmapSource source = new QualityFileBitmapSource( - createMemoryFactoryFromBitmap(bmp)); - if (source.getWidth() == 0 || source.getHeight() == 0) { - return null; - } - while (tw < source.getWidth()) { - tw *= 2; - } - while (th < source.getHeight()) { - th *= 2; - } + public static TextureRegion create1xRegion(int color) { + Bitmap bmp = Bitmap.createBitmap(8, 8, Bitmap.Config.ARGB_8888); + bmp.eraseColor(color); + int tw = 4, th = 4; + final QualityFileBitmapSource source = new QualityFileBitmapSource( + createMemoryFactoryFromBitmap(bmp)); + if (source.getWidth() == 0 || source.getHeight() == 0) { + return null; + } + while (tw < source.getWidth()) { + tw *= 2; + } + while (th < source.getHeight()) { + th *= 2; + } - int errorCount = 0; - while (source.preload() == false && errorCount < 3) { - errorCount++; - } - if (errorCount >= 3) { - return null; - } - final BitmapTextureAtlas tex = new BitmapTextureAtlas(tw, th, TextureOptions.BILINEAR); + int errorCount = 0; + while (source.preload() == false && errorCount < 3) { + errorCount++; + } + if (errorCount >= 3) { + return null; + } + final BitmapTextureAtlas tex = new BitmapTextureAtlas(tw, th, TextureOptions.BILINEAR); - TextureRegion region = TextureRegionFactory.createFromSource(tex, source, 0, 0, - false); - GlobalManager.getInstance().getEngine().getTextureManager().loadTexture(tex); - return region; - } + TextureRegion region = TextureRegionFactory.createFromSource(tex, source, 0, 0, + false); + GlobalManager.getInstance().getEngine().getTextureManager().loadTexture(tex); + return region; + } } diff --git a/src/com/edlplan/andengine/Triangle3DBuilder.java b/src/com/edlplan/andengine/Triangle3DBuilder.java index 2ceda7a7..d2813041 100644 --- a/src/com/edlplan/andengine/Triangle3DBuilder.java +++ b/src/com/edlplan/andengine/Triangle3DBuilder.java @@ -6,34 +6,34 @@ public class Triangle3DBuilder { - private float[] ver = new float[9]; - - private int offset; - - public void add(Vec3 p1, Vec3 p2, Vec3 p3) { - if (offset + 9 > ver.length) { - ver = Arrays.copyOf(ver, ver.length * 3 / 2 + 9); - } - ver[offset++] = p1.x; - ver[offset++] = p1.y; - ver[offset++] = p1.z; - ver[offset++] = p2.x; - ver[offset++] = p2.y; - ver[offset++] = p2.z; - ver[offset++] = p3.x; - ver[offset++] = p3.y; - ver[offset++] = p3.z; - } - - public float[] getVertex() { - if (offset != ver.length) { - ver = Arrays.copyOf(ver, offset); - } - return ver; - } - - public int getOffset() { - return offset; - } + private float[] ver = new float[9]; + + private int offset; + + public void add(Vec3 p1, Vec3 p2, Vec3 p3) { + if (offset + 9 > ver.length) { + ver = Arrays.copyOf(ver, ver.length * 3 / 2 + 9); + } + ver[offset++] = p1.x; + ver[offset++] = p1.y; + ver[offset++] = p1.z; + ver[offset++] = p2.x; + ver[offset++] = p2.y; + ver[offset++] = p2.z; + ver[offset++] = p3.x; + ver[offset++] = p3.y; + ver[offset++] = p3.z; + } + + public float[] getVertex() { + if (offset != ver.length) { + ver = Arrays.copyOf(ver, offset); + } + return ver; + } + + public int getOffset() { + return offset; + } } diff --git a/src/com/edlplan/andengine/Triangle3DPack.java b/src/com/edlplan/andengine/Triangle3DPack.java index 549aec1f..ff8aea6e 100644 --- a/src/com/edlplan/andengine/Triangle3DPack.java +++ b/src/com/edlplan/andengine/Triangle3DPack.java @@ -13,154 +13,154 @@ public class Triangle3DPack extends Shape { - // =========================================================== - // Fields - // =========================================================== - - private final PolygonVertexBuffer mPolygonVertexBuffer; - private float[] mVertices; - private boolean clearDepthOnStart = false; + // =========================================================== + // Fields + // =========================================================== + + private final PolygonVertexBuffer mPolygonVertexBuffer; + private float[] mVertices; + private boolean clearDepthOnStart = false; - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - public Triangle3DPack(final float pX, final float pY, final float[] pVertices) { - this(pX, pY, pVertices, new PolygonVertexBuffer(pVertices.length, - GL11.GL_STATIC_DRAW, true)); - } + public Triangle3DPack(final float pX, final float pY, final float[] pVertices) { + this(pX, pY, pVertices, new PolygonVertexBuffer(pVertices.length, + GL11.GL_STATIC_DRAW, true)); + } - public Triangle3DPack(final float pX, final float pY, final float[] pVertices, - final PolygonVertexBuffer pPolygonVertexBuffer) { - super(pX, pY); + public Triangle3DPack(final float pX, final float pY, final float[] pVertices, + final PolygonVertexBuffer pPolygonVertexBuffer) { + super(pX, pY); - this.mVertices = pVertices; + this.mVertices = pVertices; - this.mPolygonVertexBuffer = pPolygonVertexBuffer; - this.updateVertexBuffer(); - } + this.mPolygonVertexBuffer = pPolygonVertexBuffer; + this.updateVertexBuffer(); + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - public void setClearDepthOnStart(boolean clearDepthOnStart) { - this.clearDepthOnStart = clearDepthOnStart; - } + public void setClearDepthOnStart(boolean clearDepthOnStart) { + this.clearDepthOnStart = clearDepthOnStart; + } - @Override - protected void onInitDraw(final GL10 pGL) { - super.onInitDraw(pGL); - GLHelper.disableCulling(pGL); - GLHelper.disableTextures(pGL); - GLHelper.disableTexCoordArray(pGL); - if (clearDepthOnStart) pGL.glClear(GL10.GL_DEPTH_BUFFER_BIT); - } + @Override + protected void onInitDraw(final GL10 pGL) { + super.onInitDraw(pGL); + GLHelper.disableCulling(pGL); + GLHelper.disableTextures(pGL); + GLHelper.disableTexCoordArray(pGL); + if (clearDepthOnStart) pGL.glClear(GL10.GL_DEPTH_BUFFER_BIT); + } - @Override - protected VertexBuffer getVertexBuffer() { - return this.mPolygonVertexBuffer; - } + @Override + protected VertexBuffer getVertexBuffer() { + return this.mPolygonVertexBuffer; + } - @Override - protected void onUpdateVertexBuffer() { - //this.mPolygonVertexBuffer.update(mVertices); - } + @Override + protected void onUpdateVertexBuffer() { + //this.mPolygonVertexBuffer.update(mVertices); + } - public void updateShape() { - onUpdateVertexBuffer(); - } + public void updateShape() { + onUpdateVertexBuffer(); + } - public float[] getVertices() { - return mVertices; - } + public float[] getVertices() { + return mVertices; + } - public void setVertices(float[] v) { - mVertices = v; - //onUpdateVertexBuffer(); - } + public void setVertices(float[] v) { + mVertices = v; + //onUpdateVertexBuffer(); + } - @Override - protected void drawVertices(final GL10 pGL, final Camera pCamera) { - if (mVertices.length == 0) { - return; - } - boolean isEnable = GLHelper.isEnableDepthTest(); - GLHelper.enableDepthTest(pGL); - pGL.glColor4f(getRed(), getGreen(), getBlue(), getAlpha()); - Triangle3DRenderer.get().renderTriangles(mVertices, pGL); - GLHelper.setDepthTest(pGL, isEnable); - } + @Override + protected void drawVertices(final GL10 pGL, final Camera pCamera) { + if (mVertices.length == 0) { + return; + } + boolean isEnable = GLHelper.isEnableDepthTest(); + GLHelper.enableDepthTest(pGL); + pGL.glColor4f(getRed(), getGreen(), getBlue(), getAlpha()); + Triangle3DRenderer.get().renderTriangles(mVertices, pGL); + GLHelper.setDepthTest(pGL, isEnable); + } - @Override - protected boolean isCulled(final Camera pCamera) { - // TODO Auto-generated method stub - return false; - } + @Override + protected boolean isCulled(final Camera pCamera) { + // TODO Auto-generated method stub + return false; + } - public boolean collidesWith(final IShape pOtherShape) { - // TODO Auto-generated method stub - return false; - } + public boolean collidesWith(final IShape pOtherShape) { + // TODO Auto-generated method stub + return false; + } - public float getBaseHeight() { - // TODO Auto-generated method stub - return 0; - } + public float getBaseHeight() { + // TODO Auto-generated method stub + return 0; + } - public float getBaseWidth() { - // TODO Auto-generated method stub - return 0; - } + public float getBaseWidth() { + // TODO Auto-generated method stub + return 0; + } - public float getHeight() { - // TODO Auto-generated method stub - return 0; - } + public float getHeight() { + // TODO Auto-generated method stub + return 0; + } - @Override - public float[] getSceneCenterCoordinates() { - // TODO Auto-generated method stub - return null; - } + @Override + public float[] getSceneCenterCoordinates() { + // TODO Auto-generated method stub + return null; + } - public float getWidth() { - // TODO Auto-generated method stub - return 0; - } + public float getWidth() { + // TODO Auto-generated method stub + return 0; + } - @Deprecated - public boolean contains(final float pX, final float pY) { - return false; - } + @Deprecated + public boolean contains(final float pX, final float pY) { + return false; + } - @Override - @Deprecated - public float[] convertLocalToSceneCoordinates(final float pX, final float pY) { - return null; - } + @Override + @Deprecated + public float[] convertLocalToSceneCoordinates(final float pX, final float pY) { + return null; + } - @Override - @Deprecated - public float[] convertSceneToLocalCoordinates(final float pX, final float pY) { - return null; - } + @Override + @Deprecated + public float[] convertSceneToLocalCoordinates(final float pX, final float pY) { + return null; + } } diff --git a/src/com/edlplan/andengine/Triangle3DRenderer.java b/src/com/edlplan/andengine/Triangle3DRenderer.java index e8d3a5f5..f526dabe 100644 --- a/src/com/edlplan/andengine/Triangle3DRenderer.java +++ b/src/com/edlplan/andengine/Triangle3DRenderer.java @@ -9,26 +9,26 @@ public class Triangle3DRenderer { - private static Triangle3DRenderer triangleRenderer = new Triangle3DRenderer(); - FloatBuffer buffer; - - public static Triangle3DRenderer get() { - return triangleRenderer; - } - - public synchronized void renderTriangles(float[] ver, GL10 pGL) { - int offset = ver.length; - if (buffer == null || buffer.capacity() < offset) { - ByteBuffer bb = ByteBuffer.allocateDirect(Math.max(offset + 18, 900) * 4); - bb.order(ByteOrder.nativeOrder()); - buffer = bb.asFloatBuffer(); - } - buffer.position(0).limit(buffer.capacity()); - buffer.put(ver, 0, ver.length); - buffer.position(0).limit(offset); - - pGL.glVertexPointer(3, GL10.GL_FLOAT, 0, buffer); - pGL.glDrawArrays(GL10.GL_TRIANGLES, 0, ver.length / 3); - } + private static Triangle3DRenderer triangleRenderer = new Triangle3DRenderer(); + FloatBuffer buffer; + + public static Triangle3DRenderer get() { + return triangleRenderer; + } + + public synchronized void renderTriangles(float[] ver, GL10 pGL) { + int offset = ver.length; + if (buffer == null || buffer.capacity() < offset) { + ByteBuffer bb = ByteBuffer.allocateDirect(Math.max(offset + 18, 900) * 4); + bb.order(ByteOrder.nativeOrder()); + buffer = bb.asFloatBuffer(); + } + buffer.position(0).limit(buffer.capacity()); + buffer.put(ver, 0, ver.length); + buffer.position(0).limit(offset); + + pGL.glVertexPointer(3, GL10.GL_FLOAT, 0, buffer); + pGL.glDrawArrays(GL10.GL_TRIANGLES, 0, ver.length / 3); + } } diff --git a/src/com/edlplan/andengine/TriangleBuilder.java b/src/com/edlplan/andengine/TriangleBuilder.java index a76cf376..6c872c4d 100644 --- a/src/com/edlplan/andengine/TriangleBuilder.java +++ b/src/com/edlplan/andengine/TriangleBuilder.java @@ -8,55 +8,55 @@ public class TriangleBuilder extends FloatArraySlice { - public TriangleBuilder(float[] cache) { - this.ary = cache; - } - - public TriangleBuilder() { - this(1); - } - - public TriangleBuilder(int size) { - ary = new float[6 * size]; - } - - public void add(Vec3 p1, Vec3 p2, Vec3 p3) { - if (length + 6 > ary.length) { - ary = Arrays.copyOf(ary, ary.length * 3 / 2 + 6); - } - ary[length++] = p1.x; - ary[length++] = p1.y; - ary[length++] = p2.x; - ary[length++] = p2.y; - ary[length++] = p3.x; - ary[length++] = p3.y; - } - - public void add(Vec2 p1, Vec2 p2, Vec2 p3) { - if (length + 6 > ary.length) { - ary = Arrays.copyOf(ary, ary.length * 3 / 2 + 6); - } - ary[length++] = p1.x; - ary[length++] = p1.y; - ary[length++] = p2.x; - ary[length++] = p2.y; - ary[length++] = p3.x; - ary[length++] = p3.y; - } - - public float[] copyVertex() { - float[] c = Arrays.copyOf(ary, offset); - return c; - } - - public FloatArraySlice getVertex(FloatArraySlice slice) { - slice.offset = 0; - if (slice.ary.length < length) { - slice.ary = new float[length]; - } - slice.length = length; - System.arraycopy(ary, 0, slice.ary, 0, length); - return slice; - } + public TriangleBuilder(float[] cache) { + this.ary = cache; + } + + public TriangleBuilder() { + this(1); + } + + public TriangleBuilder(int size) { + ary = new float[6 * size]; + } + + public void add(Vec3 p1, Vec3 p2, Vec3 p3) { + if (length + 6 > ary.length) { + ary = Arrays.copyOf(ary, ary.length * 3 / 2 + 6); + } + ary[length++] = p1.x; + ary[length++] = p1.y; + ary[length++] = p2.x; + ary[length++] = p2.y; + ary[length++] = p3.x; + ary[length++] = p3.y; + } + + public void add(Vec2 p1, Vec2 p2, Vec2 p3) { + if (length + 6 > ary.length) { + ary = Arrays.copyOf(ary, ary.length * 3 / 2 + 6); + } + ary[length++] = p1.x; + ary[length++] = p1.y; + ary[length++] = p2.x; + ary[length++] = p2.y; + ary[length++] = p3.x; + ary[length++] = p3.y; + } + + public float[] copyVertex() { + float[] c = Arrays.copyOf(ary, offset); + return c; + } + + public FloatArraySlice getVertex(FloatArraySlice slice) { + slice.offset = 0; + if (slice.ary.length < length) { + slice.ary = new float[length]; + } + slice.length = length; + System.arraycopy(ary, 0, slice.ary, 0, length); + return slice; + } } diff --git a/src/com/edlplan/andengine/TrianglePack.java b/src/com/edlplan/andengine/TrianglePack.java index ea66a1b7..3f5e6ed1 100644 --- a/src/com/edlplan/andengine/TrianglePack.java +++ b/src/com/edlplan/andengine/TrianglePack.java @@ -15,170 +15,170 @@ public class TrianglePack extends Shape { - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - private FloatArraySlice mVertices; + private FloatArraySlice mVertices; - private PolygonVertexBuffer mPolygonVertexBuffer; + private PolygonVertexBuffer mPolygonVertexBuffer; - private boolean clearDepthOnStart = false; + private boolean clearDepthOnStart = false; - private boolean depthTest = false; + private boolean depthTest = false; - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - public TrianglePack() { - super(0, 0); - mVertices = new FloatArraySlice(); - mVertices.ary = new float[0]; - } + public TrianglePack() { + super(0, 0); + mVertices = new FloatArraySlice(); + mVertices.ary = new float[0]; + } - public TrianglePack(final float pX, final float pY, final float[] pVertices) { - this(pX, pY, pVertices, new PolygonVertexBuffer(pVertices.length, - GL11.GL_STATIC_DRAW, true)); - } + public TrianglePack(final float pX, final float pY, final float[] pVertices) { + this(pX, pY, pVertices, new PolygonVertexBuffer(pVertices.length, + GL11.GL_STATIC_DRAW, true)); + } - public TrianglePack(final float pX, final float pY, final float[] pVertices, - final PolygonVertexBuffer pPolygonVertexBuffer) { - super(pX, pY); + public TrianglePack(final float pX, final float pY, final float[] pVertices, + final PolygonVertexBuffer pPolygonVertexBuffer) { + super(pX, pY); - this.mVertices = new FloatArraySlice(); - mVertices.ary = pVertices; - mVertices.length = pVertices.length; + this.mVertices = new FloatArraySlice(); + mVertices.ary = pVertices; + mVertices.length = pVertices.length; - this.mPolygonVertexBuffer = pPolygonVertexBuffer; - this.updateVertexBuffer(); - } + this.mPolygonVertexBuffer = pPolygonVertexBuffer; + this.updateVertexBuffer(); + } - public void setClearDepthOnStart(boolean clearDepthOnStart) { - this.clearDepthOnStart = clearDepthOnStart; - } + public void setClearDepthOnStart(boolean clearDepthOnStart) { + this.clearDepthOnStart = clearDepthOnStart; + } - public void setDepthTest(boolean depthTest) { - this.depthTest = depthTest; - } + public void setDepthTest(boolean depthTest) { + this.depthTest = depthTest; + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - @Override - protected void onInitDraw(final GL10 pGL) { - super.onInitDraw(pGL); - GLHelper.disableCulling(pGL); - GLHelper.disableTextures(pGL); - GLHelper.disableTexCoordArray(pGL); - if (clearDepthOnStart) { - pGL.glClear(GL10.GL_DEPTH_BUFFER_BIT); - } - } + @Override + protected void onInitDraw(final GL10 pGL) { + super.onInitDraw(pGL); + GLHelper.disableCulling(pGL); + GLHelper.disableTextures(pGL); + GLHelper.disableTexCoordArray(pGL); + if (clearDepthOnStart) { + pGL.glClear(GL10.GL_DEPTH_BUFFER_BIT); + } + } - @Override - protected VertexBuffer getVertexBuffer() { - return this.mPolygonVertexBuffer; - } + @Override + protected VertexBuffer getVertexBuffer() { + return this.mPolygonVertexBuffer; + } - @Override - protected void onUpdateVertexBuffer() { - //this.mPolygonVertexBuffer.update(mVertices); - } + @Override + protected void onUpdateVertexBuffer() { + //this.mPolygonVertexBuffer.update(mVertices); + } - @Override - protected void onApplyVertices(GL10 pGL) { + @Override + protected void onApplyVertices(GL10 pGL) { - } + } - public FloatArraySlice getVertices() { - return mVertices; - } + public FloatArraySlice getVertices() { + return mVertices; + } - public void setVertices(FloatArraySlice v) { - mVertices = v; - } + public void setVertices(FloatArraySlice v) { + mVertices = v; + } - @Override - protected void drawVertices(final GL10 pGL, final Camera pCamera) { - if (mVertices.length == 0) return; - boolean tmp = GLHelper.isEnableDepthTest(); - GLHelper.setDepthTest(pGL, depthTest); - pGL.glColor4f(getRed(), getGreen(), getBlue(), getAlpha()); - TriangleRenderer.get().renderTriangles(mVertices, pGL); - GLHelper.setDepthTest(pGL, tmp); - } + @Override + protected void drawVertices(final GL10 pGL, final Camera pCamera) { + if (mVertices.length == 0) return; + boolean tmp = GLHelper.isEnableDepthTest(); + GLHelper.setDepthTest(pGL, depthTest); + pGL.glColor4f(getRed(), getGreen(), getBlue(), getAlpha()); + TriangleRenderer.get().renderTriangles(mVertices, pGL); + GLHelper.setDepthTest(pGL, tmp); + } - @Override - protected boolean isCulled(final Camera pCamera) { - // TODO Auto-generated method stub - return false; - } + @Override + protected boolean isCulled(final Camera pCamera) { + // TODO Auto-generated method stub + return false; + } - public boolean collidesWith(final IShape pOtherShape) { - // TODO Auto-generated method stub - return false; - } + public boolean collidesWith(final IShape pOtherShape) { + // TODO Auto-generated method stub + return false; + } - public float getBaseHeight() { - // TODO Auto-generated method stub - return 0; - } + public float getBaseHeight() { + // TODO Auto-generated method stub + return 0; + } - public float getBaseWidth() { - // TODO Auto-generated method stub - return 0; - } + public float getBaseWidth() { + // TODO Auto-generated method stub + return 0; + } - public float getHeight() { - // TODO Auto-generated method stub - return 0; - } + public float getHeight() { + // TODO Auto-generated method stub + return 0; + } - @Override - public float[] getSceneCenterCoordinates() { - // TODO Auto-generated method stub - return null; - } + @Override + public float[] getSceneCenterCoordinates() { + // TODO Auto-generated method stub + return null; + } - public float getWidth() { - // TODO Auto-generated method stub - return 0; - } + public float getWidth() { + // TODO Auto-generated method stub + return 0; + } - @Deprecated - public boolean contains(final float pX, final float pY) { - return false; - } + @Deprecated + public boolean contains(final float pX, final float pY) { + return false; + } - @Override - @Deprecated - public float[] convertLocalToSceneCoordinates(final float pX, final float pY) { - return null; - } + @Override + @Deprecated + public float[] convertLocalToSceneCoordinates(final float pX, final float pY) { + return null; + } - @Override - @Deprecated - public float[] convertSceneToLocalCoordinates(final float pX, final float pY) { - return null; - } + @Override + @Deprecated + public float[] convertSceneToLocalCoordinates(final float pX, final float pY) { + return null; + } } diff --git a/src/com/edlplan/andengine/TriangleRenderer.java b/src/com/edlplan/andengine/TriangleRenderer.java index 72643f2f..1acca5d2 100644 --- a/src/com/edlplan/andengine/TriangleRenderer.java +++ b/src/com/edlplan/andengine/TriangleRenderer.java @@ -10,26 +10,26 @@ public class TriangleRenderer { - private static TriangleRenderer triangleRenderer = new TriangleRenderer(); - FloatBuffer buffer; - - public static TriangleRenderer get() { - return triangleRenderer; - } - - public synchronized void renderTriangles(FloatArraySlice ver, GL10 pGL) { - int offset = ver.length; - if (buffer == null || buffer.capacity() < offset) { - ByteBuffer bb = ByteBuffer.allocateDirect((offset + 12) * 4); - bb.order(ByteOrder.nativeOrder()); - buffer = bb.asFloatBuffer(); - } - buffer.position(0).limit(buffer.capacity()); - buffer.put(ver.ary, ver.offset, ver.length); - buffer.position(0).limit(offset); - - pGL.glVertexPointer(2, GL10.GL_FLOAT, 0, buffer); - pGL.glDrawArrays(GL10.GL_TRIANGLES, 0, ver.length / 2); - } + private static TriangleRenderer triangleRenderer = new TriangleRenderer(); + FloatBuffer buffer; + + public static TriangleRenderer get() { + return triangleRenderer; + } + + public synchronized void renderTriangles(FloatArraySlice ver, GL10 pGL) { + int offset = ver.length; + if (buffer == null || buffer.capacity() < offset) { + ByteBuffer bb = ByteBuffer.allocateDirect((offset + 12) * 4); + bb.order(ByteOrder.nativeOrder()); + buffer = bb.asFloatBuffer(); + } + buffer.position(0).limit(buffer.capacity()); + buffer.put(ver.ary, ver.offset, ver.length); + buffer.position(0).limit(offset); + + pGL.glVertexPointer(2, GL10.GL_FLOAT, 0, buffer); + pGL.glDrawArrays(GL10.GL_TRIANGLES, 0, ver.length / 2); + } } diff --git a/src/com/edlplan/andengine/TriangleTexture3DPack.java b/src/com/edlplan/andengine/TriangleTexture3DPack.java index 6c7d4136..88fdee5e 100644 --- a/src/com/edlplan/andengine/TriangleTexture3DPack.java +++ b/src/com/edlplan/andengine/TriangleTexture3DPack.java @@ -14,159 +14,159 @@ public class TriangleTexture3DPack extends Shape { - // =========================================================== - // Fields - // =========================================================== - - private final PolygonVertexBuffer mPolygonVertexBuffer; - private float[] mVertices; - private float[] mTextureCoord; - private TextureRegion textureRegion; - - // =========================================================== - // Constructors - // =========================================================== - - public TriangleTexture3DPack(final float pX, final float pY, final float[] pVertices, float[] pTextureCoord) { - this(pX, pY, pVertices, pTextureCoord, new PolygonVertexBuffer(pVertices.length, - GL11.GL_STATIC_DRAW, true)); - } + // =========================================================== + // Fields + // =========================================================== + + private final PolygonVertexBuffer mPolygonVertexBuffer; + private float[] mVertices; + private float[] mTextureCoord; + private TextureRegion textureRegion; + + // =========================================================== + // Constructors + // =========================================================== + + public TriangleTexture3DPack(final float pX, final float pY, final float[] pVertices, float[] pTextureCoord) { + this(pX, pY, pVertices, pTextureCoord, new PolygonVertexBuffer(pVertices.length, + GL11.GL_STATIC_DRAW, true)); + } - public TriangleTexture3DPack(final float pX, final float pY, final float[] pVertices, float[] pTextureCoord, - final PolygonVertexBuffer pPolygonVertexBuffer) { - super(pX, pY); + public TriangleTexture3DPack(final float pX, final float pY, final float[] pVertices, float[] pTextureCoord, + final PolygonVertexBuffer pPolygonVertexBuffer) { + super(pX, pY); - this.mVertices = pVertices; - this.mTextureCoord = pTextureCoord; + this.mVertices = pVertices; + this.mTextureCoord = pTextureCoord; - this.mPolygonVertexBuffer = pPolygonVertexBuffer; - this.updateVertexBuffer(); - } + this.mPolygonVertexBuffer = pPolygonVertexBuffer; + this.updateVertexBuffer(); + } - public TextureRegion getTextureRegion() { - return textureRegion; - } + public TextureRegion getTextureRegion() { + return textureRegion; + } - public void setTextureRegion(TextureRegion textureRegion) { - this.textureRegion = textureRegion; - } + public void setTextureRegion(TextureRegion textureRegion) { + this.textureRegion = textureRegion; + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - @Override - protected void onInitDraw(final GL10 pGL) { - super.onInitDraw(pGL); - GLHelper.disableCulling(pGL); - } + @Override + protected void onInitDraw(final GL10 pGL) { + super.onInitDraw(pGL); + GLHelper.disableCulling(pGL); + } - @Override - protected VertexBuffer getVertexBuffer() { - return this.mPolygonVertexBuffer; - } + @Override + protected VertexBuffer getVertexBuffer() { + return this.mPolygonVertexBuffer; + } - @Override - protected void onUpdateVertexBuffer() { - //this.mPolygonVertexBuffer.update(mVertices); - } + @Override + protected void onUpdateVertexBuffer() { + //this.mPolygonVertexBuffer.update(mVertices); + } - public void updateShape() { - onUpdateVertexBuffer(); - } + public void updateShape() { + onUpdateVertexBuffer(); + } - public float[] getVertices() { - return mVertices; - } + public float[] getVertices() { + return mVertices; + } - public void setVertices(float[] v) { - mVertices = v; - //onUpdateVertexBuffer(); - } + public void setVertices(float[] v) { + mVertices = v; + //onUpdateVertexBuffer(); + } - @Override - protected void drawVertices(final GL10 pGL, final Camera pCamera) { - if (mVertices.length == 0 || mTextureCoord.length == 0 || textureRegion == null) { - return; - } - boolean isEnable = GLHelper.isEnableDepthTest(); - GLHelper.enableDepthTest(pGL); - GLHelper.enableTexCoordArray(pGL); - GLHelper.enableTextures(pGL); - textureRegion.getTexture().bind(pGL); - //pGL.glColor4f(getRed(), getGreen(), getBlue(), getAlpha()); - TriangleTexture3DRenderer.get().renderTriangles(mVertices, mTextureCoord, pGL); - GLHelper.setDepthTest(pGL, isEnable); - } + @Override + protected void drawVertices(final GL10 pGL, final Camera pCamera) { + if (mVertices.length == 0 || mTextureCoord.length == 0 || textureRegion == null) { + return; + } + boolean isEnable = GLHelper.isEnableDepthTest(); + GLHelper.enableDepthTest(pGL); + GLHelper.enableTexCoordArray(pGL); + GLHelper.enableTextures(pGL); + textureRegion.getTexture().bind(pGL); + //pGL.glColor4f(getRed(), getGreen(), getBlue(), getAlpha()); + TriangleTexture3DRenderer.get().renderTriangles(mVertices, mTextureCoord, pGL); + GLHelper.setDepthTest(pGL, isEnable); + } - @Override - protected boolean isCulled(final Camera pCamera) { - // TODO Auto-generated method stub - return false; - } + @Override + protected boolean isCulled(final Camera pCamera) { + // TODO Auto-generated method stub + return false; + } - public boolean collidesWith(final IShape pOtherShape) { - // TODO Auto-generated method stub - return false; - } + public boolean collidesWith(final IShape pOtherShape) { + // TODO Auto-generated method stub + return false; + } - public float getBaseHeight() { - // TODO Auto-generated method stub - return 0; - } + public float getBaseHeight() { + // TODO Auto-generated method stub + return 0; + } - public float getBaseWidth() { - // TODO Auto-generated method stub - return 0; - } + public float getBaseWidth() { + // TODO Auto-generated method stub + return 0; + } - public float getHeight() { - // TODO Auto-generated method stub - return 0; - } + public float getHeight() { + // TODO Auto-generated method stub + return 0; + } - @Override - public float[] getSceneCenterCoordinates() { - // TODO Auto-generated method stub - return null; - } + @Override + public float[] getSceneCenterCoordinates() { + // TODO Auto-generated method stub + return null; + } - public float getWidth() { - // TODO Auto-generated method stub - return 0; - } + public float getWidth() { + // TODO Auto-generated method stub + return 0; + } - @Deprecated - public boolean contains(final float pX, final float pY) { - return false; - } + @Deprecated + public boolean contains(final float pX, final float pY) { + return false; + } - @Override - @Deprecated - public float[] convertLocalToSceneCoordinates(final float pX, final float pY) { - return null; - } + @Override + @Deprecated + public float[] convertLocalToSceneCoordinates(final float pX, final float pY) { + return null; + } - @Override - @Deprecated - public float[] convertSceneToLocalCoordinates(final float pX, final float pY) { - return null; - } + @Override + @Deprecated + public float[] convertSceneToLocalCoordinates(final float pX, final float pY) { + return null; + } } diff --git a/src/com/edlplan/andengine/TriangleTexture3DRenderer.java b/src/com/edlplan/andengine/TriangleTexture3DRenderer.java index e2f3cd95..950fea01 100644 --- a/src/com/edlplan/andengine/TriangleTexture3DRenderer.java +++ b/src/com/edlplan/andengine/TriangleTexture3DRenderer.java @@ -8,40 +8,40 @@ public class TriangleTexture3DRenderer { - private static TriangleTexture3DRenderer triangleRenderer = new TriangleTexture3DRenderer(); - FloatBuffer buffer, coordBuffer; - - public static TriangleTexture3DRenderer get() { - return triangleRenderer; - } - - public synchronized void renderTriangles(float[] ver, float[] coord, GL10 pGL) { - { - int offset = ver.length; - if (buffer == null || buffer.capacity() < offset) { - ByteBuffer bb = ByteBuffer.allocateDirect((offset + 18) * 4); - bb.order(ByteOrder.nativeOrder()); - buffer = bb.asFloatBuffer(); - } - buffer.position(0).limit(buffer.capacity()); - buffer.put(ver, 0, ver.length); - buffer.position(0).limit(offset); - } - { - int offset = coord.length; - if (coordBuffer == null || coordBuffer.capacity() < offset) { - ByteBuffer bb = ByteBuffer.allocateDirect((offset + 12) * 4); - bb.order(ByteOrder.nativeOrder()); - coordBuffer = bb.asFloatBuffer(); - } - coordBuffer.position(0).limit(coordBuffer.capacity()); - coordBuffer.put(coord, 0, coord.length); - coordBuffer.position(0).limit(offset); - } - - pGL.glTexCoordPointer(2, GL10.GL_FLOAT, 0, coordBuffer); - pGL.glVertexPointer(3, GL10.GL_FLOAT, 0, buffer); - pGL.glDrawArrays(GL10.GL_TRIANGLES, 0, ver.length / 3); - } + private static TriangleTexture3DRenderer triangleRenderer = new TriangleTexture3DRenderer(); + FloatBuffer buffer, coordBuffer; + + public static TriangleTexture3DRenderer get() { + return triangleRenderer; + } + + public synchronized void renderTriangles(float[] ver, float[] coord, GL10 pGL) { + { + int offset = ver.length; + if (buffer == null || buffer.capacity() < offset) { + ByteBuffer bb = ByteBuffer.allocateDirect((offset + 18) * 4); + bb.order(ByteOrder.nativeOrder()); + buffer = bb.asFloatBuffer(); + } + buffer.position(0).limit(buffer.capacity()); + buffer.put(ver, 0, ver.length); + buffer.position(0).limit(offset); + } + { + int offset = coord.length; + if (coordBuffer == null || coordBuffer.capacity() < offset) { + ByteBuffer bb = ByteBuffer.allocateDirect((offset + 12) * 4); + bb.order(ByteOrder.nativeOrder()); + coordBuffer = bb.asFloatBuffer(); + } + coordBuffer.position(0).limit(coordBuffer.capacity()); + coordBuffer.put(coord, 0, coord.length); + coordBuffer.position(0).limit(offset); + } + + pGL.glTexCoordPointer(2, GL10.GL_FLOAT, 0, coordBuffer); + pGL.glVertexPointer(3, GL10.GL_FLOAT, 0, buffer); + pGL.glDrawArrays(GL10.GL_TRIANGLES, 0, ver.length / 3); + } } diff --git a/src/com/edlplan/andengine/texture/AbstractTexture.java b/src/com/edlplan/andengine/texture/AbstractTexture.java index b24ecfa6..9713a9a5 100644 --- a/src/com/edlplan/andengine/texture/AbstractTexture.java +++ b/src/com/edlplan/andengine/texture/AbstractTexture.java @@ -7,41 +7,41 @@ import com.edlplan.framework.math.Vec2; public abstract class AbstractTexture { - public abstract int getTextureId(); + public abstract int getTextureId(); - public abstract GLTexture getTexture(); + public abstract GLTexture getTexture(); - public abstract int getHeight(); + public abstract int getHeight(); - public abstract int getWidth(); + public abstract int getWidth(); - public abstract Vec2 toTexturePosition(float x, float y); + public abstract Vec2 toTexturePosition(float x, float y); - public abstract IQuad getRawQuad(); + public abstract IQuad getRawQuad(); - public Vec2 toTexturePosition(Vec2 v) { - return toTexturePosition(v.x, v.y); - } + public Vec2 toTexturePosition(Vec2 v) { + return toTexturePosition(v.x, v.y); + } - //将一个width x height坐标的rect换成1x1坐标 - public RectF toTextureRect(RectF raw) { - return toTextureRect(raw.getLeft(), raw.getTop(), raw.getRight(), raw.getBottom()); - } + //将一个width x height坐标的rect换成1x1坐标 + public RectF toTextureRect(RectF raw) { + return toTextureRect(raw.getLeft(), raw.getTop(), raw.getRight(), raw.getBottom()); + } - public RectF toTextureRect(float l, float t, float r, float b) { - Vec2 lt = toTexturePosition(l, t); - Vec2 rb = toTexturePosition(r, b); - return RectF.ltrb(lt.x, lt.y, rb.x, rb.y); - } + public RectF toTextureRect(float l, float t, float r, float b) { + Vec2 lt = toTexturePosition(l, t); + Vec2 rb = toTexturePosition(r, b); + return RectF.ltrb(lt.x, lt.y, rb.x, rb.y); + } - public Quad toTextureQuad(IQuad q) { - Quad r = new Quad(); - r.set( - toTexturePosition(q.getTopLeft()), - toTexturePosition(q.getTopRight()), - toTexturePosition(q.getBottomLeft()), - toTexturePosition(q.getBottomRight())); - return r; - } + public Quad toTextureQuad(IQuad q) { + Quad r = new Quad(); + r.set( + toTexturePosition(q.getTopLeft()), + toTexturePosition(q.getTopRight()), + toTexturePosition(q.getBottomLeft()), + toTexturePosition(q.getBottomRight())); + return r; + } } diff --git a/src/com/edlplan/andengine/texture/GLTexture.java b/src/com/edlplan/andengine/texture/GLTexture.java index 9eb66675..670a7c5d 100644 --- a/src/com/edlplan/andengine/texture/GLTexture.java +++ b/src/com/edlplan/andengine/texture/GLTexture.java @@ -21,318 +21,318 @@ import java.io.InputStream; public class GLTexture extends AbstractTexture { - public static final int[] glTexIndex = new int[]{ - GLES20.GL_TEXTURE0, - GLES20.GL_TEXTURE1, - GLES20.GL_TEXTURE2, - GLES20.GL_TEXTURE3, - GLES20.GL_TEXTURE4, - GLES20.GL_TEXTURE5, - GLES20.GL_TEXTURE6, - GLES20.GL_TEXTURE7, - GLES20.GL_TEXTURE8, - GLES20.GL_TEXTURE9, - GLES20.GL_TEXTURE10, - GLES20.GL_TEXTURE11, - GLES20.GL_TEXTURE12, - GLES20.GL_TEXTURE13, - GLES20.GL_TEXTURE14, - GLES20.GL_TEXTURE15, - GLES20.GL_TEXTURE16, - GLES20.GL_TEXTURE17, - GLES20.GL_TEXTURE18 - }; - public static BitmapFactory.Options DEF_CREATE_OPTIONS; - public static GLTexture White; - public static GLTexture Alpha; - public static GLTexture Black; - public static GLTexture Red; - public static GLTexture Blue; - public static GLTexture Yellow; - public static GLTexture ErrorTexture; - public static boolean poor_font_mode = false; - public static boolean SCALE_22 = true; - - static { - initial(); - } - - private int width, height; - - private int realWidth, realHeight; - - private float glWidth, glHeight; - - private int textureId; - - private boolean recycled = false; - - private Quad rawQuad; - - public GLTexture() { - - } - - public static GLTexture createGPUTexture(int w, int h) { - /*if(w>GLWrapped.GL_MAX_TEXTURE_SIZE||h>GLWrapped.GL_MAX_TEXTURE_SIZE){ - GLTexture t=createErrTexture(); - return t; - }*/ - int[] t = new int[1]; - GLES20.glGenTextures(1, t, 0); - GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, t[0]); - GLES20.glTexImage2D(GLES20.GL_TEXTURE_2D, 0, GLES20.GL_RGBA, w, h, 0, GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, null); - GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, - GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR); - GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, - GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR); - GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, - GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_CLAMP_TO_EDGE); - GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, - GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_CLAMP_TO_EDGE); - GLTexture tex = new GLTexture(); - tex.width = w; - tex.height = h; - tex.textureId = t[0]; - tex.glHeight = 1; - tex.glWidth = 1; - tex.endCreate(); - //Log.v("fbo","gen tx: "+tex.textureId); - return tex; - } - - public static GLTexture createGPUAlphaTexture(int w, int h) { - /*if(w>GLWrapped.GL_MAX_TEXTURE_SIZE||h>GLWrapped.GL_MAX_TEXTURE_SIZE){ - GLTexture t=createErrTexture(); - return t; - }*/ - int[] t = new int[1]; - GLES20.glGenTextures(1, t, 0); - GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, t[0]); - GLES20.glTexImage2D(GLES20.GL_TEXTURE_2D, 0, GLES20.GL_ALPHA, w, h, 0, GLES20.GL_ALPHA, GLES20.GL_UNSIGNED_BYTE, null); - GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, - GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR); - GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, - GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR); - GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, - GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_CLAMP_TO_EDGE); - GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, - GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_CLAMP_TO_EDGE); - GLTexture tex = new GLTexture(); - tex.width = w; - tex.height = h; - tex.textureId = t[0]; - tex.glHeight = 1; - tex.glWidth = 1; - tex.endCreate(); - //Log.v("fbo","gen tx: "+tex.textureId); - return tex; - } - - public static GLTexture createNotChecked(Bitmap bmp, int w, int h) { - - GLTexture tex = new GLTexture(); - tex.textureId = createTexture(); - //Log.v("texture","create Texture: "+tex.textureId); - //GLWrapped.checkGlError("create Texture: " + tex.textureId); - tex.width = w; - tex.height = h; - tex.glHeight = tex.height / (float) bmp.getHeight(); - tex.glWidth = tex.width / (float) bmp.getWidth(); - tex.endCreate(); - GLUtils.texImage2D(GLES20.GL_TEXTURE_2D, 0, bmp, 0); - //GLWrapped.checkGlError("load Texture"); - return tex; - } - - public static GLTexture decodeStream(InputStream in) { - //double time=Framework.relativePreciseTimeMillion(); - Bitmap bmp = BitmapFactory.decodeStream(in, null, DEF_CREATE_OPTIONS); - //System.out.println("decode bitmap cost "+(int)(Framework.relativePreciseTimeMillion()-time)+"ms"); - return create(bmp, true); - } - - public static GLTexture decodeStream(InputStream in, boolean ifClose) throws IOException { - GLTexture t = decodeStream(in); - if (ifClose) in.close(); - return t; - } - - public static GLTexture decodeFile(File f) throws FileNotFoundException, IOException { - return decodeStream(new FileInputStream(f), true); - } - - public static GLTexture create1pxTexture(Color4 color) { - Bitmap bmp = Bitmap.createBitmap(new int[]{color.toIntBit()}, 1, 1, Bitmap.Config.ARGB_8888); - return create(bmp, true); - } - - public static GLTexture create(Bitmap bmp, boolean ifDispos) { - GLTexture t = create(bmp); - if (ifDispos) bmp.recycle(); - return t; - } - - public static GLTexture create(Bitmap bmp) { - - int w = 1; - int h = 1; - while (w < bmp.getWidth()) w *= 2; - while (h < bmp.getHeight()) h *= 2; - - w = bmp.getWidth(); - h = bmp.getHeight(); - Bitmap nb = Bitmap.createBitmap(w, h, poor_font_mode ? Bitmap.Config.ALPHA_8 : Bitmap.Config.ARGB_8888); - Canvas c = new Canvas(nb); - GLTexture tex; - c.drawColor(0x00000000); - Paint p = new Paint(); - p.setAntiAlias(false); - c.drawBitmap(bmp, 0, 0, p); - tex = createNotChecked(nb, bmp.getWidth(), bmp.getHeight()); - nb.recycle(); - /* - if(SCALE_22){ - if(w!=bmp.getWidth()||h!=bmp.getHeight()){ - Bitmap nb=Bitmap.createBitmap(w,h,Bitmap.Config.ARGB_8888); - Canvas c=new Canvas(nb); - c.clearColor(0x00000000); - Paint p=new Paint(); - p.setAntiAlias(false); - c.drawBitmap(bmp,0,0,p); - tex=createNotChecked(nb,bmp.getWidth(),bmp.getHeight()); - nb.recycle(); - }else{ - tex=createNotChecked(bmp,bmp.getWidth(),bmp.getHeight()); - } - }else{ - tex=createNotChecked(bmp,bmp.getWidth(),bmp.getHeight()); - }*/ - return tex; - } - - private static int createTexture() { - int[] t = new int[1]; - GLES20.glGenTextures(1, t, 0); - GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, t[0]); - GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, - GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR); - GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, - GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR); - GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, - GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_REPEAT); - GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, - GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_REPEAT); - return t[0]; - } - - public static GLTexture createErrTexture() { - Bitmap bmp = Bitmap.createBitmap(128, 128, Bitmap.Config.ARGB_8888); - for (int x = 0; x < bmp.getWidth(); x++) { - for (int y = 0; y < bmp.getHeight(); y++) { - if ((x / 32 + y / 32) % 2 == 0) { - bmp.setPixel(x, y, Color.argb(255, 10, 5, 5)); - } else { - bmp.setPixel(x, y, Color.argb(255, 110, 40, 50)); - } - } - } - return create(bmp, true); - } - - public static void initial() { - DEF_CREATE_OPTIONS = new BitmapFactory.Options(); - DEF_CREATE_OPTIONS.inPremultiplied = true; - White = create1pxTexture(Color4.White); - Alpha = create1pxTexture(Color4.Alpha); - Black = create1pxTexture(Color4.Black); - Red = create1pxTexture(Color4.Red); - Blue = create1pxTexture(Color4.Blue); - Yellow = create1pxTexture(Color4.Yellow); - ErrorTexture = createErrTexture(); - } - - @Override - public IQuad getRawQuad() { - return rawQuad; - } - - protected void endCreate() { - rawQuad = RectF.xywh(0, 0, glWidth, glHeight).toQuad(); - } - - @Override - public GLTexture getTexture() { - - return this; - } - - @Override - public int getWidth() { - return width; - } - - @Override - public int getHeight() { - return height; - } - - public int getRealWidth() { - return realWidth; - } - - public int getRealHeight() { - return realHeight; - } - - public float getGlWidth() { - return glWidth; - } - - public float getGlHeight() { - return glHeight; - } - - @Override - public int getTextureId() { - return textureId; - } - - public void bind(int loc) { - bindGl(glTexIndex[loc]); - } - - private void bindGl(int i) { - GLES20.glActiveTexture(i); - GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textureId); - } - - @Override - public Vec2 toTexturePosition(float x, float y) { - return new Vec2(glWidth * x / width, glHeight * y / height); - } - - public void delete() { - GLES20.glDeleteTextures(1, new int[]{textureId}, 0); - recycled = true; - } - - @Override - protected void finalize() throws Throwable { - - if (!recycled) delete(); - super.finalize(); - } - - @Override - public int hashCode() { - - return textureId; - } - - @Override - public boolean equals(Object obj) { - - return super.equals(obj); - } -} \ No newline at end of file + public static final int[] glTexIndex = new int[]{ + GLES20.GL_TEXTURE0, + GLES20.GL_TEXTURE1, + GLES20.GL_TEXTURE2, + GLES20.GL_TEXTURE3, + GLES20.GL_TEXTURE4, + GLES20.GL_TEXTURE5, + GLES20.GL_TEXTURE6, + GLES20.GL_TEXTURE7, + GLES20.GL_TEXTURE8, + GLES20.GL_TEXTURE9, + GLES20.GL_TEXTURE10, + GLES20.GL_TEXTURE11, + GLES20.GL_TEXTURE12, + GLES20.GL_TEXTURE13, + GLES20.GL_TEXTURE14, + GLES20.GL_TEXTURE15, + GLES20.GL_TEXTURE16, + GLES20.GL_TEXTURE17, + GLES20.GL_TEXTURE18 + }; + public static BitmapFactory.Options DEF_CREATE_OPTIONS; + public static GLTexture White; + public static GLTexture Alpha; + public static GLTexture Black; + public static GLTexture Red; + public static GLTexture Blue; + public static GLTexture Yellow; + public static GLTexture ErrorTexture; + public static boolean poor_font_mode = false; + public static boolean SCALE_22 = true; + + static { + initial(); + } + + private int width, height; + + private int realWidth, realHeight; + + private float glWidth, glHeight; + + private int textureId; + + private boolean recycled = false; + + private Quad rawQuad; + + public GLTexture() { + + } + + public static GLTexture createGPUTexture(int w, int h) { + /*if(w>GLWrapped.GL_MAX_TEXTURE_SIZE||h>GLWrapped.GL_MAX_TEXTURE_SIZE){ + GLTexture t=createErrTexture(); + return t; + }*/ + int[] t = new int[1]; + GLES20.glGenTextures(1, t, 0); + GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, t[0]); + GLES20.glTexImage2D(GLES20.GL_TEXTURE_2D, 0, GLES20.GL_RGBA, w, h, 0, GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, null); + GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, + GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR); + GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, + GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR); + GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, + GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_CLAMP_TO_EDGE); + GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, + GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_CLAMP_TO_EDGE); + GLTexture tex = new GLTexture(); + tex.width = w; + tex.height = h; + tex.textureId = t[0]; + tex.glHeight = 1; + tex.glWidth = 1; + tex.endCreate(); + //Log.v("fbo","gen tx: "+tex.textureId); + return tex; + } + + public static GLTexture createGPUAlphaTexture(int w, int h) { + /*if(w>GLWrapped.GL_MAX_TEXTURE_SIZE||h>GLWrapped.GL_MAX_TEXTURE_SIZE){ + GLTexture t=createErrTexture(); + return t; + }*/ + int[] t = new int[1]; + GLES20.glGenTextures(1, t, 0); + GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, t[0]); + GLES20.glTexImage2D(GLES20.GL_TEXTURE_2D, 0, GLES20.GL_ALPHA, w, h, 0, GLES20.GL_ALPHA, GLES20.GL_UNSIGNED_BYTE, null); + GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, + GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR); + GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, + GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR); + GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, + GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_CLAMP_TO_EDGE); + GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, + GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_CLAMP_TO_EDGE); + GLTexture tex = new GLTexture(); + tex.width = w; + tex.height = h; + tex.textureId = t[0]; + tex.glHeight = 1; + tex.glWidth = 1; + tex.endCreate(); + //Log.v("fbo","gen tx: "+tex.textureId); + return tex; + } + + public static GLTexture createNotChecked(Bitmap bmp, int w, int h) { + + GLTexture tex = new GLTexture(); + tex.textureId = createTexture(); + //Log.v("texture","create Texture: "+tex.textureId); + //GLWrapped.checkGlError("create Texture: " + tex.textureId); + tex.width = w; + tex.height = h; + tex.glHeight = tex.height / (float) bmp.getHeight(); + tex.glWidth = tex.width / (float) bmp.getWidth(); + tex.endCreate(); + GLUtils.texImage2D(GLES20.GL_TEXTURE_2D, 0, bmp, 0); + //GLWrapped.checkGlError("load Texture"); + return tex; + } + + public static GLTexture decodeStream(InputStream in) { + //double time=Framework.relativePreciseTimeMillion(); + Bitmap bmp = BitmapFactory.decodeStream(in, null, DEF_CREATE_OPTIONS); + //System.out.println("decode bitmap cost "+(int)(Framework.relativePreciseTimeMillion()-time)+"ms"); + return create(bmp, true); + } + + public static GLTexture decodeStream(InputStream in, boolean ifClose) throws IOException { + GLTexture t = decodeStream(in); + if (ifClose) in.close(); + return t; + } + + public static GLTexture decodeFile(File f) throws FileNotFoundException, IOException { + return decodeStream(new FileInputStream(f), true); + } + + public static GLTexture create1pxTexture(Color4 color) { + Bitmap bmp = Bitmap.createBitmap(new int[]{color.toIntBit()}, 1, 1, Bitmap.Config.ARGB_8888); + return create(bmp, true); + } + + public static GLTexture create(Bitmap bmp, boolean ifDispos) { + GLTexture t = create(bmp); + if (ifDispos) bmp.recycle(); + return t; + } + + public static GLTexture create(Bitmap bmp) { + + int w = 1; + int h = 1; + while (w < bmp.getWidth()) w *= 2; + while (h < bmp.getHeight()) h *= 2; + + w = bmp.getWidth(); + h = bmp.getHeight(); + Bitmap nb = Bitmap.createBitmap(w, h, poor_font_mode ? Bitmap.Config.ALPHA_8 : Bitmap.Config.ARGB_8888); + Canvas c = new Canvas(nb); + GLTexture tex; + c.drawColor(0x00000000); + Paint p = new Paint(); + p.setAntiAlias(false); + c.drawBitmap(bmp, 0, 0, p); + tex = createNotChecked(nb, bmp.getWidth(), bmp.getHeight()); + nb.recycle(); + /* + if(SCALE_22){ + if(w!=bmp.getWidth()||h!=bmp.getHeight()){ + Bitmap nb=Bitmap.createBitmap(w,h,Bitmap.Config.ARGB_8888); + Canvas c=new Canvas(nb); + c.clearColor(0x00000000); + Paint p=new Paint(); + p.setAntiAlias(false); + c.drawBitmap(bmp,0,0,p); + tex=createNotChecked(nb,bmp.getWidth(),bmp.getHeight()); + nb.recycle(); + }else{ + tex=createNotChecked(bmp,bmp.getWidth(),bmp.getHeight()); + } + }else{ + tex=createNotChecked(bmp,bmp.getWidth(),bmp.getHeight()); + }*/ + return tex; + } + + private static int createTexture() { + int[] t = new int[1]; + GLES20.glGenTextures(1, t, 0); + GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, t[0]); + GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, + GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR); + GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, + GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR); + GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, + GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_REPEAT); + GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, + GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_REPEAT); + return t[0]; + } + + public static GLTexture createErrTexture() { + Bitmap bmp = Bitmap.createBitmap(128, 128, Bitmap.Config.ARGB_8888); + for (int x = 0; x < bmp.getWidth(); x++) { + for (int y = 0; y < bmp.getHeight(); y++) { + if ((x / 32 + y / 32) % 2 == 0) { + bmp.setPixel(x, y, Color.argb(255, 10, 5, 5)); + } else { + bmp.setPixel(x, y, Color.argb(255, 110, 40, 50)); + } + } + } + return create(bmp, true); + } + + public static void initial() { + DEF_CREATE_OPTIONS = new BitmapFactory.Options(); + DEF_CREATE_OPTIONS.inPremultiplied = true; + White = create1pxTexture(Color4.White); + Alpha = create1pxTexture(Color4.Alpha); + Black = create1pxTexture(Color4.Black); + Red = create1pxTexture(Color4.Red); + Blue = create1pxTexture(Color4.Blue); + Yellow = create1pxTexture(Color4.Yellow); + ErrorTexture = createErrTexture(); + } + + @Override + public IQuad getRawQuad() { + return rawQuad; + } + + protected void endCreate() { + rawQuad = RectF.xywh(0, 0, glWidth, glHeight).toQuad(); + } + + @Override + public GLTexture getTexture() { + + return this; + } + + @Override + public int getWidth() { + return width; + } + + @Override + public int getHeight() { + return height; + } + + public int getRealWidth() { + return realWidth; + } + + public int getRealHeight() { + return realHeight; + } + + public float getGlWidth() { + return glWidth; + } + + public float getGlHeight() { + return glHeight; + } + + @Override + public int getTextureId() { + return textureId; + } + + public void bind(int loc) { + bindGl(glTexIndex[loc]); + } + + private void bindGl(int i) { + GLES20.glActiveTexture(i); + GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textureId); + } + + @Override + public Vec2 toTexturePosition(float x, float y) { + return new Vec2(glWidth * x / width, glHeight * y / height); + } + + public void delete() { + GLES20.glDeleteTextures(1, new int[]{textureId}, 0); + recycled = true; + } + + @Override + protected void finalize() throws Throwable { + + if (!recycled) delete(); + super.finalize(); + } + + @Override + public int hashCode() { + + return textureId; + } + + @Override + public boolean equals(Object obj) { + + return super.equals(obj); + } +} diff --git a/src/com/edlplan/ext/EdExtensionHelper.java b/src/com/edlplan/ext/EdExtensionHelper.java index a7833d0e..6b7a78d9 100644 --- a/src/com/edlplan/ext/EdExtensionHelper.java +++ b/src/com/edlplan/ext/EdExtensionHelper.java @@ -21,187 +21,187 @@ public class EdExtensionHelper { - public static final String EXT_BROADCAST_ANY = "osu.droid.ext.broadcast.any"; - - public static boolean downloadExtension() { - final Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.edplan.cn/osu/droid/extension/latest_ext.php")); - GlobalManager.getInstance().getMainActivity().startActivity(intent); - return true; - } - - public static boolean isExtensionEnable() { - return Config.isEnableExtension(); - } - - public static void broadcastMsg(String apiName, String data) { - if (!isExtensionEnable()) return; - Intent intent = new Intent(EXT_BROADCAST_ANY); - intent.putExtra("api", apiName); - intent.putExtra("type", "anyBroadcast"); - intent.putExtra("data", data); - GlobalManager.getInstance().getMainActivity().sendBroadcast(intent); - } - - public static void onSelectTrack(TrackInfo info) { - if (!isExtensionEnable() || info == null) { - return; - } - try { - JSONObject game = new JSONObject(); - game.put("file", info.getFilename()); - game.put("mods", new JSONArray(ModMenu.getInstance().getMod())); - broadcastMsg("onSelectTrack", game.toString()); - } catch (JSONException e) { - e.printStackTrace(); - } - } - - public static void onStartGame(TrackInfo info) { - if (!isExtensionEnable() || info == null) { - return; - } - try { - JSONObject game = new JSONObject(); - game.put("file", info.getFilename()); - game.put("mods", new JSONArray(ModMenu.getInstance().getMod())); - game.put("gameId", GameHelper.getGameid()); - broadcastMsg("onStartGame", game.toString()); - } catch (JSONException e) { - e.printStackTrace(); - } - } - - public static void onRestartGame(TrackInfo info) { - if (!isExtensionEnable() || info == null) { - return; - } - try { - JSONObject game = new JSONObject(); - game.put("file", info.getFilename()); - game.put("mods", new JSONArray(ModMenu.getInstance().getMod())); - game.put("gameId", GameHelper.getGameid()); - broadcastMsg("onRestartGame", game.toString()); - } catch (JSONException e) { - e.printStackTrace(); - } - } - - public static void onExitGame(TrackInfo info) { - if (!isExtensionEnable() || info == null) { - return; - } - try { - JSONObject game = new JSONObject(); - game.put("file", info.getFilename()); - game.put("mods", new JSONArray(ModMenu.getInstance().getMod())); - game.put("gameId", GameHelper.getGameid()); - broadcastMsg("onExitgame", game.toString()); - } catch (JSONException e) { - e.printStackTrace(); - } - } - - public static void onGameover(TrackInfo info) { - if (!isExtensionEnable() || info == null) { - return; - } - try { - JSONObject game = new JSONObject(); - game.put("file", info.getFilename()); - game.put("mods", new JSONArray(ModMenu.getInstance().getMod())); - game.put("gameId", GameHelper.getGameid()); - broadcastMsg("onGameover", game.toString()); - } catch (JSONException e) { - e.printStackTrace(); - } - } - - public static void onEndGame(TrackInfo lastTrack, StatisticV2 stat) { - if (!isExtensionEnable() || lastTrack == null) { - return; - } - try { - JSONObject game = new JSONObject(); - game.put("file", lastTrack.getFilename()); - game.put("mods", new JSONArray(stat.getMod())); - game.put("score", stat.getTotalScore()); - game.put("combo", stat.getMaxCombo()); - game.put("hit300", stat.getHit300()); - game.put("hit100", stat.getHit100()); - game.put("hit50", stat.getHit50()); - game.put("miss", stat.getMisses()); - broadcastMsg("onEndGame", game.toString()); - } catch (JSONException e) { - e.printStackTrace(); - } - } - - public static void onPauseGame(TrackInfo info) { - if (!isExtensionEnable() || info == null) { - return; - } - try { - JSONObject game = new JSONObject(); - game.put("file", info.getFilename()); - game.put("mods", new JSONArray(ModMenu.getInstance().getMod())); - game.put("gameId", GameHelper.getGameid()); - broadcastMsg("onPauseGame", game.toString()); - } catch (JSONException e) { - e.printStackTrace(); - } - } - - public static void onResume(TrackInfo info) { - if (!isExtensionEnable() || info == null) { - return; - } - try { - JSONObject game = new JSONObject(); - game.put("file", info.getFilename()); - game.put("mods", new JSONArray(ModMenu.getInstance().getMod())); - game.put("gameId", GameHelper.getGameid()); - broadcastMsg("onResumeGame", game.toString()); - } catch (JSONException e) { - e.printStackTrace(); - } - } - - public static void onQuitGame(TrackInfo info) { - if (!isExtensionEnable() || info == null) { - return; - } - try { - JSONObject game = new JSONObject(); - game.put("file", info.getFilename()); - game.put("mods", new JSONArray(ModMenu.getInstance().getMod())); - game.put("gameId", GameHelper.getGameid()); - broadcastMsg("onQuitGame", game.toString()); - } catch (JSONException e) { - e.printStackTrace(); - } - } - - public static boolean openBeatmap(String filepath) { - if (!isExtensionEnable()) return false; - try { - Intent intent = new Intent(); - ComponentName componentName = new ComponentName("com.edplan.osu.osudroidextension", "com.edplan.osu.osudroidextension.ApiActivity"); - intent.setComponent(componentName); - intent.putExtra("api", "openOsuFile"); - try { - JSONObject game = new JSONObject(); - game.put("file", filepath); - game.put("mods", new JSONArray(ModMenu.getInstance().getMod())); - intent.putExtra("data", game.toString()); - GlobalManager.getInstance().getMainActivity().startActivity(intent); - } catch (JSONException e) { - e.printStackTrace(); - } - return true; - } catch (ActivityNotFoundException e) { - //e.printStackTrace(); - ToastLogger.showText(StringTable.get(R.string.message_extension_not_found), false); - return false; - } - } + public static final String EXT_BROADCAST_ANY = "osu.droid.ext.broadcast.any"; + + public static boolean downloadExtension() { + final Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.edplan.cn/osu/droid/extension/latest_ext.php")); + GlobalManager.getInstance().getMainActivity().startActivity(intent); + return true; + } + + public static boolean isExtensionEnable() { + return Config.isEnableExtension(); + } + + public static void broadcastMsg(String apiName, String data) { + if (!isExtensionEnable()) return; + Intent intent = new Intent(EXT_BROADCAST_ANY); + intent.putExtra("api", apiName); + intent.putExtra("type", "anyBroadcast"); + intent.putExtra("data", data); + GlobalManager.getInstance().getMainActivity().sendBroadcast(intent); + } + + public static void onSelectTrack(TrackInfo info) { + if (!isExtensionEnable() || info == null) { + return; + } + try { + JSONObject game = new JSONObject(); + game.put("file", info.getFilename()); + game.put("mods", new JSONArray(ModMenu.getInstance().getMod())); + broadcastMsg("onSelectTrack", game.toString()); + } catch (JSONException e) { + e.printStackTrace(); + } + } + + public static void onStartGame(TrackInfo info) { + if (!isExtensionEnable() || info == null) { + return; + } + try { + JSONObject game = new JSONObject(); + game.put("file", info.getFilename()); + game.put("mods", new JSONArray(ModMenu.getInstance().getMod())); + game.put("gameId", GameHelper.getGameid()); + broadcastMsg("onStartGame", game.toString()); + } catch (JSONException e) { + e.printStackTrace(); + } + } + + public static void onRestartGame(TrackInfo info) { + if (!isExtensionEnable() || info == null) { + return; + } + try { + JSONObject game = new JSONObject(); + game.put("file", info.getFilename()); + game.put("mods", new JSONArray(ModMenu.getInstance().getMod())); + game.put("gameId", GameHelper.getGameid()); + broadcastMsg("onRestartGame", game.toString()); + } catch (JSONException e) { + e.printStackTrace(); + } + } + + public static void onExitGame(TrackInfo info) { + if (!isExtensionEnable() || info == null) { + return; + } + try { + JSONObject game = new JSONObject(); + game.put("file", info.getFilename()); + game.put("mods", new JSONArray(ModMenu.getInstance().getMod())); + game.put("gameId", GameHelper.getGameid()); + broadcastMsg("onExitgame", game.toString()); + } catch (JSONException e) { + e.printStackTrace(); + } + } + + public static void onGameover(TrackInfo info) { + if (!isExtensionEnable() || info == null) { + return; + } + try { + JSONObject game = new JSONObject(); + game.put("file", info.getFilename()); + game.put("mods", new JSONArray(ModMenu.getInstance().getMod())); + game.put("gameId", GameHelper.getGameid()); + broadcastMsg("onGameover", game.toString()); + } catch (JSONException e) { + e.printStackTrace(); + } + } + + public static void onEndGame(TrackInfo lastTrack, StatisticV2 stat) { + if (!isExtensionEnable() || lastTrack == null) { + return; + } + try { + JSONObject game = new JSONObject(); + game.put("file", lastTrack.getFilename()); + game.put("mods", new JSONArray(stat.getMod())); + game.put("score", stat.getTotalScore()); + game.put("combo", stat.getMaxCombo()); + game.put("hit300", stat.getHit300()); + game.put("hit100", stat.getHit100()); + game.put("hit50", stat.getHit50()); + game.put("miss", stat.getMisses()); + broadcastMsg("onEndGame", game.toString()); + } catch (JSONException e) { + e.printStackTrace(); + } + } + + public static void onPauseGame(TrackInfo info) { + if (!isExtensionEnable() || info == null) { + return; + } + try { + JSONObject game = new JSONObject(); + game.put("file", info.getFilename()); + game.put("mods", new JSONArray(ModMenu.getInstance().getMod())); + game.put("gameId", GameHelper.getGameid()); + broadcastMsg("onPauseGame", game.toString()); + } catch (JSONException e) { + e.printStackTrace(); + } + } + + public static void onResume(TrackInfo info) { + if (!isExtensionEnable() || info == null) { + return; + } + try { + JSONObject game = new JSONObject(); + game.put("file", info.getFilename()); + game.put("mods", new JSONArray(ModMenu.getInstance().getMod())); + game.put("gameId", GameHelper.getGameid()); + broadcastMsg("onResumeGame", game.toString()); + } catch (JSONException e) { + e.printStackTrace(); + } + } + + public static void onQuitGame(TrackInfo info) { + if (!isExtensionEnable() || info == null) { + return; + } + try { + JSONObject game = new JSONObject(); + game.put("file", info.getFilename()); + game.put("mods", new JSONArray(ModMenu.getInstance().getMod())); + game.put("gameId", GameHelper.getGameid()); + broadcastMsg("onQuitGame", game.toString()); + } catch (JSONException e) { + e.printStackTrace(); + } + } + + public static boolean openBeatmap(String filepath) { + if (!isExtensionEnable()) return false; + try { + Intent intent = new Intent(); + ComponentName componentName = new ComponentName("com.edplan.osu.osudroidextension", "com.edplan.osu.osudroidextension.ApiActivity"); + intent.setComponent(componentName); + intent.putExtra("api", "openOsuFile"); + try { + JSONObject game = new JSONObject(); + game.put("file", filepath); + game.put("mods", new JSONArray(ModMenu.getInstance().getMod())); + intent.putExtra("data", game.toString()); + GlobalManager.getInstance().getMainActivity().startActivity(intent); + } catch (JSONException e) { + e.printStackTrace(); + } + return true; + } catch (ActivityNotFoundException e) { + //e.printStackTrace(); + ToastLogger.showText(StringTable.get(R.string.message_extension_not_found), false); + return false; + } + } } diff --git a/src/com/edlplan/favorite/FavoriteLibrary.java b/src/com/edlplan/favorite/FavoriteLibrary.java index 6a321b86..57c557f7 100644 --- a/src/com/edlplan/favorite/FavoriteLibrary.java +++ b/src/com/edlplan/favorite/FavoriteLibrary.java @@ -19,135 +19,135 @@ public class FavoriteLibrary { - private static FavoriteLibrary library = new FavoriteLibrary(); - private File json; - private HashMap> favorites = new HashMap<>(); - - public static FavoriteLibrary get() { - return library; - } - - private static void ensureFile(File file) throws IOException { - checkExistDir(file.getParentFile()); - if (!file.exists()) { - file.createNewFile(); - } - } - - private static void checkExistDir(File dir) { - if (!dir.exists()) dir.mkdirs(); - } - - private static String readFull(File file) throws IOException { - FileInputStream inputStream = new FileInputStream(file); - byte[] bytes = new byte[inputStream.available()]; - inputStream.read(bytes); - inputStream.close(); - return new String(bytes, Charset.forName("UTF-8")); - } - - public static void cover(String string, File file) throws IOException { - ensureFile(file); - FileOutputStream outputStream = new FileOutputStream(file); - outputStream.write(string.getBytes()); - outputStream.close(); - } - - public void load() { - String jsonPath = Config.getCorePath() + "json/favorite.json"; - json = new File(jsonPath); - try { - ensureFile(json); - JSONObject favorite; - String jsonTxt = readFull(json); - if (jsonTxt.isEmpty()) { - favorite = new JSONObject(); - } else { - try { - favorite = new JSONObject(jsonTxt); - } catch (JSONException e) { - e.printStackTrace(); - favorite = new JSONObject(); - } - } - Iterator iterator = favorite.keys(); - while (iterator.hasNext()) { - String floder = iterator.next(); - JSONArray array = favorite.optJSONArray(floder); - if (!favorites.containsKey(floder)) { - favorites.put(floder, new HashSet<>()); - } - for (int i = 0; i < array.length(); i++) { - favorites.get(floder).add(array.optString(i)); - } - } - } catch (IOException e) { - e.printStackTrace(); - } - } - - public HashSet getMaps(String floder) { - return favorites.get(floder); - } - - public Set getFolders() { - return favorites.keySet(); - } - - public void addFolder(String name) { - if (!favorites.containsKey(name)) { - favorites.put(name, new HashSet<>()); - save(); - } - } - - public void add(String folder, String path) { - if (!favorites.containsKey(folder)) { - favorites.put(folder, new HashSet<>()); - } - favorites.get(folder).add(path); - save(); - } - - public void remove(String folder) { - if (favorites.containsKey(folder)) { - favorites.remove(folder); - save(); - } - } - - public void remove(String folder, String path) { - if (favorites.containsKey(folder)) { - if (favorites.get(folder).contains(path)) { - favorites.get(folder).remove(path); - save(); - } - } - } - - public boolean inFolder(String folder, String path) { - return favorites.containsKey(folder) && favorites.get(folder).contains(path); - } - - /** - * 保存到文件 - */ - public void save() { - try { - JSONObject object = new JSONObject(); - for (Map.Entry> entry : favorites.entrySet()) { - JSONArray array = new JSONArray(); - for (String path : entry.getValue()) { - array.put(path); - } - object.put(entry.getKey(), array); - } - cover(object.toString(2), json); - } catch (IOException e) { - e.printStackTrace(); - } catch (JSONException e) { - e.printStackTrace(); - } - } + private static FavoriteLibrary library = new FavoriteLibrary(); + private File json; + private HashMap> favorites = new HashMap<>(); + + public static FavoriteLibrary get() { + return library; + } + + private static void ensureFile(File file) throws IOException { + checkExistDir(file.getParentFile()); + if (!file.exists()) { + file.createNewFile(); + } + } + + private static void checkExistDir(File dir) { + if (!dir.exists()) dir.mkdirs(); + } + + private static String readFull(File file) throws IOException { + FileInputStream inputStream = new FileInputStream(file); + byte[] bytes = new byte[inputStream.available()]; + inputStream.read(bytes); + inputStream.close(); + return new String(bytes, Charset.forName("UTF-8")); + } + + public static void cover(String string, File file) throws IOException { + ensureFile(file); + FileOutputStream outputStream = new FileOutputStream(file); + outputStream.write(string.getBytes()); + outputStream.close(); + } + + public void load() { + String jsonPath = Config.getCorePath() + "json/favorite.json"; + json = new File(jsonPath); + try { + ensureFile(json); + JSONObject favorite; + String jsonTxt = readFull(json); + if (jsonTxt.isEmpty()) { + favorite = new JSONObject(); + } else { + try { + favorite = new JSONObject(jsonTxt); + } catch (JSONException e) { + e.printStackTrace(); + favorite = new JSONObject(); + } + } + Iterator iterator = favorite.keys(); + while (iterator.hasNext()) { + String floder = iterator.next(); + JSONArray array = favorite.optJSONArray(floder); + if (!favorites.containsKey(floder)) { + favorites.put(floder, new HashSet<>()); + } + for (int i = 0; i < array.length(); i++) { + favorites.get(floder).add(array.optString(i)); + } + } + } catch (IOException e) { + e.printStackTrace(); + } + } + + public HashSet getMaps(String floder) { + return favorites.get(floder); + } + + public Set getFolders() { + return favorites.keySet(); + } + + public void addFolder(String name) { + if (!favorites.containsKey(name)) { + favorites.put(name, new HashSet<>()); + save(); + } + } + + public void add(String folder, String path) { + if (!favorites.containsKey(folder)) { + favorites.put(folder, new HashSet<>()); + } + favorites.get(folder).add(path); + save(); + } + + public void remove(String folder) { + if (favorites.containsKey(folder)) { + favorites.remove(folder); + save(); + } + } + + public void remove(String folder, String path) { + if (favorites.containsKey(folder)) { + if (favorites.get(folder).contains(path)) { + favorites.get(folder).remove(path); + save(); + } + } + } + + public boolean inFolder(String folder, String path) { + return favorites.containsKey(folder) && favorites.get(folder).contains(path); + } + + /** + * 保存到文件 + */ + public void save() { + try { + JSONObject object = new JSONObject(); + for (Map.Entry> entry : favorites.entrySet()) { + JSONArray array = new JSONArray(); + for (String path : entry.getValue()) { + array.put(path); + } + object.put(entry.getKey(), array); + } + cover(object.toString(2), json); + } catch (IOException e) { + e.printStackTrace(); + } catch (JSONException e) { + e.printStackTrace(); + } + } } diff --git a/src/com/edlplan/framework/support/Framework.java b/src/com/edlplan/framework/support/Framework.java index 2d87a282..2bde5117 100644 --- a/src/com/edlplan/framework/support/Framework.java +++ b/src/com/edlplan/framework/support/Framework.java @@ -9,47 +9,47 @@ public class Framework { - public static final int PLATFORM_WIN_PC = 1; - - public static final int PLATFORM_ANDROID = 2; - - private static final int frameworkVersion = 1; - - private static final int platform = PLATFORM_ANDROID; - - public static int getFrameworkVersion() { - return frameworkVersion; - } - - public static int getPlatform() { - return platform; - } - - public static File getFrameworkDir() { - final File dir = new File(Environment.getExternalStorageDirectory(), "EdFramework"); - FileUtils.checkExistDir(dir); - return dir; - } - - /** - * 获取相对的精确时间 - */ - public static double relativePreciseTimeMillion() { - return System.nanoTime() / 1000000d; - } - - public static int msToNm(double ms) { - return (int) (ms * 1000000); - } - - public static long absoluteTimeMillion() { - return System.currentTimeMillis(); - } - - /** - * @return 框架的标准时间 - */ - public static double frameworkTime() { - return SystemClock.uptimeMillis(); - } -} \ No newline at end of file + public static final int PLATFORM_WIN_PC = 1; + + public static final int PLATFORM_ANDROID = 2; + + private static final int frameworkVersion = 1; + + private static final int platform = PLATFORM_ANDROID; + + public static int getFrameworkVersion() { + return frameworkVersion; + } + + public static int getPlatform() { + return platform; + } + + public static File getFrameworkDir() { + final File dir = new File(Environment.getExternalStorageDirectory(), "EdFramework"); + FileUtils.checkExistDir(dir); + return dir; + } + + /** + * 获取相对的精确时间 + */ + public static double relativePreciseTimeMillion() { + return System.nanoTime() / 1000000d; + } + + public static int msToNm(double ms) { + return (int) (ms * 1000000); + } + + public static long absoluteTimeMillion() { + return System.currentTimeMillis(); + } + + /** + * @return 框架的标准时间 + */ + public static double frameworkTime() { + return SystemClock.uptimeMillis(); + } +} diff --git a/src/com/edlplan/framework/support/ProxySprite.java b/src/com/edlplan/framework/support/ProxySprite.java index 016cbc0a..c8e3e838 100644 --- a/src/com/edlplan/framework/support/ProxySprite.java +++ b/src/com/edlplan/framework/support/ProxySprite.java @@ -3,30 +3,30 @@ import com.edlplan.framework.support.graphics.BaseCanvas; public class ProxySprite extends SupportSprite { - DrawProxy drawProxy; - - public ProxySprite(float width, float height) { - super(width, height); - } - - public void setDrawProxy(DrawProxy drawProxy) { - this.drawProxy = drawProxy; - } - - public DrawProxy getDrawProxy() { - return drawProxy; - } - - @Override - protected void onSupportDraw(BaseCanvas canvas) { - super.onSupportDraw(canvas); - if (drawProxy != null) { - drawProxy.onSupportDraw(canvas); - } - } - - public interface DrawProxy { - void onSupportDraw(BaseCanvas canvas); - } + DrawProxy drawProxy; + + public ProxySprite(float width, float height) { + super(width, height); + } + + public void setDrawProxy(DrawProxy drawProxy) { + this.drawProxy = drawProxy; + } + + public DrawProxy getDrawProxy() { + return drawProxy; + } + + @Override + protected void onSupportDraw(BaseCanvas canvas) { + super.onSupportDraw(canvas); + if (drawProxy != null) { + drawProxy.onSupportDraw(canvas); + } + } + + public interface DrawProxy { + void onSupportDraw(BaseCanvas canvas); + } } diff --git a/src/com/edlplan/framework/support/SupportSprite.java b/src/com/edlplan/framework/support/SupportSprite.java index d76302f4..38f8960a 100644 --- a/src/com/edlplan/framework/support/SupportSprite.java +++ b/src/com/edlplan/framework/support/SupportSprite.java @@ -14,65 +14,65 @@ public class SupportSprite extends Entity { - private OnSupportDraw draw; + private OnSupportDraw draw; - private SupportCanvas canvas; + private SupportCanvas canvas; - private float width, height; + private float width, height; - public SupportSprite(float width, float height) { - this.width = width; - this.height = height; - } + public SupportSprite(float width, float height) { + this.width = width; + this.height = height; + } - public OnSupportDraw getDraw() { - return draw; - } + public OnSupportDraw getDraw() { + return draw; + } - public void setDraw(OnSupportDraw draw) { - this.draw = draw; - } + public void setDraw(OnSupportDraw draw) { + this.draw = draw; + } - protected void onSupportDraw(BaseCanvas canvas) { - if (draw != null) { - draw.draw(canvas); - } - } + protected void onSupportDraw(BaseCanvas canvas) { + if (draw != null) { + draw.draw(canvas); + } + } - @Override - protected void doDraw(GL10 pGL, Camera pCamera) { - SupportState.setUsingSupportCamera(true); - BatchEngine.pGL = pGL; + @Override + protected void doDraw(GL10 pGL, Camera pCamera) { + SupportState.setUsingSupportCamera(true); + BatchEngine.pGL = pGL; - GLWrapped.blend.setBlendType(BlendType.Normal); - GLWrapped.blend.apply(); + GLWrapped.blend.setBlendType(BlendType.Normal); + GLWrapped.blend.apply(); - com.edlplan.framework.support.graphics.Camera camera = new com.edlplan.framework.support.graphics.Camera(); - BatchEngine.setGlobalCamera(camera); + com.edlplan.framework.support.graphics.Camera camera = new com.edlplan.framework.support.graphics.Camera(); + BatchEngine.setGlobalCamera(camera); - if (canvas == null) { - canvas = new SupportCanvas(new SupportCanvas.SupportInfo() {{ - supportWidth = width; - supportHeight = height; - }}); - } - canvas.prepare(); - int count = canvas.save(); - int count2 = canvas.getBlendSetting().save(); + if (canvas == null) { + canvas = new SupportCanvas(new SupportCanvas.SupportInfo() {{ + supportWidth = width; + supportHeight = height; + }}); + } + canvas.prepare(); + int count = canvas.save(); + int count2 = canvas.getBlendSetting().save(); - onSupportDraw(canvas); + onSupportDraw(canvas); - canvas.getBlendSetting().restoreToCount(count2); - canvas.restoreToCount(count); - canvas.unprepare(); + canvas.getBlendSetting().restoreToCount(count2); + canvas.restoreToCount(count); + canvas.unprepare(); - SupportState.setUsingSupportCamera(false); - GLHelper.blendFunction(pGL, BlendType.Normal.srcTypePreM, BlendType.Normal.dstTypePreM); - } + SupportState.setUsingSupportCamera(false); + GLHelper.blendFunction(pGL, BlendType.Normal.srcTypePreM, BlendType.Normal.dstTypePreM); + } - public interface OnSupportDraw { + public interface OnSupportDraw { - void draw(BaseCanvas canvas); + void draw(BaseCanvas canvas); - } + } } diff --git a/src/com/edlplan/framework/support/SupportState.java b/src/com/edlplan/framework/support/SupportState.java index 703a395d..f8a44ece 100644 --- a/src/com/edlplan/framework/support/SupportState.java +++ b/src/com/edlplan/framework/support/SupportState.java @@ -4,15 +4,15 @@ public class SupportState { - private static boolean usingSupportCamera = false; + private static boolean usingSupportCamera = false; - public static boolean isUsingSupportCamera() { - return usingSupportCamera; - } + public static boolean isUsingSupportCamera() { + return usingSupportCamera; + } - public static void setUsingSupportCamera(boolean usingSupportCamera) { - BatchEngine.flush(); - SupportState.usingSupportCamera = usingSupportCamera; - } + public static void setUsingSupportCamera(boolean usingSupportCamera) { + BatchEngine.flush(); + SupportState.usingSupportCamera = usingSupportCamera; + } } diff --git a/src/com/edlplan/framework/support/batch/AbstractBatch.java b/src/com/edlplan/framework/support/batch/AbstractBatch.java index 6e15ec70..ccd301f6 100644 --- a/src/com/edlplan/framework/support/batch/AbstractBatch.java +++ b/src/com/edlplan/framework/support/batch/AbstractBatch.java @@ -13,63 +13,63 @@ */ public abstract class AbstractBatch { - protected abstract void onBind(); - - protected abstract void onUnbind(); - - public abstract void add(T t); - - protected abstract void clearData(); - - protected abstract boolean applyToGL(); - - public void addAll(T... ts) { - for (T t : ts) { - add(t); - } - } - - protected void checkForBind() { - if (!isBind()) { - bind(); - } - } - - public final void bind() { - BatchEngine.bind(this); - onBind(); - } - - public final void unbind() { - BatchEngine.unbind(this); - onUnbind(); - } - - public final boolean isBind() { - return BatchEngine.currentBatch() == this; - } - - public final void flush() { - GL10 pGL = BatchEngine.pGL; - int type = GLHelper.getCurrentMatrixType(); - if (SupportState.isUsingSupportCamera()) { - pGL.glMatrixMode(GL10.GL_PROJECTION); - pGL.glPushMatrix(); - pGL.glMultMatrixf(BatchEngine.shaderGlobals.camera.getProjectionMatrix().data, 0); - - pGL.glMatrixMode(GL10.GL_MODELVIEW); - pGL.glPushMatrix(); - pGL.glMultMatrixf(BatchEngine.shaderGlobals.camera.getMaskMatrix().data, 0); - } - if (applyToGL()) { - clearData(); - } - if (SupportState.isUsingSupportCamera()) { - pGL.glMatrixMode(GL10.GL_PROJECTION); - pGL.glPopMatrix(); - pGL.glMatrixMode(GL10.GL_MODELVIEW); - pGL.glPopMatrix(); - pGL.glMatrixMode(type); - } - } + protected abstract void onBind(); + + protected abstract void onUnbind(); + + public abstract void add(T t); + + protected abstract void clearData(); + + protected abstract boolean applyToGL(); + + public void addAll(T... ts) { + for (T t : ts) { + add(t); + } + } + + protected void checkForBind() { + if (!isBind()) { + bind(); + } + } + + public final void bind() { + BatchEngine.bind(this); + onBind(); + } + + public final void unbind() { + BatchEngine.unbind(this); + onUnbind(); + } + + public final boolean isBind() { + return BatchEngine.currentBatch() == this; + } + + public final void flush() { + GL10 pGL = BatchEngine.pGL; + int type = GLHelper.getCurrentMatrixType(); + if (SupportState.isUsingSupportCamera()) { + pGL.glMatrixMode(GL10.GL_PROJECTION); + pGL.glPushMatrix(); + pGL.glMultMatrixf(BatchEngine.shaderGlobals.camera.getProjectionMatrix().data, 0); + + pGL.glMatrixMode(GL10.GL_MODELVIEW); + pGL.glPushMatrix(); + pGL.glMultMatrixf(BatchEngine.shaderGlobals.camera.getMaskMatrix().data, 0); + } + if (applyToGL()) { + clearData(); + } + if (SupportState.isUsingSupportCamera()) { + pGL.glMatrixMode(GL10.GL_PROJECTION); + pGL.glPopMatrix(); + pGL.glMatrixMode(GL10.GL_MODELVIEW); + pGL.glPopMatrix(); + pGL.glMatrixMode(type); + } + } } diff --git a/src/com/edlplan/framework/support/batch/BatchEngine.java b/src/com/edlplan/framework/support/batch/BatchEngine.java index 793dcf8a..e7710c95 100644 --- a/src/com/edlplan/framework/support/batch/BatchEngine.java +++ b/src/com/edlplan/framework/support/batch/BatchEngine.java @@ -7,58 +7,58 @@ public class BatchEngine { - public static GL10 pGL; - public static ShaderGlobals shaderGlobals = new ShaderGlobals(); - private static AbstractBatch savedbatch = null; - private static boolean flushing = false; + public static GL10 pGL; + public static ShaderGlobals shaderGlobals = new ShaderGlobals(); + private static AbstractBatch savedbatch = null; + private static boolean flushing = false; - public static ShaderGlobals getShaderGlobals() { - return shaderGlobals; - } + public static ShaderGlobals getShaderGlobals() { + return shaderGlobals; + } - /** - * 设置全局透明度, - * - * @param alpha - */ - public static void setGlobalAlpha(float alpha) { - if (Math.abs(shaderGlobals.alpha - alpha) > 0.002f) { - flush(); - shaderGlobals.alpha = alpha; - } - } + /** + * 设置全局透明度, + * + * @param alpha + */ + public static void setGlobalAlpha(float alpha) { + if (Math.abs(shaderGlobals.alpha - alpha) > 0.002f) { + flush(); + shaderGlobals.alpha = alpha; + } + } - /** - * 更换全局相机,调用时必定触发flush - * - * @param camera - */ - public static void setGlobalCamera(Camera camera) { - flush(); - shaderGlobals.camera.set(camera); - } + /** + * 更换全局相机,调用时必定触发flush + * + * @param camera + */ + public static void setGlobalCamera(Camera camera) { + flush(); + shaderGlobals.camera.set(camera); + } - static void bind(AbstractBatch batch) { - flush(); - savedbatch = batch; - } + static void bind(AbstractBatch batch) { + flush(); + savedbatch = batch; + } - static void unbind(AbstractBatch batch) { - if (savedbatch == batch) { - savedbatch = null; - } - } + static void unbind(AbstractBatch batch) { + if (savedbatch == batch) { + savedbatch = null; + } + } - public static void flush() { - if (flushing) return; - if (savedbatch != null) { - flushing = true; - savedbatch.flush(); - flushing = false; - } - } + public static void flush() { + if (flushing) return; + if (savedbatch != null) { + flushing = true; + savedbatch.flush(); + flushing = false; + } + } - public static AbstractBatch currentBatch() { - return savedbatch; - } + public static AbstractBatch currentBatch() { + return savedbatch; + } } diff --git a/src/com/edlplan/framework/support/batch/object/ATextureQuad.java b/src/com/edlplan/framework/support/batch/object/ATextureQuad.java index 261189af..8918b8ad 100644 --- a/src/com/edlplan/framework/support/batch/object/ATextureQuad.java +++ b/src/com/edlplan/framework/support/batch/object/ATextureQuad.java @@ -4,8 +4,8 @@ public abstract class ATextureQuad { - public TextureRegion texture; + public TextureRegion texture; - public abstract void write(float[] ary, int offset); + public abstract void write(float[] ary, int offset); -} \ No newline at end of file +} diff --git a/src/com/edlplan/framework/support/batch/object/FlippableTextureQuad.java b/src/com/edlplan/framework/support/batch/object/FlippableTextureQuad.java index 2306d238..d54c1ecd 100644 --- a/src/com/edlplan/framework/support/batch/object/FlippableTextureQuad.java +++ b/src/com/edlplan/framework/support/batch/object/FlippableTextureQuad.java @@ -11,208 +11,208 @@ public class FlippableTextureQuad extends ATextureQuad { - public Vec2 size = new Vec2(); - - public Vec2Ref position = new Vec2Ref(); - - public Anchor anchor = Anchor.Center; - - public Vec2Ref scale; - - public FloatRef rotation; - - public FloatRef alpha = new FloatRef(1); - - public Color4 accentColor; - - public float u1, v1, u2, v2; - - public BooleanRef flipH = new BooleanRef(false); - - public BooleanRef flipV = new BooleanRef(false); - - public FlippableTextureQuad enableScale() { - if (scale == null) { - scale = new Vec2Ref(); - scale.x.value = scale.y.value = 1; - } - return this; - } - - public FlippableTextureQuad enableColor() { - if (accentColor == null) { - accentColor = Color4.White.copyNew(); - } - return this; - } - - public FlippableTextureQuad syncColor(Color4 color) { - accentColor = color; - return this; - } - - public FlippableTextureQuad syncAlpha(FloatRef ref) { - this.alpha = ref; - return this; - } - - public FlippableTextureQuad enableRotation() { - if (rotation == null) { - rotation = new FloatRef(); - } - return this; - } - - public FlippableTextureQuad syncRotation(FloatRef ref) { - this.rotation = ref; - return this; - } - - public void setTextureAndSize(TextureRegion texture) { - this.texture = texture; - size.set(texture.getWidth(), texture.getHeight()); - u1 = texture.getTextureCoordinateX1(); - u2 = texture.getTextureCoordinateX2(); - v1 = texture.getTextureCoordinateY1(); - v2 = texture.getTextureCoordinateY2(); - } - - public void setBaseWidth(float width) { - size.set(width, width * (size.y / size.x)); - } - - public void setBaseHeight(float height) { - size.set(height * (size.x / size.y), height); - } - - @Override - public void write(float[] ary, int offset) { - - float u1; - float v1; - float u2; - float v2; - - if (flipH.value) { - u1 = this.u2; - u2 = this.u1; - } else { - u1 = this.u1; - u2 = this.u2; - } - - if (flipV.value) { - v1 = this.v2; - v2 = this.v1; - } else { - v1 = this.v1; - v2 = this.v2; - } - - float l = -size.x * anchor.x(); - float r = size.x + l; - float t = -size.y * anchor.y(); - float b = size.y + t; - float cr, cg, cb, ca; - if (accentColor == null) { - cr = cg = cb = ca = alpha.value; - } else { - float a = alpha.value; - cr = a * accentColor.r; - cg = a * accentColor.g; - cb = a * accentColor.b; - ca = a * accentColor.a; - } - - if (scale != null) { - l *= scale.x.value; - r *= scale.x.value; - t *= scale.y.value; - b *= scale.y.value; - } - - if (rotation == null) { - l += position.x.value; - r += position.x.value; - t += position.y.value; - b += position.y.value; - ary[offset++] = l; - ary[offset++] = t; - ary[offset++] = u1; - ary[offset++] = v1; - ary[offset++] = cr; - ary[offset++] = cg; - ary[offset++] = cb; - ary[offset++] = ca; - - ary[offset++] = r; - ary[offset++] = t; - ary[offset++] = u2; - ary[offset++] = v1; - ary[offset++] = cr; - ary[offset++] = cg; - ary[offset++] = cb; - ary[offset++] = ca; - - ary[offset++] = l; - ary[offset++] = b; - ary[offset++] = u1; - ary[offset++] = v2; - ary[offset++] = cr; - ary[offset++] = cg; - ary[offset++] = cb; - ary[offset++] = ca; - - - ary[offset++] = r; - ary[offset++] = b; - ary[offset++] = u2; - ary[offset++] = v2; - ary[offset++] = cr; - ary[offset++] = cg; - ary[offset++] = cb; - ary[offset++] = ca; - } else { - final float s = (float) Math.sin(rotation.value); - final float c = (float) Math.cos(rotation.value); - final float x = position.x.value, y = position.y.value; - ary[offset++] = l * c - t * s + x; - ary[offset++] = l * s + t * c + y; - ary[offset++] = u1; - ary[offset++] = v1; - ary[offset++] = cr; - ary[offset++] = cg; - ary[offset++] = cb; - ary[offset++] = ca; - - ary[offset++] = r * c - t * s + x; - ary[offset++] = r * s + t * c + y; - ary[offset++] = u2; - ary[offset++] = v1; - ary[offset++] = cr; - ary[offset++] = cg; - ary[offset++] = cb; - ary[offset++] = ca; - - ary[offset++] = l * c - b * s + x; - ary[offset++] = l * s + b * c + y; - ary[offset++] = u1; - ary[offset++] = v2; - ary[offset++] = cr; - ary[offset++] = cg; - ary[offset++] = cb; - ary[offset++] = ca; - - ary[offset++] = r * c - b * s + x; - ary[offset++] = r * s + b * c + y; - ary[offset++] = u2; - ary[offset++] = v2; - ary[offset++] = cr; - ary[offset++] = cg; - ary[offset++] = cb; - ary[offset++] = ca; - } - } + public Vec2 size = new Vec2(); + + public Vec2Ref position = new Vec2Ref(); + + public Anchor anchor = Anchor.Center; + + public Vec2Ref scale; + + public FloatRef rotation; + + public FloatRef alpha = new FloatRef(1); + + public Color4 accentColor; + + public float u1, v1, u2, v2; + + public BooleanRef flipH = new BooleanRef(false); + + public BooleanRef flipV = new BooleanRef(false); + + public FlippableTextureQuad enableScale() { + if (scale == null) { + scale = new Vec2Ref(); + scale.x.value = scale.y.value = 1; + } + return this; + } + + public FlippableTextureQuad enableColor() { + if (accentColor == null) { + accentColor = Color4.White.copyNew(); + } + return this; + } + + public FlippableTextureQuad syncColor(Color4 color) { + accentColor = color; + return this; + } + + public FlippableTextureQuad syncAlpha(FloatRef ref) { + this.alpha = ref; + return this; + } + + public FlippableTextureQuad enableRotation() { + if (rotation == null) { + rotation = new FloatRef(); + } + return this; + } + + public FlippableTextureQuad syncRotation(FloatRef ref) { + this.rotation = ref; + return this; + } + + public void setTextureAndSize(TextureRegion texture) { + this.texture = texture; + size.set(texture.getWidth(), texture.getHeight()); + u1 = texture.getTextureCoordinateX1(); + u2 = texture.getTextureCoordinateX2(); + v1 = texture.getTextureCoordinateY1(); + v2 = texture.getTextureCoordinateY2(); + } + + public void setBaseWidth(float width) { + size.set(width, width * (size.y / size.x)); + } + + public void setBaseHeight(float height) { + size.set(height * (size.x / size.y), height); + } + + @Override + public void write(float[] ary, int offset) { + + float u1; + float v1; + float u2; + float v2; + + if (flipH.value) { + u1 = this.u2; + u2 = this.u1; + } else { + u1 = this.u1; + u2 = this.u2; + } + + if (flipV.value) { + v1 = this.v2; + v2 = this.v1; + } else { + v1 = this.v1; + v2 = this.v2; + } + + float l = -size.x * anchor.x(); + float r = size.x + l; + float t = -size.y * anchor.y(); + float b = size.y + t; + float cr, cg, cb, ca; + if (accentColor == null) { + cr = cg = cb = ca = alpha.value; + } else { + float a = alpha.value; + cr = a * accentColor.r; + cg = a * accentColor.g; + cb = a * accentColor.b; + ca = a * accentColor.a; + } + + if (scale != null) { + l *= scale.x.value; + r *= scale.x.value; + t *= scale.y.value; + b *= scale.y.value; + } + + if (rotation == null) { + l += position.x.value; + r += position.x.value; + t += position.y.value; + b += position.y.value; + ary[offset++] = l; + ary[offset++] = t; + ary[offset++] = u1; + ary[offset++] = v1; + ary[offset++] = cr; + ary[offset++] = cg; + ary[offset++] = cb; + ary[offset++] = ca; + + ary[offset++] = r; + ary[offset++] = t; + ary[offset++] = u2; + ary[offset++] = v1; + ary[offset++] = cr; + ary[offset++] = cg; + ary[offset++] = cb; + ary[offset++] = ca; + + ary[offset++] = l; + ary[offset++] = b; + ary[offset++] = u1; + ary[offset++] = v2; + ary[offset++] = cr; + ary[offset++] = cg; + ary[offset++] = cb; + ary[offset++] = ca; + + + ary[offset++] = r; + ary[offset++] = b; + ary[offset++] = u2; + ary[offset++] = v2; + ary[offset++] = cr; + ary[offset++] = cg; + ary[offset++] = cb; + ary[offset++] = ca; + } else { + final float s = (float) Math.sin(rotation.value); + final float c = (float) Math.cos(rotation.value); + final float x = position.x.value, y = position.y.value; + ary[offset++] = l * c - t * s + x; + ary[offset++] = l * s + t * c + y; + ary[offset++] = u1; + ary[offset++] = v1; + ary[offset++] = cr; + ary[offset++] = cg; + ary[offset++] = cb; + ary[offset++] = ca; + + ary[offset++] = r * c - t * s + x; + ary[offset++] = r * s + t * c + y; + ary[offset++] = u2; + ary[offset++] = v1; + ary[offset++] = cr; + ary[offset++] = cg; + ary[offset++] = cb; + ary[offset++] = ca; + + ary[offset++] = l * c - b * s + x; + ary[offset++] = l * s + b * c + y; + ary[offset++] = u1; + ary[offset++] = v2; + ary[offset++] = cr; + ary[offset++] = cg; + ary[offset++] = cb; + ary[offset++] = ca; + + ary[offset++] = r * c - b * s + x; + ary[offset++] = r * s + b * c + y; + ary[offset++] = u2; + ary[offset++] = v2; + ary[offset++] = cr; + ary[offset++] = cg; + ary[offset++] = cb; + ary[offset++] = ca; + } + } } diff --git a/src/com/edlplan/framework/support/batch/object/MultipleFlippableTextureQuad.java b/src/com/edlplan/framework/support/batch/object/MultipleFlippableTextureQuad.java index 18f0d8f4..a43532b6 100644 --- a/src/com/edlplan/framework/support/batch/object/MultipleFlippableTextureQuad.java +++ b/src/com/edlplan/framework/support/batch/object/MultipleFlippableTextureQuad.java @@ -8,77 +8,77 @@ public class MultipleFlippableTextureQuad extends FlippableTextureQuad { - public TextureEntry[] textureEntries; - - public TextureEntry currentEntry; - - public void switchTexture(int id) { - if (textureEntries.length == 0) { - throw new RuntimeException(); - } - id = id % textureEntries.length; - currentEntry = textureEntries[id]; - texture = currentEntry.texture; - size.set(currentEntry.size); - u1 = currentEntry.u1; - v1 = currentEntry.v1; - u2 = currentEntry.u2; - v2 = currentEntry.v2; - } - - public void initialWithTextureList(List textures) { - - textureEntries = new TextureEntry[textures.size()]; - if (textureEntries.length == 0) { - return; - } - - for (int i = 0; i < textureEntries.length; i++) { - TextureRegion texture = textures.get(i); - TextureEntry entry = new TextureEntry(); - entry.texture = texture; - entry.size = new Vec2(texture.getWidth(), texture.getHeight()); - entry.u1 = texture.getTextureCoordinateX1(); - entry.u2 = texture.getTextureCoordinateX2(); - entry.v1 = texture.getTextureCoordinateY1(); - entry.v2 = texture.getTextureCoordinateY2(); - textureEntries[i] = entry; - } - - switchTexture(0); - } - - public void initialWithTextureListWithScale(List textures, float globalScale) { - - textureEntries = new TextureEntry[textures.size()]; - if (textureEntries.length == 0) { - return; - } - - for (int i = 0; i < textureEntries.length; i++) { - TextureRegion texture = textures.get(i); - TextureEntry entry = new TextureEntry(); - entry.texture = texture; - entry.size = new Vec2(texture.getWidth() * globalScale, texture.getHeight() * globalScale); - entry.u1 = texture.getTextureCoordinateX1(); - entry.u2 = texture.getTextureCoordinateX2(); - entry.v1 = texture.getTextureCoordinateY1(); - entry.v2 = texture.getTextureCoordinateY2(); - textureEntries[i] = entry; - } - - switchTexture(0); - } - - public class TextureEntry { - - public Vec2 size = new Vec2(); - - public TextureRegion texture; - - public float u1, v1, u2, v2; - - } + public TextureEntry[] textureEntries; + + public TextureEntry currentEntry; + + public void switchTexture(int id) { + if (textureEntries.length == 0) { + throw new RuntimeException(); + } + id = id % textureEntries.length; + currentEntry = textureEntries[id]; + texture = currentEntry.texture; + size.set(currentEntry.size); + u1 = currentEntry.u1; + v1 = currentEntry.v1; + u2 = currentEntry.u2; + v2 = currentEntry.v2; + } + + public void initialWithTextureList(List textures) { + + textureEntries = new TextureEntry[textures.size()]; + if (textureEntries.length == 0) { + return; + } + + for (int i = 0; i < textureEntries.length; i++) { + TextureRegion texture = textures.get(i); + TextureEntry entry = new TextureEntry(); + entry.texture = texture; + entry.size = new Vec2(texture.getWidth(), texture.getHeight()); + entry.u1 = texture.getTextureCoordinateX1(); + entry.u2 = texture.getTextureCoordinateX2(); + entry.v1 = texture.getTextureCoordinateY1(); + entry.v2 = texture.getTextureCoordinateY2(); + textureEntries[i] = entry; + } + + switchTexture(0); + } + + public void initialWithTextureListWithScale(List textures, float globalScale) { + + textureEntries = new TextureEntry[textures.size()]; + if (textureEntries.length == 0) { + return; + } + + for (int i = 0; i < textureEntries.length; i++) { + TextureRegion texture = textures.get(i); + TextureEntry entry = new TextureEntry(); + entry.texture = texture; + entry.size = new Vec2(texture.getWidth() * globalScale, texture.getHeight() * globalScale); + entry.u1 = texture.getTextureCoordinateX1(); + entry.u2 = texture.getTextureCoordinateX2(); + entry.v1 = texture.getTextureCoordinateY1(); + entry.v2 = texture.getTextureCoordinateY2(); + textureEntries[i] = entry; + } + + switchTexture(0); + } + + public class TextureEntry { + + public Vec2 size = new Vec2(); + + public TextureRegion texture; + + public float u1, v1, u2, v2; + + } } diff --git a/src/com/edlplan/framework/support/batch/object/TextureQuad.java b/src/com/edlplan/framework/support/batch/object/TextureQuad.java index e5842445..fd8dccf3 100644 --- a/src/com/edlplan/framework/support/batch/object/TextureQuad.java +++ b/src/com/edlplan/framework/support/batch/object/TextureQuad.java @@ -9,197 +9,197 @@ public class TextureQuad extends ATextureQuad { - public static final int TopLeft = 0; - - public static final int TopRight = 1; - - public static final int BottomLeft = 2; - - public static final int BottomRight = 3; - - public Vec2 size = new Vec2(); - - public Vec2 position = new Vec2(); - - public Anchor anchor = Anchor.Center; - - public Vec2 scale; - - public FloatRef rotation; - - public FloatRef alpha = new FloatRef(1); - - public Color4 accentColor; - - public float u1, v1, u2, v2; - - public TextureQuad syncPosition(Vec2 position) { - this.position = position; - return this; - } - - public TextureQuad enableScale() { - if (scale == null) { - scale = new Vec2(1, 1); - } - return this; - } - - public TextureQuad syncScale(Vec2 vec2) { - scale = vec2; - return this; - } - - public TextureQuad enableColor() { - if (accentColor == null) { - accentColor = Color4.White.copyNew(); - } - return this; - } - - public TextureQuad syncColor(Color4 color) { - accentColor = color; - return this; - } - - public TextureQuad syncAlpha(FloatRef ref) { - this.alpha = ref; - return this; - } - - public TextureQuad enableRotation() { - if (rotation == null) { - rotation = new FloatRef(); - } - return this; - } - - public TextureQuad syncRotation(FloatRef ref) { - this.rotation = ref; - return this; - } - - public void setTextureAndSize(TextureRegion texture) { - this.texture = texture; - size.set(texture.getWidth(), texture.getHeight()); - u1 = texture.getTextureCoordinateX1(); - u2 = texture.getTextureCoordinateX2(); - v1 = texture.getTextureCoordinateY1(); - v2 = texture.getTextureCoordinateY2(); - } - - public void setBaseWidth(float width) { - size.set(width, width * (size.y / size.x)); - } - - public void setBaseHeight(float height) { - size.set(height * (size.x / size.y), height); - } - - @Override - public void write(float[] ary, int offset) { - float l = -size.x * anchor.x(); - float r = size.x + l; - float t = -size.y * anchor.y(); - float b = size.y + t; - float cr, cg, cb, ca; - if (accentColor == null) { - cr = cg = cb = ca = alpha.value; - } else { - float a = alpha.value; - cr = a * accentColor.r; - cg = a * accentColor.g; - cb = a * accentColor.b; - ca = a * accentColor.a; - } - - if (scale != null) { - l *= scale.x; - r *= scale.x; - t *= scale.y; - b *= scale.y; - } - - if (rotation == null) { - l += position.x; - r += position.x; - t += position.y; - b += position.y; - ary[offset++] = l; - ary[offset++] = t; - ary[offset++] = u1; - ary[offset++] = v1; - ary[offset++] = cr; - ary[offset++] = cg; - ary[offset++] = cb; - ary[offset++] = ca; - - ary[offset++] = r; - ary[offset++] = t; - ary[offset++] = u2; - ary[offset++] = v1; - ary[offset++] = cr; - ary[offset++] = cg; - ary[offset++] = cb; - ary[offset++] = ca; - - ary[offset++] = l; - ary[offset++] = b; - ary[offset++] = u1; - ary[offset++] = v2; - ary[offset++] = cr; - ary[offset++] = cg; - ary[offset++] = cb; - ary[offset++] = ca; - - - ary[offset++] = r; - ary[offset++] = b; - ary[offset++] = u2; - ary[offset++] = v2; - ary[offset++] = cr; - ary[offset++] = cg; - ary[offset++] = cb; - ary[offset++] = ca; - } else { - final float s = (float) Math.sin(rotation.value); - final float c = (float) Math.cos(rotation.value); - final float x = position.x, y = position.y; - ary[offset++] = l * c - t * s + x; - ary[offset++] = l * s + t * c + y; - ary[offset++] = u1; - ary[offset++] = v1; - ary[offset++] = cr; - ary[offset++] = cg; - ary[offset++] = cb; - ary[offset++] = ca; - - ary[offset++] = r * c - t * s + x; - ary[offset++] = r * s + t * c + y; - ary[offset++] = u2; - ary[offset++] = v1; - ary[offset++] = cr; - ary[offset++] = cg; - ary[offset++] = cb; - ary[offset++] = ca; - - ary[offset++] = l * c - b * s + x; - ary[offset++] = l * s + b * c + y; - ary[offset++] = u1; - ary[offset++] = v2; - ary[offset++] = cr; - ary[offset++] = cg; - ary[offset++] = cb; - ary[offset++] = ca; - - ary[offset++] = r * c - b * s + x; - ary[offset++] = r * s + b * c + y; - ary[offset++] = u2; - ary[offset++] = v2; - ary[offset++] = cr; - ary[offset++] = cg; - ary[offset++] = cb; - ary[offset++] = ca; - } - } + public static final int TopLeft = 0; + + public static final int TopRight = 1; + + public static final int BottomLeft = 2; + + public static final int BottomRight = 3; + + public Vec2 size = new Vec2(); + + public Vec2 position = new Vec2(); + + public Anchor anchor = Anchor.Center; + + public Vec2 scale; + + public FloatRef rotation; + + public FloatRef alpha = new FloatRef(1); + + public Color4 accentColor; + + public float u1, v1, u2, v2; + + public TextureQuad syncPosition(Vec2 position) { + this.position = position; + return this; + } + + public TextureQuad enableScale() { + if (scale == null) { + scale = new Vec2(1, 1); + } + return this; + } + + public TextureQuad syncScale(Vec2 vec2) { + scale = vec2; + return this; + } + + public TextureQuad enableColor() { + if (accentColor == null) { + accentColor = Color4.White.copyNew(); + } + return this; + } + + public TextureQuad syncColor(Color4 color) { + accentColor = color; + return this; + } + + public TextureQuad syncAlpha(FloatRef ref) { + this.alpha = ref; + return this; + } + + public TextureQuad enableRotation() { + if (rotation == null) { + rotation = new FloatRef(); + } + return this; + } + + public TextureQuad syncRotation(FloatRef ref) { + this.rotation = ref; + return this; + } + + public void setTextureAndSize(TextureRegion texture) { + this.texture = texture; + size.set(texture.getWidth(), texture.getHeight()); + u1 = texture.getTextureCoordinateX1(); + u2 = texture.getTextureCoordinateX2(); + v1 = texture.getTextureCoordinateY1(); + v2 = texture.getTextureCoordinateY2(); + } + + public void setBaseWidth(float width) { + size.set(width, width * (size.y / size.x)); + } + + public void setBaseHeight(float height) { + size.set(height * (size.x / size.y), height); + } + + @Override + public void write(float[] ary, int offset) { + float l = -size.x * anchor.x(); + float r = size.x + l; + float t = -size.y * anchor.y(); + float b = size.y + t; + float cr, cg, cb, ca; + if (accentColor == null) { + cr = cg = cb = ca = alpha.value; + } else { + float a = alpha.value; + cr = a * accentColor.r; + cg = a * accentColor.g; + cb = a * accentColor.b; + ca = a * accentColor.a; + } + + if (scale != null) { + l *= scale.x; + r *= scale.x; + t *= scale.y; + b *= scale.y; + } + + if (rotation == null) { + l += position.x; + r += position.x; + t += position.y; + b += position.y; + ary[offset++] = l; + ary[offset++] = t; + ary[offset++] = u1; + ary[offset++] = v1; + ary[offset++] = cr; + ary[offset++] = cg; + ary[offset++] = cb; + ary[offset++] = ca; + + ary[offset++] = r; + ary[offset++] = t; + ary[offset++] = u2; + ary[offset++] = v1; + ary[offset++] = cr; + ary[offset++] = cg; + ary[offset++] = cb; + ary[offset++] = ca; + + ary[offset++] = l; + ary[offset++] = b; + ary[offset++] = u1; + ary[offset++] = v2; + ary[offset++] = cr; + ary[offset++] = cg; + ary[offset++] = cb; + ary[offset++] = ca; + + + ary[offset++] = r; + ary[offset++] = b; + ary[offset++] = u2; + ary[offset++] = v2; + ary[offset++] = cr; + ary[offset++] = cg; + ary[offset++] = cb; + ary[offset++] = ca; + } else { + final float s = (float) Math.sin(rotation.value); + final float c = (float) Math.cos(rotation.value); + final float x = position.x, y = position.y; + ary[offset++] = l * c - t * s + x; + ary[offset++] = l * s + t * c + y; + ary[offset++] = u1; + ary[offset++] = v1; + ary[offset++] = cr; + ary[offset++] = cg; + ary[offset++] = cb; + ary[offset++] = ca; + + ary[offset++] = r * c - t * s + x; + ary[offset++] = r * s + t * c + y; + ary[offset++] = u2; + ary[offset++] = v1; + ary[offset++] = cr; + ary[offset++] = cg; + ary[offset++] = cb; + ary[offset++] = ca; + + ary[offset++] = l * c - b * s + x; + ary[offset++] = l * s + b * c + y; + ary[offset++] = u1; + ary[offset++] = v2; + ary[offset++] = cr; + ary[offset++] = cg; + ary[offset++] = cb; + ary[offset++] = ca; + + ary[offset++] = r * c - b * s + x; + ary[offset++] = r * s + b * c + y; + ary[offset++] = u2; + ary[offset++] = v2; + ary[offset++] = cr; + ary[offset++] = cg; + ary[offset++] = cb; + ary[offset++] = ca; + } + } } diff --git a/src/com/edlplan/framework/support/batch/object/TextureQuadBatch.java b/src/com/edlplan/framework/support/batch/object/TextureQuadBatch.java index c64d10d3..2df34fb3 100644 --- a/src/com/edlplan/framework/support/batch/object/TextureQuadBatch.java +++ b/src/com/edlplan/framework/support/batch/object/TextureQuadBatch.java @@ -15,146 +15,146 @@ public class TextureQuadBatch extends AbstractBatch { - private static final int SIZE_PER_QUAD = 4 * 8; - - private static final int STEP = (2 + 2 + 4) * 4; - - private static final int OFFSET_COORD = 2; - - private static final int OFFSET_COLOR = OFFSET_COORD + 2; - - private static TextureQuadBatch defaultBatch; - private final int maxArySize; - private FloatBuffer buffer; - private ShortBuffer indicesBuffer; - private float[] ary; - private int offset; - private ITexture bindTexture; - - private TextureQuadBatch(int size) { - if (size > Short.MAX_VALUE / 4 - 10) { - throw new IllegalArgumentException("过大的QuadBatch"); - } - maxArySize = size * SIZE_PER_QUAD; - ary = new float[maxArySize]; - buffer = BufferUtil.createFloatBuffer(maxArySize); - indicesBuffer = BufferUtil.createShortBuffer(size * 6); - short[] list = new short[size * 6]; - final int l = list.length; - short j = 0; - for (int i = 0; i < l; i += 6) { - list[i] = j++; - list[i + 1] = list[i + 3] = j++; - list[i + 2] = list[i + 5] = j++; - list[i + 4] = j++; - } - indicesBuffer.put(list); - indicesBuffer.position(0); - } - - public static TextureQuadBatch getDefaultBatch() { - if (defaultBatch == null) { - defaultBatch = new TextureQuadBatch(1023); - } - return defaultBatch; - } - - @Override - protected void onBind() { - - } - - @Override - protected void onUnbind() { - - } - - @Override - public void add(ATextureQuad textureQuad) { - - if (textureQuad.texture == null) { - return; - } - - if (!isBind()) { - bind(); - } - - if (textureQuad.texture.getTexture() != bindTexture) { - flush(); - bindTexture = textureQuad.texture.getTexture(); - } - - textureQuad.write(ary, offset); - offset += SIZE_PER_QUAD; - - if (offset == maxArySize) { - flush(); - } - } - - @Override - protected void clearData() { - offset = 0; - buffer.position(0); - buffer.limit(maxArySize); - } - - @Override - protected boolean applyToGL() { - if (offset != 0) { - - GLWrapped.blend.setIsPreM(bindTexture.getTextureOptions().mPreMultipyAlpha); - - //handle render operation - GL10 pGL = BatchEngine.pGL; - bindTexture.bind(pGL); - GLHelper.enableTextures(pGL); - GLHelper.enableTexCoordArray(pGL); - pGL.glEnableClientState(GL10.GL_COLOR_ARRAY); - pGL.glShadeModel(GL10.GL_SMOOTH); - GLHelper.enableVertexArray(pGL); - GLHelper.disableCulling(pGL); - - buffer.position(0); - buffer.put(ary, 0, offset); - buffer.position(0).limit(offset); - - pGL.glVertexPointer(2, GL10.GL_FLOAT, STEP, buffer); - buffer.position(OFFSET_COORD); - pGL.glTexCoordPointer(2, GL10.GL_FLOAT, STEP, buffer); - buffer.position(OFFSET_COLOR); - pGL.glColorPointer(4, GL10.GL_FLOAT, STEP, buffer); - - - pGL.glDrawElements( - GL10.GL_TRIANGLES, - offset / SIZE_PER_QUAD * 6, - GL10.GL_UNSIGNED_SHORT, - indicesBuffer); - - pGL.glDisableClientState(GL10.GL_COLOR_ARRAY); - - - /*shader.useThis(); - shader.loadShaderGlobals(BatchEngine.getShaderGlobals()); - shader.loadTexture(bindTexture); - - buffer.position(0); - buffer.put(ary, 0, offset); - buffer.position(0).limit(offset); - - shader.loadBuffer(buffer); - - BatchEngine.pGL.glDrawElements( - GL10.GL_TRIANGLES, - offset / SIZE_PER_QUAD * 6, - GL10.GL_UNSIGNED_SHORT, - indicesBuffer);*/ - return true; - } else { - return false; - } - } + private static final int SIZE_PER_QUAD = 4 * 8; + + private static final int STEP = (2 + 2 + 4) * 4; + + private static final int OFFSET_COORD = 2; + + private static final int OFFSET_COLOR = OFFSET_COORD + 2; + + private static TextureQuadBatch defaultBatch; + private final int maxArySize; + private FloatBuffer buffer; + private ShortBuffer indicesBuffer; + private float[] ary; + private int offset; + private ITexture bindTexture; + + private TextureQuadBatch(int size) { + if (size > Short.MAX_VALUE / 4 - 10) { + throw new IllegalArgumentException("过大的QuadBatch"); + } + maxArySize = size * SIZE_PER_QUAD; + ary = new float[maxArySize]; + buffer = BufferUtil.createFloatBuffer(maxArySize); + indicesBuffer = BufferUtil.createShortBuffer(size * 6); + short[] list = new short[size * 6]; + final int l = list.length; + short j = 0; + for (int i = 0; i < l; i += 6) { + list[i] = j++; + list[i + 1] = list[i + 3] = j++; + list[i + 2] = list[i + 5] = j++; + list[i + 4] = j++; + } + indicesBuffer.put(list); + indicesBuffer.position(0); + } + + public static TextureQuadBatch getDefaultBatch() { + if (defaultBatch == null) { + defaultBatch = new TextureQuadBatch(1023); + } + return defaultBatch; + } + + @Override + protected void onBind() { + + } + + @Override + protected void onUnbind() { + + } + + @Override + public void add(ATextureQuad textureQuad) { + + if (textureQuad.texture == null) { + return; + } + + if (!isBind()) { + bind(); + } + + if (textureQuad.texture.getTexture() != bindTexture) { + flush(); + bindTexture = textureQuad.texture.getTexture(); + } + + textureQuad.write(ary, offset); + offset += SIZE_PER_QUAD; + + if (offset == maxArySize) { + flush(); + } + } + + @Override + protected void clearData() { + offset = 0; + buffer.position(0); + buffer.limit(maxArySize); + } + + @Override + protected boolean applyToGL() { + if (offset != 0) { + + GLWrapped.blend.setIsPreM(bindTexture.getTextureOptions().mPreMultipyAlpha); + + //handle render operation + GL10 pGL = BatchEngine.pGL; + bindTexture.bind(pGL); + GLHelper.enableTextures(pGL); + GLHelper.enableTexCoordArray(pGL); + pGL.glEnableClientState(GL10.GL_COLOR_ARRAY); + pGL.glShadeModel(GL10.GL_SMOOTH); + GLHelper.enableVertexArray(pGL); + GLHelper.disableCulling(pGL); + + buffer.position(0); + buffer.put(ary, 0, offset); + buffer.position(0).limit(offset); + + pGL.glVertexPointer(2, GL10.GL_FLOAT, STEP, buffer); + buffer.position(OFFSET_COORD); + pGL.glTexCoordPointer(2, GL10.GL_FLOAT, STEP, buffer); + buffer.position(OFFSET_COLOR); + pGL.glColorPointer(4, GL10.GL_FLOAT, STEP, buffer); + + + pGL.glDrawElements( + GL10.GL_TRIANGLES, + offset / SIZE_PER_QUAD * 6, + GL10.GL_UNSIGNED_SHORT, + indicesBuffer); + + pGL.glDisableClientState(GL10.GL_COLOR_ARRAY); + + + /*shader.useThis(); + shader.loadShaderGlobals(BatchEngine.getShaderGlobals()); + shader.loadTexture(bindTexture); + + buffer.position(0); + buffer.put(ary, 0, offset); + buffer.position(0).limit(offset); + + shader.loadBuffer(buffer); + + BatchEngine.pGL.glDrawElements( + GL10.GL_TRIANGLES, + offset / SIZE_PER_QUAD * 6, + GL10.GL_UNSIGNED_SHORT, + indicesBuffer);*/ + return true; + } else { + return false; + } + } } diff --git a/src/com/edlplan/framework/support/graphics/BaseCanvas.java b/src/com/edlplan/framework/support/graphics/BaseCanvas.java index 920f5227..da581843 100644 --- a/src/com/edlplan/framework/support/graphics/BaseCanvas.java +++ b/src/com/edlplan/framework/support/graphics/BaseCanvas.java @@ -10,178 +10,178 @@ */ public abstract class BaseCanvas extends AbstractSRable { - public BaseCanvas() { - - } - - public BaseCanvas translate(float tx, float ty) { - getData().translate(tx, ty); - BatchEngine.setGlobalCamera(getData().getCamera()); - return this; - } - - public BaseCanvas rotate(float r) { - getData().rotate(r); - BatchEngine.setGlobalCamera(getData().getCamera()); - return this; - } - - public BaseCanvas rotate(float ox, float oy, float r) { - getData().rotate(ox, oy, r); - BatchEngine.setGlobalCamera(getData().getCamera()); - return this; - } - - /** - * 对画布对应区域缩放
- */ - public BaseCanvas scale(float x, float y) { - getData().scale(x, y); - BatchEngine.setGlobalCamera(getData().getCamera()); - return this; - } - - /** - * 拉伸轴,对应的实际像素数不会改变 - * 比如当前的Canvas是100x100大小对应100x100的像素,
- * expendAxis(2)后就变成了200x200的大小对应100x100的像素 - */ - public BaseCanvas expendAxis(float s) { - getData().expendAxis(s); - BatchEngine.setGlobalCamera(getData().getCamera()); - return this; - } - - /** - * 限制Canvas范围,但是并没有限制外部像素绘制 - */ - public BaseCanvas clip(float w, float h) { - getData().clip(w, h); - BatchEngine.setGlobalCamera(getData().getCamera()); - return this; - } - - public float getPixelDensity() { - return getData().getPixelDensity(); - } - - public float getWidth() { - return getData().getWidth(); - } - - public float getHeight() { - return getData().getHeight(); - } - - public Camera getCamera() { - return getData().getCamera(); - } - - public float getCanvasAlpha() { - return getData().getCanvasAlpha(); - } - - public void setCanvasAlpha(float a) { - if (Math.abs(a - getData().getCanvasAlpha()) > 0.0001) { - BatchEngine.flush(); - } - getData().setCanvasAlpha(a); - BatchEngine.getShaderGlobals().alpha = a; - } - - /** - * @param p:当前应该是的状态 - */ - public void checkPrepared(String msg, boolean p) { - if (p != isPrepared()) { - throw new GLException("prepare err [n,c]=[" + p + "," + isPrepared() + "] msg: " + msg); - } - } - - public boolean isPrepared() { - return this == GLWrapped.getUsingCanvas(); - } - - public final void prepare() { - GLWrapped.prepareCanvas(this); - } - - protected abstract void onPrepare(); - - public void unprepare() { - flush(); - GLWrapped.unprepareCanvas(this); - } - - protected abstract void onUnprepare(); - - @Override - public void onSave(CanvasData t) { - BatchEngine.flush(); - } - - @Override - public void onRestore(CanvasData now, CanvasData pre) { - BatchEngine.setGlobalCamera(now.getCamera()); - BatchEngine.getShaderGlobals().alpha = now.getCanvasAlpha(); - pre.recycle(); - } - - - /** - * @return 返回是否支持裁剪画板的一部分 - */ - public boolean supportClip() { - return false; - } - - /** - * 返回一个被裁剪的画板, - * - * @param x 裁剪区域起始x - * @param y 裁剪区域起始y - * @param width 裁剪区域宽度 - * @param height 裁剪区域高度 - * @return 返回一个新画板,画板的新原点为裁剪起点(会产生新对象) - */ - protected BaseCanvas clipCanvas(float x, float y, float width, float height) { - return null; - } - - - public final BaseCanvas requestClipCanvas(float x, float y, float width, float height) { - checkPrepared("you can only clip canvas when it is not working", false); - if (supportClip()) { - return clipCanvas(x, y, width, height); - } else { - return null; - } - } - - - public abstract BlendSetting getBlendSetting(); + public BaseCanvas() { + + } + + public BaseCanvas translate(float tx, float ty) { + getData().translate(tx, ty); + BatchEngine.setGlobalCamera(getData().getCamera()); + return this; + } + + public BaseCanvas rotate(float r) { + getData().rotate(r); + BatchEngine.setGlobalCamera(getData().getCamera()); + return this; + } + + public BaseCanvas rotate(float ox, float oy, float r) { + getData().rotate(ox, oy, r); + BatchEngine.setGlobalCamera(getData().getCamera()); + return this; + } + + /** + * 对画布对应区域缩放
+ */ + public BaseCanvas scale(float x, float y) { + getData().scale(x, y); + BatchEngine.setGlobalCamera(getData().getCamera()); + return this; + } + + /** + * 拉伸轴,对应的实际像素数不会改变 + * 比如当前的Canvas是100x100大小对应100x100的像素,
+ * expendAxis(2)后就变成了200x200的大小对应100x100的像素 + */ + public BaseCanvas expendAxis(float s) { + getData().expendAxis(s); + BatchEngine.setGlobalCamera(getData().getCamera()); + return this; + } + + /** + * 限制Canvas范围,但是并没有限制外部像素绘制 + */ + public BaseCanvas clip(float w, float h) { + getData().clip(w, h); + BatchEngine.setGlobalCamera(getData().getCamera()); + return this; + } + + public float getPixelDensity() { + return getData().getPixelDensity(); + } + + public float getWidth() { + return getData().getWidth(); + } + + public float getHeight() { + return getData().getHeight(); + } + + public Camera getCamera() { + return getData().getCamera(); + } + + public float getCanvasAlpha() { + return getData().getCanvasAlpha(); + } + + public void setCanvasAlpha(float a) { + if (Math.abs(a - getData().getCanvasAlpha()) > 0.0001) { + BatchEngine.flush(); + } + getData().setCanvasAlpha(a); + BatchEngine.getShaderGlobals().alpha = a; + } + + /** + * @param p:当前应该是的状态 + */ + public void checkPrepared(String msg, boolean p) { + if (p != isPrepared()) { + throw new GLException("prepare err [n,c]=[" + p + "," + isPrepared() + "] msg: " + msg); + } + } + + public boolean isPrepared() { + return this == GLWrapped.getUsingCanvas(); + } + + public final void prepare() { + GLWrapped.prepareCanvas(this); + } + + protected abstract void onPrepare(); + + public void unprepare() { + flush(); + GLWrapped.unprepareCanvas(this); + } + + protected abstract void onUnprepare(); + + @Override + public void onSave(CanvasData t) { + BatchEngine.flush(); + } + + @Override + public void onRestore(CanvasData now, CanvasData pre) { + BatchEngine.setGlobalCamera(now.getCamera()); + BatchEngine.getShaderGlobals().alpha = now.getCanvasAlpha(); + pre.recycle(); + } + + + /** + * @return 返回是否支持裁剪画板的一部分 + */ + public boolean supportClip() { + return false; + } + + /** + * 返回一个被裁剪的画板, + * + * @param x 裁剪区域起始x + * @param y 裁剪区域起始y + * @param width 裁剪区域宽度 + * @param height 裁剪区域高度 + * @return 返回一个新画板,画板的新原点为裁剪起点(会产生新对象) + */ + protected BaseCanvas clipCanvas(float x, float y, float width, float height) { + return null; + } + + + public final BaseCanvas requestClipCanvas(float x, float y, float width, float height) { + checkPrepared("you can only clip canvas when it is not working", false); + if (supportClip()) { + return clipCanvas(x, y, width, height); + } else { + return null; + } + } + + + public abstract BlendSetting getBlendSetting(); - protected abstract void checkCanDraw(); - - public abstract CanvasData getDefData(); + protected abstract void checkCanDraw(); + + public abstract CanvasData getDefData(); - public abstract void clearBuffer(); - - public abstract void clearColor(Color4 c); + public abstract void clearBuffer(); + + public abstract void clearColor(Color4 c); - public void flush() { - BatchEngine.flush(); - } + public void flush() { + BatchEngine.flush(); + } - @Override - public void recycle() { - - } - - @Override - protected void finalize() throws Throwable { + @Override + public void recycle() { + + } + + @Override + protected void finalize() throws Throwable { - super.finalize(); - } + super.finalize(); + } } diff --git a/src/com/edlplan/framework/support/graphics/BitmapUtil.java b/src/com/edlplan/framework/support/graphics/BitmapUtil.java index df217d69..0689b334 100644 --- a/src/com/edlplan/framework/support/graphics/BitmapUtil.java +++ b/src/com/edlplan/framework/support/graphics/BitmapUtil.java @@ -10,15 +10,15 @@ public class BitmapUtil { - public static Vec2Int parseBitmapSize(File file) throws FileNotFoundException { - final BitmapFactory.Options decodeOptions = new BitmapFactory.Options(); - decodeOptions.inJustDecodeBounds = true; - Vec2Int v = new Vec2Int(); - BitmapFactory.decodeStream(new FileInputStream(file), null, decodeOptions); - v.x = decodeOptions.outWidth; - v.y = decodeOptions.outHeight; - return v; - } + public static Vec2Int parseBitmapSize(File file) throws FileNotFoundException { + final BitmapFactory.Options decodeOptions = new BitmapFactory.Options(); + decodeOptions.inJustDecodeBounds = true; + Vec2Int v = new Vec2Int(); + BitmapFactory.decodeStream(new FileInputStream(file), null, decodeOptions); + v.x = decodeOptions.outWidth; + v.y = decodeOptions.outHeight; + return v; + } } diff --git a/src/com/edlplan/framework/support/graphics/BlendProperty.java b/src/com/edlplan/framework/support/graphics/BlendProperty.java index 8288c8c3..91867345 100644 --- a/src/com/edlplan/framework/support/graphics/BlendProperty.java +++ b/src/com/edlplan/framework/support/graphics/BlendProperty.java @@ -8,60 +8,60 @@ public class BlendProperty implements Copyable { - public boolean enable = true; - - public boolean isPreM = false; - - public BlendType blendType = BlendType.Normal; - - public BlendProperty() { - - } - - public BlendProperty(BlendProperty b) { - set(b); - } - - public BlendProperty(boolean e, boolean isPreM, BlendType t) { - this.isPreM = isPreM; - this.enable = e; - this.blendType = t; - } - - public void set(BlendProperty b) { - this.enable = b.enable; - this.blendType = b.blendType; - this.isPreM = b.isPreM; - } - - public void applyToGL() { - BatchEngine.flush(); - if (enable) { - GLES10.glEnable(GLES10.GL_BLEND); - if (isPreM) { - GLES10.glBlendFunc(blendType.srcTypePreM, blendType.dstTypePreM); - } else { - GLES10.glBlendFunc(blendType.srcType, blendType.dstType); - } - } else { - GLES10.glDisable(GLES10.GL_BLEND); - } - } - - public boolean equals(boolean _enable, boolean isPreM, BlendType _blendType) { - return this.enable == _enable && this.blendType == _blendType && this.isPreM == isPreM; - } - - @Override - public boolean equals(Object obj) { - if (obj instanceof BlendProperty) { - BlendProperty b = (BlendProperty) obj; - return (enable == b.enable) && (blendType == b.blendType) && (isPreM == b.isPreM); - } else return false; - } - - @Override - public Copyable copy() { - return new BlendProperty(this); - } + public boolean enable = true; + + public boolean isPreM = false; + + public BlendType blendType = BlendType.Normal; + + public BlendProperty() { + + } + + public BlendProperty(BlendProperty b) { + set(b); + } + + public BlendProperty(boolean e, boolean isPreM, BlendType t) { + this.isPreM = isPreM; + this.enable = e; + this.blendType = t; + } + + public void set(BlendProperty b) { + this.enable = b.enable; + this.blendType = b.blendType; + this.isPreM = b.isPreM; + } + + public void applyToGL() { + BatchEngine.flush(); + if (enable) { + GLES10.glEnable(GLES10.GL_BLEND); + if (isPreM) { + GLES10.glBlendFunc(blendType.srcTypePreM, blendType.dstTypePreM); + } else { + GLES10.glBlendFunc(blendType.srcType, blendType.dstType); + } + } else { + GLES10.glDisable(GLES10.GL_BLEND); + } + } + + public boolean equals(boolean _enable, boolean isPreM, BlendType _blendType) { + return this.enable == _enable && this.blendType == _blendType && this.isPreM == isPreM; + } + + @Override + public boolean equals(Object obj) { + if (obj instanceof BlendProperty) { + BlendProperty b = (BlendProperty) obj; + return (enable == b.enable) && (blendType == b.blendType) && (isPreM == b.isPreM); + } else return false; + } + + @Override + public Copyable copy() { + return new BlendProperty(this); + } } diff --git a/src/com/edlplan/framework/support/graphics/BlendSetting.java b/src/com/edlplan/framework/support/graphics/BlendSetting.java index c32beaf5..9c0c327d 100644 --- a/src/com/edlplan/framework/support/graphics/BlendSetting.java +++ b/src/com/edlplan/framework/support/graphics/BlendSetting.java @@ -4,73 +4,73 @@ public class BlendSetting extends AbstractSRable { - public BlendSetting() { - - } - - public BlendSetting setUp() { - initial(); - apply(getData()); - return this; - } - - private void apply(BlendProperty p) { - p.applyToGL(); - } - - public void apply() { - apply(getData()); - } - - public boolean isEnable() { - return getData().enable; - } - - public void setEnable(boolean enable) { - set(enable, isPreM(), getBlendType()); - } - - public BlendType getBlendType() { - return getData().blendType; - } - - public void setBlendType(BlendType type) { - set(isEnable(), isPreM(), type); - } - - public boolean isPreM() { - return getData().isPreM; - } - - public void set(boolean enable, boolean isPreM, BlendType blendType) { - if (!getData().equals(enable, isPreM, blendType)) { - BlendProperty prop = new BlendProperty(enable, isPreM, blendType); - setCurrentData(prop); - apply(prop); - } - } - - public void setIsPreM(boolean isPreM) { - if (isPreM != isPreM()) { - getData().isPreM = false; - apply(); - } - } - - @Override - public void onSave(BlendProperty t) { - - } - - @Override - public void onRestore(BlendProperty now, BlendProperty pre) { - if (!now.equals(pre)) { - apply(now); - } - } - - @Override - public BlendProperty getDefData() { - return new BlendProperty(); - } + public BlendSetting() { + + } + + public BlendSetting setUp() { + initial(); + apply(getData()); + return this; + } + + private void apply(BlendProperty p) { + p.applyToGL(); + } + + public void apply() { + apply(getData()); + } + + public boolean isEnable() { + return getData().enable; + } + + public void setEnable(boolean enable) { + set(enable, isPreM(), getBlendType()); + } + + public BlendType getBlendType() { + return getData().blendType; + } + + public void setBlendType(BlendType type) { + set(isEnable(), isPreM(), type); + } + + public boolean isPreM() { + return getData().isPreM; + } + + public void set(boolean enable, boolean isPreM, BlendType blendType) { + if (!getData().equals(enable, isPreM, blendType)) { + BlendProperty prop = new BlendProperty(enable, isPreM, blendType); + setCurrentData(prop); + apply(prop); + } + } + + public void setIsPreM(boolean isPreM) { + if (isPreM != isPreM()) { + getData().isPreM = false; + apply(); + } + } + + @Override + public void onSave(BlendProperty t) { + + } + + @Override + public void onRestore(BlendProperty now, BlendProperty pre) { + if (!now.equals(pre)) { + apply(now); + } + } + + @Override + public BlendProperty getDefData() { + return new BlendProperty(); + } } diff --git a/src/com/edlplan/framework/support/graphics/BlendType.java b/src/com/edlplan/framework/support/graphics/BlendType.java index 0a2b7cab..bbeb8714 100644 --- a/src/com/edlplan/framework/support/graphics/BlendType.java +++ b/src/com/edlplan/framework/support/graphics/BlendType.java @@ -3,48 +3,48 @@ import android.opengl.GLES20; public enum BlendType { - Normal( - GLES20.GL_SRC_ALPHA, - GLES20.GL_ONE_MINUS_SRC_ALPHA, - GLES20.GL_ONE, - GLES20.GL_ONE_MINUS_SRC_ALPHA - ), - Additive( - GLES20.GL_SRC_ALPHA, - GLES20.GL_ONE, - GLES20.GL_ONE, - GLES20.GL_ONE - ), - Delete( - GLES20.GL_ZERO, - GLES20.GL_ONE_MINUS_SRC_COLOR, - GLES20.GL_ZERO, - GLES20.GL_ONE_MINUS_SRC_COLOR - ), - Delete_Alpha( - GLES20.GL_ZERO, - GLES20.GL_ONE_MINUS_SRC_ALPHA, - GLES20.GL_ZERO, - GLES20.GL_ONE_MINUS_SRC_ALPHA - ), - DeleteRepeat( - GLES20.GL_ONE_MINUS_DST_ALPHA, - GLES20.GL_ONE_MINUS_SRC_ALPHA, - GLES20.GL_ONE_MINUS_DST_ALPHA, - GLES20.GL_ONE_MINUS_SRC_ALPHA - ); - public final int srcType; - public final int dstType; + Normal( + GLES20.GL_SRC_ALPHA, + GLES20.GL_ONE_MINUS_SRC_ALPHA, + GLES20.GL_ONE, + GLES20.GL_ONE_MINUS_SRC_ALPHA + ), + Additive( + GLES20.GL_SRC_ALPHA, + GLES20.GL_ONE, + GLES20.GL_ONE, + GLES20.GL_ONE + ), + Delete( + GLES20.GL_ZERO, + GLES20.GL_ONE_MINUS_SRC_COLOR, + GLES20.GL_ZERO, + GLES20.GL_ONE_MINUS_SRC_COLOR + ), + Delete_Alpha( + GLES20.GL_ZERO, + GLES20.GL_ONE_MINUS_SRC_ALPHA, + GLES20.GL_ZERO, + GLES20.GL_ONE_MINUS_SRC_ALPHA + ), + DeleteRepeat( + GLES20.GL_ONE_MINUS_DST_ALPHA, + GLES20.GL_ONE_MINUS_SRC_ALPHA, + GLES20.GL_ONE_MINUS_DST_ALPHA, + GLES20.GL_ONE_MINUS_SRC_ALPHA + ); + public final int srcType; + public final int dstType; - public final int srcTypePreM; - public final int dstTypePreM; + public final int srcTypePreM; + public final int dstTypePreM; - //public final boolean needPreMultiple; - BlendType(int src, int dst, int srcTypePreM, int dstTypePreM) { - srcType = src; - dstType = dst; - this.srcTypePreM = srcTypePreM; - this.dstTypePreM = dstTypePreM; - //needPreMultiple=prm; - } + //public final boolean needPreMultiple; + BlendType(int src, int dst, int srcTypePreM, int dstTypePreM) { + srcType = src; + dstType = dst; + this.srcTypePreM = srcTypePreM; + this.dstTypePreM = dstTypePreM; + //needPreMultiple=prm; + } } diff --git a/src/com/edlplan/framework/support/graphics/Camera.java b/src/com/edlplan/framework/support/graphics/Camera.java index e610556e..4de2bf88 100644 --- a/src/com/edlplan/framework/support/graphics/Camera.java +++ b/src/com/edlplan/framework/support/graphics/Camera.java @@ -4,67 +4,67 @@ import com.edlplan.framework.math.Vec2; public class Camera { - private Mat4 maskMatrix = new Mat4(); - private Mat4 projectionMatrix = new Mat4(); - - private Mat4 finalMatrix = new Mat4(); - private boolean hasChange = true; - - - public Camera() { - maskMatrix.setIden(); - projectionMatrix.setIden(); - } - - public Camera(Camera c) { - maskMatrix.set(c.maskMatrix); - projectionMatrix.set(c.projectionMatrix); - hasChange = true; - } - - public void set(Camera c) { - maskMatrix.set(c.maskMatrix); - projectionMatrix.set(c.projectionMatrix); - finalMatrix.set(c.finalMatrix); - hasChange = c.hasChange; - } - - public Vec2 toProjPostion(float x, float y) { - return maskMatrix.mapToProj(x, y); - } - - public Mat4 getMaskMatrix() { - return maskMatrix; - } - - public void setMaskMatrix(Mat4 maskMatrix) { - this.maskMatrix.set(maskMatrix); - } - - public Mat4 getProjectionMatrix() { - return projectionMatrix; - } - - public void setProjectionMatrix(Mat4 projectionMatrix) { - this.projectionMatrix.set(projectionMatrix); - } - - public void refresh() { - hasChange = true; - } - - public Mat4 getFinalMatrix() { - if (hasChange) { - finalMatrix.set(maskMatrix).post(projectionMatrix); - hasChange = false; - return finalMatrix; - } else { - return finalMatrix; - } - } - - public Camera copy() { - return new Camera(this); - } + private Mat4 maskMatrix = new Mat4(); + private Mat4 projectionMatrix = new Mat4(); + + private Mat4 finalMatrix = new Mat4(); + private boolean hasChange = true; + + + public Camera() { + maskMatrix.setIden(); + projectionMatrix.setIden(); + } + + public Camera(Camera c) { + maskMatrix.set(c.maskMatrix); + projectionMatrix.set(c.projectionMatrix); + hasChange = true; + } + + public void set(Camera c) { + maskMatrix.set(c.maskMatrix); + projectionMatrix.set(c.projectionMatrix); + finalMatrix.set(c.finalMatrix); + hasChange = c.hasChange; + } + + public Vec2 toProjPostion(float x, float y) { + return maskMatrix.mapToProj(x, y); + } + + public Mat4 getMaskMatrix() { + return maskMatrix; + } + + public void setMaskMatrix(Mat4 maskMatrix) { + this.maskMatrix.set(maskMatrix); + } + + public Mat4 getProjectionMatrix() { + return projectionMatrix; + } + + public void setProjectionMatrix(Mat4 projectionMatrix) { + this.projectionMatrix.set(projectionMatrix); + } + + public void refresh() { + hasChange = true; + } + + public Mat4 getFinalMatrix() { + if (hasChange) { + finalMatrix.set(maskMatrix).post(projectionMatrix); + hasChange = false; + return finalMatrix; + } else { + return finalMatrix; + } + } + + public Camera copy() { + return new Camera(this); + } } diff --git a/src/com/edlplan/framework/support/graphics/CanvasData.java b/src/com/edlplan/framework/support/graphics/CanvasData.java index 9bdd2968..0173f8c5 100644 --- a/src/com/edlplan/framework/support/graphics/CanvasData.java +++ b/src/com/edlplan/framework/support/graphics/CanvasData.java @@ -7,153 +7,153 @@ public class CanvasData implements Recycleable, Copyable { - private float width; - - private float height; - - private Camera camera; - - private float pixelDensity = 1; - - private float canvasAlpha = 1; - - private Vec2 theOrigin = new Vec2(); - - public CanvasData(CanvasData c) { - this.camera = c.camera.copy(); - this.width = c.width; - this.height = c.height; - this.pixelDensity = c.pixelDensity; - this.canvasAlpha = c.canvasAlpha; - this.theOrigin.set(c.theOrigin); - } - - public CanvasData() { - camera = new Camera(); - } - - public Vec2 getTheOrigin() { - return theOrigin; - } - - public float getCanvasAlpha() { - return canvasAlpha; - } - - public void setCanvasAlpha(float canvasAlpha) { - this.canvasAlpha = canvasAlpha; - } - - /** - * 定义了canvas上每单位有多少像素 - */ - public float getPixelDensity() { - return pixelDensity; - } - - public float getWidth() { - return width; - } - - public void setWidth(float width) { - this.width = width; - } - - public float getHeight() { - return height; - } - - public void setHeight(float height) { - this.height = height; - } - - public Mat4 getCurrentProjMatrix() { - return camera.getProjectionMatrix(); - } - - public void setCurrentProjMatrix(Mat4 projMatrix) { - this.camera.setProjectionMatrix(projMatrix); - freshMatrix(); - } - - /** - * 每次直接操作之后要freshMatrix,否则效果不会显示 - */ - public Mat4 getCurrentMaskMatrix() { - return camera.getMaskMatrix(); - } - - public void setCurrentMaskMatrix(Mat4 matrix) { - this.camera.setMaskMatrix(matrix); - } - - public CanvasData translate(float tx, float ty) { - getCurrentMaskMatrix().translate(tx, ty, 0); - theOrigin.add(tx, ty); - freshMatrix(); - return this; - } - - public CanvasData rotate(float rotation) { - getCurrentMaskMatrix().rotate2D(0, 0, rotation, true); - freshMatrix(); - return this; - } - - public CanvasData rotate(float ox, float oy, float rotation) { - getCurrentMaskMatrix().rotate2D(ox, oy, rotation, true); - freshMatrix(); - return this; - } - - //可能导致部分运算误差(像素密度相关) - public CanvasData scale(float sx, float sy) { - getCurrentMaskMatrix().scale(sx, sy, 1); - theOrigin.x *= sx; - theOrigin.y *= sy; - freshMatrix(); - return this; - } - - /** - * 对轴进行缩放,而不是对物件缩放,所以处理Matrix时用倒数 - */ - public CanvasData expendAxis(float s) { - if (s == 0) - throw new IllegalArgumentException("you can't scale content using a scale rate ==0"); - float rs = 1 / s; - scale(rs, rs); - this.pixelDensity *= s; - return this; - } - - public void freshMatrix() { - camera.refresh(); - } - - /* - public Mat4 getFinalMatrix(){ - return camera.getFinalMatrix(); - } - */ - - public Camera getCamera() { - return camera; - } - - public CanvasData clip(float w, float h) { - setWidth(w); - setHeight(h); - return this; - } - - @Override - public void recycle() { - this.camera = null; - } - - @Override - public Copyable copy() { - return new CanvasData(this); - } + private float width; + + private float height; + + private Camera camera; + + private float pixelDensity = 1; + + private float canvasAlpha = 1; + + private Vec2 theOrigin = new Vec2(); + + public CanvasData(CanvasData c) { + this.camera = c.camera.copy(); + this.width = c.width; + this.height = c.height; + this.pixelDensity = c.pixelDensity; + this.canvasAlpha = c.canvasAlpha; + this.theOrigin.set(c.theOrigin); + } + + public CanvasData() { + camera = new Camera(); + } + + public Vec2 getTheOrigin() { + return theOrigin; + } + + public float getCanvasAlpha() { + return canvasAlpha; + } + + public void setCanvasAlpha(float canvasAlpha) { + this.canvasAlpha = canvasAlpha; + } + + /** + * 定义了canvas上每单位有多少像素 + */ + public float getPixelDensity() { + return pixelDensity; + } + + public float getWidth() { + return width; + } + + public void setWidth(float width) { + this.width = width; + } + + public float getHeight() { + return height; + } + + public void setHeight(float height) { + this.height = height; + } + + public Mat4 getCurrentProjMatrix() { + return camera.getProjectionMatrix(); + } + + public void setCurrentProjMatrix(Mat4 projMatrix) { + this.camera.setProjectionMatrix(projMatrix); + freshMatrix(); + } + + /** + * 每次直接操作之后要freshMatrix,否则效果不会显示 + */ + public Mat4 getCurrentMaskMatrix() { + return camera.getMaskMatrix(); + } + + public void setCurrentMaskMatrix(Mat4 matrix) { + this.camera.setMaskMatrix(matrix); + } + + public CanvasData translate(float tx, float ty) { + getCurrentMaskMatrix().translate(tx, ty, 0); + theOrigin.add(tx, ty); + freshMatrix(); + return this; + } + + public CanvasData rotate(float rotation) { + getCurrentMaskMatrix().rotate2D(0, 0, rotation, true); + freshMatrix(); + return this; + } + + public CanvasData rotate(float ox, float oy, float rotation) { + getCurrentMaskMatrix().rotate2D(ox, oy, rotation, true); + freshMatrix(); + return this; + } + + //可能导致部分运算误差(像素密度相关) + public CanvasData scale(float sx, float sy) { + getCurrentMaskMatrix().scale(sx, sy, 1); + theOrigin.x *= sx; + theOrigin.y *= sy; + freshMatrix(); + return this; + } + + /** + * 对轴进行缩放,而不是对物件缩放,所以处理Matrix时用倒数 + */ + public CanvasData expendAxis(float s) { + if (s == 0) + throw new IllegalArgumentException("you can't scale content using a scale rate ==0"); + float rs = 1 / s; + scale(rs, rs); + this.pixelDensity *= s; + return this; + } + + public void freshMatrix() { + camera.refresh(); + } + + /* + public Mat4 getFinalMatrix(){ + return camera.getFinalMatrix(); + } + */ + + public Camera getCamera() { + return camera; + } + + public CanvasData clip(float w, float h) { + setWidth(w); + setHeight(h); + return this; + } + + @Override + public void recycle() { + this.camera = null; + } + + @Override + public Copyable copy() { + return new CanvasData(this); + } } diff --git a/src/com/edlplan/framework/support/graphics/GLException.java b/src/com/edlplan/framework/support/graphics/GLException.java index a89ac2e5..2339197b 100644 --- a/src/com/edlplan/framework/support/graphics/GLException.java +++ b/src/com/edlplan/framework/support/graphics/GLException.java @@ -1,12 +1,12 @@ package com.edlplan.framework.support.graphics; public class GLException extends RuntimeException { - public GLException(String msg) { - super(msg); - } + public GLException(String msg) { + super(msg); + } - public GLException(String msg, Throwable cause) { - super(msg, cause); - } + public GLException(String msg, Throwable cause) { + super(msg, cause); + } } diff --git a/src/com/edlplan/framework/support/graphics/GLWrapped.java b/src/com/edlplan/framework/support/graphics/GLWrapped.java index fd47875e..0437d904 100644 --- a/src/com/edlplan/framework/support/graphics/GLWrapped.java +++ b/src/com/edlplan/framework/support/graphics/GLWrapped.java @@ -12,128 +12,128 @@ public class GLWrapped { - public static final - BooleanSetting depthTest = new BooleanSetting(t -> { - BatchEngine.flush(); - if (t) { - GLES10.glEnable(GLES10.GL_DEPTH_TEST); - } else { - GLES10.glDisable(GLES10.GL_DEPTH_TEST); - } - }, - false).initial(); - public static int GL_SHORT = GLES10.GL_SHORT; - public static int GL_UNSIGNED_SHORT = GLES10.GL_UNSIGNED_SHORT; - public static int GL_TRIANGLES = GLES10.GL_TRIANGLES; - public static int GL_MAX_TEXTURE_SIZE; - public static BlendSetting blend = new BlendSetting().setUp(); - private static boolean enable = true; - private static int drawCalls = 0; - private static int fboCreate = 0; - private static int px1, pw, py1, ph; - private static Stack canvasStack = new Stack<>(); - - public static boolean isEnable() { - return enable; - } - - public static void setEnable(boolean enable) { - GLWrapped.enable = enable; - } - - public static void onFrame() { - drawCalls = 0; - fboCreate = 0; - } - - public static void drawArrays(int mode, int offset, int count) { - if (enable) GLES10.glDrawArrays(mode, offset, count); - drawCalls++; - } - - public static void drawElements(int mode, int count, int type, Buffer b) { - if (enable) GLES10.glDrawElements(mode, count, type, b); - drawCalls++; - } - - public static int frameDrawCalls() { - return drawCalls; - } - - public static void setViewport(int x1, int y1, int w, int h) { - GLES10.glViewport(x1, y1, w, h); - px1 = x1; - pw = w; - py1 = y1; - ph = h; - } - - public static void setClearColor(float r, float g, float b, float a) { - GLES10.glClearColor(r, g, b, a); - } - - public static void clearColorBuffer() { - if (enable) GLES10.glClear(GLES10.GL_COLOR_BUFFER_BIT); - } - - public static void clearDepthBuffer() { - if (enable) GLES10.glClear(GLES10.GL_DEPTH_BUFFER_BIT); - } - - public static void clearDepthAndColorBuffer() { - if (enable) GLES10.glClear(GLES10.GL_COLOR_BUFFER_BIT | GLES10.GL_DEPTH_BUFFER_BIT); - } - - public static void setClearColor(Color4 c) { - setClearColor(c.r, c.g, c.b, c.a); - } - - public static int getFboCreate() { - return fboCreate; - } - - public static int getIntegerValue(int key) { - int[] b = new int[1]; - GLES10.glGetIntegerv(key, b, 0); - return b[0]; - } - - public static void checkGlError(String op) { - int error; - while ((error = GLES10.glGetError()) != GLES10.GL_NO_ERROR) { - Log.e("ES20_ERROR", op + ": glError " + error); - throw new GLException(op + ": glError " + error); - } - } - - protected static void prepareCanvas(BaseCanvas canvas) { - if (!canvasStack.empty()) { - final BaseCanvas pre = canvasStack.peek(); - if (pre.isPrepared()) { - //忘记释放,这里就帮忙释放 - pre.onUnprepare(); - } - } - BatchEngine.flush(); - canvasStack.push(canvas); - canvas.onPrepare(); - BatchEngine.setGlobalCamera(canvas.getCamera()); - } - - protected static void unprepareCanvas(BaseCanvas canvas) { - if (canvasStack.empty() || canvasStack.peek() != canvas) { - //发生错误,释放的画板不是当前画板 - throw new GLException("错误的canvas释放顺序!"); - } - BatchEngine.flush(); - canvas.onUnprepare(); - canvasStack.pop(); - if (!canvasStack.empty()) { - canvasStack.peek().onPrepare(); - } - } - - public static BaseCanvas getUsingCanvas() { - return canvasStack.empty() ? null : canvasStack.peek(); - } -} \ No newline at end of file + public static final + BooleanSetting depthTest = new BooleanSetting(t -> { + BatchEngine.flush(); + if (t) { + GLES10.glEnable(GLES10.GL_DEPTH_TEST); + } else { + GLES10.glDisable(GLES10.GL_DEPTH_TEST); + } + }, + false).initial(); + public static int GL_SHORT = GLES10.GL_SHORT; + public static int GL_UNSIGNED_SHORT = GLES10.GL_UNSIGNED_SHORT; + public static int GL_TRIANGLES = GLES10.GL_TRIANGLES; + public static int GL_MAX_TEXTURE_SIZE; + public static BlendSetting blend = new BlendSetting().setUp(); + private static boolean enable = true; + private static int drawCalls = 0; + private static int fboCreate = 0; + private static int px1, pw, py1, ph; + private static Stack canvasStack = new Stack<>(); + + public static boolean isEnable() { + return enable; + } + + public static void setEnable(boolean enable) { + GLWrapped.enable = enable; + } + + public static void onFrame() { + drawCalls = 0; + fboCreate = 0; + } + + public static void drawArrays(int mode, int offset, int count) { + if (enable) GLES10.glDrawArrays(mode, offset, count); + drawCalls++; + } + + public static void drawElements(int mode, int count, int type, Buffer b) { + if (enable) GLES10.glDrawElements(mode, count, type, b); + drawCalls++; + } + + public static int frameDrawCalls() { + return drawCalls; + } + + public static void setViewport(int x1, int y1, int w, int h) { + GLES10.glViewport(x1, y1, w, h); + px1 = x1; + pw = w; + py1 = y1; + ph = h; + } + + public static void setClearColor(float r, float g, float b, float a) { + GLES10.glClearColor(r, g, b, a); + } + + public static void clearColorBuffer() { + if (enable) GLES10.glClear(GLES10.GL_COLOR_BUFFER_BIT); + } + + public static void clearDepthBuffer() { + if (enable) GLES10.glClear(GLES10.GL_DEPTH_BUFFER_BIT); + } + + public static void clearDepthAndColorBuffer() { + if (enable) GLES10.glClear(GLES10.GL_COLOR_BUFFER_BIT | GLES10.GL_DEPTH_BUFFER_BIT); + } + + public static void setClearColor(Color4 c) { + setClearColor(c.r, c.g, c.b, c.a); + } + + public static int getFboCreate() { + return fboCreate; + } + + public static int getIntegerValue(int key) { + int[] b = new int[1]; + GLES10.glGetIntegerv(key, b, 0); + return b[0]; + } + + public static void checkGlError(String op) { + int error; + while ((error = GLES10.glGetError()) != GLES10.GL_NO_ERROR) { + Log.e("ES20_ERROR", op + ": glError " + error); + throw new GLException(op + ": glError " + error); + } + } + + protected static void prepareCanvas(BaseCanvas canvas) { + if (!canvasStack.empty()) { + final BaseCanvas pre = canvasStack.peek(); + if (pre.isPrepared()) { + //忘记释放,这里就帮忙释放 + pre.onUnprepare(); + } + } + BatchEngine.flush(); + canvasStack.push(canvas); + canvas.onPrepare(); + BatchEngine.setGlobalCamera(canvas.getCamera()); + } + + protected static void unprepareCanvas(BaseCanvas canvas) { + if (canvasStack.empty() || canvasStack.peek() != canvas) { + //发生错误,释放的画板不是当前画板 + throw new GLException("错误的canvas释放顺序!"); + } + BatchEngine.flush(); + canvas.onUnprepare(); + canvasStack.pop(); + if (!canvasStack.empty()) { + canvasStack.peek().onPrepare(); + } + } + + public static BaseCanvas getUsingCanvas() { + return canvasStack.empty() ? null : canvasStack.peek(); + } +} diff --git a/src/com/edlplan/framework/support/graphics/ShaderGlobals.java b/src/com/edlplan/framework/support/graphics/ShaderGlobals.java index 6ddd058e..3eff115a 100644 --- a/src/com/edlplan/framework/support/graphics/ShaderGlobals.java +++ b/src/com/edlplan/framework/support/graphics/ShaderGlobals.java @@ -4,10 +4,10 @@ public class ShaderGlobals { - public float alpha = 1; + public float alpha = 1; - public Camera camera = new Camera(); + public Camera camera = new Camera(); - public Color4 accentColor = Color4.White.copyNew(); + public Color4 accentColor = Color4.White.copyNew(); -} \ No newline at end of file +} diff --git a/src/com/edlplan/framework/support/graphics/SupportCanvas.java b/src/com/edlplan/framework/support/graphics/SupportCanvas.java index 82221b61..24afa509 100644 --- a/src/com/edlplan/framework/support/graphics/SupportCanvas.java +++ b/src/com/edlplan/framework/support/graphics/SupportCanvas.java @@ -5,61 +5,61 @@ public class SupportCanvas extends BaseCanvas { - private SupportInfo supportInfo; + private SupportInfo supportInfo; - public SupportCanvas(SupportInfo info) { - this.supportInfo = info; - initial(); - } + public SupportCanvas(SupportInfo info) { + this.supportInfo = info; + initial(); + } - @Override - protected void onPrepare() { + @Override + protected void onPrepare() { - } + } - @Override - protected void onUnprepare() { + @Override + protected void onUnprepare() { - } + } - @Override - public BlendSetting getBlendSetting() { - return GLWrapped.blend; - } + @Override + public BlendSetting getBlendSetting() { + return GLWrapped.blend; + } - @Override - protected void checkCanDraw() { + @Override + protected void checkCanDraw() { - } + } - @Override - public CanvasData getDefData() { - CanvasData d = new CanvasData(); - d.setCurrentProjMatrix(Mat4.createIdentity()); - d.setCurrentMaskMatrix(Mat4.createIdentity()); - d.setHeight(supportInfo.supportHeight); - d.setWidth(supportInfo.supportWidth); - return d; - } + @Override + public CanvasData getDefData() { + CanvasData d = new CanvasData(); + d.setCurrentProjMatrix(Mat4.createIdentity()); + d.setCurrentMaskMatrix(Mat4.createIdentity()); + d.setHeight(supportInfo.supportHeight); + d.setWidth(supportInfo.supportWidth); + return d; + } - @Override - public void clearBuffer() { - GLWrapped.clearDepthAndColorBuffer(); - } + @Override + public void clearBuffer() { + GLWrapped.clearDepthAndColorBuffer(); + } - @Override - public void clearColor(Color4 c) { - GLWrapped.setClearColor(c); - GLWrapped.clearColorBuffer(); - } + @Override + public void clearColor(Color4 c) { + GLWrapped.setClearColor(c); + GLWrapped.clearColorBuffer(); + } - public static class SupportInfo { + public static class SupportInfo { - public float supportWidth; + public float supportWidth; - public float supportHeight; + public float supportHeight; - } + } } diff --git a/src/com/edlplan/framework/support/graphics/texture/TexturePool.java b/src/com/edlplan/framework/support/graphics/texture/TexturePool.java index cc036118..9229fdd3 100644 --- a/src/com/edlplan/framework/support/graphics/texture/TexturePool.java +++ b/src/com/edlplan/framework/support/graphics/texture/TexturePool.java @@ -36,239 +36,239 @@ public class TexturePool { - int glMaxWidth; - BitmapFactory.Options options = new BitmapFactory.Options() {{ - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { - inPremultiplied = true; - } - }}; - private File dir; - private Set createdTextures = new HashSet<>(); - private HashMap textures = new HashMap<>(); - private int currentPack = 0; - private int currentX; - private int currentY; - private int lineMaxY; - private int marginX = 2, marginY = 2; - private int maxW, maxH; + int glMaxWidth; + BitmapFactory.Options options = new BitmapFactory.Options() {{ + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { + inPremultiplied = true; + } + }}; + private File dir; + private Set createdTextures = new HashSet<>(); + private HashMap textures = new HashMap<>(); + private int currentPack = 0; + private int currentX; + private int currentY; + private int lineMaxY; + private int marginX = 2, marginY = 2; + private int maxW, maxH; - public TexturePool(File dir) { - this.dir = dir; - glMaxWidth = GLHelper.GlMaxTextureWidth; - if (BuildConfig.DEBUG) System.out.println("GL_MAX_TEXTURE_SIZE = " + glMaxWidth); - if (glMaxWidth == 0) { - throw new RuntimeException("glMaxWidth not found"); - } - glMaxWidth = Math.min(glMaxWidth, 4096); - maxW = Math.min(400, glMaxWidth / 2); - maxH = Math.min(400, glMaxWidth / 2); - } + public TexturePool(File dir) { + this.dir = dir; + glMaxWidth = GLHelper.GlMaxTextureWidth; + if (BuildConfig.DEBUG) System.out.println("GL_MAX_TEXTURE_SIZE = " + glMaxWidth); + if (glMaxWidth == 0) { + throw new RuntimeException("glMaxWidth not found"); + } + glMaxWidth = Math.min(glMaxWidth, 4096); + maxW = Math.min(400, glMaxWidth / 2); + maxH = Math.min(400, glMaxWidth / 2); + } - public void clear() { - textures.clear(); - for (ITexture texture : createdTextures) { - GlobalManager.getInstance().getEngine().getTextureManager().unloadTexture(texture); - } - createdTextures.clear(); - currentPack = 0; - currentX = currentY = lineMaxY = 0; - } + public void clear() { + textures.clear(); + for (ITexture texture : createdTextures) { + GlobalManager.getInstance().getEngine().getTextureManager().unloadTexture(texture); + } + createdTextures.clear(); + currentPack = 0; + currentX = currentY = lineMaxY = 0; + } - public void add(String name) { - TextureInfo info = loadInfo(name); - Bitmap bmp = loadBitmap(info); - info.texture = TextureHelper.createRegion(bmp); - createdTextures.add(info.texture.getTexture()); - directPut(info.name, info.texture); - bmp.recycle(); - } + public void add(String name) { + TextureInfo info = loadInfo(name); + Bitmap bmp = loadBitmap(info); + info.texture = TextureHelper.createRegion(bmp); + createdTextures.add(info.texture.getTexture()); + directPut(info.name, info.texture); + bmp.recycle(); + } - public void packAll(Iterator collection, Consumer onPackDrawDone) { - clear(); + public void packAll(Iterator collection, Consumer onPackDrawDone) { + clear(); - List infos = new ArrayList<>(); - for (String n : (Iterable) () -> collection) { - infos.add(loadInfo(n)); - } - Collections.sort(infos, (p1, p2) -> { - if (p1.size.y == p2.size.y) { - return Float.compare(p1.size.x, p2.size.x); - } else { - return Float.compare(p1.size.y, p2.size.y); - } - }); + List infos = new ArrayList<>(); + for (String n : (Iterable) () -> collection) { + infos.add(loadInfo(n)); + } + Collections.sort(infos, (p1, p2) -> { + if (p1.size.y == p2.size.y) { + return Float.compare(p1.size.x, p2.size.x); + } else { + return Float.compare(p1.size.y, p2.size.y); + } + }); - for (TextureInfo t : infos) { - testAddRaw(t); - } + for (TextureInfo t : infos) { + testAddRaw(t); + } - Collections.sort(infos, (p1, p2) -> Integer.compare(p1.pageIndex, p2.pageIndex)); + Collections.sort(infos, (p1, p2) -> Integer.compare(p1.pageIndex, p2.pageIndex)); - ListIterator iterator = infos.listIterator(); + ListIterator iterator = infos.listIterator(); - while (iterator.hasNext()) { - TextureInfo info = iterator.next(); - if (info.pageIndex != -1) { - iterator.previous(); - break; - } - Bitmap bmp = loadBitmap(info); - info.texture = TextureHelper.createRegion(bmp); - createdTextures.add(info.texture.getTexture()); - directPut(info.name, info.texture); - bmp.recycle(); - } + while (iterator.hasNext()) { + TextureInfo info = iterator.next(); + if (info.pageIndex != -1) { + iterator.previous(); + break; + } + Bitmap bmp = loadBitmap(info); + info.texture = TextureHelper.createRegion(bmp); + createdTextures.add(info.texture.getTexture()); + directPut(info.name, info.texture); + bmp.recycle(); + } - Bitmap pack = null; + Bitmap pack = null; - if (iterator.hasNext()) { - int width = glMaxWidth; - int height = currentPack == 0 ? lineMaxY + 10 : glMaxWidth; - pack = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); - } - if (pack == null) { - return; - } - Canvas canvas = new Canvas(pack); - Paint paint = new Paint(); - paint.setAntiAlias(true); - paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC)); - List toLoad = new ArrayList<>(); - Bitmap tmp; - while (iterator.hasNext()) { - toLoad.clear(); - pack.eraseColor(Color.argb(0, 0, 0, 0)); - int currentPack = iterator.next().pageIndex; - iterator.previous(); - while (iterator.hasNext()) { - TextureInfo info = iterator.next(); - if (info.pageIndex != currentPack) { - break; - } - toLoad.add(info); - canvas.drawBitmap(tmp = loadBitmap(info), info.pos.x, info.pos.y, paint); - tmp.recycle(); - } - if (onPackDrawDone != null) { - onPackDrawDone.consume(pack); - } - final QualityFileBitmapSource source = new QualityFileBitmapSource( - TextureHelper.createFactoryFromBitmap(pack)); - final BitmapTextureAtlas tex = new BitmapTextureAtlas(glMaxWidth, glMaxWidth, TextureOptions.BILINEAR); - tex.addTextureAtlasSource(source, 0, 0); - GlobalManager.getInstance().getEngine().getTextureManager().loadTexture(tex); - createdTextures.add(tex); - for (TextureInfo info : toLoad) { - info.texture = new TextureRegion(tex, info.pos.x, info.pos.y, info.size.x, info.size.y); - info.texture.setTextureRegionBufferManaged(false); - } - } - pack.recycle(); + if (iterator.hasNext()) { + int width = glMaxWidth; + int height = currentPack == 0 ? lineMaxY + 10 : glMaxWidth; + pack = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); + } + if (pack == null) { + return; + } + Canvas canvas = new Canvas(pack); + Paint paint = new Paint(); + paint.setAntiAlias(true); + paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC)); + List toLoad = new ArrayList<>(); + Bitmap tmp; + while (iterator.hasNext()) { + toLoad.clear(); + pack.eraseColor(Color.argb(0, 0, 0, 0)); + int currentPack = iterator.next().pageIndex; + iterator.previous(); + while (iterator.hasNext()) { + TextureInfo info = iterator.next(); + if (info.pageIndex != currentPack) { + break; + } + toLoad.add(info); + canvas.drawBitmap(tmp = loadBitmap(info), info.pos.x, info.pos.y, paint); + tmp.recycle(); + } + if (onPackDrawDone != null) { + onPackDrawDone.consume(pack); + } + final QualityFileBitmapSource source = new QualityFileBitmapSource( + TextureHelper.createFactoryFromBitmap(pack)); + final BitmapTextureAtlas tex = new BitmapTextureAtlas(glMaxWidth, glMaxWidth, TextureOptions.BILINEAR); + tex.addTextureAtlasSource(source, 0, 0); + GlobalManager.getInstance().getEngine().getTextureManager().loadTexture(tex); + createdTextures.add(tex); + for (TextureInfo info : toLoad) { + info.texture = new TextureRegion(tex, info.pos.x, info.pos.y, info.size.x, info.size.y); + info.texture.setTextureRegionBufferManaged(false); + } + } + pack.recycle(); - for (TextureInfo info : infos) { - directPut(info.name, info.texture); - } + for (TextureInfo info : infos) { + directPut(info.name, info.texture); + } - } + } - private void testAddRaw(TextureInfo raw) { - if (raw.size.x > maxW || raw.size.y > maxH) { - raw.single = true; - raw.pageIndex = -1; - } else { - tryAddToPack(raw); - } - } + private void testAddRaw(TextureInfo raw) { + if (raw.size.x > maxW || raw.size.y > maxH) { + raw.single = true; + raw.pageIndex = -1; + } else { + tryAddToPack(raw); + } + } - private void tryAddToPack(TextureInfo raw) { - if (currentX + raw.size.x + marginX < glMaxWidth) { - tryAddInLine(raw); - } else { - toNextLine(); - tryAddToPack(raw); - } - } + private void tryAddToPack(TextureInfo raw) { + if (currentX + raw.size.x + marginX < glMaxWidth) { + tryAddInLine(raw); + } else { + toNextLine(); + tryAddToPack(raw); + } + } - private void tryAddInLine(TextureInfo raw) { - if (currentY + raw.size.y + marginY < glMaxWidth) { - raw.single = false; - raw.pageIndex = currentPack; - raw.pos = new Vec2Int(currentX, currentY); - currentX += raw.size.x + marginX; - lineMaxY = Math.round(Math.max(lineMaxY, currentY + raw.size.y + marginY)); - } else { - toNewPack(); - tryAddToPack(raw); - } - } + private void tryAddInLine(TextureInfo raw) { + if (currentY + raw.size.y + marginY < glMaxWidth) { + raw.single = false; + raw.pageIndex = currentPack; + raw.pos = new Vec2Int(currentX, currentY); + currentX += raw.size.x + marginX; + lineMaxY = Math.round(Math.max(lineMaxY, currentY + raw.size.y + marginY)); + } else { + toNewPack(); + tryAddToPack(raw); + } + } - public void toNewPack() { - currentPack++; - currentX = 0; - currentY = 0; - lineMaxY = 0; - } + public void toNewPack() { + currentPack++; + currentX = 0; + currentY = 0; + lineMaxY = 0; + } - private void toNextLine() { - currentX = 0; - currentY = lineMaxY + marginY; - } + private void toNextLine() { + currentX = 0; + currentY = lineMaxY + marginY; + } - private Bitmap loadBitmap(TextureInfo info) { - Bitmap bmp; - if (info.err) { - bmp = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888); - bmp.setPixel(0, 0, Color.argb(255, 255, 0, 0)); - } else { - try { - bmp = BitmapFactory.decodeFile(info.file, options); - } catch (Exception e) { - bmp = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888); - bmp.setPixel(0, 0, Color.argb(255, 255, 0, 0)); - } - } - return bmp; - } + private Bitmap loadBitmap(TextureInfo info) { + Bitmap bmp; + if (info.err) { + bmp = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888); + bmp.setPixel(0, 0, Color.argb(255, 255, 0, 0)); + } else { + try { + bmp = BitmapFactory.decodeFile(info.file, options); + } catch (Exception e) { + bmp = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888); + bmp.setPixel(0, 0, Color.argb(255, 255, 0, 0)); + } + } + return bmp; + } - protected void directPut(String name, TextureRegion region) { - textures.put(name, region); - } + protected void directPut(String name, TextureRegion region) { + textures.put(name, region); + } - private TextureInfo loadInfo(String name) { - TextureInfo info = new TextureInfo(); - try { - info.name = name; - info.file = new File(dir, name).getAbsolutePath(); - Vec2Int size = BitmapUtil.parseBitmapSize(new File(info.file)); - info.pos = new Vec2Int(0, 0); - info.size = size; - } catch (Exception e) { - e.printStackTrace(); - info.err = true; - info.pos = new Vec2Int(0, 0); - info.size = new Vec2Int(1, 1); - } - return info; - } + private TextureInfo loadInfo(String name) { + TextureInfo info = new TextureInfo(); + try { + info.name = name; + info.file = new File(dir, name).getAbsolutePath(); + Vec2Int size = BitmapUtil.parseBitmapSize(new File(info.file)); + info.pos = new Vec2Int(0, 0); + info.size = size; + } catch (Exception e) { + e.printStackTrace(); + info.err = true; + info.pos = new Vec2Int(0, 0); + info.size = new Vec2Int(1, 1); + } + return info; + } - public TextureRegion get(String name) { - TextureRegion region; - if ((region = textures.get(name)) == null) { - add(name); - region = get(name); - } - return region; - } + public TextureRegion get(String name) { + TextureRegion region; + if ((region = textures.get(name)) == null) { + add(name); + region = get(name); + } + return region; + } - private static class TextureInfo { - public TextureRegion texture; - public String name; - public String file; - public Vec2Int size; - public Vec2Int pos; - public boolean err = false; - public boolean single = true; - public int pageIndex = -1; - } + private static class TextureInfo { + public TextureRegion texture; + public String name; + public String file; + public Vec2Int size; + public Vec2Int pos; + public boolean err = false; + public boolean single = true; + public int pageIndex = -1; + } } diff --git a/src/com/edlplan/framework/support/osb/DepthOrderRenderEngine.java b/src/com/edlplan/framework/support/osb/DepthOrderRenderEngine.java index 36366fa7..79a7224d 100644 --- a/src/com/edlplan/framework/support/osb/DepthOrderRenderEngine.java +++ b/src/com/edlplan/framework/support/osb/DepthOrderRenderEngine.java @@ -7,43 +7,43 @@ public class DepthOrderRenderEngine { - public LinkedNode first, end; - - public DepthOrderRenderEngine() { - first = new LinkedNode<>(); - end = new LinkedNode<>(); - first.insertToNext(end); - } - - public void add(EGFStoryboardSprite sprite) { - for (LinkedNode s = end.pre; s != first; s = s.pre) { - if (s.value.sprite.depth < sprite.sprite.depth) { - s.insertToNext(new LinkedNode<>(sprite)); - return; - } - } - first.insertToNext(new LinkedNode<>(sprite)); - } - - public void remove(EGFStoryboardSprite sprite) { - for (LinkedNode s = first.next; s != end; s = s.next) { - if (s.value == sprite) { - s.removeFromList(); - break; - } - } - } - - public void draw(BaseCanvas canvas) { - TextureQuadBatch batch = TextureQuadBatch.getDefaultBatch(); - for (LinkedNode s = first.next; s != end; s = s.next) { - if (s.value.textureQuad.alpha.value < 0.001) { - continue; - } - canvas.getBlendSetting().setBlendType(s.value.blendMode.value ? BlendType.Additive : BlendType.Normal); - batch.add(s.value.textureQuad); - } - } + public LinkedNode first, end; + + public DepthOrderRenderEngine() { + first = new LinkedNode<>(); + end = new LinkedNode<>(); + first.insertToNext(end); + } + + public void add(EGFStoryboardSprite sprite) { + for (LinkedNode s = end.pre; s != first; s = s.pre) { + if (s.value.sprite.depth < sprite.sprite.depth) { + s.insertToNext(new LinkedNode<>(sprite)); + return; + } + } + first.insertToNext(new LinkedNode<>(sprite)); + } + + public void remove(EGFStoryboardSprite sprite) { + for (LinkedNode s = first.next; s != end; s = s.next) { + if (s.value == sprite) { + s.removeFromList(); + break; + } + } + } + + public void draw(BaseCanvas canvas) { + TextureQuadBatch batch = TextureQuadBatch.getDefaultBatch(); + for (LinkedNode s = first.next; s != end; s = s.next) { + if (s.value.textureQuad.alpha.value < 0.001) { + continue; + } + canvas.getBlendSetting().setBlendType(s.value.blendMode.value ? BlendType.Additive : BlendType.Normal); + batch.add(s.value.textureQuad); + } + } } diff --git a/src/com/edlplan/framework/support/osb/EGFStoryboardAnimationSprite.java b/src/com/edlplan/framework/support/osb/EGFStoryboardAnimationSprite.java index 1a507ad9..5e4a3f0b 100644 --- a/src/com/edlplan/framework/support/osb/EGFStoryboardAnimationSprite.java +++ b/src/com/edlplan/framework/support/osb/EGFStoryboardAnimationSprite.java @@ -10,43 +10,43 @@ public class EGFStoryboardAnimationSprite extends EGFStoryboardSprite { - public EGFStoryboardAnimationSprite(OsbContext context) { - super(context); - } - - @Override - public void update(double time) { - super.update(time); - StoryboardAnimationSprite sprite = (StoryboardAnimationSprite) this.sprite; - int idx = (int) (Math.max(0, time - sprite.startTime()) / sprite.frameDelay); - if (idx >= sprite.frameCount) { - switch (sprite.loopType) { - case LoopOnce: - idx = sprite.frameCount - 1; - break; - case LoopForever: - default: - idx %= sprite.frameCount; - } - } - ((MultipleFlippableTextureQuad) textureQuad).switchTexture(idx); - } - - @Override - protected void onLoad() { - StoryboardAnimationSprite sprite = (StoryboardAnimationSprite) this.sprite; - MultipleFlippableTextureQuad textureQuad = new MultipleFlippableTextureQuad(); - - List paths = new ArrayList<>(sprite.frameCount); - for (int i = 0; i < sprite.frameCount; i++) { - paths.add(context.texturePool.get(sprite.buildPath(i))); - } - textureQuad.initialWithTextureList(paths); - textureQuad.switchTexture(0); - textureQuad.position.x.value = sprite.startX; - textureQuad.position.y.value = sprite.startY; - textureQuad.anchor = sprite.origin.value; - this.textureQuad = textureQuad; - } + public EGFStoryboardAnimationSprite(OsbContext context) { + super(context); + } + + @Override + public void update(double time) { + super.update(time); + StoryboardAnimationSprite sprite = (StoryboardAnimationSprite) this.sprite; + int idx = (int) (Math.max(0, time - sprite.startTime()) / sprite.frameDelay); + if (idx >= sprite.frameCount) { + switch (sprite.loopType) { + case LoopOnce: + idx = sprite.frameCount - 1; + break; + case LoopForever: + default: + idx %= sprite.frameCount; + } + } + ((MultipleFlippableTextureQuad) textureQuad).switchTexture(idx); + } + + @Override + protected void onLoad() { + StoryboardAnimationSprite sprite = (StoryboardAnimationSprite) this.sprite; + MultipleFlippableTextureQuad textureQuad = new MultipleFlippableTextureQuad(); + + List paths = new ArrayList<>(sprite.frameCount); + for (int i = 0; i < sprite.frameCount; i++) { + paths.add(context.texturePool.get(sprite.buildPath(i))); + } + textureQuad.initialWithTextureList(paths); + textureQuad.switchTexture(0); + textureQuad.position.x.value = sprite.startX; + textureQuad.position.y.value = sprite.startY; + textureQuad.anchor = sprite.origin.value; + this.textureQuad = textureQuad; + } } diff --git a/src/com/edlplan/framework/support/osb/EGFStoryboardSprite.java b/src/com/edlplan/framework/support/osb/EGFStoryboardSprite.java index dbe72042..06ed43d9 100644 --- a/src/com/edlplan/framework/support/osb/EGFStoryboardSprite.java +++ b/src/com/edlplan/framework/support/osb/EGFStoryboardSprite.java @@ -11,65 +11,65 @@ public class EGFStoryboardSprite extends PlayingSprite { - public FlippableTextureQuad textureQuad; - public BooleanRef blendMode = new BooleanRef(false); - protected OsbContext context; + public FlippableTextureQuad textureQuad; + public BooleanRef blendMode = new BooleanRef(false); + protected OsbContext context; - public EGFStoryboardSprite(OsbContext context) { - this.context = context; - } + public EGFStoryboardSprite(OsbContext context) { + this.context = context; + } - @Override - protected void onLoad() { - textureQuad = new FlippableTextureQuad(); - textureQuad.setTextureAndSize(context.texturePool.get(sprite.spriteFilename)); - textureQuad.position.x.value = sprite.startX; - textureQuad.position.y.value = sprite.startY; - textureQuad.anchor = sprite.origin.value; - } + @Override + protected void onLoad() { + textureQuad = new FlippableTextureQuad(); + textureQuad.setTextureAndSize(context.texturePool.get(sprite.spriteFilename)); + textureQuad.position.x.value = sprite.startX; + textureQuad.position.y.value = sprite.startY; + textureQuad.anchor = sprite.origin.value; + } - @Override - public void onAddedToScene() { - context.engines[sprite.layer.ordinal()].add(this); - } + @Override + public void onAddedToScene() { + context.engines[sprite.layer.ordinal()].add(this); + } - @Override - public void onRemoveFromScene() { - context.engines[sprite.layer.ordinal()].remove(this); - } + @Override + public void onRemoveFromScene() { + context.engines[sprite.layer.ordinal()].remove(this); + } - @Override - public CommandHandleTimeline createByTarget(Target target) { - switch (target) { - case X: - return new CommandFloatHandleTimeline(textureQuad.position.x); - case Y: - return new CommandFloatHandleTimeline(textureQuad.position.y); - case ScaleX: - return new CommandFloatHandleTimeline(textureQuad.enableScale().scale.x); - case ScaleY: - return new CommandFloatHandleTimeline(textureQuad.enableScale().scale.y); - case Alpha: - return new CommandFloatHandleTimeline(textureQuad.alpha); - case Rotation: - return new CommandFloatHandleTimeline(textureQuad.enableRotation().rotation); - case Color: - return new CommandColor4HandleTimeline() {{ - value = textureQuad.enableColor().accentColor; - }}; - case FlipH: - return new CommandBooleanHandleTimeline() {{ - value = textureQuad.flipH; - }}; - case FlipV: - return new CommandBooleanHandleTimeline() {{ - value = textureQuad.flipV; - }}; - case BlendingMode: - return new CommandBooleanHandleTimeline() {{ - value = blendMode; - }}; - } - return null; - } + @Override + public CommandHandleTimeline createByTarget(Target target) { + switch (target) { + case X: + return new CommandFloatHandleTimeline(textureQuad.position.x); + case Y: + return new CommandFloatHandleTimeline(textureQuad.position.y); + case ScaleX: + return new CommandFloatHandleTimeline(textureQuad.enableScale().scale.x); + case ScaleY: + return new CommandFloatHandleTimeline(textureQuad.enableScale().scale.y); + case Alpha: + return new CommandFloatHandleTimeline(textureQuad.alpha); + case Rotation: + return new CommandFloatHandleTimeline(textureQuad.enableRotation().rotation); + case Color: + return new CommandColor4HandleTimeline() {{ + value = textureQuad.enableColor().accentColor; + }}; + case FlipH: + return new CommandBooleanHandleTimeline() {{ + value = textureQuad.flipH; + }}; + case FlipV: + return new CommandBooleanHandleTimeline() {{ + value = textureQuad.flipV; + }}; + case BlendingMode: + return new CommandBooleanHandleTimeline() {{ + value = blendMode; + }}; + } + return null; + } } diff --git a/src/com/edlplan/framework/support/osb/LayerRenderEngine.java b/src/com/edlplan/framework/support/osb/LayerRenderEngine.java index 86ec335a..ebd703e7 100644 --- a/src/com/edlplan/framework/support/osb/LayerRenderEngine.java +++ b/src/com/edlplan/framework/support/osb/LayerRenderEngine.java @@ -4,17 +4,17 @@ public class LayerRenderEngine extends DepthOrderRenderEngine { - private com.edlplan.edlosbsupport.elements.StoryboardSprite.Layer layer; + private com.edlplan.edlosbsupport.elements.StoryboardSprite.Layer layer; - public LayerRenderEngine(com.edlplan.edlosbsupport.elements.StoryboardSprite.Layer layer) { - this.layer = layer; - } + public LayerRenderEngine(com.edlplan.edlosbsupport.elements.StoryboardSprite.Layer layer) { + this.layer = layer; + } - public StoryboardSprite.Layer getLayer() { - return layer; - } + public StoryboardSprite.Layer getLayer() { + return layer; + } - public void setLayer(StoryboardSprite.Layer layer) { - this.layer = layer; - } + public void setLayer(StoryboardSprite.Layer layer) { + this.layer = layer; + } } diff --git a/src/com/edlplan/framework/support/osb/OsbContext.java b/src/com/edlplan/framework/support/osb/OsbContext.java index ea56fbdd..8d900aaa 100644 --- a/src/com/edlplan/framework/support/osb/OsbContext.java +++ b/src/com/edlplan/framework/support/osb/OsbContext.java @@ -4,8 +4,8 @@ public class OsbContext { - public TexturePool texturePool; + public TexturePool texturePool; - public LayerRenderEngine[] engines; + public LayerRenderEngine[] engines; } diff --git a/src/com/edlplan/framework/support/osb/StoryboardSprite.java b/src/com/edlplan/framework/support/osb/StoryboardSprite.java index 224730be..233a5ee3 100644 --- a/src/com/edlplan/framework/support/osb/StoryboardSprite.java +++ b/src/com/edlplan/framework/support/osb/StoryboardSprite.java @@ -30,329 +30,329 @@ public class StoryboardSprite extends SupportSprite { - OsbContext context = new OsbContext(); - OsuStoryboard storyboard; - OsbPlayer osbPlayer; - TextureQuad backgroundQuad; - TextureQuad forgroundQuad; - boolean replaceBackground; - String loadedOsu; - private double time; - private boolean needUpdate = false; - - public StoryboardSprite(float width, float height) { - super(width, height); - } - - private static HashMap countTextureUsedTimes(OsuStoryboard storyboard) { - HashMap textures = new HashMap<>(); - Integer tmp; - String tmps; - for (OsuStoryboardLayer layer : storyboard.layers) { - if (layer != null) { - for (IStoryboardElement element : layer.elements) { - if (element instanceof StoryboardAnimationSprite) { - StoryboardAnimationSprite as = (StoryboardAnimationSprite) element; - for (int i = 0; i < as.frameCount; i++) { - if ((tmp = textures.get(tmps = as.buildPath(i))) == null) { - textures.put(tmps, 1); - continue; - } - textures.put(tmps, tmp + 1); - } - } else if (element instanceof com.edlplan.edlosbsupport.elements.StoryboardSprite) { - if ((tmp = textures.get(tmps = ((com.edlplan.edlosbsupport.elements.StoryboardSprite) element).spriteFilename)) == null) { - textures.put(tmps, 1); - continue; - } - textures.put(tmps, tmp + 1); - } - } - } - } - return textures; - } - - public TexturePool getLoadedPool() { - return context.texturePool; - } - - public void setBrightness(float brightness) { - TextureRegion region = TextureHelper.create1xRegion(Color.argb(255, 0, 0, 0)); - backgroundQuad = new TextureQuad(); - backgroundQuad.anchor = Anchor.TopLeft; - backgroundQuad.setTextureAndSize(region); - forgroundQuad = new TextureQuad(); - forgroundQuad.anchor = Anchor.TopLeft; - forgroundQuad.setTextureAndSize(region); - forgroundQuad.alpha.value = 1 - brightness; - } - - public void updateTime(double time) { - if (Math.abs(this.time - time) > 10) { - this.time = time; - if (osbPlayer != null) { - osbPlayer.update(time); - } - } - } - - public boolean isStoryboardAvailable() { - return storyboard != null; - } - - public void setOverlayDrawProxy(ProxySprite proxy) { - proxy.setDrawProxy(this::drawOverlay); - } - - public void drawOverlay(BaseCanvas canvas) { - if (storyboard == null) { - return; - } - - canvas.getBlendSetting().save(); - canvas.save(); - float scale = Math.max(640 / canvas.getWidth(), 480 / canvas.getHeight()); - Vec2 startOffset = new Vec2(canvas.getWidth() / 2, canvas.getHeight() / 2) - .minus(640 * 0.5f / scale, 480 * 0.5f / scale); - - canvas.translate(startOffset.x, startOffset.y).expendAxis(scale); - - if (context.engines != null) { - for (LayerRenderEngine engine : context.engines) { - if (engine != null && engine.getLayer() == com.edlplan.edlosbsupport.elements.StoryboardSprite.Layer.Overlay) { - engine.draw(canvas); - } - } - } - - canvas.restore(); - canvas.getBlendSetting().restore(); - } - - @Override - protected void onSupportDraw(BaseCanvas canvas) { - super.onSupportDraw(canvas); - - if (storyboard == null) { - return; - } - - if (replaceBackground) { - if (backgroundQuad != null) { - backgroundQuad.size.set(canvas.getWidth(), canvas.getHeight()); - TextureQuadBatch.getDefaultBatch().add(backgroundQuad); - BatchEngine.flush(); - } - } else { - if (backgroundQuad == null) { - backgroundQuad = new TextureQuad(); - } - backgroundQuad.anchor = Anchor.Center; - backgroundQuad.setTextureAndSize(context.texturePool.get(storyboard.backgroundFile)); - backgroundQuad.position.set(canvas.getWidth() / 2, canvas.getHeight() / 2); - backgroundQuad.enableScale().scale.set( - Math.min( - canvas.getWidth() / backgroundQuad.size.x, - canvas.getHeight() / backgroundQuad.size.y)); - TextureQuadBatch.getDefaultBatch().add(backgroundQuad); - } - - canvas.getBlendSetting().save(); - canvas.save(); - float scale = Math.max(640 / canvas.getWidth(), 480 / canvas.getHeight()); - Vec2 startOffset = new Vec2(canvas.getWidth() / 2, canvas.getHeight() / 2) - .minus(640 * 0.5f / scale, 480 * 0.5f / scale); - - canvas.translate(startOffset.x, startOffset.y).expendAxis(scale); - - if (context.engines != null) { - for (LayerRenderEngine engine : context.engines) { - if (engine != null && engine.getLayer() != com.edlplan.edlosbsupport.elements.StoryboardSprite.Layer.Overlay) { - engine.draw(canvas); - } - } - } - - canvas.restore(); - canvas.getBlendSetting().restore(); - - if (forgroundQuad != null) { - forgroundQuad.size.set(canvas.getWidth(), canvas.getHeight()); - TextureQuadBatch.getDefaultBatch().add(forgroundQuad); - BatchEngine.flush(); - } - } - - private File findOsb(String osuFile) { - File dir = new File(osuFile); - dir = dir.getParentFile(); - File[] fs = FileUtils.listFiles(dir, ".osb"); - if (fs.length > 0) { - return fs[0]; - } else { - return null; - } - } - - private void loadOsb(String osuFile) { - File file = findOsb(osuFile); - if (file == null) { - return; - } - - OsbFileParser parser = new OsbFileParser( - file, - null); - - Tracker.createTmpNode("ParseOsb").wrap(() -> { - try { - parser.parse(); - } catch (Exception e) { - e.printStackTrace(); - } - }).then(System.out::println); - - storyboard = parser.getBaseParser().getStoryboard(); - } - - private void loadOsu(String osuFile) { - OsbFileParser parser = new OsbFileParser(new File(osuFile), null); - Tracker.createTmpNode("ParseOsu").wrap(() -> { - try { - parser.parse(); - } catch (Exception e) { - e.printStackTrace(); - } - }).then(System.out::println); - - OsuStoryboard osustoryboard = parser.getBaseParser().getStoryboard(); - - if (storyboard == null) { - boolean empty = true; - for (OsuStoryboardLayer layer : osustoryboard.layers) { - if (layer != null) { - empty = false; - break; - } - } - if (empty) { - return; - } - storyboard = osustoryboard; - } else { - storyboard.appendStoryboard(osustoryboard); - } - } - - private void loadFromCache() { - - context.engines = new LayerRenderEngine[com.edlplan.edlosbsupport.elements.StoryboardSprite.Layer.values().length]; - for (int i = 0; i < context.engines.length; i++) { - context.engines[i] = new LayerRenderEngine(com.edlplan.edlosbsupport.elements.StoryboardSprite.Layer.values()[i]); - } - - if (storyboard == null) { - return; - } - - osbPlayer = new OsbPlayer(s -> { - if (s.getClass() == com.edlplan.edlosbsupport.elements.StoryboardSprite.class) { - return new EGFStoryboardSprite(context); - } else { - return new EGFStoryboardAnimationSprite(context); - } - }); - - Tracker.createTmpNode("LoadPlayer").wrap(() -> { - osbPlayer.loadStoryboard(storyboard); - }).then(System.out::println); - } - - public void loadStoryboard(String osuFile) { - System.out.println(this + " load storyboard from " + osuFile); - if (osuFile.equals(loadedOsu)) { - System.out.println("load storyboard from cache"); - loadFromCache(); - return; - } - loadedOsu = osuFile; - - releaseStoryboard(); - - loadedOsu = osuFile; - - File osu = new File(osuFile); - File dir = osu.getParentFile(); - TexturePool pool = new TexturePool(dir); - - context.texturePool = pool; - context.engines = new LayerRenderEngine[com.edlplan.edlosbsupport.elements.StoryboardSprite.Layer.values().length]; - for (int i = 0; i < context.engines.length; i++) { - context.engines[i] = new LayerRenderEngine(com.edlplan.edlosbsupport.elements.StoryboardSprite.Layer.values()[i]); - } - - loadOsb(osuFile); - loadOsu(osuFile); - - if (storyboard == null) { - return; - } - - replaceBackground = storyboard.needReplaceBackground(); - Tracker.createTmpNode("PackTextures").wrap(() -> { - //Set all = new HashSet<>();// = storyboard.getAllNeededTextures(); - HashMap counted = countTextureUsedTimes(storyboard); - if ((!replaceBackground) && storyboard.backgroundFile != null) { - counted.put( - storyboard.backgroundFile, - counted.get(storyboard.backgroundFile) == null ? - 1 : (counted.get(storyboard.backgroundFile) + 1)); - } - - SmartIterator allToPack = SmartIterator.wrap(counted.keySet().iterator()) - .applyFilter(s -> counted.get(s) >= 15); - pool.packAll(allToPack, null); - - allToPack = SmartIterator.wrap(counted.keySet().iterator()) - .applyFilter(s -> counted.get(s) < 15); - while (allToPack.hasNext()) { - pool.add(allToPack.next()); - } - }).then(System.out::println); - - - osbPlayer = new OsbPlayer(s -> { - if (s.getClass() == com.edlplan.edlosbsupport.elements.StoryboardSprite.class) { - return new EGFStoryboardSprite(context); - } else { - return new EGFStoryboardAnimationSprite(context); - } - }); - - Tracker.createTmpNode("LoadPlayer").wrap(() -> { - osbPlayer.loadStoryboard(storyboard); - }).then(System.out::println); - - } - - public void releaseStoryboard() { - if (context.texturePool != null) { - context.texturePool.clear(); - context.texturePool = null; - } - if (storyboard != null) { - storyboard.clear(); - } - if (osbPlayer != null) { - osbPlayer = null; - } - loadedOsu = null; - } - - @Override - protected void finalize() throws Throwable { - super.finalize(); - releaseStoryboard(); - } + OsbContext context = new OsbContext(); + OsuStoryboard storyboard; + OsbPlayer osbPlayer; + TextureQuad backgroundQuad; + TextureQuad forgroundQuad; + boolean replaceBackground; + String loadedOsu; + private double time; + private boolean needUpdate = false; + + public StoryboardSprite(float width, float height) { + super(width, height); + } + + private static HashMap countTextureUsedTimes(OsuStoryboard storyboard) { + HashMap textures = new HashMap<>(); + Integer tmp; + String tmps; + for (OsuStoryboardLayer layer : storyboard.layers) { + if (layer != null) { + for (IStoryboardElement element : layer.elements) { + if (element instanceof StoryboardAnimationSprite) { + StoryboardAnimationSprite as = (StoryboardAnimationSprite) element; + for (int i = 0; i < as.frameCount; i++) { + if ((tmp = textures.get(tmps = as.buildPath(i))) == null) { + textures.put(tmps, 1); + continue; + } + textures.put(tmps, tmp + 1); + } + } else if (element instanceof com.edlplan.edlosbsupport.elements.StoryboardSprite) { + if ((tmp = textures.get(tmps = ((com.edlplan.edlosbsupport.elements.StoryboardSprite) element).spriteFilename)) == null) { + textures.put(tmps, 1); + continue; + } + textures.put(tmps, tmp + 1); + } + } + } + } + return textures; + } + + public TexturePool getLoadedPool() { + return context.texturePool; + } + + public void setBrightness(float brightness) { + TextureRegion region = TextureHelper.create1xRegion(Color.argb(255, 0, 0, 0)); + backgroundQuad = new TextureQuad(); + backgroundQuad.anchor = Anchor.TopLeft; + backgroundQuad.setTextureAndSize(region); + forgroundQuad = new TextureQuad(); + forgroundQuad.anchor = Anchor.TopLeft; + forgroundQuad.setTextureAndSize(region); + forgroundQuad.alpha.value = 1 - brightness; + } + + public void updateTime(double time) { + if (Math.abs(this.time - time) > 10) { + this.time = time; + if (osbPlayer != null) { + osbPlayer.update(time); + } + } + } + + public boolean isStoryboardAvailable() { + return storyboard != null; + } + + public void setOverlayDrawProxy(ProxySprite proxy) { + proxy.setDrawProxy(this::drawOverlay); + } + + public void drawOverlay(BaseCanvas canvas) { + if (storyboard == null) { + return; + } + + canvas.getBlendSetting().save(); + canvas.save(); + float scale = Math.max(640 / canvas.getWidth(), 480 / canvas.getHeight()); + Vec2 startOffset = new Vec2(canvas.getWidth() / 2, canvas.getHeight() / 2) + .minus(640 * 0.5f / scale, 480 * 0.5f / scale); + + canvas.translate(startOffset.x, startOffset.y).expendAxis(scale); + + if (context.engines != null) { + for (LayerRenderEngine engine : context.engines) { + if (engine != null && engine.getLayer() == com.edlplan.edlosbsupport.elements.StoryboardSprite.Layer.Overlay) { + engine.draw(canvas); + } + } + } + + canvas.restore(); + canvas.getBlendSetting().restore(); + } + + @Override + protected void onSupportDraw(BaseCanvas canvas) { + super.onSupportDraw(canvas); + + if (storyboard == null) { + return; + } + + if (replaceBackground) { + if (backgroundQuad != null) { + backgroundQuad.size.set(canvas.getWidth(), canvas.getHeight()); + TextureQuadBatch.getDefaultBatch().add(backgroundQuad); + BatchEngine.flush(); + } + } else { + if (backgroundQuad == null) { + backgroundQuad = new TextureQuad(); + } + backgroundQuad.anchor = Anchor.Center; + backgroundQuad.setTextureAndSize(context.texturePool.get(storyboard.backgroundFile)); + backgroundQuad.position.set(canvas.getWidth() / 2, canvas.getHeight() / 2); + backgroundQuad.enableScale().scale.set( + Math.min( + canvas.getWidth() / backgroundQuad.size.x, + canvas.getHeight() / backgroundQuad.size.y)); + TextureQuadBatch.getDefaultBatch().add(backgroundQuad); + } + + canvas.getBlendSetting().save(); + canvas.save(); + float scale = Math.max(640 / canvas.getWidth(), 480 / canvas.getHeight()); + Vec2 startOffset = new Vec2(canvas.getWidth() / 2, canvas.getHeight() / 2) + .minus(640 * 0.5f / scale, 480 * 0.5f / scale); + + canvas.translate(startOffset.x, startOffset.y).expendAxis(scale); + + if (context.engines != null) { + for (LayerRenderEngine engine : context.engines) { + if (engine != null && engine.getLayer() != com.edlplan.edlosbsupport.elements.StoryboardSprite.Layer.Overlay) { + engine.draw(canvas); + } + } + } + + canvas.restore(); + canvas.getBlendSetting().restore(); + + if (forgroundQuad != null) { + forgroundQuad.size.set(canvas.getWidth(), canvas.getHeight()); + TextureQuadBatch.getDefaultBatch().add(forgroundQuad); + BatchEngine.flush(); + } + } + + private File findOsb(String osuFile) { + File dir = new File(osuFile); + dir = dir.getParentFile(); + File[] fs = FileUtils.listFiles(dir, ".osb"); + if (fs.length > 0) { + return fs[0]; + } else { + return null; + } + } + + private void loadOsb(String osuFile) { + File file = findOsb(osuFile); + if (file == null) { + return; + } + + OsbFileParser parser = new OsbFileParser( + file, + null); + + Tracker.createTmpNode("ParseOsb").wrap(() -> { + try { + parser.parse(); + } catch (Exception e) { + e.printStackTrace(); + } + }).then(System.out::println); + + storyboard = parser.getBaseParser().getStoryboard(); + } + + private void loadOsu(String osuFile) { + OsbFileParser parser = new OsbFileParser(new File(osuFile), null); + Tracker.createTmpNode("ParseOsu").wrap(() -> { + try { + parser.parse(); + } catch (Exception e) { + e.printStackTrace(); + } + }).then(System.out::println); + + OsuStoryboard osustoryboard = parser.getBaseParser().getStoryboard(); + + if (storyboard == null) { + boolean empty = true; + for (OsuStoryboardLayer layer : osustoryboard.layers) { + if (layer != null) { + empty = false; + break; + } + } + if (empty) { + return; + } + storyboard = osustoryboard; + } else { + storyboard.appendStoryboard(osustoryboard); + } + } + + private void loadFromCache() { + + context.engines = new LayerRenderEngine[com.edlplan.edlosbsupport.elements.StoryboardSprite.Layer.values().length]; + for (int i = 0; i < context.engines.length; i++) { + context.engines[i] = new LayerRenderEngine(com.edlplan.edlosbsupport.elements.StoryboardSprite.Layer.values()[i]); + } + + if (storyboard == null) { + return; + } + + osbPlayer = new OsbPlayer(s -> { + if (s.getClass() == com.edlplan.edlosbsupport.elements.StoryboardSprite.class) { + return new EGFStoryboardSprite(context); + } else { + return new EGFStoryboardAnimationSprite(context); + } + }); + + Tracker.createTmpNode("LoadPlayer").wrap(() -> { + osbPlayer.loadStoryboard(storyboard); + }).then(System.out::println); + } + + public void loadStoryboard(String osuFile) { + System.out.println(this + " load storyboard from " + osuFile); + if (osuFile.equals(loadedOsu)) { + System.out.println("load storyboard from cache"); + loadFromCache(); + return; + } + loadedOsu = osuFile; + + releaseStoryboard(); + + loadedOsu = osuFile; + + File osu = new File(osuFile); + File dir = osu.getParentFile(); + TexturePool pool = new TexturePool(dir); + + context.texturePool = pool; + context.engines = new LayerRenderEngine[com.edlplan.edlosbsupport.elements.StoryboardSprite.Layer.values().length]; + for (int i = 0; i < context.engines.length; i++) { + context.engines[i] = new LayerRenderEngine(com.edlplan.edlosbsupport.elements.StoryboardSprite.Layer.values()[i]); + } + + loadOsb(osuFile); + loadOsu(osuFile); + + if (storyboard == null) { + return; + } + + replaceBackground = storyboard.needReplaceBackground(); + Tracker.createTmpNode("PackTextures").wrap(() -> { + //Set all = new HashSet<>();// = storyboard.getAllNeededTextures(); + HashMap counted = countTextureUsedTimes(storyboard); + if ((!replaceBackground) && storyboard.backgroundFile != null) { + counted.put( + storyboard.backgroundFile, + counted.get(storyboard.backgroundFile) == null ? + 1 : (counted.get(storyboard.backgroundFile) + 1)); + } + + SmartIterator allToPack = SmartIterator.wrap(counted.keySet().iterator()) + .applyFilter(s -> counted.get(s) >= 15); + pool.packAll(allToPack, null); + + allToPack = SmartIterator.wrap(counted.keySet().iterator()) + .applyFilter(s -> counted.get(s) < 15); + while (allToPack.hasNext()) { + pool.add(allToPack.next()); + } + }).then(System.out::println); + + + osbPlayer = new OsbPlayer(s -> { + if (s.getClass() == com.edlplan.edlosbsupport.elements.StoryboardSprite.class) { + return new EGFStoryboardSprite(context); + } else { + return new EGFStoryboardAnimationSprite(context); + } + }); + + Tracker.createTmpNode("LoadPlayer").wrap(() -> { + osbPlayer.loadStoryboard(storyboard); + }).then(System.out::println); + + } + + public void releaseStoryboard() { + if (context.texturePool != null) { + context.texturePool.clear(); + context.texturePool = null; + } + if (storyboard != null) { + storyboard.clear(); + } + if (osbPlayer != null) { + osbPlayer = null; + } + loadedOsu = null; + } + + @Override + protected void finalize() throws Throwable { + super.finalize(); + releaseStoryboard(); + } } diff --git a/src/com/edlplan/framework/support/timing/AbstractClock.java b/src/com/edlplan/framework/support/timing/AbstractClock.java index e979e871..821bd706 100644 --- a/src/com/edlplan/framework/support/timing/AbstractClock.java +++ b/src/com/edlplan/framework/support/timing/AbstractClock.java @@ -2,5 +2,5 @@ public interface AbstractClock { - public double getTime(); + public double getTime(); } diff --git a/src/com/edlplan/framework/support/timing/FrameClock.java b/src/com/edlplan/framework/support/timing/FrameClock.java index 2671ce9b..1c6ee890 100644 --- a/src/com/edlplan/framework/support/timing/FrameClock.java +++ b/src/com/edlplan/framework/support/timing/FrameClock.java @@ -7,80 +7,80 @@ */ public class FrameClock { - private double startTime = -1; + private double startTime = -1; - private double frameTime; + private double frameTime; - private double deltaTime; + private double deltaTime; - private boolean running = false; + private boolean running = false; - public void offset(double o) { - frameTime += o; - } + public void offset(double o) { + frameTime += o; + } - public void start() { - if (startTime == -1) { - startTime = Framework.frameworkTime(); - running = true; - } - } + public void start() { + if (startTime == -1) { + startTime = Framework.frameworkTime(); + running = true; + } + } - /** - * 缓存的帧时间 - * - * @return - */ - public double getFrameTime() { - return frameTime; - } + /** + * 缓存的帧时间 + * + * @return + */ + public double getFrameTime() { + return frameTime; + } - /** - * 当前的Clock是否是有效更新的 - * - * @return - */ - public boolean isRunninng() { - return running; - } + /** + * 当前的Clock是否是有效更新的 + * + * @return + */ + public boolean isRunninng() { + return running; + } - public double toClockTime(double frameworkTime) { - if (running) { - return frameworkTime - startTime; - } else { - return frameTime; - } - } + public double toClockTime(double frameworkTime) { + if (running) { + return frameworkTime - startTime; + } else { + return frameTime; + } + } - /** - * 更新Clock的缓存时间 - */ - public void update() { - if (running) { - double t = Framework.frameworkTime() - startTime; - deltaTime = t - frameTime; - frameTime = t; - } - } + /** + * 更新Clock的缓存时间 + */ + public void update() { + if (running) { + double t = Framework.frameworkTime() - startTime; + deltaTime = t - frameTime; + frameTime = t; + } + } - /** - * 让暂停的Clock运行 - */ - public void run() { - if (!running) { - running = true; - double dt = Framework.frameworkTime() - frameTime; - startTime += dt; - } - } + /** + * 让暂停的Clock运行 + */ + public void run() { + if (!running) { + running = true; + double dt = Framework.frameworkTime() - frameTime; + startTime += dt; + } + } - /** - * 暂停Clock,暂停之后调用update时不再更新时间 - */ - public void pause() { - if (running) { - running = false; - frameTime = Framework.frameworkTime(); - } - } + /** + * 暂停Clock,暂停之后调用update时不再更新时间 + */ + public void pause() { + if (running) { + running = false; + frameTime = Framework.frameworkTime(); + } + } } diff --git a/src/com/edlplan/framework/support/timing/IHasIntervalSchedule.java b/src/com/edlplan/framework/support/timing/IHasIntervalSchedule.java index d4bdcaa9..d3e337c2 100644 --- a/src/com/edlplan/framework/support/timing/IHasIntervalSchedule.java +++ b/src/com/edlplan/framework/support/timing/IHasIntervalSchedule.java @@ -5,20 +5,20 @@ import com.edlplan.framework.utils.annotation.NotThreadSafe; public interface IHasIntervalSchedule { - IntervalSchedule getIntervalSchedule(); + IntervalSchedule getIntervalSchedule(); - @NotThreadSafe - default void addIntervalTask(double start, double end, TimeUpdateable updateable) { - getIntervalSchedule().addTask(start, end, false, updateable); - } + @NotThreadSafe + default void addIntervalTask(double start, double end, TimeUpdateable updateable) { + getIntervalSchedule().addTask(start, end, false, updateable); + } - @NotThreadSafe - default void addAnimTask(double start, double duration, TimeUpdateable anim) { - getIntervalSchedule().addAnimTask(start, duration, anim); - } + @NotThreadSafe + default void addAnimTask(double start, double duration, TimeUpdateable anim) { + getIntervalSchedule().addAnimTask(start, duration, anim); + } - @NotThreadSafe - default void addTask(double time, Runnable runnable) { - getIntervalSchedule().addTask(time, time, true, time1 -> runnable.run()); - } + @NotThreadSafe + default void addTask(double time, Runnable runnable) { + getIntervalSchedule().addTask(time, time, true, time1 -> runnable.run()); + } } diff --git a/src/com/edlplan/framework/support/timing/ILooper.java b/src/com/edlplan/framework/support/timing/ILooper.java index 91a9f7a8..20505ae4 100644 --- a/src/com/edlplan/framework/support/timing/ILooper.java +++ b/src/com/edlplan/framework/support/timing/ILooper.java @@ -1,9 +1,9 @@ package com.edlplan.framework.support.timing; public interface ILooper { - void loop(double deltaTime); + void loop(double deltaTime); - void prepare(); + void prepare(); - void addLoopable(T l); + void addLoopable(T l); } diff --git a/src/com/edlplan/framework/support/timing/IRunnableHandler.java b/src/com/edlplan/framework/support/timing/IRunnableHandler.java index 2afc6f37..a7f34d1f 100644 --- a/src/com/edlplan/framework/support/timing/IRunnableHandler.java +++ b/src/com/edlplan/framework/support/timing/IRunnableHandler.java @@ -1,7 +1,7 @@ package com.edlplan.framework.support.timing; public interface IRunnableHandler { - void post(Runnable r); + void post(Runnable r); - void post(Runnable r, double delayMS); + void post(Runnable r, double delayMS); } diff --git a/src/com/edlplan/framework/support/timing/Loopable.java b/src/com/edlplan/framework/support/timing/Loopable.java index 5a0e21c2..ea5a019d 100644 --- a/src/com/edlplan/framework/support/timing/Loopable.java +++ b/src/com/edlplan/framework/support/timing/Loopable.java @@ -2,32 +2,32 @@ public abstract class Loopable { - private Flag flag = Flag.Run; - private ILooper looper; + private Flag flag = Flag.Run; + private ILooper looper; - public Flag getFlag() { - return flag; - } + public Flag getFlag() { + return flag; + } - public void setFlag(Flag flag) { - this.flag = flag; - } + public void setFlag(Flag flag) { + this.flag = flag; + } - public ILooper getLooper() { - return looper; - } + public ILooper getLooper() { + return looper; + } - public void setLooper(ILooper lp) { - this.looper = lp; - } + public void setLooper(ILooper lp) { + this.looper = lp; + } - public void onRemove() { + public void onRemove() { - } + } - public abstract void onLoop(double deltaTime); + public abstract void onLoop(double deltaTime); - public enum Flag { - Run, Skip, Stop - } + public enum Flag { + Run, Skip, Stop + } } diff --git a/src/com/edlplan/framework/support/timing/MTimer.java b/src/com/edlplan/framework/support/timing/MTimer.java index 10be7649..7f719235 100644 --- a/src/com/edlplan/framework/support/timing/MTimer.java +++ b/src/com/edlplan/framework/support/timing/MTimer.java @@ -3,51 +3,51 @@ import com.edlplan.framework.support.Framework; public class MTimer { - public boolean hasInitial; + public boolean hasInitial; - public double startTime; + public double startTime; - public double nowTime; + public double nowTime; - public double deltaTime; + public double deltaTime; - public double runnedTime; + public double runnedTime; - public MTimer() { - hasInitial = false; - } + public MTimer() { + hasInitial = false; + } - public boolean hasInitial() { - return hasInitial; - } + public boolean hasInitial() { + return hasInitial; + } - public void initial() { - initial(Framework.relativePreciseTimeMillion()); - } + public void initial() { + initial(Framework.relativePreciseTimeMillion()); + } - public void initial(double s) { - hasInitial = true; - startTime = s; - nowTime = s; - deltaTime = 0; - runnedTime = 0; - } + public void initial(double s) { + hasInitial = true; + startTime = s; + nowTime = s; + deltaTime = 0; + runnedTime = 0; + } - public double nowTime() { - return nowTime; - } + public double nowTime() { + return nowTime; + } - public double getDeltaTime() { - return deltaTime; - } + public double getDeltaTime() { + return deltaTime; + } - public void refresh(double _deltaTime) { - deltaTime = _deltaTime; - nowTime += _deltaTime; - runnedTime += _deltaTime; - } + public void refresh(double _deltaTime) { + deltaTime = _deltaTime; + nowTime += _deltaTime; + runnedTime += _deltaTime; + } - public void refresh() { - refresh(Framework.relativePreciseTimeMillion() - nowTime); - } + public void refresh() { + refresh(Framework.relativePreciseTimeMillion() - nowTime); + } } diff --git a/src/com/edlplan/framework/support/timing/RunnableHandler.java b/src/com/edlplan/framework/support/timing/RunnableHandler.java index e99c5db8..83f60647 100644 --- a/src/com/edlplan/framework/support/timing/RunnableHandler.java +++ b/src/com/edlplan/framework/support/timing/RunnableHandler.java @@ -5,78 +5,78 @@ import java.util.Iterator; public class RunnableHandler extends Loopable implements IRunnableHandler { - private ILooper looper; - - private SafeList bufferedRunnables; - - private Loopable.Flag flag = Loopable.Flag.Run; - - public RunnableHandler() { - bufferedRunnables = new SafeList(); - } - - @Override - public void post(Runnable r, double delayMS) { - bufferedRunnables.add(new DelayedRunnable(r, delayMS)); - } - - @Override - public void post(Runnable r) { - post(r, 0); - } - - public void stop() { - flag = Loopable.Flag.Stop; - } - - public void block() { - flag = Loopable.Flag.Skip; - } - - @Override - public void setLooper(ILooper lp) { - - this.looper = lp; - } - - @Override - public void onRemove() { - - bufferedRunnables.clear(); - flag = Loopable.Flag.Stop; - } - - @Override - public void onLoop(double deltaTime) { - - bufferedRunnables.startIterate(); - Iterator iter = bufferedRunnables.iterator(); - DelayedRunnable tmp; - while (iter.hasNext()) { - tmp = iter.next(); - tmp.delay -= deltaTime; - if (tmp.delay <= 0) { - tmp.r.run(); - iter.remove(); - } - } - bufferedRunnables.endIterate(); - } - - @Override - public Loopable.Flag getFlag() { - - return flag; - } - - private class DelayedRunnable { - public Runnable r; - public double delay; - - public DelayedRunnable(Runnable r, double delay) { - this.r = r; - this.delay = delay; - } - } + private ILooper looper; + + private SafeList bufferedRunnables; + + private Loopable.Flag flag = Loopable.Flag.Run; + + public RunnableHandler() { + bufferedRunnables = new SafeList(); + } + + @Override + public void post(Runnable r, double delayMS) { + bufferedRunnables.add(new DelayedRunnable(r, delayMS)); + } + + @Override + public void post(Runnable r) { + post(r, 0); + } + + public void stop() { + flag = Loopable.Flag.Stop; + } + + public void block() { + flag = Loopable.Flag.Skip; + } + + @Override + public void setLooper(ILooper lp) { + + this.looper = lp; + } + + @Override + public void onRemove() { + + bufferedRunnables.clear(); + flag = Loopable.Flag.Stop; + } + + @Override + public void onLoop(double deltaTime) { + + bufferedRunnables.startIterate(); + Iterator iter = bufferedRunnables.iterator(); + DelayedRunnable tmp; + while (iter.hasNext()) { + tmp = iter.next(); + tmp.delay -= deltaTime; + if (tmp.delay <= 0) { + tmp.r.run(); + iter.remove(); + } + } + bufferedRunnables.endIterate(); + } + + @Override + public Loopable.Flag getFlag() { + + return flag; + } + + private class DelayedRunnable { + public Runnable r; + public double delay; + + public DelayedRunnable(Runnable r, double delay) { + this.r = r; + this.delay = delay; + } + } } diff --git a/src/com/edlplan/framework/support/util/BufferUtil.java b/src/com/edlplan/framework/support/util/BufferUtil.java index e34969d6..ce9d178d 100644 --- a/src/com/edlplan/framework/support/util/BufferUtil.java +++ b/src/com/edlplan/framework/support/util/BufferUtil.java @@ -8,62 +8,62 @@ public class BufferUtil { - public static FloatBuffer createFloatBuffer(int floatCount) { - ByteBuffer bb = ByteBuffer.allocateDirect(floatCount * 4); - bb.order(ByteOrder.nativeOrder()); - return bb.asFloatBuffer(); - } - - public static ShortBuffer createShortBuffer(int shortCount) { - ByteBuffer bb = ByteBuffer.allocateDirect(shortCount * 2); - bb.order(ByteOrder.nativeOrder()); - return bb.asShortBuffer(); - } - - public static IntBuffer createIntBuffer(int intCount) { - ByteBuffer bb = ByteBuffer.allocateDirect(intCount * 4); - bb.order(ByteOrder.nativeOrder()); - return bb.asIntBuffer(); - } - - public static class ReusedFloatBuffer { - - private FloatBuffer buffer; - - public FloatBuffer load(float[] ary) { - if (buffer == null || buffer.capacity() < ary.length) { - buffer = createFloatBuffer(ary.length * 3 / 2 + 20); - } - buffer.position(0).limit(ary.length); - buffer.put(ary); - buffer.position(0); - return buffer; - } - - public FloatBuffer getBuffer() { - return buffer; - } - - } - - public static class ReusedShortBuffer { - - private ShortBuffer buffer; - - public ShortBuffer load(short[] ary) { - if (buffer == null || buffer.capacity() < ary.length) { - buffer = createShortBuffer(ary.length * 3 / 2 + 20); - } - buffer.position(0).limit(ary.length); - buffer.put(ary); - buffer.position(0); - return buffer; - } - - public ShortBuffer getBuffer() { - return buffer; - } - - } + public static FloatBuffer createFloatBuffer(int floatCount) { + ByteBuffer bb = ByteBuffer.allocateDirect(floatCount * 4); + bb.order(ByteOrder.nativeOrder()); + return bb.asFloatBuffer(); + } + + public static ShortBuffer createShortBuffer(int shortCount) { + ByteBuffer bb = ByteBuffer.allocateDirect(shortCount * 2); + bb.order(ByteOrder.nativeOrder()); + return bb.asShortBuffer(); + } + + public static IntBuffer createIntBuffer(int intCount) { + ByteBuffer bb = ByteBuffer.allocateDirect(intCount * 4); + bb.order(ByteOrder.nativeOrder()); + return bb.asIntBuffer(); + } + + public static class ReusedFloatBuffer { + + private FloatBuffer buffer; + + public FloatBuffer load(float[] ary) { + if (buffer == null || buffer.capacity() < ary.length) { + buffer = createFloatBuffer(ary.length * 3 / 2 + 20); + } + buffer.position(0).limit(ary.length); + buffer.put(ary); + buffer.position(0); + return buffer; + } + + public FloatBuffer getBuffer() { + return buffer; + } + + } + + public static class ReusedShortBuffer { + + private ShortBuffer buffer; + + public ShortBuffer load(short[] ary) { + if (buffer == null || buffer.capacity() < ary.length) { + buffer = createShortBuffer(ary.length * 3 / 2 + 20); + } + buffer.position(0).limit(ary.length); + buffer.put(ary); + buffer.position(0); + return buffer; + } + + public ShortBuffer getBuffer() { + return buffer; + } + + } } diff --git a/src/com/edlplan/framework/support/util/Tracker.java b/src/com/edlplan/framework/support/util/Tracker.java index ff1e4c3c..6b6fa79e 100644 --- a/src/com/edlplan/framework/support/util/Tracker.java +++ b/src/com/edlplan/framework/support/util/Tracker.java @@ -8,129 +8,129 @@ import java.util.HashMap; public class Tracker { - public static final String DRAW_ARRAY = "DRAW_ARRAY"; - public static final String PREPARE_VERTEX_DATA = "PREPARE_VERTEX_DATA"; - public static final String INJECT_DATA = "INJECT_DATA"; - public static final String MAIN_LOOPER = "MAIN_LOOPER"; - public static final String DRAW_UI = "DRAW_UI"; - public static final String INVALIDATE_MEASURE_AND_LAYOUT = "INVALIDATE_MEASURE"; - public static final String TOTAL_FRAME_TIME = "TOTAL_FRAME_TIME"; - public static final TrackNode DrawArray; - public static final TrackNode PrepareVertexData; - public static final TrackNode InjectData; - public static final TrackNode MainLooper; - public static final TrackNode DrawUI; - public static final TrackNode TotalFrameTime; - public static final TrackNode InvalidateMeasureAndLayout; - private static boolean enable = true; - private static ArrayList nodes; - private static HashMap namemap; - - - static { - nodes = new ArrayList(); - namemap = new HashMap(); - - DrawArray = register(DRAW_ARRAY); - PrepareVertexData = register(PREPARE_VERTEX_DATA); - InjectData = register(INJECT_DATA); - MainLooper = register(MAIN_LOOPER); - - InvalidateMeasureAndLayout = register(INVALIDATE_MEASURE_AND_LAYOUT); - DrawUI = register(DRAW_UI); - TotalFrameTime = register(TOTAL_FRAME_TIME); - } - - public static TrackNode register(String name) { - TrackNode node = new TrackNode(nodes.size(), name); - nodes.add(node); - namemap.put(name, node); - return node; - } - - public static TrackNode createTmpNode(String name) { - return new TrackNode(-1, name); - } - - public static void reset() { - for (TrackNode n : nodes) { - n.clear(); - } - } - - public static void printlnAsTime(int ms) { - System.out.println(ms + "ms"); - } - - public static Consumer printByTag(String tag) { - return t -> System.out.println(String.format("[%s] %dms", tag, t)); - } - - public static class TrackNode { - public double totalTimeMS; - public long trackedTimes; - public double latestRecordTime; - public int id; - public String name; - - private int stack = 0; - - public TrackNode(int id, String name) { - this.id = id; - this.name = name; - } - - public void watch() { - if (stack == 0) { - latestRecordTime = Framework.relativePreciseTimeMillion(); - } else { - double time = Framework.relativePreciseTimeMillion(); - totalTimeMS += time - latestRecordTime; - latestRecordTime = time; - } - stack++; - } - - public void end() { - trackedTimes++; - stack--; - if (stack == 0) { - totalTimeMS += Framework.relativePreciseTimeMillion() - latestRecordTime; - } else { - double time = Framework.relativePreciseTimeMillion(); - totalTimeMS += time - latestRecordTime; - latestRecordTime = time; - } - } - - public void clear() { - totalTimeMS = 0; - trackedTimes = 0; - latestRecordTime = 0; - stack = 0; - } - - public void setName(String name) { - this.name = name; - } - - public ConsumerContainer wrap(Runnable runnable) { - watch(); - runnable.run(); - end(); - return new ConsumerContainer<>(this); - } - - @Override - public String toString() { - - StringBuilder sb = new StringBuilder(); - sb.append("------------------------------------\n"); - sb.append("name : " + name + " (" + id + ")\n"); - sb.append("totalTime : " + totalTimeMS + "ms\n"); - sb.append("trackedTimes : " + trackedTimes + "\n"); - sb.append("------------------------------------"); - return sb.toString(); - } - } -} \ No newline at end of file + public static final String DRAW_ARRAY = "DRAW_ARRAY"; + public static final String PREPARE_VERTEX_DATA = "PREPARE_VERTEX_DATA"; + public static final String INJECT_DATA = "INJECT_DATA"; + public static final String MAIN_LOOPER = "MAIN_LOOPER"; + public static final String DRAW_UI = "DRAW_UI"; + public static final String INVALIDATE_MEASURE_AND_LAYOUT = "INVALIDATE_MEASURE"; + public static final String TOTAL_FRAME_TIME = "TOTAL_FRAME_TIME"; + public static final TrackNode DrawArray; + public static final TrackNode PrepareVertexData; + public static final TrackNode InjectData; + public static final TrackNode MainLooper; + public static final TrackNode DrawUI; + public static final TrackNode TotalFrameTime; + public static final TrackNode InvalidateMeasureAndLayout; + private static boolean enable = true; + private static ArrayList nodes; + private static HashMap namemap; + + + static { + nodes = new ArrayList(); + namemap = new HashMap(); + + DrawArray = register(DRAW_ARRAY); + PrepareVertexData = register(PREPARE_VERTEX_DATA); + InjectData = register(INJECT_DATA); + MainLooper = register(MAIN_LOOPER); + + InvalidateMeasureAndLayout = register(INVALIDATE_MEASURE_AND_LAYOUT); + DrawUI = register(DRAW_UI); + TotalFrameTime = register(TOTAL_FRAME_TIME); + } + + public static TrackNode register(String name) { + TrackNode node = new TrackNode(nodes.size(), name); + nodes.add(node); + namemap.put(name, node); + return node; + } + + public static TrackNode createTmpNode(String name) { + return new TrackNode(-1, name); + } + + public static void reset() { + for (TrackNode n : nodes) { + n.clear(); + } + } + + public static void printlnAsTime(int ms) { + System.out.println(ms + "ms"); + } + + public static Consumer printByTag(String tag) { + return t -> System.out.println(String.format("[%s] %dms", tag, t)); + } + + public static class TrackNode { + public double totalTimeMS; + public long trackedTimes; + public double latestRecordTime; + public int id; + public String name; + + private int stack = 0; + + public TrackNode(int id, String name) { + this.id = id; + this.name = name; + } + + public void watch() { + if (stack == 0) { + latestRecordTime = Framework.relativePreciseTimeMillion(); + } else { + double time = Framework.relativePreciseTimeMillion(); + totalTimeMS += time - latestRecordTime; + latestRecordTime = time; + } + stack++; + } + + public void end() { + trackedTimes++; + stack--; + if (stack == 0) { + totalTimeMS += Framework.relativePreciseTimeMillion() - latestRecordTime; + } else { + double time = Framework.relativePreciseTimeMillion(); + totalTimeMS += time - latestRecordTime; + latestRecordTime = time; + } + } + + public void clear() { + totalTimeMS = 0; + trackedTimes = 0; + latestRecordTime = 0; + stack = 0; + } + + public void setName(String name) { + this.name = name; + } + + public ConsumerContainer wrap(Runnable runnable) { + watch(); + runnable.run(); + end(); + return new ConsumerContainer<>(this); + } + + @Override + public String toString() { + + StringBuilder sb = new StringBuilder(); + sb.append("------------------------------------\n"); + sb.append("name : " + name + " (" + id + ")\n"); + sb.append("totalTime : " + totalTimeMS + "ms\n"); + sb.append("trackedTimes : " + trackedTimes + "\n"); + sb.append("------------------------------------"); + return sb.toString(); + } + } +} diff --git a/src/com/edlplan/framework/support/util/Updater.java b/src/com/edlplan/framework/support/util/Updater.java index 9749d8b8..52bd4907 100644 --- a/src/com/edlplan/framework/support/util/Updater.java +++ b/src/com/edlplan/framework/support/util/Updater.java @@ -2,50 +2,50 @@ public abstract class Updater { - private final Object lock = new Object(); - - private int updateId; - - private Event runningEvent; - - public void update() { - synchronized (lock) { - updateId++; - if (runningEvent == null) { - Event event = new Event(); - event.updateId = updateId; - event.runnable = createEventRunnable(); - runningEvent = event; - postEvent(event); - } - } - } - - public abstract Runnable createEventRunnable(); - - public abstract void postEvent(Runnable r); - - public class Event implements Runnable { - int updateId; - Runnable runnable; - - @Override - public void run() { - runnable.run(); - synchronized (lock) { - if (this.updateId > Updater.this.updateId) { - //表示之后又发生了更新,应该再次更新 - Event event = new Event(); - event.updateId = Updater.this.updateId; - event.runnable = createEventRunnable(); - runningEvent = event; - postEvent(event); - } else { - //表示没有新的更新了 - runningEvent = null; - } - } - } - } + private final Object lock = new Object(); + + private int updateId; + + private Event runningEvent; + + public void update() { + synchronized (lock) { + updateId++; + if (runningEvent == null) { + Event event = new Event(); + event.updateId = updateId; + event.runnable = createEventRunnable(); + runningEvent = event; + postEvent(event); + } + } + } + + public abstract Runnable createEventRunnable(); + + public abstract void postEvent(Runnable r); + + public class Event implements Runnable { + int updateId; + Runnable runnable; + + @Override + public void run() { + runnable.run(); + synchronized (lock) { + if (this.updateId > Updater.this.updateId) { + //表示之后又发生了更新,应该再次更新 + Event event = new Event(); + event.updateId = Updater.this.updateId; + event.runnable = createEventRunnable(); + runningEvent = event; + postEvent(event); + } else { + //表示没有新的更新了 + runningEvent = null; + } + } + } + } } diff --git a/src/com/edlplan/osu/support/SampleSet.java b/src/com/edlplan/osu/support/SampleSet.java index b8d4d3db..daa774eb 100644 --- a/src/com/edlplan/osu/support/SampleSet.java +++ b/src/com/edlplan/osu/support/SampleSet.java @@ -1,70 +1,70 @@ package com.edlplan.osu.support; public enum SampleSet { - None("None"), Soft("Soft"), Normal("Normal"), Drum("Drum"); - private final String value; + None("None"), Soft("Soft"), Normal("Normal"), Drum("Drum"); + private final String value; - SampleSet(String v) { - value = v; - } + SampleSet(String v) { + value = v; + } - public static SampleSet parse(String s) { - switch (s) { - case "0": - case "None": - return None; - case "1": - case "Normal": - return Normal; - case "2": - case "Soft": - return Soft; - case "3": - case "Drum": - return Drum; - default: - return null; - } - } + public static SampleSet parse(String s) { + switch (s) { + case "0": + case "None": + return None; + case "1": + case "Normal": + return Normal; + case "2": + case "Soft": + return Soft; + case "3": + case "Drum": + return Drum; + default: + return null; + } + } - public static SampleSet fromName(String s) { - switch (s) { - case "None": - return None; - case "Normal": - return Normal; - case "Soft": - return Soft; - case "Drum": - return Drum; - default: - return null; - } - } + public static SampleSet fromName(String s) { + switch (s) { + case "None": + return None; + case "Normal": + return Normal; + case "Soft": + return Soft; + case "Drum": + return Drum; + default: + return null; + } + } - public String value() { - return value; - } + public String value() { + return value; + } - /* - public SampleSet(){ + /* + public SampleSet(){ - } + } - public SampleSet(ValueType t){ - setType(t); - } + public SampleSet(ValueType t){ + setType(t); + } - public void setType(ValueType type){ - this.type=type; - } + public void setType(ValueType type){ + this.type=type; + } - public ValueType getType(){ - return type; - }*/ + public ValueType getType(){ + return type; + }*/ - @Override - public String toString() { - return value; - } + @Override + public String toString() { + return value; + } } diff --git a/src/com/edlplan/osu/support/object/StdPath.java b/src/com/edlplan/osu/support/object/StdPath.java index 5c3a5873..652dffab 100644 --- a/src/com/edlplan/osu/support/object/StdPath.java +++ b/src/com/edlplan/osu/support/object/StdPath.java @@ -6,63 +6,63 @@ import java.util.List; public class StdPath { - private Type type; - private List controlPoints; + private Type type; + private List controlPoints; - public StdPath() { - controlPoints = new ArrayList<>(); - } + public StdPath() { + controlPoints = new ArrayList<>(); + } - public void addControlPoint(Vec2 p) { - controlPoints.add(p); - } + public void addControlPoint(Vec2 p) { + controlPoints.add(p); + } - public void addControlPoint(float x, float y) { - addControlPoint(new Vec2(x, y)); - } + public void addControlPoint(float x, float y) { + addControlPoint(new Vec2(x, y)); + } - public Type getType() { - return type; - } + public Type getType() { + return type; + } - public void setType(Type type) { - this.type = type; - } + public void setType(Type type) { + this.type = type; + } - public List getControlPoints() { - return controlPoints; - } + public List getControlPoints() { + return controlPoints; + } - public void setControlPoints(List controlPoints) { - this.controlPoints = controlPoints; - } + public void setControlPoints(List controlPoints) { + this.controlPoints = controlPoints; + } - public enum Type { - Linear("L"), Perfect("P"), Bezier("B"), Catmull("C"); + public enum Type { + Linear("L"), Perfect("P"), Bezier("B"), Catmull("C"); - public final String tag; + public final String tag; - Type(String t) { - tag = t; - } + Type(String t) { + tag = t; + } - public static Type forName(String n) { - switch (n) { - case "L": - return Linear; - case "P": - return Perfect; - case "B": - return Bezier; - case "C": - return Catmull; - default: - return null; - } - } + public static Type forName(String n) { + switch (n) { + case "L": + return Linear; + case "P": + return Perfect; + case "B": + return Bezier; + case "C": + return Catmull; + default: + return null; + } + } - public String getTag() { - return tag; - } - } -} \ No newline at end of file + public String getTag() { + return tag; + } + } +} diff --git a/src/com/edlplan/osu/support/object/StdSliderPathMaker.java b/src/com/edlplan/osu/support/object/StdSliderPathMaker.java index 4eb91b55..393fa7c8 100644 --- a/src/com/edlplan/osu/support/object/StdSliderPathMaker.java +++ b/src/com/edlplan/osu/support/object/StdSliderPathMaker.java @@ -11,52 +11,52 @@ public class StdSliderPathMaker { - private StdPath slider; - - private LinePath path; - - public StdSliderPathMaker(StdPath sld) { - slider = sld; - path = new LinePath(); - } - - public List getControlPoint() { - return slider.getControlPoints(); - } - - public List calculateSubPath(List subPoints) { - switch (slider.getType()) { - case Linear: - return subPoints; - case Perfect: - if (getControlPoint().size() != 3 || subPoints.size() != 3) { - break; - } else { - List sub = (new CircleApproximator(subPoints.get(0), subPoints.get(1), subPoints.get(2))).createArc(); - if (sub.size() != 0) return sub; - } - break; - case Catmull: - return (new CatmullApproximator(subPoints)).createCatmull(); - } - return (new BezierApproximator(subPoints)).createBezier(); - } - - public LinePath calculatePath() { - path.clear(); - List subControlPoints = new ArrayList(); - for (int i = 0; i < getControlPoint().size(); i++) { - subControlPoints.add(getControlPoint().get(i)); - if (i == getControlPoint().size() - 1 || getControlPoint().get(i).equals(getControlPoint().get(i + 1))) { - List subPath = calculateSubPath(subControlPoints); - for (Vec2 v : subPath) { - if (path.size() == 0 || !path.getLast().equals(v)) { - path.add(v); - } - } - subControlPoints.clear(); - } - } - return path; - } + private StdPath slider; + + private LinePath path; + + public StdSliderPathMaker(StdPath sld) { + slider = sld; + path = new LinePath(); + } + + public List getControlPoint() { + return slider.getControlPoints(); + } + + public List calculateSubPath(List subPoints) { + switch (slider.getType()) { + case Linear: + return subPoints; + case Perfect: + if (getControlPoint().size() != 3 || subPoints.size() != 3) { + break; + } else { + List sub = (new CircleApproximator(subPoints.get(0), subPoints.get(1), subPoints.get(2))).createArc(); + if (sub.size() != 0) return sub; + } + break; + case Catmull: + return (new CatmullApproximator(subPoints)).createCatmull(); + } + return (new BezierApproximator(subPoints)).createBezier(); + } + + public LinePath calculatePath() { + path.clear(); + List subControlPoints = new ArrayList(); + for (int i = 0; i < getControlPoint().size(); i++) { + subControlPoints.add(getControlPoint().get(i)); + if (i == getControlPoint().size() - 1 || getControlPoint().get(i).equals(getControlPoint().get(i + 1))) { + List subPath = calculateSubPath(subControlPoints); + for (Vec2 v : subPath) { + if (path.size() == 0 || !path.getLast().equals(v)) { + path.add(v); + } + } + subControlPoints.clear(); + } + } + return path; + } } diff --git a/src/com/edlplan/osu/support/object/SupportSliderPath.java b/src/com/edlplan/osu/support/object/SupportSliderPath.java index d1a49438..8b65e432 100644 --- a/src/com/edlplan/osu/support/object/SupportSliderPath.java +++ b/src/com/edlplan/osu/support/object/SupportSliderPath.java @@ -13,50 +13,50 @@ public class SupportSliderPath { - protected static StdPath parseStdPath(Vec2 startPoint, String s) { - StdPath p = new StdPath(); - p.addControlPoint(startPoint); - StringSplitter spl = new StringSplitter(s, "\\|"); - p.setType(StdPath.Type.forName(spl.next())); - while (spl.hasNext()) { - p.addControlPoint(parseVec2FF(spl.next())); - } - return p; - } - - protected static Vec2 parseVec2FF(String s) { - String[] sp = s.split(":"); - return new Vec2(Float.parseFloat(sp[0]), Float.parseFloat(sp[1])); - } - - public static LinePath parseToLinePath(Vec2 s, String p) { - StdPath path = parseStdPath(s, p); - return (new StdSliderPathMaker(path)).calculatePath(); - } - - public static GameHelper.SliderPath parseDroidLinePath(PointF s, String p, float l) { - LinePath path = parseToLinePath(new Vec2(s.x, s.y), p); - path.measure(); - path.bufferLength(l); - path = path.cutPath(0, path.getMeasurer().maxLength()).fitToLinePath(); - path.measure(); - ArrayList points = new ArrayList<>(path.size()); - for (int i = 0; i < path.size(); i++) { - Vec2 v = path.get(i); - points.add(Utils.realToTrackCoords(new PointF(v.x, v.y))); - } - GameHelper.SliderPath pp = new GameHelper.SliderPath(); - pp.points = points; - pp.length = new ArrayList<>(points.size()); - float len = 0; - for (int i = 1; i < points.size(); i++) { - len += Vec2.length( - points.get(i - 1).x - points.get(i).x, - points.get(i - 1).y - points.get(i).y - ); - pp.length.add(len); - } - return pp; - } + protected static StdPath parseStdPath(Vec2 startPoint, String s) { + StdPath p = new StdPath(); + p.addControlPoint(startPoint); + StringSplitter spl = new StringSplitter(s, "\\|"); + p.setType(StdPath.Type.forName(spl.next())); + while (spl.hasNext()) { + p.addControlPoint(parseVec2FF(spl.next())); + } + return p; + } + + protected static Vec2 parseVec2FF(String s) { + String[] sp = s.split(":"); + return new Vec2(Float.parseFloat(sp[0]), Float.parseFloat(sp[1])); + } + + public static LinePath parseToLinePath(Vec2 s, String p) { + StdPath path = parseStdPath(s, p); + return (new StdSliderPathMaker(path)).calculatePath(); + } + + public static GameHelper.SliderPath parseDroidLinePath(PointF s, String p, float l) { + LinePath path = parseToLinePath(new Vec2(s.x, s.y), p); + path.measure(); + path.bufferLength(l); + path = path.cutPath(0, path.getMeasurer().maxLength()).fitToLinePath(); + path.measure(); + ArrayList points = new ArrayList<>(path.size()); + for (int i = 0; i < path.size(); i++) { + Vec2 v = path.get(i); + points.add(Utils.realToTrackCoords(new PointF(v.x, v.y))); + } + GameHelper.SliderPath pp = new GameHelper.SliderPath(); + pp.points = points; + pp.length = new ArrayList<>(points.size()); + float len = 0; + for (int i = 1; i < points.size(); i++) { + len += Vec2.length( + points.get(i - 1).x - points.get(i).x, + points.get(i - 1).y - points.get(i).y + ); + pp.length.add(len); + } + return pp; + } } diff --git a/src/com/edlplan/osu/support/slider/AbstractSliderBody.java b/src/com/edlplan/osu/support/slider/AbstractSliderBody.java index 656d41ea..5377e9b9 100644 --- a/src/com/edlplan/osu/support/slider/AbstractSliderBody.java +++ b/src/com/edlplan/osu/support/slider/AbstractSliderBody.java @@ -6,31 +6,31 @@ public abstract class AbstractSliderBody { - protected LinePath path; + protected LinePath path; - public AbstractSliderBody(LinePath path) { - this.path = path; - } + public AbstractSliderBody(LinePath path) { + this.path = path; + } - public void setSliderBodyBaseAlpha(float sliderBodyBaseAlpha) { - } + public void setSliderBodyBaseAlpha(float sliderBodyBaseAlpha) { + } - public abstract void onUpdate(); + public abstract void onUpdate(); - public abstract void setBodyWidth(float width); + public abstract void setBodyWidth(float width); - public abstract void setBorderWidth(float width); + public abstract void setBorderWidth(float width); - public abstract void setBodyColor(float r, float g, float b); + public abstract void setBodyColor(float r, float g, float b); - public abstract void setBorderColor(float r, float g, float b); + public abstract void setBorderColor(float r, float g, float b); - public abstract void setStartLength(float length); + public abstract void setStartLength(float length); - public abstract void setEndLength(float length); + public abstract void setEndLength(float length); - public abstract void applyToScene(Scene scene, boolean emptyOnStart); + public abstract void applyToScene(Scene scene, boolean emptyOnStart); - public abstract void removeFromScene(Scene scene); + public abstract void removeFromScene(Scene scene); } diff --git a/src/com/edlplan/osu/support/slider/Draw3DLinePath.java b/src/com/edlplan/osu/support/slider/Draw3DLinePath.java index 75b909a1..444f721e 100644 --- a/src/com/edlplan/osu/support/slider/Draw3DLinePath.java +++ b/src/com/edlplan/osu/support/slider/Draw3DLinePath.java @@ -7,136 +7,136 @@ import com.edlplan.framework.math.line.AbstractPath; public class Draw3DLinePath { - private static final int MAXRES = 24; - public float alpha; - public float width; - private Triangle3DBuilder triangles; - private AbstractPath path; - - private float zEdge = -1, zCenter = 1; - - public Draw3DLinePath(AbstractPath p, float width, float zCenter, float zEdge) { - this.zCenter = zCenter; - this.zEdge = zEdge; - alpha = 1; - path = p; - this.width = width; - } - - public void setZCenter(float zCenter) { - this.zCenter = zCenter; - } - - public void setZEdge(float zEdge) { - this.zEdge = zEdge; - } - - public Triangle3DBuilder getTriangles() { - if (triangles == null) { - triangles = new Triangle3DBuilder(); - init(); - } - return triangles; - } - - private void addLineCap(Vec2 org, float theta, float thetaDiff) { - final float step = FMath.Pi / MAXRES; - - float dir = Math.signum(thetaDiff); - thetaDiff *= dir; - //MLog.test.vOnce("dir","gl_test","dir: "+dir); - int amountPoints = (int) Math.ceil(thetaDiff / step); - - if (dir < 0) - theta += FMath.Pi; - - /* current = org + atCircle(...)*width */ - Vec3 current = new Vec3(Vec2.atCircle(theta).zoom(width).add(org), zEdge); - - Vec3 orgAtLayer3D = new Vec3(org, zCenter); - for (int i = 1; i <= amountPoints; i++) { - triangles.add( - orgAtLayer3D, - current, - current = new Vec3( - Vec2.atCircle(theta + dir * Math.min(i * step, thetaDiff)) - .zoom(width) - .add(org), - zEdge - ) - ); - } - } - - private void addLineQuads(Vec2 ps, Vec2 pe) { - Vec2 oth_expand = Vec2.lineOthNormal(ps, pe).zoom(width); - - Vec3 startL = new Vec3(ps.copy().add(oth_expand), zEdge); - Vec3 startR = new Vec3(ps.copy().minus(oth_expand), zEdge); - Vec3 endL = new Vec3(pe.copy().add(oth_expand), zEdge); - Vec3 endR = new Vec3(pe.copy().minus(oth_expand), zEdge); - Vec3 start = new Vec3(ps, zCenter); - Vec3 end = new Vec3(pe, zCenter); - - triangles.add( - start, - end, - endL - ); - - triangles.add( - start, - endL, - startL - ); - - triangles.add( - start, - endR, - end - ); - - triangles.add( - start, - startR, - endR - ); - } - - private void init() { - if (path.size() < 2) { - if (path.size() == 1) { - addLineCap(path.get(0), FMath.Pi, FMath.Pi); - addLineCap(path.get(0), 0, FMath.Pi); - return; - } else { - return; - //throw new RuntimeException("Path must has at least 1 point"); - } - } - - float theta = Vec2.calTheta(path.get(0), path.get(1)); - addLineCap(path.get(0), theta + FMath.PiHalf, FMath.Pi); - addLineQuads(path.get(0), path.get(1)); - if (path.size() == 2) { - addLineCap(path.get(1), theta - FMath.PiHalf, FMath.Pi); - return; - } - Vec2 nowPoint = path.get(1); - Vec2 nextPoint; - float preTheta = theta; - float nextTheta; - int max_i = path.size(); - for (int i = 2; i < max_i; i++) { - nextPoint = path.get(i); - nextTheta = Vec2.calTheta(nowPoint, nextPoint); - addLineCap(nowPoint, preTheta - FMath.PiHalf, nextTheta - preTheta); - addLineQuads(nowPoint, nextPoint); - nowPoint = nextPoint; - preTheta = nextTheta; - } - addLineCap(path.get(max_i - 1), preTheta - FMath.PiHalf, FMath.Pi); - } + private static final int MAXRES = 24; + public float alpha; + public float width; + private Triangle3DBuilder triangles; + private AbstractPath path; + + private float zEdge = -1, zCenter = 1; + + public Draw3DLinePath(AbstractPath p, float width, float zCenter, float zEdge) { + this.zCenter = zCenter; + this.zEdge = zEdge; + alpha = 1; + path = p; + this.width = width; + } + + public void setZCenter(float zCenter) { + this.zCenter = zCenter; + } + + public void setZEdge(float zEdge) { + this.zEdge = zEdge; + } + + public Triangle3DBuilder getTriangles() { + if (triangles == null) { + triangles = new Triangle3DBuilder(); + init(); + } + return triangles; + } + + private void addLineCap(Vec2 org, float theta, float thetaDiff) { + final float step = FMath.Pi / MAXRES; + + float dir = Math.signum(thetaDiff); + thetaDiff *= dir; + //MLog.test.vOnce("dir","gl_test","dir: "+dir); + int amountPoints = (int) Math.ceil(thetaDiff / step); + + if (dir < 0) + theta += FMath.Pi; + + /* current = org + atCircle(...)*width */ + Vec3 current = new Vec3(Vec2.atCircle(theta).zoom(width).add(org), zEdge); + + Vec3 orgAtLayer3D = new Vec3(org, zCenter); + for (int i = 1; i <= amountPoints; i++) { + triangles.add( + orgAtLayer3D, + current, + current = new Vec3( + Vec2.atCircle(theta + dir * Math.min(i * step, thetaDiff)) + .zoom(width) + .add(org), + zEdge + ) + ); + } + } + + private void addLineQuads(Vec2 ps, Vec2 pe) { + Vec2 oth_expand = Vec2.lineOthNormal(ps, pe).zoom(width); + + Vec3 startL = new Vec3(ps.copy().add(oth_expand), zEdge); + Vec3 startR = new Vec3(ps.copy().minus(oth_expand), zEdge); + Vec3 endL = new Vec3(pe.copy().add(oth_expand), zEdge); + Vec3 endR = new Vec3(pe.copy().minus(oth_expand), zEdge); + Vec3 start = new Vec3(ps, zCenter); + Vec3 end = new Vec3(pe, zCenter); + + triangles.add( + start, + end, + endL + ); + + triangles.add( + start, + endL, + startL + ); + + triangles.add( + start, + endR, + end + ); + + triangles.add( + start, + startR, + endR + ); + } + + private void init() { + if (path.size() < 2) { + if (path.size() == 1) { + addLineCap(path.get(0), FMath.Pi, FMath.Pi); + addLineCap(path.get(0), 0, FMath.Pi); + return; + } else { + return; + //throw new RuntimeException("Path must has at least 1 point"); + } + } + + float theta = Vec2.calTheta(path.get(0), path.get(1)); + addLineCap(path.get(0), theta + FMath.PiHalf, FMath.Pi); + addLineQuads(path.get(0), path.get(1)); + if (path.size() == 2) { + addLineCap(path.get(1), theta - FMath.PiHalf, FMath.Pi); + return; + } + Vec2 nowPoint = path.get(1); + Vec2 nextPoint; + float preTheta = theta; + float nextTheta; + int max_i = path.size(); + for (int i = 2; i < max_i; i++) { + nextPoint = path.get(i); + nextTheta = Vec2.calTheta(nowPoint, nextPoint); + addLineCap(nowPoint, preTheta - FMath.PiHalf, nextTheta - preTheta); + addLineQuads(nowPoint, nextPoint); + nowPoint = nextPoint; + preTheta = nextTheta; + } + addLineCap(path.get(max_i - 1), preTheta - FMath.PiHalf, FMath.Pi); + } } diff --git a/src/com/edlplan/osu/support/slider/DrawLinePath.java b/src/com/edlplan/osu/support/slider/DrawLinePath.java index 09322679..22b3d415 100644 --- a/src/com/edlplan/osu/support/slider/DrawLinePath.java +++ b/src/com/edlplan/osu/support/slider/DrawLinePath.java @@ -6,166 +6,166 @@ import com.edlplan.framework.math.line.AbstractPath; public class DrawLinePath { - private static final int MAXRES = 24; - - private static final float Z_MIDDLE = 99.0f; - - private static final float Z_SIDE = -99.0f; - public float alpha; - public float width; - Vec2 current, current2; - Vec2 startL = new Vec2(); - Vec2 startR = new Vec2(); - Vec2 endL = new Vec2(); - Vec2 endR = new Vec2(); - Vec2 start = new Vec2(); - Vec2 end = new Vec2(); - Vec2 oth_expand = new Vec2(); - private TriangleBuilder triangles; - private AbstractPath path; - - public DrawLinePath(AbstractPath p, float width) { - alpha = 1; - path = p; - this.width = width; - } - - public DrawLinePath() { - alpha = 1; - this.width = width; - } - - public DrawLinePath reset(AbstractPath p, float width) { - alpha = 1; - path = p; - this.width = width; - if (triangles != null) { - triangles.length = 0; - } - return this; - } - - public TriangleBuilder getTriangles() { - if (triangles == null) { - triangles = new TriangleBuilder(path.size() * 6); - init(); - } - return triangles; - } - - public TriangleBuilder getTriangles(TriangleBuilder builder) { - TriangleBuilder cache = triangles; - if (cache != null) { - cache.getVertex(builder); - } else { - triangles = builder; - builder.length = 0; - init(); - } - triangles = cache; - return builder; - } - - - private void addLineCap(Vec2 org, float theta, float thetaDiff) { - final float step = FMath.Pi / MAXRES; - - float dir = Math.signum(thetaDiff); - thetaDiff *= dir; - int amountPoints = (int) Math.ceil(thetaDiff / step); - - if (dir < 0) - theta += FMath.Pi; - - /* current = org + atCircle(...)*width */ - current = Vec2.atCircle(theta, current).zoom(width).add(org); - - for (int i = 1; i <= amountPoints; i++) { - current2 = Vec2.atCircle(theta + dir * Math.min(i * step, thetaDiff), current2) - .zoom(width) - .add(org); - triangles.add( - org, - current, - current2 - ); - current.set(current2); - } - } - - private void addLineQuads(Vec2 ps, Vec2 pe) { - oth_expand = Vec2.lineOthNormal(ps, pe, oth_expand).zoom(width); - - startL.set(ps); - startL.add(oth_expand); - startR.set(ps); - startR.minus(oth_expand); - endL.set(pe); - endL.add(oth_expand); - endR.set(pe); - endR.minus(oth_expand); - start = ps; - end = pe; - - triangles.add( - start, - end, - endL - ); - - triangles.add( - start, - endL, - startL - ); - - triangles.add( - start, - endR, - end - ); - - triangles.add( - start, - startR, - endR - ); - } - - private void init() { - if (path.size() < 2) { - if (path.size() == 1) { - addLineCap(path.get(0), FMath.Pi, FMath.Pi); - addLineCap(path.get(0), 0, FMath.Pi); - return; - } else { - return; - //throw new RuntimeException("Path must has at least 1 point"); - } - } - - float theta = Vec2.calTheta(path.get(0), path.get(1)); - addLineCap(path.get(0), theta + FMath.PiHalf, FMath.Pi); - addLineQuads(path.get(0), path.get(1)); - if (path.size() == 2) { - addLineCap(path.get(1), theta - FMath.PiHalf, FMath.Pi); - return; - } - Vec2 nowPoint = path.get(1); - Vec2 nextPoint; - float preTheta = theta; - float nextTheta; - int max_i = path.size(); - for (int i = 2; i < max_i; i++) { - nextPoint = path.get(i); - nextTheta = Vec2.calTheta(nowPoint, nextPoint); - addLineCap(nowPoint, preTheta - FMath.PiHalf, nextTheta - preTheta); - addLineQuads(nowPoint, nextPoint); - nowPoint = nextPoint; - preTheta = nextTheta; - } - addLineCap(path.get(max_i - 1), preTheta - FMath.PiHalf, FMath.Pi); - } + private static final int MAXRES = 24; + + private static final float Z_MIDDLE = 99.0f; + + private static final float Z_SIDE = -99.0f; + public float alpha; + public float width; + Vec2 current, current2; + Vec2 startL = new Vec2(); + Vec2 startR = new Vec2(); + Vec2 endL = new Vec2(); + Vec2 endR = new Vec2(); + Vec2 start = new Vec2(); + Vec2 end = new Vec2(); + Vec2 oth_expand = new Vec2(); + private TriangleBuilder triangles; + private AbstractPath path; + + public DrawLinePath(AbstractPath p, float width) { + alpha = 1; + path = p; + this.width = width; + } + + public DrawLinePath() { + alpha = 1; + this.width = width; + } + + public DrawLinePath reset(AbstractPath p, float width) { + alpha = 1; + path = p; + this.width = width; + if (triangles != null) { + triangles.length = 0; + } + return this; + } + + public TriangleBuilder getTriangles() { + if (triangles == null) { + triangles = new TriangleBuilder(path.size() * 6); + init(); + } + return triangles; + } + + public TriangleBuilder getTriangles(TriangleBuilder builder) { + TriangleBuilder cache = triangles; + if (cache != null) { + cache.getVertex(builder); + } else { + triangles = builder; + builder.length = 0; + init(); + } + triangles = cache; + return builder; + } + + + private void addLineCap(Vec2 org, float theta, float thetaDiff) { + final float step = FMath.Pi / MAXRES; + + float dir = Math.signum(thetaDiff); + thetaDiff *= dir; + int amountPoints = (int) Math.ceil(thetaDiff / step); + + if (dir < 0) + theta += FMath.Pi; + + /* current = org + atCircle(...)*width */ + current = Vec2.atCircle(theta, current).zoom(width).add(org); + + for (int i = 1; i <= amountPoints; i++) { + current2 = Vec2.atCircle(theta + dir * Math.min(i * step, thetaDiff), current2) + .zoom(width) + .add(org); + triangles.add( + org, + current, + current2 + ); + current.set(current2); + } + } + + private void addLineQuads(Vec2 ps, Vec2 pe) { + oth_expand = Vec2.lineOthNormal(ps, pe, oth_expand).zoom(width); + + startL.set(ps); + startL.add(oth_expand); + startR.set(ps); + startR.minus(oth_expand); + endL.set(pe); + endL.add(oth_expand); + endR.set(pe); + endR.minus(oth_expand); + start = ps; + end = pe; + + triangles.add( + start, + end, + endL + ); + + triangles.add( + start, + endL, + startL + ); + + triangles.add( + start, + endR, + end + ); + + triangles.add( + start, + startR, + endR + ); + } + + private void init() { + if (path.size() < 2) { + if (path.size() == 1) { + addLineCap(path.get(0), FMath.Pi, FMath.Pi); + addLineCap(path.get(0), 0, FMath.Pi); + return; + } else { + return; + //throw new RuntimeException("Path must has at least 1 point"); + } + } + + float theta = Vec2.calTheta(path.get(0), path.get(1)); + addLineCap(path.get(0), theta + FMath.PiHalf, FMath.Pi); + addLineQuads(path.get(0), path.get(1)); + if (path.size() == 2) { + addLineCap(path.get(1), theta - FMath.PiHalf, FMath.Pi); + return; + } + Vec2 nowPoint = path.get(1); + Vec2 nextPoint; + float preTheta = theta; + float nextTheta; + int max_i = path.size(); + for (int i = 2; i < max_i; i++) { + nextPoint = path.get(i); + nextTheta = Vec2.calTheta(nowPoint, nextPoint); + addLineCap(nowPoint, preTheta - FMath.PiHalf, nextTheta - preTheta); + addLineQuads(nowPoint, nextPoint); + nowPoint = nextPoint; + preTheta = nextTheta; + } + addLineCap(path.get(max_i - 1), preTheta - FMath.PiHalf, FMath.Pi); + } } diff --git a/src/com/edlplan/osu/support/slider/SliderBody2D.java b/src/com/edlplan/osu/support/slider/SliderBody2D.java index f5d826d9..99e411d8 100644 --- a/src/com/edlplan/osu/support/slider/SliderBody2D.java +++ b/src/com/edlplan/osu/support/slider/SliderBody2D.java @@ -13,239 +13,239 @@ public class SliderBody2D extends AbstractSliderBody { - private static final ThreadLocal localCache = new ThreadLocal() { - @Override - public BuildCache get() { - BuildCache cache = super.get(); - if (cache == null) { - cache = new BuildCache(); - set(cache); - } - return cache; - } - }; - private float sliderBodyBaseAlpha = 0.7f; - private float hintAlpha = 0.3f; - private TrianglePack body = null, border = null, hint = null; - private RGBColor bodyColor = new RGBColor(), borderColor = new RGBColor(), hintColor = new RGBColor(); - private float bodyWidth, borderWidth, hintWidth; - private float startLength = 0, endLength = 0; - private boolean enableHint = false; - - public SliderBody2D(LinePath path) { - super(path); - } - - public boolean isEnableHint() { - return enableHint; - } - - public void setEnableHint(boolean enableHint) { - this.enableHint = enableHint; - } - - public float getSliderBodyBaseAlpha() { - return sliderBodyBaseAlpha; - } - - @Override - public void setSliderBodyBaseAlpha(float sliderBodyBaseAlpha) { - this.sliderBodyBaseAlpha = sliderBodyBaseAlpha; - } - - public void setHintAlpha(float hintAlpha) { - this.hintAlpha = hintAlpha; - } - - public void setHintColor(float r, float g, float b) { - this.hintColor.set(r, g, b); - if (hint != null) { - hint.setColor(r, g, b); - } - } - - public void setHintWidth(float hintWidth) { - this.hintWidth = hintWidth; - } - - /** - * Gradually fades the slider's body, border, and hint (if any) out over the specified duration. - *

- * Used if Hidden mod is active. - *

- * - * @param duration The duration of the fade-out animation. - */ - public void fadeOut(float duration) { - if (body.getAlpha() > 0) { - body.registerEntityModifier(new AlphaModifier(duration, body.getAlpha(), 0)); - } - if (border.getAlpha() > 0) { - border.registerEntityModifier(new AlphaModifier(duration, border.getAlpha(), 0)); - } - if (hint != null && hint.getAlpha() > 0) { - hint.registerEntityModifier(new AlphaModifier(duration, hint.getAlpha(), 0)); - } - } - - @Override - public void onUpdate() { - BuildCache cache = localCache.get(); - LinePath sub = path.cutPath(startLength, endLength).fitToLinePath(cache.path); - float alpha = endLength / path.getMeasurer().maxLength(); - body.setAlpha(alpha * sliderBodyBaseAlpha); - border.setAlpha(alpha); - - if (hint != null) { - hint.setAlpha(alpha * hintAlpha); - cache.drawLinePath - .reset(sub, hintWidth) - .getTriangles(cache.triangleBuilder) - .getVertex(hint.getVertices()); - } - - cache.drawLinePath - .reset(sub, bodyWidth) - .getTriangles(cache.triangleBuilder) - .getVertex(body.getVertices()); - cache.drawLinePath - .reset(sub, borderWidth) - .getTriangles(cache.triangleBuilder) - .getVertex(border.getVertices()); - } - - @Override - public void setBodyWidth(float width) { - bodyWidth = width; - } - - @Override - public void setBorderWidth(float width) { - borderWidth = width; - } - - @Override - public void setBodyColor(float r, float g, float b) { - bodyColor.set(r, g, b); - if (body != null) { - body.setColor(r, g, b); - } - } - - @Override - public void setBorderColor(float r, float g, float b) { - borderColor.set(r, g, b); - if (border != null) { - border.setColor(r, g, b); - } - } - - @Override - public void setStartLength(float length) { - startLength = length; - } - - @Override - public void setEndLength(float length) { - endLength = length; - } - - @Override - public void applyToScene(Scene scene, boolean emptyOnStart) { - BuildCache cache = localCache.get(); - body = SpriteCache.trianglePackCache.get(); - border = SpriteCache.trianglePackCache.get(); - - - if (enableHint) { - hint = SpriteCache.trianglePackCache.get(); - hint.setDepthTest(true); - hint.setClearDepthOnStart(true); - hint.setColor(hintColor.r(), hintColor.g(), hintColor.b()); - } - - body.setDepthTest(true); - body.setClearDepthOnStart(!enableHint); - body.setColor(bodyColor.r(), bodyColor.g(), bodyColor.b()); - - border.setDepthTest(true); - border.setClearDepthOnStart(false); - border.setColor(borderColor.r(), borderColor.g(), borderColor.b()); - - if (emptyOnStart) { - body.setAlpha(0); - border.setAlpha(0); - if (hint != null) { - hint.setAlpha(0); - hint.getVertices().length = 0; - } - body.getVertices().length = 0; - border.getVertices().length = 0; - } else { - body.setAlpha(sliderBodyBaseAlpha); - border.setAlpha(1); - if (hint != null) { - hint.setAlpha(hintAlpha); - cache.drawLinePath - .reset(path, hintWidth) - .getTriangles(cache.triangleBuilder) - .getVertex(hint.getVertices()); - } - cache.drawLinePath - .reset(path, bodyWidth) - .getTriangles(cache.triangleBuilder) - .getVertex(body.getVertices()); - cache.drawLinePath - .reset(path, borderWidth) - .getTriangles(cache.triangleBuilder) - .getVertex(border.getVertices()); - } - - - if (!emptyOnStart) { - startLength = 0; - endLength = path.getMeasurer().maxLength(); - } - - scene.attachChild(border, 0); - scene.attachChild(body, 0); - if (hint != null) { - scene.attachChild(hint, 0); - } - } - - @Override - public void removeFromScene(Scene scene) { - if (hint != null) { - hint.detachSelf(); - SpriteCache.trianglePackCache.save(hint); - hint = null; - } - if (body != null) { - body.detachSelf(); - SpriteCache.trianglePackCache.save(body); - body = null; - } - if (border != null) { - border.detachSelf(); - SpriteCache.trianglePackCache.save(border); - border = null; - } - } - - private static class BuildCache { - public LinePath path = new LinePath(); - public TriangleBuilder triangleBuilder = new TriangleBuilder(); - public DrawLinePath drawLinePath = new DrawLinePath(); - } - - public static class SliderProperty { - - public Color4 color = Color4.White.copyNew(); - - public float width; - - public TrianglePack pack; - - } + private static final ThreadLocal localCache = new ThreadLocal() { + @Override + public BuildCache get() { + BuildCache cache = super.get(); + if (cache == null) { + cache = new BuildCache(); + set(cache); + } + return cache; + } + }; + private float sliderBodyBaseAlpha = 0.7f; + private float hintAlpha = 0.3f; + private TrianglePack body = null, border = null, hint = null; + private RGBColor bodyColor = new RGBColor(), borderColor = new RGBColor(), hintColor = new RGBColor(); + private float bodyWidth, borderWidth, hintWidth; + private float startLength = 0, endLength = 0; + private boolean enableHint = false; + + public SliderBody2D(LinePath path) { + super(path); + } + + public boolean isEnableHint() { + return enableHint; + } + + public void setEnableHint(boolean enableHint) { + this.enableHint = enableHint; + } + + public float getSliderBodyBaseAlpha() { + return sliderBodyBaseAlpha; + } + + @Override + public void setSliderBodyBaseAlpha(float sliderBodyBaseAlpha) { + this.sliderBodyBaseAlpha = sliderBodyBaseAlpha; + } + + public void setHintAlpha(float hintAlpha) { + this.hintAlpha = hintAlpha; + } + + public void setHintColor(float r, float g, float b) { + this.hintColor.set(r, g, b); + if (hint != null) { + hint.setColor(r, g, b); + } + } + + public void setHintWidth(float hintWidth) { + this.hintWidth = hintWidth; + } + + /** + * Gradually fades the slider's body, border, and hint (if any) out over the specified duration. + *

+ * Used if Hidden mod is active. + *

+ * + * @param duration The duration of the fade-out animation. + */ + public void fadeOut(float duration) { + if (body.getAlpha() > 0) { + body.registerEntityModifier(new AlphaModifier(duration, body.getAlpha(), 0)); + } + if (border.getAlpha() > 0) { + border.registerEntityModifier(new AlphaModifier(duration, border.getAlpha(), 0)); + } + if (hint != null && hint.getAlpha() > 0) { + hint.registerEntityModifier(new AlphaModifier(duration, hint.getAlpha(), 0)); + } + } + + @Override + public void onUpdate() { + BuildCache cache = localCache.get(); + LinePath sub = path.cutPath(startLength, endLength).fitToLinePath(cache.path); + float alpha = endLength / path.getMeasurer().maxLength(); + body.setAlpha(alpha * sliderBodyBaseAlpha); + border.setAlpha(alpha); + + if (hint != null) { + hint.setAlpha(alpha * hintAlpha); + cache.drawLinePath + .reset(sub, hintWidth) + .getTriangles(cache.triangleBuilder) + .getVertex(hint.getVertices()); + } + + cache.drawLinePath + .reset(sub, bodyWidth) + .getTriangles(cache.triangleBuilder) + .getVertex(body.getVertices()); + cache.drawLinePath + .reset(sub, borderWidth) + .getTriangles(cache.triangleBuilder) + .getVertex(border.getVertices()); + } + + @Override + public void setBodyWidth(float width) { + bodyWidth = width; + } + + @Override + public void setBorderWidth(float width) { + borderWidth = width; + } + + @Override + public void setBodyColor(float r, float g, float b) { + bodyColor.set(r, g, b); + if (body != null) { + body.setColor(r, g, b); + } + } + + @Override + public void setBorderColor(float r, float g, float b) { + borderColor.set(r, g, b); + if (border != null) { + border.setColor(r, g, b); + } + } + + @Override + public void setStartLength(float length) { + startLength = length; + } + + @Override + public void setEndLength(float length) { + endLength = length; + } + + @Override + public void applyToScene(Scene scene, boolean emptyOnStart) { + BuildCache cache = localCache.get(); + body = SpriteCache.trianglePackCache.get(); + border = SpriteCache.trianglePackCache.get(); + + + if (enableHint) { + hint = SpriteCache.trianglePackCache.get(); + hint.setDepthTest(true); + hint.setClearDepthOnStart(true); + hint.setColor(hintColor.r(), hintColor.g(), hintColor.b()); + } + + body.setDepthTest(true); + body.setClearDepthOnStart(!enableHint); + body.setColor(bodyColor.r(), bodyColor.g(), bodyColor.b()); + + border.setDepthTest(true); + border.setClearDepthOnStart(false); + border.setColor(borderColor.r(), borderColor.g(), borderColor.b()); + + if (emptyOnStart) { + body.setAlpha(0); + border.setAlpha(0); + if (hint != null) { + hint.setAlpha(0); + hint.getVertices().length = 0; + } + body.getVertices().length = 0; + border.getVertices().length = 0; + } else { + body.setAlpha(sliderBodyBaseAlpha); + border.setAlpha(1); + if (hint != null) { + hint.setAlpha(hintAlpha); + cache.drawLinePath + .reset(path, hintWidth) + .getTriangles(cache.triangleBuilder) + .getVertex(hint.getVertices()); + } + cache.drawLinePath + .reset(path, bodyWidth) + .getTriangles(cache.triangleBuilder) + .getVertex(body.getVertices()); + cache.drawLinePath + .reset(path, borderWidth) + .getTriangles(cache.triangleBuilder) + .getVertex(border.getVertices()); + } + + + if (!emptyOnStart) { + startLength = 0; + endLength = path.getMeasurer().maxLength(); + } + + scene.attachChild(border, 0); + scene.attachChild(body, 0); + if (hint != null) { + scene.attachChild(hint, 0); + } + } + + @Override + public void removeFromScene(Scene scene) { + if (hint != null) { + hint.detachSelf(); + SpriteCache.trianglePackCache.save(hint); + hint = null; + } + if (body != null) { + body.detachSelf(); + SpriteCache.trianglePackCache.save(body); + body = null; + } + if (border != null) { + border.detachSelf(); + SpriteCache.trianglePackCache.save(border); + border = null; + } + } + + private static class BuildCache { + public LinePath path = new LinePath(); + public TriangleBuilder triangleBuilder = new TriangleBuilder(); + public DrawLinePath drawLinePath = new DrawLinePath(); + } + + public static class SliderProperty { + + public Color4 color = Color4.White.copyNew(); + + public float width; + + public TrianglePack pack; + + } } diff --git a/src/com/edlplan/osu/support/slider/SliderBody3D.java b/src/com/edlplan/osu/support/slider/SliderBody3D.java index ebd2d287..8aecef7f 100644 --- a/src/com/edlplan/osu/support/slider/SliderBody3D.java +++ b/src/com/edlplan/osu/support/slider/SliderBody3D.java @@ -9,163 +9,163 @@ public class SliderBody3D extends AbstractSliderBody { - private static float zOff = 0.001f; + private static float zOff = 0.001f; - private static float zStart = -1 + zOff; + private static float zStart = -1 + zOff; - private static float zEnd = 1; + private static float zEnd = 1; - private Triangle3DPack body = null, border = null, bodyMask = null, borderMask = null; + private Triangle3DPack body = null, border = null, bodyMask = null, borderMask = null; - private RGBColor bodyColor = new RGBColor(), borderColor = new RGBColor(); + private RGBColor bodyColor = new RGBColor(), borderColor = new RGBColor(); - private float bodyWidth, borderWidth; - - private float startLength = 0, endLength = 0; + private float bodyWidth, borderWidth; + + private float startLength = 0, endLength = 0; - public SliderBody3D(LinePath path) { - super(path); - } + public SliderBody3D(LinePath path) { + super(path); + } - @Override - public void onUpdate() { - LinePath sub = path.cutPath(startLength, endLength).fitToLinePath(); - - float zBody = -bodyWidth / borderWidth + zOff; - - float alpha = endLength / path.getMeasurer().maxLength(); - - /*bodyMask.setVertices( - (new Draw3DLinePath(sub, bodyWidth, zEnd - zOff, zBody - zOff)) - .getTriangles() - .getVertex());*/ - - body.setVertices( - (new Draw3DLinePath(sub, bodyWidth, 1, 1)) - .getTriangles() - .getVertex()); - - body.setAlpha(0.7f * alpha); - - /*borderMask.setVertices( - (new Draw3DLinePath(sub, borderWidth, zEnd - zOff, zStart - zOff)) - .getTriangles() - .getVertex());*/ - - border.setVertices( - (new Draw3DLinePath(sub, borderWidth, -1, -1)) - .getTriangles() - .getVertex()); - - border.setAlpha(alpha); - } - - @Override - public void setBodyWidth(float width) { - bodyWidth = width; - } - - @Override - public void setBorderWidth(float width) { - borderWidth = width; - } - - @Override - public void setBodyColor(float r, float g, float b) { - bodyColor.set(r, g, b); - if (body != null) { - body.setColor(r, g, b); - } - } - - @Override - public void setBorderColor(float r, float g, float b) { - borderColor.set(r, g, b); - if (border != null) { - border.setColor(r, g, b); - } - } - - @Override - public void setStartLength(float length) { - startLength = length; - } - - @Override - public void setEndLength(float length) { - endLength = length; - } - - @Override - public void applyToScene(Scene scene, boolean emptyOnStart) { - - if (!emptyOnStart) { - startLength = 0; - endLength = path.getMeasurer().maxLength(); - } - - float zBody = -bodyWidth / borderWidth + zOff; - - /*bodyMask = new Triangle3DPack(0, 0, - emptyOnStart ? - new float[0] : - (new Draw3DLinePath(path, bodyWidth, zEnd - zOff, zBody - zOff)) - .getTriangles() - .getVertex()); - bodyMask.setClearDepthOnStart(true);*/ - - body = new Triangle3DPack(0, 0, - emptyOnStart ? - new float[0] : - (new Draw3DLinePath(path, bodyWidth, zEnd, zBody)) - .getTriangles() - .getVertex() - ); - - body.setClearDepthOnStart(true); - - /*borderMask = new Triangle3DPack(0, 0, - emptyOnStart ? - new float[0] : - (new Draw3DLinePath(path, borderWidth, zEnd - zOff, zStart - zOff)) - .getTriangles() - .getVertex() - );*/ - - border = new Triangle3DPack(0, 0, - emptyOnStart ? - new float[0] : - (new Draw3DLinePath(path, borderWidth, zEnd, zStart)) - .getTriangles() - .getVertex() - ); - - //bodyMask.setAlpha(0); - //borderMask.setAlpha(0); - body.setColor(bodyColor.r(), bodyColor.g(), bodyColor.b()); - border.setColor(borderColor.r(), borderColor.g(), borderColor.b()); - - - scene.attachChild(border, 0); - //scene.attachChild(borderMask, 0); - scene.attachChild(body, 0); - //scene.attachChild(bodyMask, 0); - - } - - @Override - public void removeFromScene(Scene scene) { - if (body != null) { - body.detachSelf(); - } - if (border != null) { - border.detachSelf(); - } - if (bodyMask != null) { - bodyMask.detachSelf(); - } - if (borderMask != null) { - borderMask.detachSelf(); - } - } + @Override + public void onUpdate() { + LinePath sub = path.cutPath(startLength, endLength).fitToLinePath(); + + float zBody = -bodyWidth / borderWidth + zOff; + + float alpha = endLength / path.getMeasurer().maxLength(); + + /*bodyMask.setVertices( + (new Draw3DLinePath(sub, bodyWidth, zEnd - zOff, zBody - zOff)) + .getTriangles() + .getVertex());*/ + + body.setVertices( + (new Draw3DLinePath(sub, bodyWidth, 1, 1)) + .getTriangles() + .getVertex()); + + body.setAlpha(0.7f * alpha); + + /*borderMask.setVertices( + (new Draw3DLinePath(sub, borderWidth, zEnd - zOff, zStart - zOff)) + .getTriangles() + .getVertex());*/ + + border.setVertices( + (new Draw3DLinePath(sub, borderWidth, -1, -1)) + .getTriangles() + .getVertex()); + + border.setAlpha(alpha); + } + + @Override + public void setBodyWidth(float width) { + bodyWidth = width; + } + + @Override + public void setBorderWidth(float width) { + borderWidth = width; + } + + @Override + public void setBodyColor(float r, float g, float b) { + bodyColor.set(r, g, b); + if (body != null) { + body.setColor(r, g, b); + } + } + + @Override + public void setBorderColor(float r, float g, float b) { + borderColor.set(r, g, b); + if (border != null) { + border.setColor(r, g, b); + } + } + + @Override + public void setStartLength(float length) { + startLength = length; + } + + @Override + public void setEndLength(float length) { + endLength = length; + } + + @Override + public void applyToScene(Scene scene, boolean emptyOnStart) { + + if (!emptyOnStart) { + startLength = 0; + endLength = path.getMeasurer().maxLength(); + } + + float zBody = -bodyWidth / borderWidth + zOff; + + /*bodyMask = new Triangle3DPack(0, 0, + emptyOnStart ? + new float[0] : + (new Draw3DLinePath(path, bodyWidth, zEnd - zOff, zBody - zOff)) + .getTriangles() + .getVertex()); + bodyMask.setClearDepthOnStart(true);*/ + + body = new Triangle3DPack(0, 0, + emptyOnStart ? + new float[0] : + (new Draw3DLinePath(path, bodyWidth, zEnd, zBody)) + .getTriangles() + .getVertex() + ); + + body.setClearDepthOnStart(true); + + /*borderMask = new Triangle3DPack(0, 0, + emptyOnStart ? + new float[0] : + (new Draw3DLinePath(path, borderWidth, zEnd - zOff, zStart - zOff)) + .getTriangles() + .getVertex() + );*/ + + border = new Triangle3DPack(0, 0, + emptyOnStart ? + new float[0] : + (new Draw3DLinePath(path, borderWidth, zEnd, zStart)) + .getTriangles() + .getVertex() + ); + + //bodyMask.setAlpha(0); + //borderMask.setAlpha(0); + body.setColor(bodyColor.r(), bodyColor.g(), bodyColor.b()); + border.setColor(borderColor.r(), borderColor.g(), borderColor.b()); + + + scene.attachChild(border, 0); + //scene.attachChild(borderMask, 0); + scene.attachChild(body, 0); + //scene.attachChild(bodyMask, 0); + + } + + @Override + public void removeFromScene(Scene scene) { + if (body != null) { + body.detachSelf(); + } + if (border != null) { + border.detachSelf(); + } + if (bodyMask != null) { + bodyMask.detachSelf(); + } + if (borderMask != null) { + borderMask.detachSelf(); + } + } } diff --git a/src/com/edlplan/osu/support/timing/TimingPoint.java b/src/com/edlplan/osu/support/timing/TimingPoint.java index 7daa0b9f..93846d84 100644 --- a/src/com/edlplan/osu/support/timing/TimingPoint.java +++ b/src/com/edlplan/osu/support/timing/TimingPoint.java @@ -6,114 +6,114 @@ public class TimingPoint extends ControlPoint { - /** - * 在lazer原代码里这里是一个enum TimeSignatures, - * 定义了一拍里有几小节(大概是这么叫的。。。滚去学乐理了) - */ - private int meter; + /** + * 在lazer原代码里这里是一个enum TimeSignatures, + * 定义了一拍里有几小节(大概是这么叫的。。。滚去学乐理了) + */ + private int meter; - /** - * 定义音效类型,赞时放置,之后应该用enum代替 - */ - private int sampleType; + /** + * 定义音效类型,赞时放置,之后应该用enum代替 + */ + private int sampleType; - private SampleSet sampleSet = SampleSet.None; + private SampleSet sampleSet = SampleSet.None; - private int volume = 100; + private int volume = 100; - /** - * 在lazer里叫timingChange,一般mapper以Editor里的线的颜色区分 - */ - private boolean inherited = true; + /** + * 在lazer里叫timingChange,一般mapper以Editor里的线的颜色区分 + */ + private boolean inherited = true; - private boolean kiaiMode = false; + private boolean kiaiMode = false; - private boolean omitFirstBarSignature = false; + private boolean omitFirstBarSignature = false; - private double beatLength; + private double beatLength; - private double speedMultiplier; + private double speedMultiplier; - public double getSpeedMultiplier() { - return speedMultiplier; - } + public double getSpeedMultiplier() { + return speedMultiplier; + } - public double getBeatLength() { - return beatLength; - } + public double getBeatLength() { + return beatLength; + } - public strictfp void setBeatLength(double beatLength) { - this.beatLength = beatLength; - speedMultiplier = (beatLength < 0 ? (100.0 / -beatLength) : 1); - } + public strictfp void setBeatLength(double beatLength) { + this.beatLength = beatLength; + speedMultiplier = (beatLength < 0 ? (100.0 / -beatLength) : 1); + } - public boolean isOmitFirstBarSignature() { - return omitFirstBarSignature; - } + public boolean isOmitFirstBarSignature() { + return omitFirstBarSignature; + } - public void setOmitFirstBarSignature(boolean omitFirstBarSignature) { - this.omitFirstBarSignature = omitFirstBarSignature; - } + public void setOmitFirstBarSignature(boolean omitFirstBarSignature) { + this.omitFirstBarSignature = omitFirstBarSignature; + } - public SampleSet getSampleSet() { - return sampleSet; - } + public SampleSet getSampleSet() { + return sampleSet; + } - public void setSampleSet(SampleSet sampleSet) { - this.sampleSet = sampleSet; - } + public void setSampleSet(SampleSet sampleSet) { + this.sampleSet = sampleSet; + } - public int getMeter() { - return meter; - } + public int getMeter() { + return meter; + } - public void setMeter(int meter) { - this.meter = meter; - } + public void setMeter(int meter) { + this.meter = meter; + } - public int getSampleType() { - return sampleType; - } + public int getSampleType() { + return sampleType; + } - public void setSampleType(int sampleType) { - this.sampleType = sampleType; - } + public void setSampleType(int sampleType) { + this.sampleType = sampleType; + } - public int getVolume() { - return volume; - } + public int getVolume() { + return volume; + } - public void setVolume(int volume) { - this.volume = volume; - } + public void setVolume(int volume) { + this.volume = volume; + } - public boolean isInherited() { - return inherited; - } + public boolean isInherited() { + return inherited; + } - public void setInherited(boolean inherited) { - this.inherited = inherited; - } + public void setInherited(boolean inherited) { + this.inherited = inherited; + } - public boolean isKiaiMode() { - return kiaiMode; - } + public boolean isKiaiMode() { + return kiaiMode; + } - public void setKiaiMode(boolean kiaiMode) { - this.kiaiMode = kiaiMode; - } + public void setKiaiMode(boolean kiaiMode) { + this.kiaiMode = kiaiMode; + } - @Override - public String toString() { + @Override + public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append(getTime()).append(","); - sb.append(getBeatLength()).append(","); - sb.append(getMeter()).append(","); - sb.append(getSampleType()).append(","); - sb.append(getSampleSet()).append(","); - sb.append(U.toVString(isInherited())).append(","); - sb.append(((isKiaiMode()) ? 1 : 0) + ((isOmitFirstBarSignature()) ? 8 : 0)); - return sb.toString(); - } + StringBuilder sb = new StringBuilder(); + sb.append(getTime()).append(","); + sb.append(getBeatLength()).append(","); + sb.append(getMeter()).append(","); + sb.append(getSampleType()).append(","); + sb.append(getSampleSet()).append(","); + sb.append(U.toVString(isInherited())).append(","); + sb.append(((isKiaiMode()) ? 1 : 0) + ((isOmitFirstBarSignature()) ? 8 : 0)); + return sb.toString(); + } } diff --git a/src/com/edlplan/osu/support/timing/TimingPoints.java b/src/com/edlplan/osu/support/timing/TimingPoints.java index dc6d44cf..55a7e4fc 100644 --- a/src/com/edlplan/osu/support/timing/TimingPoints.java +++ b/src/com/edlplan/osu/support/timing/TimingPoints.java @@ -7,47 +7,47 @@ import java.util.List; public class TimingPoints { - private ArrayList timings; - - public TimingPoints() { - timings = new ArrayList(); - } - - public static TimingPoints parse(List strings) { - TimingPoints timingPoints = new TimingPoints(); - for (String ll : strings) { - String[] l = ll.split(","); - TimingPoint t = new TimingPoint(); - t.setTime((int) Math.round(Double.parseDouble(l[0]))); - t.setBeatLength(Double.parseDouble(l[1])); - t.setMeter(l.length > 2 ? Integer.parseInt(l[2]) : 4); - t.setSampleType(l.length > 3 ? Integer.parseInt(l[3]) : 1); - t.setSampleSet(l.length > 4 ? SampleSet.parse(l[4]) : SampleSet.None); - t.setVolume(l.length > 5 ? Integer.parseInt(l[5]) : 100); - t.setInherited(t.getBeatLength() < 0); - int eff = l.length > 7 ? Integer.parseInt(l[7]) : 0; - t.setKiaiMode((eff & 1) > 0); - t.setOmitFirstBarSignature((eff & 8) > 0); - timingPoints.addTimingPoint(t); - } - return timingPoints; - } - - public void addTimingPoint(TimingPoint t) { - timings.add(t); - } - - public ArrayList getTimingPointList() { - return timings; - } - - @Override - public String toString() { - - StringBuilder sb = new StringBuilder(); - for (TimingPoint t : timings) { - sb.append(t.toString()).append(U.NEXT_LINE); - } - return sb.toString(); - } + private ArrayList timings; + + public TimingPoints() { + timings = new ArrayList(); + } + + public static TimingPoints parse(List strings) { + TimingPoints timingPoints = new TimingPoints(); + for (String ll : strings) { + String[] l = ll.split(","); + TimingPoint t = new TimingPoint(); + t.setTime((int) Math.round(Double.parseDouble(l[0]))); + t.setBeatLength(Double.parseDouble(l[1])); + t.setMeter(l.length > 2 ? Integer.parseInt(l[2]) : 4); + t.setSampleType(l.length > 3 ? Integer.parseInt(l[3]) : 1); + t.setSampleSet(l.length > 4 ? SampleSet.parse(l[4]) : SampleSet.None); + t.setVolume(l.length > 5 ? Integer.parseInt(l[5]) : 100); + t.setInherited(t.getBeatLength() < 0); + int eff = l.length > 7 ? Integer.parseInt(l[7]) : 0; + t.setKiaiMode((eff & 1) > 0); + t.setOmitFirstBarSignature((eff & 8) > 0); + timingPoints.addTimingPoint(t); + } + return timingPoints; + } + + public void addTimingPoint(TimingPoint t) { + timings.add(t); + } + + public ArrayList getTimingPointList() { + return timings; + } + + @Override + public String toString() { + + StringBuilder sb = new StringBuilder(); + for (TimingPoint t : timings) { + sb.append(t.toString()).append(U.NEXT_LINE); + } + return sb.toString(); + } } diff --git a/src/com/edlplan/osu/support/timing/controlpoint/ControlPoint.java b/src/com/edlplan/osu/support/timing/controlpoint/ControlPoint.java index 0e270453..ef08c91e 100644 --- a/src/com/edlplan/osu/support/timing/controlpoint/ControlPoint.java +++ b/src/com/edlplan/osu/support/timing/controlpoint/ControlPoint.java @@ -1,24 +1,24 @@ package com.edlplan.osu.support.timing.controlpoint; public class ControlPoint { - private int time; + private int time; - private boolean autoGenerated; + private boolean autoGenerated; - public int getTime() { - return time; - } + public int getTime() { + return time; + } - public void setTime(int time) { - this.time = time; - } + public void setTime(int time) { + this.time = time; + } - public boolean isAutoGenerated() { - return autoGenerated; - } + public boolean isAutoGenerated() { + return autoGenerated; + } - public void setAutoGenerated(boolean autoGenerated) { - this.autoGenerated = autoGenerated; - } + public void setAutoGenerated(boolean autoGenerated) { + this.autoGenerated = autoGenerated; + } } diff --git a/src/com/edlplan/osu/support/timing/controlpoint/ControlPoints.java b/src/com/edlplan/osu/support/timing/controlpoint/ControlPoints.java index b4bacff5..6f9590cd 100644 --- a/src/com/edlplan/osu/support/timing/controlpoint/ControlPoints.java +++ b/src/com/edlplan/osu/support/timing/controlpoint/ControlPoints.java @@ -8,189 +8,189 @@ import java.util.List; public class ControlPoints { - private ArrayList timingPoints = new ArrayList<>(); - - private ArrayList difficultyPoints = new ArrayList<>(); - - private ArrayList effectPoints = new ArrayList<>(); - - private ArrayList samplePoints = new ArrayList<>(); - - public ControlPoints() { - - } - - public void load(TimingPoints points) { - ArrayList res = points.getTimingPointList(); - TimingControlPoint preTp; - DifficultyControlPoint preDcp; - EffectControlPoint preEcp; - SampleControlPoint preScp; - if (res.size() < 1) { - throw new IllegalArgumentException("a beatmap must has at least 1 timing point"); - } - - // Get first uninherited timing point - int tmpIndex = -1; - for (int i = 0; i < res.size(); i++) { - if (!res.get(i).isInherited()) { - tmpIndex = i; - break; - } - } - if (tmpIndex == -1) { - throw new IllegalArgumentException("No uninherited timing point found"); - } - TimingPoint tmp = res.get(tmpIndex); - preTp = new TimingControlPoint(); - preTp.setTime(tmp.getTime()); - preTp.setBeatLength(tmp.getBeatLength()); - preTp.setMeter(tmp.getMeter()); - timingPoints.add(preTp); - - final TimingPoint firstTp = res.get(0); - preDcp = new DifficultyControlPoint(); - preDcp.setTime(firstTp.getTime()); - preDcp.setSpeedMultiplier(firstTp.getSpeedMultiplier()); - difficultyPoints.add(preDcp); - - preScp = new SampleControlPoint(); - preScp.setTime(firstTp.getTime()); - samplePoints.add(preScp); - - preEcp = new EffectControlPoint(); - preEcp.setTime(firstTp.getTime()); - preEcp.setKiaiModeOn(firstTp.isKiaiMode()); - preEcp.setOmitFirstBarLine(firstTp.isOmitFirstBarSignature()); - effectPoints.add(preEcp); - - for (int i = 0; i < res.size(); i++) { - tmp = res.get(i); - if (!tmp.isInherited() && i != tmpIndex) { - preTp = new TimingControlPoint(); - preTp.setTime(tmp.getTime()); - preTp.setBeatLength(tmp.getBeatLength()); - preTp.setMeter(tmp.getMeter()); - timingPoints.add(preTp); - } - - if (preDcp.getSpeedMultiplier() != tmp.getSpeedMultiplier()) { - if (preDcp.getTime() == tmp.getTime()) { - //当控制线重合的时候,只保留绿线 - if (tmp.isInherited()) { - difficultyPoints.remove(preDcp); - preDcp = new DifficultyControlPoint(); - preDcp.setTime(tmp.getTime()); - preDcp.setSpeedMultiplier(tmp.getSpeedMultiplier()); - preDcp.setAutoGenerated(tmp.isInherited()); - difficultyPoints.add(preDcp); - } - } else { - preDcp = new DifficultyControlPoint(); - preDcp.setTime(tmp.getTime()); - preDcp.setSpeedMultiplier(tmp.getSpeedMultiplier()); - preDcp.setAutoGenerated(tmp.isInherited()); - - difficultyPoints.add(preDcp); - } - - //handleDifficultyControlPoint(preDcp); - } - - //添加Sample相关控制点,暂时跳过 - - if (tmp.isKiaiMode() != preEcp.isKiaiModeOn() || tmp.isOmitFirstBarSignature() != preEcp.isOmitFirstBarLine()) { - preEcp = new EffectControlPoint(); - preEcp.setTime(tmp.getTime()); - preEcp.setKiaiModeOn(tmp.isKiaiMode()); - preEcp.setOmitFirstBarLine(tmp.isOmitFirstBarSignature()); - effectPoints.add(preEcp); - } - } - Collections.sort(timingPoints, (a, b) -> Integer.compare(a.getTime(), b.getTime())); - Collections.sort(difficultyPoints, (a, b) -> Integer.compare(a.getTime(), b.getTime())); - Collections.sort(effectPoints, (a, b) -> Integer.compare(a.getTime(), b.getTime())); - - /*Log.v("ControlPoints", "t: " + timingPoints.size()); - Log.v("ControlPoints", "d: " + difficultyPoints.size()); - Log.v("ControlPoints", "s: " + samplePoints.size()); - Log.v("ControlPoints", "e: " + effectPoints.size());*/ - } - - private void handleDifficultyControlPoint(DifficultyControlPoint newPoint) { - DifficultyControlPoint existing = getDifficultyPointAt(newPoint.getTime()); - - if (existing.getTime() == newPoint.getTime()) { - // autogenerated points should not replace non-autogenerated. - // this allows for incorrectly ordered timing points to still be correctly handled. - if (newPoint.isAutoGenerated() && !existing.isAutoGenerated()) - return; - - difficultyPoints.remove(existing); - } - - difficultyPoints.add(newPoint); - Collections.sort(difficultyPoints, (a, b) -> Double.compare(a.getTime(), b.getTime())); - } - - public TimingControlPoint getTimingPointAt(double time) { - if (timingPoints.size() == 0) { - return null; - } - return binarySearch(timingPoints, time, timingPoints.get(0)); - } - - public EffectControlPoint getEffectPointAt(double time) { - if (effectPoints.size() == 0) { - return null; - } - return binarySearch(effectPoints, time, effectPoints.get(0)); - } - - public SampleControlPoint getSamplePointAt(double time) { - if (samplePoints.size() == 0) { - return null; - } - return binarySearch(samplePoints, time, samplePoints.get(0)); - } - - public DifficultyControlPoint getDifficultyPointAt(double time) { - if (difficultyPoints.size() == 0) { - return null; - } - DifficultyControlPoint difficultyControlPoint = binarySearch(difficultyPoints, time, difficultyPoints.get(0)); - if (difficultyControlPoint == null) { - return new DifficultyControlPoint(); - } else { - return difficultyControlPoint; - } - } - - private T binarySearch(List list, double time, T prePoint) { - - if (list.size() == 0) - return null; - - if (time < list.get(0).getTime()) - return prePoint; - - if (time >= list.get(list.size() - 1).getTime()) - return list.get(list.size() - 1); - - int l = 0; - int r = list.size() - 2; - - while (l <= r) { - int pivot = l + ((r - l) >> 1); - - if (list.get(pivot).getTime() < time) - l = pivot + 1; - else if (list.get(pivot).getTime() > time) - r = pivot - 1; - else - return list.get(pivot); - } - - return list.get(l - 1); - } + private ArrayList timingPoints = new ArrayList<>(); + + private ArrayList difficultyPoints = new ArrayList<>(); + + private ArrayList effectPoints = new ArrayList<>(); + + private ArrayList samplePoints = new ArrayList<>(); + + public ControlPoints() { + + } + + public void load(TimingPoints points) { + ArrayList res = points.getTimingPointList(); + TimingControlPoint preTp; + DifficultyControlPoint preDcp; + EffectControlPoint preEcp; + SampleControlPoint preScp; + if (res.size() < 1) { + throw new IllegalArgumentException("a beatmap must has at least 1 timing point"); + } + + // Get first uninherited timing point + int tmpIndex = -1; + for (int i = 0; i < res.size(); i++) { + if (!res.get(i).isInherited()) { + tmpIndex = i; + break; + } + } + if (tmpIndex == -1) { + throw new IllegalArgumentException("No uninherited timing point found"); + } + TimingPoint tmp = res.get(tmpIndex); + preTp = new TimingControlPoint(); + preTp.setTime(tmp.getTime()); + preTp.setBeatLength(tmp.getBeatLength()); + preTp.setMeter(tmp.getMeter()); + timingPoints.add(preTp); + + final TimingPoint firstTp = res.get(0); + preDcp = new DifficultyControlPoint(); + preDcp.setTime(firstTp.getTime()); + preDcp.setSpeedMultiplier(firstTp.getSpeedMultiplier()); + difficultyPoints.add(preDcp); + + preScp = new SampleControlPoint(); + preScp.setTime(firstTp.getTime()); + samplePoints.add(preScp); + + preEcp = new EffectControlPoint(); + preEcp.setTime(firstTp.getTime()); + preEcp.setKiaiModeOn(firstTp.isKiaiMode()); + preEcp.setOmitFirstBarLine(firstTp.isOmitFirstBarSignature()); + effectPoints.add(preEcp); + + for (int i = 0; i < res.size(); i++) { + tmp = res.get(i); + if (!tmp.isInherited() && i != tmpIndex) { + preTp = new TimingControlPoint(); + preTp.setTime(tmp.getTime()); + preTp.setBeatLength(tmp.getBeatLength()); + preTp.setMeter(tmp.getMeter()); + timingPoints.add(preTp); + } + + if (preDcp.getSpeedMultiplier() != tmp.getSpeedMultiplier()) { + if (preDcp.getTime() == tmp.getTime()) { + //当控制线重合的时候,只保留绿线 + if (tmp.isInherited()) { + difficultyPoints.remove(preDcp); + preDcp = new DifficultyControlPoint(); + preDcp.setTime(tmp.getTime()); + preDcp.setSpeedMultiplier(tmp.getSpeedMultiplier()); + preDcp.setAutoGenerated(tmp.isInherited()); + difficultyPoints.add(preDcp); + } + } else { + preDcp = new DifficultyControlPoint(); + preDcp.setTime(tmp.getTime()); + preDcp.setSpeedMultiplier(tmp.getSpeedMultiplier()); + preDcp.setAutoGenerated(tmp.isInherited()); + + difficultyPoints.add(preDcp); + } + + //handleDifficultyControlPoint(preDcp); + } + + //添加Sample相关控制点,暂时跳过 + + if (tmp.isKiaiMode() != preEcp.isKiaiModeOn() || tmp.isOmitFirstBarSignature() != preEcp.isOmitFirstBarLine()) { + preEcp = new EffectControlPoint(); + preEcp.setTime(tmp.getTime()); + preEcp.setKiaiModeOn(tmp.isKiaiMode()); + preEcp.setOmitFirstBarLine(tmp.isOmitFirstBarSignature()); + effectPoints.add(preEcp); + } + } + Collections.sort(timingPoints, (a, b) -> Integer.compare(a.getTime(), b.getTime())); + Collections.sort(difficultyPoints, (a, b) -> Integer.compare(a.getTime(), b.getTime())); + Collections.sort(effectPoints, (a, b) -> Integer.compare(a.getTime(), b.getTime())); + + /*Log.v("ControlPoints", "t: " + timingPoints.size()); + Log.v("ControlPoints", "d: " + difficultyPoints.size()); + Log.v("ControlPoints", "s: " + samplePoints.size()); + Log.v("ControlPoints", "e: " + effectPoints.size());*/ + } + + private void handleDifficultyControlPoint(DifficultyControlPoint newPoint) { + DifficultyControlPoint existing = getDifficultyPointAt(newPoint.getTime()); + + if (existing.getTime() == newPoint.getTime()) { + // autogenerated points should not replace non-autogenerated. + // this allows for incorrectly ordered timing points to still be correctly handled. + if (newPoint.isAutoGenerated() && !existing.isAutoGenerated()) + return; + + difficultyPoints.remove(existing); + } + + difficultyPoints.add(newPoint); + Collections.sort(difficultyPoints, (a, b) -> Double.compare(a.getTime(), b.getTime())); + } + + public TimingControlPoint getTimingPointAt(double time) { + if (timingPoints.size() == 0) { + return null; + } + return binarySearch(timingPoints, time, timingPoints.get(0)); + } + + public EffectControlPoint getEffectPointAt(double time) { + if (effectPoints.size() == 0) { + return null; + } + return binarySearch(effectPoints, time, effectPoints.get(0)); + } + + public SampleControlPoint getSamplePointAt(double time) { + if (samplePoints.size() == 0) { + return null; + } + return binarySearch(samplePoints, time, samplePoints.get(0)); + } + + public DifficultyControlPoint getDifficultyPointAt(double time) { + if (difficultyPoints.size() == 0) { + return null; + } + DifficultyControlPoint difficultyControlPoint = binarySearch(difficultyPoints, time, difficultyPoints.get(0)); + if (difficultyControlPoint == null) { + return new DifficultyControlPoint(); + } else { + return difficultyControlPoint; + } + } + + private T binarySearch(List list, double time, T prePoint) { + + if (list.size() == 0) + return null; + + if (time < list.get(0).getTime()) + return prePoint; + + if (time >= list.get(list.size() - 1).getTime()) + return list.get(list.size() - 1); + + int l = 0; + int r = list.size() - 2; + + while (l <= r) { + int pivot = l + ((r - l) >> 1); + + if (list.get(pivot).getTime() < time) + l = pivot + 1; + else if (list.get(pivot).getTime() > time) + r = pivot - 1; + else + return list.get(pivot); + } + + return list.get(l - 1); + } } diff --git a/src/com/edlplan/osu/support/timing/controlpoint/DifficultyControlPoint.java b/src/com/edlplan/osu/support/timing/controlpoint/DifficultyControlPoint.java index b0755074..b5b72a14 100644 --- a/src/com/edlplan/osu/support/timing/controlpoint/DifficultyControlPoint.java +++ b/src/com/edlplan/osu/support/timing/controlpoint/DifficultyControlPoint.java @@ -3,13 +3,13 @@ import com.edlplan.framework.math.FMath; public class DifficultyControlPoint extends ControlPoint { - private double speedMultiplier; + private double speedMultiplier; - public double getSpeedMultiplier() { - return speedMultiplier; - } + public double getSpeedMultiplier() { + return speedMultiplier; + } - public void setSpeedMultiplier(double speedMultiplier) { - this.speedMultiplier = FMath.clamp(speedMultiplier, 0.1, 10); - } + public void setSpeedMultiplier(double speedMultiplier) { + this.speedMultiplier = FMath.clamp(speedMultiplier, 0.1, 10); + } } diff --git a/src/com/edlplan/osu/support/timing/controlpoint/EffectControlPoint.java b/src/com/edlplan/osu/support/timing/controlpoint/EffectControlPoint.java index 71c27c6f..874bebe6 100644 --- a/src/com/edlplan/osu/support/timing/controlpoint/EffectControlPoint.java +++ b/src/com/edlplan/osu/support/timing/controlpoint/EffectControlPoint.java @@ -1,23 +1,23 @@ package com.edlplan.osu.support.timing.controlpoint; public class EffectControlPoint extends ControlPoint { - private boolean kiaiModeOn; + private boolean kiaiModeOn; - private boolean omitFirstBarLine; + private boolean omitFirstBarLine; - public boolean isKiaiModeOn() { - return kiaiModeOn; - } + public boolean isKiaiModeOn() { + return kiaiModeOn; + } - public void setKiaiModeOn(boolean kiaiModeOn) { - this.kiaiModeOn = kiaiModeOn; - } + public void setKiaiModeOn(boolean kiaiModeOn) { + this.kiaiModeOn = kiaiModeOn; + } - public boolean isOmitFirstBarLine() { - return omitFirstBarLine; - } + public boolean isOmitFirstBarLine() { + return omitFirstBarLine; + } - public void setOmitFirstBarLine(boolean omitFirstBarLine) { - this.omitFirstBarLine = omitFirstBarLine; - } + public void setOmitFirstBarLine(boolean omitFirstBarLine) { + this.omitFirstBarLine = omitFirstBarLine; + } } diff --git a/src/com/edlplan/osu/support/timing/controlpoint/TimingControlPoint.java b/src/com/edlplan/osu/support/timing/controlpoint/TimingControlPoint.java index 64e54ce9..55658c86 100644 --- a/src/com/edlplan/osu/support/timing/controlpoint/TimingControlPoint.java +++ b/src/com/edlplan/osu/support/timing/controlpoint/TimingControlPoint.java @@ -3,24 +3,24 @@ import com.edlplan.framework.math.FMath; public class TimingControlPoint extends ControlPoint { - private int meter; + private int meter; - private double beatLength; + private double beatLength; - public int getMeter() { - return meter; - } + public int getMeter() { + return meter; + } - public void setMeter(int meter) { - this.meter = meter; - } + public void setMeter(int meter) { + this.meter = meter; + } - public double getBeatLength() { - return beatLength; - } + public double getBeatLength() { + return beatLength; + } - public void setBeatLength(double beatLength) { - //this.beatLength = FMath.clamp(beatLength, 6, 6000); - this.beatLength = beatLength; - } + public void setBeatLength(double beatLength) { + //this.beatLength = FMath.clamp(beatLength, 6, 6000); + this.beatLength = beatLength; + } } diff --git a/src/com/edlplan/replay/OdrConfig.java b/src/com/edlplan/replay/OdrConfig.java index 21d62532..0745b333 100644 --- a/src/com/edlplan/replay/OdrConfig.java +++ b/src/com/edlplan/replay/OdrConfig.java @@ -8,20 +8,20 @@ public class OdrConfig { - public static File getSongDir() { - return new File(Config.getBeatmapPath()); - } + public static File getSongDir() { + return new File(Config.getBeatmapPath()); + } - public static File getDatabaseDir() { - return new File(Config.getCorePath() + "/databases"); - } + public static File getDatabaseDir() { + return new File(Config.getCorePath() + "/databases"); + } - public static File getScoreDir() { - return new File(Config.getScorePath()); - } + public static File getScoreDir() { + return new File(Config.getScorePath()); + } - public static File getMainDatabase() { - return new File(getDatabaseDir(), "osudroid_test.db"); - } + public static File getMainDatabase() { + return new File(getDatabaseDir(), "osudroid_test.db"); + } } diff --git a/src/com/edlplan/replay/OdrDatabase.java b/src/com/edlplan/replay/OdrDatabase.java index b923cc7e..ba1c5071 100644 --- a/src/com/edlplan/replay/OdrDatabase.java +++ b/src/com/edlplan/replay/OdrDatabase.java @@ -10,148 +10,148 @@ public class OdrDatabase { - private static OdrDatabase odrDatabase; - - private SQLiteDatabase database; - - private Runnable onDatabaseChangedListener; - - public OdrDatabase(File file) { - database = SQLiteDatabase.openDatabase(file.getAbsolutePath(), null, 0); - } - - public OdrDatabase(SQLiteDatabase database) { - this.database = database; - } - - public static OdrDatabase get() { - if (odrDatabase == null) { - odrDatabase = new OdrDatabase(OdrConfig.getMainDatabase()); - } - return odrDatabase; - } - - private static String getString(Cursor cursor, String c) { - return cursor.getString(cursor.getColumnIndexOrThrow(c)); - } - - private static int getInt(Cursor cursor, String c) { - return cursor.getInt(cursor.getColumnIndexOrThrow(c)); - } - - private static long getLong(Cursor cursor, String c) { - return cursor.getLong(cursor.getColumnIndexOrThrow(c)); - } - - private static float getFloat(Cursor cursor, String c) { - return cursor.getFloat(cursor.getColumnIndexOrThrow(c)); - } - - public boolean available() { - return database != null; - } - - public long write(OsuDroidReplay replay) { - ContentValues values = new ContentValues(); - values.put("filename", SongsLibrary.get().toSetLocal(replay.getFileName())); - values.put("playername", replay.getPlayerName()); - if (replay.isAbsoluteReplay()) { - values.put("replayfile", replay.getReplayFile()); - } else { - values.put("replayfile", new File(OdrConfig.getScoreDir(), replay.getReplayFile()).getAbsolutePath()); - } - values.put("mode", replay.getMode()); - values.put("score", replay.getScore()); - values.put("combo", replay.getCombo()); - values.put("mark", replay.getMark()); - values.put("h300k", replay.getH300k()); - values.put("h300", replay.getH300()); - values.put("h100k", replay.getH100k()); - values.put("h100", replay.getH100()); - values.put("h50", replay.getH50()); - values.put("misses", replay.getMisses()); - values.put("accuracy", replay.getAccuracy()); - values.put("time", replay.getTime()); - values.put("perfect", replay.getPerfect()); - - return database.insert("scores", null, values); - } - - public List getReplayById(int id) { - ArrayList replays = new ArrayList<>(); - if (!available()) { - return replays; - } - - Cursor cursor = database.rawQuery("SELECT * FROM scores WHERE id = ?", new String[]{String.valueOf(id)}); - while (cursor.moveToNext()) { - OsuDroidReplay replay = new OsuDroidReplay(); - replay.setFileName(getString(cursor, "filename")); - replay.setPlayerName(getString(cursor, "playername")); - replay.setReplayFile(getString(cursor, "replayfile")); - replay.setMode(getString(cursor, "mode")); - replay.setScore(getInt(cursor, "score")); - replay.setCombo(getInt(cursor, "combo")); - replay.setMark(getString(cursor, "mark")); - replay.setH300k(getInt(cursor, "h300k")); - replay.setH300(getInt(cursor, "h300")); - replay.setH100k(getInt(cursor, "h100k")); - replay.setH100(getInt(cursor, "h100")); - replay.setH50(getInt(cursor, "h50")); - replay.setMisses(getInt(cursor, "misses")); - replay.setAccuracy(getFloat(cursor, "accuracy")); - replay.setTime(getLong(cursor, "time")); - replay.setPerfect(getInt(cursor, "perfect")); - replays.add(replay); - } - - return replays; - } - - public List getReplays() { - ArrayList replays = new ArrayList<>(); - if (!available()) { - return replays; - } - - Cursor cursor = database.rawQuery("SELECT * FROM scores", new String[0]); - while (cursor.moveToNext()) { - OsuDroidReplay replay = new OsuDroidReplay(); - replay.setFileName(getString(cursor, "filename")); - replay.setPlayerName(getString(cursor, "playername")); - replay.setReplayFile(getString(cursor, "replayfile")); - replay.setMode(getString(cursor, "mode")); - replay.setScore(getInt(cursor, "score")); - replay.setCombo(getInt(cursor, "combo")); - replay.setMark(getString(cursor, "mark")); - replay.setH300k(getInt(cursor, "h300k")); - replay.setH300(getInt(cursor, "h300")); - replay.setH100k(getInt(cursor, "h100k")); - replay.setH100(getInt(cursor, "h100")); - replay.setH50(getInt(cursor, "h50")); - replay.setMisses(getInt(cursor, "misses")); - replay.setAccuracy(getFloat(cursor, "accuracy")); - replay.setTime(getLong(cursor, "time")); - replay.setPerfect(getInt(cursor, "perfect")); - replays.add(replay); - } - - return replays; - } - - public int deleteReplay(int id) { - if (!available()) { - return 0; - } - - int result = database.delete("scores", "id = ?", new String[]{String.valueOf(id)}); - if (onDatabaseChangedListener != null) { - onDatabaseChangedListener.run(); - } - return result; - } - - public void setOnDatabaseChangedListener(Runnable listener) { - this.onDatabaseChangedListener = listener; - } + private static OdrDatabase odrDatabase; + + private SQLiteDatabase database; + + private Runnable onDatabaseChangedListener; + + public OdrDatabase(File file) { + database = SQLiteDatabase.openDatabase(file.getAbsolutePath(), null, 0); + } + + public OdrDatabase(SQLiteDatabase database) { + this.database = database; + } + + public static OdrDatabase get() { + if (odrDatabase == null) { + odrDatabase = new OdrDatabase(OdrConfig.getMainDatabase()); + } + return odrDatabase; + } + + private static String getString(Cursor cursor, String c) { + return cursor.getString(cursor.getColumnIndexOrThrow(c)); + } + + private static int getInt(Cursor cursor, String c) { + return cursor.getInt(cursor.getColumnIndexOrThrow(c)); + } + + private static long getLong(Cursor cursor, String c) { + return cursor.getLong(cursor.getColumnIndexOrThrow(c)); + } + + private static float getFloat(Cursor cursor, String c) { + return cursor.getFloat(cursor.getColumnIndexOrThrow(c)); + } + + public boolean available() { + return database != null; + } + + public long write(OsuDroidReplay replay) { + ContentValues values = new ContentValues(); + values.put("filename", SongsLibrary.get().toSetLocal(replay.getFileName())); + values.put("playername", replay.getPlayerName()); + if (replay.isAbsoluteReplay()) { + values.put("replayfile", replay.getReplayFile()); + } else { + values.put("replayfile", new File(OdrConfig.getScoreDir(), replay.getReplayFile()).getAbsolutePath()); + } + values.put("mode", replay.getMode()); + values.put("score", replay.getScore()); + values.put("combo", replay.getCombo()); + values.put("mark", replay.getMark()); + values.put("h300k", replay.getH300k()); + values.put("h300", replay.getH300()); + values.put("h100k", replay.getH100k()); + values.put("h100", replay.getH100()); + values.put("h50", replay.getH50()); + values.put("misses", replay.getMisses()); + values.put("accuracy", replay.getAccuracy()); + values.put("time", replay.getTime()); + values.put("perfect", replay.getPerfect()); + + return database.insert("scores", null, values); + } + + public List getReplayById(int id) { + ArrayList replays = new ArrayList<>(); + if (!available()) { + return replays; + } + + Cursor cursor = database.rawQuery("SELECT * FROM scores WHERE id = ?", new String[]{String.valueOf(id)}); + while (cursor.moveToNext()) { + OsuDroidReplay replay = new OsuDroidReplay(); + replay.setFileName(getString(cursor, "filename")); + replay.setPlayerName(getString(cursor, "playername")); + replay.setReplayFile(getString(cursor, "replayfile")); + replay.setMode(getString(cursor, "mode")); + replay.setScore(getInt(cursor, "score")); + replay.setCombo(getInt(cursor, "combo")); + replay.setMark(getString(cursor, "mark")); + replay.setH300k(getInt(cursor, "h300k")); + replay.setH300(getInt(cursor, "h300")); + replay.setH100k(getInt(cursor, "h100k")); + replay.setH100(getInt(cursor, "h100")); + replay.setH50(getInt(cursor, "h50")); + replay.setMisses(getInt(cursor, "misses")); + replay.setAccuracy(getFloat(cursor, "accuracy")); + replay.setTime(getLong(cursor, "time")); + replay.setPerfect(getInt(cursor, "perfect")); + replays.add(replay); + } + + return replays; + } + + public List getReplays() { + ArrayList replays = new ArrayList<>(); + if (!available()) { + return replays; + } + + Cursor cursor = database.rawQuery("SELECT * FROM scores", new String[0]); + while (cursor.moveToNext()) { + OsuDroidReplay replay = new OsuDroidReplay(); + replay.setFileName(getString(cursor, "filename")); + replay.setPlayerName(getString(cursor, "playername")); + replay.setReplayFile(getString(cursor, "replayfile")); + replay.setMode(getString(cursor, "mode")); + replay.setScore(getInt(cursor, "score")); + replay.setCombo(getInt(cursor, "combo")); + replay.setMark(getString(cursor, "mark")); + replay.setH300k(getInt(cursor, "h300k")); + replay.setH300(getInt(cursor, "h300")); + replay.setH100k(getInt(cursor, "h100k")); + replay.setH100(getInt(cursor, "h100")); + replay.setH50(getInt(cursor, "h50")); + replay.setMisses(getInt(cursor, "misses")); + replay.setAccuracy(getFloat(cursor, "accuracy")); + replay.setTime(getLong(cursor, "time")); + replay.setPerfect(getInt(cursor, "perfect")); + replays.add(replay); + } + + return replays; + } + + public int deleteReplay(int id) { + if (!available()) { + return 0; + } + + int result = database.delete("scores", "id = ?", new String[]{String.valueOf(id)}); + if (onDatabaseChangedListener != null) { + onDatabaseChangedListener.run(); + } + return result; + } + + public void setOnDatabaseChangedListener(Runnable listener) { + this.onDatabaseChangedListener = listener; + } } diff --git a/src/com/edlplan/replay/OsuDroidReplay.java b/src/com/edlplan/replay/OsuDroidReplay.java index 4e53a0b1..a5cf21f4 100644 --- a/src/com/edlplan/replay/OsuDroidReplay.java +++ b/src/com/edlplan/replay/OsuDroidReplay.java @@ -7,225 +7,225 @@ public class OsuDroidReplay { - private String fileName; + private String fileName; - private String playerName; + private String playerName; - private String replayFile; + private String replayFile; - private String mode; + private String mode; - private int score; + private int score; - private int combo; + private int combo; - private String mark; + private String mark; - private int h300k, h300, h100k, h100, h50, misses; + private int h300k, h300, h100k, h100, h50, misses; - private float accuracy; + private float accuracy; - private long time; + private long time; - private int perfect; + private int perfect; - private static String getString(JSONObject cursor, String c) throws JSONException { - return cursor.getString(c); - } + private static String getString(JSONObject cursor, String c) throws JSONException { + return cursor.getString(c); + } - private static int getInt(JSONObject cursor, String c) throws JSONException { - return cursor.getInt(c); - } + private static int getInt(JSONObject cursor, String c) throws JSONException { + return cursor.getInt(c); + } - private static long getLong(JSONObject cursor, String c) throws JSONException { - return cursor.getLong(c); - } + private static long getLong(JSONObject cursor, String c) throws JSONException { + return cursor.getLong(c); + } - private static float getFloat(JSONObject cursor, String c) throws JSONException { - return (float) cursor.getDouble(c); - } + private static float getFloat(JSONObject cursor, String c) throws JSONException { + return (float) cursor.getDouble(c); + } - public static OsuDroidReplay parseJSON(JSONObject cursor) throws JSONException { - OsuDroidReplay replay = new OsuDroidReplay(); - replay.setFileName(getString(cursor, "filename")); - replay.setPlayerName(getString(cursor, "playername")); - replay.setReplayFile(getString(cursor, "replayfile")); - replay.setMode(getString(cursor, "mod")); - replay.setScore(getInt(cursor, "score")); - replay.setCombo(getInt(cursor, "combo")); - replay.setMark(getString(cursor, "mark")); - replay.setH300k(getInt(cursor, "h300k")); - replay.setH300(getInt(cursor, "h300")); - replay.setH100k(getInt(cursor, "h100k")); - replay.setH100(getInt(cursor, "h100")); - replay.setH50(getInt(cursor, "h50")); - replay.setMisses(getInt(cursor, "misses")); - replay.setAccuracy(getFloat(cursor, "accuracy")); - replay.setTime(getLong(cursor, "time")); - replay.setPerfect(getInt(cursor, "perfect")); - return replay; - } + public static OsuDroidReplay parseJSON(JSONObject cursor) throws JSONException { + OsuDroidReplay replay = new OsuDroidReplay(); + replay.setFileName(getString(cursor, "filename")); + replay.setPlayerName(getString(cursor, "playername")); + replay.setReplayFile(getString(cursor, "replayfile")); + replay.setMode(getString(cursor, "mod")); + replay.setScore(getInt(cursor, "score")); + replay.setCombo(getInt(cursor, "combo")); + replay.setMark(getString(cursor, "mark")); + replay.setH300k(getInt(cursor, "h300k")); + replay.setH300(getInt(cursor, "h300")); + replay.setH100k(getInt(cursor, "h100k")); + replay.setH100(getInt(cursor, "h100")); + replay.setH50(getInt(cursor, "h50")); + replay.setMisses(getInt(cursor, "misses")); + replay.setAccuracy(getFloat(cursor, "accuracy")); + replay.setTime(getLong(cursor, "time")); + replay.setPerfect(getInt(cursor, "perfect")); + return replay; + } - public String getFileName() { - return fileName; - } + public String getFileName() { + return fileName; + } - public void setFileName(String fileName) { - this.fileName = fileName; - } + public void setFileName(String fileName) { + this.fileName = fileName; + } - public String getPlayerName() { - return playerName; - } + public String getPlayerName() { + return playerName; + } - public void setPlayerName(String playerName) { - this.playerName = playerName; - } + public void setPlayerName(String playerName) { + this.playerName = playerName; + } - public String getReplayFile() { - return replayFile; - } + public String getReplayFile() { + return replayFile; + } - public void setReplayFile(String replayFile) { - this.replayFile = replayFile; - } + public void setReplayFile(String replayFile) { + this.replayFile = replayFile; + } - public boolean isAbsoluteReplay() { - return getReplayFile().contains("/"); - } + public boolean isAbsoluteReplay() { + return getReplayFile().contains("/"); + } - public String getReplayFileName() { - return isAbsoluteReplay() ? new File(replayFile).getName() : replayFile; - } + public String getReplayFileName() { + return isAbsoluteReplay() ? new File(replayFile).getName() : replayFile; + } - public String getMode() { - return mode; - } + public String getMode() { + return mode; + } - public void setMode(String mode) { - this.mode = mode; - } + public void setMode(String mode) { + this.mode = mode; + } - public int getScore() { - return score; - } - - public void setScore(int score) { - this.score = score; - } - - public int getCombo() { - return combo; - } - - public void setCombo(int combo) { - this.combo = combo; - } - - public String getMark() { - return mark; - } - - public void setMark(String mark) { - this.mark = mark; - } - - public int getH300k() { - return h300k; - } - - public void setH300k(int h300k) { - this.h300k = h300k; - } - - public int getH300() { - return h300; - } - - public void setH300(int h300) { - this.h300 = h300; - } - - public int getH100k() { - return h100k; - } - - public void setH100k(int h100k) { - this.h100k = h100k; - } - - public int getH100() { - return h100; - } - - public void setH100(int h100) { - this.h100 = h100; - } - - public int getH50() { - return h50; - } - - public void setH50(int h50) { - this.h50 = h50; - } - - public int getMisses() { - return misses; - } - - public void setMisses(int misses) { - this.misses = misses; - } - - public float getAccuracy() { - return accuracy; - } - - public void setAccuracy(float accuracy) { - this.accuracy = accuracy; - } - - public long getTime() { - return time; - } - - public void setTime(long time) { - this.time = time; - } - - public int getPerfect() { - return perfect; - } - - public void setPerfect(int perfect) { - this.perfect = perfect; - } - - public JSONObject toJSON() { - OsuDroidReplay replay = this; - JSONObject replayData = new JSONObject(); - try { - replayData.put("filename", replay.getFileName()); - replayData.put("playername", replay.getPlayerName()); - replayData.put("replayfile", replay.getReplayFileName()); - replayData.put("mod", replay.getMode()); - replayData.put("score", replay.getScore()); - replayData.put("combo", replay.getCombo()); - replayData.put("mark", replay.getMark()); - replayData.put("h300k", replay.getH300k()); - replayData.put("h300", replay.getH300()); - replayData.put("h100k", replay.getH100k()); - replayData.put("h100", replay.getH100()); - replayData.put("h50", replay.getH50()); - replayData.put("misses", replay.getMisses()); - replayData.put("accuracy", replay.getAccuracy()); - replayData.put("time", replay.getTime()); - replayData.put("perfect", replay.getPerfect()); - } catch (JSONException e) { - e.printStackTrace(); - } - return replayData; - } + public int getScore() { + return score; + } + + public void setScore(int score) { + this.score = score; + } + + public int getCombo() { + return combo; + } + + public void setCombo(int combo) { + this.combo = combo; + } + + public String getMark() { + return mark; + } + + public void setMark(String mark) { + this.mark = mark; + } + + public int getH300k() { + return h300k; + } + + public void setH300k(int h300k) { + this.h300k = h300k; + } + + public int getH300() { + return h300; + } + + public void setH300(int h300) { + this.h300 = h300; + } + + public int getH100k() { + return h100k; + } + + public void setH100k(int h100k) { + this.h100k = h100k; + } + + public int getH100() { + return h100; + } + + public void setH100(int h100) { + this.h100 = h100; + } + + public int getH50() { + return h50; + } + + public void setH50(int h50) { + this.h50 = h50; + } + + public int getMisses() { + return misses; + } + + public void setMisses(int misses) { + this.misses = misses; + } + + public float getAccuracy() { + return accuracy; + } + + public void setAccuracy(float accuracy) { + this.accuracy = accuracy; + } + + public long getTime() { + return time; + } + + public void setTime(long time) { + this.time = time; + } + + public int getPerfect() { + return perfect; + } + + public void setPerfect(int perfect) { + this.perfect = perfect; + } + + public JSONObject toJSON() { + OsuDroidReplay replay = this; + JSONObject replayData = new JSONObject(); + try { + replayData.put("filename", replay.getFileName()); + replayData.put("playername", replay.getPlayerName()); + replayData.put("replayfile", replay.getReplayFileName()); + replayData.put("mod", replay.getMode()); + replayData.put("score", replay.getScore()); + replayData.put("combo", replay.getCombo()); + replayData.put("mark", replay.getMark()); + replayData.put("h300k", replay.getH300k()); + replayData.put("h300", replay.getH300()); + replayData.put("h100k", replay.getH100k()); + replayData.put("h100", replay.getH100()); + replayData.put("h50", replay.getH50()); + replayData.put("misses", replay.getMisses()); + replayData.put("accuracy", replay.getAccuracy()); + replayData.put("time", replay.getTime()); + replayData.put("perfect", replay.getPerfect()); + } catch (JSONException e) { + e.printStackTrace(); + } + return replayData; + } } diff --git a/src/com/edlplan/replay/OsuDroidReplayPack.java b/src/com/edlplan/replay/OsuDroidReplayPack.java index 37542ddc..8e1848cd 100644 --- a/src/com/edlplan/replay/OsuDroidReplayPack.java +++ b/src/com/edlplan/replay/OsuDroidReplayPack.java @@ -17,67 +17,67 @@ public class OsuDroidReplayPack { - public static void packTo(File file, OsuDroidReplay replay) throws Exception { - if (!file.exists()) { - file.createNewFile(); - } - FileOutputStream outputStream = new FileOutputStream(file); - outputStream.write(pack(replay)); - outputStream.close(); - } + public static void packTo(File file, OsuDroidReplay replay) throws Exception { + if (!file.exists()) { + file.createNewFile(); + } + FileOutputStream outputStream = new FileOutputStream(file); + outputStream.write(pack(replay)); + outputStream.close(); + } - public static byte[] pack(OsuDroidReplay replay) throws Exception { - ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); - ZipOutputStream outputStream = new ZipOutputStream(byteArrayOutputStream); - //try { - outputStream.putNextEntry(new ZipEntry("entry.json")); + public static byte[] pack(OsuDroidReplay replay) throws Exception { + ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); + ZipOutputStream outputStream = new ZipOutputStream(byteArrayOutputStream); + //try { + outputStream.putNextEntry(new ZipEntry("entry.json")); - JSONObject entryJson = new JSONObject(); - entryJson.put("version", 1); - entryJson.put("replaydata", replay.toJSON()); + JSONObject entryJson = new JSONObject(); + entryJson.put("version", 1); + entryJson.put("replaydata", replay.toJSON()); - outputStream.write(entryJson.toString(2).getBytes()); + outputStream.write(entryJson.toString(2).getBytes()); - outputStream.putNextEntry(new ZipEntry(replay.getReplayFileName())); + outputStream.putNextEntry(new ZipEntry(replay.getReplayFileName())); - File file = replay.isAbsoluteReplay() ? - new File(replay.getReplayFile()) : new File(OdrConfig.getScoreDir(), replay.getReplayFileName()); - FileInputStream inputStream = new FileInputStream(file); + File file = replay.isAbsoluteReplay() ? + new File(replay.getReplayFile()) : new File(OdrConfig.getScoreDir(), replay.getReplayFileName()); + FileInputStream inputStream = new FileInputStream(file); - byte[] buffer = new byte[1024]; - int l; - while ((l = inputStream.read(buffer)) != -1) { - outputStream.write(buffer, 0, l); - } + byte[] buffer = new byte[1024]; + int l; + while ((l = inputStream.read(buffer)) != -1) { + outputStream.write(buffer, 0, l); + } - outputStream.finish(); - return byteArrayOutputStream.toByteArray(); - } + outputStream.finish(); + return byteArrayOutputStream.toByteArray(); + } - public static ReplayEntry unpack(InputStream raw) throws IOException, JSONException { - ZipInputStream inputStream = new ZipInputStream(raw); - ReplayEntry entry = new ReplayEntry(); - Map zipEntryMap = new HashMap<>(); - for (ZipEntry zipEntry = inputStream.getNextEntry(); zipEntry != null; zipEntry = inputStream.getNextEntry()) { - ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); - byte[] buffer = new byte[1024]; - int l; - while ((l = inputStream.read(buffer)) != -1) { - byteArrayOutputStream.write(buffer, 0, l); - } - zipEntryMap.put(zipEntry.getName(), byteArrayOutputStream.toByteArray()); - System.out.println("解压文件:" + zipEntry.getName() + " size: " + zipEntryMap.get(zipEntry.getName()).length); - } - inputStream.close(); + public static ReplayEntry unpack(InputStream raw) throws IOException, JSONException { + ZipInputStream inputStream = new ZipInputStream(raw); + ReplayEntry entry = new ReplayEntry(); + Map zipEntryMap = new HashMap<>(); + for (ZipEntry zipEntry = inputStream.getNextEntry(); zipEntry != null; zipEntry = inputStream.getNextEntry()) { + ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); + byte[] buffer = new byte[1024]; + int l; + while ((l = inputStream.read(buffer)) != -1) { + byteArrayOutputStream.write(buffer, 0, l); + } + zipEntryMap.put(zipEntry.getName(), byteArrayOutputStream.toByteArray()); + System.out.println("解压文件:" + zipEntry.getName() + " size: " + zipEntryMap.get(zipEntry.getName()).length); + } + inputStream.close(); - entry.replay = OsuDroidReplay.parseJSON(new JSONObject(new String(zipEntryMap.get("entry.json"))).getJSONObject("replaydata")); - entry.replayFile = zipEntryMap.get(entry.replay.getReplayFileName()); + entry.replay = OsuDroidReplay.parseJSON(new JSONObject(new String(zipEntryMap.get("entry.json"))).getJSONObject("replaydata")); + entry.replayFile = zipEntryMap.get(entry.replay.getReplayFileName()); - return entry; - } + return entry; + } - public static class ReplayEntry { - public OsuDroidReplay replay; - public byte[] replayFile; - } + public static class ReplayEntry { + public OsuDroidReplay replay; + public byte[] replayFile; + } } diff --git a/src/com/edlplan/replay/SongsLibrary.java b/src/com/edlplan/replay/SongsLibrary.java index 89d86a76..221f59fd 100644 --- a/src/com/edlplan/replay/SongsLibrary.java +++ b/src/com/edlplan/replay/SongsLibrary.java @@ -7,36 +7,36 @@ public class SongsLibrary { - private static SongsLibrary library; - private HashMap osu2set = new HashMap<>(); - - public SongsLibrary() { - File songs = OdrConfig.getSongDir(); - File[] songsList = FileUtils.listFiles(songs, ".osu"); - for (File set : songsList) { - if (set.isDirectory()) { - for (String osu : set.list()) { - osu2set.put(osu, set.getName() + "/" + osu); - } - } - } - } - - public static SongsLibrary get() { - if (library == null) { - library = new SongsLibrary(); - } - return library; - } - - public String toSetLocal(String raw) { - String osu = raw.substring(raw.indexOf("/") + 1, raw.length()); - if (osu2set.containsKey(osu)) { - return osu2set.get(osu); - } else { - return raw; - } - } + private static SongsLibrary library; + private HashMap osu2set = new HashMap<>(); + + public SongsLibrary() { + File songs = OdrConfig.getSongDir(); + File[] songsList = FileUtils.listFiles(songs, ".osu"); + for (File set : songsList) { + if (set.isDirectory()) { + for (String osu : set.list()) { + osu2set.put(osu, set.getName() + "/" + osu); + } + } + } + } + + public static SongsLibrary get() { + if (library == null) { + library = new SongsLibrary(); + } + return library; + } + + public String toSetLocal(String raw) { + String osu = raw.substring(raw.indexOf("/") + 1, raw.length()); + if (osu2set.containsKey(osu)) { + return osu2set.get(osu); + } else { + return raw; + } + } } diff --git a/src/com/edlplan/ui/ActivityOverlay.kt b/src/com/edlplan/ui/ActivityOverlay.kt index 99b048b4..eef9f1d7 100644 --- a/src/com/edlplan/ui/ActivityOverlay.kt +++ b/src/com/edlplan/ui/ActivityOverlay.kt @@ -8,65 +8,65 @@ import com.edlplan.ui.fragment.BackPressListener import java.util.* object ActivityOverlay { - private var fragmentManager: FragmentManager? = null - private val displayingOverlay: MutableList = ArrayList() - private var context: Activity? = null - private var containerId = 0 - @JvmStatic - fun initial(activity: AppCompatActivity, id: Int) { - context = activity - containerId = id - fragmentManager = activity.supportFragmentManager - if (fragmentManager == null) { - throw RuntimeException("FragmentManager not found!") - } - } + private var fragmentManager: FragmentManager? = null + private val displayingOverlay: MutableList = ArrayList() + private var context: Activity? = null + private var containerId = 0 + @JvmStatic + fun initial(activity: AppCompatActivity, id: Int) { + context = activity + containerId = id + fragmentManager = activity.supportFragmentManager + if (fragmentManager == null) { + throw RuntimeException("FragmentManager not found!") + } + } - @JvmStatic - @Synchronized - fun onBackPress(): Boolean { - if (fragmentManager != null && displayingOverlay.size > 0) { - val overlay: Fragment? = displayingOverlay[displayingOverlay.size - 1] - if(overlay is BackPressListener) { - overlay.callDismissOnBackPress() - } - return true - } - return false - } + @JvmStatic + @Synchronized + fun onBackPress(): Boolean { + if (fragmentManager != null && displayingOverlay.size > 0) { + val overlay: Fragment? = displayingOverlay[displayingOverlay.size - 1] + if(overlay is BackPressListener) { + overlay.callDismissOnBackPress() + } + return true + } + return false + } - @Synchronized - fun dismissOverlay(fragment: Fragment) { - if (fragmentManager != null) { - if (displayingOverlay.contains(fragment)) { - displayingOverlay.remove(fragment) - fragmentManager!!.beginTransaction().remove(fragment).commit() - } - } - } + @Synchronized + fun dismissOverlay(fragment: Fragment) { + if (fragmentManager != null) { + if (displayingOverlay.contains(fragment)) { + displayingOverlay.remove(fragment) + fragmentManager!!.beginTransaction().remove(fragment).commit() + } + } + } - @Synchronized - fun addOverlay(fragment: Fragment, tag: String?) { - if (fragmentManager != null) { - if (fragment.isAdded()) { - return - } - if (displayingOverlay.contains(fragment) || fragmentManager!!.findFragmentByTag(tag) != null) { - displayingOverlay.remove(fragment) - fragmentManager!!.beginTransaction() - .remove(fragment) - .add(containerId, fragment, tag) - .commit() - return - } - displayingOverlay.add(fragment) - fragmentManager!!.beginTransaction() - .add(containerId, fragment, tag) - .commit() - } - } + @Synchronized + fun addOverlay(fragment: Fragment, tag: String?) { + if (fragmentManager != null) { + if (fragment.isAdded()) { + return + } + if (displayingOverlay.contains(fragment) || fragmentManager!!.findFragmentByTag(tag) != null) { + displayingOverlay.remove(fragment) + fragmentManager!!.beginTransaction() + .remove(fragment) + .add(containerId, fragment, tag) + .commit() + return + } + displayingOverlay.add(fragment) + fragmentManager!!.beginTransaction() + .add(containerId, fragment, tag) + .commit() + } + } - fun runOnUiThread(runnable: Runnable?) { - context!!.runOnUiThread(runnable) - } -} \ No newline at end of file + fun runOnUiThread(runnable: Runnable?) { + context!!.runOnUiThread(runnable) + } +} diff --git a/src/com/edlplan/ui/BaseAnimationListener.java b/src/com/edlplan/ui/BaseAnimationListener.java index da7730ad..add0dba4 100644 --- a/src/com/edlplan/ui/BaseAnimationListener.java +++ b/src/com/edlplan/ui/BaseAnimationListener.java @@ -4,23 +4,23 @@ public class BaseAnimationListener implements Animator.AnimatorListener { - @Override - public void onAnimationStart(Animator animation) { + @Override + public void onAnimationStart(Animator animation) { - } + } - @Override - public void onAnimationEnd(Animator animation) { + @Override + public void onAnimationEnd(Animator animation) { - } + } - @Override - public void onAnimationCancel(Animator animation) { + @Override + public void onAnimationCancel(Animator animation) { - } + } - @Override - public void onAnimationRepeat(Animator animation) { + @Override + public void onAnimationRepeat(Animator animation) { - } + } } diff --git a/src/com/edlplan/ui/EasingHelper.java b/src/com/edlplan/ui/EasingHelper.java index 1ab10b0b..d602697b 100644 --- a/src/com/edlplan/ui/EasingHelper.java +++ b/src/com/edlplan/ui/EasingHelper.java @@ -7,9 +7,9 @@ public class EasingHelper { - public static Interpolator asInterpolator(Easing easing) { - return f -> (float) EasingManager.apply(easing, f); - } + public static Interpolator asInterpolator(Easing easing) { + return f -> (float) EasingManager.apply(easing, f); + } } diff --git a/src/com/edlplan/ui/ImportReplayActivity.java b/src/com/edlplan/ui/ImportReplayActivity.java index f3b0e44e..e6f9fd6c 100644 --- a/src/com/edlplan/ui/ImportReplayActivity.java +++ b/src/com/edlplan/ui/ImportReplayActivity.java @@ -17,54 +17,54 @@ public class ImportReplayActivity extends Activity { - @Override - protected void onCreate(@Nullable Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - } + @Override + protected void onCreate(@Nullable Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + } - @Override - protected void onStart() { - super.onStart(); - if (getIntent().getData() != null) { - String path = getIntent().getData().getPath(); - System.out.println("path: " + path); - File file = new File(path); - if ((!file.exists()) || file.isDirectory()) { - Toast.makeText(this, R.string.invalid_edr_file, Toast.LENGTH_SHORT).show(); - super.onStart(); - finish(); - return; - } - try { - OsuDroidReplayPack.ReplayEntry entry = OsuDroidReplayPack.unpack(new FileInputStream(file)); - File rep = new File(OdrConfig.getScoreDir(), entry.replay.getReplayFileName()); - if (!rep.exists()) { - if (!rep.createNewFile()) { - Toast.makeText(this, R.string.failed_to_import_edr, Toast.LENGTH_SHORT).show(); - super.onStart(); - finish(); - return; - } - } - FileOutputStream outputStream = new FileOutputStream(rep); - outputStream.write(entry.replayFile); - outputStream.close(); - entry.replay.setReplayFile(rep.getAbsolutePath()); - if (OdrDatabase.get().write(entry.replay) != -1) { - Toast.makeText(this, R.string.import_edr_successfully, Toast.LENGTH_SHORT).show(); - finish(); - } else { - Toast.makeText(this, R.string.failed_to_import_edr, Toast.LENGTH_SHORT).show(); - finish(); - } - } catch (Exception e) { - e.printStackTrace(); - Toast.makeText(this, String.format(getResources().getString(R.string.failed_to_import_edr_with_err), e.toString()), Toast.LENGTH_SHORT).show(); - super.onStart(); - finish(); - return; - } - } - super.onStart(); - } + @Override + protected void onStart() { + super.onStart(); + if (getIntent().getData() != null) { + String path = getIntent().getData().getPath(); + System.out.println("path: " + path); + File file = new File(path); + if ((!file.exists()) || file.isDirectory()) { + Toast.makeText(this, R.string.invalid_edr_file, Toast.LENGTH_SHORT).show(); + super.onStart(); + finish(); + return; + } + try { + OsuDroidReplayPack.ReplayEntry entry = OsuDroidReplayPack.unpack(new FileInputStream(file)); + File rep = new File(OdrConfig.getScoreDir(), entry.replay.getReplayFileName()); + if (!rep.exists()) { + if (!rep.createNewFile()) { + Toast.makeText(this, R.string.failed_to_import_edr, Toast.LENGTH_SHORT).show(); + super.onStart(); + finish(); + return; + } + } + FileOutputStream outputStream = new FileOutputStream(rep); + outputStream.write(entry.replayFile); + outputStream.close(); + entry.replay.setReplayFile(rep.getAbsolutePath()); + if (OdrDatabase.get().write(entry.replay) != -1) { + Toast.makeText(this, R.string.import_edr_successfully, Toast.LENGTH_SHORT).show(); + finish(); + } else { + Toast.makeText(this, R.string.failed_to_import_edr, Toast.LENGTH_SHORT).show(); + finish(); + } + } catch (Exception e) { + e.printStackTrace(); + Toast.makeText(this, String.format(getResources().getString(R.string.failed_to_import_edr_with_err), e.toString()), Toast.LENGTH_SHORT).show(); + super.onStart(); + finish(); + return; + } + } + super.onStart(); + } } diff --git a/src/com/edlplan/ui/InputDialog.java b/src/com/edlplan/ui/InputDialog.java index 396f468c..18f676e6 100644 --- a/src/com/edlplan/ui/InputDialog.java +++ b/src/com/edlplan/ui/InputDialog.java @@ -9,20 +9,20 @@ public class InputDialog extends Dialog { - public InputDialog(@NonNull Context context) { - super(context, R.style.Theme_Design_BottomSheetDialog); - setContentView(R.layout.dialog_for_input); - } + public InputDialog(@NonNull Context context) { + super(context, R.style.Theme_Design_BottomSheetDialog); + setContentView(R.layout.dialog_for_input); + } - public void showForResult(OnResult onResult) { - findViewById(R.id.button3).setOnClickListener(view -> { - onResult.onResult(((EditText) findViewById(R.id.editText)).getText().toString()); - dismiss(); - }); - show(); - } + public void showForResult(OnResult onResult) { + findViewById(R.id.button3).setOnClickListener(view -> { + onResult.onResult(((EditText) findViewById(R.id.editText)).getText().toString()); + dismiss(); + }); + show(); + } - public interface OnResult { - void onResult(String result); - } + public interface OnResult { + void onResult(String result); + } } diff --git a/src/com/edlplan/ui/InvalidateView.java b/src/com/edlplan/ui/InvalidateView.java index 528b2ea0..758c9bec 100644 --- a/src/com/edlplan/ui/InvalidateView.java +++ b/src/com/edlplan/ui/InvalidateView.java @@ -9,26 +9,26 @@ import android.view.View; public class InvalidateView extends View { - public InvalidateView(Context context) { - super(context); - } + public InvalidateView(Context context) { + super(context); + } - public InvalidateView(Context context, @Nullable AttributeSet attrs) { - super(context, attrs); - } + public InvalidateView(Context context, @Nullable AttributeSet attrs) { + super(context, attrs); + } - public InvalidateView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { - super(context, attrs, defStyleAttr); - } + public InvalidateView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { + super(context, attrs, defStyleAttr); + } - @TargetApi(Build.VERSION_CODES.LOLLIPOP) - public InvalidateView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) { - super(context, attrs, defStyleAttr, defStyleRes); - } + @TargetApi(Build.VERSION_CODES.LOLLIPOP) + public InvalidateView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) { + super(context, attrs, defStyleAttr, defStyleRes); + } - @Override - protected void onDraw(Canvas canvas) { - super.onDraw(canvas); - invalidate(); - } + @Override + protected void onDraw(Canvas canvas) { + super.onDraw(canvas); + invalidate(); + } } diff --git a/src/com/edlplan/ui/SkinPathPreference.java b/src/com/edlplan/ui/SkinPathPreference.java index f1ac492f..f5316538 100644 --- a/src/com/edlplan/ui/SkinPathPreference.java +++ b/src/com/edlplan/ui/SkinPathPreference.java @@ -1,70 +1,70 @@ -package com.edlplan.ui; - -import android.content.Context; -import android.util.AttributeSet; - -import androidx.preference.ListPreference; - -import java.io.File; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; - -import org.anddev.andengine.util.Debug; - -import ru.nsu.ccfit.zuev.osu.Config; -import ru.nsu.ccfit.zuev.osu.GlobalManager; -import ru.nsu.ccfit.zuev.osu.async.AsyncTaskLoader; -import ru.nsu.ccfit.zuev.osu.async.OsuAsyncCallback; -import ru.nsu.ccfit.zuev.osuplus.R; - -public class SkinPathPreference extends ListPreference { - - public SkinPathPreference(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { - super(context, attrs, defStyleAttr, defStyleRes); - } - - public SkinPathPreference(Context context, AttributeSet attrs, int defStyleAttr) { - super(context, attrs); - } - - public SkinPathPreference(Context context, AttributeSet attrs) { - super(context, attrs); - } - - public SkinPathPreference(Context context) { - super(context); - } - - public void reloadSkinList() { - try { - File skinMain = new File(Config.getSkinTopPath()); - Map skins = new HashMap(Config.getSkins()); - int skinsSize = (skins.size() > 0) ? skins.size() + 1 : 1; - Debug.i("Skins count:" + skinsSize); - CharSequence[] entries = new CharSequence[skinsSize]; - CharSequence[] entryValues = new CharSequence[skinsSize]; - entries[0] = skinMain.getName() + " (Default)"; - entryValues[0] = skinMain.getPath(); - - if(skins.size() > 0) { - int index = 1; - for(Map.Entry skin : skins.entrySet()) { - entries[index] = skin.getKey(); - entryValues[index] = skin.getValue(); - index++; - } - - Arrays.sort(entries, 1, entries.length); - Arrays.sort(entryValues, 1, entryValues.length); - } - - setEntries(entries); - setEntryValues(entryValues); - } catch (Exception e) { - Debug.e("SkinPathPreference.reloadSkinList: ", e); - e.printStackTrace(); - } - } - -} \ No newline at end of file +package com.edlplan.ui; + +import android.content.Context; +import android.util.AttributeSet; + +import androidx.preference.ListPreference; + +import java.io.File; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + +import org.anddev.andengine.util.Debug; + +import ru.nsu.ccfit.zuev.osu.Config; +import ru.nsu.ccfit.zuev.osu.GlobalManager; +import ru.nsu.ccfit.zuev.osu.async.AsyncTaskLoader; +import ru.nsu.ccfit.zuev.osu.async.OsuAsyncCallback; +import ru.nsu.ccfit.zuev.osuplus.R; + +public class SkinPathPreference extends ListPreference { + + public SkinPathPreference(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { + super(context, attrs, defStyleAttr, defStyleRes); + } + + public SkinPathPreference(Context context, AttributeSet attrs, int defStyleAttr) { + super(context, attrs); + } + + public SkinPathPreference(Context context, AttributeSet attrs) { + super(context, attrs); + } + + public SkinPathPreference(Context context) { + super(context); + } + + public void reloadSkinList() { + try { + File skinMain = new File(Config.getSkinTopPath()); + Map skins = new HashMap(Config.getSkins()); + int skinsSize = (skins.size() > 0) ? skins.size() + 1 : 1; + Debug.i("Skins count:" + skinsSize); + CharSequence[] entries = new CharSequence[skinsSize]; + CharSequence[] entryValues = new CharSequence[skinsSize]; + entries[0] = skinMain.getName() + " (Default)"; + entryValues[0] = skinMain.getPath(); + + if(skins.size() > 0) { + int index = 1; + for(Map.Entry skin : skins.entrySet()) { + entries[index] = skin.getKey(); + entryValues[index] = skin.getValue(); + index++; + } + + Arrays.sort(entries, 1, entries.length); + Arrays.sort(entryValues, 1, entryValues.length); + } + + setEntries(entries); + setEntryValues(entryValues); + } catch (Exception e) { + Debug.e("SkinPathPreference.reloadSkinList: ", e); + e.printStackTrace(); + } + } + +} diff --git a/src/com/edlplan/ui/TriangleDrawable.java b/src/com/edlplan/ui/TriangleDrawable.java index c4ca026c..9d5c8a8d 100644 --- a/src/com/edlplan/ui/TriangleDrawable.java +++ b/src/com/edlplan/ui/TriangleDrawable.java @@ -21,222 +21,222 @@ public class TriangleDrawable extends Drawable { - private final float m = (float) (Math.sqrt(3) / 2); - int spawnClock = 0; - int spawnCost = 120; - private LinkedList triangles = new LinkedList<>(); - private boolean spawnNewTriangles = true; - private Paint paint = new Paint(); - private Random random = new Random(); - private Path path = new Path(); - private int[] colors = new int[]{ - 0xFFF7E67A, - 0xFFEE8100, - 0xFF74C684, - 0xFFF8558C, - 0xFF5245F7 - }; - private float width, height; - private long time = -1; - private boolean preSpawnTriangles; - private PosXDistribution xDistribution = null; - private float defaultXDistributionScale = 10; - private float baseSpeed = 15; - private float edgeClampRate = 0.2f; - private boolean freeze = false; - - public TriangleDrawable() { - this(true); - } - - public TriangleDrawable(boolean preSpawnTriangles) { - this.preSpawnTriangles = preSpawnTriangles; - } - - @Override - public void draw(@NonNull Canvas canvas) { - onDraw(canvas); - } - - @Override - public void setAlpha(int alpha) { - - } - - @Override - public void setColorFilter(@Nullable ColorFilter colorFilter) { - - } - - @Override - public int getOpacity() { - return PixelFormat.TRANSPARENT; - } - - public void setFreeze(boolean freeze) { - this.freeze = freeze; - } - - public void setXDistribution(PosXDistribution xDistribution) { - this.xDistribution = xDistribution; - this.time = -1; - this.triangles.clear(); - } - - public void setDefaultXDistributionScale(float defaultXDistributionScale) { - this.defaultXDistributionScale = defaultXDistributionScale; - } - - public void setEdgeClampRate(float edgeClampRate) { - this.edgeClampRate = edgeClampRate; - } - - public float getEdgeClampRate() { - return edgeClampRate; - } - - protected void onDraw(Canvas canvas) { - if(!Config.isTrianglesAnimation()) { - return; - } - - width = getBounds().width(); - height = getBounds().height(); - paint.setColor(0xFFFFFFFF); - if (time == -1) { - time = System.currentTimeMillis(); - if (this.preSpawnTriangles) { - for (int i = 0; i < 200; i++) { - update(36); - } - } - return; - } - int dt = (int) (System.currentTimeMillis() - time); - time += dt; - if (!freeze) { - update(dt * 2); - } - - for (Triangle triangle : triangles) { - path.rewind(); - path.moveTo(triangle.center.x, triangle.center.y - triangle.size); - path.rLineTo(triangle.size * m, triangle.size * 1.5f); - path.rLineTo(-triangle.size * m * 2, 0); - path.close(); - canvas.drawPath(path, triangle.paint); - } - } - - private float nextAlpha() { - return (float) Math.max(1 - 1.5 * Math.abs(random.nextGaussian()), 0.1); - } - - private float defaultX() { - // return 2 * random.nextGaussian(); - return (float) (2f / (1 + Math.exp((Math.random() * 2 - 1) * defaultXDistributionScale)) - 1); - } - - private PointF nextPos() { - return new PointF( - FMath.clamp(width / 2 * (1 + - (xDistribution != null ? xDistribution.generate() : defaultX())), 0, width), - height - ); - } - - private float nextSize() { - //return random.nextInt(200); - //return (float) (Math.min(width, height) * 0.8 * (Math.min(1, Math.abs(random.nextGaussian())) * 0.8 + 0.2)); - return (float) (Math.pow(Math.random(), 2) * 200); - } - - private void spawnOneTriangle() { - Triangle triangle = new Triangle(); - triangle.color = colors[random.nextInt(colors.length)]; - triangle.alpha = nextAlpha(); - triangle.center = nextPos(); - - triangle.speed = (float) (15 * (Math.abs(random.nextGaussian()) * 0.4 + 0.6)); - triangle.size = nextSize(); - triangle.center.y += triangle.size; - triangle.lifeTime = 8000; - triangle.center.x = FMath.clamp(triangle.center.x, triangle.size * edgeClampRate, width - triangle.size * edgeClampRate); - triangle.fixBound(); - if (triangle.size < 20 || triangle.lifeTime < 100) { - return; - } - triangle.paint = new Paint(); - triangle.paint.setColor(triangle.color); - triangles.add(triangle); - } - - private void doSpawnNewTriangles(int dt) { - spawnClock += dt; - while (spawnClock > spawnCost) { - /*int count = random.nextInt(2); - for (int i = 0; i < count; i++) { - spawnOneTriangle(); - }*/ - spawnOneTriangle(); - spawnClock -= spawnCost; - } - - } - - private void update(int dt) { - if (spawnNewTriangles) { - doSpawnNewTriangles(dt); - } - - Iterator iterator = triangles.iterator(); - while (iterator.hasNext()) { - Triangle triangle = iterator.next(); - triangle.update(dt); - if (triangle.updateAlpha < 0.005) { - iterator.remove(); - } - } - } - - public interface PosXDistribution { - float generate(); - } - - - public class Triangle { - - public Paint paint; - - public PointF center; - - public float size; - - public float alpha; - - public float updateAlpha; - - public float speed; - - public int color; - - public int lifeTime; - - public int passTime; - - public void fixBound() { - /*size = Math.min(size, Math.min(center.x, width - center.x)); - size = Math.min(center.y, size); - size = Math.min(2 * (height - center.y), size); - lifeTime = (int) Math.min(lifeTime, (center.y - size) / speed * 1000);*/ - } - - public void update(int dt) { - passTime += dt; - updateAlpha = center.y / height * alpha; - center.y -= dt * speed / 1000; - paint.setAlpha(Math.min(255, (int) (updateAlpha * 255))); - } - - } + private final float m = (float) (Math.sqrt(3) / 2); + int spawnClock = 0; + int spawnCost = 120; + private LinkedList triangles = new LinkedList<>(); + private boolean spawnNewTriangles = true; + private Paint paint = new Paint(); + private Random random = new Random(); + private Path path = new Path(); + private int[] colors = new int[]{ + 0xFFF7E67A, + 0xFFEE8100, + 0xFF74C684, + 0xFFF8558C, + 0xFF5245F7 + }; + private float width, height; + private long time = -1; + private boolean preSpawnTriangles; + private PosXDistribution xDistribution = null; + private float defaultXDistributionScale = 10; + private float baseSpeed = 15; + private float edgeClampRate = 0.2f; + private boolean freeze = false; + + public TriangleDrawable() { + this(true); + } + + public TriangleDrawable(boolean preSpawnTriangles) { + this.preSpawnTriangles = preSpawnTriangles; + } + + @Override + public void draw(@NonNull Canvas canvas) { + onDraw(canvas); + } + + @Override + public void setAlpha(int alpha) { + + } + + @Override + public void setColorFilter(@Nullable ColorFilter colorFilter) { + + } + + @Override + public int getOpacity() { + return PixelFormat.TRANSPARENT; + } + + public void setFreeze(boolean freeze) { + this.freeze = freeze; + } + + public void setXDistribution(PosXDistribution xDistribution) { + this.xDistribution = xDistribution; + this.time = -1; + this.triangles.clear(); + } + + public void setDefaultXDistributionScale(float defaultXDistributionScale) { + this.defaultXDistributionScale = defaultXDistributionScale; + } + + public void setEdgeClampRate(float edgeClampRate) { + this.edgeClampRate = edgeClampRate; + } + + public float getEdgeClampRate() { + return edgeClampRate; + } + + protected void onDraw(Canvas canvas) { + if(!Config.isTrianglesAnimation()) { + return; + } + + width = getBounds().width(); + height = getBounds().height(); + paint.setColor(0xFFFFFFFF); + if (time == -1) { + time = System.currentTimeMillis(); + if (this.preSpawnTriangles) { + for (int i = 0; i < 200; i++) { + update(36); + } + } + return; + } + int dt = (int) (System.currentTimeMillis() - time); + time += dt; + if (!freeze) { + update(dt * 2); + } + + for (Triangle triangle : triangles) { + path.rewind(); + path.moveTo(triangle.center.x, triangle.center.y - triangle.size); + path.rLineTo(triangle.size * m, triangle.size * 1.5f); + path.rLineTo(-triangle.size * m * 2, 0); + path.close(); + canvas.drawPath(path, triangle.paint); + } + } + + private float nextAlpha() { + return (float) Math.max(1 - 1.5 * Math.abs(random.nextGaussian()), 0.1); + } + + private float defaultX() { + // return 2 * random.nextGaussian(); + return (float) (2f / (1 + Math.exp((Math.random() * 2 - 1) * defaultXDistributionScale)) - 1); + } + + private PointF nextPos() { + return new PointF( + FMath.clamp(width / 2 * (1 + + (xDistribution != null ? xDistribution.generate() : defaultX())), 0, width), + height + ); + } + + private float nextSize() { + //return random.nextInt(200); + //return (float) (Math.min(width, height) * 0.8 * (Math.min(1, Math.abs(random.nextGaussian())) * 0.8 + 0.2)); + return (float) (Math.pow(Math.random(), 2) * 200); + } + + private void spawnOneTriangle() { + Triangle triangle = new Triangle(); + triangle.color = colors[random.nextInt(colors.length)]; + triangle.alpha = nextAlpha(); + triangle.center = nextPos(); + + triangle.speed = (float) (15 * (Math.abs(random.nextGaussian()) * 0.4 + 0.6)); + triangle.size = nextSize(); + triangle.center.y += triangle.size; + triangle.lifeTime = 8000; + triangle.center.x = FMath.clamp(triangle.center.x, triangle.size * edgeClampRate, width - triangle.size * edgeClampRate); + triangle.fixBound(); + if (triangle.size < 20 || triangle.lifeTime < 100) { + return; + } + triangle.paint = new Paint(); + triangle.paint.setColor(triangle.color); + triangles.add(triangle); + } + + private void doSpawnNewTriangles(int dt) { + spawnClock += dt; + while (spawnClock > spawnCost) { + /*int count = random.nextInt(2); + for (int i = 0; i < count; i++) { + spawnOneTriangle(); + }*/ + spawnOneTriangle(); + spawnClock -= spawnCost; + } + + } + + private void update(int dt) { + if (spawnNewTriangles) { + doSpawnNewTriangles(dt); + } + + Iterator iterator = triangles.iterator(); + while (iterator.hasNext()) { + Triangle triangle = iterator.next(); + triangle.update(dt); + if (triangle.updateAlpha < 0.005) { + iterator.remove(); + } + } + } + + public interface PosXDistribution { + float generate(); + } + + + public class Triangle { + + public Paint paint; + + public PointF center; + + public float size; + + public float alpha; + + public float updateAlpha; + + public float speed; + + public int color; + + public int lifeTime; + + public int passTime; + + public void fixBound() { + /*size = Math.min(size, Math.min(center.x, width - center.x)); + size = Math.min(center.y, size); + size = Math.min(2 * (height - center.y), size); + lifeTime = (int) Math.min(lifeTime, (center.y - size) / speed * 1000);*/ + } + + public void update(int dt) { + passTime += dt; + updateAlpha = center.y / height * alpha; + center.y -= dt * speed / 1000; + paint.setAlpha(Math.min(255, (int) (updateAlpha * 255))); + } + + } } diff --git a/src/com/edlplan/ui/TriangleEffectView.java b/src/com/edlplan/ui/TriangleEffectView.java index 17af58de..baee66ca 100644 --- a/src/com/edlplan/ui/TriangleEffectView.java +++ b/src/com/edlplan/ui/TriangleEffectView.java @@ -9,60 +9,60 @@ import android.view.View; public class TriangleEffectView extends View { - private static final String NAMESPACE = "http://ui.edlplan.com/customview"; + private static final String NAMESPACE = "http://ui.edlplan.com/customview"; - private TriangleDrawable triangleDrawable; + private TriangleDrawable triangleDrawable; - public TriangleEffectView(Context context) { - super(context); - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { - setBackground(triangleDrawable = new TriangleDrawable()); - } - } + public TriangleEffectView(Context context) { + super(context); + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { + setBackground(triangleDrawable = new TriangleDrawable()); + } + } - public TriangleEffectView(Context context, @Nullable AttributeSet attrs) { - super(context, attrs); - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { - setBackground(triangleDrawable = createDrawable(attrs)); - } - } + public TriangleEffectView(Context context, @Nullable AttributeSet attrs) { + super(context, attrs); + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { + setBackground(triangleDrawable = createDrawable(attrs)); + } + } - public TriangleEffectView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { - super(context, attrs, defStyleAttr); - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { - setBackground(triangleDrawable = createDrawable(attrs)); - } - } + public TriangleEffectView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { + super(context, attrs, defStyleAttr); + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { + setBackground(triangleDrawable = createDrawable(attrs)); + } + } - @TargetApi(Build.VERSION_CODES.LOLLIPOP) - public TriangleEffectView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) { - super(context, attrs, defStyleAttr, defStyleRes); + @TargetApi(Build.VERSION_CODES.LOLLIPOP) + public TriangleEffectView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) { + super(context, attrs, defStyleAttr, defStyleRes); - setBackground(triangleDrawable = createDrawable(attrs)); - } + setBackground(triangleDrawable = createDrawable(attrs)); + } - protected TriangleDrawable createDrawable(@Nullable AttributeSet attrs) { - boolean preSpawnTriangles = true; - if (attrs != null) { - preSpawnTriangles = attrs.getAttributeBooleanValue(NAMESPACE, "preSpawnTriangles", true); - } - TriangleDrawable triangle = new TriangleDrawable(preSpawnTriangles); - if (attrs != null) { - if (attrs.getAttributeBooleanValue(NAMESPACE, "freeze", false)) { - triangle.setFreeze(true); - } - triangle.setEdgeClampRate(attrs.getAttributeFloatValue(NAMESPACE, "edgeClampRate", triangle.getEdgeClampRate())); - } - return triangle; - } + protected TriangleDrawable createDrawable(@Nullable AttributeSet attrs) { + boolean preSpawnTriangles = true; + if (attrs != null) { + preSpawnTriangles = attrs.getAttributeBooleanValue(NAMESPACE, "preSpawnTriangles", true); + } + TriangleDrawable triangle = new TriangleDrawable(preSpawnTriangles); + if (attrs != null) { + if (attrs.getAttributeBooleanValue(NAMESPACE, "freeze", false)) { + triangle.setFreeze(true); + } + triangle.setEdgeClampRate(attrs.getAttributeFloatValue(NAMESPACE, "edgeClampRate", triangle.getEdgeClampRate())); + } + return triangle; + } - @Override - protected void onDraw(Canvas canvas) { - super.onDraw(canvas); - invalidate(); - } + @Override + protected void onDraw(Canvas canvas) { + super.onDraw(canvas); + invalidate(); + } - public void setXDistribution(TriangleDrawable.PosXDistribution xDistribution) { - triangleDrawable.setXDistribution(xDistribution); - } + public void setXDistribution(TriangleDrawable.PosXDistribution xDistribution) { + triangleDrawable.setXDistribution(xDistribution); + } } diff --git a/src/com/edlplan/ui/design/IColor.java b/src/com/edlplan/ui/design/IColor.java index bdca6c7f..fbfe6b67 100644 --- a/src/com/edlplan/ui/design/IColor.java +++ b/src/com/edlplan/ui/design/IColor.java @@ -4,10 +4,10 @@ public interface IColor { - Color4 getColor(); + Color4 getColor(); - default boolean isContextNeeded() { - return false; - } + default boolean isContextNeeded() { + return false; + } } diff --git a/src/com/edlplan/ui/fragment/BackPressListener.kt b/src/com/edlplan/ui/fragment/BackPressListener.kt index 67dc5763..37d41fa0 100644 --- a/src/com/edlplan/ui/fragment/BackPressListener.kt +++ b/src/com/edlplan/ui/fragment/BackPressListener.kt @@ -1,5 +1,5 @@ -package com.edlplan.ui.fragment - -fun interface BackPressListener { - fun callDismissOnBackPress() -} \ No newline at end of file +package com.edlplan.ui.fragment + +fun interface BackPressListener { + fun callDismissOnBackPress() +} diff --git a/src/com/edlplan/ui/fragment/BaseFragment.kt b/src/com/edlplan/ui/fragment/BaseFragment.kt index ef497608..f8ed979f 100644 --- a/src/com/edlplan/ui/fragment/BaseFragment.kt +++ b/src/com/edlplan/ui/fragment/BaseFragment.kt @@ -13,85 +13,85 @@ import com.edlplan.ui.EasingHelper import ru.nsu.ccfit.zuev.osuplus.R abstract class BaseFragment : Fragment(), BackPressListener { - var root: View? = null - private set - private var background: View? = null - var onDismissListener: OnDismissListener? = null - var isDismissOnBackgroundClick = false - var isCreated = false - private set - var isDismissOnBackPress = true + var root: View? = null + private set + private var background: View? = null + var onDismissListener: OnDismissListener? = null + var isDismissOnBackgroundClick = false + var isCreated = false + private set + var isDismissOnBackPress = true - @get:IdRes - val backgroundId: Int - get() = R.id.frg_background + @get:IdRes + val backgroundId: Int + get() = R.id.frg_background - @Suppress("UNCHECKED_CAST") - fun findViewById(@IdRes id: Int): T? { - val o: Any? = if (root != null) root!!.findViewById(id) else null - return if (o == null) { - null - } else { - o as T - } - } + @Suppress("UNCHECKED_CAST") + fun findViewById(@IdRes id: Int): T? { + val o: Any? = if (root != null) root!!.findViewById(id) else null + return if (o == null) { + null + } else { + o as T + } + } - @get:LayoutRes - protected abstract val layoutID: Int - protected abstract fun onLoadView() - protected fun playBackgroundHideInAnim(duration: Int) { - val background = findViewById(R.id.frg_background) - if (background != null) { - background.alpha = 0f - background.animate().cancel() - background.animate() - .alpha(1f) - .setDuration(duration.toLong()) - .setInterpolator(EasingHelper.asInterpolator(Easing.InOutQuad)) - .start() - } - } + @get:LayoutRes + protected abstract val layoutID: Int + protected abstract fun onLoadView() + protected fun playBackgroundHideInAnim(duration: Int) { + val background = findViewById(R.id.frg_background) + if (background != null) { + background.alpha = 0f + background.animate().cancel() + background.animate() + .alpha(1f) + .setDuration(duration.toLong()) + .setInterpolator(EasingHelper.asInterpolator(Easing.InOutQuad)) + .start() + } + } - protected fun playBackgroundHideOutAnim(duration: Int) { - val background = findViewById(R.id.frg_background) - if (background != null) { - background.animate().cancel() - background.animate() - .alpha(0f) - .setDuration(duration.toLong()) - .setInterpolator(EasingHelper.asInterpolator(Easing.InOutQuad)) - .start() - } - } + protected fun playBackgroundHideOutAnim(duration: Int) { + val background = findViewById(R.id.frg_background) + if (background != null) { + background.animate().cancel() + background.animate() + .alpha(0f) + .setDuration(duration.toLong()) + .setInterpolator(EasingHelper.asInterpolator(Easing.InOutQuad)) + .start() + } + } - open fun show() { - ActivityOverlay.addOverlay(this, this.javaClass.name + "@" + this.hashCode()) - } + open fun show() { + ActivityOverlay.addOverlay(this, this.javaClass.name + "@" + this.hashCode()) + } - open fun dismiss() { - ActivityOverlay.dismissOverlay(this) - onDismissListener?.OnDismiss() - } + open fun dismiss() { + ActivityOverlay.dismissOverlay(this) + onDismissListener?.OnDismiss() + } - override fun callDismissOnBackPress() { - if (isDismissOnBackPress) { - dismiss() - } - } + override fun callDismissOnBackPress() { + if (isDismissOnBackPress) { + dismiss() + } + } - override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { - isCreated = true - root = inflater.inflate(layoutID, container, false) - findViewById(backgroundId)?.setOnClickListener { - if (isDismissOnBackgroundClick) { - dismiss() - } - } - onLoadView() - return root - } + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { + isCreated = true + root = inflater.inflate(layoutID, container, false) + findViewById(backgroundId)?.setOnClickListener { + if (isDismissOnBackgroundClick) { + dismiss() + } + } + onLoadView() + return root + } - fun interface OnDismissListener { - fun OnDismiss() - } -} \ No newline at end of file + fun interface OnDismissListener { + fun OnDismiss() + } +} diff --git a/src/com/edlplan/ui/fragment/BuildTypeNoticeFragment.kt b/src/com/edlplan/ui/fragment/BuildTypeNoticeFragment.kt index 18600b2c..ebb6f870 100644 --- a/src/com/edlplan/ui/fragment/BuildTypeNoticeFragment.kt +++ b/src/com/edlplan/ui/fragment/BuildTypeNoticeFragment.kt @@ -14,73 +14,73 @@ import ru.nsu.ccfit.zuev.osuplus.R import java.io.IOException class BuildTypeNoticeFragment : BaseFragment() { - override val layoutID: Int - get() = R.layout.fragment_build_type_notice + override val layoutID: Int + get() = R.layout.fragment_build_type_notice - @RequiresApi(api = Build.VERSION_CODES.O) - override fun onLoadView() { - findViewById(R.id.bg_triangles)!!.setXDistribution { (2f / (1 + Math.exp((Math.random() * 2 - 1) * 10)) - 1).toFloat() } - findViewById(R.id.button_view_changelist)!!.setOnClickListener { - var markdown: String? - try { - val `in` = requireContext().assets.open("app/changelog.md") - markdown = StreamUtils.readFully(`in`) - `in`.close() - } catch (e: IOException) { - e.printStackTrace() - markdown = e.message - } - MarkdownFragment() - .setTitle(R.string.changelog_title) - .setMarkdown(markdown) - .show() - } - playOnLoadAnim() - } + @RequiresApi(api = Build.VERSION_CODES.O) + override fun onLoadView() { + findViewById(R.id.bg_triangles)!!.setXDistribution { (2f / (1 + Math.exp((Math.random() * 2 - 1) * 10)) - 1).toFloat() } + findViewById(R.id.button_view_changelist)!!.setOnClickListener { + var markdown: String? + try { + val `in` = requireContext().assets.open("app/changelog.md") + markdown = StreamUtils.readFully(`in`) + `in`.close() + } catch (e: IOException) { + e.printStackTrace() + markdown = e.message + } + MarkdownFragment() + .setTitle(R.string.changelog_title) + .setMarkdown(markdown) + .show() + } + playOnLoadAnim() + } - override fun dismiss() { - playOnDismissAnim(Runnable { super.dismiss() }) - } + override fun dismiss() { + playOnDismissAnim(Runnable { super.dismiss() }) + } - protected fun playOnLoadAnim() { - val body = findViewById(R.id.frg_body) - body!!.alpha = 0f - body.animate().cancel() - body.animate() - .alpha(1f) - .setDuration(1000) - .start() - /*View icon = findViewById(R.id.warning_icon); - Animation anim = AnimationUtils.loadAnimation(getContext(), R.anim.warning_rotate); - anim.setInterpolator(EasingHelper.asInterpolator(Easing.InOutQuad)); - icon.startAnimation(anim);*/ - body.postDelayed({ dismiss() }, 6000) - } + protected fun playOnLoadAnim() { + val body = findViewById(R.id.frg_body) + body!!.alpha = 0f + body.animate().cancel() + body.animate() + .alpha(1f) + .setDuration(1000) + .start() + /*View icon = findViewById(R.id.warning_icon); + Animation anim = AnimationUtils.loadAnimation(getContext(), R.anim.warning_rotate); + anim.setInterpolator(EasingHelper.asInterpolator(Easing.InOutQuad)); + icon.startAnimation(anim);*/ + body.postDelayed({ dismiss() }, 6000) + } - protected fun playOnDismissAnim(runnable: Runnable?) { - val body = findViewById(R.id.frg_body) - body!!.animate().cancel() - body.animate() - .scaleX(2f) - .scaleY(2f) - .setDuration(1000) - .setInterpolator(EasingHelper.asInterpolator(Easing.InOutQuad)) - .setListener(object : BaseAnimationListener() { - override fun onAnimationEnd(animation: Animator) { - runnable?.run() - } - }) - .start() - playBackgroundHideOutAnim(1000) - } + protected fun playOnDismissAnim(runnable: Runnable?) { + val body = findViewById(R.id.frg_body) + body!!.animate().cancel() + body.animate() + .scaleX(2f) + .scaleY(2f) + .setDuration(1000) + .setInterpolator(EasingHelper.asInterpolator(Easing.InOutQuad)) + .setListener(object : BaseAnimationListener() { + override fun onAnimationEnd(animation: Animator) { + runnable?.run() + } + }) + .start() + playBackgroundHideOutAnim(1000) + } - companion object { - @JvmField - val single = Lazy.create { BuildTypeNoticeFragment() } - } + companion object { + @JvmField + val single = Lazy.create { BuildTypeNoticeFragment() } + } - init { - isDismissOnBackgroundClick = true - isDismissOnBackPress = true - } -} \ No newline at end of file + init { + isDismissOnBackgroundClick = true + isDismissOnBackPress = true + } +} diff --git a/src/com/edlplan/ui/fragment/ConfirmDialogFragment.java b/src/com/edlplan/ui/fragment/ConfirmDialogFragment.java index 477e1f5f..dc165fc5 100644 --- a/src/com/edlplan/ui/fragment/ConfirmDialogFragment.java +++ b/src/com/edlplan/ui/fragment/ConfirmDialogFragment.java @@ -14,86 +14,86 @@ public class ConfirmDialogFragment extends BaseFragment { - private OnResult onResult; - - @StringRes - private int text; - - public ConfirmDialogFragment() { - setDismissOnBackgroundClick(true); - } - - @Override - protected int getLayoutID() { - return R.layout.frgdialog_confirm; - } - - @Override - protected void onLoadView() { - findViewById(R.id.okButton).setOnClickListener(v -> { - if (onResult != null) { - onResult.onAccept(true); - dismiss(); - } - }); - if (text != 0) { - ((TextView) findViewById(R.id.confirm_message)).setText(text); - } - playOnLoadAnim(); - } - - @Override - public void dismiss() { - playOnDismissAnim(super::dismiss); - } - - public ConfirmDialogFragment setMessage(@StringRes int text) { - this.text = text; - if (findViewById(R.id.confirm_message) != null) { - ((TextView) findViewById(R.id.confirm_message)).setText(text); - } - return this; - } - - public void showForResult(OnResult result) { - this.onResult = result; - show(); - } - - protected void playOnLoadAnim() { - View body = findViewById(R.id.frg_body); - body.setTranslationY(100); - body.animate().cancel(); - body.animate() - .translationY(0) - .setDuration(200) - .setInterpolator(EasingHelper.asInterpolator(Easing.InOutQuad)) - .start(); - playBackgroundHideInAnim(200); - } - - protected void playOnDismissAnim(Runnable runnable) { - View body = findViewById(R.id.frg_body); - body.animate().cancel(); - body.animate() - .translationY(100) - .setDuration(200) - .setInterpolator(EasingHelper.asInterpolator(Easing.InOutQuad)) - .setListener(new BaseAnimationListener() { - @Override - public void onAnimationEnd(Animator animation) { - if (runnable != null) { - runnable.run(); - } - } - }) - .start(); - playBackgroundHideOutAnim(200); - } - - - public interface OnResult { - void onAccept(boolean isAccepted); - } + private OnResult onResult; + + @StringRes + private int text; + + public ConfirmDialogFragment() { + setDismissOnBackgroundClick(true); + } + + @Override + protected int getLayoutID() { + return R.layout.frgdialog_confirm; + } + + @Override + protected void onLoadView() { + findViewById(R.id.okButton).setOnClickListener(v -> { + if (onResult != null) { + onResult.onAccept(true); + dismiss(); + } + }); + if (text != 0) { + ((TextView) findViewById(R.id.confirm_message)).setText(text); + } + playOnLoadAnim(); + } + + @Override + public void dismiss() { + playOnDismissAnim(super::dismiss); + } + + public ConfirmDialogFragment setMessage(@StringRes int text) { + this.text = text; + if (findViewById(R.id.confirm_message) != null) { + ((TextView) findViewById(R.id.confirm_message)).setText(text); + } + return this; + } + + public void showForResult(OnResult result) { + this.onResult = result; + show(); + } + + protected void playOnLoadAnim() { + View body = findViewById(R.id.frg_body); + body.setTranslationY(100); + body.animate().cancel(); + body.animate() + .translationY(0) + .setDuration(200) + .setInterpolator(EasingHelper.asInterpolator(Easing.InOutQuad)) + .start(); + playBackgroundHideInAnim(200); + } + + protected void playOnDismissAnim(Runnable runnable) { + View body = findViewById(R.id.frg_body); + body.animate().cancel(); + body.animate() + .translationY(100) + .setDuration(200) + .setInterpolator(EasingHelper.asInterpolator(Easing.InOutQuad)) + .setListener(new BaseAnimationListener() { + @Override + public void onAnimationEnd(Animator animation) { + if (runnable != null) { + runnable.run(); + } + } + }) + .start(); + playBackgroundHideOutAnim(200); + } + + + public interface OnResult { + void onAccept(boolean isAccepted); + } } diff --git a/src/com/edlplan/ui/fragment/FavoriteManagerFragment.java b/src/com/edlplan/ui/fragment/FavoriteManagerFragment.java index 22089359..55fb25fd 100644 --- a/src/com/edlplan/ui/fragment/FavoriteManagerFragment.java +++ b/src/com/edlplan/ui/fragment/FavoriteManagerFragment.java @@ -27,298 +27,298 @@ public class FavoriteManagerFragment extends BaseFragment { - private String selected; - - private FMAdapter adapter; - - private Runnable onLoadViewFunc; - - @Override - protected int getLayoutID() { - return R.layout.favorite_manager_dialog; - } - - @Override - protected void onLoadView() { - setDismissOnBackgroundClick(true); - GridLayoutManager layoutManager = new GridLayoutManager(getContext(), 2); - ((RecyclerView) findViewById(R.id.main_recycler_view)).setLayoutManager(layoutManager); - layoutManager.setOrientation(RecyclerView.VERTICAL); - - Button newFolder = findViewById(R.id.new_folder); - newFolder.setOnClickListener(v -> { - InputDialog dialog = new InputDialog(getContext()); - dialog.showForResult(s -> { - if (s.isEmpty()) return; - if (FavoriteLibrary.get().getMaps(s) == null && !s.equals(StringTable.get(R.string.favorite_default))) { - FavoriteLibrary.get().addFolder(s); - adapter.add(s); - } - }); - }); - - if (onLoadViewFunc != null) { - onLoadViewFunc.run(); - } - - playOnLoadAnim(); - } - - private void playOnLoadAnim() { - View body = findViewById(R.id.frg_body); - body.setTranslationY(600); - body.animate().cancel(); - body.animate() - .translationY(0) - .setDuration(200) - .start(); - playBackgroundHideInAnim(200); - } - - private void playEndAnim(Runnable action) { - View body = findViewById(R.id.frg_body); - body.animate().cancel(); - body.animate() - .translationXBy(50) - .alpha(0) - .setDuration(150) - .setInterpolator(EasingHelper.asInterpolator(Easing.OutQuad)) - .setListener(new BaseAnimationListener() { - @Override - public void onAnimationEnd(Animator animation) { - if (action != null) { - action.run(); - } - } - }) - .start(); - playBackgroundHideOutAnim(200); - } - - @Override - public void dismiss() { - playEndAnim(super::dismiss); - } - - public String getSelected() { - return selected; - } - - public void showToSelectFloder(OnSelectListener onSelectListener) { - onLoadViewFunc = () -> { - adapter = new SelectAdapter(onSelectListener); - ((RecyclerView) findViewById(R.id.main_recycler_view)).setAdapter(adapter); - }; - show(); - } - - public void showToAddToFloder(String track) { - onLoadViewFunc = () -> { - adapter = new AddAdapter(track); - ((RecyclerView) findViewById(R.id.main_recycler_view)).setAdapter(adapter); - }; - show(); - } - - public interface OnSelectListener { - void onSelect(String folder); - } - - private static class VH extends RecyclerView.ViewHolder { - - public TextView folderName; - - public Button button1; - - public Button button2; - - public View mainBody; - - public VH(View itemView) { - super(itemView); - mainBody = itemView.findViewById(R.id.mainBody); - folderName = itemView.findViewById(R.id.folder_name); - button1 = itemView.findViewById(R.id.button); - button2 = itemView.findViewById(R.id.button2); - } - } - - public abstract class FMAdapter extends RecyclerView.Adapter { - - protected List folders; - - public FMAdapter() { - load(); - } - - public void add(String folder) { - ArrayList tmp = new ArrayList<>(folders); - folders = new ArrayList<>(); - folders.add(tmp.get(0)); - folders.add(folder); - tmp.remove(tmp.get(0)); - folders.addAll(tmp); - notifyDataSetChanged(); - } - - protected void load() { - ArrayList tmp = new ArrayList<>(FavoriteLibrary.get().getFolders()); - Collections.sort(tmp); - folders = new ArrayList<>(); - folders.add(StringTable.get(R.string.favorite_default)); - folders.addAll(tmp); - } - - @NonNull - @Override - public VH onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { - return new VH(LayoutInflater.from(parent.getContext()).inflate(R.layout.favorite_folder_item, parent, false)); - } - - @Override - public int getItemCount() { - return folders.size(); - } - - } - - public class AddAdapter extends FMAdapter { - - private String track; - - public AddAdapter(String track) { - this.track = track; - } - - @Override - public void onBindViewHolder(@NonNull VH holder, int position) { - final String f = folders.get(position); - holder.folderName.setText(String.format("%s (%s)", - f, FavoriteLibrary.get().getMaps(f) == null ? "*" : ("" + FavoriteLibrary.get().getMaps(f).size()))); - holder.button1.setText(R.string.favorite_delete); - if (position == 0) { - holder.button2.setText("( • ̀ω•́ )✧"); - } else { - holder.button2.setText(FavoriteLibrary.get().inFolder(f, track) ? R.string.favorite_remove : R.string.favorite_add); - } - - holder.button1.setOnClickListener(new View.OnClickListener() { - boolean clicked = false; - boolean deleted = false; - - @Override - public void onClick(View v) { - if (clicked) { - FavoriteLibrary.get().remove(f); - deleted = true; - holder.button1.setTextColor(Color.argb(255, 255, 255, 255)); - load(); - notifyDataSetChanged(); - } else { - clicked = true; - holder.button1.setText(R.string.favorite_ensure); - holder.button1.setTextColor(Color.argb(255, 255, 0, 0)); - findViewById(R.id.main_recycler_view).postDelayed(() -> { - if (!deleted) { - clicked = false; - holder.button1.setTextColor(Color.argb(255, 0, 0, 0)); - holder.button1.setText(R.string.favorite_delete); - } - }, 2000); - } - } - }); - - holder.button2.setOnClickListener(view -> { - if (FavoriteLibrary.get().inFolder(f, track)) { - FavoriteLibrary.get().remove(f, track); - holder.folderName.setText(String.format("%s (%s)", - f, FavoriteLibrary.get().getMaps(f) == null ? "*" : ("" + FavoriteLibrary.get().getMaps(f).size()))); - holder.button2.setText(R.string.favorite_add); - } else { - FavoriteLibrary.get().add(f, track); - holder.folderName.setText(String.format("%s (%s)", - f, FavoriteLibrary.get().getMaps(f) == null ? "*" : ("" + FavoriteLibrary.get().getMaps(f).size()))); - holder.button2.setText(R.string.favorite_remove); - } - }); - - if (position == 0) { - holder.button1.setOnClickListener(view -> { - ToastLogger.showText(StringTable.get(R.string.favorite_warning_on_delete_default), false); - }); - holder.button2.setOnClickListener(view -> { - }); - } - } - } - - public class SelectAdapter extends FMAdapter { - - private OnSelectListener onSelectListener; - - public SelectAdapter(OnSelectListener onSelectListener) { - this.onSelectListener = onSelectListener; - } - - @Override - public void onBindViewHolder(@NonNull VH holder, int position) { - final String f = folders.get(position); - holder.folderName.setText(String.format("%s (%s)", - f, FavoriteLibrary.get().getMaps(f) == null ? "*" : ("" + FavoriteLibrary.get().getMaps(f).size()))); - holder.button1.setText(R.string.favorite_delete); - holder.button2.setText(R.string.favorite_select); - - View.OnClickListener mainClick; - if (position != 0) { - mainClick = view -> { - selected = folders.get(position); - dismiss(); - onSelectListener.onSelect(selected); - }; - } else { - mainClick = view -> { - selected = folders.get(position); - dismiss(); - onSelectListener.onSelect(null); - }; - } - - holder.button2.setOnClickListener(mainClick); - holder.mainBody.setOnClickListener(mainClick); - - holder.button1.setOnClickListener(new View.OnClickListener() { - boolean clicked = false; - boolean deleted = false; - - @Override - public void onClick(View v) { - if (clicked) { - FavoriteLibrary.get().remove(f); - deleted = true; - holder.button1.setTextColor(Color.argb(255, 255, 255, 255)); - load(); - notifyDataSetChanged(); - } else { - clicked = true; - holder.button1.setText(R.string.favorite_ensure); - holder.button1.setTextColor(Color.argb(255, 255, 0, 0)); - findViewById(R.id.main_recycler_view).postDelayed(() -> { - if (!deleted) { - clicked = false; - holder.button1.setTextColor(Color.argb(255, 255, 255, 255)); - holder.button1.setText(R.string.favorite_delete); - } - }, 2000); - } - } - }); - - if (position == 0) { - holder.button1.setOnClickListener(view -> { - ToastLogger.showText(StringTable.get(R.string.favorite_warning_on_delete_default), false); - }); - } - } - } + private String selected; + + private FMAdapter adapter; + + private Runnable onLoadViewFunc; + + @Override + protected int getLayoutID() { + return R.layout.favorite_manager_dialog; + } + + @Override + protected void onLoadView() { + setDismissOnBackgroundClick(true); + GridLayoutManager layoutManager = new GridLayoutManager(getContext(), 2); + ((RecyclerView) findViewById(R.id.main_recycler_view)).setLayoutManager(layoutManager); + layoutManager.setOrientation(RecyclerView.VERTICAL); + + Button newFolder = findViewById(R.id.new_folder); + newFolder.setOnClickListener(v -> { + InputDialog dialog = new InputDialog(getContext()); + dialog.showForResult(s -> { + if (s.isEmpty()) return; + if (FavoriteLibrary.get().getMaps(s) == null && !s.equals(StringTable.get(R.string.favorite_default))) { + FavoriteLibrary.get().addFolder(s); + adapter.add(s); + } + }); + }); + + if (onLoadViewFunc != null) { + onLoadViewFunc.run(); + } + + playOnLoadAnim(); + } + + private void playOnLoadAnim() { + View body = findViewById(R.id.frg_body); + body.setTranslationY(600); + body.animate().cancel(); + body.animate() + .translationY(0) + .setDuration(200) + .start(); + playBackgroundHideInAnim(200); + } + + private void playEndAnim(Runnable action) { + View body = findViewById(R.id.frg_body); + body.animate().cancel(); + body.animate() + .translationXBy(50) + .alpha(0) + .setDuration(150) + .setInterpolator(EasingHelper.asInterpolator(Easing.OutQuad)) + .setListener(new BaseAnimationListener() { + @Override + public void onAnimationEnd(Animator animation) { + if (action != null) { + action.run(); + } + } + }) + .start(); + playBackgroundHideOutAnim(200); + } + + @Override + public void dismiss() { + playEndAnim(super::dismiss); + } + + public String getSelected() { + return selected; + } + + public void showToSelectFloder(OnSelectListener onSelectListener) { + onLoadViewFunc = () -> { + adapter = new SelectAdapter(onSelectListener); + ((RecyclerView) findViewById(R.id.main_recycler_view)).setAdapter(adapter); + }; + show(); + } + + public void showToAddToFloder(String track) { + onLoadViewFunc = () -> { + adapter = new AddAdapter(track); + ((RecyclerView) findViewById(R.id.main_recycler_view)).setAdapter(adapter); + }; + show(); + } + + public interface OnSelectListener { + void onSelect(String folder); + } + + private static class VH extends RecyclerView.ViewHolder { + + public TextView folderName; + + public Button button1; + + public Button button2; + + public View mainBody; + + public VH(View itemView) { + super(itemView); + mainBody = itemView.findViewById(R.id.mainBody); + folderName = itemView.findViewById(R.id.folder_name); + button1 = itemView.findViewById(R.id.button); + button2 = itemView.findViewById(R.id.button2); + } + } + + public abstract class FMAdapter extends RecyclerView.Adapter { + + protected List folders; + + public FMAdapter() { + load(); + } + + public void add(String folder) { + ArrayList tmp = new ArrayList<>(folders); + folders = new ArrayList<>(); + folders.add(tmp.get(0)); + folders.add(folder); + tmp.remove(tmp.get(0)); + folders.addAll(tmp); + notifyDataSetChanged(); + } + + protected void load() { + ArrayList tmp = new ArrayList<>(FavoriteLibrary.get().getFolders()); + Collections.sort(tmp); + folders = new ArrayList<>(); + folders.add(StringTable.get(R.string.favorite_default)); + folders.addAll(tmp); + } + + @NonNull + @Override + public VH onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { + return new VH(LayoutInflater.from(parent.getContext()).inflate(R.layout.favorite_folder_item, parent, false)); + } + + @Override + public int getItemCount() { + return folders.size(); + } + + } + + public class AddAdapter extends FMAdapter { + + private String track; + + public AddAdapter(String track) { + this.track = track; + } + + @Override + public void onBindViewHolder(@NonNull VH holder, int position) { + final String f = folders.get(position); + holder.folderName.setText(String.format("%s (%s)", + f, FavoriteLibrary.get().getMaps(f) == null ? "*" : ("" + FavoriteLibrary.get().getMaps(f).size()))); + holder.button1.setText(R.string.favorite_delete); + if (position == 0) { + holder.button2.setText("( • ̀ω•́ )✧"); + } else { + holder.button2.setText(FavoriteLibrary.get().inFolder(f, track) ? R.string.favorite_remove : R.string.favorite_add); + } + + holder.button1.setOnClickListener(new View.OnClickListener() { + boolean clicked = false; + boolean deleted = false; + + @Override + public void onClick(View v) { + if (clicked) { + FavoriteLibrary.get().remove(f); + deleted = true; + holder.button1.setTextColor(Color.argb(255, 255, 255, 255)); + load(); + notifyDataSetChanged(); + } else { + clicked = true; + holder.button1.setText(R.string.favorite_ensure); + holder.button1.setTextColor(Color.argb(255, 255, 0, 0)); + findViewById(R.id.main_recycler_view).postDelayed(() -> { + if (!deleted) { + clicked = false; + holder.button1.setTextColor(Color.argb(255, 0, 0, 0)); + holder.button1.setText(R.string.favorite_delete); + } + }, 2000); + } + } + }); + + holder.button2.setOnClickListener(view -> { + if (FavoriteLibrary.get().inFolder(f, track)) { + FavoriteLibrary.get().remove(f, track); + holder.folderName.setText(String.format("%s (%s)", + f, FavoriteLibrary.get().getMaps(f) == null ? "*" : ("" + FavoriteLibrary.get().getMaps(f).size()))); + holder.button2.setText(R.string.favorite_add); + } else { + FavoriteLibrary.get().add(f, track); + holder.folderName.setText(String.format("%s (%s)", + f, FavoriteLibrary.get().getMaps(f) == null ? "*" : ("" + FavoriteLibrary.get().getMaps(f).size()))); + holder.button2.setText(R.string.favorite_remove); + } + }); + + if (position == 0) { + holder.button1.setOnClickListener(view -> { + ToastLogger.showText(StringTable.get(R.string.favorite_warning_on_delete_default), false); + }); + holder.button2.setOnClickListener(view -> { + }); + } + } + } + + public class SelectAdapter extends FMAdapter { + + private OnSelectListener onSelectListener; + + public SelectAdapter(OnSelectListener onSelectListener) { + this.onSelectListener = onSelectListener; + } + + @Override + public void onBindViewHolder(@NonNull VH holder, int position) { + final String f = folders.get(position); + holder.folderName.setText(String.format("%s (%s)", + f, FavoriteLibrary.get().getMaps(f) == null ? "*" : ("" + FavoriteLibrary.get().getMaps(f).size()))); + holder.button1.setText(R.string.favorite_delete); + holder.button2.setText(R.string.favorite_select); + + View.OnClickListener mainClick; + if (position != 0) { + mainClick = view -> { + selected = folders.get(position); + dismiss(); + onSelectListener.onSelect(selected); + }; + } else { + mainClick = view -> { + selected = folders.get(position); + dismiss(); + onSelectListener.onSelect(null); + }; + } + + holder.button2.setOnClickListener(mainClick); + holder.mainBody.setOnClickListener(mainClick); + + holder.button1.setOnClickListener(new View.OnClickListener() { + boolean clicked = false; + boolean deleted = false; + + @Override + public void onClick(View v) { + if (clicked) { + FavoriteLibrary.get().remove(f); + deleted = true; + holder.button1.setTextColor(Color.argb(255, 255, 255, 255)); + load(); + notifyDataSetChanged(); + } else { + clicked = true; + holder.button1.setText(R.string.favorite_ensure); + holder.button1.setTextColor(Color.argb(255, 255, 0, 0)); + findViewById(R.id.main_recycler_view).postDelayed(() -> { + if (!deleted) { + clicked = false; + holder.button1.setTextColor(Color.argb(255, 255, 255, 255)); + holder.button1.setText(R.string.favorite_delete); + } + }, 2000); + } + } + }); + + if (position == 0) { + holder.button1.setOnClickListener(view -> { + ToastLogger.showText(StringTable.get(R.string.favorite_warning_on_delete_default), false); + }); + } + } + } } diff --git a/src/com/edlplan/ui/fragment/FilterMenuFragment.java b/src/com/edlplan/ui/fragment/FilterMenuFragment.java index dc02c1dc..6a37ae69 100644 --- a/src/com/edlplan/ui/fragment/FilterMenuFragment.java +++ b/src/com/edlplan/ui/fragment/FilterMenuFragment.java @@ -29,300 +29,300 @@ public class FilterMenuFragment extends BaseFragment implements IFilterMenu { - private static Context configContext = null; - private static String savedFolder; - private static boolean savedFavOnly = false; - private static String savedFilter = null; - private Scene scene = null; - private EditText filter; - private SongMenu menu; - private CheckBox favoritesOnly; - private TextView favoriteFolder; - private Button orderButton; - //private TextView openMapInfo; - - private Updater updater; - - public FilterMenuFragment() { - setDismissOnBackgroundClick(true); - } - - - @Override - protected int getLayoutID() { - return R.layout.fragment_filtermenu; - } - - @Override - protected void onLoadView() { - reloadViewData(); - playOnLoadAnim(); - } - - private void playOnLoadAnim() { - View body = findViewById(R.id.frg_body); - body.setAlpha(0); - body.setTranslationX(400); - body.animate().cancel(); - body.animate() - .translationX(0) - .alpha(1) - .setInterpolator(EasingHelper.asInterpolator(Easing.InOutQuad)) - .setDuration(150) - .start(); - playBackgroundHideInAnim(150); - } - - private void playEndAnim(Runnable action) { - View body = findViewById(R.id.frg_body); - body.animate().cancel(); - body.animate() - .translationXBy(400) - .alpha(0) - .setDuration(200) - .setInterpolator(EasingHelper.asInterpolator(Easing.InOutQuad)) - .setListener(new BaseAnimationListener() { - @Override - public void onAnimationEnd(Animator animation) { - if (action != null) { - action.run(); - } - } - }) - .start(); - playBackgroundHideOutAnim(200); - } - - private void updateFavChecked() { - favoritesOnly.setText(favoritesOnly.isChecked() ? - R.string.menu_search_favsenabled : R.string.menu_search_favsdisabled); - } - - private void updateOrderButton() { - SongMenu.SortOrder order = getOrder(); - @StringRes int s; - switch (order) { - case Title: - s = R.string.menu_search_sort_title; - break; - case Artist: - s = R.string.menu_search_sort_artist; - break; - case Date: - s = R.string.menu_search_sort_date; - break; - case Bpm: - s = R.string.menu_search_sort_bpm; - break; - case Stars: - s = R.string.menu_search_sort_stars; - break; - case Length: - s = R.string.menu_search_sort_length; - break; - default: - s = R.string.menu_search_sort_creator; - break; - } - orderButton.setText(s); - } - - private void updateFavFolderText() { - if (savedFolder != null) { - favoriteFolder.setText(savedFolder); - } - if (favoriteFolder.getText().length() == 0) { - favoriteFolder.setText(StringTable.get(R.string.favorite_default)); - } - } - - @Override - public void dismiss() { - playEndAnim(super::dismiss); - } - - @Override - public String getFilter() { - return filter == null ? "" : (filter.getText() == null ? "" : filter.getText().toString()); - } - - @Override - public SongMenu.SortOrder getOrder() { - final SharedPreferences prefs = PreferenceManager - .getDefaultSharedPreferences(configContext); - final int sortOrder = prefs.getInt("sortorder", 0); - return SongMenu.SortOrder.values()[sortOrder % SongMenu.SortOrder.values().length]; - } - - @SuppressLint("ApplySharedPref") - private void saveOrder(SongMenu.SortOrder order) { - PreferenceManager - .getDefaultSharedPreferences(configContext) - .edit() - .putInt("sortorder", order.ordinal()) - .commit(); - } - - private void nextOrder() { - SongMenu.SortOrder order = getOrder(); - order = SongMenu.SortOrder.values()[(order.ordinal() + 1) % SongMenu.SortOrder.values().length]; - saveOrder(order); - } - - @Override - public boolean isFavoritesOnly() { - return favoritesOnly.isChecked(); - } - - @Override - public String getFavoriteFolder() { - return favoriteFolder == null ? - null : StringTable.get(R.string.favorite_default).equals(favoriteFolder.getText().toString()) ? - null : favoriteFolder.getText().toString(); - } - - @Override - public void loadConfig(Context context) { - configContext = context; - reloadViewData(); - } - - @Override - public Scene getScene() { - return scene; - } - - @Override - public void hideMenu() { - updateUpdater(); - scene = null; - dismiss(); - } - - @Override - public void showMenu(SongMenu parent) { - this.menu = parent; - scene = new Scene(); - scene.setBackgroundEnabled(false); - if (parent != null) { - //parent.scene.setChildScene( - // scene, false, - // true, true); - } - updater = new Updater() { - @Override - public Runnable createEventRunnable() { - return () -> parent.loadFilter(FilterMenuFragment.this); - } - - @Override - public void postEvent(Runnable r) { - parent.getScene().postRunnable(r); - } - }; - show(); - } - - @Override - public void onDetach() { - super.onDetach(); - if (menu != null) { - final SongMenu menu = this.menu; - menu.getScene().postRunnable(() -> { - //menu.getScene().clearChildScene(); - menu.loadFilter(this); - }); - this.menu = null; - } - scene = null; - } - - @Override - public void onAttach(Context context) { - super.onAttach(context); - reloadViewData(); - } - - private void updateUpdater() { - if (updater != null) { - updater.update(); - } - } - - //private void openMapinfoDialog() { - // MapInfoFragment dialog = new MapInfoFragment(); - // TrackInfo selectedTrack = GlobalManager.getInstance().getSongMenu().getSelectedTrack(); - // DifficultyReCalculator diffReCalculator = new DifficultyReCalculator(); - // if (selectedTrack != null) - // dialog.showWithMap(selectedTrack, ModMenu.getInstance().getSpeed(), diffReCalculator.getCS(selectedTrack)); - // diffReCalculator = null; - //} - - public void reloadViewData() { - if (isCreated()) { - filter = findViewById(R.id.searchEditText); - favoritesOnly = findViewById(R.id.showFav); - orderButton = findViewById(R.id.sortButton); - favoriteFolder = findViewById(R.id.favFolder); - //openMapInfo = findViewById(R.id.openMapInfo); - - favoritesOnly.setOnCheckedChangeListener((buttonView, isChecked) -> { - updateFavChecked(); - updateUpdater(); - savedFavOnly = isChecked; - }); - orderButton.setOnClickListener(v -> { - nextOrder(); - updateOrderButton(); - updateUpdater(); - }); - findViewById(R.id.favFolderLayout).setOnClickListener(v -> { - FavoriteManagerFragment favoriteManagerFragment = new FavoriteManagerFragment(); - favoriteManagerFragment.showToSelectFloder(t -> { - savedFolder = t; - favoriteFolder.setText(t == null ? StringTable.get(R.string.favorite_default) : t); - updateUpdater(); - }); - }); - filter.setOnEditorActionListener((v, actionId, event) -> { - if (event == null) { - return false; - } - - if (event.getKeyCode() == KeyEvent.KEYCODE_ENTER) { - hideMenu(); - return true; - } - return false; - }); - filter.addTextChangedListener(new TextWatcher() { - @Override - public void beforeTextChanged(CharSequence s, int start, int count, int after) { - } - - @Override - public void onTextChanged(CharSequence s, int start, int before, int count) { - } - - @Override - public void afterTextChanged(Editable s) { - savedFilter = s.toString(); - updateUpdater(); - } - }); - - //openMapInfo.setOnClickListener(v -> { - // openMapinfoDialog(); - //}); - //openMapInfo.setText("MapInfo"); - - favoritesOnly.setChecked(savedFavOnly); - if (savedFilter != null && savedFilter.length() > 0) { - filter.setText(savedFilter); - } - updateOrderButton(); - updateFavChecked(); - updateFavFolderText(); - } - } + private static Context configContext = null; + private static String savedFolder; + private static boolean savedFavOnly = false; + private static String savedFilter = null; + private Scene scene = null; + private EditText filter; + private SongMenu menu; + private CheckBox favoritesOnly; + private TextView favoriteFolder; + private Button orderButton; + //private TextView openMapInfo; + + private Updater updater; + + public FilterMenuFragment() { + setDismissOnBackgroundClick(true); + } + + + @Override + protected int getLayoutID() { + return R.layout.fragment_filtermenu; + } + + @Override + protected void onLoadView() { + reloadViewData(); + playOnLoadAnim(); + } + + private void playOnLoadAnim() { + View body = findViewById(R.id.frg_body); + body.setAlpha(0); + body.setTranslationX(400); + body.animate().cancel(); + body.animate() + .translationX(0) + .alpha(1) + .setInterpolator(EasingHelper.asInterpolator(Easing.InOutQuad)) + .setDuration(150) + .start(); + playBackgroundHideInAnim(150); + } + + private void playEndAnim(Runnable action) { + View body = findViewById(R.id.frg_body); + body.animate().cancel(); + body.animate() + .translationXBy(400) + .alpha(0) + .setDuration(200) + .setInterpolator(EasingHelper.asInterpolator(Easing.InOutQuad)) + .setListener(new BaseAnimationListener() { + @Override + public void onAnimationEnd(Animator animation) { + if (action != null) { + action.run(); + } + } + }) + .start(); + playBackgroundHideOutAnim(200); + } + + private void updateFavChecked() { + favoritesOnly.setText(favoritesOnly.isChecked() ? + R.string.menu_search_favsenabled : R.string.menu_search_favsdisabled); + } + + private void updateOrderButton() { + SongMenu.SortOrder order = getOrder(); + @StringRes int s; + switch (order) { + case Title: + s = R.string.menu_search_sort_title; + break; + case Artist: + s = R.string.menu_search_sort_artist; + break; + case Date: + s = R.string.menu_search_sort_date; + break; + case Bpm: + s = R.string.menu_search_sort_bpm; + break; + case Stars: + s = R.string.menu_search_sort_stars; + break; + case Length: + s = R.string.menu_search_sort_length; + break; + default: + s = R.string.menu_search_sort_creator; + break; + } + orderButton.setText(s); + } + + private void updateFavFolderText() { + if (savedFolder != null) { + favoriteFolder.setText(savedFolder); + } + if (favoriteFolder.getText().length() == 0) { + favoriteFolder.setText(StringTable.get(R.string.favorite_default)); + } + } + + @Override + public void dismiss() { + playEndAnim(super::dismiss); + } + + @Override + public String getFilter() { + return filter == null ? "" : (filter.getText() == null ? "" : filter.getText().toString()); + } + + @Override + public SongMenu.SortOrder getOrder() { + final SharedPreferences prefs = PreferenceManager + .getDefaultSharedPreferences(configContext); + final int sortOrder = prefs.getInt("sortorder", 0); + return SongMenu.SortOrder.values()[sortOrder % SongMenu.SortOrder.values().length]; + } + + @SuppressLint("ApplySharedPref") + private void saveOrder(SongMenu.SortOrder order) { + PreferenceManager + .getDefaultSharedPreferences(configContext) + .edit() + .putInt("sortorder", order.ordinal()) + .commit(); + } + + private void nextOrder() { + SongMenu.SortOrder order = getOrder(); + order = SongMenu.SortOrder.values()[(order.ordinal() + 1) % SongMenu.SortOrder.values().length]; + saveOrder(order); + } + + @Override + public boolean isFavoritesOnly() { + return favoritesOnly.isChecked(); + } + + @Override + public String getFavoriteFolder() { + return favoriteFolder == null ? + null : StringTable.get(R.string.favorite_default).equals(favoriteFolder.getText().toString()) ? + null : favoriteFolder.getText().toString(); + } + + @Override + public void loadConfig(Context context) { + configContext = context; + reloadViewData(); + } + + @Override + public Scene getScene() { + return scene; + } + + @Override + public void hideMenu() { + updateUpdater(); + scene = null; + dismiss(); + } + + @Override + public void showMenu(SongMenu parent) { + this.menu = parent; + scene = new Scene(); + scene.setBackgroundEnabled(false); + if (parent != null) { + //parent.scene.setChildScene( + // scene, false, + // true, true); + } + updater = new Updater() { + @Override + public Runnable createEventRunnable() { + return () -> parent.loadFilter(FilterMenuFragment.this); + } + + @Override + public void postEvent(Runnable r) { + parent.getScene().postRunnable(r); + } + }; + show(); + } + + @Override + public void onDetach() { + super.onDetach(); + if (menu != null) { + final SongMenu menu = this.menu; + menu.getScene().postRunnable(() -> { + //menu.getScene().clearChildScene(); + menu.loadFilter(this); + }); + this.menu = null; + } + scene = null; + } + + @Override + public void onAttach(Context context) { + super.onAttach(context); + reloadViewData(); + } + + private void updateUpdater() { + if (updater != null) { + updater.update(); + } + } + + //private void openMapinfoDialog() { + // MapInfoFragment dialog = new MapInfoFragment(); + // TrackInfo selectedTrack = GlobalManager.getInstance().getSongMenu().getSelectedTrack(); + // DifficultyReCalculator diffReCalculator = new DifficultyReCalculator(); + // if (selectedTrack != null) + // dialog.showWithMap(selectedTrack, ModMenu.getInstance().getSpeed(), diffReCalculator.getCS(selectedTrack)); + // diffReCalculator = null; + //} + + public void reloadViewData() { + if (isCreated()) { + filter = findViewById(R.id.searchEditText); + favoritesOnly = findViewById(R.id.showFav); + orderButton = findViewById(R.id.sortButton); + favoriteFolder = findViewById(R.id.favFolder); + //openMapInfo = findViewById(R.id.openMapInfo); + + favoritesOnly.setOnCheckedChangeListener((buttonView, isChecked) -> { + updateFavChecked(); + updateUpdater(); + savedFavOnly = isChecked; + }); + orderButton.setOnClickListener(v -> { + nextOrder(); + updateOrderButton(); + updateUpdater(); + }); + findViewById(R.id.favFolderLayout).setOnClickListener(v -> { + FavoriteManagerFragment favoriteManagerFragment = new FavoriteManagerFragment(); + favoriteManagerFragment.showToSelectFloder(t -> { + savedFolder = t; + favoriteFolder.setText(t == null ? StringTable.get(R.string.favorite_default) : t); + updateUpdater(); + }); + }); + filter.setOnEditorActionListener((v, actionId, event) -> { + if (event == null) { + return false; + } + + if (event.getKeyCode() == KeyEvent.KEYCODE_ENTER) { + hideMenu(); + return true; + } + return false; + }); + filter.addTextChangedListener(new TextWatcher() { + @Override + public void beforeTextChanged(CharSequence s, int start, int count, int after) { + } + + @Override + public void onTextChanged(CharSequence s, int start, int before, int count) { + } + + @Override + public void afterTextChanged(Editable s) { + savedFilter = s.toString(); + updateUpdater(); + } + }); + + //openMapInfo.setOnClickListener(v -> { + // openMapinfoDialog(); + //}); + //openMapInfo.setText("MapInfo"); + + favoritesOnly.setChecked(savedFavOnly); + if (savedFilter != null && savedFilter.length() > 0) { + filter.setText(savedFilter); + } + updateOrderButton(); + updateFavChecked(); + updateFavFolderText(); + } + } } diff --git a/src/com/edlplan/ui/fragment/InGameSettingMenu.java b/src/com/edlplan/ui/fragment/InGameSettingMenu.java index a332760f..c055f3f3 100644 --- a/src/com/edlplan/ui/fragment/InGameSettingMenu.java +++ b/src/com/edlplan/ui/fragment/InGameSettingMenu.java @@ -26,334 +26,334 @@ public class InGameSettingMenu extends BaseFragment { - private static InGameSettingMenu menu; - private CheckBox enableStoryboard; - private CheckBox showScoreboard; - private CheckBox enableNCWhenSpeedChange; - private CheckBox enableSpeedChange; - private CheckBox enableForceAR; - private SeekBar backgroundBrightness; - private SeekBar changeSpeed; - private SeekBar forceAR; - private SeekBar flashlightFollowDelay; - - private final int greenColor = Color.parseColor("#62c700"); - - public static InGameSettingMenu getInstance() { - if (menu == null) { - menu = new InGameSettingMenu(); - } - return menu; - } - - @Override - protected int getLayoutID() { - return R.layout.fragment_in_game_option; - } - - @Override - protected void onLoadView() { - reload(); - findViewById(R.id.frg_header).animate().cancel(); - findViewById(R.id.frg_header).setAlpha(0); - findViewById(R.id.frg_header).setTranslationY(100); - findViewById(R.id.frg_header).animate() - .alpha(1) - .translationY(0) - .setDuration(200) - .setInterpolator(EasingHelper.asInterpolator(Easing.InOutQuad)) - .start(); - } - - private void applyCustomModColor() { - final TextView customizedModsText = findViewById(R.id.customize_mods); - int color = ModMenu.getInstance().getFLfollowDelay() != FlashLightEntity.defaultMoveDelayS ? Color.RED : greenColor; - customizedModsText.setTextColor(color); - } - - @SuppressLint({"ClickableViewAccessibility", "ApplySharedPref"}) - private void reload() { - View showMoreButton = findViewById(R.id.showMoreButton); - if (showMoreButton == null) { - return; - } - showMoreButton.setOnTouchListener((v, event) -> { - if (event.getAction() == TouchEvent.ACTION_DOWN) { - v.animate().cancel(); - v.animate().scaleY(0.9f).scaleX(0.9f).translationY(v.getHeight() * 0.1f).setDuration(100).start(); - toggleSettingPanel(); - return true; - } else if (event.getAction() == TouchEvent.ACTION_UP) { - v.animate().cancel(); - v.animate().scaleY(1).scaleX(1).setDuration(100).translationY(0).start(); - if (event.getX() < v.getWidth() - && event.getY() < v.getHeight() - && event.getX() > 0 - && event.getY() > 0) { - } - return true; - } - return false; - }); - - findViewById(R.id.frg_background).setClickable(false); - - enableStoryboard = findViewById(R.id.enableStoryboard); - enableStoryboard.setChecked(Config.isEnableStoryboard()); - enableStoryboard.setOnCheckedChangeListener((buttonView, isChecked) -> { - Config.setEnableStoryboard(isChecked); - PreferenceManager.getDefaultSharedPreferences(getContext()).edit() - .putBoolean("enableStoryboard", isChecked) - .commit(); - }); - - showScoreboard = findViewById(R.id.showScoreboard); - showScoreboard.setChecked(Config.isShowScoreboard()); - showScoreboard.setOnCheckedChangeListener((buttonView, isChecked) -> { - Config.setShowScoreboard(isChecked); - PreferenceManager.getDefaultSharedPreferences(getContext()).edit() - .putBoolean("showscoreboard", isChecked) - .commit(); - }); - - enableNCWhenSpeedChange = findViewById(R.id.enableNCwhenSpeedChange); - enableNCWhenSpeedChange.setChecked(ModMenu.getInstance().isEnableNCWhenSpeedChange()); - enableNCWhenSpeedChange.setOnCheckedChangeListener((buttonView, isChecked) -> { - ModMenu.getInstance().setEnableNCWhenSpeedChange(isChecked); - }); - - enableSpeedChange = findViewById(R.id.enableSpeedChange); - enableSpeedChange.setChecked(ModMenu.getInstance().getChangeSpeed() != 1.0f); - enableSpeedChange.setOnCheckedChangeListener((buttonView, isChecked) -> { - if (!isChecked) { - ModMenu.getInstance().setChangeSpeed(1.0f); - ((TextView) findViewById(R.id.changeSpeedText)).setText(String.format(Locale.getDefault(), "%.2fx", ModMenu.getInstance().getChangeSpeed())); - changeSpeed.setProgress(10); - ModMenu.getInstance().updateMultiplierText(); - } - else if(ModMenu.getInstance().getChangeSpeed() == 1.0f){ - enableSpeedChange.setChecked(false); - } - }); - - enableForceAR = findViewById(R.id.enableForceAR); - enableForceAR.setChecked(ModMenu.getInstance().isEnableForceAR()); - enableForceAR.setOnCheckedChangeListener((buttonView, isChecked) -> { - ModMenu.getInstance().setEnableForceAR(isChecked); - ModMenu.getInstance().updateMultiplierText(); - }); - - backgroundBrightness = findViewById(R.id.backgroundBrightnessBar); - backgroundBrightness.setProgress( - PreferenceManager.getDefaultSharedPreferences(getContext()).getInt("bgbrightness", 25)); - backgroundBrightness.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { - @Override - public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { - ((TextView) findViewById(R.id.brightPreviewText)).setText(String.valueOf(progress)); - ((TextView) findViewById(R.id.bgBrightnessText)).setText(progress + "%"); - int p = Math.round(FMath.clamp(255 * (progress / 100f), 0, 255)); - findViewById(R.id.brightnessPreview).setBackgroundColor(Color.argb(255, p, p, p)); - } - - @Override - public void onStartTrackingTouch(SeekBar seekBar) { - findViewById(R.id.brightnessPreviewLayout).setVisibility(View.VISIBLE); - int progress = seekBar.getProgress(); - ((TextView) findViewById(R.id.brightPreviewText)).setText(String.valueOf(progress)); - ((TextView) findViewById(R.id.bgBrightnessText)).setText(progress + "%"); - int p = Math.round(FMath.clamp(255 * (progress / 100f), 0, 255)); - findViewById(R.id.brightnessPreview).setBackgroundColor(Color.argb(255, p, p, p)); - } - - @Override - public void onStopTrackingTouch(SeekBar seekBar) { - findViewById(R.id.brightnessPreviewLayout).setVisibility(View.GONE); - int progress = seekBar.getProgress(); - ((TextView) findViewById(R.id.bgBrightnessText)).setText(progress + "%"); - Config.setBackgroundBrightness(seekBar.getProgress() / 100f); - PreferenceManager.getDefaultSharedPreferences(getContext()) - .edit() - .putInt("bgbrightness", progress) - .commit(); - } - }); - ((TextView) findViewById(R.id.bgBrightnessText)).setText( - PreferenceManager.getDefaultSharedPreferences(getContext()).getInt("bgbrightness", 25) + "%"); - - changeSpeed = findViewById(R.id.changeSpeedBar); - changeSpeed.setProgress((int)(ModMenu.getInstance().getChangeSpeed() * 20 - 10)); - changeSpeed.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { - @Override - public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { - float p = 0.5f + 0.05f * progress; - ((TextView) findViewById(R.id.changeSpeedText)).setText(String.format(Locale.getDefault(), "%.2fx", p)); - if (p == 1.0f){ - enableSpeedChange.setChecked(false); - } - else { - enableSpeedChange.setChecked(true); - ModMenu.getInstance().updateMultiplierText(); - } - } - - @Override - public void onStartTrackingTouch(SeekBar seekBar) { - int progress = seekBar.getProgress(); - float p = 0.5f + 0.05f * progress; - ((TextView) findViewById(R.id.changeSpeedText)).setText(String.format(Locale.getDefault(), "%.2fx", p)); - if (p == 1.0f){ - enableSpeedChange.setChecked(false); - } - else { - enableSpeedChange.setChecked(true); - ModMenu.getInstance().updateMultiplierText(); - } - } - - @Override - public void onStopTrackingTouch(SeekBar seekBar) { - int progress = seekBar.getProgress(); - float p = 0.5f + 0.05f * progress; - ((TextView) findViewById(R.id.changeSpeedText)).setText(String.format(Locale.getDefault(), "%.2fx", p)); - ModMenu.getInstance().setChangeSpeed(p); - if (p == 1.0f){ - enableSpeedChange.setChecked(false); - } - else { - enableSpeedChange.setChecked(true); - ModMenu.getInstance().updateMultiplierText(); - } - } - }); - ((TextView) findViewById(R.id.changeSpeedText)).setText(String.format(Locale.getDefault(), "%.2fx", ModMenu.getInstance().getChangeSpeed())); - - forceAR = findViewById(R.id.forceARBar); - forceAR.setProgress((int)(ModMenu.getInstance().getForceAR() * 10)); - forceAR.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { - @Override - public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { - float p = 0.1f * progress; - ((TextView) findViewById(R.id.forceARText)).setText(String.format(Locale.getDefault(), "AR%.1f", p)); - if(ModMenu.getInstance().isEnableForceAR()){ - ModMenu.getInstance().updateMultiplierText(); - } - } - - @Override - public void onStartTrackingTouch(SeekBar seekBar) { - int progress = seekBar.getProgress(); - float p = 0.1f * progress; - ((TextView) findViewById(R.id.forceARText)).setText(String.format(Locale.getDefault(), "AR%.1f", p)); - if(ModMenu.getInstance().isEnableForceAR()){ - ModMenu.getInstance().updateMultiplierText(); - } - } - - @Override - public void onStopTrackingTouch(SeekBar seekBar) { - int progress = seekBar.getProgress(); - float p = 0.1f * progress; - ((TextView) findViewById(R.id.forceARText)).setText(String.format(Locale.getDefault(), "AR%.1f", p)); - ModMenu.getInstance().setForceAR(p); - if(ModMenu.getInstance().isEnableForceAR()){ - ModMenu.getInstance().updateMultiplierText(); - } - } - }); - - ((TextView) findViewById(R.id.forceARText)).setText(String.format(Locale.getDefault(), "AR%.1f", ModMenu.getInstance().getForceAR())); - - flashlightFollowDelay = findViewById(R.id.flashlightFollowDelayBar); - flashlightFollowDelay.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { - @Override - public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { - ModMenu.getInstance().setFLfollowDelay((float) Math.round(progress * 1200f) / (10f * 1000f)); - applyCustomModColor(); - ((TextView) findViewById(R.id.flashlightFollowDelayText)) - .setText(String.format(Locale.getDefault(), "%.1fms", progress * FlashLightEntity.defaultMoveDelayMS)); - } - - @Override - public void onStartTrackingTouch(SeekBar seekBar) {} - - @Override - public void onStopTrackingTouch(SeekBar seekBar) {} - }); - ((TextView) findViewById(R.id.forceARText)).setText(String.format("AR%.1f", ModMenu.getInstance().getForceAR())); - } - - @Override - public void show() { - super.show(); - } - - @Override - public void dismiss() { - super.dismiss(); - ModMenu.getInstance().hideByFrag(); - } - - public boolean isSettingPanelShow() { - return findViewById(R.id.fullLayout) != null && Math.abs(findViewById(R.id.fullLayout).getTranslationY()) < 10; - } - - @SuppressLint("ClickableViewAccessibility") - protected void toggleSettingPanel() { - if (isSettingPanelShow()) { - playHidePanelAnim(); - findViewById(R.id.frg_background).setOnTouchListener(null); - findViewById(R.id.frg_background).setClickable(false); - } else { - playShowPanelAnim(); - findViewById(R.id.frg_background).setOnTouchListener((v, event) -> { - if (event.getAction() == TouchEvent.ACTION_DOWN) { - if (isSettingPanelShow()) { - toggleSettingPanel(); - return true; - } - } - return false; - }); - findViewById(R.id.frg_background).setClickable(true); - } - } - - protected void playShowPanelAnim() { - View fullLayout = findViewById(R.id.fullLayout); - if (fullLayout != null) { - fullLayout.animate().cancel(); - fullLayout.animate() - .translationY(0) - .setDuration(200) - .setInterpolator(EasingHelper.asInterpolator(Easing.InOutQuad)) - .setListener(new BaseAnimationListener() { - @Override - public void onAnimationEnd(Animator animation) { - super.onAnimationEnd(animation); - findViewById(R.id.frg_background).setClickable(true); - findViewById(R.id.frg_background).setOnClickListener(v -> playHidePanelAnim()); - } - }) - .start(); - } - } - - protected void playHidePanelAnim() { - View fullLayout = findViewById(R.id.fullLayout); - if (fullLayout != null) { - fullLayout.animate().cancel(); - fullLayout.animate() - .translationY(findViewById(R.id.optionBody).getHeight()) - .setDuration(200) - .setInterpolator(EasingHelper.asInterpolator(Easing.InOutQuad)) - .setListener(new BaseAnimationListener() { - @Override - public void onAnimationEnd(Animator animation) { - super.onAnimationEnd(animation); - findViewById(R.id.frg_background).setClickable(false); - } - }) - .start(); - } - } + private static InGameSettingMenu menu; + private CheckBox enableStoryboard; + private CheckBox showScoreboard; + private CheckBox enableNCWhenSpeedChange; + private CheckBox enableSpeedChange; + private CheckBox enableForceAR; + private SeekBar backgroundBrightness; + private SeekBar changeSpeed; + private SeekBar forceAR; + private SeekBar flashlightFollowDelay; + + private final int greenColor = Color.parseColor("#62c700"); + + public static InGameSettingMenu getInstance() { + if (menu == null) { + menu = new InGameSettingMenu(); + } + return menu; + } + + @Override + protected int getLayoutID() { + return R.layout.fragment_in_game_option; + } + + @Override + protected void onLoadView() { + reload(); + findViewById(R.id.frg_header).animate().cancel(); + findViewById(R.id.frg_header).setAlpha(0); + findViewById(R.id.frg_header).setTranslationY(100); + findViewById(R.id.frg_header).animate() + .alpha(1) + .translationY(0) + .setDuration(200) + .setInterpolator(EasingHelper.asInterpolator(Easing.InOutQuad)) + .start(); + } + + private void applyCustomModColor() { + final TextView customizedModsText = findViewById(R.id.customize_mods); + int color = ModMenu.getInstance().getFLfollowDelay() != FlashLightEntity.defaultMoveDelayS ? Color.RED : greenColor; + customizedModsText.setTextColor(color); + } + + @SuppressLint({"ClickableViewAccessibility", "ApplySharedPref"}) + private void reload() { + View showMoreButton = findViewById(R.id.showMoreButton); + if (showMoreButton == null) { + return; + } + showMoreButton.setOnTouchListener((v, event) -> { + if (event.getAction() == TouchEvent.ACTION_DOWN) { + v.animate().cancel(); + v.animate().scaleY(0.9f).scaleX(0.9f).translationY(v.getHeight() * 0.1f).setDuration(100).start(); + toggleSettingPanel(); + return true; + } else if (event.getAction() == TouchEvent.ACTION_UP) { + v.animate().cancel(); + v.animate().scaleY(1).scaleX(1).setDuration(100).translationY(0).start(); + if (event.getX() < v.getWidth() + && event.getY() < v.getHeight() + && event.getX() > 0 + && event.getY() > 0) { + } + return true; + } + return false; + }); + + findViewById(R.id.frg_background).setClickable(false); + + enableStoryboard = findViewById(R.id.enableStoryboard); + enableStoryboard.setChecked(Config.isEnableStoryboard()); + enableStoryboard.setOnCheckedChangeListener((buttonView, isChecked) -> { + Config.setEnableStoryboard(isChecked); + PreferenceManager.getDefaultSharedPreferences(getContext()).edit() + .putBoolean("enableStoryboard", isChecked) + .commit(); + }); + + showScoreboard = findViewById(R.id.showScoreboard); + showScoreboard.setChecked(Config.isShowScoreboard()); + showScoreboard.setOnCheckedChangeListener((buttonView, isChecked) -> { + Config.setShowScoreboard(isChecked); + PreferenceManager.getDefaultSharedPreferences(getContext()).edit() + .putBoolean("showscoreboard", isChecked) + .commit(); + }); + + enableNCWhenSpeedChange = findViewById(R.id.enableNCwhenSpeedChange); + enableNCWhenSpeedChange.setChecked(ModMenu.getInstance().isEnableNCWhenSpeedChange()); + enableNCWhenSpeedChange.setOnCheckedChangeListener((buttonView, isChecked) -> { + ModMenu.getInstance().setEnableNCWhenSpeedChange(isChecked); + }); + + enableSpeedChange = findViewById(R.id.enableSpeedChange); + enableSpeedChange.setChecked(ModMenu.getInstance().getChangeSpeed() != 1.0f); + enableSpeedChange.setOnCheckedChangeListener((buttonView, isChecked) -> { + if (!isChecked) { + ModMenu.getInstance().setChangeSpeed(1.0f); + ((TextView) findViewById(R.id.changeSpeedText)).setText(String.format(Locale.getDefault(), "%.2fx", ModMenu.getInstance().getChangeSpeed())); + changeSpeed.setProgress(10); + ModMenu.getInstance().updateMultiplierText(); + } + else if(ModMenu.getInstance().getChangeSpeed() == 1.0f){ + enableSpeedChange.setChecked(false); + } + }); + + enableForceAR = findViewById(R.id.enableForceAR); + enableForceAR.setChecked(ModMenu.getInstance().isEnableForceAR()); + enableForceAR.setOnCheckedChangeListener((buttonView, isChecked) -> { + ModMenu.getInstance().setEnableForceAR(isChecked); + ModMenu.getInstance().updateMultiplierText(); + }); + + backgroundBrightness = findViewById(R.id.backgroundBrightnessBar); + backgroundBrightness.setProgress( + PreferenceManager.getDefaultSharedPreferences(getContext()).getInt("bgbrightness", 25)); + backgroundBrightness.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { + @Override + public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { + ((TextView) findViewById(R.id.brightPreviewText)).setText(String.valueOf(progress)); + ((TextView) findViewById(R.id.bgBrightnessText)).setText(progress + "%"); + int p = Math.round(FMath.clamp(255 * (progress / 100f), 0, 255)); + findViewById(R.id.brightnessPreview).setBackgroundColor(Color.argb(255, p, p, p)); + } + + @Override + public void onStartTrackingTouch(SeekBar seekBar) { + findViewById(R.id.brightnessPreviewLayout).setVisibility(View.VISIBLE); + int progress = seekBar.getProgress(); + ((TextView) findViewById(R.id.brightPreviewText)).setText(String.valueOf(progress)); + ((TextView) findViewById(R.id.bgBrightnessText)).setText(progress + "%"); + int p = Math.round(FMath.clamp(255 * (progress / 100f), 0, 255)); + findViewById(R.id.brightnessPreview).setBackgroundColor(Color.argb(255, p, p, p)); + } + + @Override + public void onStopTrackingTouch(SeekBar seekBar) { + findViewById(R.id.brightnessPreviewLayout).setVisibility(View.GONE); + int progress = seekBar.getProgress(); + ((TextView) findViewById(R.id.bgBrightnessText)).setText(progress + "%"); + Config.setBackgroundBrightness(seekBar.getProgress() / 100f); + PreferenceManager.getDefaultSharedPreferences(getContext()) + .edit() + .putInt("bgbrightness", progress) + .commit(); + } + }); + ((TextView) findViewById(R.id.bgBrightnessText)).setText( + PreferenceManager.getDefaultSharedPreferences(getContext()).getInt("bgbrightness", 25) + "%"); + + changeSpeed = findViewById(R.id.changeSpeedBar); + changeSpeed.setProgress((int)(ModMenu.getInstance().getChangeSpeed() * 20 - 10)); + changeSpeed.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { + @Override + public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { + float p = 0.5f + 0.05f * progress; + ((TextView) findViewById(R.id.changeSpeedText)).setText(String.format(Locale.getDefault(), "%.2fx", p)); + if (p == 1.0f){ + enableSpeedChange.setChecked(false); + } + else { + enableSpeedChange.setChecked(true); + ModMenu.getInstance().updateMultiplierText(); + } + } + + @Override + public void onStartTrackingTouch(SeekBar seekBar) { + int progress = seekBar.getProgress(); + float p = 0.5f + 0.05f * progress; + ((TextView) findViewById(R.id.changeSpeedText)).setText(String.format(Locale.getDefault(), "%.2fx", p)); + if (p == 1.0f){ + enableSpeedChange.setChecked(false); + } + else { + enableSpeedChange.setChecked(true); + ModMenu.getInstance().updateMultiplierText(); + } + } + + @Override + public void onStopTrackingTouch(SeekBar seekBar) { + int progress = seekBar.getProgress(); + float p = 0.5f + 0.05f * progress; + ((TextView) findViewById(R.id.changeSpeedText)).setText(String.format(Locale.getDefault(), "%.2fx", p)); + ModMenu.getInstance().setChangeSpeed(p); + if (p == 1.0f){ + enableSpeedChange.setChecked(false); + } + else { + enableSpeedChange.setChecked(true); + ModMenu.getInstance().updateMultiplierText(); + } + } + }); + ((TextView) findViewById(R.id.changeSpeedText)).setText(String.format(Locale.getDefault(), "%.2fx", ModMenu.getInstance().getChangeSpeed())); + + forceAR = findViewById(R.id.forceARBar); + forceAR.setProgress((int)(ModMenu.getInstance().getForceAR() * 10)); + forceAR.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { + @Override + public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { + float p = 0.1f * progress; + ((TextView) findViewById(R.id.forceARText)).setText(String.format(Locale.getDefault(), "AR%.1f", p)); + if(ModMenu.getInstance().isEnableForceAR()){ + ModMenu.getInstance().updateMultiplierText(); + } + } + + @Override + public void onStartTrackingTouch(SeekBar seekBar) { + int progress = seekBar.getProgress(); + float p = 0.1f * progress; + ((TextView) findViewById(R.id.forceARText)).setText(String.format(Locale.getDefault(), "AR%.1f", p)); + if(ModMenu.getInstance().isEnableForceAR()){ + ModMenu.getInstance().updateMultiplierText(); + } + } + + @Override + public void onStopTrackingTouch(SeekBar seekBar) { + int progress = seekBar.getProgress(); + float p = 0.1f * progress; + ((TextView) findViewById(R.id.forceARText)).setText(String.format(Locale.getDefault(), "AR%.1f", p)); + ModMenu.getInstance().setForceAR(p); + if(ModMenu.getInstance().isEnableForceAR()){ + ModMenu.getInstance().updateMultiplierText(); + } + } + }); + + ((TextView) findViewById(R.id.forceARText)).setText(String.format(Locale.getDefault(), "AR%.1f", ModMenu.getInstance().getForceAR())); + + flashlightFollowDelay = findViewById(R.id.flashlightFollowDelayBar); + flashlightFollowDelay.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { + @Override + public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { + ModMenu.getInstance().setFLfollowDelay((float) Math.round(progress * 1200f) / (10f * 1000f)); + applyCustomModColor(); + ((TextView) findViewById(R.id.flashlightFollowDelayText)) + .setText(String.format(Locale.getDefault(), "%.1fms", progress * FlashLightEntity.defaultMoveDelayMS)); + } + + @Override + public void onStartTrackingTouch(SeekBar seekBar) {} + + @Override + public void onStopTrackingTouch(SeekBar seekBar) {} + }); + ((TextView) findViewById(R.id.forceARText)).setText(String.format("AR%.1f", ModMenu.getInstance().getForceAR())); + } + + @Override + public void show() { + super.show(); + } + + @Override + public void dismiss() { + super.dismiss(); + ModMenu.getInstance().hideByFrag(); + } + + public boolean isSettingPanelShow() { + return findViewById(R.id.fullLayout) != null && Math.abs(findViewById(R.id.fullLayout).getTranslationY()) < 10; + } + + @SuppressLint("ClickableViewAccessibility") + protected void toggleSettingPanel() { + if (isSettingPanelShow()) { + playHidePanelAnim(); + findViewById(R.id.frg_background).setOnTouchListener(null); + findViewById(R.id.frg_background).setClickable(false); + } else { + playShowPanelAnim(); + findViewById(R.id.frg_background).setOnTouchListener((v, event) -> { + if (event.getAction() == TouchEvent.ACTION_DOWN) { + if (isSettingPanelShow()) { + toggleSettingPanel(); + return true; + } + } + return false; + }); + findViewById(R.id.frg_background).setClickable(true); + } + } + + protected void playShowPanelAnim() { + View fullLayout = findViewById(R.id.fullLayout); + if (fullLayout != null) { + fullLayout.animate().cancel(); + fullLayout.animate() + .translationY(0) + .setDuration(200) + .setInterpolator(EasingHelper.asInterpolator(Easing.InOutQuad)) + .setListener(new BaseAnimationListener() { + @Override + public void onAnimationEnd(Animator animation) { + super.onAnimationEnd(animation); + findViewById(R.id.frg_background).setClickable(true); + findViewById(R.id.frg_background).setOnClickListener(v -> playHidePanelAnim()); + } + }) + .start(); + } + } + + protected void playHidePanelAnim() { + View fullLayout = findViewById(R.id.fullLayout); + if (fullLayout != null) { + fullLayout.animate().cancel(); + fullLayout.animate() + .translationY(findViewById(R.id.optionBody).getHeight()) + .setDuration(200) + .setInterpolator(EasingHelper.asInterpolator(Easing.InOutQuad)) + .setListener(new BaseAnimationListener() { + @Override + public void onAnimationEnd(Animator animation) { + super.onAnimationEnd(animation); + findViewById(R.id.frg_background).setClickable(false); + } + }) + .start(); + } + } } diff --git a/src/com/edlplan/ui/fragment/LoadingFragment.java b/src/com/edlplan/ui/fragment/LoadingFragment.java index cb52bf11..728da7ca 100644 --- a/src/com/edlplan/ui/fragment/LoadingFragment.java +++ b/src/com/edlplan/ui/fragment/LoadingFragment.java @@ -1,64 +1,64 @@ -package com.edlplan.ui.fragment; - -import android.animation.Animator; -import android.view.View; - -import androidx.annotation.StringRes; - -import com.edlplan.framework.easing.Easing; -import com.edlplan.ui.BaseAnimationListener; -import com.edlplan.ui.EasingHelper; - -import ru.nsu.ccfit.zuev.osuplus.R; - -public class LoadingFragment extends BaseFragment { - - @Override - protected int getLayoutID() { - return R.layout.fragment_loading; - } - - @Override - protected void onLoadView() { - playOnLoadAnim(); - } - - @Override - public void dismiss() { - playOnDismissAnim(super::dismiss); - } - - protected void playOnLoadAnim() { - View body = findViewById(R.id.frg_body); - if(body == null) return; - body.setTranslationY(100); - body.animate().cancel(); - body.animate() - .translationY(0) - .setDuration(200) - .setInterpolator(EasingHelper.asInterpolator(Easing.InOutQuad)) - .start(); - playBackgroundHideInAnim(200); - } - - protected void playOnDismissAnim(Runnable runnable) { - View body = findViewById(R.id.frg_body); - if(body == null) return; - body.animate().cancel(); - body.animate() - .translationY(100) - .setDuration(200) - .setInterpolator(EasingHelper.asInterpolator(Easing.InOutQuad)) - .setListener(new BaseAnimationListener() { - @Override - public void onAnimationEnd(Animator animation) { - if (runnable != null) { - runnable.run(); - } - } - }) - .start(); - playBackgroundHideOutAnim(200); - } - -} \ No newline at end of file +package com.edlplan.ui.fragment; + +import android.animation.Animator; +import android.view.View; + +import androidx.annotation.StringRes; + +import com.edlplan.framework.easing.Easing; +import com.edlplan.ui.BaseAnimationListener; +import com.edlplan.ui.EasingHelper; + +import ru.nsu.ccfit.zuev.osuplus.R; + +public class LoadingFragment extends BaseFragment { + + @Override + protected int getLayoutID() { + return R.layout.fragment_loading; + } + + @Override + protected void onLoadView() { + playOnLoadAnim(); + } + + @Override + public void dismiss() { + playOnDismissAnim(super::dismiss); + } + + protected void playOnLoadAnim() { + View body = findViewById(R.id.frg_body); + if(body == null) return; + body.setTranslationY(100); + body.animate().cancel(); + body.animate() + .translationY(0) + .setDuration(200) + .setInterpolator(EasingHelper.asInterpolator(Easing.InOutQuad)) + .start(); + playBackgroundHideInAnim(200); + } + + protected void playOnDismissAnim(Runnable runnable) { + View body = findViewById(R.id.frg_body); + if(body == null) return; + body.animate().cancel(); + body.animate() + .translationY(100) + .setDuration(200) + .setInterpolator(EasingHelper.asInterpolator(Easing.InOutQuad)) + .setListener(new BaseAnimationListener() { + @Override + public void onAnimationEnd(Animator animation) { + if (runnable != null) { + runnable.run(); + } + } + }) + .start(); + playBackgroundHideOutAnim(200); + } + +} diff --git a/src/com/edlplan/ui/fragment/MapInfoFragment.java b/src/com/edlplan/ui/fragment/MapInfoFragment.java index c75b6dd0..b16b120b 100644 --- a/src/com/edlplan/ui/fragment/MapInfoFragment.java +++ b/src/com/edlplan/ui/fragment/MapInfoFragment.java @@ -14,107 +14,107 @@ import ru.nsu.ccfit.zuev.osuplus.R; public class MapInfoFragment extends BaseFragment { - private TextView text; - private String info; - @Override - protected int getLayoutID() { - return R.layout.mapinfo_dialog; - } + private TextView text; + private String info; + @Override + protected int getLayoutID() { + return R.layout.mapinfo_dialog; + } - @Override - protected void onLoadView() { - setDismissOnBackgroundClick(true); - text = findViewById(R.id.mapinfo_text); - text.setText(info); - Button exit = findViewById(R.id.mapinfo_exit); - exit.setOnClickListener(v -> { - dismiss(); - }); - playOnLoadAnim(); - } + @Override + protected void onLoadView() { + setDismissOnBackgroundClick(true); + text = findViewById(R.id.mapinfo_text); + text.setText(info); + Button exit = findViewById(R.id.mapinfo_exit); + exit.setOnClickListener(v -> { + dismiss(); + }); + playOnLoadAnim(); + } - private void playOnLoadAnim() { - View body = findViewById(R.id.frg_body); - body.setTranslationY(200); - body.animate().cancel(); - body.animate() - .translationY(0) - .setDuration(200) - .start(); - playBackgroundHideInAnim(200); - } + private void playOnLoadAnim() { + View body = findViewById(R.id.frg_body); + body.setTranslationY(200); + body.animate().cancel(); + body.animate() + .translationY(0) + .setDuration(200) + .start(); + playBackgroundHideInAnim(200); + } - private void playEndAnim(Runnable action) { - View body = findViewById(R.id.frg_body); - body.animate().cancel(); - body.animate() - .translationXBy(50) - .alpha(0) - .setDuration(150) - .setInterpolator(EasingHelper.asInterpolator(Easing.OutQuad)) - .setListener(new BaseAnimationListener() { - @Override - public void onAnimationEnd(Animator animation) { - if (action != null) { - action.run(); - } - } - }) - .start(); - playBackgroundHideOutAnim(200); - } + private void playEndAnim(Runnable action) { + View body = findViewById(R.id.frg_body); + body.animate().cancel(); + body.animate() + .translationXBy(50) + .alpha(0) + .setDuration(150) + .setInterpolator(EasingHelper.asInterpolator(Easing.OutQuad)) + .setListener(new BaseAnimationListener() { + @Override + public void onAnimationEnd(Animator animation) { + if (action != null) { + action.run(); + } + } + }) + .start(); + playBackgroundHideOutAnim(200); + } - @Override - public void dismiss() { - playEndAnim(super::dismiss); - } + @Override + public void dismiss() { + playEndAnim(super::dismiss); + } /* - public void showWithMap(final TrackInfo track, float speedMultiplier){ - DifficultyReCalculator diffRecalculator = new DifficultyReCalculator(); - if (!diffRecalculator.calculateMapInfo(track, speedMultiplier)){ - return; - } - int circleCount = track.getHitCircleCount(); - int sliderCount = track.getSliderCount(); - int spinnerCount = track.getSpinnerCount(); - int objectCount = track.getTotalHitObjectCount(); - float circlePercent = (float)circleCount / objectCount * 100; - float sliderPercent = (float)sliderCount / objectCount * 100; - float spinnerPercent = (float)spinnerCount / objectCount * 100; - int singleCount = diffRecalculator.getSingleCount(); - int fastSingleCount = diffRecalculator.getFastSingleCount(); - int streamCount = diffRecalculator.getStreamCount(); - int jumpCount = diffRecalculator.getJumpCount(); - int multiCount = diffRecalculator.getMultiCount(); - int switchCount = diffRecalculator.getSwitchFingeringCount(); - float singlePercent = (float)singleCount / objectCount * 100; - float fastSinglePercent = (float)fastSingleCount / objectCount * 100; - float streamPercent = (float)streamCount / objectCount * 100; - float jumpPercent = (float)jumpCount / objectCount * 100; - float multiPercent = (float)multiCount / objectCount * 100; - float switchPercent = (float)switchCount / objectCount * 100; - int longestStreamCount = diffRecalculator.getLongestStreamCount(); - float realTime = diffRecalculator.getRealTime(); - float objectPerMin = objectCount / realTime * 60; + public void showWithMap(final TrackInfo track, float speedMultiplier){ + DifficultyReCalculator diffRecalculator = new DifficultyReCalculator(); + if (!diffRecalculator.calculateMapInfo(track, speedMultiplier)){ + return; + } + int circleCount = track.getHitCircleCount(); + int sliderCount = track.getSliderCount(); + int spinnerCount = track.getSpinnerCount(); + int objectCount = track.getTotalHitObjectCount(); + float circlePercent = (float)circleCount / objectCount * 100; + float sliderPercent = (float)sliderCount / objectCount * 100; + float spinnerPercent = (float)spinnerCount / objectCount * 100; + int singleCount = diffRecalculator.getSingleCount(); + int fastSingleCount = diffRecalculator.getFastSingleCount(); + int streamCount = diffRecalculator.getStreamCount(); + int jumpCount = diffRecalculator.getJumpCount(); + int multiCount = diffRecalculator.getMultiCount(); + int switchCount = diffRecalculator.getSwitchFingeringCount(); + float singlePercent = (float)singleCount / objectCount * 100; + float fastSinglePercent = (float)fastSingleCount / objectCount * 100; + float streamPercent = (float)streamCount / objectCount * 100; + float jumpPercent = (float)jumpCount / objectCount * 100; + float multiPercent = (float)multiCount / objectCount * 100; + float switchPercent = (float)switchCount / objectCount * 100; + int longestStreamCount = diffRecalculator.getLongestStreamCount(); + float realTime = diffRecalculator.getRealTime(); + float objectPerMin = objectCount / realTime * 60; - StringBuilder string = new StringBuilder(); - //string.append(String.format(StringTable.get(R.string.binfoStr2), - // track.getHitCircleCount(), track.getSliderCount(), track.getSpinnerCount(), track.getBeatmapSetID())); - //string.append("\n\r"); - string.append(String.format("圈数:%d[%.1f%%] 滑条数:%d[%.1f%%] 转盘数:%d[%.1f%%] 物件数:%d 实际时间:%.1fs %.1f物件/分", - circleCount, circlePercent, sliderCount, sliderPercent, spinnerCount, spinnerPercent, - objectCount, realTime, objectPerMin)); - string.append("\n\r"); - string.append(String.format("单点:%d[%.1f%%] 高速单点:%d[%.1f%%] 连打:%d[%.1f%%] 跳:%d[%.1f%%]", - singleCount, singlePercent, fastSingleCount, fastSinglePercent, - streamCount, streamPercent, jumpCount, jumpPercent)); - string.append("\n\r"); - string.append(String.format("多押:%d[%.1f%%] 切指:%d[%.1f%%] 最长连打:%d", - multiCount, multiPercent, - switchCount, switchPercent, longestStreamCount)); - info = string.toString(); - show(); - diffRecalculator = null; - } - */ -} \ No newline at end of file + StringBuilder string = new StringBuilder(); + //string.append(String.format(StringTable.get(R.string.binfoStr2), + // track.getHitCircleCount(), track.getSliderCount(), track.getSpinnerCount(), track.getBeatmapSetID())); + //string.append("\n\r"); + string.append(String.format("圈数:%d[%.1f%%] 滑条数:%d[%.1f%%] 转盘数:%d[%.1f%%] 物件数:%d 实际时间:%.1fs %.1f物件/分", + circleCount, circlePercent, sliderCount, sliderPercent, spinnerCount, spinnerPercent, + objectCount, realTime, objectPerMin)); + string.append("\n\r"); + string.append(String.format("单点:%d[%.1f%%] 高速单点:%d[%.1f%%] 连打:%d[%.1f%%] 跳:%d[%.1f%%]", + singleCount, singlePercent, fastSingleCount, fastSinglePercent, + streamCount, streamPercent, jumpCount, jumpPercent)); + string.append("\n\r"); + string.append(String.format("多押:%d[%.1f%%] 切指:%d[%.1f%%] 最长连打:%d", + multiCount, multiPercent, + switchCount, switchPercent, longestStreamCount)); + info = string.toString(); + show(); + diffRecalculator = null; + } + */ +} diff --git a/src/com/edlplan/ui/fragment/MarkdownFragment.java b/src/com/edlplan/ui/fragment/MarkdownFragment.java index 1c54e25a..12568aba 100644 --- a/src/com/edlplan/ui/fragment/MarkdownFragment.java +++ b/src/com/edlplan/ui/fragment/MarkdownFragment.java @@ -17,82 +17,82 @@ public class MarkdownFragment extends BaseFragment { - private String markdown; - - @StringRes - private int title; - - public MarkdownFragment() { - setDismissOnBackgroundClick(false); - setDismissOnBackPress(true); - } - - @Override - protected int getLayoutID() { - return R.layout.fragment_markdown; - } - - @Override - protected void onLoadView() { - if (markdown != null) { - ((MarkdownWebView) findViewById(R.id.markdown_view)).setText(markdown); - } - if (title != 0) { - ((TextView) findViewById(R.id.title)).setText(title); - } - findViewById(R.id.frg_close).setOnClickListener(v -> this.dismiss()); - playOnLoadAnim(); - } - - @Override - public void dismiss() { - playOnDismissAnim(super::dismiss); - } - - public MarkdownFragment setMarkdown(String markdown) { - this.markdown = markdown; - if (findViewById(R.id.markdown_view) != null) { - ((MarkdownWebView) findViewById(R.id.markdown_view)).setText(markdown); - } - return this; - } - - public MarkdownFragment setTitle(@StringRes int title) { - this.title = title; - if (findViewById(R.id.title) != null) { - ((TextView) findViewById(R.id.title)).setText(title); - } - return this; - } - - protected void playOnLoadAnim() { - View body = findViewById(R.id.frg_body); - body.setTranslationY(500); - body.animate().cancel(); - body.animate() - .translationY(0) - .setDuration(200) - .setInterpolator(EasingHelper.asInterpolator(Easing.OutQuad)) - .start(); - playBackgroundHideInAnim(200); - } - - protected void playOnDismissAnim(Runnable runnable) { - View body = findViewById(R.id.frg_body); - body.animate().cancel(); - body.animate() - .translationY(500) - .setDuration(200) - .setInterpolator(EasingHelper.asInterpolator(Easing.InQuad)) - .setListener(new BaseAnimationListener() { - @Override - public void onAnimationEnd(Animator animation) { - if (runnable != null) { - runnable.run(); - } - } - }) - .start(); - playBackgroundHideOutAnim(200); - } + private String markdown; + + @StringRes + private int title; + + public MarkdownFragment() { + setDismissOnBackgroundClick(false); + setDismissOnBackPress(true); + } + + @Override + protected int getLayoutID() { + return R.layout.fragment_markdown; + } + + @Override + protected void onLoadView() { + if (markdown != null) { + ((MarkdownWebView) findViewById(R.id.markdown_view)).setText(markdown); + } + if (title != 0) { + ((TextView) findViewById(R.id.title)).setText(title); + } + findViewById(R.id.frg_close).setOnClickListener(v -> this.dismiss()); + playOnLoadAnim(); + } + + @Override + public void dismiss() { + playOnDismissAnim(super::dismiss); + } + + public MarkdownFragment setMarkdown(String markdown) { + this.markdown = markdown; + if (findViewById(R.id.markdown_view) != null) { + ((MarkdownWebView) findViewById(R.id.markdown_view)).setText(markdown); + } + return this; + } + + public MarkdownFragment setTitle(@StringRes int title) { + this.title = title; + if (findViewById(R.id.title) != null) { + ((TextView) findViewById(R.id.title)).setText(title); + } + return this; + } + + protected void playOnLoadAnim() { + View body = findViewById(R.id.frg_body); + body.setTranslationY(500); + body.animate().cancel(); + body.animate() + .translationY(0) + .setDuration(200) + .setInterpolator(EasingHelper.asInterpolator(Easing.OutQuad)) + .start(); + playBackgroundHideInAnim(200); + } + + protected void playOnDismissAnim(Runnable runnable) { + View body = findViewById(R.id.frg_body); + body.animate().cancel(); + body.animate() + .translationY(500) + .setDuration(200) + .setInterpolator(EasingHelper.asInterpolator(Easing.InQuad)) + .setListener(new BaseAnimationListener() { + @Override + public void onAnimationEnd(Animator animation) { + if (runnable != null) { + runnable.run(); + } + } + }) + .start(); + playBackgroundHideOutAnim(200); + } } diff --git a/src/com/edlplan/ui/fragment/PropsMenuFragment.java b/src/com/edlplan/ui/fragment/PropsMenuFragment.java index 34cf0c1c..ab7e1ce5 100644 --- a/src/com/edlplan/ui/fragment/PropsMenuFragment.java +++ b/src/com/edlplan/ui/fragment/PropsMenuFragment.java @@ -23,164 +23,164 @@ public class PropsMenuFragment extends BaseFragment implements IPropsMenu { - SongMenu menu; - MenuItem item; - BeatmapProperties props; - - private EditText offset; - private CheckBox isFav; - - public PropsMenuFragment() { - setDismissOnBackgroundClick(true); - } - - @Override - protected int getLayoutID() { - return R.layout.fragment_props_menu; - } - - @Override - protected void onLoadView() { - offset = findViewById(R.id.offsetBox); - isFav = findViewById(R.id.addToFav); - - offset.setText(props.getOffset() + ""); - isFav.setChecked(props.isFavorite()); - - isFav.setOnCheckedChangeListener((buttonView, isChecked) -> { - props.setFavorite(isChecked); - saveProp(); - }); - - offset.addTextChangedListener(new TextWatcher() { - - boolean needRest = false; - - int o; - - int pos; - - @Override - public void beforeTextChanged(CharSequence s, int start, int count, int after) { - pos = start; - } - - @Override - public void onTextChanged(CharSequence s, int start, int before, int count) { - - } - - @Override - public void afterTextChanged(Editable s) { - - try { - o = Integer.parseInt(s.toString()); - needRest = false; - if (Math.abs(o) > 250) { - o = 250 * (o > 0 ? 1 : -1); - needRest = true; - } - if (needRest) { - offset.removeTextChangedListener(this); - offset.setText(o + ""); - offset.setSelection(pos); - offset.addTextChangedListener(this); - } - props.setOffset(o); - saveProp(); - } catch (NumberFormatException e) { - if (s.length() == 0) { - props.setOffset(0); - saveProp(); - } - return; - } - } - }); - - findViewById(R.id.manageFavButton).setOnClickListener(v -> { - FavoriteManagerFragment dialog = new FavoriteManagerFragment(); - //TODO : 铺面引用还是全局耦合的,需要分离 - dialog.showToAddToFloder(ScoreLibrary.getTrackDir(GlobalManager.getInstance().getSelectedTrack().getFilename())); - }); - - findViewById(R.id.deleteBeatmap).setOnClickListener(v -> { - ConfirmDialogFragment confirm = new ConfirmDialogFragment(); - confirm.showForResult(isAccepted -> { - if (isAccepted) { - if (menu != null) { - menu.scene.postRunnable(item::delete); - } - dismiss(); - } - }); - }); - - playOnLoadAnim(); - } - - private void playOnLoadAnim() { - View body = findViewById(R.id.fullLayout); - body.setAlpha(0); - body.setTranslationY(200); - body.animate().cancel(); - body.animate() - .translationY(0) - .alpha(1) - .setInterpolator(EasingHelper.asInterpolator(Easing.InOutQuad)) - .setDuration(150) - .start(); - playBackgroundHideInAnim(150); - } - - private void playEndAnim(Runnable action) { - View body = findViewById(R.id.fullLayout); - body.animate().cancel(); - body.animate() - .translationY(200) - .alpha(0) - .setDuration(200) - .setInterpolator(EasingHelper.asInterpolator(Easing.InOutQuad)) - .setListener(new BaseAnimationListener() { - @Override - public void onAnimationEnd(Animator animation) { - if (action != null) { - action.run(); - } - } - }) - .start(); - playBackgroundHideOutAnim(200); - } - - - @Override - public void dismiss() { - menu.setRank(); - playEndAnim(super::dismiss); - } - - @Override - public void onAttach(Context context) { - super.onAttach(context); - - } - - @Override - public void show(SongMenu menu, MenuItem item) { - this.menu = menu; - this.item = item; - props = PropertiesLibrary.getInstance().getProperties(item.getBeatmap().getPath()); - if (props == null) { - props = new BeatmapProperties(); - } - show(); - } - - public void saveProp() { - PropertiesLibrary.getInstance().setProperties( - item.getBeatmap().getPath(), props); - item.setFavorite(props.favorite); - PropertiesLibrary.getInstance().save(); - } + SongMenu menu; + MenuItem item; + BeatmapProperties props; + + private EditText offset; + private CheckBox isFav; + + public PropsMenuFragment() { + setDismissOnBackgroundClick(true); + } + + @Override + protected int getLayoutID() { + return R.layout.fragment_props_menu; + } + + @Override + protected void onLoadView() { + offset = findViewById(R.id.offsetBox); + isFav = findViewById(R.id.addToFav); + + offset.setText(props.getOffset() + ""); + isFav.setChecked(props.isFavorite()); + + isFav.setOnCheckedChangeListener((buttonView, isChecked) -> { + props.setFavorite(isChecked); + saveProp(); + }); + + offset.addTextChangedListener(new TextWatcher() { + + boolean needRest = false; + + int o; + + int pos; + + @Override + public void beforeTextChanged(CharSequence s, int start, int count, int after) { + pos = start; + } + + @Override + public void onTextChanged(CharSequence s, int start, int before, int count) { + + } + + @Override + public void afterTextChanged(Editable s) { + + try { + o = Integer.parseInt(s.toString()); + needRest = false; + if (Math.abs(o) > 250) { + o = 250 * (o > 0 ? 1 : -1); + needRest = true; + } + if (needRest) { + offset.removeTextChangedListener(this); + offset.setText(o + ""); + offset.setSelection(pos); + offset.addTextChangedListener(this); + } + props.setOffset(o); + saveProp(); + } catch (NumberFormatException e) { + if (s.length() == 0) { + props.setOffset(0); + saveProp(); + } + return; + } + } + }); + + findViewById(R.id.manageFavButton).setOnClickListener(v -> { + FavoriteManagerFragment dialog = new FavoriteManagerFragment(); + //TODO : 铺面引用还是全局耦合的,需要分离 + dialog.showToAddToFloder(ScoreLibrary.getTrackDir(GlobalManager.getInstance().getSelectedTrack().getFilename())); + }); + + findViewById(R.id.deleteBeatmap).setOnClickListener(v -> { + ConfirmDialogFragment confirm = new ConfirmDialogFragment(); + confirm.showForResult(isAccepted -> { + if (isAccepted) { + if (menu != null) { + menu.scene.postRunnable(item::delete); + } + dismiss(); + } + }); + }); + + playOnLoadAnim(); + } + + private void playOnLoadAnim() { + View body = findViewById(R.id.fullLayout); + body.setAlpha(0); + body.setTranslationY(200); + body.animate().cancel(); + body.animate() + .translationY(0) + .alpha(1) + .setInterpolator(EasingHelper.asInterpolator(Easing.InOutQuad)) + .setDuration(150) + .start(); + playBackgroundHideInAnim(150); + } + + private void playEndAnim(Runnable action) { + View body = findViewById(R.id.fullLayout); + body.animate().cancel(); + body.animate() + .translationY(200) + .alpha(0) + .setDuration(200) + .setInterpolator(EasingHelper.asInterpolator(Easing.InOutQuad)) + .setListener(new BaseAnimationListener() { + @Override + public void onAnimationEnd(Animator animation) { + if (action != null) { + action.run(); + } + } + }) + .start(); + playBackgroundHideOutAnim(200); + } + + + @Override + public void dismiss() { + menu.setRank(); + playEndAnim(super::dismiss); + } + + @Override + public void onAttach(Context context) { + super.onAttach(context); + + } + + @Override + public void show(SongMenu menu, MenuItem item) { + this.menu = menu; + this.item = item; + props = PropertiesLibrary.getInstance().getProperties(item.getBeatmap().getPath()); + if (props == null) { + props = new BeatmapProperties(); + } + show(); + } + + public void saveProp() { + PropertiesLibrary.getInstance().setProperties( + item.getBeatmap().getPath(), props); + item.setFavorite(props.favorite); + PropertiesLibrary.getInstance().save(); + } } diff --git a/src/com/edlplan/ui/fragment/ScoreMenuFragment.java b/src/com/edlplan/ui/fragment/ScoreMenuFragment.java index d9fe5968..fb453d9e 100644 --- a/src/com/edlplan/ui/fragment/ScoreMenuFragment.java +++ b/src/com/edlplan/ui/fragment/ScoreMenuFragment.java @@ -25,127 +25,127 @@ public class ScoreMenuFragment extends BaseFragment { - private int scoreId; + private int scoreId; - public ScoreMenuFragment() { - setDismissOnBackgroundClick(true); - } + public ScoreMenuFragment() { + setDismissOnBackgroundClick(true); + } - @Override - protected int getLayoutID() { - return R.layout.fragment_score_menu; - } + @Override + protected int getLayoutID() { + return R.layout.fragment_score_menu; + } - @Override - protected void onLoadView() { - findViewById(R.id.exportReplay).setOnClickListener(v -> { - List replays = OdrDatabase.get().getReplayById(scoreId); - if (replays.size() == 0) { - return; - } else { - try { - OsuDroidReplay replay = replays.get(0); - final File file = new File( - new File(Environment.getExternalStorageDirectory(), "osu!droid/export"), - String.format(Locale.getDefault(), "%s [%s]-%d.edr", - replay.getFileName().subSequence(replay.getFileName().indexOf('/') + 1, replay.getFileName().lastIndexOf('.')), - replay.getPlayerName(), - replay.getTime()) - ); - if (!file.getParentFile().exists()) { - file.getParentFile().mkdirs(); - } - OsuDroidReplayPack.packTo(file, replay); + @Override + protected void onLoadView() { + findViewById(R.id.exportReplay).setOnClickListener(v -> { + List replays = OdrDatabase.get().getReplayById(scoreId); + if (replays.size() == 0) { + return; + } else { + try { + OsuDroidReplay replay = replays.get(0); + final File file = new File( + new File(Environment.getExternalStorageDirectory(), "osu!droid/export"), + String.format(Locale.getDefault(), "%s [%s]-%d.edr", + replay.getFileName().subSequence(replay.getFileName().indexOf('/') + 1, replay.getFileName().lastIndexOf('.')), + replay.getPlayerName(), + replay.getTime()) + ); + if (!file.getParentFile().exists()) { + file.getParentFile().mkdirs(); + } + OsuDroidReplayPack.packTo(file, replay); - Snackbar.make(v, String.format(getResources().getString(R.string.frg_score_menu_export_succeed), file.getAbsolutePath()), 2750).setAction("Share", new View.OnClickListener() { - @Override - public void onClick(View v) { - Intent intent = new Intent(); - intent.setAction(Intent.ACTION_VIEW); - intent.setDataAndType(FileProvider.getUriForFile( - GlobalManager.getInstance().getMainActivity(), - BuildConfig.APPLICATION_ID + ".fileProvider", - file), "*/*"); - intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); - GlobalManager.getInstance().getMainActivity().startActivityForResult(intent, 0); - } - }).show(); - } catch (Exception e) { - e.printStackTrace(); - Toast.makeText(v.getContext(), R.string.frg_score_menu_export_failed, Toast.LENGTH_SHORT).show(); - } - } - }); - findViewById(R.id.deleteReplay).setOnClickListener(v -> { - ConfirmDialogFragment confirm = new ConfirmDialogFragment(); - confirm.showForResult(isAccepted -> { - if (isAccepted) { - List replays = OdrDatabase.get().getReplayById(scoreId); - if (replays.size() == 0) { - return; - } else { - try { - if (OdrDatabase.get().deleteReplay(scoreId) == 0) { - Snackbar.make(v, "Failed to delete replay!", 1500) - .show(); - } else { - Snackbar.make(v, R.string.menu_deletescore_delete_success, 1500) - .show(); - } - ScoreMenuFragment.this.dismiss(); - } catch (Exception e) { - e.printStackTrace(); - Toast.makeText(v.getContext(), "Failed to delete replay!", Toast.LENGTH_SHORT).show(); - } - } - } - }); - }); - playOnLoadAnim(); - } + Snackbar.make(v, String.format(getResources().getString(R.string.frg_score_menu_export_succeed), file.getAbsolutePath()), 2750).setAction("Share", new View.OnClickListener() { + @Override + public void onClick(View v) { + Intent intent = new Intent(); + intent.setAction(Intent.ACTION_VIEW); + intent.setDataAndType(FileProvider.getUriForFile( + GlobalManager.getInstance().getMainActivity(), + BuildConfig.APPLICATION_ID + ".fileProvider", + file), "*/*"); + intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); + GlobalManager.getInstance().getMainActivity().startActivityForResult(intent, 0); + } + }).show(); + } catch (Exception e) { + e.printStackTrace(); + Toast.makeText(v.getContext(), R.string.frg_score_menu_export_failed, Toast.LENGTH_SHORT).show(); + } + } + }); + findViewById(R.id.deleteReplay).setOnClickListener(v -> { + ConfirmDialogFragment confirm = new ConfirmDialogFragment(); + confirm.showForResult(isAccepted -> { + if (isAccepted) { + List replays = OdrDatabase.get().getReplayById(scoreId); + if (replays.size() == 0) { + return; + } else { + try { + if (OdrDatabase.get().deleteReplay(scoreId) == 0) { + Snackbar.make(v, "Failed to delete replay!", 1500) + .show(); + } else { + Snackbar.make(v, R.string.menu_deletescore_delete_success, 1500) + .show(); + } + ScoreMenuFragment.this.dismiss(); + } catch (Exception e) { + e.printStackTrace(); + Toast.makeText(v.getContext(), "Failed to delete replay!", Toast.LENGTH_SHORT).show(); + } + } + } + }); + }); + playOnLoadAnim(); + } - @Override - public void dismiss() { - playEndAnim(super::dismiss); - } + @Override + public void dismiss() { + playEndAnim(super::dismiss); + } - private void playOnLoadAnim() { - View body = findViewById(R.id.fullLayout); - body.setAlpha(0); - body.setTranslationY(200); - body.animate().cancel(); - body.animate() - .translationY(0) - .alpha(1) - .setInterpolator(EasingHelper.asInterpolator(Easing.InOutQuad)) - .setDuration(150) - .start(); - playBackgroundHideInAnim(150); - } + private void playOnLoadAnim() { + View body = findViewById(R.id.fullLayout); + body.setAlpha(0); + body.setTranslationY(200); + body.animate().cancel(); + body.animate() + .translationY(0) + .alpha(1) + .setInterpolator(EasingHelper.asInterpolator(Easing.InOutQuad)) + .setDuration(150) + .start(); + playBackgroundHideInAnim(150); + } - private void playEndAnim(Runnable action) { - View body = findViewById(R.id.fullLayout); - body.animate().cancel(); - body.animate() - .translationY(200) - .alpha(0) - .setDuration(200) - .setInterpolator(EasingHelper.asInterpolator(Easing.InOutQuad)) - .setListener(new BaseAnimationListener() { - @Override - public void onAnimationEnd(Animator animation) { - if (action != null) { - action.run(); - } - } - }) - .start(); - playBackgroundHideOutAnim(200); - } + private void playEndAnim(Runnable action) { + View body = findViewById(R.id.fullLayout); + body.animate().cancel(); + body.animate() + .translationY(200) + .alpha(0) + .setDuration(200) + .setInterpolator(EasingHelper.asInterpolator(Easing.InOutQuad)) + .setListener(new BaseAnimationListener() { + @Override + public void onAnimationEnd(Animator animation) { + if (action != null) { + action.run(); + } + } + }) + .start(); + playBackgroundHideOutAnim(200); + } - public void show(int scoreId) { - this.scoreId = scoreId; - show(); - } + public void show(int scoreId) { + this.scoreId = scoreId; + show(); + } } diff --git a/src/com/edlplan/ui/fragment/SettingsFragment.kt b/src/com/edlplan/ui/fragment/SettingsFragment.kt index 30530a3d..a2ea52f4 100644 --- a/src/com/edlplan/ui/fragment/SettingsFragment.kt +++ b/src/com/edlplan/ui/fragment/SettingsFragment.kt @@ -1,74 +1,74 @@ -package com.edlplan.ui.fragment - -import android.os.Bundle -import android.view.LayoutInflater -import android.view.View -import android.view.ViewGroup -import androidx.annotation.IdRes -import androidx.preference.PreferenceFragmentCompat -import com.edlplan.framework.easing.Easing -import com.edlplan.ui.ActivityOverlay -import com.edlplan.ui.EasingHelper -import ru.nsu.ccfit.zuev.osuplus.R - -abstract class SettingsFragment : PreferenceFragmentCompat(), BackPressListener { - var root: View? = null - private set - var isCreated = false - private set - - @Suppress("UNCHECKED_CAST") - fun findViewById(@IdRes id: Int): T? { - val o: Any? = if (root != null) root!!.findViewById(id) else null - return if (o == null) { - null - } else { - o as T - } - } - - protected abstract fun onLoadView() - protected fun playBackgroundHideInAnim(duration: Int) { - val background = findViewById(R.id.frg_background) - if (background != null) { - background.alpha = 0f - background.animate().cancel() - background.animate() - .alpha(1f) - .setDuration(duration.toLong()) - .setInterpolator(EasingHelper.asInterpolator(Easing.InOutQuad)) - .start() - } - } - - protected fun playBackgroundHideOutAnim(duration: Int) { - val background = findViewById(R.id.frg_background) - if (background != null) { - background.animate().cancel() - background.animate() - .alpha(0f) - .setDuration(duration.toLong()) - .setInterpolator(EasingHelper.asInterpolator(Easing.InOutQuad)) - .start() - } - } - - open fun show() { - ActivityOverlay.addOverlay(this, this.javaClass.name + "@" + this.hashCode()) - } - - open fun dismiss() { - ActivityOverlay.dismissOverlay(this) - } - - override fun callDismissOnBackPress() { - dismiss() - } - - override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { - isCreated = true - root = super.onCreateView(inflater, container, savedInstanceState) - onLoadView() - return root - } -} \ No newline at end of file +package com.edlplan.ui.fragment + +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import androidx.annotation.IdRes +import androidx.preference.PreferenceFragmentCompat +import com.edlplan.framework.easing.Easing +import com.edlplan.ui.ActivityOverlay +import com.edlplan.ui.EasingHelper +import ru.nsu.ccfit.zuev.osuplus.R + +abstract class SettingsFragment : PreferenceFragmentCompat(), BackPressListener { + var root: View? = null + private set + var isCreated = false + private set + + @Suppress("UNCHECKED_CAST") + fun findViewById(@IdRes id: Int): T? { + val o: Any? = if (root != null) root!!.findViewById(id) else null + return if (o == null) { + null + } else { + o as T + } + } + + protected abstract fun onLoadView() + protected fun playBackgroundHideInAnim(duration: Int) { + val background = findViewById(R.id.frg_background) + if (background != null) { + background.alpha = 0f + background.animate().cancel() + background.animate() + .alpha(1f) + .setDuration(duration.toLong()) + .setInterpolator(EasingHelper.asInterpolator(Easing.InOutQuad)) + .start() + } + } + + protected fun playBackgroundHideOutAnim(duration: Int) { + val background = findViewById(R.id.frg_background) + if (background != null) { + background.animate().cancel() + background.animate() + .alpha(0f) + .setDuration(duration.toLong()) + .setInterpolator(EasingHelper.asInterpolator(Easing.InOutQuad)) + .start() + } + } + + open fun show() { + ActivityOverlay.addOverlay(this, this.javaClass.name + "@" + this.hashCode()) + } + + open fun dismiss() { + ActivityOverlay.dismissOverlay(this) + } + + override fun callDismissOnBackPress() { + dismiss() + } + + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { + isCreated = true + root = super.onCreateView(inflater, container, savedInstanceState) + onLoadView() + return root + } +} diff --git a/src/com/edlplan/ui/fragment/TestFragment.java b/src/com/edlplan/ui/fragment/TestFragment.java index 5cbdd7c1..f3d01b57 100644 --- a/src/com/edlplan/ui/fragment/TestFragment.java +++ b/src/com/edlplan/ui/fragment/TestFragment.java @@ -13,18 +13,18 @@ public class TestFragment extends Fragment { - @Nullable - @Override - public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { - View root = inflater.inflate(R.layout.frg_test, container, false); - TextView textView = root.findViewById(R.id.textView); - //textView.animate().translationYBy(500).setDuration(1000).start(); - return root; - } + @Nullable + @Override + public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { + View root = inflater.inflate(R.layout.frg_test, container, false); + TextView textView = root.findViewById(R.id.textView); + //textView.animate().translationYBy(500).setDuration(1000).start(); + return root; + } - @Override - public void onDetach() { - super.onDetach(); - System.out.println("detach " + this); - } + @Override + public void onDetach() { + super.onDetach(); + System.out.println("detach " + this); + } } diff --git a/src/com/edlplan/ui/fragment/UpdateDialogFragment.java b/src/com/edlplan/ui/fragment/UpdateDialogFragment.java index c1987ff9..be928881 100644 --- a/src/com/edlplan/ui/fragment/UpdateDialogFragment.java +++ b/src/com/edlplan/ui/fragment/UpdateDialogFragment.java @@ -1,95 +1,95 @@ -package com.edlplan.ui.fragment; - -import android.animation.Animator; -import android.content.Intent; -import android.net.Uri; -import android.view.View; -import android.widget.TextView; - -import androidx.annotation.StringRes; - -import com.edlplan.framework.easing.Easing; -import com.edlplan.ui.BaseAnimationListener; -import com.edlplan.ui.EasingHelper; - -import ru.nsu.ccfit.zuev.osuplus.R; - -public class UpdateDialogFragment extends BaseFragment { - - private String changelogMsg, downloadUrl; - - public UpdateDialogFragment() { - setDismissOnBackgroundClick(true); - } - - @Override - protected int getLayoutID() { - return R.layout.fragment_update_dialog; - } - - @Override - protected void onLoadView() { - findViewById(R.id.updateButton).setOnClickListener(v -> { - Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(downloadUrl)); - getActivity().startActivity(browserIntent); - dismiss(); - }); - - findViewById(R.id.changelogButton).setOnClickListener(v -> { - new MarkdownFragment() - .setTitle(R.string.changelog_title) - .setMarkdown(changelogMsg) - .show(); - }); - - findViewById(R.id.laterButton).setOnClickListener(v -> dismiss()); - playOnLoadAnim(); - } - - @Override - public void dismiss() { - playOnDismissAnim(super::dismiss); - } - - public UpdateDialogFragment setChangelogMessage(String changelogMsg) { - this.changelogMsg = changelogMsg; - return this; - } - - public UpdateDialogFragment setDownloadUrl(String downloadUrl) { - this.downloadUrl = downloadUrl; - return this; - } - - protected void playOnLoadAnim() { - View body = findViewById(R.id.frg_body); - body.setTranslationY(100); - body.animate().cancel(); - body.animate() - .translationY(0) - .setDuration(200) - .setInterpolator(EasingHelper.asInterpolator(Easing.InOutQuad)) - .start(); - playBackgroundHideInAnim(200); - } - - protected void playOnDismissAnim(Runnable runnable) { - View body = findViewById(R.id.frg_body); - body.animate().cancel(); - body.animate() - .translationY(100) - .setDuration(200) - .setInterpolator(EasingHelper.asInterpolator(Easing.InOutQuad)) - .setListener(new BaseAnimationListener() { - @Override - public void onAnimationEnd(Animator animation) { - if (runnable != null) { - runnable.run(); - } - } - }) - .start(); - playBackgroundHideOutAnim(200); - } - -} +package com.edlplan.ui.fragment; + +import android.animation.Animator; +import android.content.Intent; +import android.net.Uri; +import android.view.View; +import android.widget.TextView; + +import androidx.annotation.StringRes; + +import com.edlplan.framework.easing.Easing; +import com.edlplan.ui.BaseAnimationListener; +import com.edlplan.ui.EasingHelper; + +import ru.nsu.ccfit.zuev.osuplus.R; + +public class UpdateDialogFragment extends BaseFragment { + + private String changelogMsg, downloadUrl; + + public UpdateDialogFragment() { + setDismissOnBackgroundClick(true); + } + + @Override + protected int getLayoutID() { + return R.layout.fragment_update_dialog; + } + + @Override + protected void onLoadView() { + findViewById(R.id.updateButton).setOnClickListener(v -> { + Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(downloadUrl)); + getActivity().startActivity(browserIntent); + dismiss(); + }); + + findViewById(R.id.changelogButton).setOnClickListener(v -> { + new MarkdownFragment() + .setTitle(R.string.changelog_title) + .setMarkdown(changelogMsg) + .show(); + }); + + findViewById(R.id.laterButton).setOnClickListener(v -> dismiss()); + playOnLoadAnim(); + } + + @Override + public void dismiss() { + playOnDismissAnim(super::dismiss); + } + + public UpdateDialogFragment setChangelogMessage(String changelogMsg) { + this.changelogMsg = changelogMsg; + return this; + } + + public UpdateDialogFragment setDownloadUrl(String downloadUrl) { + this.downloadUrl = downloadUrl; + return this; + } + + protected void playOnLoadAnim() { + View body = findViewById(R.id.frg_body); + body.setTranslationY(100); + body.animate().cancel(); + body.animate() + .translationY(0) + .setDuration(200) + .setInterpolator(EasingHelper.asInterpolator(Easing.InOutQuad)) + .start(); + playBackgroundHideInAnim(200); + } + + protected void playOnDismissAnim(Runnable runnable) { + View body = findViewById(R.id.frg_body); + body.animate().cancel(); + body.animate() + .translationY(100) + .setDuration(200) + .setInterpolator(EasingHelper.asInterpolator(Easing.InOutQuad)) + .setListener(new BaseAnimationListener() { + @Override + public void onAnimationEnd(Animator animation) { + if (runnable != null) { + runnable.run(); + } + } + }) + .start(); + playBackgroundHideOutAnim(200); + } + +} diff --git a/src/com/edlplan/ui/fragment/WebViewFragment.java b/src/com/edlplan/ui/fragment/WebViewFragment.java index 7aeb8301..6d6e205d 100644 --- a/src/com/edlplan/ui/fragment/WebViewFragment.java +++ b/src/com/edlplan/ui/fragment/WebViewFragment.java @@ -1,131 +1,131 @@ -package com.edlplan.ui.fragment; - -import android.annotation.TargetApi; -import android.animation.Animator; - -import android.graphics.Bitmap; -import android.os.Build; -import android.view.View; -import android.webkit.WebView; -import android.webkit.WebResourceRequest; -import android.webkit.WebSettings; -import android.webkit.WebViewClient; -import android.widget.ImageButton; - -import androidx.annotation.StringRes; - -import com.edlplan.framework.easing.Easing; -import com.edlplan.ui.BaseAnimationListener; -import com.edlplan.ui.EasingHelper; - -import ru.nsu.ccfit.zuev.osu.online.OnlineManager; -import ru.nsu.ccfit.zuev.osuplus.R; - -public class WebViewFragment extends BaseFragment { - - public static final String REGISTER_URL = "https://" + OnlineManager.hostname + "/user/?action=register"; - public static final String PROFILE_URL = "https://" + OnlineManager.hostname + "/profile.php?uid="; - - private WebView webview; - private String url; - private LoadingFragment loadingFragment; - - public WebViewFragment setURL(String url) { - this.url = url; - return this; - } - - @Override - protected int getLayoutID() { - return R.layout.fragment_webview; - } - - @Override - protected void onLoadView() { - webview = (WebView) findViewById(R.id.web); - WebSettings webSettings = webview.getSettings(); - webSettings.setJavaScriptEnabled(true); - webSettings.setUserAgentString("osudroid"); - - ((ImageButton) findViewById(R.id.close_button)).setOnClickListener(v -> { - dismiss(); - }); - - webview.setWebViewClient(new WebViewClient() { - @Override - public void onPageStarted(WebView view, String url, Bitmap favicon) { - if(loadingFragment == null) { - loadingFragment = new LoadingFragment(); - loadingFragment.show(); - } - } - - @Override - public void onPageFinished(WebView view, String url) { - if(loadingFragment != null) { - loadingFragment.dismiss(); - loadingFragment = null; - } - } - - @Override - public boolean shouldOverrideUrlLoading(WebView view, String url) { - return false; - } - - @Override - @TargetApi(Build.VERSION_CODES.N) - public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) { - return false; - } - }); - webview.loadUrl(url); - playOnLoadAnim(); - } - - @Override - public void dismiss() { - playOnDismissAnim(super::dismiss); - } - - @Override - public void callDismissOnBackPress() { - if(webview.canGoBack()) { - webview.goBack(); - }else { - dismiss(); - } - } - - protected void playOnLoadAnim() { - View body = findViewById(R.id.fullLayout); - body.setTranslationY(100); - body.animate().cancel(); - body.animate() - .translationY(0) - .setDuration(200) - .setInterpolator(EasingHelper.asInterpolator(Easing.InOutQuad)) - .start(); - playBackgroundHideInAnim(200); - } - - protected void playOnDismissAnim(Runnable runnable) { - View body = findViewById(R.id.fullLayout); - body.animate().cancel(); - body.animate() - .translationY(100) - .setDuration(200) - .setInterpolator(EasingHelper.asInterpolator(Easing.InOutQuad)) - .setListener(new BaseAnimationListener() { - @Override - public void onAnimationEnd(Animator animation) { - if (runnable != null) { - runnable.run(); - } - } - }) - .start(); - playBackgroundHideOutAnim(200); - } - -} \ No newline at end of file +package com.edlplan.ui.fragment; + +import android.annotation.TargetApi; +import android.animation.Animator; + +import android.graphics.Bitmap; +import android.os.Build; +import android.view.View; +import android.webkit.WebView; +import android.webkit.WebResourceRequest; +import android.webkit.WebSettings; +import android.webkit.WebViewClient; +import android.widget.ImageButton; + +import androidx.annotation.StringRes; + +import com.edlplan.framework.easing.Easing; +import com.edlplan.ui.BaseAnimationListener; +import com.edlplan.ui.EasingHelper; + +import ru.nsu.ccfit.zuev.osu.online.OnlineManager; +import ru.nsu.ccfit.zuev.osuplus.R; + +public class WebViewFragment extends BaseFragment { + + public static final String REGISTER_URL = "https://" + OnlineManager.hostname + "/user/?action=register"; + public static final String PROFILE_URL = "https://" + OnlineManager.hostname + "/profile.php?uid="; + + private WebView webview; + private String url; + private LoadingFragment loadingFragment; + + public WebViewFragment setURL(String url) { + this.url = url; + return this; + } + + @Override + protected int getLayoutID() { + return R.layout.fragment_webview; + } + + @Override + protected void onLoadView() { + webview = (WebView) findViewById(R.id.web); + WebSettings webSettings = webview.getSettings(); + webSettings.setJavaScriptEnabled(true); + webSettings.setUserAgentString("osudroid"); + + ((ImageButton) findViewById(R.id.close_button)).setOnClickListener(v -> { + dismiss(); + }); + + webview.setWebViewClient(new WebViewClient() { + @Override + public void onPageStarted(WebView view, String url, Bitmap favicon) { + if(loadingFragment == null) { + loadingFragment = new LoadingFragment(); + loadingFragment.show(); + } + } + + @Override + public void onPageFinished(WebView view, String url) { + if(loadingFragment != null) { + loadingFragment.dismiss(); + loadingFragment = null; + } + } + + @Override + public boolean shouldOverrideUrlLoading(WebView view, String url) { + return false; + } + + @Override + @TargetApi(Build.VERSION_CODES.N) + public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) { + return false; + } + }); + webview.loadUrl(url); + playOnLoadAnim(); + } + + @Override + public void dismiss() { + playOnDismissAnim(super::dismiss); + } + + @Override + public void callDismissOnBackPress() { + if(webview.canGoBack()) { + webview.goBack(); + }else { + dismiss(); + } + } + + protected void playOnLoadAnim() { + View body = findViewById(R.id.fullLayout); + body.setTranslationY(100); + body.animate().cancel(); + body.animate() + .translationY(0) + .setDuration(200) + .setInterpolator(EasingHelper.asInterpolator(Easing.InOutQuad)) + .start(); + playBackgroundHideInAnim(200); + } + + protected void playOnDismissAnim(Runnable runnable) { + View body = findViewById(R.id.fullLayout); + body.animate().cancel(); + body.animate() + .translationY(100) + .setDuration(200) + .setInterpolator(EasingHelper.asInterpolator(Easing.InOutQuad)) + .setListener(new BaseAnimationListener() { + @Override + public void onAnimationEnd(Animator animation) { + if (runnable != null) { + runnable.run(); + } + } + }) + .start(); + playBackgroundHideOutAnim(200); + } + +} diff --git a/src/lt/ekgame/beatmap_analyzer/Gamemode.java b/src/lt/ekgame/beatmap_analyzer/Gamemode.java index c55aac38..619651b3 100644 --- a/src/lt/ekgame/beatmap_analyzer/Gamemode.java +++ b/src/lt/ekgame/beatmap_analyzer/Gamemode.java @@ -2,18 +2,18 @@ public enum Gamemode { - UNKNOWN(-1), OSU(0), TAIKO(1), CATCH(2), MANIA(3); + UNKNOWN(-1), OSU(0), TAIKO(1), CATCH(2), MANIA(3); - int numValue; + int numValue; - Gamemode(int numValue) { - this.numValue = numValue; - } + Gamemode(int numValue) { + this.numValue = numValue; + } - public static Gamemode fromInt(int value) { - for (Gamemode gamemode : Gamemode.values()) - if (gamemode.numValue == value) - return gamemode; - return UNKNOWN; - } + public static Gamemode fromInt(int value) { + for (Gamemode gamemode : Gamemode.values()) + if (gamemode.numValue == value) + return gamemode; + return UNKNOWN; + } } diff --git a/src/lt/ekgame/beatmap_analyzer/beatmap/Beatmap.java b/src/lt/ekgame/beatmap_analyzer/beatmap/Beatmap.java index a327880b..92d02f0a 100644 --- a/src/lt/ekgame/beatmap_analyzer/beatmap/Beatmap.java +++ b/src/lt/ekgame/beatmap_analyzer/beatmap/Beatmap.java @@ -10,86 +10,86 @@ public abstract class Beatmap { - protected BeatmapGenerals generals; - protected BeatmapEditorState editorState; - protected BeatmapMetadata metadata; - protected BeatmapDifficulties difficulties; - - protected List breaks; - protected List timingPoints; - - protected Beatmap(BeatmapGenerals generals, BeatmapEditorState editorState, - BeatmapMetadata metadata, BeatmapDifficulties difficulties, - List breaks, List timingPoints) { - this.generals = generals; - this.editorState = editorState; - this.metadata = metadata; - this.difficulties = difficulties; - this.breaks = breaks; - this.timingPoints = timingPoints; - } - - protected void finalizeObjects(List objects) { - ListIterator timingIterator = timingPoints.listIterator(); - ListIterator objectIterator = objects.listIterator(); - - // find first parent point - TimingPoint parent = null; - while (parent == null || parent.isInherited()) - parent = timingIterator.next(); - - while (true) { - TimingPoint current = timingIterator.hasNext() ? timingIterator.next() : null; - TimingPoint previous = timingPoints.get(timingIterator.previousIndex() - (current == null ? 0 : 1)); - if (!previous.isInherited()) parent = previous; - - while (objectIterator.hasNext()) { - HitObject object = objectIterator.next(); - if (current == null || object.getStartTime() < current.getTimestamp()) { - object.finalize(previous, parent, this); - } else { - objectIterator.previous(); - break; - } - } - - if (current == null) break; - } - } - - public abstract Gamemode getGamemode(); - - public abstract DifficultyCalculator getDifficultyCalculator(); - - public abstract Difficulty getDifficulty(Mods mods); - - public abstract Difficulty getDifficulty(); - - public abstract int getMaxCombo(); - - public abstract int getObjectCount(); - - public BeatmapGenerals getGenerals() { - return generals; - } - - public BeatmapEditorState getEditorState() { - return editorState; - } - - public BeatmapMetadata getMetadata() { - return metadata; - } - - public BeatmapDifficulties getDifficultySettings() { - return difficulties; - } - - public List getBreaks() { - return breaks; - } - - public List getTimingPoints() { - return timingPoints; - } + protected BeatmapGenerals generals; + protected BeatmapEditorState editorState; + protected BeatmapMetadata metadata; + protected BeatmapDifficulties difficulties; + + protected List breaks; + protected List timingPoints; + + protected Beatmap(BeatmapGenerals generals, BeatmapEditorState editorState, + BeatmapMetadata metadata, BeatmapDifficulties difficulties, + List breaks, List timingPoints) { + this.generals = generals; + this.editorState = editorState; + this.metadata = metadata; + this.difficulties = difficulties; + this.breaks = breaks; + this.timingPoints = timingPoints; + } + + protected void finalizeObjects(List objects) { + ListIterator timingIterator = timingPoints.listIterator(); + ListIterator objectIterator = objects.listIterator(); + + // find first parent point + TimingPoint parent = null; + while (parent == null || parent.isInherited()) + parent = timingIterator.next(); + + while (true) { + TimingPoint current = timingIterator.hasNext() ? timingIterator.next() : null; + TimingPoint previous = timingPoints.get(timingIterator.previousIndex() - (current == null ? 0 : 1)); + if (!previous.isInherited()) parent = previous; + + while (objectIterator.hasNext()) { + HitObject object = objectIterator.next(); + if (current == null || object.getStartTime() < current.getTimestamp()) { + object.finalize(previous, parent, this); + } else { + objectIterator.previous(); + break; + } + } + + if (current == null) break; + } + } + + public abstract Gamemode getGamemode(); + + public abstract DifficultyCalculator getDifficultyCalculator(); + + public abstract Difficulty getDifficulty(Mods mods); + + public abstract Difficulty getDifficulty(); + + public abstract int getMaxCombo(); + + public abstract int getObjectCount(); + + public BeatmapGenerals getGenerals() { + return generals; + } + + public BeatmapEditorState getEditorState() { + return editorState; + } + + public BeatmapMetadata getMetadata() { + return metadata; + } + + public BeatmapDifficulties getDifficultySettings() { + return difficulties; + } + + public List getBreaks() { + return breaks; + } + + public List getTimingPoints() { + return timingPoints; + } } diff --git a/src/lt/ekgame/beatmap_analyzer/beatmap/BeatmapDifficulties.java b/src/lt/ekgame/beatmap_analyzer/beatmap/BeatmapDifficulties.java index 71efebb5..3e94db47 100644 --- a/src/lt/ekgame/beatmap_analyzer/beatmap/BeatmapDifficulties.java +++ b/src/lt/ekgame/beatmap_analyzer/beatmap/BeatmapDifficulties.java @@ -6,83 +6,83 @@ public class BeatmapDifficulties { - private double healthDrain; - private double cirlceSize; - private double overallDifficulty; - private double approachRate; - private double sliderMultiplier; - private double tickRate; - - private BeatmapDifficulties() { - } - - public BeatmapDifficulties(FilePart part) throws BeatmapException { - FilePartConfig config = new FilePartConfig(part); - healthDrain = config.getDouble("HPDrainRate"); - cirlceSize = config.getDouble("CircleSize"); - overallDifficulty = config.getDouble("OverallDifficulty"); - // Long ago, osu! OD and AR used to be the same setting, so some maps don't have it. - approachRate = config.getDouble("ApproachRate", overallDifficulty); - sliderMultiplier = config.getDouble("SliderMultiplier"); - tickRate = config.getDouble("SliderTickRate"); - } - - public BeatmapDifficulties clone() { - BeatmapDifficulties clone = new BeatmapDifficulties(); - clone.healthDrain = this.healthDrain; - clone.cirlceSize = this.cirlceSize; - clone.overallDifficulty = this.overallDifficulty; - clone.approachRate = this.approachRate; - clone.sliderMultiplier = this.sliderMultiplier; - clone.tickRate = this.tickRate; - return clone; - } - - public double getHP() { - return healthDrain; - } - - public void setHP(double healthDrain) { - this.healthDrain = healthDrain; - } - - public double getCS() { - return cirlceSize; - } - - public void setCS(double cirlceSize) { - this.cirlceSize = cirlceSize; - } - - public double getOD() { - return overallDifficulty; - } - - public void setOD(double overallDifficulty) { - this.overallDifficulty = overallDifficulty; - } - - public double getAR() { - return approachRate; - } - - public void setAR(double approachRate) { - this.approachRate = approachRate; - } - - public double getSliderMultiplier() { - return sliderMultiplier; - } - - public void setSliderMultiplier(double sliderMultiplier) { - this.sliderMultiplier = sliderMultiplier; - } - - public double getTickRate() { - return tickRate; - } - - public void setTickRate(double tickRate) { - this.tickRate = tickRate; - } + private double healthDrain; + private double cirlceSize; + private double overallDifficulty; + private double approachRate; + private double sliderMultiplier; + private double tickRate; + + private BeatmapDifficulties() { + } + + public BeatmapDifficulties(FilePart part) throws BeatmapException { + FilePartConfig config = new FilePartConfig(part); + healthDrain = config.getDouble("HPDrainRate"); + cirlceSize = config.getDouble("CircleSize"); + overallDifficulty = config.getDouble("OverallDifficulty"); + // Long ago, osu! OD and AR used to be the same setting, so some maps don't have it. + approachRate = config.getDouble("ApproachRate", overallDifficulty); + sliderMultiplier = config.getDouble("SliderMultiplier"); + tickRate = config.getDouble("SliderTickRate"); + } + + public BeatmapDifficulties clone() { + BeatmapDifficulties clone = new BeatmapDifficulties(); + clone.healthDrain = this.healthDrain; + clone.cirlceSize = this.cirlceSize; + clone.overallDifficulty = this.overallDifficulty; + clone.approachRate = this.approachRate; + clone.sliderMultiplier = this.sliderMultiplier; + clone.tickRate = this.tickRate; + return clone; + } + + public double getHP() { + return healthDrain; + } + + public void setHP(double healthDrain) { + this.healthDrain = healthDrain; + } + + public double getCS() { + return cirlceSize; + } + + public void setCS(double cirlceSize) { + this.cirlceSize = cirlceSize; + } + + public double getOD() { + return overallDifficulty; + } + + public void setOD(double overallDifficulty) { + this.overallDifficulty = overallDifficulty; + } + + public double getAR() { + return approachRate; + } + + public void setAR(double approachRate) { + this.approachRate = approachRate; + } + + public double getSliderMultiplier() { + return sliderMultiplier; + } + + public void setSliderMultiplier(double sliderMultiplier) { + this.sliderMultiplier = sliderMultiplier; + } + + public double getTickRate() { + return tickRate; + } + + public void setTickRate(double tickRate) { + this.tickRate = tickRate; + } } diff --git a/src/lt/ekgame/beatmap_analyzer/beatmap/BeatmapEditorState.java b/src/lt/ekgame/beatmap_analyzer/beatmap/BeatmapEditorState.java index 7e47e218..9d4d80d6 100644 --- a/src/lt/ekgame/beatmap_analyzer/beatmap/BeatmapEditorState.java +++ b/src/lt/ekgame/beatmap_analyzer/beatmap/BeatmapEditorState.java @@ -9,84 +9,84 @@ public class BeatmapEditorState { - private List bookmarks = new ArrayList<>(); - private double distanceSpacing; - private int beatDivisor; - private int gridSize; - private double timelineZoom; - - private BeatmapEditorState() { - } - - public BeatmapEditorState(FilePart part) throws BeatmapException { - FilePartConfig config = new FilePartConfig(part); - distanceSpacing = config.getDouble("DistanceSpacing"); - beatDivisor = config.getInt("BeatDivisor"); - gridSize = config.getInt("GridSize"); - timelineZoom = config.getDouble("TimelineZoom", 1); - - if (config.hasProperty("Bookmarks")) { - String[] line = config.getString("Bookmarks").split(","); - for (int i = 0; i < line.length; i++) { - if (!line[i].isEmpty()) { - bookmarks.add(Integer.parseInt(line[i].trim())); - } - } - /* - bookmarks = Arrays.asList(config.getString("Bookmarks").split(",")) - .stream().filter(o->!o.isEmpty()) - .map(o->Integer.parseInt(o.trim())) - .collect(Collectors.toList());*/ - } - } - - public BeatmapEditorState clone() { - BeatmapEditorState clone = new BeatmapEditorState(); - clone.distanceSpacing = this.distanceSpacing; - clone.beatDivisor = this.beatDivisor; - clone.gridSize = this.gridSize; - clone.timelineZoom = this.timelineZoom; - clone.bookmarks = this.bookmarks; - return clone; - } - - public List getBookmarks() { - return bookmarks; - } - - public void setBookmarks(List bookmarks) { - this.bookmarks = bookmarks; - } - - public double getDistanceSpacing() { - return distanceSpacing; - } - - public void setDistanceSpacing(double distanceSpacing) { - this.distanceSpacing = distanceSpacing; - } - - public int getBeatDivisor() { - return beatDivisor; - } - - public void setBeatDivisor(int beatDivisor) { - this.beatDivisor = beatDivisor; - } - - public int getGridSize() { - return gridSize; - } - - public void setGridSize(int gridSize) { - this.gridSize = gridSize; - } - - public double getTimelineZoom() { - return timelineZoom; - } - - public void setTimelineZoom(double timelineZoom) { - this.timelineZoom = timelineZoom; - } + private List bookmarks = new ArrayList<>(); + private double distanceSpacing; + private int beatDivisor; + private int gridSize; + private double timelineZoom; + + private BeatmapEditorState() { + } + + public BeatmapEditorState(FilePart part) throws BeatmapException { + FilePartConfig config = new FilePartConfig(part); + distanceSpacing = config.getDouble("DistanceSpacing"); + beatDivisor = config.getInt("BeatDivisor"); + gridSize = config.getInt("GridSize"); + timelineZoom = config.getDouble("TimelineZoom", 1); + + if (config.hasProperty("Bookmarks")) { + String[] line = config.getString("Bookmarks").split(","); + for (int i = 0; i < line.length; i++) { + if (!line[i].isEmpty()) { + bookmarks.add(Integer.parseInt(line[i].trim())); + } + } + /* + bookmarks = Arrays.asList(config.getString("Bookmarks").split(",")) + .stream().filter(o->!o.isEmpty()) + .map(o->Integer.parseInt(o.trim())) + .collect(Collectors.toList());*/ + } + } + + public BeatmapEditorState clone() { + BeatmapEditorState clone = new BeatmapEditorState(); + clone.distanceSpacing = this.distanceSpacing; + clone.beatDivisor = this.beatDivisor; + clone.gridSize = this.gridSize; + clone.timelineZoom = this.timelineZoom; + clone.bookmarks = this.bookmarks; + return clone; + } + + public List getBookmarks() { + return bookmarks; + } + + public void setBookmarks(List bookmarks) { + this.bookmarks = bookmarks; + } + + public double getDistanceSpacing() { + return distanceSpacing; + } + + public void setDistanceSpacing(double distanceSpacing) { + this.distanceSpacing = distanceSpacing; + } + + public int getBeatDivisor() { + return beatDivisor; + } + + public void setBeatDivisor(int beatDivisor) { + this.beatDivisor = beatDivisor; + } + + public int getGridSize() { + return gridSize; + } + + public void setGridSize(int gridSize) { + this.gridSize = gridSize; + } + + public double getTimelineZoom() { + return timelineZoom; + } + + public void setTimelineZoom(double timelineZoom) { + this.timelineZoom = timelineZoom; + } } diff --git a/src/lt/ekgame/beatmap_analyzer/beatmap/BeatmapGenerals.java b/src/lt/ekgame/beatmap_analyzer/beatmap/BeatmapGenerals.java index c8bcfc2b..68243519 100644 --- a/src/lt/ekgame/beatmap_analyzer/beatmap/BeatmapGenerals.java +++ b/src/lt/ekgame/beatmap_analyzer/beatmap/BeatmapGenerals.java @@ -7,128 +7,128 @@ public class BeatmapGenerals { - private String audioFileName; - private int audioLeadIn; - private int previewTime; - private boolean hasCountdown; - private String sampleSet; - private double stackLeniency; - private Gamemode gamemode; - private boolean hasLetterboxing; - private boolean hasEpilepsyWarning; - private boolean hasWidescreenStoryboard; - - private BeatmapGenerals() { - } - - ; - - public BeatmapGenerals(FilePart part) throws BeatmapException { - FilePartConfig config = new FilePartConfig(part); - audioFileName = config.getString("AudioFilename"); - audioLeadIn = config.getInt("AudioLeadIn", 0); - previewTime = config.getInt("PreviewTime"); - hasCountdown = config.getBoolean("Countdown", true); - sampleSet = config.getString("SampleSet"); - stackLeniency = config.getDouble("StackLeniency", 0.7); - gamemode = config.getGamemode("Mode", Gamemode.OSU); - hasLetterboxing = config.getBoolean("LetterboxInBreaks", true); - hasEpilepsyWarning = config.getBoolean("EpilepsyWarning", false); - hasWidescreenStoryboard = config.getBoolean("WidescreenStoryboard", false); - } - - public BeatmapGenerals clone() { - BeatmapGenerals clone = new BeatmapGenerals(); - clone.audioFileName = this.audioFileName; - clone.audioLeadIn = this.audioLeadIn; - clone.previewTime = this.previewTime; - clone.hasCountdown = this.hasCountdown; - clone.sampleSet = this.sampleSet; - clone.stackLeniency = this.stackLeniency; - clone.gamemode = this.gamemode; - clone.hasLetterboxing = this.hasLetterboxing; - clone.hasEpilepsyWarning = this.hasEpilepsyWarning; - clone.hasWidescreenStoryboard = this.hasWidescreenStoryboard; - return clone; - } - - public String getAudioFileName() { - return audioFileName; - } - - public void setAudioFileName(String audioFileName) { - this.audioFileName = audioFileName; - } - - public int getAudioLeadIn() { - return audioLeadIn; - } - - public void setAudioLeadIn(int audioLeadIn) { - this.audioLeadIn = audioLeadIn; - } - - public int getPreviewTime() { - return previewTime; - } - - public void setPreviewTime(int previewTime) { - this.previewTime = previewTime; - } - - public boolean hasCountdown() { - return hasCountdown; - } - - public String getSampleSet() { - return sampleSet; - } - - public void setSampleSet(String sampleSet) { - this.sampleSet = sampleSet; - } - - public double getStackLeniency() { - return stackLeniency; - } - - public void setStackLeniency(double stackLeniency) { - this.stackLeniency = stackLeniency; - } - - public Gamemode getGamemode() { - return gamemode; - } - - public void setGamemode(Gamemode gamemode) { - this.gamemode = gamemode; - } - - public boolean hasLetterboxing() { - return hasLetterboxing; - } - - public boolean hasEpilepsyWarning() { - return hasEpilepsyWarning; - } - - public boolean hasWidescreenStoryboard() { - return hasWidescreenStoryboard; - } - - public void setHasCountdown(boolean hasCountdown) { - this.hasCountdown = hasCountdown; - } - - public void setLetterboxing(boolean hasLetterboxing) { - this.hasLetterboxing = hasLetterboxing; - } - - public void setEpilepsyWarning(boolean hasEpilepsyWarning) { - this.hasEpilepsyWarning = hasEpilepsyWarning; - } - - public void setWidescreenStoryboard(boolean hasWidescreenStoryboard) { - this.hasWidescreenStoryboard = hasWidescreenStoryboard; - } + private String audioFileName; + private int audioLeadIn; + private int previewTime; + private boolean hasCountdown; + private String sampleSet; + private double stackLeniency; + private Gamemode gamemode; + private boolean hasLetterboxing; + private boolean hasEpilepsyWarning; + private boolean hasWidescreenStoryboard; + + private BeatmapGenerals() { + } + + ; + + public BeatmapGenerals(FilePart part) throws BeatmapException { + FilePartConfig config = new FilePartConfig(part); + audioFileName = config.getString("AudioFilename"); + audioLeadIn = config.getInt("AudioLeadIn", 0); + previewTime = config.getInt("PreviewTime"); + hasCountdown = config.getBoolean("Countdown", true); + sampleSet = config.getString("SampleSet"); + stackLeniency = config.getDouble("StackLeniency", 0.7); + gamemode = config.getGamemode("Mode", Gamemode.OSU); + hasLetterboxing = config.getBoolean("LetterboxInBreaks", true); + hasEpilepsyWarning = config.getBoolean("EpilepsyWarning", false); + hasWidescreenStoryboard = config.getBoolean("WidescreenStoryboard", false); + } + + public BeatmapGenerals clone() { + BeatmapGenerals clone = new BeatmapGenerals(); + clone.audioFileName = this.audioFileName; + clone.audioLeadIn = this.audioLeadIn; + clone.previewTime = this.previewTime; + clone.hasCountdown = this.hasCountdown; + clone.sampleSet = this.sampleSet; + clone.stackLeniency = this.stackLeniency; + clone.gamemode = this.gamemode; + clone.hasLetterboxing = this.hasLetterboxing; + clone.hasEpilepsyWarning = this.hasEpilepsyWarning; + clone.hasWidescreenStoryboard = this.hasWidescreenStoryboard; + return clone; + } + + public String getAudioFileName() { + return audioFileName; + } + + public void setAudioFileName(String audioFileName) { + this.audioFileName = audioFileName; + } + + public int getAudioLeadIn() { + return audioLeadIn; + } + + public void setAudioLeadIn(int audioLeadIn) { + this.audioLeadIn = audioLeadIn; + } + + public int getPreviewTime() { + return previewTime; + } + + public void setPreviewTime(int previewTime) { + this.previewTime = previewTime; + } + + public boolean hasCountdown() { + return hasCountdown; + } + + public String getSampleSet() { + return sampleSet; + } + + public void setSampleSet(String sampleSet) { + this.sampleSet = sampleSet; + } + + public double getStackLeniency() { + return stackLeniency; + } + + public void setStackLeniency(double stackLeniency) { + this.stackLeniency = stackLeniency; + } + + public Gamemode getGamemode() { + return gamemode; + } + + public void setGamemode(Gamemode gamemode) { + this.gamemode = gamemode; + } + + public boolean hasLetterboxing() { + return hasLetterboxing; + } + + public boolean hasEpilepsyWarning() { + return hasEpilepsyWarning; + } + + public boolean hasWidescreenStoryboard() { + return hasWidescreenStoryboard; + } + + public void setHasCountdown(boolean hasCountdown) { + this.hasCountdown = hasCountdown; + } + + public void setLetterboxing(boolean hasLetterboxing) { + this.hasLetterboxing = hasLetterboxing; + } + + public void setEpilepsyWarning(boolean hasEpilepsyWarning) { + this.hasEpilepsyWarning = hasEpilepsyWarning; + } + + public void setWidescreenStoryboard(boolean hasWidescreenStoryboard) { + this.hasWidescreenStoryboard = hasWidescreenStoryboard; + } } diff --git a/src/lt/ekgame/beatmap_analyzer/beatmap/BeatmapMetadata.java b/src/lt/ekgame/beatmap_analyzer/beatmap/BeatmapMetadata.java index cc10df84..767ba891 100644 --- a/src/lt/ekgame/beatmap_analyzer/beatmap/BeatmapMetadata.java +++ b/src/lt/ekgame/beatmap_analyzer/beatmap/BeatmapMetadata.java @@ -10,128 +10,128 @@ public class BeatmapMetadata { - private String title; - private String titleRomanized; - private String artist; - private String artistRomanized; - private String creator; - private String version; - private String source; - private List tags = new ArrayList<>(); - private String beatmapId; - private String beatmapSetId; - - private BeatmapMetadata() { - } - - public BeatmapMetadata(FilePart part) throws BeatmapException { - FilePartConfig config = new FilePartConfig(part); - titleRomanized = config.getString("Title"); - title = config.getString("TitleUnicode", titleRomanized); - artistRomanized = config.getString("Artist"); - artist = config.getString("ArtistUnicode", artistRomanized); - - creator = config.getString("Creator"); - version = config.getString("Version"); - source = config.getString("Source", ""); - tags = Arrays.asList(config.getString("Tags", "").split(" ")); - beatmapId = config.getString("BeatmapID", null); - beatmapSetId = config.getString("BeatmapSetID", null); - } - - public BeatmapMetadata clone() { - BeatmapMetadata clone = new BeatmapMetadata(); - clone.titleRomanized = this.titleRomanized; - clone.title = this.title; - clone.artistRomanized = this.artistRomanized; - clone.artist = this.artist; - - clone.creator = this.creator; - clone.version = this.version; - clone.source = this.source; - clone.tags = this.tags; - clone.beatmapId = this.beatmapId; - clone.beatmapSetId = this.beatmapSetId; - return clone; - } - - public String getTitle() { - return title; - } - - public void setTitle(String title) { - this.title = title; - } - - public String getTitleRomanized() { - return titleRomanized; - } - - public void setTitleRomanized(String titleRomanized) { - this.titleRomanized = titleRomanized; - } - - public String getArtist() { - return artist; - } - - public void setArtist(String artist) { - this.artist = artist; - } - - public String getArtistRomanized() { - return artistRomanized; - } - - public void setArtistRomanized(String artistRomanized) { - this.artistRomanized = artistRomanized; - } - - public String getCreator() { - return creator; - } - - public void setCreator(String creator) { - this.creator = creator; - } - - public String getVersion() { - return version; - } - - public void setVersion(String version) { - this.version = version; - } - - public String getSource() { - return source; - } - - public void setSource(String source) { - this.source = source; - } - - public List getTags() { - return tags; - } - - public void setTags(List tags) { - this.tags = tags; - } - - public String getBeatmapId() { - return beatmapId; - } - - public void setBeatmapId(String beatmapId) { - this.beatmapId = beatmapId; - } - - public String getBeatmapSetId() { - return beatmapSetId; - } - - public void setBeatmapSetId(String beatmapSetId) { - this.beatmapSetId = beatmapSetId; - } + private String title; + private String titleRomanized; + private String artist; + private String artistRomanized; + private String creator; + private String version; + private String source; + private List tags = new ArrayList<>(); + private String beatmapId; + private String beatmapSetId; + + private BeatmapMetadata() { + } + + public BeatmapMetadata(FilePart part) throws BeatmapException { + FilePartConfig config = new FilePartConfig(part); + titleRomanized = config.getString("Title"); + title = config.getString("TitleUnicode", titleRomanized); + artistRomanized = config.getString("Artist"); + artist = config.getString("ArtistUnicode", artistRomanized); + + creator = config.getString("Creator"); + version = config.getString("Version"); + source = config.getString("Source", ""); + tags = Arrays.asList(config.getString("Tags", "").split(" ")); + beatmapId = config.getString("BeatmapID", null); + beatmapSetId = config.getString("BeatmapSetID", null); + } + + public BeatmapMetadata clone() { + BeatmapMetadata clone = new BeatmapMetadata(); + clone.titleRomanized = this.titleRomanized; + clone.title = this.title; + clone.artistRomanized = this.artistRomanized; + clone.artist = this.artist; + + clone.creator = this.creator; + clone.version = this.version; + clone.source = this.source; + clone.tags = this.tags; + clone.beatmapId = this.beatmapId; + clone.beatmapSetId = this.beatmapSetId; + return clone; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public String getTitleRomanized() { + return titleRomanized; + } + + public void setTitleRomanized(String titleRomanized) { + this.titleRomanized = titleRomanized; + } + + public String getArtist() { + return artist; + } + + public void setArtist(String artist) { + this.artist = artist; + } + + public String getArtistRomanized() { + return artistRomanized; + } + + public void setArtistRomanized(String artistRomanized) { + this.artistRomanized = artistRomanized; + } + + public String getCreator() { + return creator; + } + + public void setCreator(String creator) { + this.creator = creator; + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public String getSource() { + return source; + } + + public void setSource(String source) { + this.source = source; + } + + public List getTags() { + return tags; + } + + public void setTags(List tags) { + this.tags = tags; + } + + public String getBeatmapId() { + return beatmapId; + } + + public void setBeatmapId(String beatmapId) { + this.beatmapId = beatmapId; + } + + public String getBeatmapSetId() { + return beatmapSetId; + } + + public void setBeatmapSetId(String beatmapSetId) { + this.beatmapSetId = beatmapSetId; + } } diff --git a/src/lt/ekgame/beatmap_analyzer/beatmap/BreakPeriod.java b/src/lt/ekgame/beatmap_analyzer/beatmap/BreakPeriod.java index eeaf3072..e7c7ae28 100644 --- a/src/lt/ekgame/beatmap_analyzer/beatmap/BreakPeriod.java +++ b/src/lt/ekgame/beatmap_analyzer/beatmap/BreakPeriod.java @@ -2,30 +2,30 @@ public class BreakPeriod { - private int startTime, endTime; + private int startTime, endTime; - public BreakPeriod(int startTime, int endTime) { - this.startTime = startTime; - this.endTime = endTime; - } + public BreakPeriod(int startTime, int endTime) { + this.startTime = startTime; + this.endTime = endTime; + } - public BreakPeriod clone() { - return new BreakPeriod(startTime, endTime); - } + public BreakPeriod clone() { + return new BreakPeriod(startTime, endTime); + } - public int getStartTime() { - return startTime; - } + public int getStartTime() { + return startTime; + } - public void setStartTime(int startTime) { - this.startTime = startTime; - } + public void setStartTime(int startTime) { + this.startTime = startTime; + } - public int getEndTime() { - return endTime; - } + public int getEndTime() { + return endTime; + } - public void setEndTime(int endTime) { - this.endTime = endTime; - } + public void setEndTime(int endTime) { + this.endTime = endTime; + } } diff --git a/src/lt/ekgame/beatmap_analyzer/beatmap/HitObject.java b/src/lt/ekgame/beatmap_analyzer/beatmap/HitObject.java index 3695a415..584c65fc 100644 --- a/src/lt/ekgame/beatmap_analyzer/beatmap/HitObject.java +++ b/src/lt/ekgame/beatmap_analyzer/beatmap/HitObject.java @@ -4,91 +4,91 @@ public abstract class HitObject { - protected Vec2 position; - protected int startTime, endTime; - protected int hitSound; - protected boolean isNewCombo; - - public HitObject(Vec2 position, int startTime, int endTime, int hitSound) { - this.position = position; - this.startTime = startTime; - this.endTime = endTime; - this.hitSound = hitSound; - } - - /** - * Clones the object and every attribute it contains. - */ - public abstract HitObject clone(); - - /** - * Finalize the object (calculate slider combo, mania key index, etc). - * - * @param current Current TimingPoint can be inherited. - * @param parent Current non-inherited TimingPoint. - * @param beatmap Betmap this object belongs to. - */ - public void finalize(TimingPoint current, TimingPoint parent, Beatmap beatmap) { - // Do nothing by default - } - - /** - * The max combo that can be achieved with this object. - * - * @return Integer value for the max combo. - */ - public int getCombo() { - return 1; - } - - /** - * The position of this object. - * - * @return Vec2 object. - */ - public Vec2 getPosition() { - return position; - } - - public void setPosition(Vec2 position) { - this.position = position; - } - - /** - * Start time of the object. - * - * @return Integer value. - */ - public int getStartTime() { - return startTime; - } - - public void setStartTime(int startTime) { - this.startTime = startTime; - } - - /** - * End time of the object. May be the same as the start time for some objects. - * - * @return Integer value. - */ - public int getEndTime() { - return endTime; - } - - public void setEndTime(int endTime) { - this.endTime = endTime; - } - - public int getHitSound() { - return hitSound; - } - - public void setHitSound(int hitSound) { - this.hitSound = hitSound; - } - - public void setNewCombo(boolean isNewCombo) { - this.isNewCombo = isNewCombo; - } -} \ No newline at end of file + protected Vec2 position; + protected int startTime, endTime; + protected int hitSound; + protected boolean isNewCombo; + + public HitObject(Vec2 position, int startTime, int endTime, int hitSound) { + this.position = position; + this.startTime = startTime; + this.endTime = endTime; + this.hitSound = hitSound; + } + + /** + * Clones the object and every attribute it contains. + */ + public abstract HitObject clone(); + + /** + * Finalize the object (calculate slider combo, mania key index, etc). + * + * @param current Current TimingPoint can be inherited. + * @param parent Current non-inherited TimingPoint. + * @param beatmap Betmap this object belongs to. + */ + public void finalize(TimingPoint current, TimingPoint parent, Beatmap beatmap) { + // Do nothing by default + } + + /** + * The max combo that can be achieved with this object. + * + * @return Integer value for the max combo. + */ + public int getCombo() { + return 1; + } + + /** + * The position of this object. + * + * @return Vec2 object. + */ + public Vec2 getPosition() { + return position; + } + + public void setPosition(Vec2 position) { + this.position = position; + } + + /** + * Start time of the object. + * + * @return Integer value. + */ + public int getStartTime() { + return startTime; + } + + public void setStartTime(int startTime) { + this.startTime = startTime; + } + + /** + * End time of the object. May be the same as the start time for some objects. + * + * @return Integer value. + */ + public int getEndTime() { + return endTime; + } + + public void setEndTime(int endTime) { + this.endTime = endTime; + } + + public int getHitSound() { + return hitSound; + } + + public void setHitSound(int hitSound) { + this.hitSound = hitSound; + } + + public void setNewCombo(boolean isNewCombo) { + this.isNewCombo = isNewCombo; + } +} diff --git a/src/lt/ekgame/beatmap_analyzer/beatmap/TimingPoint.java b/src/lt/ekgame/beatmap_analyzer/beatmap/TimingPoint.java index 19c6ebe8..ba0e4a33 100644 --- a/src/lt/ekgame/beatmap_analyzer/beatmap/TimingPoint.java +++ b/src/lt/ekgame/beatmap_analyzer/beatmap/TimingPoint.java @@ -2,104 +2,104 @@ public class TimingPoint { - private double timestamp; - private double beatLength; - private int meter; - private int sampleType; - private int sampleSet; - private int volume; - private boolean isInherited; - private boolean isKiai; - - private TimingPoint() { - } - - ; - - public TimingPoint(double timestamp, double beatLength, int meter, int sampleType, int sampleSet, int volume, boolean isInherited, boolean isKiai) { - this.timestamp = timestamp; - this.beatLength = beatLength; - this.meter = meter; - this.sampleType = sampleType; - this.sampleSet = sampleSet; - this.volume = volume; - this.isInherited = isInherited; - this.isKiai = isKiai; - } - - public TimingPoint clone() { - TimingPoint clone = new TimingPoint(); - clone.timestamp = this.timestamp; - clone.beatLength = this.beatLength; - clone.meter = this.meter; - clone.sampleType = this.sampleType; - clone.volume = this.volume; - clone.isInherited = this.isInherited; - clone.isKiai = this.isKiai; - return clone; - } - - public double getTimestamp() { - return timestamp; - } - - public void setTimestamp(double timestamp) { - this.timestamp = timestamp; - } - - public double getBeatLength() { - return beatLength; - } - - public void setBeatLength(double beatLength) { - this.beatLength = beatLength; - } - - public int getMeter() { - return meter; - } - - public void setMeter(int meter) { - this.meter = meter; - } - - public int getSampleType() { - return sampleType; - } - - public void setSampleType(int sampleType) { - this.sampleType = sampleType; - } - - public int getSampleSet() { - return sampleSet; - } - - public void setSampleSet(int sampleSet) { - this.sampleSet = sampleSet; - } - - public int getVolume() { - return volume; - } - - public void setVolume(int volume) { - this.volume = volume; - } - - public boolean isInherited() { - return isInherited; - } - - public void setInherited(boolean isInherited) { - this.isInherited = isInherited; - } - - public boolean isKiai() { - return isKiai; - } - - public void setKiai(boolean isKiai) { - this.isKiai = isKiai; - } + private double timestamp; + private double beatLength; + private int meter; + private int sampleType; + private int sampleSet; + private int volume; + private boolean isInherited; + private boolean isKiai; + + private TimingPoint() { + } + + ; + + public TimingPoint(double timestamp, double beatLength, int meter, int sampleType, int sampleSet, int volume, boolean isInherited, boolean isKiai) { + this.timestamp = timestamp; + this.beatLength = beatLength; + this.meter = meter; + this.sampleType = sampleType; + this.sampleSet = sampleSet; + this.volume = volume; + this.isInherited = isInherited; + this.isKiai = isKiai; + } + + public TimingPoint clone() { + TimingPoint clone = new TimingPoint(); + clone.timestamp = this.timestamp; + clone.beatLength = this.beatLength; + clone.meter = this.meter; + clone.sampleType = this.sampleType; + clone.volume = this.volume; + clone.isInherited = this.isInherited; + clone.isKiai = this.isKiai; + return clone; + } + + public double getTimestamp() { + return timestamp; + } + + public void setTimestamp(double timestamp) { + this.timestamp = timestamp; + } + + public double getBeatLength() { + return beatLength; + } + + public void setBeatLength(double beatLength) { + this.beatLength = beatLength; + } + + public int getMeter() { + return meter; + } + + public void setMeter(int meter) { + this.meter = meter; + } + + public int getSampleType() { + return sampleType; + } + + public void setSampleType(int sampleType) { + this.sampleType = sampleType; + } + + public int getSampleSet() { + return sampleSet; + } + + public void setSampleSet(int sampleSet) { + this.sampleSet = sampleSet; + } + + public int getVolume() { + return volume; + } + + public void setVolume(int volume) { + this.volume = volume; + } + + public boolean isInherited() { + return isInherited; + } + + public void setInherited(boolean isInherited) { + this.isInherited = isInherited; + } + + public boolean isKiai() { + return isKiai; + } + + public void setKiai(boolean isKiai) { + this.isKiai = isKiai; + } } diff --git a/src/lt/ekgame/beatmap_analyzer/beatmap/ctb/CatchBananas.java b/src/lt/ekgame/beatmap_analyzer/beatmap/ctb/CatchBananas.java index a3a76398..06e920eb 100644 --- a/src/lt/ekgame/beatmap_analyzer/beatmap/ctb/CatchBananas.java +++ b/src/lt/ekgame/beatmap_analyzer/beatmap/ctb/CatchBananas.java @@ -4,13 +4,13 @@ public class CatchBananas extends CatchObject { - public CatchBananas(Vec2 position, int startTime, int endTime, int hitSound) { - super(position, startTime, endTime, hitSound, false); - } + public CatchBananas(Vec2 position, int startTime, int endTime, int hitSound) { + super(position, startTime, endTime, hitSound, false); + } - @Override - public CatchObject clone() { - return new CatchBananas(position.clone(), startTime, endTime, hitSound); - } + @Override + public CatchObject clone() { + return new CatchBananas(position.clone(), startTime, endTime, hitSound); + } } diff --git a/src/lt/ekgame/beatmap_analyzer/beatmap/ctb/CatchBeatmap.java b/src/lt/ekgame/beatmap_analyzer/beatmap/ctb/CatchBeatmap.java index 9f6ee69c..86738310 100644 --- a/src/lt/ekgame/beatmap_analyzer/beatmap/ctb/CatchBeatmap.java +++ b/src/lt/ekgame/beatmap_analyzer/beatmap/ctb/CatchBeatmap.java @@ -16,48 +16,48 @@ public class CatchBeatmap extends Beatmap { - private List hitObjects; - - public CatchBeatmap(BeatmapGenerals generals, BeatmapEditorState editorState, BeatmapMetadata metadata, - BeatmapDifficulties difficulties, List breaks, List timingPoints, - List hitObjects) { - super(generals, editorState, metadata, difficulties, breaks, timingPoints); - this.hitObjects = hitObjects; - - finalizeObjects(hitObjects); - } - - public List getHitObjects() { - return hitObjects; - } - - @Override - public Gamemode getGamemode() { - return Gamemode.CATCH; - } - - @Override - public Difficulty getDifficulty(Mods mods) { - return null; - } - - @Override - public Difficulty getDifficulty() { - return null; - } - - @Override - public DifficultyCalculator getDifficultyCalculator() { - return null; - } - - @Override - public int getMaxCombo() { - return 0; - } - - @Override - public int getObjectCount() { - return 0; - } + private List hitObjects; + + public CatchBeatmap(BeatmapGenerals generals, BeatmapEditorState editorState, BeatmapMetadata metadata, + BeatmapDifficulties difficulties, List breaks, List timingPoints, + List hitObjects) { + super(generals, editorState, metadata, difficulties, breaks, timingPoints); + this.hitObjects = hitObjects; + + finalizeObjects(hitObjects); + } + + public List getHitObjects() { + return hitObjects; + } + + @Override + public Gamemode getGamemode() { + return Gamemode.CATCH; + } + + @Override + public Difficulty getDifficulty(Mods mods) { + return null; + } + + @Override + public Difficulty getDifficulty() { + return null; + } + + @Override + public DifficultyCalculator getDifficultyCalculator() { + return null; + } + + @Override + public int getMaxCombo() { + return 0; + } + + @Override + public int getObjectCount() { + return 0; + } } diff --git a/src/lt/ekgame/beatmap_analyzer/beatmap/ctb/CatchFruit.java b/src/lt/ekgame/beatmap_analyzer/beatmap/ctb/CatchFruit.java index 6173b6aa..83509e18 100644 --- a/src/lt/ekgame/beatmap_analyzer/beatmap/ctb/CatchFruit.java +++ b/src/lt/ekgame/beatmap_analyzer/beatmap/ctb/CatchFruit.java @@ -4,12 +4,12 @@ public class CatchFruit extends CatchObject { - public CatchFruit(Vec2 position, int startTime, int hitSound, boolean isNewCombo) { - super(position, startTime, startTime, hitSound, isNewCombo); - } - - @Override - public CatchObject clone() { - return new CatchFruit(position.clone(), startTime, hitSound, isNewCombo); - } + public CatchFruit(Vec2 position, int startTime, int hitSound, boolean isNewCombo) { + super(position, startTime, startTime, hitSound, isNewCombo); + } + + @Override + public CatchObject clone() { + return new CatchFruit(position.clone(), startTime, hitSound, isNewCombo); + } } diff --git a/src/lt/ekgame/beatmap_analyzer/beatmap/ctb/CatchObject.java b/src/lt/ekgame/beatmap_analyzer/beatmap/ctb/CatchObject.java index dbe2b7de..b886608c 100644 --- a/src/lt/ekgame/beatmap_analyzer/beatmap/ctb/CatchObject.java +++ b/src/lt/ekgame/beatmap_analyzer/beatmap/ctb/CatchObject.java @@ -5,15 +5,15 @@ public abstract class CatchObject extends HitObject { - protected boolean isNewCombo; + protected boolean isNewCombo; - public CatchObject(Vec2 position, int startTime, int endTime, int hitSound, boolean isNewCombo) { - super(position, startTime, endTime, hitSound); - this.isNewCombo = isNewCombo; - } + public CatchObject(Vec2 position, int startTime, int endTime, int hitSound, boolean isNewCombo) { + super(position, startTime, endTime, hitSound); + this.isNewCombo = isNewCombo; + } - public boolean isNewCombo() { - return isNewCombo; - } + public boolean isNewCombo() { + return isNewCombo; + } } diff --git a/src/lt/ekgame/beatmap_analyzer/beatmap/ctb/CatchSlider.java b/src/lt/ekgame/beatmap_analyzer/beatmap/ctb/CatchSlider.java index 3dee7a01..0c16cc11 100644 --- a/src/lt/ekgame/beatmap_analyzer/beatmap/ctb/CatchSlider.java +++ b/src/lt/ekgame/beatmap_analyzer/beatmap/ctb/CatchSlider.java @@ -4,13 +4,13 @@ public class CatchSlider extends CatchObject { - public CatchSlider(Vec2 position, int startTime, int endTime, int hitSound, boolean isNewCombo) { - super(position, startTime, endTime, hitSound, isNewCombo); - } + public CatchSlider(Vec2 position, int startTime, int endTime, int hitSound, boolean isNewCombo) { + super(position, startTime, endTime, hitSound, isNewCombo); + } - @Override - public CatchObject clone() { - return new CatchSlider(position.clone(), startTime, endTime, hitSound, isNewCombo); - } + @Override + public CatchObject clone() { + return new CatchSlider(position.clone(), startTime, endTime, hitSound, isNewCombo); + } } diff --git a/src/lt/ekgame/beatmap_analyzer/beatmap/mania/ManiaBeatmap.java b/src/lt/ekgame/beatmap_analyzer/beatmap/mania/ManiaBeatmap.java index 18589ef8..8fdeb415 100644 --- a/src/lt/ekgame/beatmap_analyzer/beatmap/mania/ManiaBeatmap.java +++ b/src/lt/ekgame/beatmap_analyzer/beatmap/mania/ManiaBeatmap.java @@ -16,59 +16,59 @@ public class ManiaBeatmap extends Beatmap { - private List hitObjects; - - public ManiaBeatmap(BeatmapGenerals generals, BeatmapEditorState editorState, BeatmapMetadata metadata, - BeatmapDifficulties difficulties, List breaks, List timingPoints, - List hitObjects) { - super(generals, editorState, metadata, difficulties, breaks, timingPoints); - this.hitObjects = hitObjects; - - finalizeObjects(hitObjects); - } - - @Override - public Gamemode getGamemode() { - return Gamemode.MANIA; - } - - @Override - public ManiaDifficultyCalculator getDifficultyCalculator() { - return new ManiaDifficultyCalculator(); - } - - @Override - public ManiaDifficulty getDifficulty(Mods mods) { - return getDifficultyCalculator().calculate(mods, this); - } - - @Override - public ManiaDifficulty getDifficulty() { - return getDifficulty(Mods.NOMOD); - } - - public List getHitObjects() { - return hitObjects; - } - - public int getCollumns() { - return (int) difficulties.getCS(); - } - - @Override - public int getMaxCombo() { - int c = 0; - for (ManiaObject h : hitObjects) { - c += h.getCombo(); - } - - return c; - - //return hitObjects.stream().mapToInt(o->o.getCombo()).sum(); - } - - @Override - public int getObjectCount() { - return hitObjects.size(); - } + private List hitObjects; + + public ManiaBeatmap(BeatmapGenerals generals, BeatmapEditorState editorState, BeatmapMetadata metadata, + BeatmapDifficulties difficulties, List breaks, List timingPoints, + List hitObjects) { + super(generals, editorState, metadata, difficulties, breaks, timingPoints); + this.hitObjects = hitObjects; + + finalizeObjects(hitObjects); + } + + @Override + public Gamemode getGamemode() { + return Gamemode.MANIA; + } + + @Override + public ManiaDifficultyCalculator getDifficultyCalculator() { + return new ManiaDifficultyCalculator(); + } + + @Override + public ManiaDifficulty getDifficulty(Mods mods) { + return getDifficultyCalculator().calculate(mods, this); + } + + @Override + public ManiaDifficulty getDifficulty() { + return getDifficulty(Mods.NOMOD); + } + + public List getHitObjects() { + return hitObjects; + } + + public int getCollumns() { + return (int) difficulties.getCS(); + } + + @Override + public int getMaxCombo() { + int c = 0; + for (ManiaObject h : hitObjects) { + c += h.getCombo(); + } + + return c; + + //return hitObjects.stream().mapToInt(o->o.getCombo()).sum(); + } + + @Override + public int getObjectCount() { + return hitObjects.size(); + } } diff --git a/src/lt/ekgame/beatmap_analyzer/beatmap/mania/ManiaHold.java b/src/lt/ekgame/beatmap_analyzer/beatmap/mania/ManiaHold.java index 78194709..34de8ca8 100644 --- a/src/lt/ekgame/beatmap_analyzer/beatmap/mania/ManiaHold.java +++ b/src/lt/ekgame/beatmap_analyzer/beatmap/mania/ManiaHold.java @@ -4,13 +4,13 @@ public class ManiaHold extends ManiaObject { - public ManiaHold(Vec2 position, int startTime, int endTime, int hitSound) { - super(position, startTime, endTime, hitSound); - } + public ManiaHold(Vec2 position, int startTime, int endTime, int hitSound) { + super(position, startTime, endTime, hitSound); + } - @Override - public ManiaObject clone() { - return new ManiaHold(position.clone(), startTime, endTime, hitSound); - } + @Override + public ManiaObject clone() { + return new ManiaHold(position.clone(), startTime, endTime, hitSound); + } } diff --git a/src/lt/ekgame/beatmap_analyzer/beatmap/mania/ManiaObject.java b/src/lt/ekgame/beatmap_analyzer/beatmap/mania/ManiaObject.java index 6c03cdc1..f938f4c8 100644 --- a/src/lt/ekgame/beatmap_analyzer/beatmap/mania/ManiaObject.java +++ b/src/lt/ekgame/beatmap_analyzer/beatmap/mania/ManiaObject.java @@ -8,20 +8,20 @@ public abstract class ManiaObject extends HitObject { - private int collumn; + private int collumn; - public ManiaObject(Vec2 position, int startTime, int endTime, int hitSound) { - super(position, startTime, endTime, hitSound); - } + public ManiaObject(Vec2 position, int startTime, int endTime, int hitSound) { + super(position, startTime, endTime, hitSound); + } - @Override - public void finalize(TimingPoint current, TimingPoint parent, Beatmap beatmap) { - int numCollumns = ((ManiaBeatmap) beatmap).getCollumns(); - collumn = MathUtils.calculateManiaCollumn(position.getX(), numCollumns); - } + @Override + public void finalize(TimingPoint current, TimingPoint parent, Beatmap beatmap) { + int numCollumns = ((ManiaBeatmap) beatmap).getCollumns(); + collumn = MathUtils.calculateManiaCollumn(position.getX(), numCollumns); + } - public int getCollumn() { - return collumn; - } + public int getCollumn() { + return collumn; + } } diff --git a/src/lt/ekgame/beatmap_analyzer/beatmap/mania/ManiaSingle.java b/src/lt/ekgame/beatmap_analyzer/beatmap/mania/ManiaSingle.java index d28a21fd..716a7d21 100644 --- a/src/lt/ekgame/beatmap_analyzer/beatmap/mania/ManiaSingle.java +++ b/src/lt/ekgame/beatmap_analyzer/beatmap/mania/ManiaSingle.java @@ -4,13 +4,13 @@ public class ManiaSingle extends ManiaObject { - public ManiaSingle(Vec2 position, int startTime, int hitSound) { - super(position, startTime, startTime, hitSound); - } + public ManiaSingle(Vec2 position, int startTime, int hitSound) { + super(position, startTime, startTime, hitSound); + } - @Override - public ManiaObject clone() { - return new ManiaSingle(position.clone(), startTime, hitSound); - } + @Override + public ManiaObject clone() { + return new ManiaSingle(position.clone(), startTime, hitSound); + } } diff --git a/src/lt/ekgame/beatmap_analyzer/beatmap/osu/OsuBeatmap.java b/src/lt/ekgame/beatmap_analyzer/beatmap/osu/OsuBeatmap.java index 74ff1d9f..ef363389 100644 --- a/src/lt/ekgame/beatmap_analyzer/beatmap/osu/OsuBeatmap.java +++ b/src/lt/ekgame/beatmap_analyzer/beatmap/osu/OsuBeatmap.java @@ -18,100 +18,100 @@ public class OsuBeatmap extends Beatmap { - private List hitObjects; - - public OsuBeatmap(BeatmapGenerals generals, BeatmapEditorState editorState, BeatmapMetadata metadata, - BeatmapDifficulties difficulties, List breaks, List timingPoints, List hitObjects) { - super(generals, editorState, metadata, difficulties, breaks, timingPoints); - this.hitObjects = hitObjects; - - finalizeObjects(hitObjects); - - applyDroid(); - } - - private void applyDroid() { - difficulties.setCS(difficulties.getCS() / 1.3); - } - - public double getOD() { - return difficulties.getOD(); - } - - public double getOD(Mods mods) { - if (!mods.isMapChanging()) - return getOD(); - - double odMultiplier = 1; - if (mods.has(Mod.HARDROCK)) odMultiplier *= 1.4; - if (mods.has(Mod.EASY)) odMultiplier *= 0.5; - return MathUtils.recalculateOverallDifficulty(getOD(), odMultiplier, mods.getSpeedMultiplier()); - } - - public double getAR() { - return difficulties.getAR(); - } - - public double getAR(Mods mods) { - if (!mods.isMapChanging()) - return getAR(); - - double arMultiplier = 1; - if (mods.has(Mod.HARDROCK)) arMultiplier *= 1.4; - if (mods.has(Mod.EASY)) arMultiplier *= 0.5; - return MathUtils.recalculateApproachRate(getAR(), arMultiplier, mods.getSpeedMultiplier()); - } - - public double getCS() { - return difficulties.getCS(); - } - - public double getCS(Mods mods) { - if (!mods.isMapChanging()) - return getCS(); - - double csMultiplier = 1; - if (mods.has(Mod.HARDROCK)) csMultiplier *= 1.3; - if (mods.has(Mod.EASY)) csMultiplier *= 0.5; - return MathUtils.recalculateCircleSize(getCS(), csMultiplier); - } - - @Override - public Gamemode getGamemode() { - return Gamemode.OSU; - } - - @Override - public int getMaxCombo() { - int c = 0; - for (OsuObject o : hitObjects) { - c += o.getCombo(); - } - return c; - //hitObjects.stream().mapToInt(o->o.getCombo()).sum(); - } - - public List getHitObjects() { - return hitObjects; - } - - @Override - public int getObjectCount() { - return hitObjects.size(); - } - - @Override - public OsuDifficultyCalculator getDifficultyCalculator() { - return new OsuDifficultyCalculator(); - } - - @Override - public OsuDifficulty getDifficulty(Mods mods) { - return getDifficultyCalculator().calculate(mods, this); - } - - @Override - public OsuDifficulty getDifficulty() { - return getDifficulty(Mods.NOMOD); - } + private List hitObjects; + + public OsuBeatmap(BeatmapGenerals generals, BeatmapEditorState editorState, BeatmapMetadata metadata, + BeatmapDifficulties difficulties, List breaks, List timingPoints, List hitObjects) { + super(generals, editorState, metadata, difficulties, breaks, timingPoints); + this.hitObjects = hitObjects; + + finalizeObjects(hitObjects); + + applyDroid(); + } + + private void applyDroid() { + difficulties.setCS(difficulties.getCS() / 1.3); + } + + public double getOD() { + return difficulties.getOD(); + } + + public double getOD(Mods mods) { + if (!mods.isMapChanging()) + return getOD(); + + double odMultiplier = 1; + if (mods.has(Mod.HARDROCK)) odMultiplier *= 1.4; + if (mods.has(Mod.EASY)) odMultiplier *= 0.5; + return MathUtils.recalculateOverallDifficulty(getOD(), odMultiplier, mods.getSpeedMultiplier()); + } + + public double getAR() { + return difficulties.getAR(); + } + + public double getAR(Mods mods) { + if (!mods.isMapChanging()) + return getAR(); + + double arMultiplier = 1; + if (mods.has(Mod.HARDROCK)) arMultiplier *= 1.4; + if (mods.has(Mod.EASY)) arMultiplier *= 0.5; + return MathUtils.recalculateApproachRate(getAR(), arMultiplier, mods.getSpeedMultiplier()); + } + + public double getCS() { + return difficulties.getCS(); + } + + public double getCS(Mods mods) { + if (!mods.isMapChanging()) + return getCS(); + + double csMultiplier = 1; + if (mods.has(Mod.HARDROCK)) csMultiplier *= 1.3; + if (mods.has(Mod.EASY)) csMultiplier *= 0.5; + return MathUtils.recalculateCircleSize(getCS(), csMultiplier); + } + + @Override + public Gamemode getGamemode() { + return Gamemode.OSU; + } + + @Override + public int getMaxCombo() { + int c = 0; + for (OsuObject o : hitObjects) { + c += o.getCombo(); + } + return c; + //hitObjects.stream().mapToInt(o->o.getCombo()).sum(); + } + + public List getHitObjects() { + return hitObjects; + } + + @Override + public int getObjectCount() { + return hitObjects.size(); + } + + @Override + public OsuDifficultyCalculator getDifficultyCalculator() { + return new OsuDifficultyCalculator(); + } + + @Override + public OsuDifficulty getDifficulty(Mods mods) { + return getDifficultyCalculator().calculate(mods, this); + } + + @Override + public OsuDifficulty getDifficulty() { + return getDifficulty(Mods.NOMOD); + } } diff --git a/src/lt/ekgame/beatmap_analyzer/beatmap/osu/OsuCircle.java b/src/lt/ekgame/beatmap_analyzer/beatmap/osu/OsuCircle.java index 3cf75573..6c75d064 100644 --- a/src/lt/ekgame/beatmap_analyzer/beatmap/osu/OsuCircle.java +++ b/src/lt/ekgame/beatmap_analyzer/beatmap/osu/OsuCircle.java @@ -4,13 +4,13 @@ public class OsuCircle extends OsuObject { - public OsuCircle(Vec2 position, int timestamp, int hitSound, boolean isNewCombo) { - super(position, timestamp, timestamp, hitSound, isNewCombo); - } + public OsuCircle(Vec2 position, int timestamp, int hitSound, boolean isNewCombo) { + super(position, timestamp, timestamp, hitSound, isNewCombo); + } - @Override - public OsuObject clone() { - return new OsuCircle(position.clone(), startTime, hitSound, isNewCombo); - } + @Override + public OsuObject clone() { + return new OsuCircle(position.clone(), startTime, hitSound, isNewCombo); + } } diff --git a/src/lt/ekgame/beatmap_analyzer/beatmap/osu/OsuObject.java b/src/lt/ekgame/beatmap_analyzer/beatmap/osu/OsuObject.java index 87484b64..f4b7d438 100644 --- a/src/lt/ekgame/beatmap_analyzer/beatmap/osu/OsuObject.java +++ b/src/lt/ekgame/beatmap_analyzer/beatmap/osu/OsuObject.java @@ -5,14 +5,14 @@ public abstract class OsuObject extends HitObject { - protected boolean isNewCombo; + protected boolean isNewCombo; - public OsuObject(Vec2 position, int startTime, int endTime, int hitSound, boolean isNewCombo) { - super(position, startTime, endTime, hitSound); - this.isNewCombo = isNewCombo; - } + public OsuObject(Vec2 position, int startTime, int endTime, int hitSound, boolean isNewCombo) { + super(position, startTime, endTime, hitSound); + this.isNewCombo = isNewCombo; + } - public boolean isNewCombo() { - return isNewCombo; - } + public boolean isNewCombo() { + return isNewCombo; + } } diff --git a/src/lt/ekgame/beatmap_analyzer/beatmap/osu/OsuSlider.java b/src/lt/ekgame/beatmap_analyzer/beatmap/osu/OsuSlider.java index e534a7e7..08eb7a4a 100644 --- a/src/lt/ekgame/beatmap_analyzer/beatmap/osu/OsuSlider.java +++ b/src/lt/ekgame/beatmap_analyzer/beatmap/osu/OsuSlider.java @@ -9,88 +9,88 @@ public class OsuSlider extends OsuObject { - private SliderType sliderType; - private List sliderPoints; - private int repetitions; - private double pixelLength; - private int combo; - - public OsuSlider(Vec2 position, int startTime, int hitSound, boolean isNewCombo, SliderType sliderType, List sliderPoints, int repetitions, double pixelLength) { - super(position, startTime, startTime, hitSound, isNewCombo); - this.sliderType = sliderType; - this.sliderPoints = sliderPoints; - this.repetitions = repetitions; - this.pixelLength = pixelLength; - } - - @Override - public OsuObject clone() { - return new OsuSlider(position.clone(), startTime, hitSound, isNewCombo, sliderType, cloneSliderPoints(), repetitions, pixelLength); - } - - @Override - public void finalize(TimingPoint current, TimingPoint parent, Beatmap beatmap) { - double velocityMultiplier = 1; - if (current.isInherited() && current.getBeatLength() < 0) - velocityMultiplier = -100 / current.getBeatLength(); - - double pixelsPerBeat = beatmap.getDifficultySettings().getSliderMultiplier() * 100 * velocityMultiplier; - double beats = pixelLength * repetitions / pixelsPerBeat; - int duration = (int) Math.ceil(beats * parent.getBeatLength()); - endTime = startTime + duration; - - combo = (int) Math.ceil((beats - 0.01) / repetitions * beatmap.getDifficultySettings().getTickRate()) - 1; - combo *= repetitions; - combo += repetitions + 1; // head and tail - } - - @Override - public int getCombo() { - return combo; - } - - private List cloneSliderPoints() { - List r = new ArrayList(sliderPoints.size()); - for (int i = 0; i < sliderPoints.size(); i++) { - r.add(i, sliderPoints.get(i).clone()); - } - - return r; - - //return sliderPoints.stream().map(o->o.clone()).collect(Collectors.toList()); - } - - public SliderType getSliderType() { - return sliderType; - } - - public List getSliderPoints() { - return sliderPoints; - } - - public int getRepetitions() { - return repetitions; - } - - public double getPixelLength() { - return pixelLength; - } - - public enum SliderType { - LINEAR, ARC, BAZIER, CATMULL, INVALID; - - public static SliderType fromChar(char c) { - switch (c) { - case 'L': - return LINEAR; - case 'P': - return ARC; - case 'B': - return BAZIER; - case 'C': - return CATMULL; - } - return INVALID; - } - } + private SliderType sliderType; + private List sliderPoints; + private int repetitions; + private double pixelLength; + private int combo; + + public OsuSlider(Vec2 position, int startTime, int hitSound, boolean isNewCombo, SliderType sliderType, List sliderPoints, int repetitions, double pixelLength) { + super(position, startTime, startTime, hitSound, isNewCombo); + this.sliderType = sliderType; + this.sliderPoints = sliderPoints; + this.repetitions = repetitions; + this.pixelLength = pixelLength; + } + + @Override + public OsuObject clone() { + return new OsuSlider(position.clone(), startTime, hitSound, isNewCombo, sliderType, cloneSliderPoints(), repetitions, pixelLength); + } + + @Override + public void finalize(TimingPoint current, TimingPoint parent, Beatmap beatmap) { + double velocityMultiplier = 1; + if (current.isInherited() && current.getBeatLength() < 0) + velocityMultiplier = -100 / current.getBeatLength(); + + double pixelsPerBeat = beatmap.getDifficultySettings().getSliderMultiplier() * 100 * velocityMultiplier; + double beats = pixelLength * repetitions / pixelsPerBeat; + int duration = (int) Math.ceil(beats * parent.getBeatLength()); + endTime = startTime + duration; + + combo = (int) Math.ceil((beats - 0.01) / repetitions * beatmap.getDifficultySettings().getTickRate()) - 1; + combo *= repetitions; + combo += repetitions + 1; // head and tail + } + + @Override + public int getCombo() { + return combo; + } + + private List cloneSliderPoints() { + List r = new ArrayList(sliderPoints.size()); + for (int i = 0; i < sliderPoints.size(); i++) { + r.add(i, sliderPoints.get(i).clone()); + } + + return r; + + //return sliderPoints.stream().map(o->o.clone()).collect(Collectors.toList()); + } + + public SliderType getSliderType() { + return sliderType; + } + + public List getSliderPoints() { + return sliderPoints; + } + + public int getRepetitions() { + return repetitions; + } + + public double getPixelLength() { + return pixelLength; + } + + public enum SliderType { + LINEAR, ARC, BAZIER, CATMULL, INVALID; + + public static SliderType fromChar(char c) { + switch (c) { + case 'L': + return LINEAR; + case 'P': + return ARC; + case 'B': + return BAZIER; + case 'C': + return CATMULL; + } + return INVALID; + } + } } diff --git a/src/lt/ekgame/beatmap_analyzer/beatmap/osu/OsuSpinner.java b/src/lt/ekgame/beatmap_analyzer/beatmap/osu/OsuSpinner.java index a6a737f3..53affd4a 100644 --- a/src/lt/ekgame/beatmap_analyzer/beatmap/osu/OsuSpinner.java +++ b/src/lt/ekgame/beatmap_analyzer/beatmap/osu/OsuSpinner.java @@ -4,12 +4,12 @@ public class OsuSpinner extends OsuObject { - public OsuSpinner(Vec2 position, int startTime, int endTime, int hitSound, boolean isNewCombo) { - super(position, startTime, endTime, hitSound, isNewCombo); - } - - @Override - public OsuObject clone() { - return new OsuSpinner(position.clone(), startTime, endTime, hitSound, isNewCombo); - } + public OsuSpinner(Vec2 position, int startTime, int endTime, int hitSound, boolean isNewCombo) { + super(position, startTime, endTime, hitSound, isNewCombo); + } + + @Override + public OsuObject clone() { + return new OsuSpinner(position.clone(), startTime, endTime, hitSound, isNewCombo); + } } diff --git a/src/lt/ekgame/beatmap_analyzer/beatmap/taiko/TaikoBeatmap.java b/src/lt/ekgame/beatmap_analyzer/beatmap/taiko/TaikoBeatmap.java index c8a2d07a..ed7afe86 100644 --- a/src/lt/ekgame/beatmap_analyzer/beatmap/taiko/TaikoBeatmap.java +++ b/src/lt/ekgame/beatmap_analyzer/beatmap/taiko/TaikoBeatmap.java @@ -17,54 +17,54 @@ public class TaikoBeatmap extends Beatmap { - private List hitObjects; + private List hitObjects; - public TaikoBeatmap(BeatmapGenerals generals, BeatmapEditorState editorState, BeatmapMetadata metadata, - BeatmapDifficulties difficulties, List breaks, List timingPoints, - List hitObjects) { - super(generals, editorState, metadata, difficulties, breaks, timingPoints); - this.hitObjects = hitObjects; - finalizeObjects(hitObjects); - } + public TaikoBeatmap(BeatmapGenerals generals, BeatmapEditorState editorState, BeatmapMetadata metadata, + BeatmapDifficulties difficulties, List breaks, List timingPoints, + List hitObjects) { + super(generals, editorState, metadata, difficulties, breaks, timingPoints); + this.hitObjects = hitObjects; + finalizeObjects(hitObjects); + } - @Override - public Gamemode getGamemode() { - return Gamemode.TAIKO; - } + @Override + public Gamemode getGamemode() { + return Gamemode.TAIKO; + } - @Override - public int getMaxCombo() { - int c = 0; - for (HitObject o : hitObjects) { - if (o instanceof TaikoCircle) c++; - } + @Override + public int getMaxCombo() { + int c = 0; + for (HitObject o : hitObjects) { + if (o instanceof TaikoCircle) c++; + } - return c; - //(int) hitObjects.stream().filter(o->o instanceof TaikoCircle).count(); - } + return c; + //(int) hitObjects.stream().filter(o->o instanceof TaikoCircle).count(); + } - public List getHitObjects() { - return hitObjects; - } + public List getHitObjects() { + return hitObjects; + } - @Override - public int getObjectCount() { - return hitObjects.size(); - } + @Override + public int getObjectCount() { + return hitObjects.size(); + } - @Override - public TaikoDifficultyCalculator getDifficultyCalculator() { - return new TaikoDifficultyCalculator(); - } + @Override + public TaikoDifficultyCalculator getDifficultyCalculator() { + return new TaikoDifficultyCalculator(); + } - @Override - public TaikoDifficulty getDifficulty(Mods mods) { - return getDifficultyCalculator().calculate(mods, this); - } + @Override + public TaikoDifficulty getDifficulty(Mods mods) { + return getDifficultyCalculator().calculate(mods, this); + } - @Override - public TaikoDifficulty getDifficulty() { - return getDifficulty(Mods.NOMOD); - } + @Override + public TaikoDifficulty getDifficulty() { + return getDifficulty(Mods.NOMOD); + } } diff --git a/src/lt/ekgame/beatmap_analyzer/beatmap/taiko/TaikoCircle.java b/src/lt/ekgame/beatmap_analyzer/beatmap/taiko/TaikoCircle.java index e2243bd5..e5687de2 100644 --- a/src/lt/ekgame/beatmap_analyzer/beatmap/taiko/TaikoCircle.java +++ b/src/lt/ekgame/beatmap_analyzer/beatmap/taiko/TaikoCircle.java @@ -4,29 +4,29 @@ public class TaikoCircle extends TaikoObject { - private TaikoColor color; - private boolean isBig; - - public TaikoCircle(Vec2 position, int startTime, int hitSound, TaikoColor color, boolean isBig) { - super(position, startTime, startTime, hitSound); - this.color = color; - this.isBig = isBig; - } - - @Override - public TaikoObject clone() { - return new TaikoCircle(position.clone(), startTime, hitSound, color, isBig); - } - - public TaikoColor getColor() { - return color; - } - - public boolean isBig() { - return isBig; - } - - public enum TaikoColor { - RED, BLUE - } + private TaikoColor color; + private boolean isBig; + + public TaikoCircle(Vec2 position, int startTime, int hitSound, TaikoColor color, boolean isBig) { + super(position, startTime, startTime, hitSound); + this.color = color; + this.isBig = isBig; + } + + @Override + public TaikoObject clone() { + return new TaikoCircle(position.clone(), startTime, hitSound, color, isBig); + } + + public TaikoColor getColor() { + return color; + } + + public boolean isBig() { + return isBig; + } + + public enum TaikoColor { + RED, BLUE + } } diff --git a/src/lt/ekgame/beatmap_analyzer/beatmap/taiko/TaikoDrumroll.java b/src/lt/ekgame/beatmap_analyzer/beatmap/taiko/TaikoDrumroll.java index ab9a1485..62210b48 100644 --- a/src/lt/ekgame/beatmap_analyzer/beatmap/taiko/TaikoDrumroll.java +++ b/src/lt/ekgame/beatmap_analyzer/beatmap/taiko/TaikoDrumroll.java @@ -4,22 +4,22 @@ public class TaikoDrumroll extends TaikoObject { - private double pixelLength; - private boolean isBig; + private double pixelLength; + private boolean isBig; - public TaikoDrumroll(Vec2 position, int startTime, int hitSound, double pixelLength, boolean isBig) { - super(position, startTime, startTime, hitSound); - this.pixelLength = pixelLength; - this.isBig = isBig; - } + public TaikoDrumroll(Vec2 position, int startTime, int hitSound, double pixelLength, boolean isBig) { + super(position, startTime, startTime, hitSound); + this.pixelLength = pixelLength; + this.isBig = isBig; + } - @Override - public TaikoObject clone() { - return new TaikoDrumroll(position.clone(), startTime, hitSound, pixelLength, isBig); - } + @Override + public TaikoObject clone() { + return new TaikoDrumroll(position.clone(), startTime, hitSound, pixelLength, isBig); + } - @Override - public int getCombo() { - return 0; - } + @Override + public int getCombo() { + return 0; + } } diff --git a/src/lt/ekgame/beatmap_analyzer/beatmap/taiko/TaikoObject.java b/src/lt/ekgame/beatmap_analyzer/beatmap/taiko/TaikoObject.java index 4142c605..39d8ed49 100644 --- a/src/lt/ekgame/beatmap_analyzer/beatmap/taiko/TaikoObject.java +++ b/src/lt/ekgame/beatmap_analyzer/beatmap/taiko/TaikoObject.java @@ -5,7 +5,7 @@ public abstract class TaikoObject extends HitObject { - public TaikoObject(Vec2 position, int startTime, int endTime, int hitSound) { - super(position, startTime, endTime, hitSound); - } + public TaikoObject(Vec2 position, int startTime, int endTime, int hitSound) { + super(position, startTime, endTime, hitSound); + } } diff --git a/src/lt/ekgame/beatmap_analyzer/beatmap/taiko/TaikoShaker.java b/src/lt/ekgame/beatmap_analyzer/beatmap/taiko/TaikoShaker.java index dd698d0a..7d2b8ac4 100644 --- a/src/lt/ekgame/beatmap_analyzer/beatmap/taiko/TaikoShaker.java +++ b/src/lt/ekgame/beatmap_analyzer/beatmap/taiko/TaikoShaker.java @@ -5,17 +5,17 @@ public class TaikoShaker extends TaikoObject { - public TaikoShaker(Vec2 position, int startTime, int endTime, int hitSound) { - super(position, startTime, endTime, hitSound); - } + public TaikoShaker(Vec2 position, int startTime, int endTime, int hitSound) { + super(position, startTime, endTime, hitSound); + } - @Override - public HitObject clone() { - return new TaikoShaker(position.clone(), startTime, endTime, hitSound); - } + @Override + public HitObject clone() { + return new TaikoShaker(position.clone(), startTime, endTime, hitSound); + } - @Override - public int getCombo() { - return 0; - } + @Override + public int getCombo() { + return 0; + } } diff --git a/src/lt/ekgame/beatmap_analyzer/difficulty/Difficulty.java b/src/lt/ekgame/beatmap_analyzer/difficulty/Difficulty.java index 31140dd7..a17c3f20 100644 --- a/src/lt/ekgame/beatmap_analyzer/difficulty/Difficulty.java +++ b/src/lt/ekgame/beatmap_analyzer/difficulty/Difficulty.java @@ -10,49 +10,49 @@ public abstract class Difficulty { - protected Beatmap beatmap; - protected Mods mods; - protected double starDiff; - //protected List strains; - - public Difficulty(Beatmap beatmap, Mods mods, double starDiff, List strains) { - this.beatmap = beatmap; - this.mods = mods; - this.starDiff = starDiff; - //this.strains = strains; - } - - public abstract Performance getPerformance(Score score); - - public double getSpeedMultiplier() { - return mods.getSpeedMultiplier(); - } - - public double getOD() { - return beatmap.getDifficultySettings().getOD(); - } - - public Beatmap getBeatmap() { - return beatmap; - } - - public Mods getMods() { - return mods; - } - - public double getStars() { - return starDiff; - } - - public int getMaxCombo() { - return beatmap.getMaxCombo(); - } - - public int getObjectCount() { - return beatmap.getObjectCount(); - } - - public boolean hasMod(Mod mod) { - return mods.has(mod); - } + protected Beatmap beatmap; + protected Mods mods; + protected double starDiff; + //protected List strains; + + public Difficulty(Beatmap beatmap, Mods mods, double starDiff, List strains) { + this.beatmap = beatmap; + this.mods = mods; + this.starDiff = starDiff; + //this.strains = strains; + } + + public abstract Performance getPerformance(Score score); + + public double getSpeedMultiplier() { + return mods.getSpeedMultiplier(); + } + + public double getOD() { + return beatmap.getDifficultySettings().getOD(); + } + + public Beatmap getBeatmap() { + return beatmap; + } + + public Mods getMods() { + return mods; + } + + public double getStars() { + return starDiff; + } + + public int getMaxCombo() { + return beatmap.getMaxCombo(); + } + + public int getObjectCount() { + return beatmap.getObjectCount(); + } + + public boolean hasMod(Mod mod) { + return mods.has(mod); + } } diff --git a/src/lt/ekgame/beatmap_analyzer/difficulty/DifficultyCalculator.java b/src/lt/ekgame/beatmap_analyzer/difficulty/DifficultyCalculator.java index c653ade2..39cf2f35 100644 --- a/src/lt/ekgame/beatmap_analyzer/difficulty/DifficultyCalculator.java +++ b/src/lt/ekgame/beatmap_analyzer/difficulty/DifficultyCalculator.java @@ -7,8 +7,8 @@ public interface DifficultyCalculator { - public Difficulty calculate(Mods mods, Beatmap beatmap); + public Difficulty calculate(Mods mods, Beatmap beatmap); - public double calculateDifficulty(List strains); + public double calculateDifficulty(List strains); } diff --git a/src/lt/ekgame/beatmap_analyzer/difficulty/ManiaDifficulty.java b/src/lt/ekgame/beatmap_analyzer/difficulty/ManiaDifficulty.java index 96a4d72c..fdf13071 100644 --- a/src/lt/ekgame/beatmap_analyzer/difficulty/ManiaDifficulty.java +++ b/src/lt/ekgame/beatmap_analyzer/difficulty/ManiaDifficulty.java @@ -10,12 +10,12 @@ public class ManiaDifficulty extends Difficulty { - public ManiaDifficulty(ManiaBeatmap beatmap, Mods mods, double starDiff, List strains) { - super(beatmap, mods, starDiff, strains); - } + public ManiaDifficulty(ManiaBeatmap beatmap, Mods mods, double starDiff, List strains) { + super(beatmap, mods, starDiff, strains); + } - @Override - public Performance getPerformance(Score score) { - return new ManiaPerformanceCalculator().calculate(this, score); - } + @Override + public Performance getPerformance(Score score) { + return new ManiaPerformanceCalculator().calculate(this, score); + } } diff --git a/src/lt/ekgame/beatmap_analyzer/difficulty/ManiaDifficultyCalculator.java b/src/lt/ekgame/beatmap_analyzer/difficulty/ManiaDifficultyCalculator.java index 260321da..d0c25324 100644 --- a/src/lt/ekgame/beatmap_analyzer/difficulty/ManiaDifficultyCalculator.java +++ b/src/lt/ekgame/beatmap_analyzer/difficulty/ManiaDifficultyCalculator.java @@ -14,141 +14,141 @@ public class ManiaDifficultyCalculator implements DifficultyCalculator { - public static final double STAR_SCALING_FACTOR = 0.018; - - public static final double INDIVIDUAL_DECAY_BASE = 0.125; - public static final double OVERALL_DECAY_BASE = 0.3; - - public static final double DECAY_WEIGHT = 0.9; - public static final int STRAIN_STEP = 400; - - public ManiaDifficulty calculate(Mods mods, Beatmap beatmap) { - ManiaBeatmap bm = (ManiaBeatmap) beatmap; - double timeRate = mods.getSpeedMultiplier(); - List hitObjects = bm.getHitObjects(); - List objects = generateDifficultyObjects(hitObjects, timeRate, bm.getCollumns()); - List strains = calculateStrains(objects, timeRate); - List originalStrains = new ArrayList<>(strains); - double difficulty = calculateDifficulty(strains); - return new ManiaDifficulty(bm, mods, difficulty, originalStrains); - } - - private List generateDifficultyObjects(List hitObjects, double timeRate, - int collumns) { - - List difficultyObjects = new ArrayList(hitObjects.size()); - for (int i = 0; i < hitObjects.size(); i++) { - difficultyObjects.add(i, new DifficultyObject(hitObjects.get(i), collumns)); - } - - //hitObjects.stream().map(o -> new DifficultyObject(o, collumns)) - // .sorted((a, b)-> a.object.getStartTime() - - // b.object.getStartTime()) - // .collect(Collectors.toList()); - - // .NET 4.0 framework uses quicksort - an unstable algorithm, which means - // that objects with equal value may change order. - // This algorithm depends on the order of the difficulty objects. - // Mania has lots of notes on the same timestamp. - Quicksort.sort(difficultyObjects); - // This is still not precise and might produce about 0.05 error for the final result. - // Because of this error, the current highest PP score is calculated - // as if it is worth 7.73pp more (actual: 1209.12pp, calculated: 1216.85) - - DifficultyObject previous = null; - for (DifficultyObject current : difficultyObjects) { - if (previous != null) - current.calculateStrains(previous, timeRate, collumns); - previous = current; - } - - return difficultyObjects; - } - - private List calculateStrains(List difficultyObjects, double timeRate) { - List highestStrains = new ArrayList<>(); - double realStrainStep = STRAIN_STEP * timeRate; - double intervalEnd = realStrainStep; - double maxStrain = 0; - - DifficultyObject previous = null; - for (DifficultyObject current : difficultyObjects) { - while (current.object.getStartTime() > intervalEnd) { - highestStrains.add(maxStrain); - if (previous != null) { - double individualDecay = Math.pow(INDIVIDUAL_DECAY_BASE, - (intervalEnd - previous.object.getStartTime()) / 1000.0); - double overallDecay = Math.pow(OVERALL_DECAY_BASE, - (intervalEnd - previous.object.getStartTime()) / 1000.0); - maxStrain = previous.individualStrains[previous.collumn] * individualDecay - + previous.strain * overallDecay; - } - intervalEnd += realStrainStep; - } - maxStrain = Math.max(maxStrain, current.individualStrains[current.collumn] + current.strain); - previous = current; - } - return highestStrains; - } - - public double calculateDifficulty(List strains) { - Collections.sort(strains, new Comparator() { - @Override - public int compare(Double a, Double b) { - return b.compareTo(a); - } - });//b.compareTo(a)); - double difficulty = 0, weight = 1; - for (double strain : strains) { - difficulty += weight * strain; - weight *= DECAY_WEIGHT; - } - return difficulty * STAR_SCALING_FACTOR; - } - - class DifficultyObject implements Comparable { - - private final ManiaObject object; - private final int collumn; - private double strain = 1; - private double[] individualStrains; - private double[] heldUntil; - DifficultyObject(ManiaObject object, int collumns) { - this.object = object; - - individualStrains = new double[collumns]; - heldUntil = new double[collumns]; - collumn = MathUtils.calculateManiaCollumn(object.getPosition().getX(), collumns); - } - - @Override - public int compareTo(DifficultyObject o) { - return object.getStartTime() - o.object.getStartTime(); - } - - private void calculateStrains(DifficultyObject previous, double timeRate, int collumns) { - double timeElapsed = (object.getStartTime() - previous.object.getStartTime()) / timeRate; - double individualDecay = Math.pow(INDIVIDUAL_DECAY_BASE, timeElapsed / 1000); - double overallDecay = Math.pow(OVERALL_DECAY_BASE, timeElapsed / 1000); - double holdFactor = 1; - double holdAddition = 0; - - for (int i = 0; i < collumns; i++) { - heldUntil[i] = previous.heldUntil[i]; - - if (object.getStartTime() < heldUntil[i] && object.getEndTime() > heldUntil[i] - && object.getEndTime() != heldUntil[i]) - holdAddition = 1; - - if (heldUntil[i] > object.getEndTime()) - holdFactor = 1.25; - - individualStrains[i] = previous.individualStrains[i] * individualDecay; - } - - heldUntil[collumn] = object.getEndTime(); - individualStrains[collumn] += 2 * holdFactor; - strain = previous.strain * overallDecay + (1 + holdAddition) * holdFactor; - } - } + public static final double STAR_SCALING_FACTOR = 0.018; + + public static final double INDIVIDUAL_DECAY_BASE = 0.125; + public static final double OVERALL_DECAY_BASE = 0.3; + + public static final double DECAY_WEIGHT = 0.9; + public static final int STRAIN_STEP = 400; + + public ManiaDifficulty calculate(Mods mods, Beatmap beatmap) { + ManiaBeatmap bm = (ManiaBeatmap) beatmap; + double timeRate = mods.getSpeedMultiplier(); + List hitObjects = bm.getHitObjects(); + List objects = generateDifficultyObjects(hitObjects, timeRate, bm.getCollumns()); + List strains = calculateStrains(objects, timeRate); + List originalStrains = new ArrayList<>(strains); + double difficulty = calculateDifficulty(strains); + return new ManiaDifficulty(bm, mods, difficulty, originalStrains); + } + + private List generateDifficultyObjects(List hitObjects, double timeRate, + int collumns) { + + List difficultyObjects = new ArrayList(hitObjects.size()); + for (int i = 0; i < hitObjects.size(); i++) { + difficultyObjects.add(i, new DifficultyObject(hitObjects.get(i), collumns)); + } + + //hitObjects.stream().map(o -> new DifficultyObject(o, collumns)) + // .sorted((a, b)-> a.object.getStartTime() - + // b.object.getStartTime()) + // .collect(Collectors.toList()); + + // .NET 4.0 framework uses quicksort - an unstable algorithm, which means + // that objects with equal value may change order. + // This algorithm depends on the order of the difficulty objects. + // Mania has lots of notes on the same timestamp. + Quicksort.sort(difficultyObjects); + // This is still not precise and might produce about 0.05 error for the final result. + // Because of this error, the current highest PP score is calculated + // as if it is worth 7.73pp more (actual: 1209.12pp, calculated: 1216.85) + + DifficultyObject previous = null; + for (DifficultyObject current : difficultyObjects) { + if (previous != null) + current.calculateStrains(previous, timeRate, collumns); + previous = current; + } + + return difficultyObjects; + } + + private List calculateStrains(List difficultyObjects, double timeRate) { + List highestStrains = new ArrayList<>(); + double realStrainStep = STRAIN_STEP * timeRate; + double intervalEnd = realStrainStep; + double maxStrain = 0; + + DifficultyObject previous = null; + for (DifficultyObject current : difficultyObjects) { + while (current.object.getStartTime() > intervalEnd) { + highestStrains.add(maxStrain); + if (previous != null) { + double individualDecay = Math.pow(INDIVIDUAL_DECAY_BASE, + (intervalEnd - previous.object.getStartTime()) / 1000.0); + double overallDecay = Math.pow(OVERALL_DECAY_BASE, + (intervalEnd - previous.object.getStartTime()) / 1000.0); + maxStrain = previous.individualStrains[previous.collumn] * individualDecay + + previous.strain * overallDecay; + } + intervalEnd += realStrainStep; + } + maxStrain = Math.max(maxStrain, current.individualStrains[current.collumn] + current.strain); + previous = current; + } + return highestStrains; + } + + public double calculateDifficulty(List strains) { + Collections.sort(strains, new Comparator() { + @Override + public int compare(Double a, Double b) { + return b.compareTo(a); + } + });//b.compareTo(a)); + double difficulty = 0, weight = 1; + for (double strain : strains) { + difficulty += weight * strain; + weight *= DECAY_WEIGHT; + } + return difficulty * STAR_SCALING_FACTOR; + } + + class DifficultyObject implements Comparable { + + private final ManiaObject object; + private final int collumn; + private double strain = 1; + private double[] individualStrains; + private double[] heldUntil; + DifficultyObject(ManiaObject object, int collumns) { + this.object = object; + + individualStrains = new double[collumns]; + heldUntil = new double[collumns]; + collumn = MathUtils.calculateManiaCollumn(object.getPosition().getX(), collumns); + } + + @Override + public int compareTo(DifficultyObject o) { + return object.getStartTime() - o.object.getStartTime(); + } + + private void calculateStrains(DifficultyObject previous, double timeRate, int collumns) { + double timeElapsed = (object.getStartTime() - previous.object.getStartTime()) / timeRate; + double individualDecay = Math.pow(INDIVIDUAL_DECAY_BASE, timeElapsed / 1000); + double overallDecay = Math.pow(OVERALL_DECAY_BASE, timeElapsed / 1000); + double holdFactor = 1; + double holdAddition = 0; + + for (int i = 0; i < collumns; i++) { + heldUntil[i] = previous.heldUntil[i]; + + if (object.getStartTime() < heldUntil[i] && object.getEndTime() > heldUntil[i] + && object.getEndTime() != heldUntil[i]) + holdAddition = 1; + + if (heldUntil[i] > object.getEndTime()) + holdFactor = 1.25; + + individualStrains[i] = previous.individualStrains[i] * individualDecay; + } + + heldUntil[collumn] = object.getEndTime(); + individualStrains[collumn] += 2 * holdFactor; + strain = previous.strain * overallDecay + (1 + holdAddition) * holdFactor; + } + } } diff --git a/src/lt/ekgame/beatmap_analyzer/difficulty/OsuDifficulty.java b/src/lt/ekgame/beatmap_analyzer/difficulty/OsuDifficulty.java index af6b2763..012076dc 100644 --- a/src/lt/ekgame/beatmap_analyzer/difficulty/OsuDifficulty.java +++ b/src/lt/ekgame/beatmap_analyzer/difficulty/OsuDifficulty.java @@ -14,70 +14,70 @@ public class OsuDifficulty extends Difficulty { - private double aimDiff, speedDiff; - - private List aimStrains; - private List speedStrains; - - public OsuDifficulty(OsuBeatmap beatmap, Mods mods, double starDiff, double aimDiff, double speedDiff, List aimStrains, List speedStrains) { - super(beatmap, mods, starDiff, null); - this.aimDiff = aimDiff; - this.speedDiff = speedDiff; - this.aimStrains = aimStrains; - this.speedStrains = speedStrains; - } - - private static List mergeStrains(List aimStrains, List speedStrains) { - List overall = new ArrayList(); - Iterator aimIterator = aimStrains.iterator(); - Iterator speedIterator = speedStrains.iterator(); - while (aimIterator.hasNext() && speedIterator.hasNext()) { - Double aimStrain = aimIterator.next(); - Double speedStrain = speedIterator.next(); - overall.add(aimStrain + speedStrain + Math.abs(speedStrain - aimStrain) * OsuDifficultyCalculator.EXTREME_SCALING_FACTOR); - } - return overall; - } - - public List getAimStrains() { - return aimStrains; - } - - public List getSpeedStrains() { - return speedStrains; - } - - public double getAim() { - return aimDiff; - } - - public double getSpeed() { - return speedDiff; - } - - public double getAR() { - return ((OsuBeatmap) beatmap).getAR(mods); - } - - public double getOD() { - return ((OsuBeatmap) beatmap).getOD(mods); - } - - public int getNumCircles() { - int c = 0; - for (HitObject o : ((OsuBeatmap) beatmap).getHitObjects()) { - if (o instanceof OsuCircle) c++; - } - - - return c; - - - //return (int) ((OsuBeatmap)beatmap).getHitObjects().stream().filter(o->o instanceof OsuCircle).count(); - } - - @Override - public Performance getPerformance(Score score) { - return new OsuPerformanceCalculator().calculate(this, score); - } + private double aimDiff, speedDiff; + + private List aimStrains; + private List speedStrains; + + public OsuDifficulty(OsuBeatmap beatmap, Mods mods, double starDiff, double aimDiff, double speedDiff, List aimStrains, List speedStrains) { + super(beatmap, mods, starDiff, null); + this.aimDiff = aimDiff; + this.speedDiff = speedDiff; + this.aimStrains = aimStrains; + this.speedStrains = speedStrains; + } + + private static List mergeStrains(List aimStrains, List speedStrains) { + List overall = new ArrayList(); + Iterator aimIterator = aimStrains.iterator(); + Iterator speedIterator = speedStrains.iterator(); + while (aimIterator.hasNext() && speedIterator.hasNext()) { + Double aimStrain = aimIterator.next(); + Double speedStrain = speedIterator.next(); + overall.add(aimStrain + speedStrain + Math.abs(speedStrain - aimStrain) * OsuDifficultyCalculator.EXTREME_SCALING_FACTOR); + } + return overall; + } + + public List getAimStrains() { + return aimStrains; + } + + public List getSpeedStrains() { + return speedStrains; + } + + public double getAim() { + return aimDiff; + } + + public double getSpeed() { + return speedDiff; + } + + public double getAR() { + return ((OsuBeatmap) beatmap).getAR(mods); + } + + public double getOD() { + return ((OsuBeatmap) beatmap).getOD(mods); + } + + public int getNumCircles() { + int c = 0; + for (HitObject o : ((OsuBeatmap) beatmap).getHitObjects()) { + if (o instanceof OsuCircle) c++; + } + + + return c; + + + //return (int) ((OsuBeatmap)beatmap).getHitObjects().stream().filter(o->o instanceof OsuCircle).count(); + } + + @Override + public Performance getPerformance(Score score) { + return new OsuPerformanceCalculator().calculate(this, score); + } } diff --git a/src/lt/ekgame/beatmap_analyzer/difficulty/OsuDifficultyCalculator.java b/src/lt/ekgame/beatmap_analyzer/difficulty/OsuDifficultyCalculator.java index d1b5232c..6bd6d380 100644 --- a/src/lt/ekgame/beatmap_analyzer/difficulty/OsuDifficultyCalculator.java +++ b/src/lt/ekgame/beatmap_analyzer/difficulty/OsuDifficultyCalculator.java @@ -18,271 +18,271 @@ public class OsuDifficultyCalculator implements DifficultyCalculator { - public static final double DECAY_BASE[] = {0.27, 0.10}; - public static final double STRIAN_DECAY_BASE[] = {0.3, 0.12}; - public static final double WEIGHT_SCALING[] = {1400, 26.25}; - public static final double STAR_SCALING_FACTOR = 0.005;// 0.0675; - public static final double EXTREME_SCALING_FACTOR = 0.5; - public static final float PLAYFIELD_WIDTH = 512; - public static final double DECAY_WEIGHT = 0.9; - public static final double SPEED_DECAY_WEIGHT = 0.91; - - public static final double ALMOST_DIAMETER = 60; - public static final double STREAM_SPACING = 90; - public static final double SINGLE_SPACING = 125; - - public static final double TIMES_STREAM = 200; - - public static final int STRAIN_STEP = 300; - - public static final float CIRCLE_SIZE_BUFF_TRESHOLD = 30; - - public static final byte DIFF_SPEED = 0; - public static final byte DIFF_AIM = 1; - - public static final double[] STRAIN_D_STEP = {3, 3}; - public static final double[] STRAIN_D_RATE = {0.95, 0.95}; - public static final double STRAIN_TIME_WIDTH = 500; - - - @Override - public OsuDifficulty calculate(Mods mods, Beatmap beatmap) { - OsuBeatmap bm = (OsuBeatmap) beatmap; - - double timeRate = mods.getSpeedMultiplier(); - List hitObjects = bm.getHitObjects(); - List objects = generateDifficultyObjects(hitObjects, bm.getCS(mods), timeRate); - - List aimStrains = calculateStrains(objects, DIFF_AIM, timeRate); - List speedStrains = calculateStrains(objects, DIFF_SPEED, timeRate); - - //List aimStrainsOriginal = new ArrayList<>(aimStrains); - //List speedStrainsOriginal = new ArrayList<>(speedStrains); - - double aimDifficulty = - //calculateNewDifficulty(objects, DIFF_AIM, timeRate); - calculateDifficulty(aimStrains); - double speedDifficulty = - //calculateNewDifficulty(objects, DIFF_SPEED, timeRate); - calculateDifficulty(speedStrains, SPEED_DECAY_WEIGHT); - Log.i("new-diff", 0 + ": " + speedDifficulty); - double starDifficulty = aimDifficulty + speedDifficulty + Math.abs(speedDifficulty - aimDifficulty) * EXTREME_SCALING_FACTOR; - return new OsuDifficulty(bm, mods, starDifficulty, aimDifficulty, speedDifficulty, null, null); - //return new OsuDifficulty(bm, mods, starDifficulty, aimDifficulty, speedDifficulty, aimStrainsOriginal, speedStrainsOriginal); - } - - public double calculateNewDifficulty(List objects, int type, double timeRate) { - - ArrayList> classifyObj = new ArrayList<>(); - - double currentTime = 0; - double strainTimeWidth = STRAIN_TIME_WIDTH * timeRate; - double blockTime = strainTimeWidth; - - Iterator iterator = objects.iterator(); - ArrayList tmpList = new ArrayList<>(); - classifyObj.add(tmpList); - while (iterator.hasNext()) { - final DifficultyObject object = iterator.next(); - currentTime = object.object.getStartTime(); - while (currentTime > blockTime) { - //新的时间段开始 - blockTime += STRAIN_TIME_WIDTH; - tmpList = new ArrayList<>(); - classifyObj.add(tmpList); - } - tmpList.add(object); - } - - double[] avgDiff = new double[classifyObj.size()]; - for (int i = 0; i < avgDiff.length; i++) { - final ArrayList tmp = classifyObj.get(i); - if (tmp.size() == 0) { - avgDiff[i] = 0; - } else { - for (DifficultyObject object : tmp) { - avgDiff[i] += object.strains[type]; - } - avgDiff[i] /= tmp.size(); - } - } - - Arrays.sort(avgDiff); - - double totalDiff = 0; - double weight = 1; - double preDiff = avgDiff[avgDiff.length - 1]; - for (int i = avgDiff.length - 1; i >= 0; i--) { - final double diff = avgDiff[i]; - totalDiff += diff * weight; - - //难度对weight的减少值 - weight *= Math.pow(STRAIN_D_RATE[type], Math.min(1, (preDiff - diff) / STRAIN_D_STEP[type])); - //物件对weight的减少值 - weight *= 0.9; - - if (weight > 0.01) { - //Log.i("new-diff", type + ": w :" + weight); - //Log.i("new-diff", type + ": d :" + diff); - } - preDiff = diff; - } - totalDiff *= STAR_SCALING_FACTOR; - //Log.i("new-diff", type + ": " + totalDiff); - return totalDiff; - } - - public List generateDifficultyObjects(OsuBeatmap bm) { - return generateDifficultyObjects(bm.getHitObjects(), bm.getCS(), 1); - } - - public List generateDifficultyObjects(List hitObjects, double csRating, double timeRate) { - double radius = (PLAYFIELD_WIDTH / 16) * (1 - 0.7 * (csRating - 5) / 5); - - List difficultyObjects = new ArrayList(hitObjects.size()); - - for (int i = 0; i < hitObjects.size(); i++) { - difficultyObjects.add(i, new DifficultyObject(hitObjects.get(i), radius, i)); - } - Collections.sort(difficultyObjects, new Comparator() { - @Override - public int compare(OsuDifficultyCalculator.DifficultyObject o1, OsuDifficultyCalculator.DifficultyObject o2) { - return o1.object.getStartTime() - o2.object.getStartTime(); - } - }); - - //hitObjects.stream() - // .map(o->new DifficultyObject(o, radius)) - // .sorted((a, b)-> a.object.getStartTime() - b.object.getStartTime()) - // .collect(Collectors.toList()); - - DifficultyObject previous = null; - for (DifficultyObject current : difficultyObjects) { - if (previous != null) - current.calculateStrains(previous, timeRate); - previous = current; - } - - return difficultyObjects; - } - - private List calculateStrains(List objects, byte difficultyType, double timeRate) { - List highestStrains = new ArrayList<>(); - double realStrainStep = STRAIN_STEP * timeRate; - double intervalEnd = realStrainStep; - double maxStrain = 0; - - DifficultyObject previous = null; - for (DifficultyObject current : objects) { - while (current.object.getStartTime() > intervalEnd) { - highestStrains.add(maxStrain); - if (previous != null) { - double decay = Math.pow( - STRIAN_DECAY_BASE[difficultyType], - (double) (intervalEnd - previous.object.getStartTime()) / 1000 - ); - maxStrain = previous.strains[difficultyType] * decay; - } - intervalEnd += realStrainStep; - } - maxStrain = Math.max(maxStrain, current.strains[difficultyType]); - previous = current; - } - return highestStrains; - } - - @Override - public double calculateDifficulty(List strains) { - return calculateDifficulty(strains, DECAY_WEIGHT); - } - - public double calculateDifficulty(List strains, double decayWeight) { - Collections.sort(strains, new Comparator() { - @Override - public int compare(Double a, Double b) { - return (int) (Math.signum(b - a)); - } - }); - //(a,b)->(int)(Math.signum(b-a))); - - double difficulty = 0, weight = 1; - for (double strain : strains) { - difficulty += weight * strain; - weight *= decayWeight; - } - - - return Math.sqrt(difficulty) * STAR_SCALING_FACTOR; - } - - public class DifficultyObject { - - public double[] strains = {1, 1}; - public int idx; - private OsuObject object; - private Vec2 normStart;//, normEnd; - - DifficultyObject(OsuObject object, double radius, int idx) { - this.object = object; - this.idx = idx; - - double scalingFactor = 52 / radius; - if (radius < CIRCLE_SIZE_BUFF_TRESHOLD) - scalingFactor *= 1 + Math.min(CIRCLE_SIZE_BUFF_TRESHOLD - radius, 5) / 50; - - normStart = object.getPosition().scale(scalingFactor); - //normEnd = normStart; - } - - private void calculateStrains(DifficultyObject previous, double timeRate) { - calculateStrain(previous, timeRate, DIFF_SPEED); - calculateStrain(previous, timeRate, DIFF_AIM); - } - - private void calculateStrain(DifficultyObject previous, double timeRate, byte difficultyType) { - double res = 0; - double timeElapsed = (object.getStartTime() - previous.object.getStartTime()) / timeRate; - double decay = Math.pow(DECAY_BASE[difficultyType], timeElapsed / 1000f); - double scaling = WEIGHT_SCALING[difficultyType]; - - if (!(object instanceof OsuSpinner)) { - double distance = normStart.distance(previous.normStart); - res = spacingWeight(distance, timeElapsed, difficultyType) * scaling; - } - - res /= Math.max(timeElapsed, 50); - strains[difficultyType] = previous.strains[difficultyType] * decay + res; - } - - private double spacingWeight(double distance, double time, byte difficultyType) { - if (difficultyType == DIFF_SPEED) { - double v = 0; - if (distance > SINGLE_SPACING) { - v = 2.3; - } else if (distance > STREAM_SPACING) { - v = 1.7 + 0.6 * (distance - STREAM_SPACING) / (SINGLE_SPACING - STREAM_SPACING); - } else if (distance > ALMOST_DIAMETER) { - v = 1.2 + 0.5 * (distance - ALMOST_DIAMETER) / (STREAM_SPACING - ALMOST_DIAMETER); - } else if (distance > ALMOST_DIAMETER / 2) { - v = 0.9 + 0.3 * (distance - ALMOST_DIAMETER / 2) / (ALMOST_DIAMETER / 2); - } else v = 0.9; - if (time < TIMES_STREAM) { - double t = time / TIMES_STREAM; - v *= 1.9 * (1 - t) + t * 0.5; - } else { - v *= 0.5f; - } - return v; - } else if (difficultyType == DIFF_AIM) { - if (time < TIMES_STREAM * 2) { - double t = time / TIMES_STREAM / 2; - distance *= 1.1 * (1 - t) + 0.9 * t; - } else { - distance *= 0.9; - } - return distance; - } else - return 0; - } - } + public static final double DECAY_BASE[] = {0.27, 0.10}; + public static final double STRIAN_DECAY_BASE[] = {0.3, 0.12}; + public static final double WEIGHT_SCALING[] = {1400, 26.25}; + public static final double STAR_SCALING_FACTOR = 0.005;// 0.0675; + public static final double EXTREME_SCALING_FACTOR = 0.5; + public static final float PLAYFIELD_WIDTH = 512; + public static final double DECAY_WEIGHT = 0.9; + public static final double SPEED_DECAY_WEIGHT = 0.91; + + public static final double ALMOST_DIAMETER = 60; + public static final double STREAM_SPACING = 90; + public static final double SINGLE_SPACING = 125; + + public static final double TIMES_STREAM = 200; + + public static final int STRAIN_STEP = 300; + + public static final float CIRCLE_SIZE_BUFF_TRESHOLD = 30; + + public static final byte DIFF_SPEED = 0; + public static final byte DIFF_AIM = 1; + + public static final double[] STRAIN_D_STEP = {3, 3}; + public static final double[] STRAIN_D_RATE = {0.95, 0.95}; + public static final double STRAIN_TIME_WIDTH = 500; + + + @Override + public OsuDifficulty calculate(Mods mods, Beatmap beatmap) { + OsuBeatmap bm = (OsuBeatmap) beatmap; + + double timeRate = mods.getSpeedMultiplier(); + List hitObjects = bm.getHitObjects(); + List objects = generateDifficultyObjects(hitObjects, bm.getCS(mods), timeRate); + + List aimStrains = calculateStrains(objects, DIFF_AIM, timeRate); + List speedStrains = calculateStrains(objects, DIFF_SPEED, timeRate); + + //List aimStrainsOriginal = new ArrayList<>(aimStrains); + //List speedStrainsOriginal = new ArrayList<>(speedStrains); + + double aimDifficulty = + //calculateNewDifficulty(objects, DIFF_AIM, timeRate); + calculateDifficulty(aimStrains); + double speedDifficulty = + //calculateNewDifficulty(objects, DIFF_SPEED, timeRate); + calculateDifficulty(speedStrains, SPEED_DECAY_WEIGHT); + Log.i("new-diff", 0 + ": " + speedDifficulty); + double starDifficulty = aimDifficulty + speedDifficulty + Math.abs(speedDifficulty - aimDifficulty) * EXTREME_SCALING_FACTOR; + return new OsuDifficulty(bm, mods, starDifficulty, aimDifficulty, speedDifficulty, null, null); + //return new OsuDifficulty(bm, mods, starDifficulty, aimDifficulty, speedDifficulty, aimStrainsOriginal, speedStrainsOriginal); + } + + public double calculateNewDifficulty(List objects, int type, double timeRate) { + + ArrayList> classifyObj = new ArrayList<>(); + + double currentTime = 0; + double strainTimeWidth = STRAIN_TIME_WIDTH * timeRate; + double blockTime = strainTimeWidth; + + Iterator iterator = objects.iterator(); + ArrayList tmpList = new ArrayList<>(); + classifyObj.add(tmpList); + while (iterator.hasNext()) { + final DifficultyObject object = iterator.next(); + currentTime = object.object.getStartTime(); + while (currentTime > blockTime) { + //新的时间段开始 + blockTime += STRAIN_TIME_WIDTH; + tmpList = new ArrayList<>(); + classifyObj.add(tmpList); + } + tmpList.add(object); + } + + double[] avgDiff = new double[classifyObj.size()]; + for (int i = 0; i < avgDiff.length; i++) { + final ArrayList tmp = classifyObj.get(i); + if (tmp.size() == 0) { + avgDiff[i] = 0; + } else { + for (DifficultyObject object : tmp) { + avgDiff[i] += object.strains[type]; + } + avgDiff[i] /= tmp.size(); + } + } + + Arrays.sort(avgDiff); + + double totalDiff = 0; + double weight = 1; + double preDiff = avgDiff[avgDiff.length - 1]; + for (int i = avgDiff.length - 1; i >= 0; i--) { + final double diff = avgDiff[i]; + totalDiff += diff * weight; + + //难度对weight的减少值 + weight *= Math.pow(STRAIN_D_RATE[type], Math.min(1, (preDiff - diff) / STRAIN_D_STEP[type])); + //物件对weight的减少值 + weight *= 0.9; + + if (weight > 0.01) { + //Log.i("new-diff", type + ": w :" + weight); + //Log.i("new-diff", type + ": d :" + diff); + } + preDiff = diff; + } + totalDiff *= STAR_SCALING_FACTOR; + //Log.i("new-diff", type + ": " + totalDiff); + return totalDiff; + } + + public List generateDifficultyObjects(OsuBeatmap bm) { + return generateDifficultyObjects(bm.getHitObjects(), bm.getCS(), 1); + } + + public List generateDifficultyObjects(List hitObjects, double csRating, double timeRate) { + double radius = (PLAYFIELD_WIDTH / 16) * (1 - 0.7 * (csRating - 5) / 5); + + List difficultyObjects = new ArrayList(hitObjects.size()); + + for (int i = 0; i < hitObjects.size(); i++) { + difficultyObjects.add(i, new DifficultyObject(hitObjects.get(i), radius, i)); + } + Collections.sort(difficultyObjects, new Comparator() { + @Override + public int compare(OsuDifficultyCalculator.DifficultyObject o1, OsuDifficultyCalculator.DifficultyObject o2) { + return o1.object.getStartTime() - o2.object.getStartTime(); + } + }); + + //hitObjects.stream() + // .map(o->new DifficultyObject(o, radius)) + // .sorted((a, b)-> a.object.getStartTime() - b.object.getStartTime()) + // .collect(Collectors.toList()); + + DifficultyObject previous = null; + for (DifficultyObject current : difficultyObjects) { + if (previous != null) + current.calculateStrains(previous, timeRate); + previous = current; + } + + return difficultyObjects; + } + + private List calculateStrains(List objects, byte difficultyType, double timeRate) { + List highestStrains = new ArrayList<>(); + double realStrainStep = STRAIN_STEP * timeRate; + double intervalEnd = realStrainStep; + double maxStrain = 0; + + DifficultyObject previous = null; + for (DifficultyObject current : objects) { + while (current.object.getStartTime() > intervalEnd) { + highestStrains.add(maxStrain); + if (previous != null) { + double decay = Math.pow( + STRIAN_DECAY_BASE[difficultyType], + (double) (intervalEnd - previous.object.getStartTime()) / 1000 + ); + maxStrain = previous.strains[difficultyType] * decay; + } + intervalEnd += realStrainStep; + } + maxStrain = Math.max(maxStrain, current.strains[difficultyType]); + previous = current; + } + return highestStrains; + } + + @Override + public double calculateDifficulty(List strains) { + return calculateDifficulty(strains, DECAY_WEIGHT); + } + + public double calculateDifficulty(List strains, double decayWeight) { + Collections.sort(strains, new Comparator() { + @Override + public int compare(Double a, Double b) { + return (int) (Math.signum(b - a)); + } + }); + //(a,b)->(int)(Math.signum(b-a))); + + double difficulty = 0, weight = 1; + for (double strain : strains) { + difficulty += weight * strain; + weight *= decayWeight; + } + + + return Math.sqrt(difficulty) * STAR_SCALING_FACTOR; + } + + public class DifficultyObject { + + public double[] strains = {1, 1}; + public int idx; + private OsuObject object; + private Vec2 normStart;//, normEnd; + + DifficultyObject(OsuObject object, double radius, int idx) { + this.object = object; + this.idx = idx; + + double scalingFactor = 52 / radius; + if (radius < CIRCLE_SIZE_BUFF_TRESHOLD) + scalingFactor *= 1 + Math.min(CIRCLE_SIZE_BUFF_TRESHOLD - radius, 5) / 50; + + normStart = object.getPosition().scale(scalingFactor); + //normEnd = normStart; + } + + private void calculateStrains(DifficultyObject previous, double timeRate) { + calculateStrain(previous, timeRate, DIFF_SPEED); + calculateStrain(previous, timeRate, DIFF_AIM); + } + + private void calculateStrain(DifficultyObject previous, double timeRate, byte difficultyType) { + double res = 0; + double timeElapsed = (object.getStartTime() - previous.object.getStartTime()) / timeRate; + double decay = Math.pow(DECAY_BASE[difficultyType], timeElapsed / 1000f); + double scaling = WEIGHT_SCALING[difficultyType]; + + if (!(object instanceof OsuSpinner)) { + double distance = normStart.distance(previous.normStart); + res = spacingWeight(distance, timeElapsed, difficultyType) * scaling; + } + + res /= Math.max(timeElapsed, 50); + strains[difficultyType] = previous.strains[difficultyType] * decay + res; + } + + private double spacingWeight(double distance, double time, byte difficultyType) { + if (difficultyType == DIFF_SPEED) { + double v = 0; + if (distance > SINGLE_SPACING) { + v = 2.3; + } else if (distance > STREAM_SPACING) { + v = 1.7 + 0.6 * (distance - STREAM_SPACING) / (SINGLE_SPACING - STREAM_SPACING); + } else if (distance > ALMOST_DIAMETER) { + v = 1.2 + 0.5 * (distance - ALMOST_DIAMETER) / (STREAM_SPACING - ALMOST_DIAMETER); + } else if (distance > ALMOST_DIAMETER / 2) { + v = 0.9 + 0.3 * (distance - ALMOST_DIAMETER / 2) / (ALMOST_DIAMETER / 2); + } else v = 0.9; + if (time < TIMES_STREAM) { + double t = time / TIMES_STREAM; + v *= 1.9 * (1 - t) + t * 0.5; + } else { + v *= 0.5f; + } + return v; + } else if (difficultyType == DIFF_AIM) { + if (time < TIMES_STREAM * 2) { + double t = time / TIMES_STREAM / 2; + distance *= 1.1 * (1 - t) + 0.9 * t; + } else { + distance *= 0.9; + } + return distance; + } else + return 0; + } + } } diff --git a/src/lt/ekgame/beatmap_analyzer/difficulty/TaikoDifficulty.java b/src/lt/ekgame/beatmap_analyzer/difficulty/TaikoDifficulty.java index 203aa6ff..c8a5e576 100644 --- a/src/lt/ekgame/beatmap_analyzer/difficulty/TaikoDifficulty.java +++ b/src/lt/ekgame/beatmap_analyzer/difficulty/TaikoDifficulty.java @@ -10,12 +10,12 @@ public class TaikoDifficulty extends Difficulty { - public TaikoDifficulty(TaikoBeatmap beatmap, Mods mods, double starDiff, List strains) { - super(beatmap, mods, starDiff, strains); - } + public TaikoDifficulty(TaikoBeatmap beatmap, Mods mods, double starDiff, List strains) { + super(beatmap, mods, starDiff, strains); + } - @Override - public Performance getPerformance(Score score) { - return new TaikoPerformanceCalculator().calculate(this, score); - } + @Override + public Performance getPerformance(Score score) { + return new TaikoPerformanceCalculator().calculate(this, score); + } } diff --git a/src/lt/ekgame/beatmap_analyzer/difficulty/TaikoDifficultyCalculator.java b/src/lt/ekgame/beatmap_analyzer/difficulty/TaikoDifficultyCalculator.java index 190714e8..fae8c0f4 100644 --- a/src/lt/ekgame/beatmap_analyzer/difficulty/TaikoDifficultyCalculator.java +++ b/src/lt/ekgame/beatmap_analyzer/difficulty/TaikoDifficultyCalculator.java @@ -14,162 +14,162 @@ public class TaikoDifficultyCalculator implements DifficultyCalculator { - public static final double STAR_SCALING_FACTOR = 0.04125; - public static final double DECAY_WEIGHT = 0.9; - public static final int STRAIN_STEP = 400; - - public static final double DECAY_BASE = 0.30; - public static final double COLOR_CHANGE_BONUS = 0.75; - - public static final double RHYTHM_CHANGE_BONUS = 1.0; - public static final double RHYTHM_CHANGE_BASE_THRESHOLD = 0.2; - public static final double RHYTHM_CHANGE_BASE = 2.0; - - @Override - public TaikoDifficulty calculate(Mods mods, Beatmap beatmap) { - TaikoBeatmap bm = (TaikoBeatmap) beatmap; - double timeRate = mods.getSpeedMultiplier(); - List hitObjects = bm.getHitObjects(); - List objects = generateDifficultyObjects(hitObjects, timeRate); - List strains = calculateStrains(objects, timeRate); - List strainsOriginal = new ArrayList<>(strains); - double difficulty = calculateDifficulty(strains); - return new TaikoDifficulty(bm, mods, difficulty, strainsOriginal); - } - - private List generateDifficultyObjects(List hitObjects, double timeRate) { - List difficultyObjects = new ArrayList(); - for (int i = 0; i < hitObjects.size(); i++) { - difficultyObjects.add(i, new DifficultyObject(hitObjects.get(i))); - } - - Collections.sort(difficultyObjects, new Comparator() { - @Override - public int compare(TaikoDifficultyCalculator.DifficultyObject a, TaikoDifficultyCalculator.DifficultyObject b) { - return a.object.getStartTime() - b.object.getStartTime(); - } - }); - - //hitObjects.stream() - //.map(o->new DifficultyObject(o)) - //.sorted((a, b)-> a.object.getStartTime() - b.object.getStartTime()) - //.collect(Collectors.toList()); - - DifficultyObject previous = null; - for (DifficultyObject current : difficultyObjects) { - if (previous != null) - current.calculateStrain(previous, timeRate); - previous = current; - } - - return difficultyObjects; - } - - private List calculateStrains(List difficultyObjects, double timeRate) { - List highestStrains = new ArrayList<>(); - double realStrainStep = STRAIN_STEP * timeRate; - double intervalEnd = realStrainStep; - double maxStrain = 0; - - DifficultyObject previous = null; - for (DifficultyObject current : difficultyObjects) { - while (current.object.getStartTime() > intervalEnd) { - highestStrains.add(maxStrain); - if (previous != null) { - double decay = Math.pow(DECAY_BASE, (double) (intervalEnd - previous.object.getStartTime()) / 1000); - maxStrain = previous.strain * decay; - } - intervalEnd += realStrainStep; - } - maxStrain = Math.max(maxStrain, current.strain); - previous = current; - } - - return highestStrains; - } - - public double calculateDifficulty(List strains) { - Collections.sort(strains, new Comparator() { - @Override - public int compare(Double a, Double b) { - return (int) Math.signum(b - a); - } - }); - //(a,b)->(int)(Math.signum(b-a))); - double difficulty = 0, weight = 1; - for (double strain : strains) { - difficulty += weight * strain; - weight *= DECAY_WEIGHT; - } - return difficulty * STAR_SCALING_FACTOR; - } - - enum ColorSwitch { - NONE, EVEN, ODD - } - - class DifficultyObject { - - private TaikoObject object; - private double strain = 1; - private double timeElapsed; - private boolean isBlue = false; - private int sameColorChain = 0; - private ColorSwitch lastColorSwitch = ColorSwitch.NONE; - - DifficultyObject(TaikoObject object) { - this.object = object; - - // XXX: can drumrolls be blue? - if (object instanceof TaikoCircle) - isBlue = ((TaikoCircle) object).getColor() == TaikoColor.BLUE; - } - - private void calculateStrain(DifficultyObject previous, double timeRate) { - timeElapsed = (object.getStartTime() - previous.object.getStartTime()) / timeRate; - double decay = Math.pow(DECAY_BASE, timeElapsed / 1000); - double addition = 1; - - - boolean isClose = object.getStartTime() - previous.object.getStartTime() < 1000; - if (object instanceof TaikoCircle && previous.object instanceof TaikoCircle && isClose) { - addition += colorChangeAddition(previous); - addition += rhythmChangeAddition(previous); - } - - double additionFactor = 1; - if (timeElapsed < 50) - additionFactor = 0.4 + 0.6 * timeElapsed / 50; - - strain = previous.strain * decay + addition * additionFactor; - } - - private double colorChangeAddition(DifficultyObject previous) { - if (isBlue != previous.isBlue) { - lastColorSwitch = previous.sameColorChain % 2 == 0 ? ColorSwitch.EVEN : ColorSwitch.ODD; - - if (previous.lastColorSwitch != ColorSwitch.NONE && previous.lastColorSwitch != lastColorSwitch) - return COLOR_CHANGE_BONUS; - } else { - lastColorSwitch = previous.lastColorSwitch; - sameColorChain = previous.sameColorChain + 1; - } - return 0; - } - - private double rhythmChangeAddition(DifficultyObject previous) { - if (timeElapsed == 0 || previous.timeElapsed == 0) - return 0; - - double timeElapsedRatio = Math.max(previous.timeElapsed / timeElapsed, timeElapsed / previous.timeElapsed); - if (timeElapsedRatio > 8) - return 0; - - double difference = (Math.log(timeElapsedRatio) / Math.log(RHYTHM_CHANGE_BASE)) % 1.0; - if (difference > RHYTHM_CHANGE_BASE_THRESHOLD && difference < 1 - RHYTHM_CHANGE_BASE_THRESHOLD) - return RHYTHM_CHANGE_BONUS; - - return 0; - } - } + public static final double STAR_SCALING_FACTOR = 0.04125; + public static final double DECAY_WEIGHT = 0.9; + public static final int STRAIN_STEP = 400; + + public static final double DECAY_BASE = 0.30; + public static final double COLOR_CHANGE_BONUS = 0.75; + + public static final double RHYTHM_CHANGE_BONUS = 1.0; + public static final double RHYTHM_CHANGE_BASE_THRESHOLD = 0.2; + public static final double RHYTHM_CHANGE_BASE = 2.0; + + @Override + public TaikoDifficulty calculate(Mods mods, Beatmap beatmap) { + TaikoBeatmap bm = (TaikoBeatmap) beatmap; + double timeRate = mods.getSpeedMultiplier(); + List hitObjects = bm.getHitObjects(); + List objects = generateDifficultyObjects(hitObjects, timeRate); + List strains = calculateStrains(objects, timeRate); + List strainsOriginal = new ArrayList<>(strains); + double difficulty = calculateDifficulty(strains); + return new TaikoDifficulty(bm, mods, difficulty, strainsOriginal); + } + + private List generateDifficultyObjects(List hitObjects, double timeRate) { + List difficultyObjects = new ArrayList(); + for (int i = 0; i < hitObjects.size(); i++) { + difficultyObjects.add(i, new DifficultyObject(hitObjects.get(i))); + } + + Collections.sort(difficultyObjects, new Comparator() { + @Override + public int compare(TaikoDifficultyCalculator.DifficultyObject a, TaikoDifficultyCalculator.DifficultyObject b) { + return a.object.getStartTime() - b.object.getStartTime(); + } + }); + + //hitObjects.stream() + //.map(o->new DifficultyObject(o)) + //.sorted((a, b)-> a.object.getStartTime() - b.object.getStartTime()) + //.collect(Collectors.toList()); + + DifficultyObject previous = null; + for (DifficultyObject current : difficultyObjects) { + if (previous != null) + current.calculateStrain(previous, timeRate); + previous = current; + } + + return difficultyObjects; + } + + private List calculateStrains(List difficultyObjects, double timeRate) { + List highestStrains = new ArrayList<>(); + double realStrainStep = STRAIN_STEP * timeRate; + double intervalEnd = realStrainStep; + double maxStrain = 0; + + DifficultyObject previous = null; + for (DifficultyObject current : difficultyObjects) { + while (current.object.getStartTime() > intervalEnd) { + highestStrains.add(maxStrain); + if (previous != null) { + double decay = Math.pow(DECAY_BASE, (double) (intervalEnd - previous.object.getStartTime()) / 1000); + maxStrain = previous.strain * decay; + } + intervalEnd += realStrainStep; + } + maxStrain = Math.max(maxStrain, current.strain); + previous = current; + } + + return highestStrains; + } + + public double calculateDifficulty(List strains) { + Collections.sort(strains, new Comparator() { + @Override + public int compare(Double a, Double b) { + return (int) Math.signum(b - a); + } + }); + //(a,b)->(int)(Math.signum(b-a))); + double difficulty = 0, weight = 1; + for (double strain : strains) { + difficulty += weight * strain; + weight *= DECAY_WEIGHT; + } + return difficulty * STAR_SCALING_FACTOR; + } + + enum ColorSwitch { + NONE, EVEN, ODD + } + + class DifficultyObject { + + private TaikoObject object; + private double strain = 1; + private double timeElapsed; + private boolean isBlue = false; + private int sameColorChain = 0; + private ColorSwitch lastColorSwitch = ColorSwitch.NONE; + + DifficultyObject(TaikoObject object) { + this.object = object; + + // XXX: can drumrolls be blue? + if (object instanceof TaikoCircle) + isBlue = ((TaikoCircle) object).getColor() == TaikoColor.BLUE; + } + + private void calculateStrain(DifficultyObject previous, double timeRate) { + timeElapsed = (object.getStartTime() - previous.object.getStartTime()) / timeRate; + double decay = Math.pow(DECAY_BASE, timeElapsed / 1000); + double addition = 1; + + + boolean isClose = object.getStartTime() - previous.object.getStartTime() < 1000; + if (object instanceof TaikoCircle && previous.object instanceof TaikoCircle && isClose) { + addition += colorChangeAddition(previous); + addition += rhythmChangeAddition(previous); + } + + double additionFactor = 1; + if (timeElapsed < 50) + additionFactor = 0.4 + 0.6 * timeElapsed / 50; + + strain = previous.strain * decay + addition * additionFactor; + } + + private double colorChangeAddition(DifficultyObject previous) { + if (isBlue != previous.isBlue) { + lastColorSwitch = previous.sameColorChain % 2 == 0 ? ColorSwitch.EVEN : ColorSwitch.ODD; + + if (previous.lastColorSwitch != ColorSwitch.NONE && previous.lastColorSwitch != lastColorSwitch) + return COLOR_CHANGE_BONUS; + } else { + lastColorSwitch = previous.lastColorSwitch; + sameColorChain = previous.sameColorChain + 1; + } + return 0; + } + + private double rhythmChangeAddition(DifficultyObject previous) { + if (timeElapsed == 0 || previous.timeElapsed == 0) + return 0; + + double timeElapsedRatio = Math.max(previous.timeElapsed / timeElapsed, timeElapsed / previous.timeElapsed); + if (timeElapsedRatio > 8) + return 0; + + double difference = (Math.log(timeElapsedRatio) / Math.log(RHYTHM_CHANGE_BASE)) % 1.0; + if (difference > RHYTHM_CHANGE_BASE_THRESHOLD && difference < 1 - RHYTHM_CHANGE_BASE_THRESHOLD) + return RHYTHM_CHANGE_BONUS; + + return 0; + } + } } diff --git a/src/lt/ekgame/beatmap_analyzer/parser/BeatmapException.java b/src/lt/ekgame/beatmap_analyzer/parser/BeatmapException.java index 9e833a57..0b867640 100644 --- a/src/lt/ekgame/beatmap_analyzer/parser/BeatmapException.java +++ b/src/lt/ekgame/beatmap_analyzer/parser/BeatmapException.java @@ -2,10 +2,10 @@ public class BeatmapException extends Exception { - private static final long serialVersionUID = 8317471789581978277L; + private static final long serialVersionUID = 8317471789581978277L; - public BeatmapException(String message) { - super(message); - } + public BeatmapException(String message) { + super(message); + } } diff --git a/src/lt/ekgame/beatmap_analyzer/parser/BeatmapParser.java b/src/lt/ekgame/beatmap_analyzer/parser/BeatmapParser.java index 40d577cf..84efe5f7 100644 --- a/src/lt/ekgame/beatmap_analyzer/parser/BeatmapParser.java +++ b/src/lt/ekgame/beatmap_analyzer/parser/BeatmapParser.java @@ -29,200 +29,200 @@ public class BeatmapParser { - private static final Pattern PART_TAG = Pattern.compile("^\\[(\\w+)\\]"); - private static final String[] REQUIRED_TAGS = {"General", "Metadata", "TimingPoints", "Difficulty", "Events", "HitObjects"}; - - private static final Map> PARSERS = new HashMap<>(); - private static Function timingPointMapper = new Function() { - - @Override - public TimingPoint apply(String line) { - String[] args = line.split(","); - - double timestamp = Double.parseDouble(args[0].trim()); - double beatLength = Double.parseDouble(args[1].trim()); - int meter = 4; - int sampleType = 0; - int sampleSet = 0; - int volume = 100; - boolean isInherited = false; - boolean isKiai = false; - - if (args.length > 2) { - meter = Integer.parseInt(args[2].trim()); - sampleType = Integer.parseInt(args[3].trim()); - sampleSet = Integer.parseInt(args[4].trim()); - volume = Integer.parseInt(args[5].trim()); - } - - if (args.length >= 7) - isInherited = Integer.parseInt(args[6].trim()) == 0; - if (args.length >= 8) - isKiai = Integer.parseInt(args[7].trim()) == 0; - - return new TimingPoint(timestamp, beatLength, meter, sampleType, sampleSet, volume, isInherited, isKiai); - - } - }; - private static Function breakPeriodMapper = new Function() { - @Override - public BreakPeriod apply(String line) { - { - String[] args = line.split(","); - return new BreakPeriod( - Integer.parseInt(args[1].trim()), - Integer.parseInt(args[2].trim()) - ); - } - } - }; - - static { - PARSERS.put(Gamemode.OSU, new OsuParser()); - PARSERS.put(Gamemode.TAIKO, new TaikoParser()); - //PARSERS.put(Gamemode.CATCH, new CatchParser()); - PARSERS.put(Gamemode.MANIA, new ManiaParser()); - } - - @SuppressWarnings("unchecked") - public T parse(File file, Class klass) throws BeatmapException, FileNotFoundException { - return (T) parse(file); - } - - public Beatmap parse(File file) throws FileNotFoundException, BeatmapException { - return parse(new FileInputStream(file)); - } - - @SuppressWarnings("unchecked") - public T parse(String string, Class klass) throws BeatmapException { - return (T) parse(string); - } - - public Beatmap parse(String string) throws BeatmapException { - return parse(new ByteArrayInputStream(string.getBytes())); - } - - @SuppressWarnings("unchecked") - public T parse(InputStream stream, Class klass) throws BeatmapException { - return (T) parse(stream); - } - /* - line -> { - String[] args = line.split(","); - - double timestamp = Double.parseDouble(args[0].trim()); - double beatLength = Double.parseDouble(args[1].trim()); - int meter = 4; - int sampleType = 0; - int sampleSet = 0; - int volume = 100; - boolean isInherited = false; - boolean isKiai = false; - - if (args.length > 2) { - meter = Integer.parseInt(args[2].trim()); - sampleType = Integer.parseInt(args[3].trim()); - sampleSet = Integer.parseInt(args[4].trim()); - volume = Integer.parseInt(args[5].trim()); - } - - if (args.length >= 7) - isInherited = Integer.parseInt(args[6].trim()) == 0; - if (args.length >= 8) - isKiai = Integer.parseInt(args[7].trim()) == 0; - - return new TimingPoint(timestamp, beatLength, meter, sampleType, sampleSet, volume, isInherited, isKiai); - };*/ - - public Beatmap parse(InputStream stream) throws BeatmapException { - Scanner scanner = new Scanner(stream); - //try (Scanner scanner = new Scanner(stream)){ - Map parts = new HashMap<>(); - - String tag = "Header"; - List lines = new ArrayList<>(); - while (scanner.hasNextLine()) { - String line = scanner.nextLine().trim(); - //Log.i("ed-test","line : "+line); - if (line.startsWith("[")) { - parts.put(tag, new FilePart(tag, lines)); - lines = new ArrayList<>(); - tag = line.substring(1, line.indexOf("]")); - //Log.i("ed-test","tag : "+tag); - } else if (!line.isEmpty() && !line.startsWith("//")) { - lines.add(line); - } - } - parts.put(tag, new FilePart(tag, lines)); - - for (String reqiredTag : REQUIRED_TAGS) - if (!parts.containsKey(reqiredTag)) - throw new BeatmapException("Couldn't find required \"" + reqiredTag + "\" tag found."); - - BeatmapGenerals generalSettings = new BeatmapGenerals(parts.get("General")); - HitObjectParser parser = PARSERS.get(generalSettings.getGamemode()); - if (parser == null) - return null; - - BeatmapMetadata metadata = new BeatmapMetadata(parts.get("Metadata")); - BeatmapDifficulties difficulties = new BeatmapDifficulties(parts.get("Difficulty")); - BeatmapEditorState editorState = null; - - // Older formats don't have the "Editor" tag - if (parts.containsKey("Editor")) - editorState = new BeatmapEditorState(parts.get("Editor")); - - List breaks = parseBreaks(parts.get("Events")); - List timingPoints = parseTimePoints(parts.get("TimingPoints")); - List rawObjects = parts.get("HitObjects").getLines(); - scanner.close(); - return parser.buildBeatmap(generalSettings, editorState, metadata, difficulties, breaks, timingPoints, rawObjects); - //} - - } - - private List parseTimePoints(FilePart part) { - List l = new ArrayList(part.getLines().size()); - for (int i = 0; i < part.getLines().size(); i++) { - l.add(timingPointMapper.apply(part.getLines().get(i))); - } - Collections.sort(l, new Comparator() { - @Override - public int compare(TimingPoint o1, TimingPoint o2) { - return (int) (o1.getTimestamp() - o2.getTimestamp()); - } - }); - return l; - /* - part.getLines().stream() - .map(timingPointMapper) - .sorted((o1, o2) -> (int)(o1.getTimestamp()- o2.getTimestamp())) - .collect(Collectors.toList());*/ - } - /* line -> { - String[] args = line.split(","); - return new BreakPeriod( - Integer.parseInt(args[1].trim()), - Integer.parseInt(args[2].trim()) - ); - };*/ - - private List parseBreaks(FilePart part) { - List breakPeriods = new ArrayList(); - for (int i = 0; i < part.getLines().size(); i++) { - if (part.getLines().get(i).trim().startsWith("2,")) { - breakPeriods.add(breakPeriodMapper.apply(part.getLines().get(i))); - } - } - return breakPeriods; - /* - part.getLines().stream() - .filter(o->o.trim().startsWith("2,")) - .map(breakPeriodMapper) - .collect(Collectors.toList());*/ - } - - public static interface Function { - public P apply(T t); - } + private static final Pattern PART_TAG = Pattern.compile("^\\[(\\w+)\\]"); + private static final String[] REQUIRED_TAGS = {"General", "Metadata", "TimingPoints", "Difficulty", "Events", "HitObjects"}; + + private static final Map> PARSERS = new HashMap<>(); + private static Function timingPointMapper = new Function() { + + @Override + public TimingPoint apply(String line) { + String[] args = line.split(","); + + double timestamp = Double.parseDouble(args[0].trim()); + double beatLength = Double.parseDouble(args[1].trim()); + int meter = 4; + int sampleType = 0; + int sampleSet = 0; + int volume = 100; + boolean isInherited = false; + boolean isKiai = false; + + if (args.length > 2) { + meter = Integer.parseInt(args[2].trim()); + sampleType = Integer.parseInt(args[3].trim()); + sampleSet = Integer.parseInt(args[4].trim()); + volume = Integer.parseInt(args[5].trim()); + } + + if (args.length >= 7) + isInherited = Integer.parseInt(args[6].trim()) == 0; + if (args.length >= 8) + isKiai = Integer.parseInt(args[7].trim()) == 0; + + return new TimingPoint(timestamp, beatLength, meter, sampleType, sampleSet, volume, isInherited, isKiai); + + } + }; + private static Function breakPeriodMapper = new Function() { + @Override + public BreakPeriod apply(String line) { + { + String[] args = line.split(","); + return new BreakPeriod( + Integer.parseInt(args[1].trim()), + Integer.parseInt(args[2].trim()) + ); + } + } + }; + + static { + PARSERS.put(Gamemode.OSU, new OsuParser()); + PARSERS.put(Gamemode.TAIKO, new TaikoParser()); + //PARSERS.put(Gamemode.CATCH, new CatchParser()); + PARSERS.put(Gamemode.MANIA, new ManiaParser()); + } + + @SuppressWarnings("unchecked") + public T parse(File file, Class klass) throws BeatmapException, FileNotFoundException { + return (T) parse(file); + } + + public Beatmap parse(File file) throws FileNotFoundException, BeatmapException { + return parse(new FileInputStream(file)); + } + + @SuppressWarnings("unchecked") + public T parse(String string, Class klass) throws BeatmapException { + return (T) parse(string); + } + + public Beatmap parse(String string) throws BeatmapException { + return parse(new ByteArrayInputStream(string.getBytes())); + } + + @SuppressWarnings("unchecked") + public T parse(InputStream stream, Class klass) throws BeatmapException { + return (T) parse(stream); + } + /* + line -> { + String[] args = line.split(","); + + double timestamp = Double.parseDouble(args[0].trim()); + double beatLength = Double.parseDouble(args[1].trim()); + int meter = 4; + int sampleType = 0; + int sampleSet = 0; + int volume = 100; + boolean isInherited = false; + boolean isKiai = false; + + if (args.length > 2) { + meter = Integer.parseInt(args[2].trim()); + sampleType = Integer.parseInt(args[3].trim()); + sampleSet = Integer.parseInt(args[4].trim()); + volume = Integer.parseInt(args[5].trim()); + } + + if (args.length >= 7) + isInherited = Integer.parseInt(args[6].trim()) == 0; + if (args.length >= 8) + isKiai = Integer.parseInt(args[7].trim()) == 0; + + return new TimingPoint(timestamp, beatLength, meter, sampleType, sampleSet, volume, isInherited, isKiai); + };*/ + + public Beatmap parse(InputStream stream) throws BeatmapException { + Scanner scanner = new Scanner(stream); + //try (Scanner scanner = new Scanner(stream)){ + Map parts = new HashMap<>(); + + String tag = "Header"; + List lines = new ArrayList<>(); + while (scanner.hasNextLine()) { + String line = scanner.nextLine().trim(); + //Log.i("ed-test","line : "+line); + if (line.startsWith("[")) { + parts.put(tag, new FilePart(tag, lines)); + lines = new ArrayList<>(); + tag = line.substring(1, line.indexOf("]")); + //Log.i("ed-test","tag : "+tag); + } else if (!line.isEmpty() && !line.startsWith("//")) { + lines.add(line); + } + } + parts.put(tag, new FilePart(tag, lines)); + + for (String reqiredTag : REQUIRED_TAGS) + if (!parts.containsKey(reqiredTag)) + throw new BeatmapException("Couldn't find required \"" + reqiredTag + "\" tag found."); + + BeatmapGenerals generalSettings = new BeatmapGenerals(parts.get("General")); + HitObjectParser parser = PARSERS.get(generalSettings.getGamemode()); + if (parser == null) + return null; + + BeatmapMetadata metadata = new BeatmapMetadata(parts.get("Metadata")); + BeatmapDifficulties difficulties = new BeatmapDifficulties(parts.get("Difficulty")); + BeatmapEditorState editorState = null; + + // Older formats don't have the "Editor" tag + if (parts.containsKey("Editor")) + editorState = new BeatmapEditorState(parts.get("Editor")); + + List breaks = parseBreaks(parts.get("Events")); + List timingPoints = parseTimePoints(parts.get("TimingPoints")); + List rawObjects = parts.get("HitObjects").getLines(); + scanner.close(); + return parser.buildBeatmap(generalSettings, editorState, metadata, difficulties, breaks, timingPoints, rawObjects); + //} + + } + + private List parseTimePoints(FilePart part) { + List l = new ArrayList(part.getLines().size()); + for (int i = 0; i < part.getLines().size(); i++) { + l.add(timingPointMapper.apply(part.getLines().get(i))); + } + Collections.sort(l, new Comparator() { + @Override + public int compare(TimingPoint o1, TimingPoint o2) { + return (int) (o1.getTimestamp() - o2.getTimestamp()); + } + }); + return l; + /* + part.getLines().stream() + .map(timingPointMapper) + .sorted((o1, o2) -> (int)(o1.getTimestamp()- o2.getTimestamp())) + .collect(Collectors.toList());*/ + } + /* line -> { + String[] args = line.split(","); + return new BreakPeriod( + Integer.parseInt(args[1].trim()), + Integer.parseInt(args[2].trim()) + ); + };*/ + + private List parseBreaks(FilePart part) { + List breakPeriods = new ArrayList(); + for (int i = 0; i < part.getLines().size(); i++) { + if (part.getLines().get(i).trim().startsWith("2,")) { + breakPeriods.add(breakPeriodMapper.apply(part.getLines().get(i))); + } + } + return breakPeriods; + /* + part.getLines().stream() + .filter(o->o.trim().startsWith("2,")) + .map(breakPeriodMapper) + .collect(Collectors.toList());*/ + } + + public static interface Function { + public P apply(T t); + } } diff --git a/src/lt/ekgame/beatmap_analyzer/parser/FilePart.java b/src/lt/ekgame/beatmap_analyzer/parser/FilePart.java index 8fca9f1f..b84b377a 100644 --- a/src/lt/ekgame/beatmap_analyzer/parser/FilePart.java +++ b/src/lt/ekgame/beatmap_analyzer/parser/FilePart.java @@ -4,19 +4,19 @@ public class FilePart { - private String tag; - private List lines; + private String tag; + private List lines; - FilePart(String tag, List lines) { - this.tag = tag; - this.lines = lines; - } + FilePart(String tag, List lines) { + this.tag = tag; + this.lines = lines; + } - public String getTag() { - return tag; - } + public String getTag() { + return tag; + } - public List getLines() { - return lines; - } + public List getLines() { + return lines; + } } diff --git a/src/lt/ekgame/beatmap_analyzer/parser/FilePartConfig.java b/src/lt/ekgame/beatmap_analyzer/parser/FilePartConfig.java index b1ff34b7..45c412e5 100644 --- a/src/lt/ekgame/beatmap_analyzer/parser/FilePartConfig.java +++ b/src/lt/ekgame/beatmap_analyzer/parser/FilePartConfig.java @@ -7,76 +7,76 @@ public class FilePartConfig { - private FilePart part; - private Map values = new HashMap<>(); - - public FilePartConfig(FilePart part) { - this.part = part; - for (String line : part.getLines()) { - int seperator = line.indexOf(":"); - // I found one map file that has a stack trace in it (https://osu.ppy.sh/osu/326) - // That's why I need this check - if (seperator != -1) { - String key = line.substring(0, seperator).trim(); - String value = line.substring(seperator + 1).trim(); - values.put(key, value); - } - } - } - - public String getString(String name) throws BeatmapException { - if (values.containsKey(name)) - return values.get(name); - throw new BeatmapException("Can't find property \"" + name + "\" under [" + part.getTag() + "]."); - } - - public String getString(String name, String defaultValue) throws BeatmapException { - if (hasProperty(name)) - return getString(name); - return defaultValue; - } - - public double getDouble(String name) throws BeatmapException { - return Double.parseDouble(getString(name)); - } - - public int getInt(String name) throws BeatmapException { - return Integer.parseInt(getString(name)); - } - - public boolean getBoolean(String name) throws BeatmapException { - return Integer.parseInt(getString(name)) == 1; - } - - public Gamemode getGamemode(String name) throws BeatmapException { - return Gamemode.fromInt(getInt(name)); - } - - public double getDouble(String name, double defaultValue) throws BeatmapException { - if (hasProperty(name)) - return getDouble(name); - return defaultValue; - } - - public int getInt(String name, int defaultValue) throws BeatmapException { - if (hasProperty(name)) - return getInt(name); - return defaultValue; - } - - public boolean getBoolean(String name, boolean defaultValue) throws BeatmapException { - if (hasProperty(name)) - return getBoolean(name); - return defaultValue; - } - - public Gamemode getGamemode(String name, Gamemode defaultValue) throws BeatmapException { - if (hasProperty(name)) - return getGamemode(name); - return defaultValue; - } - - public boolean hasProperty(String name) throws BeatmapException { - return values.containsKey(name); - } + private FilePart part; + private Map values = new HashMap<>(); + + public FilePartConfig(FilePart part) { + this.part = part; + for (String line : part.getLines()) { + int seperator = line.indexOf(":"); + // I found one map file that has a stack trace in it (https://osu.ppy.sh/osu/326) + // That's why I need this check + if (seperator != -1) { + String key = line.substring(0, seperator).trim(); + String value = line.substring(seperator + 1).trim(); + values.put(key, value); + } + } + } + + public String getString(String name) throws BeatmapException { + if (values.containsKey(name)) + return values.get(name); + throw new BeatmapException("Can't find property \"" + name + "\" under [" + part.getTag() + "]."); + } + + public String getString(String name, String defaultValue) throws BeatmapException { + if (hasProperty(name)) + return getString(name); + return defaultValue; + } + + public double getDouble(String name) throws BeatmapException { + return Double.parseDouble(getString(name)); + } + + public int getInt(String name) throws BeatmapException { + return Integer.parseInt(getString(name)); + } + + public boolean getBoolean(String name) throws BeatmapException { + return Integer.parseInt(getString(name)) == 1; + } + + public Gamemode getGamemode(String name) throws BeatmapException { + return Gamemode.fromInt(getInt(name)); + } + + public double getDouble(String name, double defaultValue) throws BeatmapException { + if (hasProperty(name)) + return getDouble(name); + return defaultValue; + } + + public int getInt(String name, int defaultValue) throws BeatmapException { + if (hasProperty(name)) + return getInt(name); + return defaultValue; + } + + public boolean getBoolean(String name, boolean defaultValue) throws BeatmapException { + if (hasProperty(name)) + return getBoolean(name); + return defaultValue; + } + + public Gamemode getGamemode(String name, Gamemode defaultValue) throws BeatmapException { + if (hasProperty(name)) + return getGamemode(name); + return defaultValue; + } + + public boolean hasProperty(String name) throws BeatmapException { + return values.containsKey(name); + } } diff --git a/src/lt/ekgame/beatmap_analyzer/parser/FilePartParser.java b/src/lt/ekgame/beatmap_analyzer/parser/FilePartParser.java index 4201024c..54d36e22 100644 --- a/src/lt/ekgame/beatmap_analyzer/parser/FilePartParser.java +++ b/src/lt/ekgame/beatmap_analyzer/parser/FilePartParser.java @@ -2,7 +2,7 @@ public abstract class FilePartParser { - protected abstract T parseLine(String line); + protected abstract T parseLine(String line); } diff --git a/src/lt/ekgame/beatmap_analyzer/parser/hitobjects/CatchParser.java b/src/lt/ekgame/beatmap_analyzer/parser/hitobjects/CatchParser.java index 7907b3f2..baf3a115 100644 --- a/src/lt/ekgame/beatmap_analyzer/parser/hitobjects/CatchParser.java +++ b/src/lt/ekgame/beatmap_analyzer/parser/hitobjects/CatchParser.java @@ -13,15 +13,15 @@ public class CatchParser extends HitObjectParser { - @Override - public CatchObject parse(String line) { - return null; - } + @Override + public CatchObject parse(String line) { + return null; + } - @Override - public Beatmap buildBeatmap(BeatmapGenerals generals, BeatmapEditorState editorState, - BeatmapMetadata metadata, BeatmapDifficulties difficulties, List breaks, - List timingPoints, List rawObjects) { - return null; - } + @Override + public Beatmap buildBeatmap(BeatmapGenerals generals, BeatmapEditorState editorState, + BeatmapMetadata metadata, BeatmapDifficulties difficulties, List breaks, + List timingPoints, List rawObjects) { + return null; + } } diff --git a/src/lt/ekgame/beatmap_analyzer/parser/hitobjects/HitObjectParser.java b/src/lt/ekgame/beatmap_analyzer/parser/hitobjects/HitObjectParser.java index 59278bea..8def8866 100644 --- a/src/lt/ekgame/beatmap_analyzer/parser/hitobjects/HitObjectParser.java +++ b/src/lt/ekgame/beatmap_analyzer/parser/hitobjects/HitObjectParser.java @@ -14,22 +14,22 @@ public abstract class HitObjectParser { - public abstract T parse(String line); + public abstract T parse(String line); - public List parse(List lines) { - List l = new ArrayList(lines.size()); - for (int i = 0; i < lines.size(); i++) { - l.add(i, parse(lines.get(i))); - } + public List parse(List lines) { + List l = new ArrayList(lines.size()); + for (int i = 0; i < lines.size(); i++) { + l.add(i, parse(lines.get(i))); + } - return l; - //lines.stream().map(this::parse) - // .collect(Collectors.toList()); - } + return l; + //lines.stream().map(this::parse) + // .collect(Collectors.toList()); + } - public abstract Beatmap buildBeatmap(BeatmapGenerals generals, BeatmapEditorState editorState, - BeatmapMetadata metadata, BeatmapDifficulties difficulties, List breaks, - List timingPoints, List rawObjects); + public abstract Beatmap buildBeatmap(BeatmapGenerals generals, BeatmapEditorState editorState, + BeatmapMetadata metadata, BeatmapDifficulties difficulties, List breaks, + List timingPoints, List rawObjects); } diff --git a/src/lt/ekgame/beatmap_analyzer/parser/hitobjects/ManiaParser.java b/src/lt/ekgame/beatmap_analyzer/parser/hitobjects/ManiaParser.java index 5d40a5da..e0a841fc 100644 --- a/src/lt/ekgame/beatmap_analyzer/parser/hitobjects/ManiaParser.java +++ b/src/lt/ekgame/beatmap_analyzer/parser/hitobjects/ManiaParser.java @@ -17,31 +17,31 @@ public class ManiaParser extends HitObjectParser { - @Override - public ManiaObject parse(String line) { - String[] args = line.split(","); - Vec2 position = new Vec2( - Integer.parseInt(args[0].trim()), - Integer.parseInt(args[1].trim()) - ); - int time = Integer.parseInt(args[2].trim()); - int type = Integer.parseInt(args[3].trim()); - int hitSound = Integer.parseInt(args[4].trim()); + @Override + public ManiaObject parse(String line) { + String[] args = line.split(","); + Vec2 position = new Vec2( + Integer.parseInt(args[0].trim()), + Integer.parseInt(args[1].trim()) + ); + int time = Integer.parseInt(args[2].trim()); + int type = Integer.parseInt(args[3].trim()); + int hitSound = Integer.parseInt(args[4].trim()); - if ((type & 1) > 0) { - return new ManiaSingle(position, time, hitSound); - } else { - String[] additions = args[5].split(":"); - int endTime = Integer.parseInt(additions[0].trim()); - return new ManiaHold(position, time, endTime, hitSound); - } - } + if ((type & 1) > 0) { + return new ManiaSingle(position, time, hitSound); + } else { + String[] additions = args[5].split(":"); + int endTime = Integer.parseInt(additions[0].trim()); + return new ManiaHold(position, time, endTime, hitSound); + } + } - @Override - public Beatmap buildBeatmap(BeatmapGenerals generals, BeatmapEditorState editorState, BeatmapMetadata metadata, - BeatmapDifficulties difficulties, List breaks, List timingPoints, - List rawObjects) { - List hitObjects = parse(rawObjects); - return new ManiaBeatmap(generals, editorState, metadata, difficulties, breaks, timingPoints, hitObjects); - } + @Override + public Beatmap buildBeatmap(BeatmapGenerals generals, BeatmapEditorState editorState, BeatmapMetadata metadata, + BeatmapDifficulties difficulties, List breaks, List timingPoints, + List rawObjects) { + List hitObjects = parse(rawObjects); + return new ManiaBeatmap(generals, editorState, metadata, difficulties, breaks, timingPoints, hitObjects); + } } diff --git a/src/lt/ekgame/beatmap_analyzer/parser/hitobjects/OsuParser.java b/src/lt/ekgame/beatmap_analyzer/parser/hitobjects/OsuParser.java index c6884008..b4779ca3 100644 --- a/src/lt/ekgame/beatmap_analyzer/parser/hitobjects/OsuParser.java +++ b/src/lt/ekgame/beatmap_analyzer/parser/hitobjects/OsuParser.java @@ -19,51 +19,51 @@ public class OsuParser extends HitObjectParser { - @Override - public OsuObject parse(String line) { - String[] args = line.split(","); - Vec2 position = new Vec2( - Integer.parseInt(args[0].trim()), - Integer.parseInt(args[1].trim()) - ); - int time = Integer.parseInt(args[2].trim()); - int type = Integer.parseInt(args[3].trim()); - int hitSound = Integer.parseInt(args[4].trim()); - boolean newCombo = (type & 4) > 0; + @Override + public OsuObject parse(String line) { + String[] args = line.split(","); + Vec2 position = new Vec2( + Integer.parseInt(args[0].trim()), + Integer.parseInt(args[1].trim()) + ); + int time = Integer.parseInt(args[2].trim()); + int type = Integer.parseInt(args[3].trim()); + int hitSound = Integer.parseInt(args[4].trim()); + boolean newCombo = (type & 4) > 0; - if ((type & 1) > 0) { - return new OsuCircle(position, time, hitSound, newCombo); - } else if ((type & 2) > 0) { - String[] sliderData = args[5].trim().split("\\|"); + if ((type & 1) > 0) { + return new OsuCircle(position, time, hitSound, newCombo); + } else if ((type & 2) > 0) { + String[] sliderData = args[5].trim().split("\\|"); - char sliderTypeChar = sliderData[0].charAt(0); - OsuSlider.SliderType sliderType = OsuSlider.SliderType.fromChar(sliderTypeChar); + char sliderTypeChar = sliderData[0].charAt(0); + OsuSlider.SliderType sliderType = OsuSlider.SliderType.fromChar(sliderTypeChar); - List sliderPoints = new ArrayList<>(); + List sliderPoints = new ArrayList<>(); - for (int i = 1; i < sliderData.length; i++) { - String[] pointData = sliderData[i].split(":"); - sliderPoints.add(new Vec2( - Integer.parseInt(pointData[0]), - Integer.parseInt(pointData[1]) - )); - } - int repetitions = Integer.parseInt(args[6].trim()); - double pixelLength = Double.parseDouble(args[7].trim()); + for (int i = 1; i < sliderData.length; i++) { + String[] pointData = sliderData[i].split(":"); + sliderPoints.add(new Vec2( + Integer.parseInt(pointData[0]), + Integer.parseInt(pointData[1]) + )); + } + int repetitions = Integer.parseInt(args[6].trim()); + double pixelLength = Double.parseDouble(args[7].trim()); - return new OsuSlider(position, time, hitSound, newCombo, sliderType, sliderPoints, repetitions, pixelLength); - } else { - int endTime = Integer.parseInt(args[5].trim()); - return new OsuSpinner(position, time, endTime, hitSound, newCombo); - } - } + return new OsuSlider(position, time, hitSound, newCombo, sliderType, sliderPoints, repetitions, pixelLength); + } else { + int endTime = Integer.parseInt(args[5].trim()); + return new OsuSpinner(position, time, endTime, hitSound, newCombo); + } + } - @Override - public Beatmap buildBeatmap(BeatmapGenerals generals, BeatmapEditorState editorState, - BeatmapMetadata metadata, BeatmapDifficulties difficulties, List breaks, - List timingPoints, List rawObjects) { - List hitObjects = parse(rawObjects); - return new OsuBeatmap(generals, editorState, metadata, difficulties, breaks, timingPoints, hitObjects); - } + @Override + public Beatmap buildBeatmap(BeatmapGenerals generals, BeatmapEditorState editorState, + BeatmapMetadata metadata, BeatmapDifficulties difficulties, List breaks, + List timingPoints, List rawObjects) { + List hitObjects = parse(rawObjects); + return new OsuBeatmap(generals, editorState, metadata, difficulties, breaks, timingPoints, hitObjects); + } } diff --git a/src/lt/ekgame/beatmap_analyzer/parser/hitobjects/TaikoParser.java b/src/lt/ekgame/beatmap_analyzer/parser/hitobjects/TaikoParser.java index ed2be534..54d608ce 100644 --- a/src/lt/ekgame/beatmap_analyzer/parser/hitobjects/TaikoParser.java +++ b/src/lt/ekgame/beatmap_analyzer/parser/hitobjects/TaikoParser.java @@ -18,39 +18,39 @@ public class TaikoParser extends HitObjectParser { - @Override - public TaikoObject parse(String line) { - String[] args = line.split(","); - Vec2 position = new Vec2( - Integer.parseInt(args[0].trim()), - Integer.parseInt(args[1].trim()) - ); - int time = Integer.parseInt(args[2].trim()); - int type = Integer.parseInt(args[3].trim()); - int hitSound = Integer.parseInt(args[4].trim()); - - boolean isBlue = (hitSound & 2) > 0 || (hitSound & 8) > 0; - TaikoCircle.TaikoColor color = isBlue ? TaikoCircle.TaikoColor.BLUE : TaikoCircle.TaikoColor.RED; - boolean isBig = (hitSound & 4) > 0; - - if ((type & 1) > 0) { - return new TaikoCircle(position, time, hitSound, color, isBig); - } else if ((type & 2) > 0) { - int repetitions = Integer.parseInt(args[6].trim()); - double pixelLength = Double.parseDouble(args[7].trim()); - return new TaikoDrumroll(position, time, hitSound, repetitions * pixelLength, isBig); - } else { - int endTime = Integer.parseInt(args[5].trim()); - return new TaikoShaker(position, time, endTime, hitSound); - } - } - - @Override - public Beatmap buildBeatmap(BeatmapGenerals generals, BeatmapEditorState editorState, - BeatmapMetadata metadata, BeatmapDifficulties difficulties, List breaks, - List timingPoints, List rawObjects) { - List hitObjects = parse(rawObjects); - return new TaikoBeatmap(generals, editorState, metadata, difficulties, breaks, timingPoints, hitObjects); - } + @Override + public TaikoObject parse(String line) { + String[] args = line.split(","); + Vec2 position = new Vec2( + Integer.parseInt(args[0].trim()), + Integer.parseInt(args[1].trim()) + ); + int time = Integer.parseInt(args[2].trim()); + int type = Integer.parseInt(args[3].trim()); + int hitSound = Integer.parseInt(args[4].trim()); + + boolean isBlue = (hitSound & 2) > 0 || (hitSound & 8) > 0; + TaikoCircle.TaikoColor color = isBlue ? TaikoCircle.TaikoColor.BLUE : TaikoCircle.TaikoColor.RED; + boolean isBig = (hitSound & 4) > 0; + + if ((type & 1) > 0) { + return new TaikoCircle(position, time, hitSound, color, isBig); + } else if ((type & 2) > 0) { + int repetitions = Integer.parseInt(args[6].trim()); + double pixelLength = Double.parseDouble(args[7].trim()); + return new TaikoDrumroll(position, time, hitSound, repetitions * pixelLength, isBig); + } else { + int endTime = Integer.parseInt(args[5].trim()); + return new TaikoShaker(position, time, endTime, hitSound); + } + } + + @Override + public Beatmap buildBeatmap(BeatmapGenerals generals, BeatmapEditorState editorState, + BeatmapMetadata metadata, BeatmapDifficulties difficulties, List breaks, + List timingPoints, List rawObjects) { + List hitObjects = parse(rawObjects); + return new TaikoBeatmap(generals, editorState, metadata, difficulties, breaks, timingPoints, hitObjects); + } } diff --git a/src/lt/ekgame/beatmap_analyzer/performance/ManiaPerformanceCalculator.java b/src/lt/ekgame/beatmap_analyzer/performance/ManiaPerformanceCalculator.java index fb9d65f7..bf00d7ed 100644 --- a/src/lt/ekgame/beatmap_analyzer/performance/ManiaPerformanceCalculator.java +++ b/src/lt/ekgame/beatmap_analyzer/performance/ManiaPerformanceCalculator.java @@ -8,56 +8,56 @@ public class ManiaPerformanceCalculator implements PerformanceCalculator { - @Override - public Performance calculate(Difficulty difficulty, Score score) { - ManiaDifficulty diff = (ManiaDifficulty) difficulty; - - double strainValue = calculateStrain(diff, score); - double accValue = calculateAccuracy(diff, score); - - double multiplier = 1.1; - if (diff.hasMod(Mod.NO_FAIL)) multiplier *= 0.9; - if (diff.hasMod(Mod.SPUN_OUT)) multiplier *= 0.95; - if (diff.hasMod(Mod.EASY)) multiplier *= 0.5; - - double performance = Math.pow(Math.pow(strainValue, 1.1) + Math.pow(accValue, 1.1), 1 / 1.1) * multiplier; - return new Performance(score.getAccuracy(), performance, 0, strainValue, accValue); - } - - private double calculateStrain(ManiaDifficulty difficulty, Score score) { - double scoreMultiplier = difficulty.getMods().getScoreMultiplier(Gamemode.MANIA); - if (scoreMultiplier <= 0) - return 0; - - int actualScore = (int) Math.round(score.getScore() * (1 / scoreMultiplier)); - - double strainValue = Math.pow(5 * Math.max(1, difficulty.getStars() / 0.0825f) - 4, 3) / 110000; - strainValue *= 1 + 0.1 * Math.min(1, difficulty.getObjectCount() / 1500.0); - - if (actualScore <= 500_000) - strainValue *= actualScore / 500_000.0 * 0.1; - else if (actualScore <= 600_000) - strainValue *= 0.1 + (actualScore - 500_000) / 100_000.0 * 0.2; - else if (actualScore <= 700_000) - strainValue *= 0.3 + (actualScore - 600_000) / 100_000.0 * 0.35; - else if (actualScore <= 800_000) - strainValue *= 0.65 + (actualScore - 700_000) / 100_000.0 * 0.2; - else if (actualScore <= 900_000) - strainValue *= 0.85 + (actualScore - 800_000) / 100_000.0 * 0.1; - else - strainValue *= 0.95 + (actualScore - 900_000) / 100_000.0 * 0.05; - - return strainValue; - } - - private double calculateAccuracy(ManiaDifficulty difficulty, Score score) { - double od = Math.min(10, Math.max(0, 10 - difficulty.getOD())); - double hitWindow = (34 + 3 * od);///difficulty.getSpeedMultiplier(); - if (hitWindow <= 0) - return 0; - - double accuracyValue = Math.pow(150 / hitWindow * Math.pow(score.getAccuracy(), 16), 1.8) * 2.5; - accuracyValue *= Math.min(1.15, Math.pow(difficulty.getObjectCount() / 1500.0, 0.3)); - return accuracyValue; - } + @Override + public Performance calculate(Difficulty difficulty, Score score) { + ManiaDifficulty diff = (ManiaDifficulty) difficulty; + + double strainValue = calculateStrain(diff, score); + double accValue = calculateAccuracy(diff, score); + + double multiplier = 1.1; + if (diff.hasMod(Mod.NO_FAIL)) multiplier *= 0.9; + if (diff.hasMod(Mod.SPUN_OUT)) multiplier *= 0.95; + if (diff.hasMod(Mod.EASY)) multiplier *= 0.5; + + double performance = Math.pow(Math.pow(strainValue, 1.1) + Math.pow(accValue, 1.1), 1 / 1.1) * multiplier; + return new Performance(score.getAccuracy(), performance, 0, strainValue, accValue); + } + + private double calculateStrain(ManiaDifficulty difficulty, Score score) { + double scoreMultiplier = difficulty.getMods().getScoreMultiplier(Gamemode.MANIA); + if (scoreMultiplier <= 0) + return 0; + + int actualScore = (int) Math.round(score.getScore() * (1 / scoreMultiplier)); + + double strainValue = Math.pow(5 * Math.max(1, difficulty.getStars() / 0.0825f) - 4, 3) / 110000; + strainValue *= 1 + 0.1 * Math.min(1, difficulty.getObjectCount() / 1500.0); + + if (actualScore <= 500_000) + strainValue *= actualScore / 500_000.0 * 0.1; + else if (actualScore <= 600_000) + strainValue *= 0.1 + (actualScore - 500_000) / 100_000.0 * 0.2; + else if (actualScore <= 700_000) + strainValue *= 0.3 + (actualScore - 600_000) / 100_000.0 * 0.35; + else if (actualScore <= 800_000) + strainValue *= 0.65 + (actualScore - 700_000) / 100_000.0 * 0.2; + else if (actualScore <= 900_000) + strainValue *= 0.85 + (actualScore - 800_000) / 100_000.0 * 0.1; + else + strainValue *= 0.95 + (actualScore - 900_000) / 100_000.0 * 0.05; + + return strainValue; + } + + private double calculateAccuracy(ManiaDifficulty difficulty, Score score) { + double od = Math.min(10, Math.max(0, 10 - difficulty.getOD())); + double hitWindow = (34 + 3 * od);///difficulty.getSpeedMultiplier(); + if (hitWindow <= 0) + return 0; + + double accuracyValue = Math.pow(150 / hitWindow * Math.pow(score.getAccuracy(), 16), 1.8) * 2.5; + accuracyValue *= Math.min(1.15, Math.pow(difficulty.getObjectCount() / 1500.0, 0.3)); + return accuracyValue; + } } diff --git a/src/lt/ekgame/beatmap_analyzer/performance/OsuPerformanceCalculator.java b/src/lt/ekgame/beatmap_analyzer/performance/OsuPerformanceCalculator.java index 3c39bd42..1ae0f9a9 100644 --- a/src/lt/ekgame/beatmap_analyzer/performance/OsuPerformanceCalculator.java +++ b/src/lt/ekgame/beatmap_analyzer/performance/OsuPerformanceCalculator.java @@ -9,137 +9,137 @@ public class OsuPerformanceCalculator implements PerformanceCalculator { - public static double DROID_AIM_M = 1.0; - public static double DROID_SPEED_M = 1.0; - public static double DROID_ACC_M = 1.0; + public static double DROID_AIM_M = 1.0; + public static double DROID_SPEED_M = 1.0; + public static double DROID_ACC_M = 1.0; - public static double SPEED_TO_ACC = 0.25; + public static double SPEED_TO_ACC = 0.25; - public Performance calculate(Difficulty difficulty, Score score) { - OsuDifficulty diff = (OsuDifficulty) difficulty; + public Performance calculate(Difficulty difficulty, Score score) { + OsuDifficulty diff = (OsuDifficulty) difficulty; - if (diff.getMaxCombo() <= 0) - throw new IllegalStateException("Beatmap must have elements."); + if (diff.getMaxCombo() <= 0) + throw new IllegalStateException("Beatmap must have elements."); - double hitsOver2k = diff.getObjectCount() / (double) 2000; - double hitsOver2k5 = diff.getObjectCount() / 2500d; - double lengthBonus = 0.95 + 0.3 * Math.min(1, hitsOver2k) + (diff.getObjectCount() > 2000 ? Math.log10(hitsOver2k) * 0.5 : 0); - double speedLengthBonus = 0.75 + 0.6 * Math.min(1, hitsOver2k5) + (diff.getObjectCount() > 2500 ? Math.log10(hitsOver2k5) : 0); - double missPenalty = Math.pow(0.97, score.getMisses()); - double comboBreak = Math.pow(score.getCombo(), 0.8) / Math.pow(diff.getMaxCombo(), 0.8); + double hitsOver2k = diff.getObjectCount() / (double) 2000; + double hitsOver2k5 = diff.getObjectCount() / 2500d; + double lengthBonus = 0.95 + 0.3 * Math.min(1, hitsOver2k) + (diff.getObjectCount() > 2000 ? Math.log10(hitsOver2k) * 0.5 : 0); + double speedLengthBonus = 0.75 + 0.6 * Math.min(1, hitsOver2k5) + (diff.getObjectCount() > 2500 ? Math.log10(hitsOver2k5) : 0); + double missPenalty = Math.pow(0.97, score.getMisses()); + double comboBreak = Math.pow(score.getCombo(), 0.8) / Math.pow(diff.getMaxCombo(), 0.8); - - // aim calculation - double ARBonus = 1; - double approachRate = diff.getAR(); - if (approachRate > 10.33) { - ARBonus += 0.45 * (approachRate - 10.33); - } else if (approachRate < 8) { - double lowARBonus = 0.01 * (8 - approachRate); - if (diff.hasMod(Mod.HIDDEN)) - lowARBonus *= 2; - ARBonus += lowARBonus; - } - - double aimValue = baseStrain(diff.getAim()); - aimValue *= lengthBonus * missPenalty * comboBreak * ARBonus * DROID_AIM_M; - - if (diff.hasMod(Mod.HIDDEN)) - aimValue *= 1.18; - - if (diff.hasMod(Mod.FLASHLIGHT)) - aimValue *= 1.45 * lengthBonus; - - double accuracy = score.getAccuracy(); - double accuracyBonus = 0.5 + accuracy / 2; - double ODBonus = 0.98 + Math.pow(diff.getOD(), 2) / 2500; - - aimValue *= accuracyBonus * ODBonus; - - // speed calculation - double speedValue = baseStrain(diff.getSpeed()); - double speedAccM; - if (accuracy < 0.6) { - speedAccM = 0; - } else if (accuracy < 0.9) { - speedAccM = (accuracy - 0.6) / 0.3 * 0.1; - } else if (accuracy < 0.95) { - speedAccM = 0.1 + 0.35 * (accuracy - 0.9) / 0.05; - } else { - speedAccM = 0.45 + 0.55 * (accuracy - 0.95) / 0.05; - } - speedValue *= speedLengthBonus * comboBreak * speedAccM * ODBonus * DROID_SPEED_M; - - // score v2 - double realAccuracy = accuracy; - int circles = diff.getObjectCount(); - - // score v1 - if (score.getVersion() == ScoreVersion.V1) { - circles = diff.getNumCircles(); - realAccuracy = getScoreV1Accuracy(diff.getObjectCount(), circles, accuracy, score.getMisses()); - } - - // accuracy calculation - double accuracyValue = Math.pow(1.52163, difficulty.getOD() / 1.15) * 2.83; - - //高speed会让高acc变困难,所以将speed的一部分转给acc,而且这个趋势在高ar下更明显 - double speed2acc = SPEED_TO_ACC * (0.5 + diff.getAR() / 10 * 0.6); - accuracyValue += speedValue * speed2acc; - - //aim也会对speed造成一定影响,但是影响不大 - accuracyValue += aimValue * 0.05; - - accuracyValue *= Math.min(1.15, Math.pow(circles / (double) 1000, 0.3)) * Math.pow(realAccuracy, 24.0) * DROID_ACC_M; - // 高ar会让高acc变困难 - accuracyValue *= 0.8 + diff.getAR() / 10 * 0.4; - - if (difficulty.hasMod(Mod.HIDDEN)) - accuracyValue *= 1.02; - - if (difficulty.hasMod(Mod.FLASHLIGHT)) - accuracyValue *= 1.02; - - // total pp calculation - double finalMultiplier = 1.12; - - if (difficulty.hasMod(Mod.NO_FAIL)) - finalMultiplier *= 0.9; - - if (difficulty.hasMod(Mod.SPUN_OUT)) - finalMultiplier *= 0.95; - - - double performance = Math.pow(Math.pow(aimValue, 1.1) + Math.pow(speedValue, 1.1) + Math.pow(accuracyValue, 1.1), 1 / 1.1) * finalMultiplier; - - return new Performance(realAccuracy, performance, aimValue, speedValue, accuracyValue); - } - - private double getScoreV1Accuracy(int objects, int circles, double accuracy, int misses) { - misses = Math.min(objects, misses); - int max300 = objects - misses; - - accuracy = Math.max(0.0, Math.min(MathUtils.calculateOsuAccuracy(max300, 0, 0, misses), accuracy)); - int num50 = 0; - int num100 = (int) Math.round(-3 * ((accuracy - 1) * objects + misses) * 0.5); - - if (num100 > objects - misses) { - num100 = 0; - num50 = (int) Math.round(-6.0 * ((accuracy - 1) * objects + misses) * 0.2); - num50 = Math.min(max300, num50); - } else { - num100 = Math.min(max300, num100); - } - int num300 = objects - num100 - num50 - misses; - - double realAccuracy = 0; - if (circles > 0) - realAccuracy = ((num300 - (objects - circles)) * 300 + num100 * 100 + num50 * 50) / ((double) circles * 300); - return Math.max(0, realAccuracy); - } - - private double baseStrain(double strain) { - return Math.pow(5 * Math.max(1, strain / 0.0675) - 4, 3) / 100000; - } + + // aim calculation + double ARBonus = 1; + double approachRate = diff.getAR(); + if (approachRate > 10.33) { + ARBonus += 0.45 * (approachRate - 10.33); + } else if (approachRate < 8) { + double lowARBonus = 0.01 * (8 - approachRate); + if (diff.hasMod(Mod.HIDDEN)) + lowARBonus *= 2; + ARBonus += lowARBonus; + } + + double aimValue = baseStrain(diff.getAim()); + aimValue *= lengthBonus * missPenalty * comboBreak * ARBonus * DROID_AIM_M; + + if (diff.hasMod(Mod.HIDDEN)) + aimValue *= 1.18; + + if (diff.hasMod(Mod.FLASHLIGHT)) + aimValue *= 1.45 * lengthBonus; + + double accuracy = score.getAccuracy(); + double accuracyBonus = 0.5 + accuracy / 2; + double ODBonus = 0.98 + Math.pow(diff.getOD(), 2) / 2500; + + aimValue *= accuracyBonus * ODBonus; + + // speed calculation + double speedValue = baseStrain(diff.getSpeed()); + double speedAccM; + if (accuracy < 0.6) { + speedAccM = 0; + } else if (accuracy < 0.9) { + speedAccM = (accuracy - 0.6) / 0.3 * 0.1; + } else if (accuracy < 0.95) { + speedAccM = 0.1 + 0.35 * (accuracy - 0.9) / 0.05; + } else { + speedAccM = 0.45 + 0.55 * (accuracy - 0.95) / 0.05; + } + speedValue *= speedLengthBonus * comboBreak * speedAccM * ODBonus * DROID_SPEED_M; + + // score v2 + double realAccuracy = accuracy; + int circles = diff.getObjectCount(); + + // score v1 + if (score.getVersion() == ScoreVersion.V1) { + circles = diff.getNumCircles(); + realAccuracy = getScoreV1Accuracy(diff.getObjectCount(), circles, accuracy, score.getMisses()); + } + + // accuracy calculation + double accuracyValue = Math.pow(1.52163, difficulty.getOD() / 1.15) * 2.83; + + //高speed会让高acc变困难,所以将speed的一部分转给acc,而且这个趋势在高ar下更明显 + double speed2acc = SPEED_TO_ACC * (0.5 + diff.getAR() / 10 * 0.6); + accuracyValue += speedValue * speed2acc; + + //aim也会对speed造成一定影响,但是影响不大 + accuracyValue += aimValue * 0.05; + + accuracyValue *= Math.min(1.15, Math.pow(circles / (double) 1000, 0.3)) * Math.pow(realAccuracy, 24.0) * DROID_ACC_M; + // 高ar会让高acc变困难 + accuracyValue *= 0.8 + diff.getAR() / 10 * 0.4; + + if (difficulty.hasMod(Mod.HIDDEN)) + accuracyValue *= 1.02; + + if (difficulty.hasMod(Mod.FLASHLIGHT)) + accuracyValue *= 1.02; + + // total pp calculation + double finalMultiplier = 1.12; + + if (difficulty.hasMod(Mod.NO_FAIL)) + finalMultiplier *= 0.9; + + if (difficulty.hasMod(Mod.SPUN_OUT)) + finalMultiplier *= 0.95; + + + double performance = Math.pow(Math.pow(aimValue, 1.1) + Math.pow(speedValue, 1.1) + Math.pow(accuracyValue, 1.1), 1 / 1.1) * finalMultiplier; + + return new Performance(realAccuracy, performance, aimValue, speedValue, accuracyValue); + } + + private double getScoreV1Accuracy(int objects, int circles, double accuracy, int misses) { + misses = Math.min(objects, misses); + int max300 = objects - misses; + + accuracy = Math.max(0.0, Math.min(MathUtils.calculateOsuAccuracy(max300, 0, 0, misses), accuracy)); + int num50 = 0; + int num100 = (int) Math.round(-3 * ((accuracy - 1) * objects + misses) * 0.5); + + if (num100 > objects - misses) { + num100 = 0; + num50 = (int) Math.round(-6.0 * ((accuracy - 1) * objects + misses) * 0.2); + num50 = Math.min(max300, num50); + } else { + num100 = Math.min(max300, num100); + } + int num300 = objects - num100 - num50 - misses; + + double realAccuracy = 0; + if (circles > 0) + realAccuracy = ((num300 - (objects - circles)) * 300 + num100 * 100 + num50 * 50) / ((double) circles * 300); + return Math.max(0, realAccuracy); + } + + private double baseStrain(double strain) { + return Math.pow(5 * Math.max(1, strain / 0.0675) - 4, 3) / 100000; + } } diff --git a/src/lt/ekgame/beatmap_analyzer/performance/Performance.java b/src/lt/ekgame/beatmap_analyzer/performance/Performance.java index 768f1d27..cda1186f 100644 --- a/src/lt/ekgame/beatmap_analyzer/performance/Performance.java +++ b/src/lt/ekgame/beatmap_analyzer/performance/Performance.java @@ -2,33 +2,33 @@ public class Performance { - private double accuracy, performance, aimPerformance, speedPerformance, accuracyPerformance; - - public Performance(double accuracy, double performance, double aimPerformance, double speedPerformance, double accuracyPerformance) { - this.accuracy = accuracy; - this.performance = performance; - this.aimPerformance = aimPerformance; - this.speedPerformance = speedPerformance; - this.accuracyPerformance = accuracyPerformance; - } - - public double getAccuracy() { - return accuracy; - } - - public double getPerformance() { - return performance; - } - - public double getAimPerformance() { - return aimPerformance; - } - - public double getSpeedPerformance() { - return speedPerformance; - } - - public double getAccuracyPerformance() { - return accuracyPerformance; - } + private double accuracy, performance, aimPerformance, speedPerformance, accuracyPerformance; + + public Performance(double accuracy, double performance, double aimPerformance, double speedPerformance, double accuracyPerformance) { + this.accuracy = accuracy; + this.performance = performance; + this.aimPerformance = aimPerformance; + this.speedPerformance = speedPerformance; + this.accuracyPerformance = accuracyPerformance; + } + + public double getAccuracy() { + return accuracy; + } + + public double getPerformance() { + return performance; + } + + public double getAimPerformance() { + return aimPerformance; + } + + public double getSpeedPerformance() { + return speedPerformance; + } + + public double getAccuracyPerformance() { + return accuracyPerformance; + } } diff --git a/src/lt/ekgame/beatmap_analyzer/performance/PerformanceCalculator.java b/src/lt/ekgame/beatmap_analyzer/performance/PerformanceCalculator.java index cb6a89a7..500d718d 100644 --- a/src/lt/ekgame/beatmap_analyzer/performance/PerformanceCalculator.java +++ b/src/lt/ekgame/beatmap_analyzer/performance/PerformanceCalculator.java @@ -5,6 +5,6 @@ public interface PerformanceCalculator { - public Performance calculate(Difficulty difficulty, Score score); + public Performance calculate(Difficulty difficulty, Score score); } diff --git a/src/lt/ekgame/beatmap_analyzer/performance/TaikoPerformanceCalculator.java b/src/lt/ekgame/beatmap_analyzer/performance/TaikoPerformanceCalculator.java index bcb8ba3c..d671d810 100644 --- a/src/lt/ekgame/beatmap_analyzer/performance/TaikoPerformanceCalculator.java +++ b/src/lt/ekgame/beatmap_analyzer/performance/TaikoPerformanceCalculator.java @@ -9,55 +9,55 @@ public class TaikoPerformanceCalculator implements PerformanceCalculator { - @Override - public Performance calculate(Difficulty difficulty, Score score) { - TaikoDifficulty diff = (TaikoDifficulty) difficulty; - double multiplier = 1.1; + @Override + public Performance calculate(Difficulty difficulty, Score score) { + TaikoDifficulty diff = (TaikoDifficulty) difficulty; + double multiplier = 1.1; - if (diff.hasMod(Mod.NO_FAIL)) - multiplier *= 0.9; + if (diff.hasMod(Mod.NO_FAIL)) + multiplier *= 0.9; - if (diff.hasMod(Mod.SPUN_OUT)) - multiplier *= 0.95; + if (diff.hasMod(Mod.SPUN_OUT)) + multiplier *= 0.95; - if (diff.hasMod(Mod.HIDDEN)) - multiplier *= 1.1; + if (diff.hasMod(Mod.HIDDEN)) + multiplier *= 1.1; - double accuracy = score.getAccuracy(); - double strainValue = calculateStrainValue(diff, score); - double accValue = calculateAccuracyValue(diff, score); - double performance = Math.pow(Math.pow(strainValue, 1.1) + Math.pow(accValue, 1.1), 1 / 1.1) * multiplier; + double accuracy = score.getAccuracy(); + double strainValue = calculateStrainValue(diff, score); + double accValue = calculateAccuracyValue(diff, score); + double performance = Math.pow(Math.pow(strainValue, 1.1) + Math.pow(accValue, 1.1), 1 / 1.1) * multiplier; - return new Performance(accuracy, performance, 0, strainValue, accValue); - } + return new Performance(accuracy, performance, 0, strainValue, accValue); + } - private double calculateStrainValue(TaikoDifficulty difficulty, Score score) { - double strainValue = Math.pow(5 * Math.max(1, difficulty.getStars() / 0.0075) - 4, 2) / 100000; - double lengthBonus = 1 + 0.1 * Math.min(1, difficulty.getObjectCount() / 1500.0); - strainValue *= lengthBonus; + private double calculateStrainValue(TaikoDifficulty difficulty, Score score) { + double strainValue = Math.pow(5 * Math.max(1, difficulty.getStars() / 0.0075) - 4, 2) / 100000; + double lengthBonus = 1 + 0.1 * Math.min(1, difficulty.getObjectCount() / 1500.0); + strainValue *= lengthBonus; - // miss penalty - strainValue *= Math.pow(0.985, score.getMisses()); + // miss penalty + strainValue *= Math.pow(0.985, score.getMisses()); - int maxCombo = difficulty.getMaxCombo(); - if (maxCombo > 0) - strainValue *= Math.min(Math.pow(score.getCombo(), 0.5) / Math.pow(maxCombo, 0.5), 1); + int maxCombo = difficulty.getMaxCombo(); + if (maxCombo > 0) + strainValue *= Math.min(Math.pow(score.getCombo(), 0.5) / Math.pow(maxCombo, 0.5), 1); - if (difficulty.hasMod(Mod.HIDDEN)) - strainValue *= 1.025; + if (difficulty.hasMod(Mod.HIDDEN)) + strainValue *= 1.025; - if (difficulty.hasMod(Mod.FLASHLIGHT)) - strainValue *= 1.05 * lengthBonus; + if (difficulty.hasMod(Mod.FLASHLIGHT)) + strainValue *= 1.05 * lengthBonus; - return strainValue * score.getAccuracy(); - } + return strainValue * score.getAccuracy(); + } - private double calculateAccuracyValue(TaikoDifficulty difficulty, Score score) { - int perfectHitWindow = MathUtils.getHitWindow300(difficulty.getOD(), Gamemode.TAIKO, difficulty.getMods()); - if (perfectHitWindow <= 0) - return 0; + private double calculateAccuracyValue(TaikoDifficulty difficulty, Score score) { + int perfectHitWindow = MathUtils.getHitWindow300(difficulty.getOD(), Gamemode.TAIKO, difficulty.getMods()); + if (perfectHitWindow <= 0) + return 0; - double accValue = Math.pow(150.0 / perfectHitWindow, 1.1) * Math.pow(score.getAccuracy(), 15) * 22; - return accValue * Math.min(1.15, Math.pow(difficulty.getMaxCombo() / 1500.0, 0.3)); - } + double accValue = Math.pow(150.0 / perfectHitWindow, 1.1) * Math.pow(score.getAccuracy(), 15) * 22; + return accValue * Math.min(1.15, Math.pow(difficulty.getMaxCombo() / 1500.0, 0.3)); + } } diff --git a/src/lt/ekgame/beatmap_analyzer/performance/scores/Score.java b/src/lt/ekgame/beatmap_analyzer/performance/scores/Score.java index 752e35a1..593683ac 100644 --- a/src/lt/ekgame/beatmap_analyzer/performance/scores/Score.java +++ b/src/lt/ekgame/beatmap_analyzer/performance/scores/Score.java @@ -5,39 +5,39 @@ public class Score { - private int score, combo, numMiss; - private double accuracy; - private ScoreVersion version; - - Score(int score, int combo, double accuracy, int numMiss, ScoreVersion version) { - this.score = score; - this.combo = combo; - this.accuracy = accuracy; - this.numMiss = numMiss; - this.version = version; - } - - public static ScoreBuilder of(Beatmap beatmap) { - return new ScoreBuilder(beatmap); - } - - public int getScore() { - return score; - } - - public int getCombo() { - return combo; - } - - public int getMisses() { - return numMiss; - } - - public double getAccuracy() { - return accuracy; - } - - public ScoreVersion getVersion() { - return version; - } + private int score, combo, numMiss; + private double accuracy; + private ScoreVersion version; + + Score(int score, int combo, double accuracy, int numMiss, ScoreVersion version) { + this.score = score; + this.combo = combo; + this.accuracy = accuracy; + this.numMiss = numMiss; + this.version = version; + } + + public static ScoreBuilder of(Beatmap beatmap) { + return new ScoreBuilder(beatmap); + } + + public int getScore() { + return score; + } + + public int getCombo() { + return combo; + } + + public int getMisses() { + return numMiss; + } + + public double getAccuracy() { + return accuracy; + } + + public ScoreVersion getVersion() { + return version; + } } diff --git a/src/lt/ekgame/beatmap_analyzer/performance/scores/ScoreBuilder.java b/src/lt/ekgame/beatmap_analyzer/performance/scores/ScoreBuilder.java index 73016601..f36db477 100644 --- a/src/lt/ekgame/beatmap_analyzer/performance/scores/ScoreBuilder.java +++ b/src/lt/ekgame/beatmap_analyzer/performance/scores/ScoreBuilder.java @@ -6,78 +6,78 @@ public class ScoreBuilder { - private Beatmap beatmap; - private int score = 1000000, combo, numMiss = 0; - private double accuracy = 1; - private ScoreVersion version = ScoreVersion.V2; - - public ScoreBuilder(Beatmap beatmap) { - this.beatmap = beatmap; - this.combo = beatmap.getMaxCombo(); - } - - public ScoreBuilder version(ScoreVersion version) { - this.version = version; - return this; - } - - public ScoreBuilder score(int score) { - this.score = score; - return this; - } - - public ScoreBuilder combo(int combo) { - this.combo = combo; - return this; - } - - public ScoreBuilder accuracy(double accuracy) { - return accuracy(accuracy, 0); - } - - public ScoreBuilder accuracy(double accuracy, int numMiss) { - this.numMiss = numMiss; - this.accuracy = accuracy; - return this; - } - - public ScoreBuilder osuAccuracy(int num100, int num50) { - return osuAccuracy(num100, num50, 0); - } - - public ScoreBuilder osuAccuracy(int num100, int num50, int numMiss) { - int num300 = beatmap.getObjectCount() - num100 - num50 - numMiss; - return accuracy(MathUtils.calculateOsuAccuracy(num300, num100, num50, numMiss), numMiss); - } - - public ScoreBuilder taikoAccuracy(int numHalf) { - return taikoAccuracy(numHalf, 0); - } - - public ScoreBuilder taikoAccuracy(int numHalf, int numMiss) { - int numGreat = beatmap.getMaxCombo() - numHalf - numMiss; - return accuracy(MathUtils.calculateTaikoAccuracy(numGreat, numHalf, numMiss), numMiss); - } - - public ScoreBuilder maniaAccuracy(int num200, int num100) { - return maniaAccuracy(num200, num100, 0, 0); - } - - public ScoreBuilder maniaAccuracy(int num200, int num100, int num50) { - return maniaAccuracy(num200, num100, num50, 0); - } - - public ScoreBuilder maniaAccuracy(int num200, int num100, int num50, int numMiss) { - int num300 = beatmap.getObjectCount() - num200 - num100 - num50 - numMiss; - return accuracy(MathUtils.calculateManiaAccuracy(0, num300, num200, num100, num50, numMiss), numMiss); - } - - public ScoreBuilder catchAccuracy(int missedDroplets, int numMiss) { - int hits = beatmap.getMaxCombo() - missedDroplets - numMiss; - return accuracy(MathUtils.calculateCatchAccuracy(hits, missedDroplets + numMiss), numMiss); - } - - public Score build() { - return new Score(score, combo, accuracy, numMiss, version); - } + private Beatmap beatmap; + private int score = 1000000, combo, numMiss = 0; + private double accuracy = 1; + private ScoreVersion version = ScoreVersion.V2; + + public ScoreBuilder(Beatmap beatmap) { + this.beatmap = beatmap; + this.combo = beatmap.getMaxCombo(); + } + + public ScoreBuilder version(ScoreVersion version) { + this.version = version; + return this; + } + + public ScoreBuilder score(int score) { + this.score = score; + return this; + } + + public ScoreBuilder combo(int combo) { + this.combo = combo; + return this; + } + + public ScoreBuilder accuracy(double accuracy) { + return accuracy(accuracy, 0); + } + + public ScoreBuilder accuracy(double accuracy, int numMiss) { + this.numMiss = numMiss; + this.accuracy = accuracy; + return this; + } + + public ScoreBuilder osuAccuracy(int num100, int num50) { + return osuAccuracy(num100, num50, 0); + } + + public ScoreBuilder osuAccuracy(int num100, int num50, int numMiss) { + int num300 = beatmap.getObjectCount() - num100 - num50 - numMiss; + return accuracy(MathUtils.calculateOsuAccuracy(num300, num100, num50, numMiss), numMiss); + } + + public ScoreBuilder taikoAccuracy(int numHalf) { + return taikoAccuracy(numHalf, 0); + } + + public ScoreBuilder taikoAccuracy(int numHalf, int numMiss) { + int numGreat = beatmap.getMaxCombo() - numHalf - numMiss; + return accuracy(MathUtils.calculateTaikoAccuracy(numGreat, numHalf, numMiss), numMiss); + } + + public ScoreBuilder maniaAccuracy(int num200, int num100) { + return maniaAccuracy(num200, num100, 0, 0); + } + + public ScoreBuilder maniaAccuracy(int num200, int num100, int num50) { + return maniaAccuracy(num200, num100, num50, 0); + } + + public ScoreBuilder maniaAccuracy(int num200, int num100, int num50, int numMiss) { + int num300 = beatmap.getObjectCount() - num200 - num100 - num50 - numMiss; + return accuracy(MathUtils.calculateManiaAccuracy(0, num300, num200, num100, num50, numMiss), numMiss); + } + + public ScoreBuilder catchAccuracy(int missedDroplets, int numMiss) { + int hits = beatmap.getMaxCombo() - missedDroplets - numMiss; + return accuracy(MathUtils.calculateCatchAccuracy(hits, missedDroplets + numMiss), numMiss); + } + + public Score build() { + return new Score(score, combo, accuracy, numMiss, version); + } } diff --git a/src/lt/ekgame/beatmap_analyzer/utils/Introsort.java b/src/lt/ekgame/beatmap_analyzer/utils/Introsort.java index 12bd7e8a..7101ab82 100644 --- a/src/lt/ekgame/beatmap_analyzer/utils/Introsort.java +++ b/src/lt/ekgame/beatmap_analyzer/utils/Introsort.java @@ -20,130 +20,130 @@ public final class Introsort { - private static int size_threshold = 16; - - public static > void sort(List list) { - introSortLoop(list, 0, list.size(), 2 * floorLg(list.size())); - - } - - public static > void sort(List list, int begin, int end) { - if (begin < end) { - introSortLoop(list, begin, end, 2 * floorLg(end - begin)); - } - } - - /* - * Quicksort algorithm modified for Introsort - */ - private static > void introSortLoop(List list, int lo, int hi, int depth_limit) { - while (hi - lo > size_threshold) { - if (depth_limit == 0) { - heapsort(list, lo, hi); - return; - } - depth_limit = depth_limit - 1; - int p = partition(list, lo, hi, medianof3(list, lo, lo + ((hi - lo) / 2) + 1, hi - 1)); - introSortLoop(list, p, hi, depth_limit); - hi = p; - } - insertionsort(list, lo, hi); - } - - private static > int partition(List list, int lo, int hi, T x) { - int i = lo, j = hi; - while (true) { - while (list.get(i).compareTo(x) < 0) - i++; - j = j - 1; - while (x.compareTo(list.get(j)) < 0) - j = j - 1; - if (!(i < j)) - return i; - exchange(list, i, j); - i++; - } - } - - private static > T medianof3(List list, int lo, int mid, int hi) { - - if (list.get(mid).compareTo(list.get(lo)) < 0) { - if (list.get(hi).compareTo(list.get(mid)) < 0) - return list.get(mid); - else { - if (list.get(hi).compareTo(list.get(lo)) < 0) - return list.get(hi); - else - return list.get(lo); - } - } else { - if (list.get(hi).compareTo(list.get(mid)) < 0) { - if (list.get(hi).compareTo(list.get(lo)) < 0) - return list.get(lo); - else - return list.get(hi); - } else - return list.get(mid); - } - } - - /* - * Heapsort algorithm - */ - private static > void heapsort(List list, int lo, int hi) { - int n = hi - lo; - for (int i = n / 2; i >= 1; i = i - 1) { - downheap(list, i, n, lo); - } - for (int i = n; i > 1; i = i - 1) { - exchange(list, lo, lo + i - 1); - downheap(list, 1, i - 1, lo); - } - } - - private static > void downheap(List list, int i, int n, int lo) { - T d = list.get(lo + i - 1); - int child; - while (i <= n / 2) { - child = 2 * i; - if (child < n && (list.get(lo + child - 1).compareTo(list.get(lo + child)) < 0)) { - child++; - } - if (d.compareTo(list.get(lo + child - 1)) >= 0) - break; - list.set(lo + i - 1, list.get(lo + child - 1)); - i = child; - } - list.set(lo + i - 1, d); - } - - /* - * Insertion sort algorithm - */ - private static > void insertionsort(List list, int lo, int hi) { - int i, j; - T t; - for (i = lo; i < hi; i++) { - j = i; - t = list.get(i); - while (j != lo && t.compareTo(list.get(j - 1)) < 0) { - list.set(j, list.get(j - 1)); - j--; - } - list.set(j, t); - } - } - - /* - * Common methods for all algorithms - */ - private static > void exchange(List list, int i, int j) { - T t = list.get(i); - list.set(i, list.get(j)); - list.set(j, t); - } - - private static int floorLg(int a) { - return (int) (Math.floor(Math.log(a) / Math.log(2))); - } + private static int size_threshold = 16; + + public static > void sort(List list) { + introSortLoop(list, 0, list.size(), 2 * floorLg(list.size())); + + } + + public static > void sort(List list, int begin, int end) { + if (begin < end) { + introSortLoop(list, begin, end, 2 * floorLg(end - begin)); + } + } + + /* + * Quicksort algorithm modified for Introsort + */ + private static > void introSortLoop(List list, int lo, int hi, int depth_limit) { + while (hi - lo > size_threshold) { + if (depth_limit == 0) { + heapsort(list, lo, hi); + return; + } + depth_limit = depth_limit - 1; + int p = partition(list, lo, hi, medianof3(list, lo, lo + ((hi - lo) / 2) + 1, hi - 1)); + introSortLoop(list, p, hi, depth_limit); + hi = p; + } + insertionsort(list, lo, hi); + } + + private static > int partition(List list, int lo, int hi, T x) { + int i = lo, j = hi; + while (true) { + while (list.get(i).compareTo(x) < 0) + i++; + j = j - 1; + while (x.compareTo(list.get(j)) < 0) + j = j - 1; + if (!(i < j)) + return i; + exchange(list, i, j); + i++; + } + } + + private static > T medianof3(List list, int lo, int mid, int hi) { + + if (list.get(mid).compareTo(list.get(lo)) < 0) { + if (list.get(hi).compareTo(list.get(mid)) < 0) + return list.get(mid); + else { + if (list.get(hi).compareTo(list.get(lo)) < 0) + return list.get(hi); + else + return list.get(lo); + } + } else { + if (list.get(hi).compareTo(list.get(mid)) < 0) { + if (list.get(hi).compareTo(list.get(lo)) < 0) + return list.get(lo); + else + return list.get(hi); + } else + return list.get(mid); + } + } + + /* + * Heapsort algorithm + */ + private static > void heapsort(List list, int lo, int hi) { + int n = hi - lo; + for (int i = n / 2; i >= 1; i = i - 1) { + downheap(list, i, n, lo); + } + for (int i = n; i > 1; i = i - 1) { + exchange(list, lo, lo + i - 1); + downheap(list, 1, i - 1, lo); + } + } + + private static > void downheap(List list, int i, int n, int lo) { + T d = list.get(lo + i - 1); + int child; + while (i <= n / 2) { + child = 2 * i; + if (child < n && (list.get(lo + child - 1).compareTo(list.get(lo + child)) < 0)) { + child++; + } + if (d.compareTo(list.get(lo + child - 1)) >= 0) + break; + list.set(lo + i - 1, list.get(lo + child - 1)); + i = child; + } + list.set(lo + i - 1, d); + } + + /* + * Insertion sort algorithm + */ + private static > void insertionsort(List list, int lo, int hi) { + int i, j; + T t; + for (i = lo; i < hi; i++) { + j = i; + t = list.get(i); + while (j != lo && t.compareTo(list.get(j - 1)) < 0) { + list.set(j, list.get(j - 1)); + j--; + } + list.set(j, t); + } + } + + /* + * Common methods for all algorithms + */ + private static > void exchange(List list, int i, int j) { + T t = list.get(i); + list.set(i, list.get(j)); + list.set(j, t); + } + + private static int floorLg(int a) { + return (int) (Math.floor(Math.log(a) / Math.log(2))); + } } diff --git a/src/lt/ekgame/beatmap_analyzer/utils/MathUtils.java b/src/lt/ekgame/beatmap_analyzer/utils/MathUtils.java index 7e64b8b6..f0cf5868 100644 --- a/src/lt/ekgame/beatmap_analyzer/utils/MathUtils.java +++ b/src/lt/ekgame/beatmap_analyzer/utils/MathUtils.java @@ -4,127 +4,127 @@ public class MathUtils { - private static final double - ODMinMs = 80, // OD 0 - ODMaxMs = 20, // OD 10 - ARMinMs = 1800, // AR 0 - ARMidMs = 1200, // AR 5 - ARMaxMs = 450; // AR 10 - - private static final double - ODStep = 6, - ARStepLow = 120, // AR 0-5 - ARStepHigh = 150; // AR 5-10 - - public static double clamp(double min, double max, double value) { - return Math.min(max, Math.max(min, value)); - } - - public static double difficultyRange(double diff, double min, double mid, double max, Mods mods) { - if (mods.has(Mod.EASY)) - diff = Math.max(0, diff / 2); - - if (mods.has(Mod.HARDROCK)) - diff = Math.min(10, diff * 1.4); - - return (diff > 5) ? (mid + (max - mid) * (diff - 5) / 5) - : (diff < 5) ? (mid - (mid - min) * (5 - diff) / 5) - : mid; - } - - public static int getHitWindow50(double od, Gamemode gamemode, Mods mods) { - double speed = mods.getSpeedMultiplier(); - switch (gamemode) { - case OSU: - return (int) (difficultyRange(od, 200, 150, 100, mods) / speed); - case TAIKO: - return (int) (difficultyRange(od, 135, 95, 70, mods) / speed); - case CATCH: - return -1; - case MANIA: - return -1; - default: - return -1; - } - } - - public static int getHitWindow100(double od, Gamemode gamemode, Mods mods) { - double speed = mods.getSpeedMultiplier(); - switch (gamemode) { - case OSU: - return (int) (difficultyRange(od, 140, 100, 60, mods) / speed); - case TAIKO: - return (int) (difficultyRange(od, 120, 80, 50, mods) / speed); - case CATCH: - return -1; - case MANIA: - return -1; - default: - return -1; - } - } - - public static int getHitWindow300(double od, Gamemode gamemode, Mods mods) { - double speed = mods.getSpeedMultiplier(); - switch (gamemode) { - case OSU: - return (int) (difficultyRange(od, 80, 50, 20, mods) / speed); - case TAIKO: - return (int) (difficultyRange(od, 50, 35, 20, mods) / speed); - case CATCH: - return -1; - case MANIA: - return -1; - default: - return -1; - } - } - - public static double recalculateOverallDifficulty(double od, double multiplier, double speedMultiplier) { - double overallDifficulty = od * multiplier; - double overallDifficultyTime = ODMinMs - Math.ceil(ODStep * overallDifficulty); - overallDifficultyTime = MathUtils.clamp(ODMaxMs, ODMinMs, overallDifficultyTime / speedMultiplier); - return (ODMinMs - overallDifficultyTime) / ODStep; - } - - public static double recalculateApproachRate(double ar, double multiplier, double speedMultiplier) { - double approachRate = ar * multiplier; - double approachRateTime = approachRate <= 5 ? (ARMinMs - ARStepLow * approachRate) : (ARMidMs - ARStepHigh * (approachRate - 5)); - approachRateTime = MathUtils.clamp(ARMaxMs, ARMinMs, approachRateTime / speedMultiplier); - return approachRate <= 5 ? ((ARMinMs - approachRateTime) / ARStepLow) : (5 + (ARMidMs - approachRateTime) / ARStepHigh); - } - - public static double recalculateCircleSize(double cs, double multiplier) { - double circleSize = cs * multiplier; - return MathUtils.clamp(0, 10, circleSize); - } - - public static int calculateManiaCollumn(double x, int collumns) { - return (int) (x / (512.0 / collumns)); - } - - public static double calculateOsuAccuracy(int num300, int num100, int num50, int numMiss) { - int total = num300 + num100 + num50 + numMiss; - return total == 0 ? 0 : ((num300 * 6 + num100 * 2 + num50) / (total * 6.0)); - } - - public static double calculateTaikoAccuracy(int numGreat, int numHalf, int numMiss) { - int total = numGreat + numHalf + numMiss; - return total == 0 ? 0 : ((numGreat * 2 + numHalf) / (total * 2.0)); - } - - public static double calculateManiaAccuracy(int numMax300, int num300, int num200, int num100, int num50, int numMiss) { - int total = numMax300 + num300 + num200 + num100 + num50 + numMiss; - return total == 0 ? 0 : (((numMax300 + num300) * 6 + num200 * 4 + num100 * 2 + num50) / (total * 6.0)); - } - - public static double calculateCatchAccuracy(int numFruit, int numTick, int numDroplet, int numMiss, int numDropletMiss) { - int total = numFruit + numTick + numDroplet + numMiss + numDropletMiss; - return total == 0 ? 0 : (numFruit + numTick + numDroplet) / ((double) total); - } - - public static double calculateCatchAccuracy(int numHits, int numMisses) { - int total = numHits + numMisses; - return total == 0 ? 0 : (numHits) / ((double) total); - } -} \ No newline at end of file + private static final double + ODMinMs = 80, // OD 0 + ODMaxMs = 20, // OD 10 + ARMinMs = 1800, // AR 0 + ARMidMs = 1200, // AR 5 + ARMaxMs = 450; // AR 10 + + private static final double + ODStep = 6, + ARStepLow = 120, // AR 0-5 + ARStepHigh = 150; // AR 5-10 + + public static double clamp(double min, double max, double value) { + return Math.min(max, Math.max(min, value)); + } + + public static double difficultyRange(double diff, double min, double mid, double max, Mods mods) { + if (mods.has(Mod.EASY)) + diff = Math.max(0, diff / 2); + + if (mods.has(Mod.HARDROCK)) + diff = Math.min(10, diff * 1.4); + + return (diff > 5) ? (mid + (max - mid) * (diff - 5) / 5) + : (diff < 5) ? (mid - (mid - min) * (5 - diff) / 5) + : mid; + } + + public static int getHitWindow50(double od, Gamemode gamemode, Mods mods) { + double speed = mods.getSpeedMultiplier(); + switch (gamemode) { + case OSU: + return (int) (difficultyRange(od, 200, 150, 100, mods) / speed); + case TAIKO: + return (int) (difficultyRange(od, 135, 95, 70, mods) / speed); + case CATCH: + return -1; + case MANIA: + return -1; + default: + return -1; + } + } + + public static int getHitWindow100(double od, Gamemode gamemode, Mods mods) { + double speed = mods.getSpeedMultiplier(); + switch (gamemode) { + case OSU: + return (int) (difficultyRange(od, 140, 100, 60, mods) / speed); + case TAIKO: + return (int) (difficultyRange(od, 120, 80, 50, mods) / speed); + case CATCH: + return -1; + case MANIA: + return -1; + default: + return -1; + } + } + + public static int getHitWindow300(double od, Gamemode gamemode, Mods mods) { + double speed = mods.getSpeedMultiplier(); + switch (gamemode) { + case OSU: + return (int) (difficultyRange(od, 80, 50, 20, mods) / speed); + case TAIKO: + return (int) (difficultyRange(od, 50, 35, 20, mods) / speed); + case CATCH: + return -1; + case MANIA: + return -1; + default: + return -1; + } + } + + public static double recalculateOverallDifficulty(double od, double multiplier, double speedMultiplier) { + double overallDifficulty = od * multiplier; + double overallDifficultyTime = ODMinMs - Math.ceil(ODStep * overallDifficulty); + overallDifficultyTime = MathUtils.clamp(ODMaxMs, ODMinMs, overallDifficultyTime / speedMultiplier); + return (ODMinMs - overallDifficultyTime) / ODStep; + } + + public static double recalculateApproachRate(double ar, double multiplier, double speedMultiplier) { + double approachRate = ar * multiplier; + double approachRateTime = approachRate <= 5 ? (ARMinMs - ARStepLow * approachRate) : (ARMidMs - ARStepHigh * (approachRate - 5)); + approachRateTime = MathUtils.clamp(ARMaxMs, ARMinMs, approachRateTime / speedMultiplier); + return approachRate <= 5 ? ((ARMinMs - approachRateTime) / ARStepLow) : (5 + (ARMidMs - approachRateTime) / ARStepHigh); + } + + public static double recalculateCircleSize(double cs, double multiplier) { + double circleSize = cs * multiplier; + return MathUtils.clamp(0, 10, circleSize); + } + + public static int calculateManiaCollumn(double x, int collumns) { + return (int) (x / (512.0 / collumns)); + } + + public static double calculateOsuAccuracy(int num300, int num100, int num50, int numMiss) { + int total = num300 + num100 + num50 + numMiss; + return total == 0 ? 0 : ((num300 * 6 + num100 * 2 + num50) / (total * 6.0)); + } + + public static double calculateTaikoAccuracy(int numGreat, int numHalf, int numMiss) { + int total = numGreat + numHalf + numMiss; + return total == 0 ? 0 : ((numGreat * 2 + numHalf) / (total * 2.0)); + } + + public static double calculateManiaAccuracy(int numMax300, int num300, int num200, int num100, int num50, int numMiss) { + int total = numMax300 + num300 + num200 + num100 + num50 + numMiss; + return total == 0 ? 0 : (((numMax300 + num300) * 6 + num200 * 4 + num100 * 2 + num50) / (total * 6.0)); + } + + public static double calculateCatchAccuracy(int numFruit, int numTick, int numDroplet, int numMiss, int numDropletMiss) { + int total = numFruit + numTick + numDroplet + numMiss + numDropletMiss; + return total == 0 ? 0 : (numFruit + numTick + numDroplet) / ((double) total); + } + + public static double calculateCatchAccuracy(int numHits, int numMisses) { + int total = numHits + numMisses; + return total == 0 ? 0 : (numHits) / ((double) total); + } +} diff --git a/src/lt/ekgame/beatmap_analyzer/utils/Mod.java b/src/lt/ekgame/beatmap_analyzer/utils/Mod.java index 61a0048b..2ced74d5 100644 --- a/src/lt/ekgame/beatmap_analyzer/utils/Mod.java +++ b/src/lt/ekgame/beatmap_analyzer/utils/Mod.java @@ -2,64 +2,64 @@ public enum Mod { - NO_FAIL(0, "No Fail", "nf"), - EASY(1, "Easy", "ez"), - HIDDEN(3, "Hidden", "hd"), - HARDROCK(4, "Hardrock", "hr"), - SUDDEN_DEATH(5, "Sudden Death", "sd"), - DOUBLE_TIME(6, "Double Time", "dt"), - RELAX(7, "Relax", "rx", false), - HALF_TIME(8, "Half Time", "ht"), - NIGHTCORE(9, "Nightcore", "nc"), - FLASHLIGHT(10, "Flashlight", "fl"), - AUTOPLAY(11, "Autoplay", "ap", false), - SPUN_OUT(12, "Spun Out", "so"), - AUTOPILOT(13, "Autopilot", "ap", false); + NO_FAIL(0, "No Fail", "nf"), + EASY(1, "Easy", "ez"), + HIDDEN(3, "Hidden", "hd"), + HARDROCK(4, "Hardrock", "hr"), + SUDDEN_DEATH(5, "Sudden Death", "sd"), + DOUBLE_TIME(6, "Double Time", "dt"), + RELAX(7, "Relax", "rx", false), + HALF_TIME(8, "Half Time", "ht"), + NIGHTCORE(9, "Nightcore", "nc"), + FLASHLIGHT(10, "Flashlight", "fl"), + AUTOPLAY(11, "Autoplay", "ap", false), + SPUN_OUT(12, "Spun Out", "so"), + AUTOPILOT(13, "Autopilot", "ap", false); - private int offset; - private String name, shortName; - private boolean isRanked = true; + private int offset; + private String name, shortName; + private boolean isRanked = true; - Mod(int offset, String name, String shortName, boolean isRanked) { - this(offset, name, shortName); - this.isRanked = isRanked; - } + Mod(int offset, String name, String shortName, boolean isRanked) { + this(offset, name, shortName); + this.isRanked = isRanked; + } - Mod(int offset, String name, String shortName) { - this.offset = offset; - this.name = name; - this.shortName = shortName; - } + Mod(int offset, String name, String shortName) { + this.offset = offset; + this.name = name; + this.shortName = shortName; + } - public static Mod parse(String shortName) { - if (shortName == null) - return null; + public static Mod parse(String shortName) { + if (shortName == null) + return null; - shortName = shortName.toLowerCase(); - for (Mod mod : Mod.values()) - if (mod.getShortName().equals(shortName)) - return mod; + shortName = shortName.toLowerCase(); + for (Mod mod : Mod.values()) + if (mod.getShortName().equals(shortName)) + return mod; - return null; - } + return null; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public String getShortName() { - return shortName; - } + public String getShortName() { + return shortName; + } - public boolean isRanked() { - return isRanked; - } + public boolean isRanked() { + return isRanked; + } - public int getBitOffset() { - return offset; - } + public int getBitOffset() { + return offset; + } - public int getBit() { - return 1 << offset; - } + public int getBit() { + return 1 << offset; + } } diff --git a/src/lt/ekgame/beatmap_analyzer/utils/Mods.java b/src/lt/ekgame/beatmap_analyzer/utils/Mods.java index 7ead1762..07710237 100644 --- a/src/lt/ekgame/beatmap_analyzer/utils/Mods.java +++ b/src/lt/ekgame/beatmap_analyzer/utils/Mods.java @@ -9,130 +9,130 @@ public class Mods { - public static final Mods NOMOD = new Mods(); - - private final int speedChangingFlags = Mod.DOUBLE_TIME.getBit() | Mod.NIGHTCORE.getBit() | Mod.HALF_TIME.getBit(); - private final int mapChangingFlags = speedChangingFlags | Mod.EASY.getBit() | Mod.HARDROCK.getBit(); - - private List mods = new ArrayList<>(); - private int modFlags; - - public Mods(List mods) { - for (Mod mod : mods) - if (!this.mods.contains(mod)) - this.mods.add(mod); - calculateFlags(); - } - - public Mods(Mod... mods) { - this(Arrays.asList(mods)); - } - - public static Mods parse(int flags) { - List result = new ArrayList<>(); - for (Mod mod : Mod.values()) - if ((flags & mod.getBit()) > 0) - result.add(mod); - return new Mods(result); - } - - public static Mods parse(String mods) { - List result = new ArrayList(); - int length = mods.length(); - for (int i = 0; i < length; i += 2) { - String modString = mods.substring(i, Math.min(length, i + 2)); - if (modString.length() != 2) - continue; - - Mod mod = Mod.parse(modString); - if (mod != null) - result.add(mod); - } - return new Mods(result); - } - - public boolean isRanked() { - for (Mod m : mods) { - if (!m.isRanked()) return false; - } - return true; - - //return !mods.stream() - // .filter(mod->!mod.isRanked()) - // .findAny().isPresent(); - } - - public Mods withoutUnranked() { - List ms = new ArrayList(); - for (Mod m : mods) { - if (m.isRanked()) ms.add(m); - } - - return new Mods(ms); - //new Mods(mods.stream().filter(mod->mod.isRanked()).collect(Collectors.toList())); - } - - public List getMods() { - return Collections.unmodifiableList(mods); - } - - public String toString() { - StringBuilder b = new StringBuilder(); - for (Mod m : mods) { - b.append(m.getShortName()); - } - - return b.toString().toUpperCase(); - //mods.stream().map(o->o.getShortName()) - // .collect(Collectors.joining()).toUpperCase(); - } - - public boolean isNomod() { - return mods.isEmpty(); - } - - private void calculateFlags() { - for (Mod mod : mods) - modFlags |= mod.getBit(); - } - - public int getFlags() { - return modFlags; - } - - public boolean has(Mod mod) { - return (mod.getBit() & modFlags) > 0; - } - - public boolean isMapChanging() { - return (mapChangingFlags & modFlags) > 0; - } - - public boolean isSpeedChanging() { - return (speedChangingFlags & modFlags) > 0; - } - - public double getSpeedMultiplier() { - if (has(Mod.DOUBLE_TIME) || has(Mod.NIGHTCORE)) - return 1.5; - else if (has(Mod.HALF_TIME)) - return 0.75; - return 1; - } - - public double getScoreMultiplier(Gamemode mode) { - double multiplier = 1; - if (has(Mod.NO_FAIL)) multiplier *= 0.5; - if (has(Mod.HALF_TIME)) multiplier *= mode == Gamemode.MANIA ? 0.5 : 0.3; - if (has(Mod.HIDDEN)) multiplier *= mode == Gamemode.MANIA ? 1 : 1.06; - if (has(Mod.FLASHLIGHT)) multiplier *= mode == Gamemode.MANIA ? 1 : 1.12; - - if (has(Mod.HARDROCK)) - multiplier *= mode == Gamemode.CATCH ? 1.12 : mode == Gamemode.MANIA ? 1 : 1.06; - - if (has(Mod.DOUBLE_TIME) || has(Mod.NIGHTCORE)) - multiplier *= mode == Gamemode.CATCH ? 1.06 : mode == Gamemode.MANIA ? 1 : 1.12; - - return multiplier; - } + public static final Mods NOMOD = new Mods(); + + private final int speedChangingFlags = Mod.DOUBLE_TIME.getBit() | Mod.NIGHTCORE.getBit() | Mod.HALF_TIME.getBit(); + private final int mapChangingFlags = speedChangingFlags | Mod.EASY.getBit() | Mod.HARDROCK.getBit(); + + private List mods = new ArrayList<>(); + private int modFlags; + + public Mods(List mods) { + for (Mod mod : mods) + if (!this.mods.contains(mod)) + this.mods.add(mod); + calculateFlags(); + } + + public Mods(Mod... mods) { + this(Arrays.asList(mods)); + } + + public static Mods parse(int flags) { + List result = new ArrayList<>(); + for (Mod mod : Mod.values()) + if ((flags & mod.getBit()) > 0) + result.add(mod); + return new Mods(result); + } + + public static Mods parse(String mods) { + List result = new ArrayList(); + int length = mods.length(); + for (int i = 0; i < length; i += 2) { + String modString = mods.substring(i, Math.min(length, i + 2)); + if (modString.length() != 2) + continue; + + Mod mod = Mod.parse(modString); + if (mod != null) + result.add(mod); + } + return new Mods(result); + } + + public boolean isRanked() { + for (Mod m : mods) { + if (!m.isRanked()) return false; + } + return true; + + //return !mods.stream() + // .filter(mod->!mod.isRanked()) + // .findAny().isPresent(); + } + + public Mods withoutUnranked() { + List ms = new ArrayList(); + for (Mod m : mods) { + if (m.isRanked()) ms.add(m); + } + + return new Mods(ms); + //new Mods(mods.stream().filter(mod->mod.isRanked()).collect(Collectors.toList())); + } + + public List getMods() { + return Collections.unmodifiableList(mods); + } + + public String toString() { + StringBuilder b = new StringBuilder(); + for (Mod m : mods) { + b.append(m.getShortName()); + } + + return b.toString().toUpperCase(); + //mods.stream().map(o->o.getShortName()) + // .collect(Collectors.joining()).toUpperCase(); + } + + public boolean isNomod() { + return mods.isEmpty(); + } + + private void calculateFlags() { + for (Mod mod : mods) + modFlags |= mod.getBit(); + } + + public int getFlags() { + return modFlags; + } + + public boolean has(Mod mod) { + return (mod.getBit() & modFlags) > 0; + } + + public boolean isMapChanging() { + return (mapChangingFlags & modFlags) > 0; + } + + public boolean isSpeedChanging() { + return (speedChangingFlags & modFlags) > 0; + } + + public double getSpeedMultiplier() { + if (has(Mod.DOUBLE_TIME) || has(Mod.NIGHTCORE)) + return 1.5; + else if (has(Mod.HALF_TIME)) + return 0.75; + return 1; + } + + public double getScoreMultiplier(Gamemode mode) { + double multiplier = 1; + if (has(Mod.NO_FAIL)) multiplier *= 0.5; + if (has(Mod.HALF_TIME)) multiplier *= mode == Gamemode.MANIA ? 0.5 : 0.3; + if (has(Mod.HIDDEN)) multiplier *= mode == Gamemode.MANIA ? 1 : 1.06; + if (has(Mod.FLASHLIGHT)) multiplier *= mode == Gamemode.MANIA ? 1 : 1.12; + + if (has(Mod.HARDROCK)) + multiplier *= mode == Gamemode.CATCH ? 1.12 : mode == Gamemode.MANIA ? 1 : 1.06; + + if (has(Mod.DOUBLE_TIME) || has(Mod.NIGHTCORE)) + multiplier *= mode == Gamemode.CATCH ? 1.06 : mode == Gamemode.MANIA ? 1 : 1.12; + + return multiplier; + } } diff --git a/src/lt/ekgame/beatmap_analyzer/utils/Quicksort.java b/src/lt/ekgame/beatmap_analyzer/utils/Quicksort.java index 2125bb3a..6f1159bc 100644 --- a/src/lt/ekgame/beatmap_analyzer/utils/Quicksort.java +++ b/src/lt/ekgame/beatmap_analyzer/utils/Quicksort.java @@ -12,91 +12,91 @@ public class Quicksort { - private static int size_threshold = 16; + private static int size_threshold = 16; - public static > void sort(List list) { - introSortLoop(list, 0, list.size()); + public static > void sort(List list) { + introSortLoop(list, 0, list.size()); - } + } - public static > void sort(List list, int begin, int end) { - if (begin < end) { - introSortLoop(list, begin, end); - } - } + public static > void sort(List list, int begin, int end) { + if (begin < end) { + introSortLoop(list, begin, end); + } + } - /* - * Quicksort algorithm modified for Introsort - */ - private static > void introSortLoop(List list, int lo, int hi) { - while (hi - lo > size_threshold) { - int p = partition(list, lo, hi, medianof3(list, lo, lo + ((hi - lo) / 2) + 1, hi - 1)); - introSortLoop(list, p, hi); - hi = p; - } - insertionsort(list, lo, hi); - } + /* + * Quicksort algorithm modified for Introsort + */ + private static > void introSortLoop(List list, int lo, int hi) { + while (hi - lo > size_threshold) { + int p = partition(list, lo, hi, medianof3(list, lo, lo + ((hi - lo) / 2) + 1, hi - 1)); + introSortLoop(list, p, hi); + hi = p; + } + insertionsort(list, lo, hi); + } - private static > int partition(List list, int lo, int hi, T x) { - int i = lo, j = hi; - while (true) { - while (list.get(i).compareTo(x) < 0) - i++; - j = j - 1; - while (x.compareTo(list.get(j)) < 0) - j = j - 1; - if (!(i < j)) - return i; - exchange(list, i, j); - i++; - } - } + private static > int partition(List list, int lo, int hi, T x) { + int i = lo, j = hi; + while (true) { + while (list.get(i).compareTo(x) < 0) + i++; + j = j - 1; + while (x.compareTo(list.get(j)) < 0) + j = j - 1; + if (!(i < j)) + return i; + exchange(list, i, j); + i++; + } + } - private static > T medianof3(List list, int lo, int mid, int hi) { + private static > T medianof3(List list, int lo, int mid, int hi) { - if (list.get(mid).compareTo(list.get(lo)) < 0) { - if (list.get(hi).compareTo(list.get(mid)) < 0) - return list.get(mid); - else { - if (list.get(hi).compareTo(list.get(lo)) < 0) - return list.get(hi); - else - return list.get(lo); - } - } else { - if (list.get(hi).compareTo(list.get(mid)) < 0) { - if (list.get(hi).compareTo(list.get(lo)) < 0) - return list.get(lo); - else - return list.get(hi); - } else - return list.get(mid); - } - } + if (list.get(mid).compareTo(list.get(lo)) < 0) { + if (list.get(hi).compareTo(list.get(mid)) < 0) + return list.get(mid); + else { + if (list.get(hi).compareTo(list.get(lo)) < 0) + return list.get(hi); + else + return list.get(lo); + } + } else { + if (list.get(hi).compareTo(list.get(mid)) < 0) { + if (list.get(hi).compareTo(list.get(lo)) < 0) + return list.get(lo); + else + return list.get(hi); + } else + return list.get(mid); + } + } - /* - * Insertion sort algorithm - */ - private static > void insertionsort(List list, int lo, int hi) { - int i, j; - T t; - for (i = lo; i < hi; i++) { - j = i; - t = list.get(i); - while (j != lo && t.compareTo(list.get(j - 1)) < 0) { - list.set(j, list.get(j - 1)); - j--; - } - list.set(j, t); - } - } + /* + * Insertion sort algorithm + */ + private static > void insertionsort(List list, int lo, int hi) { + int i, j; + T t; + for (i = lo; i < hi; i++) { + j = i; + t = list.get(i); + while (j != lo && t.compareTo(list.get(j - 1)) < 0) { + list.set(j, list.get(j - 1)); + j--; + } + list.set(j, t); + } + } - /* - * Common methods for all algorithms - */ - private static > void exchange(List list, int i, int j) { - T t = list.get(i); - list.set(i, list.get(j)); - list.set(j, t); - } -} \ No newline at end of file + /* + * Common methods for all algorithms + */ + private static > void exchange(List list, int i, int j) { + T t = list.get(i); + list.set(i, list.get(j)); + list.set(j, t); + } +} diff --git a/src/lt/ekgame/beatmap_analyzer/utils/ScoreVersion.java b/src/lt/ekgame/beatmap_analyzer/utils/ScoreVersion.java index 377ab43c..42b0b16c 100644 --- a/src/lt/ekgame/beatmap_analyzer/utils/ScoreVersion.java +++ b/src/lt/ekgame/beatmap_analyzer/utils/ScoreVersion.java @@ -1,5 +1,5 @@ package lt.ekgame.beatmap_analyzer.utils; public enum ScoreVersion { - V1, V2 + V1, V2 } diff --git a/src/lt/ekgame/beatmap_analyzer/utils/Vec2.java b/src/lt/ekgame/beatmap_analyzer/utils/Vec2.java index 521049f0..2ffe941a 100644 --- a/src/lt/ekgame/beatmap_analyzer/utils/Vec2.java +++ b/src/lt/ekgame/beatmap_analyzer/utils/Vec2.java @@ -2,50 +2,50 @@ public class Vec2 { - double positionX, positionY; + double positionX, positionY; - public Vec2(double positionX, double positionY) { - this.positionX = positionX; - this.positionY = positionY; - } + public Vec2(double positionX, double positionY) { + this.positionX = positionX; + this.positionY = positionY; + } - public Vec2 add(Vec2 position) { - return new Vec2(positionX + position.getX(), positionY + position.getY()); - } + public Vec2 add(Vec2 position) { + return new Vec2(positionX + position.getX(), positionY + position.getY()); + } - public Vec2 subract(Vec2 position) { - return new Vec2(positionX - position.getX(), positionY - position.getY()); - } + public Vec2 subract(Vec2 position) { + return new Vec2(positionX - position.getX(), positionY - position.getY()); + } - public Vec2 scale(double scale) { - return new Vec2(positionX * scale, positionY * scale); - } + public Vec2 scale(double scale) { + return new Vec2(positionX * scale, positionY * scale); + } - public double length() { - return Math.sqrt(positionX * positionX + positionY * positionY); - } + public double length() { + return Math.sqrt(positionX * positionX + positionY * positionY); + } - public double distance(Vec2 position) { - return position.subract(this).length(); - } + public double distance(Vec2 position) { + return position.subract(this).length(); + } - public double getX() { - return positionX; - } + public double getX() { + return positionX; + } - public void setX(double x) { - this.positionX = x; - } + public void setX(double x) { + this.positionX = x; + } - public double getY() { - return positionY; - } + public double getY() { + return positionY; + } - public void setY(double y) { - this.positionY = y; - } + public void setY(double y) { + this.positionY = y; + } - public Vec2 clone() { - return new Vec2(positionX, positionY); - } + public Vec2 clone() { + return new Vec2(positionX, positionY); + } } diff --git a/src/net/margaritov/preference/colorpicker/AlphaPatternDrawable.java b/src/net/margaritov/preference/colorpicker/AlphaPatternDrawable.java index 6c88c443..befd790a 100644 --- a/src/net/margaritov/preference/colorpicker/AlphaPatternDrawable.java +++ b/src/net/margaritov/preference/colorpicker/AlphaPatternDrawable.java @@ -5,7 +5,7 @@ * 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 + * 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, @@ -34,97 +34,97 @@ */ public class AlphaPatternDrawable extends Drawable { - private int mRectangleSize = 10; + private int mRectangleSize = 10; - private Paint mPaint = new Paint(); - private Paint mPaintWhite = new Paint(); - private Paint mPaintGray = new Paint(); + private Paint mPaint = new Paint(); + private Paint mPaintWhite = new Paint(); + private Paint mPaintGray = new Paint(); - private int numRectanglesHorizontal; - private int numRectanglesVertical; + private int numRectanglesHorizontal; + private int numRectanglesVertical; - /** - * Bitmap in which the pattern will be cahched. - */ - private Bitmap mBitmap; + /** + * Bitmap in which the pattern will be cahched. + */ + private Bitmap mBitmap; - public AlphaPatternDrawable(int rectangleSize) { - mRectangleSize = rectangleSize; - mPaintWhite.setColor(0xffffffff); - mPaintGray.setColor(0xffcbcbcb); - } + public AlphaPatternDrawable(int rectangleSize) { + mRectangleSize = rectangleSize; + mPaintWhite.setColor(0xffffffff); + mPaintGray.setColor(0xffcbcbcb); + } - @Override - public void draw(Canvas canvas) { - canvas.drawBitmap(mBitmap, null, getBounds(), mPaint); - } + @Override + public void draw(Canvas canvas) { + canvas.drawBitmap(mBitmap, null, getBounds(), mPaint); + } - @Override - public int getOpacity() { - return PixelFormat.UNKNOWN; - } + @Override + public int getOpacity() { + return PixelFormat.UNKNOWN; + } - @Override - public void setAlpha(int alpha) { - throw new UnsupportedOperationException("Alpha is not supported by this drawwable."); - } + @Override + public void setAlpha(int alpha) { + throw new UnsupportedOperationException("Alpha is not supported by this drawwable."); + } - @Override - public void setColorFilter(ColorFilter cf) { - throw new UnsupportedOperationException("ColorFilter is not supported by this drawwable."); - } + @Override + public void setColorFilter(ColorFilter cf) { + throw new UnsupportedOperationException("ColorFilter is not supported by this drawwable."); + } - @Override - protected void onBoundsChange(Rect bounds) { - super.onBoundsChange(bounds); + @Override + protected void onBoundsChange(Rect bounds) { + super.onBoundsChange(bounds); - int height = bounds.height(); - int width = bounds.width(); + int height = bounds.height(); + int width = bounds.width(); - numRectanglesHorizontal = (int) Math.ceil((width / mRectangleSize)); - numRectanglesVertical = (int) Math.ceil(height / mRectangleSize); + numRectanglesHorizontal = (int) Math.ceil((width / mRectangleSize)); + numRectanglesVertical = (int) Math.ceil(height / mRectangleSize); - generatePatternBitmap(); + generatePatternBitmap(); - } + } - /** - * This will generate a bitmap with the pattern - * as big as the rectangle we were allow to draw on. - * We do this to chache the bitmap so we don't need to - * recreate it each time draw() is called since it - * takes a few milliseconds. - */ - private void generatePatternBitmap() { + /** + * This will generate a bitmap with the pattern + * as big as the rectangle we were allow to draw on. + * We do this to chache the bitmap so we don't need to + * recreate it each time draw() is called since it + * takes a few milliseconds. + */ + private void generatePatternBitmap() { - if (getBounds().width() <= 0 || getBounds().height() <= 0) { - return; - } + if (getBounds().width() <= 0 || getBounds().height() <= 0) { + return; + } - mBitmap = Bitmap.createBitmap(getBounds().width(), getBounds().height(), Config.ARGB_8888); - Canvas canvas = new Canvas(mBitmap); + mBitmap = Bitmap.createBitmap(getBounds().width(), getBounds().height(), Config.ARGB_8888); + Canvas canvas = new Canvas(mBitmap); - Rect r = new Rect(); - boolean verticalStartWhite = true; - for (int i = 0; i <= numRectanglesVertical; i++) { + Rect r = new Rect(); + boolean verticalStartWhite = true; + for (int i = 0; i <= numRectanglesVertical; i++) { - boolean isWhite = verticalStartWhite; - for (int j = 0; j <= numRectanglesHorizontal; j++) { + boolean isWhite = verticalStartWhite; + for (int j = 0; j <= numRectanglesHorizontal; j++) { - r.top = i * mRectangleSize; - r.left = j * mRectangleSize; - r.bottom = r.top + mRectangleSize; - r.right = r.left + mRectangleSize; + r.top = i * mRectangleSize; + r.left = j * mRectangleSize; + r.bottom = r.top + mRectangleSize; + r.right = r.left + mRectangleSize; - canvas.drawRect(r, isWhite ? mPaintWhite : mPaintGray); + canvas.drawRect(r, isWhite ? mPaintWhite : mPaintGray); - isWhite = !isWhite; - } + isWhite = !isWhite; + } - verticalStartWhite = !verticalStartWhite; + verticalStartWhite = !verticalStartWhite; - } + } - } + } -} \ No newline at end of file +} diff --git a/src/net/margaritov/preference/colorpicker/ColorPickerDialog.java b/src/net/margaritov/preference/colorpicker/ColorPickerDialog.java index 0b7abd45..b46921d2 100644 --- a/src/net/margaritov/preference/colorpicker/ColorPickerDialog.java +++ b/src/net/margaritov/preference/colorpicker/ColorPickerDialog.java @@ -5,7 +5,7 @@ * 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 + * 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, @@ -40,212 +40,212 @@ import ru.nsu.ccfit.zuev.osuplus.R; public class ColorPickerDialog - extends - AppCompatDialog - implements - ColorPickerView.OnColorChangedListener, - View.OnClickListener, ViewTreeObserver.OnGlobalLayoutListener { - - private ColorPickerView mColorPicker; - - private ColorPickerPanelView mOldColor; - private ColorPickerPanelView mNewColor; - - private EditText mHexVal; - private boolean mHexValueEnabled = false; - private ColorStateList mHexDefaultTextColor; - - private OnColorChangedListener mListener; - private int mOrientation; - private View mLayout; - - private String mTitle; - - @Override - public void onGlobalLayout() { - if (getContext().getResources().getConfiguration().orientation != mOrientation) { - final int oldcolor = mOldColor.getColor(); - final int newcolor = mNewColor.getColor(); - mLayout.getViewTreeObserver().removeGlobalOnLayoutListener(this); - setUp(oldcolor); - mNewColor.setColor(newcolor); - mColorPicker.setColor(newcolor); - } - } - - public interface OnColorChangedListener { - public void onColorChanged(int color); - } - - public ColorPickerDialog(Context context, int initialColor, String title) { - super(context); - - mTitle = title; - init(initialColor); - } - - private void init(int color) { - // To fight color banding. - getWindow().setFormat(PixelFormat.RGBA_8888); - - setUp(color); - - } - - private void setUp(int color) { - - LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); - - mLayout = inflater.inflate(R.layout.dialog_color_picker, null); - mLayout.getViewTreeObserver().addOnGlobalLayoutListener(this); - - mOrientation = getContext().getResources().getConfiguration().orientation; - setContentView(mLayout); - - setTitle(mTitle); - - mColorPicker = (ColorPickerView) mLayout.findViewById(R.id.color_picker_view); - mOldColor = (ColorPickerPanelView) mLayout.findViewById(R.id.old_color_panel); - mNewColor = (ColorPickerPanelView) mLayout.findViewById(R.id.new_color_panel); - - mHexVal = (EditText) mLayout.findViewById(R.id.hex_val); - mHexVal.setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS); - mHexDefaultTextColor = mHexVal.getTextColors(); - - mHexVal.setOnEditorActionListener(new TextView.OnEditorActionListener() { - - @Override - public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { - if (actionId == EditorInfo.IME_ACTION_DONE) { - InputMethodManager imm = (InputMethodManager) v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE); - imm.hideSoftInputFromWindow(v.getWindowToken(), 0); - String s = mHexVal.getText().toString(); - if (s.length() > 5 || s.length() < 10) { - try { - int c = ColorPickerPreference.convertToColorInt(s.toString()); - mColorPicker.setColor(c, true); - mHexVal.setTextColor(mHexDefaultTextColor); - } catch (IllegalArgumentException e) { - mHexVal.setTextColor(Color.RED); - } - } else { - mHexVal.setTextColor(Color.RED); - } - return true; - } - return false; - } - }); - - ((LinearLayout) mOldColor.getParent()).setPadding( - Math.round(mColorPicker.getDrawingOffset()), - 0, - Math.round(mColorPicker.getDrawingOffset()), - 0 - ); - - mOldColor.setOnClickListener(this); - mNewColor.setOnClickListener(this); - mColorPicker.setOnColorChangedListener(this); - mOldColor.setColor(color); - mColorPicker.setColor(color, true); - - } - - @Override - public void onColorChanged(int color) { - - mNewColor.setColor(color); - - if (mHexValueEnabled) - updateHexValue(color); - - /* - if (mListener != null) { - mListener.onColorChanged(color); - } - */ - - } - - public void setHexValueEnabled(boolean enable) { - mHexValueEnabled = enable; - if (enable) { - mHexVal.setVisibility(View.VISIBLE); - updateHexLengthFilter(); - updateHexValue(getColor()); - } else - mHexVal.setVisibility(View.GONE); - } - - public boolean getHexValueEnabled() { - return mHexValueEnabled; - } - - private void updateHexLengthFilter() { - if (getAlphaSliderVisible()) - mHexVal.setFilters(new InputFilter[]{new InputFilter.LengthFilter(9)}); - else - mHexVal.setFilters(new InputFilter[]{new InputFilter.LengthFilter(7)}); - } - - private void updateHexValue(int color) { - if (getAlphaSliderVisible()) { - mHexVal.setText(ColorPickerPreference.convertToARGB(color).toUpperCase(Locale.getDefault())); - } else { - mHexVal.setText(ColorPickerPreference.convertToRGB(color).toUpperCase(Locale.getDefault())); - } - mHexVal.setTextColor(mHexDefaultTextColor); - } - - public void setAlphaSliderVisible(boolean visible) { - mColorPicker.setAlphaSliderVisible(visible); - if (mHexValueEnabled) { - updateHexLengthFilter(); - updateHexValue(getColor()); - } - } - - public boolean getAlphaSliderVisible() { - return mColorPicker.getAlphaSliderVisible(); - } - - /** - * Set a OnColorChangedListener to get notified when the color - * selected by the user has changed. - * - * @param listener - */ - public void setOnColorChangedListener(OnColorChangedListener listener) { - mListener = listener; - } - - public int getColor() { - return mColorPicker.getColor(); - } - - @Override - public void onClick(View v) { - if (v.getId() == R.id.new_color_panel) { - if (mListener != null) { - mListener.onColorChanged(mNewColor.getColor()); - } - } - dismiss(); - } - - @Override - public Bundle onSaveInstanceState() { - Bundle state = super.onSaveInstanceState(); - state.putInt("old_color", mOldColor.getColor()); - state.putInt("new_color", mNewColor.getColor()); - return state; - } - - @Override - public void onRestoreInstanceState(Bundle savedInstanceState) { - super.onRestoreInstanceState(savedInstanceState); - mOldColor.setColor(savedInstanceState.getInt("old_color")); - mColorPicker.setColor(savedInstanceState.getInt("new_color"), true); - } -} \ No newline at end of file + extends + AppCompatDialog + implements + ColorPickerView.OnColorChangedListener, + View.OnClickListener, ViewTreeObserver.OnGlobalLayoutListener { + + private ColorPickerView mColorPicker; + + private ColorPickerPanelView mOldColor; + private ColorPickerPanelView mNewColor; + + private EditText mHexVal; + private boolean mHexValueEnabled = false; + private ColorStateList mHexDefaultTextColor; + + private OnColorChangedListener mListener; + private int mOrientation; + private View mLayout; + + private String mTitle; + + @Override + public void onGlobalLayout() { + if (getContext().getResources().getConfiguration().orientation != mOrientation) { + final int oldcolor = mOldColor.getColor(); + final int newcolor = mNewColor.getColor(); + mLayout.getViewTreeObserver().removeGlobalOnLayoutListener(this); + setUp(oldcolor); + mNewColor.setColor(newcolor); + mColorPicker.setColor(newcolor); + } + } + + public interface OnColorChangedListener { + public void onColorChanged(int color); + } + + public ColorPickerDialog(Context context, int initialColor, String title) { + super(context); + + mTitle = title; + init(initialColor); + } + + private void init(int color) { + // To fight color banding. + getWindow().setFormat(PixelFormat.RGBA_8888); + + setUp(color); + + } + + private void setUp(int color) { + + LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); + + mLayout = inflater.inflate(R.layout.dialog_color_picker, null); + mLayout.getViewTreeObserver().addOnGlobalLayoutListener(this); + + mOrientation = getContext().getResources().getConfiguration().orientation; + setContentView(mLayout); + + setTitle(mTitle); + + mColorPicker = (ColorPickerView) mLayout.findViewById(R.id.color_picker_view); + mOldColor = (ColorPickerPanelView) mLayout.findViewById(R.id.old_color_panel); + mNewColor = (ColorPickerPanelView) mLayout.findViewById(R.id.new_color_panel); + + mHexVal = (EditText) mLayout.findViewById(R.id.hex_val); + mHexVal.setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS); + mHexDefaultTextColor = mHexVal.getTextColors(); + + mHexVal.setOnEditorActionListener(new TextView.OnEditorActionListener() { + + @Override + public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { + if (actionId == EditorInfo.IME_ACTION_DONE) { + InputMethodManager imm = (InputMethodManager) v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE); + imm.hideSoftInputFromWindow(v.getWindowToken(), 0); + String s = mHexVal.getText().toString(); + if (s.length() > 5 || s.length() < 10) { + try { + int c = ColorPickerPreference.convertToColorInt(s.toString()); + mColorPicker.setColor(c, true); + mHexVal.setTextColor(mHexDefaultTextColor); + } catch (IllegalArgumentException e) { + mHexVal.setTextColor(Color.RED); + } + } else { + mHexVal.setTextColor(Color.RED); + } + return true; + } + return false; + } + }); + + ((LinearLayout) mOldColor.getParent()).setPadding( + Math.round(mColorPicker.getDrawingOffset()), + 0, + Math.round(mColorPicker.getDrawingOffset()), + 0 + ); + + mOldColor.setOnClickListener(this); + mNewColor.setOnClickListener(this); + mColorPicker.setOnColorChangedListener(this); + mOldColor.setColor(color); + mColorPicker.setColor(color, true); + + } + + @Override + public void onColorChanged(int color) { + + mNewColor.setColor(color); + + if (mHexValueEnabled) + updateHexValue(color); + + /* + if (mListener != null) { + mListener.onColorChanged(color); + } + */ + + } + + public void setHexValueEnabled(boolean enable) { + mHexValueEnabled = enable; + if (enable) { + mHexVal.setVisibility(View.VISIBLE); + updateHexLengthFilter(); + updateHexValue(getColor()); + } else + mHexVal.setVisibility(View.GONE); + } + + public boolean getHexValueEnabled() { + return mHexValueEnabled; + } + + private void updateHexLengthFilter() { + if (getAlphaSliderVisible()) + mHexVal.setFilters(new InputFilter[]{new InputFilter.LengthFilter(9)}); + else + mHexVal.setFilters(new InputFilter[]{new InputFilter.LengthFilter(7)}); + } + + private void updateHexValue(int color) { + if (getAlphaSliderVisible()) { + mHexVal.setText(ColorPickerPreference.convertToARGB(color).toUpperCase(Locale.getDefault())); + } else { + mHexVal.setText(ColorPickerPreference.convertToRGB(color).toUpperCase(Locale.getDefault())); + } + mHexVal.setTextColor(mHexDefaultTextColor); + } + + public void setAlphaSliderVisible(boolean visible) { + mColorPicker.setAlphaSliderVisible(visible); + if (mHexValueEnabled) { + updateHexLengthFilter(); + updateHexValue(getColor()); + } + } + + public boolean getAlphaSliderVisible() { + return mColorPicker.getAlphaSliderVisible(); + } + + /** + * Set a OnColorChangedListener to get notified when the color + * selected by the user has changed. + * + * @param listener + */ + public void setOnColorChangedListener(OnColorChangedListener listener) { + mListener = listener; + } + + public int getColor() { + return mColorPicker.getColor(); + } + + @Override + public void onClick(View v) { + if (v.getId() == R.id.new_color_panel) { + if (mListener != null) { + mListener.onColorChanged(mNewColor.getColor()); + } + } + dismiss(); + } + + @Override + public Bundle onSaveInstanceState() { + Bundle state = super.onSaveInstanceState(); + state.putInt("old_color", mOldColor.getColor()); + state.putInt("new_color", mNewColor.getColor()); + return state; + } + + @Override + public void onRestoreInstanceState(Bundle savedInstanceState) { + super.onRestoreInstanceState(savedInstanceState); + mOldColor.setColor(savedInstanceState.getInt("old_color")); + mColorPicker.setColor(savedInstanceState.getInt("new_color"), true); + } +} diff --git a/src/net/margaritov/preference/colorpicker/ColorPickerPanelView.java b/src/net/margaritov/preference/colorpicker/ColorPickerPanelView.java index 7740619d..c2e5c5c7 100644 --- a/src/net/margaritov/preference/colorpicker/ColorPickerPanelView.java +++ b/src/net/margaritov/preference/colorpicker/ColorPickerPanelView.java @@ -5,7 +5,7 @@ * 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 + * 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, @@ -32,143 +32,143 @@ */ public class ColorPickerPanelView extends View { - /** - * The width in pixels of the border - * surrounding the color panel. - */ - private final static float BORDER_WIDTH_PX = 1; + /** + * The width in pixels of the border + * surrounding the color panel. + */ + private final static float BORDER_WIDTH_PX = 1; - private float mDensity = 1f; + private float mDensity = 1f; - private int mBorderColor = 0xff6E6E6E; - private int mColor = 0xff000000; + private int mBorderColor = 0xff6E6E6E; + private int mColor = 0xff000000; - private Paint mBorderPaint; - private Paint mColorPaint; + private Paint mBorderPaint; + private Paint mColorPaint; - private RectF mDrawingRect; - private RectF mColorRect; + private RectF mDrawingRect; + private RectF mColorRect; - private AlphaPatternDrawable mAlphaPattern; + private AlphaPatternDrawable mAlphaPattern; - public ColorPickerPanelView(Context context) { - this(context, null); - } + public ColorPickerPanelView(Context context) { + this(context, null); + } - public ColorPickerPanelView(Context context, AttributeSet attrs) { - this(context, attrs, 0); - } + public ColorPickerPanelView(Context context, AttributeSet attrs) { + this(context, attrs, 0); + } - public ColorPickerPanelView(Context context, AttributeSet attrs, int defStyle) { - super(context, attrs, defStyle); - init(); - } + public ColorPickerPanelView(Context context, AttributeSet attrs, int defStyle) { + super(context, attrs, defStyle); + init(); + } - private void init() { - mBorderPaint = new Paint(); - mColorPaint = new Paint(); - mDensity = getContext().getResources().getDisplayMetrics().density; - } + private void init() { + mBorderPaint = new Paint(); + mColorPaint = new Paint(); + mDensity = getContext().getResources().getDisplayMetrics().density; + } - @Override - protected void onDraw(Canvas canvas) { + @Override + protected void onDraw(Canvas canvas) { - final RectF rect = mColorRect; + final RectF rect = mColorRect; - if (BORDER_WIDTH_PX > 0) { - mBorderPaint.setColor(mBorderColor); - canvas.drawRect(mDrawingRect, mBorderPaint); - } + if (BORDER_WIDTH_PX > 0) { + mBorderPaint.setColor(mBorderColor); + canvas.drawRect(mDrawingRect, mBorderPaint); + } - if (mAlphaPattern != null) { - mAlphaPattern.draw(canvas); - } + if (mAlphaPattern != null) { + mAlphaPattern.draw(canvas); + } - mColorPaint.setColor(mColor); + mColorPaint.setColor(mColor); - canvas.drawRect(rect, mColorPaint); - } + canvas.drawRect(rect, mColorPaint); + } - @Override - protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { + @Override + protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { - int width = MeasureSpec.getSize(widthMeasureSpec); - int height = MeasureSpec.getSize(heightMeasureSpec); + int width = MeasureSpec.getSize(widthMeasureSpec); + int height = MeasureSpec.getSize(heightMeasureSpec); - setMeasuredDimension(width, height); - } + setMeasuredDimension(width, height); + } - @Override - protected void onSizeChanged(int w, int h, int oldw, int oldh) { - super.onSizeChanged(w, h, oldw, oldh); + @Override + protected void onSizeChanged(int w, int h, int oldw, int oldh) { + super.onSizeChanged(w, h, oldw, oldh); - mDrawingRect = new RectF(); - mDrawingRect.left = getPaddingLeft(); - mDrawingRect.right = w - getPaddingRight(); - mDrawingRect.top = getPaddingTop(); - mDrawingRect.bottom = h - getPaddingBottom(); + mDrawingRect = new RectF(); + mDrawingRect.left = getPaddingLeft(); + mDrawingRect.right = w - getPaddingRight(); + mDrawingRect.top = getPaddingTop(); + mDrawingRect.bottom = h - getPaddingBottom(); - setUpColorRect(); + setUpColorRect(); - } + } - private void setUpColorRect() { - final RectF dRect = mDrawingRect; + private void setUpColorRect() { + final RectF dRect = mDrawingRect; - float left = dRect.left + BORDER_WIDTH_PX; - float top = dRect.top + BORDER_WIDTH_PX; - float bottom = dRect.bottom - BORDER_WIDTH_PX; - float right = dRect.right - BORDER_WIDTH_PX; + float left = dRect.left + BORDER_WIDTH_PX; + float top = dRect.top + BORDER_WIDTH_PX; + float bottom = dRect.bottom - BORDER_WIDTH_PX; + float right = dRect.right - BORDER_WIDTH_PX; - mColorRect = new RectF(left, top, right, bottom); + mColorRect = new RectF(left, top, right, bottom); - mAlphaPattern = new AlphaPatternDrawable((int) (5 * mDensity)); + mAlphaPattern = new AlphaPatternDrawable((int) (5 * mDensity)); - mAlphaPattern.setBounds( - Math.round(mColorRect.left), - Math.round(mColorRect.top), - Math.round(mColorRect.right), - Math.round(mColorRect.bottom) - ); + mAlphaPattern.setBounds( + Math.round(mColorRect.left), + Math.round(mColorRect.top), + Math.round(mColorRect.right), + Math.round(mColorRect.bottom) + ); - } + } - /** - * Set the color that should be shown by this view. - * - * @param color - */ - public void setColor(int color) { - mColor = color; - invalidate(); - } + /** + * Set the color that should be shown by this view. + * + * @param color + */ + public void setColor(int color) { + mColor = color; + invalidate(); + } - /** - * Get the color currently show by this view. - * - * @return - */ - public int getColor() { - return mColor; - } - - /** - * Set the color of the border surrounding the panel. - * - * @param color - */ - public void setBorderColor(int color) { - mBorderColor = color; - invalidate(); - } - - /** - * Get the color of the border surrounding the panel. - */ - public int getBorderColor() { - return mBorderColor; - } + /** + * Get the color currently show by this view. + * + * @return + */ + public int getColor() { + return mColor; + } + + /** + * Set the color of the border surrounding the panel. + * + * @param color + */ + public void setBorderColor(int color) { + mBorderColor = color; + invalidate(); + } + + /** + * Get the color of the border surrounding the panel. + */ + public int getBorderColor() { + return mBorderColor; + } -} \ No newline at end of file +} diff --git a/src/net/margaritov/preference/colorpicker/ColorPickerPreference.java b/src/net/margaritov/preference/colorpicker/ColorPickerPreference.java index e37fa33a..652dd94a 100644 --- a/src/net/margaritov/preference/colorpicker/ColorPickerPreference.java +++ b/src/net/margaritov/preference/colorpicker/ColorPickerPreference.java @@ -5,7 +5,7 @@ * 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 + * 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, @@ -38,298 +38,298 @@ * @author Sergey Margaritov */ public class ColorPickerPreference - extends - Preference - implements - Preference.OnPreferenceClickListener, - ColorPickerDialog.OnColorChangedListener { - - View mView; - ColorPickerDialog mDialog; - private int mValue = Color.BLACK; - private float mDensity = 0; - private boolean mAlphaSliderEnabled = false; - private boolean mHexValueEnabled = false; - - public ColorPickerPreference(Context context) { - super(context); - init(context, null); - } - - public ColorPickerPreference(Context context, AttributeSet attrs) { - super(context, attrs); - init(context, attrs); - } - - public ColorPickerPreference(Context context, AttributeSet attrs, int defStyle) { - super(context, attrs, defStyle); - init(context, attrs); - } - - /**Method edited by - * @author Anna Berkovitch - * added functionality to accept hex string as defaultValue - * and to properly persist resources reference string, such as @color/someColor - * previously persisted 0*/ - @Override - protected Object onGetDefaultValue(TypedArray a, int index) { - int colorInt; - String mHexDefaultValue = a.getString(index); - if (mHexDefaultValue != null && mHexDefaultValue.startsWith("#")) { - colorInt = convertToColorInt(mHexDefaultValue); - return colorInt; - - } else { - return a.getColor(index, Color.BLACK); - } - } - - @Override - protected void onSetInitialValue(boolean restoreValue, Object defaultValue) { - onColorChanged(restoreValue ? getPersistedInt(mValue) : (Integer) defaultValue); - } - - private void init(Context context, AttributeSet attrs) { - mDensity = getContext().getResources().getDisplayMetrics().density; - setOnPreferenceClickListener(this); - if (attrs != null) { - mAlphaSliderEnabled = attrs.getAttributeBooleanValue(null, "alphaSlider", false); - mHexValueEnabled = attrs.getAttributeBooleanValue(null, "hexValue", false); - } - } - - @Override - public void onBindViewHolder(PreferenceViewHolder holder) { - super.onBindViewHolder(holder); - - mView = holder.itemView; - setPreviewColor(); - } - - private void setPreviewColor() { - if (mView == null) return; - ImageView iView = new ImageView(getContext()); - LinearLayout widgetFrameView = ((LinearLayout) mView.findViewById(android.R.id.widget_frame)); - if (widgetFrameView == null) return; - widgetFrameView.setVisibility(View.VISIBLE); - widgetFrameView.setPadding( - widgetFrameView.getPaddingLeft(), - widgetFrameView.getPaddingTop(), - (int) (mDensity * 8), - widgetFrameView.getPaddingBottom() - ); - // remove already create preview image - int count = widgetFrameView.getChildCount(); - if (count > 0) { - widgetFrameView.removeViews(0, count); - } - widgetFrameView.addView(iView); - widgetFrameView.setMinimumWidth(0); - iView.setBackgroundDrawable(new AlphaPatternDrawable((int) (5 * mDensity))); - iView.setImageBitmap(getPreviewBitmap()); - } - - private Bitmap getPreviewBitmap() { - int d = (int) (mDensity * 31); //30dip - int color = mValue; - Bitmap bm = Bitmap.createBitmap(d, d, Config.ARGB_8888); - int w = bm.getWidth(); - int h = bm.getHeight(); - int c = color; - for (int i = 0; i < w; i++) { - for (int j = i; j < h; j++) { - c = (i <= 1 || j <= 1 || i >= w - 2 || j >= h - 2) ? Color.GRAY : color; - bm.setPixel(i, j, c); - if (i != j) { - bm.setPixel(j, i, c); - } - } - } - - return bm; - } - - @Override - public void onColorChanged(int color) { - if (isPersistent()) { - persistInt(color); - } - mValue = color; - setPreviewColor(); - try { - getOnPreferenceChangeListener().onPreferenceChange(this, color); - } catch (NullPointerException e) { - - } - } - - public boolean onPreferenceClick(Preference preference) { - showDialog(null); - return false; - } - - protected void showDialog(Bundle state) { - mDialog = new ColorPickerDialog(getContext(), mValue, getTitle().toString()); - mDialog.setOnColorChangedListener(this); - if (mAlphaSliderEnabled) { - mDialog.setAlphaSliderVisible(true); - } - if (mHexValueEnabled) { - mDialog.setHexValueEnabled(true); - } - if (state != null) { - mDialog.onRestoreInstanceState(state); - } - mDialog.show(); - } - - /** - * Toggle Alpha Slider visibility (by default it's disabled) - * - * @param enable - */ - public void setAlphaSliderEnabled(boolean enable) { - mAlphaSliderEnabled = enable; - } - - /** - * Toggle Hex Value visibility (by default it's disabled) - * - * @param enable - */ - public void setHexValueEnabled(boolean enable) { - mHexValueEnabled = enable; - } - - /** - * For custom purposes. Not used by ColorPickerPreferrence - * - * @param color - * @author Unknown - */ - public static String convertToARGB(int color) { - String alpha = Integer.toHexString(Color.alpha(color)); - String red = Integer.toHexString(Color.red(color)); - String green = Integer.toHexString(Color.green(color)); - String blue = Integer.toHexString(Color.blue(color)); - - if (alpha.length() == 1) { - alpha = "0" + alpha; - } - - if (red.length() == 1) { - red = "0" + red; - } - - if (green.length() == 1) { - green = "0" + green; - } - - if (blue.length() == 1) { - blue = "0" + blue; - } - - return "#" + alpha + red + green + blue; - } - - /** - * Method currently used by onGetDefaultValue method to - * convert hex string provided in android:defaultValue to color integer. - * - * @param color - * @return A string representing the hex value of color, - * without the alpha value - * @author Charles Rosaaen - */ - public static String convertToRGB(int color) { - String red = Integer.toHexString(Color.red(color)); - String green = Integer.toHexString(Color.green(color)); - String blue = Integer.toHexString(Color.blue(color)); - - if (red.length() == 1) { - red = "0" + red; - } - - if (green.length() == 1) { - green = "0" + green; - } - - if (blue.length() == 1) { - blue = "0" + blue; - } - - return "#" + red + green + blue; - } - - /** - * For custom purposes. Not used by ColorPickerPreferrence - * - * @param argb - * @throws NumberFormatException - * @author Unknown - */ - public static int convertToColorInt(String argb) throws IllegalArgumentException { - - if (!argb.startsWith("#")) { - argb = "#" + argb; - } - - return Color.parseColor(argb); - } - - @Override - protected Parcelable onSaveInstanceState() { - final Parcelable superState = super.onSaveInstanceState(); - if (mDialog == null || !mDialog.isShowing()) { - return superState; - } - - final SavedState myState = new SavedState(superState); - myState.dialogBundle = mDialog.onSaveInstanceState(); - return myState; - } - - @Override - protected void onRestoreInstanceState(Parcelable state) { - if (state == null || !(state instanceof SavedState)) { - // Didn't save state for us in onSaveInstanceState - super.onRestoreInstanceState(state); - return; - } - - SavedState myState = (SavedState) state; - super.onRestoreInstanceState(myState.getSuperState()); - showDialog(myState.dialogBundle); - } - - private static class SavedState extends BaseSavedState { - Bundle dialogBundle; - - public SavedState(Parcel source) { - super(source); - dialogBundle = source.readBundle(); - } - - @Override - public void writeToParcel(Parcel dest, int flags) { - super.writeToParcel(dest, flags); - dest.writeBundle(dialogBundle); - } - - public SavedState(Parcelable superState) { - super(superState); - } - - @SuppressWarnings("unused") - public static final Parcelable.Creator CREATOR = - new Parcelable.Creator() { - public SavedState createFromParcel(Parcel in) { - return new SavedState(in); - } - - public SavedState[] newArray(int size) { - return new SavedState[size]; - } - }; - } -} \ No newline at end of file + extends + Preference + implements + Preference.OnPreferenceClickListener, + ColorPickerDialog.OnColorChangedListener { + + View mView; + ColorPickerDialog mDialog; + private int mValue = Color.BLACK; + private float mDensity = 0; + private boolean mAlphaSliderEnabled = false; + private boolean mHexValueEnabled = false; + + public ColorPickerPreference(Context context) { + super(context); + init(context, null); + } + + public ColorPickerPreference(Context context, AttributeSet attrs) { + super(context, attrs); + init(context, attrs); + } + + public ColorPickerPreference(Context context, AttributeSet attrs, int defStyle) { + super(context, attrs, defStyle); + init(context, attrs); + } + + /**Method edited by + * @author Anna Berkovitch + * added functionality to accept hex string as defaultValue + * and to properly persist resources reference string, such as @color/someColor + * previously persisted 0*/ + @Override + protected Object onGetDefaultValue(TypedArray a, int index) { + int colorInt; + String mHexDefaultValue = a.getString(index); + if (mHexDefaultValue != null && mHexDefaultValue.startsWith("#")) { + colorInt = convertToColorInt(mHexDefaultValue); + return colorInt; + + } else { + return a.getColor(index, Color.BLACK); + } + } + + @Override + protected void onSetInitialValue(boolean restoreValue, Object defaultValue) { + onColorChanged(restoreValue ? getPersistedInt(mValue) : (Integer) defaultValue); + } + + private void init(Context context, AttributeSet attrs) { + mDensity = getContext().getResources().getDisplayMetrics().density; + setOnPreferenceClickListener(this); + if (attrs != null) { + mAlphaSliderEnabled = attrs.getAttributeBooleanValue(null, "alphaSlider", false); + mHexValueEnabled = attrs.getAttributeBooleanValue(null, "hexValue", false); + } + } + + @Override + public void onBindViewHolder(PreferenceViewHolder holder) { + super.onBindViewHolder(holder); + + mView = holder.itemView; + setPreviewColor(); + } + + private void setPreviewColor() { + if (mView == null) return; + ImageView iView = new ImageView(getContext()); + LinearLayout widgetFrameView = ((LinearLayout) mView.findViewById(android.R.id.widget_frame)); + if (widgetFrameView == null) return; + widgetFrameView.setVisibility(View.VISIBLE); + widgetFrameView.setPadding( + widgetFrameView.getPaddingLeft(), + widgetFrameView.getPaddingTop(), + (int) (mDensity * 8), + widgetFrameView.getPaddingBottom() + ); + // remove already create preview image + int count = widgetFrameView.getChildCount(); + if (count > 0) { + widgetFrameView.removeViews(0, count); + } + widgetFrameView.addView(iView); + widgetFrameView.setMinimumWidth(0); + iView.setBackgroundDrawable(new AlphaPatternDrawable((int) (5 * mDensity))); + iView.setImageBitmap(getPreviewBitmap()); + } + + private Bitmap getPreviewBitmap() { + int d = (int) (mDensity * 31); //30dip + int color = mValue; + Bitmap bm = Bitmap.createBitmap(d, d, Config.ARGB_8888); + int w = bm.getWidth(); + int h = bm.getHeight(); + int c = color; + for (int i = 0; i < w; i++) { + for (int j = i; j < h; j++) { + c = (i <= 1 || j <= 1 || i >= w - 2 || j >= h - 2) ? Color.GRAY : color; + bm.setPixel(i, j, c); + if (i != j) { + bm.setPixel(j, i, c); + } + } + } + + return bm; + } + + @Override + public void onColorChanged(int color) { + if (isPersistent()) { + persistInt(color); + } + mValue = color; + setPreviewColor(); + try { + getOnPreferenceChangeListener().onPreferenceChange(this, color); + } catch (NullPointerException e) { + + } + } + + public boolean onPreferenceClick(Preference preference) { + showDialog(null); + return false; + } + + protected void showDialog(Bundle state) { + mDialog = new ColorPickerDialog(getContext(), mValue, getTitle().toString()); + mDialog.setOnColorChangedListener(this); + if (mAlphaSliderEnabled) { + mDialog.setAlphaSliderVisible(true); + } + if (mHexValueEnabled) { + mDialog.setHexValueEnabled(true); + } + if (state != null) { + mDialog.onRestoreInstanceState(state); + } + mDialog.show(); + } + + /** + * Toggle Alpha Slider visibility (by default it's disabled) + * + * @param enable + */ + public void setAlphaSliderEnabled(boolean enable) { + mAlphaSliderEnabled = enable; + } + + /** + * Toggle Hex Value visibility (by default it's disabled) + * + * @param enable + */ + public void setHexValueEnabled(boolean enable) { + mHexValueEnabled = enable; + } + + /** + * For custom purposes. Not used by ColorPickerPreferrence + * + * @param color + * @author Unknown + */ + public static String convertToARGB(int color) { + String alpha = Integer.toHexString(Color.alpha(color)); + String red = Integer.toHexString(Color.red(color)); + String green = Integer.toHexString(Color.green(color)); + String blue = Integer.toHexString(Color.blue(color)); + + if (alpha.length() == 1) { + alpha = "0" + alpha; + } + + if (red.length() == 1) { + red = "0" + red; + } + + if (green.length() == 1) { + green = "0" + green; + } + + if (blue.length() == 1) { + blue = "0" + blue; + } + + return "#" + alpha + red + green + blue; + } + + /** + * Method currently used by onGetDefaultValue method to + * convert hex string provided in android:defaultValue to color integer. + * + * @param color + * @return A string representing the hex value of color, + * without the alpha value + * @author Charles Rosaaen + */ + public static String convertToRGB(int color) { + String red = Integer.toHexString(Color.red(color)); + String green = Integer.toHexString(Color.green(color)); + String blue = Integer.toHexString(Color.blue(color)); + + if (red.length() == 1) { + red = "0" + red; + } + + if (green.length() == 1) { + green = "0" + green; + } + + if (blue.length() == 1) { + blue = "0" + blue; + } + + return "#" + red + green + blue; + } + + /** + * For custom purposes. Not used by ColorPickerPreferrence + * + * @param argb + * @throws NumberFormatException + * @author Unknown + */ + public static int convertToColorInt(String argb) throws IllegalArgumentException { + + if (!argb.startsWith("#")) { + argb = "#" + argb; + } + + return Color.parseColor(argb); + } + + @Override + protected Parcelable onSaveInstanceState() { + final Parcelable superState = super.onSaveInstanceState(); + if (mDialog == null || !mDialog.isShowing()) { + return superState; + } + + final SavedState myState = new SavedState(superState); + myState.dialogBundle = mDialog.onSaveInstanceState(); + return myState; + } + + @Override + protected void onRestoreInstanceState(Parcelable state) { + if (state == null || !(state instanceof SavedState)) { + // Didn't save state for us in onSaveInstanceState + super.onRestoreInstanceState(state); + return; + } + + SavedState myState = (SavedState) state; + super.onRestoreInstanceState(myState.getSuperState()); + showDialog(myState.dialogBundle); + } + + private static class SavedState extends BaseSavedState { + Bundle dialogBundle; + + public SavedState(Parcel source) { + super(source); + dialogBundle = source.readBundle(); + } + + @Override + public void writeToParcel(Parcel dest, int flags) { + super.writeToParcel(dest, flags); + dest.writeBundle(dialogBundle); + } + + public SavedState(Parcelable superState) { + super(superState); + } + + @SuppressWarnings("unused") + public static final Parcelable.Creator CREATOR = + new Parcelable.Creator() { + public SavedState createFromParcel(Parcel in) { + return new SavedState(in); + } + + public SavedState[] newArray(int size) { + return new SavedState[size]; + } + }; + } +} diff --git a/src/net/margaritov/preference/colorpicker/ColorPickerView.java b/src/net/margaritov/preference/colorpicker/ColorPickerView.java index ff9df69b..04bcb10d 100644 --- a/src/net/margaritov/preference/colorpicker/ColorPickerView.java +++ b/src/net/margaritov/preference/colorpicker/ColorPickerView.java @@ -5,7 +5,7 @@ * 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 + * 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, @@ -43,903 +43,903 @@ */ public class ColorPickerView extends View { - private final static int PANEL_SAT_VAL = 0; - private final static int PANEL_HUE = 1; - private final static int PANEL_ALPHA = 2; - - /** - * The width in pixels of the border - * surrounding all color panels. - */ - private final static float BORDER_WIDTH_PX = 1; - - /** - * The width in dp of the hue panel. - */ - private float HUE_PANEL_WIDTH = 30f; - /** - * The height in dp of the alpha panel - */ - private float ALPHA_PANEL_HEIGHT = 20f; - /** - * The distance in dp between the different - * color panels. - */ - private float PANEL_SPACING = 10f; - /** - * The radius in dp of the color palette tracker circle. - */ - private float PALETTE_CIRCLE_TRACKER_RADIUS = 5f; - /** - * The dp which the tracker of the hue or alpha panel - * will extend outside of its bounds. - */ - private float RECTANGLE_TRACKER_OFFSET = 2f; - - - private float mDensity = 1f; - - private OnColorChangedListener mListener; - - private Paint mSatValPaint; - private Paint mSatValTrackerPaint; - - private Paint mHuePaint; - private Paint mHueTrackerPaint; - - private Paint mAlphaPaint; - private Paint mAlphaTextPaint; - - private Paint mBorderPaint; - - private Shader mValShader; - private Shader mSatShader; - private Shader mHueShader; - private Shader mAlphaShader; - - private int mAlpha = 0xff; - private float mHue = 360f; - private float mSat = 0f; - private float mVal = 0f; - - private String mAlphaSliderText = ""; - private int mSliderTrackerColor = 0xff1c1c1c; - private int mBorderColor = 0xff6E6E6E; - private boolean mShowAlphaPanel = false; - - /* - * To remember which panel that has the "focus" when - * processing hardware button data. - */ - private int mLastTouchedPanel = PANEL_SAT_VAL; - - /** - * Offset from the edge we must have or else - * the finger tracker will get clipped when - * it is drawn outside of the view. - */ - private float mDrawingOffset; + private final static int PANEL_SAT_VAL = 0; + private final static int PANEL_HUE = 1; + private final static int PANEL_ALPHA = 2; + + /** + * The width in pixels of the border + * surrounding all color panels. + */ + private final static float BORDER_WIDTH_PX = 1; + + /** + * The width in dp of the hue panel. + */ + private float HUE_PANEL_WIDTH = 30f; + /** + * The height in dp of the alpha panel + */ + private float ALPHA_PANEL_HEIGHT = 20f; + /** + * The distance in dp between the different + * color panels. + */ + private float PANEL_SPACING = 10f; + /** + * The radius in dp of the color palette tracker circle. + */ + private float PALETTE_CIRCLE_TRACKER_RADIUS = 5f; + /** + * The dp which the tracker of the hue or alpha panel + * will extend outside of its bounds. + */ + private float RECTANGLE_TRACKER_OFFSET = 2f; + + + private float mDensity = 1f; + + private OnColorChangedListener mListener; + + private Paint mSatValPaint; + private Paint mSatValTrackerPaint; + + private Paint mHuePaint; + private Paint mHueTrackerPaint; + + private Paint mAlphaPaint; + private Paint mAlphaTextPaint; + + private Paint mBorderPaint; + + private Shader mValShader; + private Shader mSatShader; + private Shader mHueShader; + private Shader mAlphaShader; + + private int mAlpha = 0xff; + private float mHue = 360f; + private float mSat = 0f; + private float mVal = 0f; + + private String mAlphaSliderText = ""; + private int mSliderTrackerColor = 0xff1c1c1c; + private int mBorderColor = 0xff6E6E6E; + private boolean mShowAlphaPanel = false; + + /* + * To remember which panel that has the "focus" when + * processing hardware button data. + */ + private int mLastTouchedPanel = PANEL_SAT_VAL; + + /** + * Offset from the edge we must have or else + * the finger tracker will get clipped when + * it is drawn outside of the view. + */ + private float mDrawingOffset; - /* - * Distance form the edges of the view - * of where we are allowed to draw. - */ - private RectF mDrawingRect; + /* + * Distance form the edges of the view + * of where we are allowed to draw. + */ + private RectF mDrawingRect; - private RectF mSatValRect; - private RectF mHueRect; - private RectF mAlphaRect; + private RectF mSatValRect; + private RectF mHueRect; + private RectF mAlphaRect; - private AlphaPatternDrawable mAlphaPattern; + private AlphaPatternDrawable mAlphaPattern; - private Point mStartTouchPoint = null; + private Point mStartTouchPoint = null; - public interface OnColorChangedListener { - public void onColorChanged(int color); - } + public interface OnColorChangedListener { + public void onColorChanged(int color); + } - public ColorPickerView(Context context) { - this(context, null); - } + public ColorPickerView(Context context) { + this(context, null); + } - public ColorPickerView(Context context, AttributeSet attrs) { - this(context, attrs, 0); - } + public ColorPickerView(Context context, AttributeSet attrs) { + this(context, attrs, 0); + } - public ColorPickerView(Context context, AttributeSet attrs, int defStyle) { - super(context, attrs, defStyle); - init(); - } + public ColorPickerView(Context context, AttributeSet attrs, int defStyle) { + super(context, attrs, defStyle); + init(); + } - private void init() { - mDensity = getContext().getResources().getDisplayMetrics().density; - PALETTE_CIRCLE_TRACKER_RADIUS *= mDensity; - RECTANGLE_TRACKER_OFFSET *= mDensity; - HUE_PANEL_WIDTH *= mDensity; - ALPHA_PANEL_HEIGHT *= mDensity; - PANEL_SPACING = PANEL_SPACING * mDensity; + private void init() { + mDensity = getContext().getResources().getDisplayMetrics().density; + PALETTE_CIRCLE_TRACKER_RADIUS *= mDensity; + RECTANGLE_TRACKER_OFFSET *= mDensity; + HUE_PANEL_WIDTH *= mDensity; + ALPHA_PANEL_HEIGHT *= mDensity; + PANEL_SPACING = PANEL_SPACING * mDensity; - mDrawingOffset = calculateRequiredOffset(); + mDrawingOffset = calculateRequiredOffset(); - initPaintTools(); + initPaintTools(); - //Needed for receiving trackball motion events. - setFocusable(true); - setFocusableInTouchMode(true); - } + //Needed for receiving trackball motion events. + setFocusable(true); + setFocusableInTouchMode(true); + } - private void initPaintTools() { + private void initPaintTools() { - mSatValPaint = new Paint(); - mSatValTrackerPaint = new Paint(); - mHuePaint = new Paint(); - mHueTrackerPaint = new Paint(); - mAlphaPaint = new Paint(); - mAlphaTextPaint = new Paint(); - mBorderPaint = new Paint(); + mSatValPaint = new Paint(); + mSatValTrackerPaint = new Paint(); + mHuePaint = new Paint(); + mHueTrackerPaint = new Paint(); + mAlphaPaint = new Paint(); + mAlphaTextPaint = new Paint(); + mBorderPaint = new Paint(); - mSatValTrackerPaint.setStyle(Style.STROKE); - mSatValTrackerPaint.setStrokeWidth(2f * mDensity); - mSatValTrackerPaint.setAntiAlias(true); + mSatValTrackerPaint.setStyle(Style.STROKE); + mSatValTrackerPaint.setStrokeWidth(2f * mDensity); + mSatValTrackerPaint.setAntiAlias(true); - mHueTrackerPaint.setColor(mSliderTrackerColor); - mHueTrackerPaint.setStyle(Style.STROKE); - mHueTrackerPaint.setStrokeWidth(2f * mDensity); - mHueTrackerPaint.setAntiAlias(true); + mHueTrackerPaint.setColor(mSliderTrackerColor); + mHueTrackerPaint.setStyle(Style.STROKE); + mHueTrackerPaint.setStrokeWidth(2f * mDensity); + mHueTrackerPaint.setAntiAlias(true); - mAlphaTextPaint.setColor(0xff1c1c1c); - mAlphaTextPaint.setTextSize(14f * mDensity); - mAlphaTextPaint.setAntiAlias(true); - mAlphaTextPaint.setTextAlign(Align.CENTER); - mAlphaTextPaint.setFakeBoldText(true); + mAlphaTextPaint.setColor(0xff1c1c1c); + mAlphaTextPaint.setTextSize(14f * mDensity); + mAlphaTextPaint.setAntiAlias(true); + mAlphaTextPaint.setTextAlign(Align.CENTER); + mAlphaTextPaint.setFakeBoldText(true); - } + } - private float calculateRequiredOffset() { - float offset = Math.max(PALETTE_CIRCLE_TRACKER_RADIUS, RECTANGLE_TRACKER_OFFSET); - offset = Math.max(offset, BORDER_WIDTH_PX * mDensity); + private float calculateRequiredOffset() { + float offset = Math.max(PALETTE_CIRCLE_TRACKER_RADIUS, RECTANGLE_TRACKER_OFFSET); + offset = Math.max(offset, BORDER_WIDTH_PX * mDensity); - return offset * 1.5f; - } + return offset * 1.5f; + } - private int[] buildHueColorArray() { + private int[] buildHueColorArray() { - int[] hue = new int[361]; + int[] hue = new int[361]; - int count = 0; - for (int i = hue.length - 1; i >= 0; i--, count++) { - hue[count] = Color.HSVToColor(new float[]{i, 1f, 1f}); - } + int count = 0; + for (int i = hue.length - 1; i >= 0; i--, count++) { + hue[count] = Color.HSVToColor(new float[]{i, 1f, 1f}); + } - return hue; - } + return hue; + } - @Override - protected void onDraw(Canvas canvas) { + @Override + protected void onDraw(Canvas canvas) { - if (mDrawingRect.width() <= 0 || mDrawingRect.height() <= 0) return; + if (mDrawingRect.width() <= 0 || mDrawingRect.height() <= 0) return; - drawSatValPanel(canvas); - drawHuePanel(canvas); - drawAlphaPanel(canvas); + drawSatValPanel(canvas); + drawHuePanel(canvas); + drawAlphaPanel(canvas); - } + } - private void drawSatValPanel(Canvas canvas) { + private void drawSatValPanel(Canvas canvas) { - final RectF rect = mSatValRect; + final RectF rect = mSatValRect; - if (BORDER_WIDTH_PX > 0) { - mBorderPaint.setColor(mBorderColor); - canvas.drawRect(mDrawingRect.left, mDrawingRect.top, rect.right + BORDER_WIDTH_PX, rect.bottom + BORDER_WIDTH_PX, mBorderPaint); - } + if (BORDER_WIDTH_PX > 0) { + mBorderPaint.setColor(mBorderColor); + canvas.drawRect(mDrawingRect.left, mDrawingRect.top, rect.right + BORDER_WIDTH_PX, rect.bottom + BORDER_WIDTH_PX, mBorderPaint); + } - if (mValShader == null) { - mValShader = new LinearGradient(rect.left, rect.top, rect.left, rect.bottom, - 0xffffffff, 0xff000000, TileMode.CLAMP); - } + if (mValShader == null) { + mValShader = new LinearGradient(rect.left, rect.top, rect.left, rect.bottom, + 0xffffffff, 0xff000000, TileMode.CLAMP); + } - int rgb = Color.HSVToColor(new float[]{mHue, 1f, 1f}); + int rgb = Color.HSVToColor(new float[]{mHue, 1f, 1f}); - mSatShader = new LinearGradient(rect.left, rect.top, rect.right, rect.top, - 0xffffffff, rgb, TileMode.CLAMP); - ComposeShader mShader = new ComposeShader(mValShader, mSatShader, PorterDuff.Mode.MULTIPLY); - mSatValPaint.setShader(mShader); + mSatShader = new LinearGradient(rect.left, rect.top, rect.right, rect.top, + 0xffffffff, rgb, TileMode.CLAMP); + ComposeShader mShader = new ComposeShader(mValShader, mSatShader, PorterDuff.Mode.MULTIPLY); + mSatValPaint.setShader(mShader); - canvas.drawRect(rect, mSatValPaint); + canvas.drawRect(rect, mSatValPaint); - Point p = satValToPoint(mSat, mVal); + Point p = satValToPoint(mSat, mVal); - mSatValTrackerPaint.setColor(0xff000000); - canvas.drawCircle(p.x, p.y, PALETTE_CIRCLE_TRACKER_RADIUS - 1f * mDensity, mSatValTrackerPaint); + mSatValTrackerPaint.setColor(0xff000000); + canvas.drawCircle(p.x, p.y, PALETTE_CIRCLE_TRACKER_RADIUS - 1f * mDensity, mSatValTrackerPaint); - mSatValTrackerPaint.setColor(0xffdddddd); - canvas.drawCircle(p.x, p.y, PALETTE_CIRCLE_TRACKER_RADIUS, mSatValTrackerPaint); + mSatValTrackerPaint.setColor(0xffdddddd); + canvas.drawCircle(p.x, p.y, PALETTE_CIRCLE_TRACKER_RADIUS, mSatValTrackerPaint); - } + } - private void drawHuePanel(Canvas canvas) { + private void drawHuePanel(Canvas canvas) { - final RectF rect = mHueRect; + final RectF rect = mHueRect; - if (BORDER_WIDTH_PX > 0) { - mBorderPaint.setColor(mBorderColor); - canvas.drawRect(rect.left - BORDER_WIDTH_PX, - rect.top - BORDER_WIDTH_PX, - rect.right + BORDER_WIDTH_PX, - rect.bottom + BORDER_WIDTH_PX, - mBorderPaint); - } + if (BORDER_WIDTH_PX > 0) { + mBorderPaint.setColor(mBorderColor); + canvas.drawRect(rect.left - BORDER_WIDTH_PX, + rect.top - BORDER_WIDTH_PX, + rect.right + BORDER_WIDTH_PX, + rect.bottom + BORDER_WIDTH_PX, + mBorderPaint); + } - if (mHueShader == null) { - mHueShader = new LinearGradient(rect.left, rect.top, rect.left, rect.bottom, buildHueColorArray(), null, TileMode.CLAMP); - mHuePaint.setShader(mHueShader); - } + if (mHueShader == null) { + mHueShader = new LinearGradient(rect.left, rect.top, rect.left, rect.bottom, buildHueColorArray(), null, TileMode.CLAMP); + mHuePaint.setShader(mHueShader); + } - canvas.drawRect(rect, mHuePaint); + canvas.drawRect(rect, mHuePaint); - float rectHeight = 4 * mDensity / 2; + float rectHeight = 4 * mDensity / 2; - Point p = hueToPoint(mHue); + Point p = hueToPoint(mHue); - RectF r = new RectF(); - r.left = rect.left - RECTANGLE_TRACKER_OFFSET; - r.right = rect.right + RECTANGLE_TRACKER_OFFSET; - r.top = p.y - rectHeight; - r.bottom = p.y + rectHeight; + RectF r = new RectF(); + r.left = rect.left - RECTANGLE_TRACKER_OFFSET; + r.right = rect.right + RECTANGLE_TRACKER_OFFSET; + r.top = p.y - rectHeight; + r.bottom = p.y + rectHeight; - canvas.drawRoundRect(r, 2, 2, mHueTrackerPaint); + canvas.drawRoundRect(r, 2, 2, mHueTrackerPaint); - } + } - private void drawAlphaPanel(Canvas canvas) { + private void drawAlphaPanel(Canvas canvas) { - if (!mShowAlphaPanel || mAlphaRect == null || mAlphaPattern == null) return; + if (!mShowAlphaPanel || mAlphaRect == null || mAlphaPattern == null) return; - final RectF rect = mAlphaRect; + final RectF rect = mAlphaRect; - if (BORDER_WIDTH_PX > 0) { - mBorderPaint.setColor(mBorderColor); - canvas.drawRect(rect.left - BORDER_WIDTH_PX, - rect.top - BORDER_WIDTH_PX, - rect.right + BORDER_WIDTH_PX, - rect.bottom + BORDER_WIDTH_PX, - mBorderPaint); - } + if (BORDER_WIDTH_PX > 0) { + mBorderPaint.setColor(mBorderColor); + canvas.drawRect(rect.left - BORDER_WIDTH_PX, + rect.top - BORDER_WIDTH_PX, + rect.right + BORDER_WIDTH_PX, + rect.bottom + BORDER_WIDTH_PX, + mBorderPaint); + } - mAlphaPattern.draw(canvas); + mAlphaPattern.draw(canvas); - float[] hsv = new float[]{mHue, mSat, mVal}; - int color = Color.HSVToColor(hsv); - int acolor = Color.HSVToColor(0, hsv); + float[] hsv = new float[]{mHue, mSat, mVal}; + int color = Color.HSVToColor(hsv); + int acolor = Color.HSVToColor(0, hsv); - mAlphaShader = new LinearGradient(rect.left, rect.top, rect.right, rect.top, - color, acolor, TileMode.CLAMP); + mAlphaShader = new LinearGradient(rect.left, rect.top, rect.right, rect.top, + color, acolor, TileMode.CLAMP); - mAlphaPaint.setShader(mAlphaShader); + mAlphaPaint.setShader(mAlphaShader); - canvas.drawRect(rect, mAlphaPaint); + canvas.drawRect(rect, mAlphaPaint); - if (mAlphaSliderText != null && mAlphaSliderText != "") { - canvas.drawText(mAlphaSliderText, rect.centerX(), rect.centerY() + 4 * mDensity, mAlphaTextPaint); - } + if (mAlphaSliderText != null && mAlphaSliderText != "") { + canvas.drawText(mAlphaSliderText, rect.centerX(), rect.centerY() + 4 * mDensity, mAlphaTextPaint); + } - float rectWidth = 4 * mDensity / 2; + float rectWidth = 4 * mDensity / 2; - Point p = alphaToPoint(mAlpha); + Point p = alphaToPoint(mAlpha); - RectF r = new RectF(); - r.left = p.x - rectWidth; - r.right = p.x + rectWidth; - r.top = rect.top - RECTANGLE_TRACKER_OFFSET; - r.bottom = rect.bottom + RECTANGLE_TRACKER_OFFSET; + RectF r = new RectF(); + r.left = p.x - rectWidth; + r.right = p.x + rectWidth; + r.top = rect.top - RECTANGLE_TRACKER_OFFSET; + r.bottom = rect.bottom + RECTANGLE_TRACKER_OFFSET; - canvas.drawRoundRect(r, 2, 2, mHueTrackerPaint); + canvas.drawRoundRect(r, 2, 2, mHueTrackerPaint); - } + } - private Point hueToPoint(float hue) { + private Point hueToPoint(float hue) { - final RectF rect = mHueRect; - final float height = rect.height(); + final RectF rect = mHueRect; + final float height = rect.height(); - Point p = new Point(); + Point p = new Point(); - p.y = (int) (height - (hue * height / 360f) + rect.top); - p.x = (int) rect.left; + p.y = (int) (height - (hue * height / 360f) + rect.top); + p.x = (int) rect.left; - return p; - } + return p; + } - private Point satValToPoint(float sat, float val) { + private Point satValToPoint(float sat, float val) { - final RectF rect = mSatValRect; - final float height = rect.height(); - final float width = rect.width(); + final RectF rect = mSatValRect; + final float height = rect.height(); + final float width = rect.width(); - Point p = new Point(); + Point p = new Point(); - p.x = (int) (sat * width + rect.left); - p.y = (int) ((1f - val) * height + rect.top); + p.x = (int) (sat * width + rect.left); + p.y = (int) ((1f - val) * height + rect.top); - return p; - } + return p; + } - private Point alphaToPoint(int alpha) { + private Point alphaToPoint(int alpha) { - final RectF rect = mAlphaRect; - final float width = rect.width(); + final RectF rect = mAlphaRect; + final float width = rect.width(); - Point p = new Point(); + Point p = new Point(); - p.x = (int) (width - (alpha * width / 0xff) + rect.left); - p.y = (int) rect.top; + p.x = (int) (width - (alpha * width / 0xff) + rect.left); + p.y = (int) rect.top; - return p; + return p; - } + } - private float[] pointToSatVal(float x, float y) { + private float[] pointToSatVal(float x, float y) { - final RectF rect = mSatValRect; - float[] result = new float[2]; + final RectF rect = mSatValRect; + float[] result = new float[2]; - float width = rect.width(); - float height = rect.height(); + float width = rect.width(); + float height = rect.height(); - if (x < rect.left) { - x = 0f; - } else if (x > rect.right) { - x = width; - } else { - x = x - rect.left; - } + if (x < rect.left) { + x = 0f; + } else if (x > rect.right) { + x = width; + } else { + x = x - rect.left; + } - if (y < rect.top) { - y = 0f; - } else if (y > rect.bottom) { - y = height; - } else { - y = y - rect.top; - } + if (y < rect.top) { + y = 0f; + } else if (y > rect.bottom) { + y = height; + } else { + y = y - rect.top; + } - result[0] = 1.f / width * x; - result[1] = 1.f - (1.f / height * y); + result[0] = 1.f / width * x; + result[1] = 1.f - (1.f / height * y); - return result; - } + return result; + } - private float pointToHue(float y) { + private float pointToHue(float y) { - final RectF rect = mHueRect; + final RectF rect = mHueRect; - float height = rect.height(); + float height = rect.height(); - if (y < rect.top) { - y = 0f; - } else if (y > rect.bottom) { - y = height; - } else { - y = y - rect.top; - } + if (y < rect.top) { + y = 0f; + } else if (y > rect.bottom) { + y = height; + } else { + y = y - rect.top; + } - return 360f - (y * 360f / height); - } + return 360f - (y * 360f / height); + } - private int pointToAlpha(int x) { + private int pointToAlpha(int x) { - final RectF rect = mAlphaRect; - final int width = (int) rect.width(); + final RectF rect = mAlphaRect; + final int width = (int) rect.width(); - if (x < rect.left) { - x = 0; - } else if (x > rect.right) { - x = width; - } else { - x = x - (int) rect.left; - } + if (x < rect.left) { + x = 0; + } else if (x > rect.right) { + x = width; + } else { + x = x - (int) rect.left; + } - return 0xff - (x * 0xff / width); + return 0xff - (x * 0xff / width); - } + } - @Override - public boolean onTrackballEvent(MotionEvent event) { + @Override + public boolean onTrackballEvent(MotionEvent event) { - float x = event.getX(); - float y = event.getY(); + float x = event.getX(); + float y = event.getY(); - boolean update = false; + boolean update = false; - if (event.getAction() == MotionEvent.ACTION_MOVE) { + if (event.getAction() == MotionEvent.ACTION_MOVE) { - switch (mLastTouchedPanel) { + switch (mLastTouchedPanel) { - case PANEL_SAT_VAL: + case PANEL_SAT_VAL: - float sat, val; + float sat, val; - sat = mSat + x / 50f; - val = mVal - y / 50f; + sat = mSat + x / 50f; + val = mVal - y / 50f; - if (sat < 0f) { - sat = 0f; - } else if (sat > 1f) { - sat = 1f; - } + if (sat < 0f) { + sat = 0f; + } else if (sat > 1f) { + sat = 1f; + } - if (val < 0f) { - val = 0f; - } else if (val > 1f) { - val = 1f; - } + if (val < 0f) { + val = 0f; + } else if (val > 1f) { + val = 1f; + } - mSat = sat; - mVal = val; + mSat = sat; + mVal = val; - update = true; + update = true; - break; + break; - case PANEL_HUE: + case PANEL_HUE: - float hue = mHue - y * 10f; + float hue = mHue - y * 10f; - if (hue < 0f) { - hue = 0f; - } else if (hue > 360f) { - hue = 360f; - } + if (hue < 0f) { + hue = 0f; + } else if (hue > 360f) { + hue = 360f; + } - mHue = hue; + mHue = hue; - update = true; + update = true; - break; + break; - case PANEL_ALPHA: + case PANEL_ALPHA: - if (!mShowAlphaPanel || mAlphaRect == null) { - update = false; - } else { + if (!mShowAlphaPanel || mAlphaRect == null) { + update = false; + } else { - int alpha = (int) (mAlpha - x * 10); + int alpha = (int) (mAlpha - x * 10); - if (alpha < 0) { - alpha = 0; - } else if (alpha > 0xff) { - alpha = 0xff; - } + if (alpha < 0) { + alpha = 0; + } else if (alpha > 0xff) { + alpha = 0xff; + } - mAlpha = alpha; + mAlpha = alpha; - update = true; - } + update = true; + } - break; - } + break; + } - } + } - if (update) { + if (update) { - if (mListener != null) { - mListener.onColorChanged(Color.HSVToColor(mAlpha, new float[]{mHue, mSat, mVal})); - } + if (mListener != null) { + mListener.onColorChanged(Color.HSVToColor(mAlpha, new float[]{mHue, mSat, mVal})); + } - invalidate(); - return true; - } + invalidate(); + return true; + } - return super.onTrackballEvent(event); - } + return super.onTrackballEvent(event); + } - @Override - public boolean onTouchEvent(MotionEvent event) { + @Override + public boolean onTouchEvent(MotionEvent event) { - boolean update = false; + boolean update = false; - switch (event.getAction()) { + switch (event.getAction()) { - case MotionEvent.ACTION_DOWN: + case MotionEvent.ACTION_DOWN: - mStartTouchPoint = new Point((int) event.getX(), (int) event.getY()); + mStartTouchPoint = new Point((int) event.getX(), (int) event.getY()); - update = moveTrackersIfNeeded(event); + update = moveTrackersIfNeeded(event); - break; + break; - case MotionEvent.ACTION_MOVE: + case MotionEvent.ACTION_MOVE: - update = moveTrackersIfNeeded(event); + update = moveTrackersIfNeeded(event); - break; + break; - case MotionEvent.ACTION_UP: + case MotionEvent.ACTION_UP: - mStartTouchPoint = null; + mStartTouchPoint = null; - update = moveTrackersIfNeeded(event); + update = moveTrackersIfNeeded(event); - break; + break; - } + } - if (update) { + if (update) { - if (mListener != null) { - mListener.onColorChanged(Color.HSVToColor(mAlpha, new float[]{mHue, mSat, mVal})); - } + if (mListener != null) { + mListener.onColorChanged(Color.HSVToColor(mAlpha, new float[]{mHue, mSat, mVal})); + } - invalidate(); - return true; - } + invalidate(); + return true; + } - return super.onTouchEvent(event); - } + return super.onTouchEvent(event); + } - private boolean moveTrackersIfNeeded(MotionEvent event) { + private boolean moveTrackersIfNeeded(MotionEvent event) { - if (mStartTouchPoint == null) return false; + if (mStartTouchPoint == null) return false; - boolean update = false; + boolean update = false; - int startX = mStartTouchPoint.x; - int startY = mStartTouchPoint.y; + int startX = mStartTouchPoint.x; + int startY = mStartTouchPoint.y; - if (mHueRect.contains(startX, startY)) { - mLastTouchedPanel = PANEL_HUE; + if (mHueRect.contains(startX, startY)) { + mLastTouchedPanel = PANEL_HUE; - mHue = pointToHue(event.getY()); + mHue = pointToHue(event.getY()); - update = true; - } else if (mSatValRect.contains(startX, startY)) { + update = true; + } else if (mSatValRect.contains(startX, startY)) { - mLastTouchedPanel = PANEL_SAT_VAL; + mLastTouchedPanel = PANEL_SAT_VAL; - float[] result = pointToSatVal(event.getX(), event.getY()); + float[] result = pointToSatVal(event.getX(), event.getY()); - mSat = result[0]; - mVal = result[1]; + mSat = result[0]; + mVal = result[1]; - update = true; - } else if (mAlphaRect != null && mAlphaRect.contains(startX, startY)) { + update = true; + } else if (mAlphaRect != null && mAlphaRect.contains(startX, startY)) { - mLastTouchedPanel = PANEL_ALPHA; + mLastTouchedPanel = PANEL_ALPHA; - mAlpha = pointToAlpha((int) event.getX()); + mAlpha = pointToAlpha((int) event.getX()); - update = true; - } + update = true; + } - return update; - } + return update; + } - @Override - protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { + @Override + protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { - int width = 0; - int height = 0; + int width = 0; + int height = 0; - int widthMode = MeasureSpec.getMode(widthMeasureSpec); - int heightMode = MeasureSpec.getMode(heightMeasureSpec); + int widthMode = MeasureSpec.getMode(widthMeasureSpec); + int heightMode = MeasureSpec.getMode(heightMeasureSpec); - int widthAllowed = MeasureSpec.getSize(widthMeasureSpec); - int heightAllowed = MeasureSpec.getSize(heightMeasureSpec); + int widthAllowed = MeasureSpec.getSize(widthMeasureSpec); + int heightAllowed = MeasureSpec.getSize(heightMeasureSpec); - widthAllowed = chooseWidth(widthMode, widthAllowed); - heightAllowed = chooseHeight(heightMode, heightAllowed); + widthAllowed = chooseWidth(widthMode, widthAllowed); + heightAllowed = chooseHeight(heightMode, heightAllowed); - if (!mShowAlphaPanel) { + if (!mShowAlphaPanel) { - height = (int) (widthAllowed - PANEL_SPACING - HUE_PANEL_WIDTH); + height = (int) (widthAllowed - PANEL_SPACING - HUE_PANEL_WIDTH); - //If calculated height (based on the width) is more than the allowed height. - if (height > heightAllowed || getTag().equals("landscape")) { - height = heightAllowed; - width = (int) (height + PANEL_SPACING + HUE_PANEL_WIDTH); - } else { - width = widthAllowed; - } - } else { + //If calculated height (based on the width) is more than the allowed height. + if (height > heightAllowed || getTag().equals("landscape")) { + height = heightAllowed; + width = (int) (height + PANEL_SPACING + HUE_PANEL_WIDTH); + } else { + width = widthAllowed; + } + } else { - width = (int) (heightAllowed - ALPHA_PANEL_HEIGHT + HUE_PANEL_WIDTH); + width = (int) (heightAllowed - ALPHA_PANEL_HEIGHT + HUE_PANEL_WIDTH); - if (width > widthAllowed) { - width = widthAllowed; - height = (int) (widthAllowed - HUE_PANEL_WIDTH + ALPHA_PANEL_HEIGHT); - } else { - height = heightAllowed; - } + if (width > widthAllowed) { + width = widthAllowed; + height = (int) (widthAllowed - HUE_PANEL_WIDTH + ALPHA_PANEL_HEIGHT); + } else { + height = heightAllowed; + } - } + } - setMeasuredDimension(width, height); - } + setMeasuredDimension(width, height); + } - private int chooseWidth(int mode, int size) { - if (mode == MeasureSpec.AT_MOST || mode == MeasureSpec.EXACTLY) { - return size; - } else { // (mode == MeasureSpec.UNSPECIFIED) - return getPrefferedWidth(); - } - } + private int chooseWidth(int mode, int size) { + if (mode == MeasureSpec.AT_MOST || mode == MeasureSpec.EXACTLY) { + return size; + } else { // (mode == MeasureSpec.UNSPECIFIED) + return getPrefferedWidth(); + } + } - private int chooseHeight(int mode, int size) { - if (mode == MeasureSpec.AT_MOST || mode == MeasureSpec.EXACTLY) { - return size; - } else { // (mode == MeasureSpec.UNSPECIFIED) - return getPrefferedHeight(); - } - } + private int chooseHeight(int mode, int size) { + if (mode == MeasureSpec.AT_MOST || mode == MeasureSpec.EXACTLY) { + return size; + } else { // (mode == MeasureSpec.UNSPECIFIED) + return getPrefferedHeight(); + } + } - private int getPrefferedWidth() { + private int getPrefferedWidth() { - int width = getPrefferedHeight(); + int width = getPrefferedHeight(); - if (mShowAlphaPanel) { - width -= (PANEL_SPACING + ALPHA_PANEL_HEIGHT); - } + if (mShowAlphaPanel) { + width -= (PANEL_SPACING + ALPHA_PANEL_HEIGHT); + } - return (int) (width + HUE_PANEL_WIDTH + PANEL_SPACING); + return (int) (width + HUE_PANEL_WIDTH + PANEL_SPACING); - } + } - private int getPrefferedHeight() { + private int getPrefferedHeight() { - int height = (int) (200 * mDensity); + int height = (int) (200 * mDensity); - if (mShowAlphaPanel) { - height += PANEL_SPACING + ALPHA_PANEL_HEIGHT; - } + if (mShowAlphaPanel) { + height += PANEL_SPACING + ALPHA_PANEL_HEIGHT; + } - return height; - } + return height; + } - @Override - protected void onSizeChanged(int w, int h, int oldw, int oldh) { - super.onSizeChanged(w, h, oldw, oldh); + @Override + protected void onSizeChanged(int w, int h, int oldw, int oldh) { + super.onSizeChanged(w, h, oldw, oldh); - mDrawingRect = new RectF(); - mDrawingRect.left = mDrawingOffset + getPaddingLeft(); - mDrawingRect.right = w - mDrawingOffset - getPaddingRight(); - mDrawingRect.top = mDrawingOffset + getPaddingTop(); - mDrawingRect.bottom = h - mDrawingOffset - getPaddingBottom(); + mDrawingRect = new RectF(); + mDrawingRect.left = mDrawingOffset + getPaddingLeft(); + mDrawingRect.right = w - mDrawingOffset - getPaddingRight(); + mDrawingRect.top = mDrawingOffset + getPaddingTop(); + mDrawingRect.bottom = h - mDrawingOffset - getPaddingBottom(); - setUpSatValRect(); - setUpHueRect(); - setUpAlphaRect(); - } + setUpSatValRect(); + setUpHueRect(); + setUpAlphaRect(); + } - private void setUpSatValRect() { + private void setUpSatValRect() { - final RectF dRect = mDrawingRect; - float panelSide = dRect.height() - BORDER_WIDTH_PX * 2; - - if (mShowAlphaPanel) { - panelSide -= PANEL_SPACING + ALPHA_PANEL_HEIGHT; - } - - float left = dRect.left + BORDER_WIDTH_PX; - float top = dRect.top + BORDER_WIDTH_PX; - float bottom = top + panelSide; - float right = left + panelSide; + final RectF dRect = mDrawingRect; + float panelSide = dRect.height() - BORDER_WIDTH_PX * 2; + + if (mShowAlphaPanel) { + panelSide -= PANEL_SPACING + ALPHA_PANEL_HEIGHT; + } + + float left = dRect.left + BORDER_WIDTH_PX; + float top = dRect.top + BORDER_WIDTH_PX; + float bottom = top + panelSide; + float right = left + panelSide; - mSatValRect = new RectF(left, top, right, bottom); - } + mSatValRect = new RectF(left, top, right, bottom); + } - private void setUpHueRect() { - final RectF dRect = mDrawingRect; - - float left = dRect.right - HUE_PANEL_WIDTH + BORDER_WIDTH_PX; - float top = dRect.top + BORDER_WIDTH_PX; - float bottom = dRect.bottom - BORDER_WIDTH_PX - (mShowAlphaPanel ? (PANEL_SPACING + ALPHA_PANEL_HEIGHT) : 0); - float right = dRect.right - BORDER_WIDTH_PX; - - mHueRect = new RectF(left, top, right, bottom); - } - - private void setUpAlphaRect() { - - if (!mShowAlphaPanel) return; - - final RectF dRect = mDrawingRect; - - float left = dRect.left + BORDER_WIDTH_PX; - float top = dRect.bottom - ALPHA_PANEL_HEIGHT + BORDER_WIDTH_PX; - float bottom = dRect.bottom - BORDER_WIDTH_PX; - float right = dRect.right - BORDER_WIDTH_PX; - - mAlphaRect = new RectF(left, top, right, bottom); - - mAlphaPattern = new AlphaPatternDrawable((int) (5 * mDensity)); - mAlphaPattern.setBounds( - Math.round(mAlphaRect.left), - Math.round(mAlphaRect.top), - Math.round(mAlphaRect.right), - Math.round(mAlphaRect.bottom) - ); - - } - - - /** - * Set a OnColorChangedListener to get notified when the color - * selected by the user has changed. - * - * @param listener - */ - public void setOnColorChangedListener(OnColorChangedListener listener) { - mListener = listener; - } - - /** - * Set the color of the border surrounding all panels. - * - * @param color - */ - public void setBorderColor(int color) { - mBorderColor = color; - invalidate(); - } - - /** - * Get the color of the border surrounding all panels. - */ - public int getBorderColor() { - return mBorderColor; - } - - /** - * Get the current color this view is showing. - * - * @return the current color. - */ - public int getColor() { - return Color.HSVToColor(mAlpha, new float[]{mHue, mSat, mVal}); - } - - /** - * Set the color the view should show. - * - * @param color The color that should be selected. - */ - public void setColor(int color) { - setColor(color, false); - } - - /** - * Set the color this view should show. - * - * @param color The color that should be selected. - * @param callback If you want to get a callback to - * your OnColorChangedListener. - */ - public void setColor(int color, boolean callback) { - - int alpha = Color.alpha(color); - - float[] hsv = new float[3]; - - Color.colorToHSV(color, hsv); - - mAlpha = alpha; - mHue = hsv[0]; - mSat = hsv[1]; - mVal = hsv[2]; - - if (callback && mListener != null) { - mListener.onColorChanged(Color.HSVToColor(mAlpha, new float[]{mHue, mSat, mVal})); - } - - invalidate(); - } - - /** - * Get the drawing offset of the color picker view. - * The drawing offset is the distance from the side of - * a panel to the side of the view minus the padding. - * Useful if you want to have your own panel below showing - * the currently selected color and want to align it perfectly. - * - * @return The offset in pixels. - */ - public float getDrawingOffset() { - return mDrawingOffset; - } - - /** - * Set if the user is allowed to adjust the alpha panel. Default is false. - * If it is set to false no alpha will be set. - * - * @param visible - */ - public void setAlphaSliderVisible(boolean visible) { - - if (mShowAlphaPanel != visible) { - mShowAlphaPanel = visible; - - /* - * Reset all shader to force a recreation. - * Otherwise they will not look right after - * the size of the view has changed. - */ - mValShader = null; - mSatShader = null; - mHueShader = null; - mAlphaShader = null; - - requestLayout(); - } - - } - - public boolean getAlphaSliderVisible() { - return mShowAlphaPanel; - } - - public void setSliderTrackerColor(int color) { - mSliderTrackerColor = color; - - mHueTrackerPaint.setColor(mSliderTrackerColor); - - invalidate(); - } - - public int getSliderTrackerColor() { - return mSliderTrackerColor; - } - - /** - * Set the text that should be shown in the - * alpha slider. Set to null to disable text. - * - * @param res string resource id. - */ - public void setAlphaSliderText(int res) { - String text = getContext().getString(res); - setAlphaSliderText(text); - } - - /** - * Set the text that should be shown in the - * alpha slider. Set to null to disable text. - * - * @param text Text that should be shown. - */ - public void setAlphaSliderText(String text) { - mAlphaSliderText = text; - invalidate(); - } - - /** - * Get the current value of the text - * that will be shown in the alpha - * slider. - * - * @return - */ - public String getAlphaSliderText() { - return mAlphaSliderText; - } -} \ No newline at end of file + private void setUpHueRect() { + final RectF dRect = mDrawingRect; + + float left = dRect.right - HUE_PANEL_WIDTH + BORDER_WIDTH_PX; + float top = dRect.top + BORDER_WIDTH_PX; + float bottom = dRect.bottom - BORDER_WIDTH_PX - (mShowAlphaPanel ? (PANEL_SPACING + ALPHA_PANEL_HEIGHT) : 0); + float right = dRect.right - BORDER_WIDTH_PX; + + mHueRect = new RectF(left, top, right, bottom); + } + + private void setUpAlphaRect() { + + if (!mShowAlphaPanel) return; + + final RectF dRect = mDrawingRect; + + float left = dRect.left + BORDER_WIDTH_PX; + float top = dRect.bottom - ALPHA_PANEL_HEIGHT + BORDER_WIDTH_PX; + float bottom = dRect.bottom - BORDER_WIDTH_PX; + float right = dRect.right - BORDER_WIDTH_PX; + + mAlphaRect = new RectF(left, top, right, bottom); + + mAlphaPattern = new AlphaPatternDrawable((int) (5 * mDensity)); + mAlphaPattern.setBounds( + Math.round(mAlphaRect.left), + Math.round(mAlphaRect.top), + Math.round(mAlphaRect.right), + Math.round(mAlphaRect.bottom) + ); + + } + + + /** + * Set a OnColorChangedListener to get notified when the color + * selected by the user has changed. + * + * @param listener + */ + public void setOnColorChangedListener(OnColorChangedListener listener) { + mListener = listener; + } + + /** + * Set the color of the border surrounding all panels. + * + * @param color + */ + public void setBorderColor(int color) { + mBorderColor = color; + invalidate(); + } + + /** + * Get the color of the border surrounding all panels. + */ + public int getBorderColor() { + return mBorderColor; + } + + /** + * Get the current color this view is showing. + * + * @return the current color. + */ + public int getColor() { + return Color.HSVToColor(mAlpha, new float[]{mHue, mSat, mVal}); + } + + /** + * Set the color the view should show. + * + * @param color The color that should be selected. + */ + public void setColor(int color) { + setColor(color, false); + } + + /** + * Set the color this view should show. + * + * @param color The color that should be selected. + * @param callback If you want to get a callback to + * your OnColorChangedListener. + */ + public void setColor(int color, boolean callback) { + + int alpha = Color.alpha(color); + + float[] hsv = new float[3]; + + Color.colorToHSV(color, hsv); + + mAlpha = alpha; + mHue = hsv[0]; + mSat = hsv[1]; + mVal = hsv[2]; + + if (callback && mListener != null) { + mListener.onColorChanged(Color.HSVToColor(mAlpha, new float[]{mHue, mSat, mVal})); + } + + invalidate(); + } + + /** + * Get the drawing offset of the color picker view. + * The drawing offset is the distance from the side of + * a panel to the side of the view minus the padding. + * Useful if you want to have your own panel below showing + * the currently selected color and want to align it perfectly. + * + * @return The offset in pixels. + */ + public float getDrawingOffset() { + return mDrawingOffset; + } + + /** + * Set if the user is allowed to adjust the alpha panel. Default is false. + * If it is set to false no alpha will be set. + * + * @param visible + */ + public void setAlphaSliderVisible(boolean visible) { + + if (mShowAlphaPanel != visible) { + mShowAlphaPanel = visible; + + /* + * Reset all shader to force a recreation. + * Otherwise they will not look right after + * the size of the view has changed. + */ + mValShader = null; + mSatShader = null; + mHueShader = null; + mAlphaShader = null; + + requestLayout(); + } + + } + + public boolean getAlphaSliderVisible() { + return mShowAlphaPanel; + } + + public void setSliderTrackerColor(int color) { + mSliderTrackerColor = color; + + mHueTrackerPaint.setColor(mSliderTrackerColor); + + invalidate(); + } + + public int getSliderTrackerColor() { + return mSliderTrackerColor; + } + + /** + * Set the text that should be shown in the + * alpha slider. Set to null to disable text. + * + * @param res string resource id. + */ + public void setAlphaSliderText(int res) { + String text = getContext().getString(res); + setAlphaSliderText(text); + } + + /** + * Set the text that should be shown in the + * alpha slider. Set to null to disable text. + * + * @param text Text that should be shown. + */ + public void setAlphaSliderText(String text) { + mAlphaSliderText = text; + invalidate(); + } + + /** + * Get the current value of the text + * that will be shown in the alpha + * slider. + * + * @return + */ + public String getAlphaSliderText() { + return mAlphaSliderText; + } +} diff --git a/src/ru/nsu/ccfit/zuev/audio/BassAudioPlayer.java b/src/ru/nsu/ccfit/zuev/audio/BassAudioPlayer.java index 6d754568..e32f5da0 100644 --- a/src/ru/nsu/ccfit/zuev/audio/BassAudioPlayer.java +++ b/src/ru/nsu/ccfit/zuev/audio/BassAudioPlayer.java @@ -7,146 +7,146 @@ */ public class BassAudioPlayer implements IMusicPlayer { - private static BassAudioProvider provider = null; - private int loadMode = 0; - private AssetManager manager; - private String path; - - public BassAudioPlayer() { - initDevice(); - provider.setUseSoftDecoder(0); - provider.setDecoderMultiplier(100); - } - - public BassAudioPlayer(final String fileName) { - this(); - this.loadMode = 0; - this.path = fileName; - } - - public BassAudioPlayer(final AssetManager manager, String assetName) { - this(); - this.loadMode = 1; - this.manager = manager; - this.path = assetName; - } - - public static void initDevice() { - if (provider == null) { - provider = new BassAudioProvider(); - } - } - - public static BassAudioProvider getProvider() { - return provider; - } - - public void prepare() { - if (loadMode == 0) { - provider.prepare(path); - } else { - provider.prepare(manager, path); - } - } - - public void prepare(String fileName) { - provider.prepare(fileName); - } - - public void play() { - if (provider != null) { - provider.play(); - } - } - - public void pause() { - if (provider != null) { - provider.pause(); - } - } - - public void stop() { - if (provider != null) { - provider.stop(); - } - } - - public void release() { - if (provider != null) { - provider.stop(); - provider.free(); - } - } - - public Status getStatus() { - if (provider != null) { - return provider.getStatus(); - } - return Status.STALLED; - } - - public int getPosition() { - if (provider != null) { - return (int) (provider.getPosition() * 1000.0); - } - return 0; - } - - public int getLength() { - if (provider != null) { - return (int) (provider.getLength() * 1000.0); - } - return 0; - } - - public float[] getSpectrum() { - if (provider != null) { - return provider.getSpectrum(); - } - return new float[0]; - } - - public void seekTo(int ms) { - if (provider != null) { - provider.seek(ms / 1000.0); - } - } - - public void setUseSoftDecoder(int decoder) { - if (provider != null) { - provider.setUseSoftDecoder(decoder); - } - } - - public void setDecoderMultiplier(int multiplier) { - if (provider != null) { - provider.setDecoderMultiplier(multiplier); - } - } - - public void setLoop() { - if (provider != null) { - provider.setLoop(); - } - } - - public float getVolume() { - if (provider != null) { - return provider.getVolume(); - } - return 0; - } - - public void setVolume(float volume) { - if (provider != null) { - provider.setVolume(volume); - } - } - - public int getErrorCode() { - if (provider != null) { - return provider.getErrorCode(); - } - return -1; - } + private static BassAudioProvider provider = null; + private int loadMode = 0; + private AssetManager manager; + private String path; + + public BassAudioPlayer() { + initDevice(); + provider.setUseSoftDecoder(0); + provider.setDecoderMultiplier(100); + } + + public BassAudioPlayer(final String fileName) { + this(); + this.loadMode = 0; + this.path = fileName; + } + + public BassAudioPlayer(final AssetManager manager, String assetName) { + this(); + this.loadMode = 1; + this.manager = manager; + this.path = assetName; + } + + public static void initDevice() { + if (provider == null) { + provider = new BassAudioProvider(); + } + } + + public static BassAudioProvider getProvider() { + return provider; + } + + public void prepare() { + if (loadMode == 0) { + provider.prepare(path); + } else { + provider.prepare(manager, path); + } + } + + public void prepare(String fileName) { + provider.prepare(fileName); + } + + public void play() { + if (provider != null) { + provider.play(); + } + } + + public void pause() { + if (provider != null) { + provider.pause(); + } + } + + public void stop() { + if (provider != null) { + provider.stop(); + } + } + + public void release() { + if (provider != null) { + provider.stop(); + provider.free(); + } + } + + public Status getStatus() { + if (provider != null) { + return provider.getStatus(); + } + return Status.STALLED; + } + + public int getPosition() { + if (provider != null) { + return (int) (provider.getPosition() * 1000.0); + } + return 0; + } + + public int getLength() { + if (provider != null) { + return (int) (provider.getLength() * 1000.0); + } + return 0; + } + + public float[] getSpectrum() { + if (provider != null) { + return provider.getSpectrum(); + } + return new float[0]; + } + + public void seekTo(int ms) { + if (provider != null) { + provider.seek(ms / 1000.0); + } + } + + public void setUseSoftDecoder(int decoder) { + if (provider != null) { + provider.setUseSoftDecoder(decoder); + } + } + + public void setDecoderMultiplier(int multiplier) { + if (provider != null) { + provider.setDecoderMultiplier(multiplier); + } + } + + public void setLoop() { + if (provider != null) { + provider.setLoop(); + } + } + + public float getVolume() { + if (provider != null) { + return provider.getVolume(); + } + return 0; + } + + public void setVolume(float volume) { + if (provider != null) { + provider.setVolume(volume); + } + } + + public int getErrorCode() { + if (provider != null) { + return provider.getErrorCode(); + } + return -1; + } } diff --git a/src/ru/nsu/ccfit/zuev/audio/BassAudioProvider.java b/src/ru/nsu/ccfit/zuev/audio/BassAudioProvider.java index 3dc8c56b..7eb5d710 100644 --- a/src/ru/nsu/ccfit/zuev/audio/BassAudioProvider.java +++ b/src/ru/nsu/ccfit/zuev/audio/BassAudioProvider.java @@ -12,198 +12,198 @@ */ public class BassAudioProvider { - public static final int DECODER_NORMAL = 0; - public static final int DECODER_DOUBLE_TIME = 1; - public static final int DECODER_NIGHT_CORE = 2; - public static final int WINDOW_FFT = 1024; - - private int channel = 0; - private BASS.FloatValue freq = new BASS.FloatValue(); - private int fileFlag = 0; - private int decoder = 0; - private int multiplier = 0; - - private ByteBuffer buffer = null; - - public BassAudioProvider() { - freq.value = 1.0f; - BASS.BASS_Init(-1, 44100, BASS.BASS_DEVICE_LATENCY); - BASS.BASS_SetConfig(BASS.BASS_CONFIG_DEV_BUFFER, 0); - // BASS.BASS_SetConfig(BASS.BASS_CONFIG_BUFFER, 100); - // BASS.BASS_SetConfig(BASS.BASS_CONFIG_UPDATEPERIOD, 10); - } - - public boolean prepare(final String fileName) { - free(); - if (fileName != null && fileName.length() > 0) { - channel = BASS.BASS_StreamCreateFile(fileName, 0, 0, fileFlag); // BASS.BASS_STREAM_DECODE - if (decoder > 0) { - channel = BASS_FX.BASS_FX_TempoCreate(channel, 0); - BASS.BASS_ChannelGetAttribute(channel, BASS.BASS_ATTRIB_FREQ, freq); - - if (decoder == DECODER_DOUBLE_TIME) { - float targetTempo = multiplier - 100.0f; - BASS.BASS_ChannelSetAttribute(channel, BASS.BASS_ATTRIB_FREQ, freq.value); - BASS.BASS_ChannelSetAttribute(channel, BASS_FX.BASS_ATTRIB_TEMPO, targetTempo); - - } else if (decoder == DECODER_NIGHT_CORE) { - float targetFreq = multiplier / 100.0f; - BASS.BASS_ChannelSetAttribute(channel, BASS.BASS_ATTRIB_FREQ, freq.value * targetFreq); - BASS.BASS_ChannelSetAttribute(channel, BASS_FX.BASS_ATTRIB_TEMPO, 1.0f); - } - } - } - return channel != 0; - } - - public boolean prepare(final AssetManager manager, final String assetName) { - free(); - if (manager != null && assetName != null && assetName.length() > 0) { - BASS.Asset asset = new BASS.Asset(manager, assetName); - channel = BASS.BASS_StreamCreateFile(asset, 0, 0, fileFlag); - if (decoder > 0) { - channel = BASS_FX.BASS_FX_TempoCreate(channel, 0); - BASS.BASS_ChannelGetAttribute(channel, BASS.BASS_ATTRIB_FREQ, freq); - - if (decoder == DECODER_DOUBLE_TIME) { - float targetTempo = multiplier - 100.0f; - BASS.BASS_ChannelSetAttribute(channel, BASS.BASS_ATTRIB_FREQ, freq.value); - BASS.BASS_ChannelSetAttribute(channel, BASS_FX.BASS_ATTRIB_TEMPO, targetTempo); - - } else if (decoder == DECODER_NIGHT_CORE) { - float targetFreq = multiplier / 100.0f; - BASS.BASS_ChannelSetAttribute(channel, BASS.BASS_ATTRIB_FREQ, freq.value * targetFreq); - BASS.BASS_ChannelSetAttribute(channel, BASS_FX.BASS_ATTRIB_TEMPO, 1.0f); - } - } - } - return channel != 0; - } - - public void play() { - if (channel != 0) { - if (BASS.BASS_ChannelIsActive(channel) == BASS.BASS_ACTIVE_PAUSED) { - BASS.BASS_ChannelPlay(channel, false); - } else { - BASS.BASS_ChannelPlay(channel, true); - } - } - } - - public void pause() { - if (channel != 0 && BASS.BASS_ChannelIsActive(channel) == BASS.BASS_ACTIVE_PLAYING) { - BASS.BASS_ChannelPause(channel); - } - } - - public void stop() { - if (channel != 0) { - BASS.BASS_ChannelStop(channel); - } - } - - public void seek(double sec) { - if (channel != 0) { - long playPos = BASS.BASS_ChannelSeconds2Bytes(channel, sec); - BASS.BASS_ChannelSetPosition(channel, playPos, BASS.BASS_POS_DECODETO); - } - } - - public void free() { - if (isPlaying()) { - stop(); - } - BASS.BASS_StreamFree(channel); - channel = 0; - } - - public float[] getSpectrum() { - if (!isPlaying()) { - return null; - } - if (buffer == null) { - buffer = ByteBuffer.allocateDirect(WINDOW_FFT << 1); - buffer.order(null); - } - BASS.BASS_ChannelGetData(channel, buffer, BASS.BASS_DATA_FFT1024); - - int resSize = WINDOW_FFT >> 1; - float[] spectrum = new float[resSize]; - buffer.asFloatBuffer().get(spectrum); - return spectrum; - } - - public int getErrorCode() { - return BASS.BASS_ErrorGetCode(); - } - - public Status getStatus() { - if (channel == 0) - return Status.STOPPED; - - final int playerStatus = BASS.BASS_ChannelIsActive(channel); - - if (playerStatus == BASS.BASS_ACTIVE_STOPPED) - return Status.STOPPED; - else if (playerStatus == BASS.BASS_ACTIVE_PLAYING) - return Status.PLAYING; - else if (playerStatus == BASS.BASS_ACTIVE_PAUSED) - return Status.PAUSED; - return Status.STALLED; - } - - public boolean isPlaying() { - return channel != 0 && BASS.BASS_ChannelIsActive(channel) == BASS.BASS_ACTIVE_PLAYING; - } - - public double getPosition() { - if (channel != 0) { - long pos = BASS.BASS_ChannelGetPosition(channel, BASS.BASS_POS_BYTE); - if (pos != -1) { - return BASS.BASS_ChannelBytes2Seconds(channel, pos); - } - } - return 0f; - } - - public double getLength() { - if (channel != 0) { - long length = BASS.BASS_ChannelGetLength(channel, BASS.BASS_POS_BYTE); - if (length != -1) { - return BASS.BASS_ChannelBytes2Seconds(channel, length); - } - } - return 0f; - } - - public void setLoop() { - fileFlag |= BASS.BASS_SAMPLE_LOOP; - } - - public void setUseSoftDecoder(int decoder) { - if (decoder > 0) { - this.fileFlag |= BASS.BASS_STREAM_DECODE; - } else { - this.fileFlag = 0; - } - this.decoder = decoder; - } - - public void setDecoderMultiplier(int multiplier) { - this.multiplier = multiplier; - } - - public float getVolume() { - BASS.FloatValue volume = new BASS.FloatValue(); - if (channel != 0) { - BASS.BASS_ChannelGetAttribute(channel, BASS.BASS_ATTRIB_VOL, volume); - } - return volume.value; - } - - public void setVolume(float volume) { - if (channel != 0) { - BASS.BASS_ChannelSetAttribute(channel, BASS.BASS_ATTRIB_VOL, volume); - } - } + public static final int DECODER_NORMAL = 0; + public static final int DECODER_DOUBLE_TIME = 1; + public static final int DECODER_NIGHT_CORE = 2; + public static final int WINDOW_FFT = 1024; + + private int channel = 0; + private BASS.FloatValue freq = new BASS.FloatValue(); + private int fileFlag = 0; + private int decoder = 0; + private int multiplier = 0; + + private ByteBuffer buffer = null; + + public BassAudioProvider() { + freq.value = 1.0f; + BASS.BASS_Init(-1, 44100, BASS.BASS_DEVICE_LATENCY); + BASS.BASS_SetConfig(BASS.BASS_CONFIG_DEV_BUFFER, 0); + // BASS.BASS_SetConfig(BASS.BASS_CONFIG_BUFFER, 100); + // BASS.BASS_SetConfig(BASS.BASS_CONFIG_UPDATEPERIOD, 10); + } + + public boolean prepare(final String fileName) { + free(); + if (fileName != null && fileName.length() > 0) { + channel = BASS.BASS_StreamCreateFile(fileName, 0, 0, fileFlag); // BASS.BASS_STREAM_DECODE + if (decoder > 0) { + channel = BASS_FX.BASS_FX_TempoCreate(channel, 0); + BASS.BASS_ChannelGetAttribute(channel, BASS.BASS_ATTRIB_FREQ, freq); + + if (decoder == DECODER_DOUBLE_TIME) { + float targetTempo = multiplier - 100.0f; + BASS.BASS_ChannelSetAttribute(channel, BASS.BASS_ATTRIB_FREQ, freq.value); + BASS.BASS_ChannelSetAttribute(channel, BASS_FX.BASS_ATTRIB_TEMPO, targetTempo); + + } else if (decoder == DECODER_NIGHT_CORE) { + float targetFreq = multiplier / 100.0f; + BASS.BASS_ChannelSetAttribute(channel, BASS.BASS_ATTRIB_FREQ, freq.value * targetFreq); + BASS.BASS_ChannelSetAttribute(channel, BASS_FX.BASS_ATTRIB_TEMPO, 1.0f); + } + } + } + return channel != 0; + } + + public boolean prepare(final AssetManager manager, final String assetName) { + free(); + if (manager != null && assetName != null && assetName.length() > 0) { + BASS.Asset asset = new BASS.Asset(manager, assetName); + channel = BASS.BASS_StreamCreateFile(asset, 0, 0, fileFlag); + if (decoder > 0) { + channel = BASS_FX.BASS_FX_TempoCreate(channel, 0); + BASS.BASS_ChannelGetAttribute(channel, BASS.BASS_ATTRIB_FREQ, freq); + + if (decoder == DECODER_DOUBLE_TIME) { + float targetTempo = multiplier - 100.0f; + BASS.BASS_ChannelSetAttribute(channel, BASS.BASS_ATTRIB_FREQ, freq.value); + BASS.BASS_ChannelSetAttribute(channel, BASS_FX.BASS_ATTRIB_TEMPO, targetTempo); + + } else if (decoder == DECODER_NIGHT_CORE) { + float targetFreq = multiplier / 100.0f; + BASS.BASS_ChannelSetAttribute(channel, BASS.BASS_ATTRIB_FREQ, freq.value * targetFreq); + BASS.BASS_ChannelSetAttribute(channel, BASS_FX.BASS_ATTRIB_TEMPO, 1.0f); + } + } + } + return channel != 0; + } + + public void play() { + if (channel != 0) { + if (BASS.BASS_ChannelIsActive(channel) == BASS.BASS_ACTIVE_PAUSED) { + BASS.BASS_ChannelPlay(channel, false); + } else { + BASS.BASS_ChannelPlay(channel, true); + } + } + } + + public void pause() { + if (channel != 0 && BASS.BASS_ChannelIsActive(channel) == BASS.BASS_ACTIVE_PLAYING) { + BASS.BASS_ChannelPause(channel); + } + } + + public void stop() { + if (channel != 0) { + BASS.BASS_ChannelStop(channel); + } + } + + public void seek(double sec) { + if (channel != 0) { + long playPos = BASS.BASS_ChannelSeconds2Bytes(channel, sec); + BASS.BASS_ChannelSetPosition(channel, playPos, BASS.BASS_POS_DECODETO); + } + } + + public void free() { + if (isPlaying()) { + stop(); + } + BASS.BASS_StreamFree(channel); + channel = 0; + } + + public float[] getSpectrum() { + if (!isPlaying()) { + return null; + } + if (buffer == null) { + buffer = ByteBuffer.allocateDirect(WINDOW_FFT << 1); + buffer.order(null); + } + BASS.BASS_ChannelGetData(channel, buffer, BASS.BASS_DATA_FFT1024); + + int resSize = WINDOW_FFT >> 1; + float[] spectrum = new float[resSize]; + buffer.asFloatBuffer().get(spectrum); + return spectrum; + } + + public int getErrorCode() { + return BASS.BASS_ErrorGetCode(); + } + + public Status getStatus() { + if (channel == 0) + return Status.STOPPED; + + final int playerStatus = BASS.BASS_ChannelIsActive(channel); + + if (playerStatus == BASS.BASS_ACTIVE_STOPPED) + return Status.STOPPED; + else if (playerStatus == BASS.BASS_ACTIVE_PLAYING) + return Status.PLAYING; + else if (playerStatus == BASS.BASS_ACTIVE_PAUSED) + return Status.PAUSED; + return Status.STALLED; + } + + public boolean isPlaying() { + return channel != 0 && BASS.BASS_ChannelIsActive(channel) == BASS.BASS_ACTIVE_PLAYING; + } + + public double getPosition() { + if (channel != 0) { + long pos = BASS.BASS_ChannelGetPosition(channel, BASS.BASS_POS_BYTE); + if (pos != -1) { + return BASS.BASS_ChannelBytes2Seconds(channel, pos); + } + } + return 0f; + } + + public double getLength() { + if (channel != 0) { + long length = BASS.BASS_ChannelGetLength(channel, BASS.BASS_POS_BYTE); + if (length != -1) { + return BASS.BASS_ChannelBytes2Seconds(channel, length); + } + } + return 0f; + } + + public void setLoop() { + fileFlag |= BASS.BASS_SAMPLE_LOOP; + } + + public void setUseSoftDecoder(int decoder) { + if (decoder > 0) { + this.fileFlag |= BASS.BASS_STREAM_DECODE; + } else { + this.fileFlag = 0; + } + this.decoder = decoder; + } + + public void setDecoderMultiplier(int multiplier) { + this.multiplier = multiplier; + } + + public float getVolume() { + BASS.FloatValue volume = new BASS.FloatValue(); + if (channel != 0) { + BASS.BASS_ChannelGetAttribute(channel, BASS.BASS_ATTRIB_VOL, volume); + } + return volume.value; + } + + public void setVolume(float volume) { + if (channel != 0) { + BASS.BASS_ChannelSetAttribute(channel, BASS.BASS_ATTRIB_VOL, volume); + } + } } diff --git a/src/ru/nsu/ccfit/zuev/audio/BassSoundProvider.java b/src/ru/nsu/ccfit/zuev/audio/BassSoundProvider.java index 75fad3a6..f2caefcd 100644 --- a/src/ru/nsu/ccfit/zuev/audio/BassSoundProvider.java +++ b/src/ru/nsu/ccfit/zuev/audio/BassSoundProvider.java @@ -11,59 +11,59 @@ */ public class BassSoundProvider { - private static final int SIMULTANEOUS_PLAYBACKS = 8; + private static final int SIMULTANEOUS_PLAYBACKS = 8; - private int sample = 0; - private int channel = 0; + private int sample = 0; + private int channel = 0; - public BassSoundProvider() { - BASS.BASS_Init(-1, 44100, BASS.BASS_DEVICE_LATENCY); - BASS.BASS_SetConfig(BASS.BASS_CONFIG_DEV_BUFFER, 0); - } + public BassSoundProvider() { + BASS.BASS_Init(-1, 44100, BASS.BASS_DEVICE_LATENCY); + BASS.BASS_SetConfig(BASS.BASS_CONFIG_DEV_BUFFER, 0); + } - public boolean prepare(final String fileName) { - free(); - if (fileName != null && fileName.length() > 0) { - sample = BASS.BASS_SampleLoad(fileName, 0, 0, SIMULTANEOUS_PLAYBACKS, BASS.BASS_SAMPLE_OVER_POS); - } - return sample != 0; - } + public boolean prepare(final String fileName) { + free(); + if (fileName != null && fileName.length() > 0) { + sample = BASS.BASS_SampleLoad(fileName, 0, 0, SIMULTANEOUS_PLAYBACKS, BASS.BASS_SAMPLE_OVER_POS); + } + return sample != 0; + } - public boolean prepare(final AssetManager manager, final String assetName) { - free(); - if (manager != null && assetName != null && assetName.length() > 0) { - BASS.Asset asset = new BASS.Asset(manager, assetName); - sample = BASS.BASS_SampleLoad(asset, 0, 0, SIMULTANEOUS_PLAYBACKS, BASS.BASS_SAMPLE_OVER_POS); - } - return sample != 0; - } + public boolean prepare(final AssetManager manager, final String assetName) { + free(); + if (manager != null && assetName != null && assetName.length() > 0) { + BASS.Asset asset = new BASS.Asset(manager, assetName); + sample = BASS.BASS_SampleLoad(asset, 0, 0, SIMULTANEOUS_PLAYBACKS, BASS.BASS_SAMPLE_OVER_POS); + } + return sample != 0; + } - public void play() { - play(Config.getSoundVolume()); - } + public void play() { + play(Config.getSoundVolume()); + } - public void play(float volume) { - if (sample != 0) { - channel = BASS.BASS_SampleGetChannel(sample, false); - BASS.BASS_ChannelSetAttribute(channel, BASS.BASS_ATTRIB_NOBUFFER, 1); - BASS.BASS_ChannelPlay(channel, false); - BASS.BASS_ChannelSetAttribute(channel, BASS.BASS_ATTRIB_VOL, volume * Config.getSoundVolume()); - } - } + public void play(float volume) { + if (sample != 0) { + channel = BASS.BASS_SampleGetChannel(sample, false); + BASS.BASS_ChannelSetAttribute(channel, BASS.BASS_ATTRIB_NOBUFFER, 1); + BASS.BASS_ChannelPlay(channel, false); + BASS.BASS_ChannelSetAttribute(channel, BASS.BASS_ATTRIB_VOL, volume * Config.getSoundVolume()); + } + } - public void stop() { - if (sample != 0) { - BASS.BASS_ChannelStop(channel); - } - } + public void stop() { + if (sample != 0) { + BASS.BASS_ChannelStop(channel); + } + } - public void free() { - stop(); - BASS.BASS_SampleFree(sample); - sample = 0; - } + public void free() { + stop(); + BASS.BASS_SampleFree(sample); + sample = 0; + } - public void setLooping(boolean looping) { - // not impl - } + public void setLooping(boolean looping) { + // not impl + } } diff --git a/src/ru/nsu/ccfit/zuev/audio/IMusicPlayer.java b/src/ru/nsu/ccfit/zuev/audio/IMusicPlayer.java index c74ed620..6b01b527 100644 --- a/src/ru/nsu/ccfit/zuev/audio/IMusicPlayer.java +++ b/src/ru/nsu/ccfit/zuev/audio/IMusicPlayer.java @@ -1,29 +1,29 @@ package ru.nsu.ccfit.zuev.audio; public interface IMusicPlayer { - void prepare(); + void prepare(); - void play(); + void play(); - void pause(); + void pause(); - void stop(); + void stop(); - void release(); + void release(); - Status getStatus(); + Status getStatus(); - int getPosition(); + int getPosition(); - int getLength(); + int getLength(); - void seekTo(int ms); + void seekTo(int ms); - void setUseSoftDecoder(int decoder); + void setUseSoftDecoder(int decoder); - void setDecoderMultiplier(int multiplier); + void setDecoderMultiplier(int multiplier); - float getVolume(); + float getVolume(); - void setVolume(float volume); -} \ No newline at end of file + void setVolume(float volume); +} diff --git a/src/ru/nsu/ccfit/zuev/audio/Status.java b/src/ru/nsu/ccfit/zuev/audio/Status.java index cd683b87..cb1388d0 100644 --- a/src/ru/nsu/ccfit/zuev/audio/Status.java +++ b/src/ru/nsu/ccfit/zuev/audio/Status.java @@ -5,8 +5,8 @@ */ public enum Status { - STOPPED, - PLAYING, - PAUSED, - STALLED + STOPPED, + PLAYING, + PAUSED, + STALLED } diff --git a/src/ru/nsu/ccfit/zuev/audio/effect/Metronome.java b/src/ru/nsu/ccfit/zuev/audio/effect/Metronome.java index ca775ec4..ff90feaf 100644 --- a/src/ru/nsu/ccfit/zuev/audio/effect/Metronome.java +++ b/src/ru/nsu/ccfit/zuev/audio/effect/Metronome.java @@ -6,53 +6,53 @@ public class Metronome { - private ResourceManager resources = ResourceManager.getInstance(); - - private BassSoundProvider kickSound = resources.getSound("nightcore-kick"); - private BassSoundProvider finishSound = resources.getSound("nightcore-finish"); - private BassSoundProvider clapSound = resources.getSound("nightcore-clap"); - private BassSoundProvider hatSound = resources.getSound("nightcore-hat"); - - private float volume = 1.0f; - private int lastBeatIndex = -1; - - public void update(float elapsedTime) { - if (elapsedTime - GameHelper.getTimingOffset() <= 0) { - return; - } - - float playSeconds = elapsedTime - GameHelper.getTimingOffset(); - int beatIndex = (int) (playSeconds * 2 / GameHelper.getBeatLength()); - - if (beatIndex < 0) { - return; - } - if (beatIndex == lastBeatIndex) { - return; - } - lastBeatIndex = beatIndex; - - int beatInBar = beatIndex % GameHelper.getTimeSignature(); - - // 每隔8小节在第4拍kick+finish - if (beatIndex % (8 * GameHelper.getTimeSignature()) == 0) { - kickSound.play(volume); - if (beatIndex > 0) { - finishSound.play(volume); - } - return; - } - // 每小节第4拍kick - if (beatInBar % 4 == 0) { - kickSound.play(volume); - return; - } - // 每小节第2拍clap - if (beatInBar % 4 == 2) { - clapSound.play(volume); - return; - } - // 每小节奇数拍hat - hatSound.play(volume); - } + private ResourceManager resources = ResourceManager.getInstance(); + + private BassSoundProvider kickSound = resources.getSound("nightcore-kick"); + private BassSoundProvider finishSound = resources.getSound("nightcore-finish"); + private BassSoundProvider clapSound = resources.getSound("nightcore-clap"); + private BassSoundProvider hatSound = resources.getSound("nightcore-hat"); + + private float volume = 1.0f; + private int lastBeatIndex = -1; + + public void update(float elapsedTime) { + if (elapsedTime - GameHelper.getTimingOffset() <= 0) { + return; + } + + float playSeconds = elapsedTime - GameHelper.getTimingOffset(); + int beatIndex = (int) (playSeconds * 2 / GameHelper.getBeatLength()); + + if (beatIndex < 0) { + return; + } + if (beatIndex == lastBeatIndex) { + return; + } + lastBeatIndex = beatIndex; + + int beatInBar = beatIndex % GameHelper.getTimeSignature(); + + // 每隔8小节在第4拍kick+finish + if (beatIndex % (8 * GameHelper.getTimeSignature()) == 0) { + kickSound.play(volume); + if (beatIndex > 0) { + finishSound.play(volume); + } + return; + } + // 每小节第4拍kick + if (beatInBar % 4 == 0) { + kickSound.play(volume); + return; + } + // 每小节第2拍clap + if (beatInBar % 4 == 2) { + clapSound.play(volume); + return; + } + // 每小节奇数拍hat + hatSound.play(volume); + } } diff --git a/src/ru/nsu/ccfit/zuev/audio/serviceAudio/BassAudioFunc.java b/src/ru/nsu/ccfit/zuev/audio/serviceAudio/BassAudioFunc.java index ce2045e4..511bd5e4 100644 --- a/src/ru/nsu/ccfit/zuev/audio/serviceAudio/BassAudioFunc.java +++ b/src/ru/nsu/ccfit/zuev/audio/serviceAudio/BassAudioFunc.java @@ -17,247 +17,247 @@ public class BassAudioFunc { - public static final int WINDOW_FFT = 1024; - - private int channel = 0; - private PlayMode mode; - private long skipPosition; - private ByteBuffer buffer = null; - private int playflag = BASS.BASS_STREAM_PRESCAN; - private boolean isGaming = false; - private BroadcastReceiver receiver; - private LocalBroadcastManager broadcastManager; - - BassAudioFunc() { - BASS.BASS_Init(-1, 44100, BASS.BASS_DEVICE_LATENCY); - BASS.BASS_SetConfig(BASS.BASS_CONFIG_DEV_BUFFER, 0); - } - - public boolean pause() { - return BASS.BASS_ChannelPause(channel); - } - - private boolean resume() { - return BASS.BASS_ChannelPlay(channel, false); - } - - public boolean preLoad(String filePath, PlayMode mode) { - Log.w("BassAudioFunc", "preLoad File: " + filePath); - BASS.BASS_CHANNELINFO fx = new BASS.BASS_CHANNELINFO(); - doClear(); - this.mode = mode; - switch (mode) { - case MODE_NONE: //None - channel = BASS.BASS_StreamCreateFile(filePath, 0, 0, playflag); - // BASS.BASS_ChannelSetAttribute(channel, BASS.BASS_ATTRIB_NOBUFFER, 1); - break; - case MODE_HT: //HT - channel = BASS.BASS_StreamCreateFile(filePath, 0, 0, BASS.BASS_STREAM_DECODE | BASS.BASS_STREAM_PRESCAN); - channel = BASS_FX.BASS_FX_TempoCreate(channel, BASS.BASS_STREAM_AUTOFREE); - // BASS.BASS_ChannelSetAttribute(channel, BASS.BASS_ATTRIB_NOBUFFER, 1); - BASS.BASS_ChannelSetAttribute(channel, BASS_FX.BASS_ATTRIB_TEMPO, -25.0f); - break; - case MODE_DT: //DT - channel = BASS.BASS_StreamCreateFile(filePath, 0, 0, BASS.BASS_STREAM_DECODE | BASS.BASS_STREAM_PRESCAN); - channel = BASS_FX.BASS_FX_TempoCreate(channel, BASS.BASS_STREAM_AUTOFREE); - // BASS.BASS_ChannelSetAttribute(channel, BASS.BASS_ATTRIB_NOBUFFER, 1); - BASS.BASS_ChannelSetAttribute(channel, BASS_FX.BASS_ATTRIB_TEMPO, 50.0f); - break; - case MODE_NC: //NC - channel = BASS.BASS_StreamCreateFile(filePath, 0, 0, BASS.BASS_STREAM_DECODE | BASS.BASS_STREAM_PRESCAN); - channel = BASS_FX.BASS_FX_TempoCreate(channel, BASS.BASS_STREAM_AUTOFREE); - // BASS.BASS_ChannelSetAttribute(channel, BASS.BASS_ATTRIB_NOBUFFER, 1); - - BASS.BASS_ChannelGetInfo(channel, fx); - BASS.BASS_ChannelSetAttribute(channel, BASS.BASS_ATTRIB_FREQ, (int) (fx.freq * 1.5)); - BASS.BASS_ChannelSetAttribute(channel, BASS_FX.BASS_ATTRIB_TEMPO, 0.0f); - break; - case MODE_SU: //SU - channel = BASS.BASS_StreamCreateFile(filePath, 0, 0, BASS.BASS_STREAM_DECODE | BASS.BASS_STREAM_PRESCAN); - channel = BASS_FX.BASS_FX_TempoCreate(channel, BASS.BASS_STREAM_AUTOFREE); - // BASS.BASS_ChannelSetAttribute(channel, BASS.BASS_ATTRIB_NOBUFFER, 1); - BASS.BASS_ChannelSetAttribute(channel, BASS_FX.BASS_ATTRIB_TEMPO, 25.0f); - break; - } - return channel != 0; - } - - public boolean preLoad(String filePath, float speed, boolean enableNC) { - if (speed == 1.0f) { - return preLoad(filePath, PlayMode.MODE_NONE); - } - Log.w("BassAudioFunc", "preLoad File: " + filePath); - BASS.BASS_CHANNELINFO fx = new BASS.BASS_CHANNELINFO(); - doClear(); - this.mode = PlayMode.MODE_SC; - channel = BASS.BASS_StreamCreateFile(filePath, 0, 0, BASS.BASS_STREAM_DECODE | BASS.BASS_STREAM_PRESCAN); - channel = BASS_FX.BASS_FX_TempoCreate(channel, BASS.BASS_STREAM_AUTOFREE); - if (enableNC) { - BASS.BASS_ChannelGetInfo(channel, fx); - if (speed > 1.5){ - BASS.BASS_ChannelSetAttribute(channel, BASS.BASS_ATTRIB_FREQ, (int) (fx.freq * 1.5f)); - BASS.BASS_ChannelSetAttribute(channel, BASS_FX.BASS_ATTRIB_TEMPO, (speed / 1.5f - 1.0f) * 100); - } - else if (speed < 0.75){ - BASS.BASS_ChannelSetAttribute(channel, BASS.BASS_ATTRIB_FREQ, (int) (fx.freq * 0.75f)); - BASS.BASS_ChannelSetAttribute(channel, BASS_FX.BASS_ATTRIB_TEMPO, (speed / 0.75f - 1.0f) * 100); - } - else { - BASS.BASS_ChannelSetAttribute(channel, BASS.BASS_ATTRIB_FREQ, (int) (fx.freq * speed)); - BASS.BASS_ChannelSetAttribute(channel, BASS_FX.BASS_ATTRIB_TEMPO, 0.0f); - } - } - else{ - BASS.BASS_ChannelSetAttribute(channel, BASS_FX.BASS_ATTRIB_TEMPO, (speed - 1.0f) * 100); - } - return channel != 0; - } - - public boolean play() { - if (channel != 0 && BASS.BASS_ChannelIsActive(channel) == BASS.BASS_ACTIVE_PAUSED) { - return resume(); - } else if (channel != 0) { - /*if(!isGaming){ - BASS.BASS_ChannelSetSync(channel, BASS.BASS_SYNC_END, 0, new BASS.SYNCPROC() { - @Override - public void SYNCPROC(int handle, int channel, int data, Object user) { - broadcastManager.sendBroadcast(new Intent("Notify_next")); - } - },0); - }*/ - BASS.BASS_ChannelSetSync(channel, BASS.BASS_SYNC_END, 0, new BASS.SYNCPROC() { - @Override - public void SYNCPROC(int handle, int channel, int data, Object user) { - if (!isGaming) { - broadcastManager.sendBroadcast(new Intent("Notify_next")); - } else { - stop(); - } - } - }, 0); - return BASS.BASS_ChannelPlay(channel, true); - } - return false; - } - - public boolean stop() { - if (channel != 0) { - BASS.BASS_ChannelStop(channel); - return BASS.BASS_StreamFree(channel); - } - return false; - } - - public boolean jump(int ms) { - if (channel != 0 && ms > 0) { - if (skipPosition == 0 || skipPosition == -1) - skipPosition = BASS.BASS_ChannelSeconds2Bytes(channel, ms / 1000.0); - if (mode == PlayMode.MODE_NONE) - return BASS.BASS_ChannelSetPosition(channel, skipPosition, BASS.BASS_POS_BYTE); - else return BASS.BASS_ChannelSetPosition(channel, skipPosition, BASS.BASS_POS_DECODE); - } - return false; - } - - public Status getStatus() { - if (channel == 0) return Status.STOPPED; - - switch (BASS.BASS_ChannelIsActive(channel)) { - case BASS.BASS_ACTIVE_STOPPED: - return Status.STOPPED; - case BASS.BASS_ACTIVE_PAUSED: - return Status.PAUSED; - case BASS.BASS_ACTIVE_PLAYING: - return Status.PLAYING; - } - - return Status.STALLED; - } - - public int getPosition() { - if (channel != 0) { - long pos = BASS.BASS_ChannelGetPosition(channel, BASS.BASS_POS_BYTE); - if (pos != -1) { - return (int) (BASS.BASS_ChannelBytes2Seconds(channel, pos) * 1000); - } - } - return 0; - } - - public int getLength() { - if (channel != 0) { - long length = BASS.BASS_ChannelGetLength(channel, BASS.BASS_POS_BYTE); - if (length != -1) { - return (int) (BASS.BASS_ChannelBytes2Seconds(channel, length) * 1000); - } - } - return 0; - } - - public float[] getSpectrum() { - if (BASS.BASS_ChannelIsActive(channel) != BASS.BASS_ACTIVE_PLAYING) { - return null; - } - if (buffer == null) { - buffer = ByteBuffer.allocateDirect(WINDOW_FFT << 1); - buffer.order(null); - } - BASS.BASS_ChannelGetData(channel, buffer, BASS.BASS_DATA_FFT1024); - int resSize = WINDOW_FFT >> 1; - float[] spectrum = new float[resSize]; - buffer.asFloatBuffer().get(spectrum); - return spectrum; - } - - private void doClear() { - if (channel != 0 && BASS.BASS_ChannelIsActive(channel) == BASS.BASS_ACTIVE_PLAYING) { - BASS.BASS_ChannelStop(channel); - } - BASS.BASS_StreamFree(channel); - skipPosition = 0; - } - - public void setLoop(boolean isLoop) { - if (isLoop) { - this.playflag = BASS.BASS_SAMPLE_LOOP | BASS.BASS_STREAM_PRESCAN; - } else { - this.playflag = BASS.BASS_STREAM_PRESCAN; - } - } - - public float getVolume() { - BASS.FloatValue volume = new BASS.FloatValue(); - if (channel != 0) { - BASS.BASS_ChannelGetAttribute(channel, BASS.BASS_ATTRIB_VOL, volume); - } - return volume.value; - } - - public void setVolume(float volume) { - if (channel != 0) { - BASS.BASS_ChannelSetAttribute(channel, BASS.BASS_ATTRIB_VOL, volume); - } - } - - public void setGaming(boolean isGaming) { - System.out.println("Audio Service Running In Game: " + isGaming); - this.isGaming = isGaming; - } - - public void setReciverStuff(BroadcastReceiver receiver, IntentFilter filter, Context context) { - this.receiver = receiver; - if (broadcastManager == null) { - broadcastManager = LocalBroadcastManager.getInstance(context); - broadcastManager.registerReceiver(receiver, filter); - } - } - - public void unregisterReceiverBM() { - if (broadcastManager != null) broadcastManager.unregisterReceiver(receiver); - } - - public void freeALL() { - BASS.BASS_Free(); - } + public static final int WINDOW_FFT = 1024; + + private int channel = 0; + private PlayMode mode; + private long skipPosition; + private ByteBuffer buffer = null; + private int playflag = BASS.BASS_STREAM_PRESCAN; + private boolean isGaming = false; + private BroadcastReceiver receiver; + private LocalBroadcastManager broadcastManager; + + BassAudioFunc() { + BASS.BASS_Init(-1, 44100, BASS.BASS_DEVICE_LATENCY); + BASS.BASS_SetConfig(BASS.BASS_CONFIG_DEV_BUFFER, 0); + } + + public boolean pause() { + return BASS.BASS_ChannelPause(channel); + } + + private boolean resume() { + return BASS.BASS_ChannelPlay(channel, false); + } + + public boolean preLoad(String filePath, PlayMode mode) { + Log.w("BassAudioFunc", "preLoad File: " + filePath); + BASS.BASS_CHANNELINFO fx = new BASS.BASS_CHANNELINFO(); + doClear(); + this.mode = mode; + switch (mode) { + case MODE_NONE: //None + channel = BASS.BASS_StreamCreateFile(filePath, 0, 0, playflag); + // BASS.BASS_ChannelSetAttribute(channel, BASS.BASS_ATTRIB_NOBUFFER, 1); + break; + case MODE_HT: //HT + channel = BASS.BASS_StreamCreateFile(filePath, 0, 0, BASS.BASS_STREAM_DECODE | BASS.BASS_STREAM_PRESCAN); + channel = BASS_FX.BASS_FX_TempoCreate(channel, BASS.BASS_STREAM_AUTOFREE); + // BASS.BASS_ChannelSetAttribute(channel, BASS.BASS_ATTRIB_NOBUFFER, 1); + BASS.BASS_ChannelSetAttribute(channel, BASS_FX.BASS_ATTRIB_TEMPO, -25.0f); + break; + case MODE_DT: //DT + channel = BASS.BASS_StreamCreateFile(filePath, 0, 0, BASS.BASS_STREAM_DECODE | BASS.BASS_STREAM_PRESCAN); + channel = BASS_FX.BASS_FX_TempoCreate(channel, BASS.BASS_STREAM_AUTOFREE); + // BASS.BASS_ChannelSetAttribute(channel, BASS.BASS_ATTRIB_NOBUFFER, 1); + BASS.BASS_ChannelSetAttribute(channel, BASS_FX.BASS_ATTRIB_TEMPO, 50.0f); + break; + case MODE_NC: //NC + channel = BASS.BASS_StreamCreateFile(filePath, 0, 0, BASS.BASS_STREAM_DECODE | BASS.BASS_STREAM_PRESCAN); + channel = BASS_FX.BASS_FX_TempoCreate(channel, BASS.BASS_STREAM_AUTOFREE); + // BASS.BASS_ChannelSetAttribute(channel, BASS.BASS_ATTRIB_NOBUFFER, 1); + + BASS.BASS_ChannelGetInfo(channel, fx); + BASS.BASS_ChannelSetAttribute(channel, BASS.BASS_ATTRIB_FREQ, (int) (fx.freq * 1.5)); + BASS.BASS_ChannelSetAttribute(channel, BASS_FX.BASS_ATTRIB_TEMPO, 0.0f); + break; + case MODE_SU: //SU + channel = BASS.BASS_StreamCreateFile(filePath, 0, 0, BASS.BASS_STREAM_DECODE | BASS.BASS_STREAM_PRESCAN); + channel = BASS_FX.BASS_FX_TempoCreate(channel, BASS.BASS_STREAM_AUTOFREE); + // BASS.BASS_ChannelSetAttribute(channel, BASS.BASS_ATTRIB_NOBUFFER, 1); + BASS.BASS_ChannelSetAttribute(channel, BASS_FX.BASS_ATTRIB_TEMPO, 25.0f); + break; + } + return channel != 0; + } + + public boolean preLoad(String filePath, float speed, boolean enableNC) { + if (speed == 1.0f) { + return preLoad(filePath, PlayMode.MODE_NONE); + } + Log.w("BassAudioFunc", "preLoad File: " + filePath); + BASS.BASS_CHANNELINFO fx = new BASS.BASS_CHANNELINFO(); + doClear(); + this.mode = PlayMode.MODE_SC; + channel = BASS.BASS_StreamCreateFile(filePath, 0, 0, BASS.BASS_STREAM_DECODE | BASS.BASS_STREAM_PRESCAN); + channel = BASS_FX.BASS_FX_TempoCreate(channel, BASS.BASS_STREAM_AUTOFREE); + if (enableNC) { + BASS.BASS_ChannelGetInfo(channel, fx); + if (speed > 1.5){ + BASS.BASS_ChannelSetAttribute(channel, BASS.BASS_ATTRIB_FREQ, (int) (fx.freq * 1.5f)); + BASS.BASS_ChannelSetAttribute(channel, BASS_FX.BASS_ATTRIB_TEMPO, (speed / 1.5f - 1.0f) * 100); + } + else if (speed < 0.75){ + BASS.BASS_ChannelSetAttribute(channel, BASS.BASS_ATTRIB_FREQ, (int) (fx.freq * 0.75f)); + BASS.BASS_ChannelSetAttribute(channel, BASS_FX.BASS_ATTRIB_TEMPO, (speed / 0.75f - 1.0f) * 100); + } + else { + BASS.BASS_ChannelSetAttribute(channel, BASS.BASS_ATTRIB_FREQ, (int) (fx.freq * speed)); + BASS.BASS_ChannelSetAttribute(channel, BASS_FX.BASS_ATTRIB_TEMPO, 0.0f); + } + } + else{ + BASS.BASS_ChannelSetAttribute(channel, BASS_FX.BASS_ATTRIB_TEMPO, (speed - 1.0f) * 100); + } + return channel != 0; + } + + public boolean play() { + if (channel != 0 && BASS.BASS_ChannelIsActive(channel) == BASS.BASS_ACTIVE_PAUSED) { + return resume(); + } else if (channel != 0) { + /*if(!isGaming){ + BASS.BASS_ChannelSetSync(channel, BASS.BASS_SYNC_END, 0, new BASS.SYNCPROC() { + @Override + public void SYNCPROC(int handle, int channel, int data, Object user) { + broadcastManager.sendBroadcast(new Intent("Notify_next")); + } + },0); + }*/ + BASS.BASS_ChannelSetSync(channel, BASS.BASS_SYNC_END, 0, new BASS.SYNCPROC() { + @Override + public void SYNCPROC(int handle, int channel, int data, Object user) { + if (!isGaming) { + broadcastManager.sendBroadcast(new Intent("Notify_next")); + } else { + stop(); + } + } + }, 0); + return BASS.BASS_ChannelPlay(channel, true); + } + return false; + } + + public boolean stop() { + if (channel != 0) { + BASS.BASS_ChannelStop(channel); + return BASS.BASS_StreamFree(channel); + } + return false; + } + + public boolean jump(int ms) { + if (channel != 0 && ms > 0) { + if (skipPosition == 0 || skipPosition == -1) + skipPosition = BASS.BASS_ChannelSeconds2Bytes(channel, ms / 1000.0); + if (mode == PlayMode.MODE_NONE) + return BASS.BASS_ChannelSetPosition(channel, skipPosition, BASS.BASS_POS_BYTE); + else return BASS.BASS_ChannelSetPosition(channel, skipPosition, BASS.BASS_POS_DECODE); + } + return false; + } + + public Status getStatus() { + if (channel == 0) return Status.STOPPED; + + switch (BASS.BASS_ChannelIsActive(channel)) { + case BASS.BASS_ACTIVE_STOPPED: + return Status.STOPPED; + case BASS.BASS_ACTIVE_PAUSED: + return Status.PAUSED; + case BASS.BASS_ACTIVE_PLAYING: + return Status.PLAYING; + } + + return Status.STALLED; + } + + public int getPosition() { + if (channel != 0) { + long pos = BASS.BASS_ChannelGetPosition(channel, BASS.BASS_POS_BYTE); + if (pos != -1) { + return (int) (BASS.BASS_ChannelBytes2Seconds(channel, pos) * 1000); + } + } + return 0; + } + + public int getLength() { + if (channel != 0) { + long length = BASS.BASS_ChannelGetLength(channel, BASS.BASS_POS_BYTE); + if (length != -1) { + return (int) (BASS.BASS_ChannelBytes2Seconds(channel, length) * 1000); + } + } + return 0; + } + + public float[] getSpectrum() { + if (BASS.BASS_ChannelIsActive(channel) != BASS.BASS_ACTIVE_PLAYING) { + return null; + } + if (buffer == null) { + buffer = ByteBuffer.allocateDirect(WINDOW_FFT << 1); + buffer.order(null); + } + BASS.BASS_ChannelGetData(channel, buffer, BASS.BASS_DATA_FFT1024); + int resSize = WINDOW_FFT >> 1; + float[] spectrum = new float[resSize]; + buffer.asFloatBuffer().get(spectrum); + return spectrum; + } + + private void doClear() { + if (channel != 0 && BASS.BASS_ChannelIsActive(channel) == BASS.BASS_ACTIVE_PLAYING) { + BASS.BASS_ChannelStop(channel); + } + BASS.BASS_StreamFree(channel); + skipPosition = 0; + } + + public void setLoop(boolean isLoop) { + if (isLoop) { + this.playflag = BASS.BASS_SAMPLE_LOOP | BASS.BASS_STREAM_PRESCAN; + } else { + this.playflag = BASS.BASS_STREAM_PRESCAN; + } + } + + public float getVolume() { + BASS.FloatValue volume = new BASS.FloatValue(); + if (channel != 0) { + BASS.BASS_ChannelGetAttribute(channel, BASS.BASS_ATTRIB_VOL, volume); + } + return volume.value; + } + + public void setVolume(float volume) { + if (channel != 0) { + BASS.BASS_ChannelSetAttribute(channel, BASS.BASS_ATTRIB_VOL, volume); + } + } + + public void setGaming(boolean isGaming) { + System.out.println("Audio Service Running In Game: " + isGaming); + this.isGaming = isGaming; + } + + public void setReciverStuff(BroadcastReceiver receiver, IntentFilter filter, Context context) { + this.receiver = receiver; + if (broadcastManager == null) { + broadcastManager = LocalBroadcastManager.getInstance(context); + broadcastManager.registerReceiver(receiver, filter); + } + } + + public void unregisterReceiverBM() { + if (broadcastManager != null) broadcastManager.unregisterReceiver(receiver); + } + + public void freeALL() { + BASS.BASS_Free(); + } } diff --git a/src/ru/nsu/ccfit/zuev/audio/serviceAudio/PlayMode.java b/src/ru/nsu/ccfit/zuev/audio/serviceAudio/PlayMode.java index 013be914..eb79315a 100644 --- a/src/ru/nsu/ccfit/zuev/audio/serviceAudio/PlayMode.java +++ b/src/ru/nsu/ccfit/zuev/audio/serviceAudio/PlayMode.java @@ -2,11 +2,11 @@ public enum PlayMode { - MODE_NC, - MODE_DT, - MODE_HT, - MODE_SU, - MODE_SC, - MODE_NONE + MODE_NC, + MODE_DT, + MODE_HT, + MODE_SU, + MODE_SC, + MODE_NONE } diff --git a/src/ru/nsu/ccfit/zuev/audio/serviceAudio/SaveServiceObject.java b/src/ru/nsu/ccfit/zuev/audio/serviceAudio/SaveServiceObject.java index 12af2a43..1befd43f 100644 --- a/src/ru/nsu/ccfit/zuev/audio/serviceAudio/SaveServiceObject.java +++ b/src/ru/nsu/ccfit/zuev/audio/serviceAudio/SaveServiceObject.java @@ -11,72 +11,72 @@ public class SaveServiceObject extends Application { - static private SongService songService; - private String string = "NONONNOONONO"; - - public static void finishAllActivities() { - if (GlobalManager.getInstance().getMainActivity() != null) - GlobalManager.getInstance().getMainActivity().finish(); - } - - public String getString() { - return string; - } - - public void setString(String string) { - this.string = string; - } - - public SongService getSongService() { - return songService; - } - - public void setSongService(SongService object) { - songService = object; - if (songService != null) { - System.out.println("SongService Created!"); - } else { - System.out.println("SongService is NULL"); - } - } - - @Override - public void onCreate() { - super.onCreate(); - Thread.setDefaultUncaughtExceptionHandler(AppException.getAppExceptionHandler()); - registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() { - @Override - public void onActivityCreated(Activity activity, Bundle savedInstanceState) { - } - - @Override - public void onActivityStarted(Activity activity) { - } - - @Override - public void onActivityResumed(Activity activity) { - } - - @Override - public void onActivityPaused(Activity activity) { - } - - @Override - public void onActivityStopped(Activity activity) { - } - - @Override - public void onActivitySaveInstanceState(Activity activity, Bundle outState) { - } - - @Override - public void onActivityDestroyed(Activity activity) { - Log.w("onActivityDestroyed", "I'm going to Dead O_x"); - if (songService != null) { - Log.w("onActivityDestroyed", "I'm Dead x_x"); - songService.hideNotifyPanel(); - } - } - }); - } + static private SongService songService; + private String string = "NONONNOONONO"; + + public static void finishAllActivities() { + if (GlobalManager.getInstance().getMainActivity() != null) + GlobalManager.getInstance().getMainActivity().finish(); + } + + public String getString() { + return string; + } + + public void setString(String string) { + this.string = string; + } + + public SongService getSongService() { + return songService; + } + + public void setSongService(SongService object) { + songService = object; + if (songService != null) { + System.out.println("SongService Created!"); + } else { + System.out.println("SongService is NULL"); + } + } + + @Override + public void onCreate() { + super.onCreate(); + Thread.setDefaultUncaughtExceptionHandler(AppException.getAppExceptionHandler()); + registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() { + @Override + public void onActivityCreated(Activity activity, Bundle savedInstanceState) { + } + + @Override + public void onActivityStarted(Activity activity) { + } + + @Override + public void onActivityResumed(Activity activity) { + } + + @Override + public void onActivityPaused(Activity activity) { + } + + @Override + public void onActivityStopped(Activity activity) { + } + + @Override + public void onActivitySaveInstanceState(Activity activity, Bundle outState) { + } + + @Override + public void onActivityDestroyed(Activity activity) { + Log.w("onActivityDestroyed", "I'm going to Dead O_x"); + if (songService != null) { + Log.w("onActivityDestroyed", "I'm Dead x_x"); + songService.hideNotifyPanel(); + } + } + }); + } } diff --git a/src/ru/nsu/ccfit/zuev/audio/serviceAudio/SongService.java b/src/ru/nsu/ccfit/zuev/audio/serviceAudio/SongService.java index 0c1794b5..cdb49b1c 100644 --- a/src/ru/nsu/ccfit/zuev/audio/serviceAudio/SongService.java +++ b/src/ru/nsu/ccfit/zuev/audio/serviceAudio/SongService.java @@ -29,368 +29,368 @@ public class SongService extends Service { - private BassAudioFunc audioFunc; - private NotificationManager manager; - private Notification notification; - private RemoteViews notifyView_Small; - private boolean showingNotify = false; - private String backgroundPath = " "; - private boolean isGaming = false; - // private boolean isSettingMenu = false; - private IntentFilter filter = null; - private BroadcastReceiver onNotifyButtonClick = null; - private long lastHit = 0; - private static final String CHANNEL_ID = "ru.nsu.ccfit.zuev.audio"; - - @Override - public IBinder onBind(Intent intent) { - if (audioFunc == null) { - audioFunc = new BassAudioFunc(); - if (Build.VERSION.SDK_INT > 10) onCreateNotifyReceiver(); - } - return new ReturnBindObject(); - } - - @Override - public boolean onUnbind(Intent intent) { - System.out.println("Service unbind"); - hideNotifyPanel(); - exit(); - return super.onUnbind(intent); - } - - @Override - public void onRebind(Intent intent) { - super.onRebind(intent); - System.out.println("onReBind"); - } - - public boolean preLoad(String filePath, PlayMode mode, boolean isLoop) { - if (checkFileExist(filePath)) { - if (audioFunc == null) return false; - if (isLoop) { - audioFunc.setLoop(isLoop); - } - return audioFunc.preLoad(filePath, mode); - } - return false; - } - - public boolean preLoad(String filePath) { - return preLoad(filePath, PlayMode.MODE_NONE, false); - } - - public boolean preLoad(String filePath, PlayMode mode) { - return preLoad(filePath, mode, false); - } - - public boolean preLoad(String filePath, float speed, boolean enableNC) { - if (checkFileExist(filePath)) { - if (audioFunc == null) return false; - audioFunc.setLoop(false); - return audioFunc.preLoad(filePath, speed, enableNC); - } - return false; - } - - public boolean preLoadWithLoop(String filePath) { - return preLoad(filePath, PlayMode.MODE_NONE, true); - } - - public void play() { - if (audioFunc == null) return; - audioFunc.play(); - updateStatus(); - } - - public void pause() { - if (audioFunc == null) return; - audioFunc.pause(); - updateStatus(); - } - - public boolean stop() { - if (audioFunc == null) return false; - updateStatus(); - return audioFunc.stop(); - } - - public boolean exit() { - Log.w("SongService", "Hei Service is on EXIT()"); - if (audioFunc == null) return false; - audioFunc.stop(); - audioFunc.unregisterReceiverBM(); - audioFunc.freeALL(); - if (Build.VERSION.SDK_INT > 10) { - unregisterReceiver(onNotifyButtonClick); - stopForeground(true); - } - stopSelf(); - return true; - } - - public void seekTo(int time) { - if (audioFunc == null) return; - System.out.println(audioFunc.jump(time)); - } - - public boolean isGaming() { - return isGaming; - } - - public void setGaming(boolean isGaming) { - audioFunc.setGaming(isGaming); - if (!isGaming && showingNotify) { - hideNotifyPanel(); - } - Log.w("Gaming Mode", "In Gamming mode :" + isGaming); - this.isGaming = isGaming; - } - - /* - public boolean isSettingMenu() { - return isSettingMenu; - } - - public void setIsSettingMenu(boolean isSettingMenu) { - this.isSettingMenu = isSettingMenu; - } */ - - public Status getStatus() { - if (audioFunc != null) { - return audioFunc.getStatus(); - } - return Status.STOPPED; - } - - public int getPosition() { - if (audioFunc != null) { - return audioFunc.getPosition(); - } - return 0; - } - - public int getLength() { - if (audioFunc != null) { - return audioFunc.getLength(); - } - return 0; - } - - public float[] getSpectrum() { - if (audioFunc != null) { - return audioFunc.getSpectrum(); - } - return new float[0]; - } - - public float getVolume() { - if (audioFunc != null) { - return audioFunc.getVolume(); - } - return 0; - } - - public void setVolume(float volume) { - if (audioFunc != null) { - audioFunc.setVolume(volume); - } - } - - //Notify相关处理 - public void showNotifyPanel() { - if (this.isGaming) { - Log.w("SongService", "NOT SHOW THE NOTIFY CUZ IS GAMING"); - return; - } - - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { - NotificationChannel channel = new NotificationChannel(CHANNEL_ID, "osu!droid AudioService", NotificationManager.IMPORTANCE_DEFAULT); - channel.setDescription("AudioService for osu!droid"); - NotificationManager notificationManager = getSystemService(NotificationManager.class); - notificationManager.createNotificationChannel(channel); - } - - if (notification == null) createNotifyPanel(); - startForeground(9, notification); - manager.notify(9, notification); - showingNotify = true; - } - - public boolean hideNotifyPanel() { - if (!showingNotify) return false; - if (notification != null) { - showingNotify = false; - } - stopForeground(true); - return true; - } - - public void setReceiverStuff(BroadcastReceiver receiver, IntentFilter filter) { - if (audioFunc != null) audioFunc.setReciverStuff(receiver, filter, this); - } - - public void updateTitleText(String title, String artist) { - if (notification == null) return; - notifyView_Small.setTextViewText(R.id.notify_small_title, title); - notifyView_Small.setTextViewText(R.id.notify_small_artist, artist); - showNotifyPanel(); - } - - public void updateStatus() { - if (notification == null) return; - switch (getStatus()) { - case PLAYING: - notifyView_Small.setImageViewResource(R.id.notify_small_play, R.drawable.notify_pause); - break; - case PAUSED: - notifyView_Small.setImageViewResource(R.id.notify_small_play, R.drawable.notify_play); - break; - case STOPPED: - notifyView_Small.setImageViewResource(R.id.notify_small_play, R.drawable.notify_stop); - break; - } - showNotifyPanel(); - } - - public void updateCoverImage(String backgroundPath) { - if (notification == null) return; - if (backgroundPath == null || backgroundPath.trim().equals("") || !checkFileExist(backgroundPath)) { - notifyView_Small.setImageViewResource(R.id.notify_small_icon, R.drawable.osut); - return; - } - this.backgroundPath = backgroundPath; - BitmapFactory.Options options = new BitmapFactory.Options(); - options.inSampleSize = 8; - if(Config.isSafeBeatmapBg()) { - File bg; - if ((bg = new File(Config.getSkinPath() + "menu-background.png")).exists() - || (bg = new File(Config.getSkinPath() + "menu-background.jpg")).exists()) { - notifyView_Small.setImageViewBitmap(R.id.notify_small_icon, BitmapFactory.decodeFile(bg.getAbsolutePath(), options)); - }else { - notifyView_Small.setImageViewResource(R.id.notify_small_icon, R.drawable.osut); - } - }else { - notifyView_Small.setImageViewBitmap(R.id.notify_small_icon, BitmapFactory.decodeFile(backgroundPath, options)); - } - - showNotifyPanel(); - } - - private void createNotifyPanel() { - manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); - - //创建Notify的布局 - notifyView_Small = new RemoteViews(getPackageName(), R.layout.notify_small_layout); - notifyView_Small.setImageViewResource(R.id.notify_small_icon, R.drawable.notify_icon); - - Intent intent = new Intent(SongService.this, MainActivity.class); - intent.setAction(Intent.ACTION_MAIN); - intent.addCategory(Intent.CATEGORY_LAUNCHER); - PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent, 0); - - //Notify按钮的事件设置 - notifyView_Small.setOnClickPendingIntent(R.id.notify_small_up, PendingIntent.getBroadcast(getApplicationContext(), 0, new Intent("Notify_up"), 0)); - notifyView_Small.setOnClickPendingIntent(R.id.notify_small_play, PendingIntent.getBroadcast(getApplicationContext(), 0, new Intent("Notify_play"), 0)); - notifyView_Small.setOnClickPendingIntent(R.id.notify_small_next, PendingIntent.getBroadcast(getApplicationContext(), 0, new Intent("Notify_next"), 0)); - notifyView_Small.setOnClickPendingIntent(R.id.notify_small_cancel, PendingIntent.getBroadcast(getApplicationContext(), 0, new Intent("Notify_cancel"), 0)); - notifyView_Small.setOnClickPendingIntent(R.id.notify_small_icon, pendingIntent); - - //开始创建Notify - NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID) - .setPriority(NotificationCompat.PRIORITY_DEFAULT) - .setTicker("Background playing~ ///w///") - .setSmallIcon(R.drawable.notify_inso) - .setOngoing(true); - notification = builder.build(); - notification.contentView = notifyView_Small; - //notification.contentIntent = pendingIntent; - notification.flags = Notification.FLAG_FOREGROUND_SERVICE; - } - - public boolean checkFileExist(String path) { - if (path == null) return false; - if (path.trim().equals("")) return false; - else { - File songFile = new File(path); - if (!songFile.exists()) return false; - } - return true; - } - - private void onCreateNotifyReceiver() { - if (this.filter == null) { - filter = new IntentFilter(); - filter.addAction("Notify_up"); - filter.addAction("Notify_play"); - filter.addAction("Notify_pause"); - filter.addAction("Notify_stop"); - filter.addAction("Notify_next"); - } - - onNotifyButtonClick = new BroadcastReceiver() { - @Override - public void onReceive(Context context, Intent intent) { - if (isRunningForeground()) return; - if (lastHit == 0) { - lastHit = System.currentTimeMillis(); - } else { - if (System.currentTimeMillis() - lastHit <= 1000) { - return; - } - } - lastHit = System.currentTimeMillis(); - if (intent.getAction().equals("Notify_play")) { - if (getStatus() == Status.PLAYING) pause(); - else { - play(); - } - } else if (intent.getAction().equals("Notify_next")) { - if (isRunningForeground()) return; - - stop(); - BeatmapInfo tempBeatmap = LibraryManager.getInstance().getNextBeatmap(); - preLoad(tempBeatmap.getMusic()); - updateCoverImage(tempBeatmap.getTrack(0).getBackground()); - - if (tempBeatmap.getArtistUnicode() != null && tempBeatmap.getTitleUnicode() != null && !Config.isForceRomanized()) { - updateTitleText(tempBeatmap.getTitleUnicode(), tempBeatmap.getArtistUnicode()); - }else if (tempBeatmap.getArtist() != null && tempBeatmap.getTitle() != null && Config.isForceRomanized()) { - updateTitleText(tempBeatmap.getTitle(), tempBeatmap.getArtist()); - } - - play(); - } else { - if (isRunningForeground()) return; - stop(); - BeatmapInfo tempBeatmap = LibraryManager.getInstance().getPrevBeatmap(); - preLoad(tempBeatmap.getMusic()); - updateCoverImage(tempBeatmap.getTrack(0).getBackground()); - - if (tempBeatmap.getArtistUnicode() != null && tempBeatmap.getTitleUnicode() != null && !Config.isForceRomanized()) { - updateTitleText(tempBeatmap.getTitleUnicode(), tempBeatmap.getArtistUnicode()); - }else if (tempBeatmap.getArtist() != null && tempBeatmap.getTitle() != null && Config.isForceRomanized()) { - updateTitleText(tempBeatmap.getTitle(), tempBeatmap.getArtist()); - } - - play(); - } - } - }; - - registerReceiver(onNotifyButtonClick, filter); - - setReceiverStuff(onNotifyButtonClick, filter); - } - - public boolean isRunningForeground() { - return MainActivity.isActivityVisible(); - } - - public class ReturnBindObject extends Binder { - public SongService getObject() { - return SongService.this; - } - } + private BassAudioFunc audioFunc; + private NotificationManager manager; + private Notification notification; + private RemoteViews notifyView_Small; + private boolean showingNotify = false; + private String backgroundPath = " "; + private boolean isGaming = false; + // private boolean isSettingMenu = false; + private IntentFilter filter = null; + private BroadcastReceiver onNotifyButtonClick = null; + private long lastHit = 0; + private static final String CHANNEL_ID = "ru.nsu.ccfit.zuev.audio"; + + @Override + public IBinder onBind(Intent intent) { + if (audioFunc == null) { + audioFunc = new BassAudioFunc(); + if (Build.VERSION.SDK_INT > 10) onCreateNotifyReceiver(); + } + return new ReturnBindObject(); + } + + @Override + public boolean onUnbind(Intent intent) { + System.out.println("Service unbind"); + hideNotifyPanel(); + exit(); + return super.onUnbind(intent); + } + + @Override + public void onRebind(Intent intent) { + super.onRebind(intent); + System.out.println("onReBind"); + } + + public boolean preLoad(String filePath, PlayMode mode, boolean isLoop) { + if (checkFileExist(filePath)) { + if (audioFunc == null) return false; + if (isLoop) { + audioFunc.setLoop(isLoop); + } + return audioFunc.preLoad(filePath, mode); + } + return false; + } + + public boolean preLoad(String filePath) { + return preLoad(filePath, PlayMode.MODE_NONE, false); + } + + public boolean preLoad(String filePath, PlayMode mode) { + return preLoad(filePath, mode, false); + } + + public boolean preLoad(String filePath, float speed, boolean enableNC) { + if (checkFileExist(filePath)) { + if (audioFunc == null) return false; + audioFunc.setLoop(false); + return audioFunc.preLoad(filePath, speed, enableNC); + } + return false; + } + + public boolean preLoadWithLoop(String filePath) { + return preLoad(filePath, PlayMode.MODE_NONE, true); + } + + public void play() { + if (audioFunc == null) return; + audioFunc.play(); + updateStatus(); + } + + public void pause() { + if (audioFunc == null) return; + audioFunc.pause(); + updateStatus(); + } + + public boolean stop() { + if (audioFunc == null) return false; + updateStatus(); + return audioFunc.stop(); + } + + public boolean exit() { + Log.w("SongService", "Hei Service is on EXIT()"); + if (audioFunc == null) return false; + audioFunc.stop(); + audioFunc.unregisterReceiverBM(); + audioFunc.freeALL(); + if (Build.VERSION.SDK_INT > 10) { + unregisterReceiver(onNotifyButtonClick); + stopForeground(true); + } + stopSelf(); + return true; + } + + public void seekTo(int time) { + if (audioFunc == null) return; + System.out.println(audioFunc.jump(time)); + } + + public boolean isGaming() { + return isGaming; + } + + public void setGaming(boolean isGaming) { + audioFunc.setGaming(isGaming); + if (!isGaming && showingNotify) { + hideNotifyPanel(); + } + Log.w("Gaming Mode", "In Gamming mode :" + isGaming); + this.isGaming = isGaming; + } + + /* + public boolean isSettingMenu() { + return isSettingMenu; + } + + public void setIsSettingMenu(boolean isSettingMenu) { + this.isSettingMenu = isSettingMenu; + } */ + + public Status getStatus() { + if (audioFunc != null) { + return audioFunc.getStatus(); + } + return Status.STOPPED; + } + + public int getPosition() { + if (audioFunc != null) { + return audioFunc.getPosition(); + } + return 0; + } + + public int getLength() { + if (audioFunc != null) { + return audioFunc.getLength(); + } + return 0; + } + + public float[] getSpectrum() { + if (audioFunc != null) { + return audioFunc.getSpectrum(); + } + return new float[0]; + } + + public float getVolume() { + if (audioFunc != null) { + return audioFunc.getVolume(); + } + return 0; + } + + public void setVolume(float volume) { + if (audioFunc != null) { + audioFunc.setVolume(volume); + } + } + + //Notify相关处理 + public void showNotifyPanel() { + if (this.isGaming) { + Log.w("SongService", "NOT SHOW THE NOTIFY CUZ IS GAMING"); + return; + } + + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { + NotificationChannel channel = new NotificationChannel(CHANNEL_ID, "osu!droid AudioService", NotificationManager.IMPORTANCE_DEFAULT); + channel.setDescription("AudioService for osu!droid"); + NotificationManager notificationManager = getSystemService(NotificationManager.class); + notificationManager.createNotificationChannel(channel); + } + + if (notification == null) createNotifyPanel(); + startForeground(9, notification); + manager.notify(9, notification); + showingNotify = true; + } + + public boolean hideNotifyPanel() { + if (!showingNotify) return false; + if (notification != null) { + showingNotify = false; + } + stopForeground(true); + return true; + } + + public void setReceiverStuff(BroadcastReceiver receiver, IntentFilter filter) { + if (audioFunc != null) audioFunc.setReciverStuff(receiver, filter, this); + } + + public void updateTitleText(String title, String artist) { + if (notification == null) return; + notifyView_Small.setTextViewText(R.id.notify_small_title, title); + notifyView_Small.setTextViewText(R.id.notify_small_artist, artist); + showNotifyPanel(); + } + + public void updateStatus() { + if (notification == null) return; + switch (getStatus()) { + case PLAYING: + notifyView_Small.setImageViewResource(R.id.notify_small_play, R.drawable.notify_pause); + break; + case PAUSED: + notifyView_Small.setImageViewResource(R.id.notify_small_play, R.drawable.notify_play); + break; + case STOPPED: + notifyView_Small.setImageViewResource(R.id.notify_small_play, R.drawable.notify_stop); + break; + } + showNotifyPanel(); + } + + public void updateCoverImage(String backgroundPath) { + if (notification == null) return; + if (backgroundPath == null || backgroundPath.trim().equals("") || !checkFileExist(backgroundPath)) { + notifyView_Small.setImageViewResource(R.id.notify_small_icon, R.drawable.osut); + return; + } + this.backgroundPath = backgroundPath; + BitmapFactory.Options options = new BitmapFactory.Options(); + options.inSampleSize = 8; + if(Config.isSafeBeatmapBg()) { + File bg; + if ((bg = new File(Config.getSkinPath() + "menu-background.png")).exists() + || (bg = new File(Config.getSkinPath() + "menu-background.jpg")).exists()) { + notifyView_Small.setImageViewBitmap(R.id.notify_small_icon, BitmapFactory.decodeFile(bg.getAbsolutePath(), options)); + }else { + notifyView_Small.setImageViewResource(R.id.notify_small_icon, R.drawable.osut); + } + }else { + notifyView_Small.setImageViewBitmap(R.id.notify_small_icon, BitmapFactory.decodeFile(backgroundPath, options)); + } + + showNotifyPanel(); + } + + private void createNotifyPanel() { + manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); + + //创建Notify的布局 + notifyView_Small = new RemoteViews(getPackageName(), R.layout.notify_small_layout); + notifyView_Small.setImageViewResource(R.id.notify_small_icon, R.drawable.notify_icon); + + Intent intent = new Intent(SongService.this, MainActivity.class); + intent.setAction(Intent.ACTION_MAIN); + intent.addCategory(Intent.CATEGORY_LAUNCHER); + PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent, 0); + + //Notify按钮的事件设置 + notifyView_Small.setOnClickPendingIntent(R.id.notify_small_up, PendingIntent.getBroadcast(getApplicationContext(), 0, new Intent("Notify_up"), 0)); + notifyView_Small.setOnClickPendingIntent(R.id.notify_small_play, PendingIntent.getBroadcast(getApplicationContext(), 0, new Intent("Notify_play"), 0)); + notifyView_Small.setOnClickPendingIntent(R.id.notify_small_next, PendingIntent.getBroadcast(getApplicationContext(), 0, new Intent("Notify_next"), 0)); + notifyView_Small.setOnClickPendingIntent(R.id.notify_small_cancel, PendingIntent.getBroadcast(getApplicationContext(), 0, new Intent("Notify_cancel"), 0)); + notifyView_Small.setOnClickPendingIntent(R.id.notify_small_icon, pendingIntent); + + //开始创建Notify + NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID) + .setPriority(NotificationCompat.PRIORITY_DEFAULT) + .setTicker("Background playing~ ///w///") + .setSmallIcon(R.drawable.notify_inso) + .setOngoing(true); + notification = builder.build(); + notification.contentView = notifyView_Small; + //notification.contentIntent = pendingIntent; + notification.flags = Notification.FLAG_FOREGROUND_SERVICE; + } + + public boolean checkFileExist(String path) { + if (path == null) return false; + if (path.trim().equals("")) return false; + else { + File songFile = new File(path); + if (!songFile.exists()) return false; + } + return true; + } + + private void onCreateNotifyReceiver() { + if (this.filter == null) { + filter = new IntentFilter(); + filter.addAction("Notify_up"); + filter.addAction("Notify_play"); + filter.addAction("Notify_pause"); + filter.addAction("Notify_stop"); + filter.addAction("Notify_next"); + } + + onNotifyButtonClick = new BroadcastReceiver() { + @Override + public void onReceive(Context context, Intent intent) { + if (isRunningForeground()) return; + if (lastHit == 0) { + lastHit = System.currentTimeMillis(); + } else { + if (System.currentTimeMillis() - lastHit <= 1000) { + return; + } + } + lastHit = System.currentTimeMillis(); + if (intent.getAction().equals("Notify_play")) { + if (getStatus() == Status.PLAYING) pause(); + else { + play(); + } + } else if (intent.getAction().equals("Notify_next")) { + if (isRunningForeground()) return; + + stop(); + BeatmapInfo tempBeatmap = LibraryManager.getInstance().getNextBeatmap(); + preLoad(tempBeatmap.getMusic()); + updateCoverImage(tempBeatmap.getTrack(0).getBackground()); + + if (tempBeatmap.getArtistUnicode() != null && tempBeatmap.getTitleUnicode() != null && !Config.isForceRomanized()) { + updateTitleText(tempBeatmap.getTitleUnicode(), tempBeatmap.getArtistUnicode()); + }else if (tempBeatmap.getArtist() != null && tempBeatmap.getTitle() != null && Config.isForceRomanized()) { + updateTitleText(tempBeatmap.getTitle(), tempBeatmap.getArtist()); + } + + play(); + } else { + if (isRunningForeground()) return; + stop(); + BeatmapInfo tempBeatmap = LibraryManager.getInstance().getPrevBeatmap(); + preLoad(tempBeatmap.getMusic()); + updateCoverImage(tempBeatmap.getTrack(0).getBackground()); + + if (tempBeatmap.getArtistUnicode() != null && tempBeatmap.getTitleUnicode() != null && !Config.isForceRomanized()) { + updateTitleText(tempBeatmap.getTitleUnicode(), tempBeatmap.getArtistUnicode()); + }else if (tempBeatmap.getArtist() != null && tempBeatmap.getTitle() != null && Config.isForceRomanized()) { + updateTitleText(tempBeatmap.getTitle(), tempBeatmap.getArtist()); + } + + play(); + } + } + }; + + registerReceiver(onNotifyButtonClick, filter); + + setReceiverStuff(onNotifyButtonClick, filter); + } + + public boolean isRunningForeground() { + return MainActivity.isActivityVisible(); + } + + public class ReturnBindObject extends Binder { + public SongService getObject() { + return SongService.this; + } + } } diff --git a/src/ru/nsu/ccfit/zuev/osu/AppException.java b/src/ru/nsu/ccfit/zuev/osu/AppException.java index 8087d38d..bde0f5ca 100644 --- a/src/ru/nsu/ccfit/zuev/osu/AppException.java +++ b/src/ru/nsu/ccfit/zuev/osu/AppException.java @@ -40,364 +40,364 @@ */ public class AppException extends Exception implements Thread.UncaughtExceptionHandler { - /** - * 定义异常类型 - */ - public final static byte TYPE_NETWORK = 0x01; - public final static byte TYPE_SOCKET = 0x02; - public final static byte TYPE_HTTP_CODE = 0x03; - public final static byte TYPE_HTTP_ERROR = 0x04; - public final static byte TYPE_XML = 0x05; - public final static byte TYPE_IO = 0x06; - public final static byte TYPE_RUN = 0x07; - /** - * - */ - private static final long serialVersionUID = 6243307165131877535L; - private final static boolean Debug = true;// 是否保存错误日志 - private byte type; - private int code; - - /** - * 系统默认的UncaughtException处理类 - */ - private Thread.UncaughtExceptionHandler mDefaultHandler; - - private AppException() { - this.mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler(); - } - - private AppException(byte type, int code, Exception excp) { - super(excp); - this.type = type; - this.code = code; - if (Debug) { - this.saveErrorLog(excp); - } - } - - public static AppException http(int code) { - return new AppException(TYPE_HTTP_CODE, code, null); - } - - public static AppException http(Exception e) { - return new AppException(TYPE_HTTP_ERROR, 0, e); - } - - public static AppException socket(Exception e) { - return new AppException(TYPE_SOCKET, 0, e); - } - - public static AppException io(Exception e) { - if (e instanceof UnknownHostException || e instanceof ConnectException) { - return new AppException(TYPE_NETWORK, 0, e); - } else if (e instanceof IOException) { - return new AppException(TYPE_IO, 0, e); - } - return run(e); - } - - public static AppException xml(Exception e) { - return new AppException(TYPE_XML, 0, e); - } - - public static AppException network(Exception e) { - if (e instanceof UnknownHostException || e instanceof ConnectException) { - return new AppException(TYPE_NETWORK, 0, e); - } else if (e instanceof HttpException) { - return http(e); - } else if (e instanceof SocketException) { - return socket(e); - } - return http(e); - } - - public static AppException run(Exception e) { - return new AppException(TYPE_RUN, 0, e); - } - - /** - * 获取APP异常崩溃处理对象 - * - * @return - */ - public static AppException getAppExceptionHandler() { - return new AppException(); - } - - public static StringBuffer getTraceInfo(Activity a, Throwable e) { - StringBuffer sb = new StringBuffer(); - - Throwable ex = e.getCause() == null ? e : e.getCause(); - StackTraceElement[] stacks = ex.getStackTrace(); - for (StackTraceElement stack : stacks) { - sb.append("class: ").append(stack.getClassName()).append("; method: ") - .append(stack.getMethodName()).append("; line: ").append(stack.getLineNumber()) - .append("; Exception: ").append(ex.toString()).append("\n"); - } - return sb; - } - - public int getCode() { - return this.code; - } - - public int getType() { - return this.type; - } - - /** - * 提示友好的错误信息 - * - * @param ctx - */ - public void makeToast(Context ctx) { - switch (this.getType()) { - case TYPE_HTTP_CODE: - String err = ctx.getString(R.string.http_status_code_error, this.getCode()); - Toast.makeText(ctx, err, Toast.LENGTH_SHORT).show(); - break; - case TYPE_HTTP_ERROR: - Toast.makeText(ctx, R.string.http_exception_error, Toast.LENGTH_SHORT).show(); - break; - case TYPE_SOCKET: - Toast.makeText(ctx, R.string.socket_exception_error, Toast.LENGTH_SHORT).show(); - break; - case TYPE_NETWORK: - Toast.makeText(ctx, R.string.network_not_connected, Toast.LENGTH_SHORT).show(); - break; - case TYPE_XML: - Toast.makeText(ctx, R.string.xml_parser_failed, Toast.LENGTH_SHORT).show(); - break; - case TYPE_IO: - Toast.makeText(ctx, R.string.io_exception_error, Toast.LENGTH_SHORT).show(); - break; - case TYPE_RUN: - Toast.makeText(ctx, R.string.app_run_code_error, Toast.LENGTH_SHORT).show(); - break; - } - } - - /** - * 保存异常日志 - * - * @param excp - */ - public void saveErrorLog(Exception excp) { - saveErrorLog(excp.getLocalizedMessage()); - } - - /** - * 保存异常日志 - * - * @param excpMessage - */ - public void saveErrorLog(String excpMessage) { - String errorlog = "errorlog.txt"; - String savePath = ""; - String logFilePath = ""; - FileWriter fw = null; - PrintWriter pw = null; - try { - // 判断是否挂载了SD卡 - String storageState = Environment.getExternalStorageState(); - if (storageState.equals(Environment.MEDIA_MOUNTED)) { - savePath = Config.getCorePath() + File.separator + "Log/"; - File file = new File(savePath); - if (!file.exists()) { - file.mkdirs(); - } - logFilePath = savePath + errorlog; - } - // 没有挂载SD卡,无法写文件 - if (logFilePath.equals("")) { - return; - } - File logFile = new File(logFilePath); - if (!logFile.exists()) { - logFile.createNewFile(); - } - fw = new FileWriter(logFile, true); - pw = new PrintWriter(fw); - pw.println("--------------------" + (DateFormat.format("yyyy-MM-dd hh:mm:ss", new Date())) - + "---------------------"); - pw.println(excpMessage); - pw.close(); - fw.close(); - } catch (Exception e) { - Log.e("AppException", "[Exception]" + e.getLocalizedMessage()); - } finally { - if (pw != null) { - pw.close(); - } - if (fw != null) { - try { - fw.close(); - } catch (IOException e) { - } - } - } - - } - - @Override - public void uncaughtException(Thread thread, Throwable ex) { - - if (!handleException(ex) && mDefaultHandler != null) { - //如果用户没有处理则让系统默认的异常处理器来处理 - mDefaultHandler.uncaughtException(thread, ex); - } else { - try { - Thread.sleep(5000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - // 结束所有Activity - SaveServiceObject.finishAllActivities(); - //退出程序 - android.os.Process.killProcess(android.os.Process.myPid()); - System.exit(1); - } - } - - /** - * 自定义异常处理:收集错误信息&发送错误报告 - * - * @param ex - * @return true:处理了该异常信息;否则返回false - */ - private boolean handleException(Throwable ex) { - if (ex == null) { - return false; - } - - final Context context = GlobalManager.getInstance().getMainActivity(); - - if (context == null) { - return false; - } - - final String crashReport = getCrashReport(context, ex); - // 显示异常信息&发送报告 - new Thread() { - public void run() { - Looper.prepare(); - Toast.makeText(context, StringTable.get(R.string.crash), Toast.LENGTH_SHORT).show(); - Looper.loop(); - } - - }.start(); - - saveErrorLog(crashReport); - - return true; - } - - /** - * 获取APP崩溃异常报告 - * - * @param ex - * @return - */ - private String getCrashReport(Context context, Throwable ex) { - PackageManager pm = context.getPackageManager(); - PackageInfo pinfo = null; - StringBuilder exceptionStr = new StringBuilder(); - try { - pinfo = pm.getPackageInfo(context.getPackageName(), PackageManager.GET_ACTIVITIES); - exceptionStr.append("Version: ").append(pinfo.versionName).append("(").append(pinfo.versionCode).append(")\n").append("\n"); - exceptionStr.append("Android: ").append(Build.VERSION.RELEASE).append("(").append(Build.MODEL).append(")\n").append("\n"); - exceptionStr.append("System Package Info:").append(collectDeviceInfo(context)).append("\n").append("\n"); - exceptionStr.append("System Screen Info:").append(getScreenInfo(context)).append("\n").append("\n"); - exceptionStr.append("System OS Info:").append(getMobileInfo()).append("\n").append("\n"); - exceptionStr.append("Exception: ").append(ex.getMessage()).append("\n").append("\n"); - exceptionStr.append("Exception stack:").append(getTraceInfo((Activity) context, ex)).append("\n").append("\n"); - } catch (NameNotFoundException e) { - e.printStackTrace(); - } - ex.printStackTrace(); - return exceptionStr.toString(); - } - - /** - * 收集设备参数信息 - * - * @param ctx - */ - public String collectDeviceInfo(Context ctx) { - StringBuilder sb = new StringBuilder(); - JSONObject activePackageJson = new JSONObject(); - - try { - PackageManager pm = ctx.getPackageManager(); - PackageInfo pi = pm.getPackageInfo(ctx.getPackageName(), PackageManager.GET_ACTIVITIES); - if (pi != null) { - String versionName = pi.versionName == null ? "null" : pi.versionName; - String versionCode = pi.versionCode + ""; - - activePackageJson.put("versionName", versionName); - activePackageJson.put("versionCode", versionCode); - } - } catch (NameNotFoundException e) { - Log.e("AppException", "an error occured when collect package info", e); - } catch (JSONException e) { - Log.e("AppException", "jsonException", e); - } - sb.append("[active Package]"); - sb.append(activePackageJson.toString()); - - return sb.toString(); - } - - /** - * 获取手机的硬件信息 - * - * @return - */ - public String getMobileInfo() { - JSONObject osJson = new JSONObject(); - // 通过反射获取系统的硬件信息 - - Field[] fields = Build.class.getDeclaredFields(); - for (Field field : fields) { - try { - field.setAccessible(true); - osJson.put(field.getName(), field.get(null).toString()); - Log.d("AppException", field.getName() + " : " + field.get(null)); - } catch (Exception e) { - Log.e("AppException", "an error occured when collect crash info", e); - } - } - - try { - return osJson.toString(4); - } catch (JSONException e) { - e.printStackTrace(); - return osJson.toString(); - } - } - - public String getScreenInfo(Context ctx) { - JSONObject osJson = new JSONObject(); - - DisplayMetrics displaymetrics = new DisplayMetrics(); - ((Activity) ctx).getWindowManager().getDefaultDisplay().getMetrics(displaymetrics); - for (Field field : displaymetrics.getClass().getDeclaredFields()) { - try { - field.setAccessible(true); - osJson.put(field.getName(), field.get(displaymetrics).toString()); - Log.d("AppException", field.getName() + " : " + field.get(displaymetrics)); - } catch (Exception e) { - Log.e("AppException", "an error occured when collect crash info", e); - } - } - - try { - return osJson.toString(4); - } catch (JSONException e) { - e.printStackTrace(); - return osJson.toString(); - } - } - -} \ No newline at end of file + /** + * 定义异常类型 + */ + public final static byte TYPE_NETWORK = 0x01; + public final static byte TYPE_SOCKET = 0x02; + public final static byte TYPE_HTTP_CODE = 0x03; + public final static byte TYPE_HTTP_ERROR = 0x04; + public final static byte TYPE_XML = 0x05; + public final static byte TYPE_IO = 0x06; + public final static byte TYPE_RUN = 0x07; + /** + * + */ + private static final long serialVersionUID = 6243307165131877535L; + private final static boolean Debug = true;// 是否保存错误日志 + private byte type; + private int code; + + /** + * 系统默认的UncaughtException处理类 + */ + private Thread.UncaughtExceptionHandler mDefaultHandler; + + private AppException() { + this.mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler(); + } + + private AppException(byte type, int code, Exception excp) { + super(excp); + this.type = type; + this.code = code; + if (Debug) { + this.saveErrorLog(excp); + } + } + + public static AppException http(int code) { + return new AppException(TYPE_HTTP_CODE, code, null); + } + + public static AppException http(Exception e) { + return new AppException(TYPE_HTTP_ERROR, 0, e); + } + + public static AppException socket(Exception e) { + return new AppException(TYPE_SOCKET, 0, e); + } + + public static AppException io(Exception e) { + if (e instanceof UnknownHostException || e instanceof ConnectException) { + return new AppException(TYPE_NETWORK, 0, e); + } else if (e instanceof IOException) { + return new AppException(TYPE_IO, 0, e); + } + return run(e); + } + + public static AppException xml(Exception e) { + return new AppException(TYPE_XML, 0, e); + } + + public static AppException network(Exception e) { + if (e instanceof UnknownHostException || e instanceof ConnectException) { + return new AppException(TYPE_NETWORK, 0, e); + } else if (e instanceof HttpException) { + return http(e); + } else if (e instanceof SocketException) { + return socket(e); + } + return http(e); + } + + public static AppException run(Exception e) { + return new AppException(TYPE_RUN, 0, e); + } + + /** + * 获取APP异常崩溃处理对象 + * + * @return + */ + public static AppException getAppExceptionHandler() { + return new AppException(); + } + + public static StringBuffer getTraceInfo(Activity a, Throwable e) { + StringBuffer sb = new StringBuffer(); + + Throwable ex = e.getCause() == null ? e : e.getCause(); + StackTraceElement[] stacks = ex.getStackTrace(); + for (StackTraceElement stack : stacks) { + sb.append("class: ").append(stack.getClassName()).append("; method: ") + .append(stack.getMethodName()).append("; line: ").append(stack.getLineNumber()) + .append("; Exception: ").append(ex.toString()).append("\n"); + } + return sb; + } + + public int getCode() { + return this.code; + } + + public int getType() { + return this.type; + } + + /** + * 提示友好的错误信息 + * + * @param ctx + */ + public void makeToast(Context ctx) { + switch (this.getType()) { + case TYPE_HTTP_CODE: + String err = ctx.getString(R.string.http_status_code_error, this.getCode()); + Toast.makeText(ctx, err, Toast.LENGTH_SHORT).show(); + break; + case TYPE_HTTP_ERROR: + Toast.makeText(ctx, R.string.http_exception_error, Toast.LENGTH_SHORT).show(); + break; + case TYPE_SOCKET: + Toast.makeText(ctx, R.string.socket_exception_error, Toast.LENGTH_SHORT).show(); + break; + case TYPE_NETWORK: + Toast.makeText(ctx, R.string.network_not_connected, Toast.LENGTH_SHORT).show(); + break; + case TYPE_XML: + Toast.makeText(ctx, R.string.xml_parser_failed, Toast.LENGTH_SHORT).show(); + break; + case TYPE_IO: + Toast.makeText(ctx, R.string.io_exception_error, Toast.LENGTH_SHORT).show(); + break; + case TYPE_RUN: + Toast.makeText(ctx, R.string.app_run_code_error, Toast.LENGTH_SHORT).show(); + break; + } + } + + /** + * 保存异常日志 + * + * @param excp + */ + public void saveErrorLog(Exception excp) { + saveErrorLog(excp.getLocalizedMessage()); + } + + /** + * 保存异常日志 + * + * @param excpMessage + */ + public void saveErrorLog(String excpMessage) { + String errorlog = "errorlog.txt"; + String savePath = ""; + String logFilePath = ""; + FileWriter fw = null; + PrintWriter pw = null; + try { + // 判断是否挂载了SD卡 + String storageState = Environment.getExternalStorageState(); + if (storageState.equals(Environment.MEDIA_MOUNTED)) { + savePath = Config.getCorePath() + File.separator + "Log/"; + File file = new File(savePath); + if (!file.exists()) { + file.mkdirs(); + } + logFilePath = savePath + errorlog; + } + // 没有挂载SD卡,无法写文件 + if (logFilePath.equals("")) { + return; + } + File logFile = new File(logFilePath); + if (!logFile.exists()) { + logFile.createNewFile(); + } + fw = new FileWriter(logFile, true); + pw = new PrintWriter(fw); + pw.println("--------------------" + (DateFormat.format("yyyy-MM-dd hh:mm:ss", new Date())) + + "---------------------"); + pw.println(excpMessage); + pw.close(); + fw.close(); + } catch (Exception e) { + Log.e("AppException", "[Exception]" + e.getLocalizedMessage()); + } finally { + if (pw != null) { + pw.close(); + } + if (fw != null) { + try { + fw.close(); + } catch (IOException e) { + } + } + } + + } + + @Override + public void uncaughtException(Thread thread, Throwable ex) { + + if (!handleException(ex) && mDefaultHandler != null) { + //如果用户没有处理则让系统默认的异常处理器来处理 + mDefaultHandler.uncaughtException(thread, ex); + } else { + try { + Thread.sleep(5000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + // 结束所有Activity + SaveServiceObject.finishAllActivities(); + //退出程序 + android.os.Process.killProcess(android.os.Process.myPid()); + System.exit(1); + } + } + + /** + * 自定义异常处理:收集错误信息&发送错误报告 + * + * @param ex + * @return true:处理了该异常信息;否则返回false + */ + private boolean handleException(Throwable ex) { + if (ex == null) { + return false; + } + + final Context context = GlobalManager.getInstance().getMainActivity(); + + if (context == null) { + return false; + } + + final String crashReport = getCrashReport(context, ex); + // 显示异常信息&发送报告 + new Thread() { + public void run() { + Looper.prepare(); + Toast.makeText(context, StringTable.get(R.string.crash), Toast.LENGTH_SHORT).show(); + Looper.loop(); + } + + }.start(); + + saveErrorLog(crashReport); + + return true; + } + + /** + * 获取APP崩溃异常报告 + * + * @param ex + * @return + */ + private String getCrashReport(Context context, Throwable ex) { + PackageManager pm = context.getPackageManager(); + PackageInfo pinfo = null; + StringBuilder exceptionStr = new StringBuilder(); + try { + pinfo = pm.getPackageInfo(context.getPackageName(), PackageManager.GET_ACTIVITIES); + exceptionStr.append("Version: ").append(pinfo.versionName).append("(").append(pinfo.versionCode).append(")\n").append("\n"); + exceptionStr.append("Android: ").append(Build.VERSION.RELEASE).append("(").append(Build.MODEL).append(")\n").append("\n"); + exceptionStr.append("System Package Info:").append(collectDeviceInfo(context)).append("\n").append("\n"); + exceptionStr.append("System Screen Info:").append(getScreenInfo(context)).append("\n").append("\n"); + exceptionStr.append("System OS Info:").append(getMobileInfo()).append("\n").append("\n"); + exceptionStr.append("Exception: ").append(ex.getMessage()).append("\n").append("\n"); + exceptionStr.append("Exception stack:").append(getTraceInfo((Activity) context, ex)).append("\n").append("\n"); + } catch (NameNotFoundException e) { + e.printStackTrace(); + } + ex.printStackTrace(); + return exceptionStr.toString(); + } + + /** + * 收集设备参数信息 + * + * @param ctx + */ + public String collectDeviceInfo(Context ctx) { + StringBuilder sb = new StringBuilder(); + JSONObject activePackageJson = new JSONObject(); + + try { + PackageManager pm = ctx.getPackageManager(); + PackageInfo pi = pm.getPackageInfo(ctx.getPackageName(), PackageManager.GET_ACTIVITIES); + if (pi != null) { + String versionName = pi.versionName == null ? "null" : pi.versionName; + String versionCode = pi.versionCode + ""; + + activePackageJson.put("versionName", versionName); + activePackageJson.put("versionCode", versionCode); + } + } catch (NameNotFoundException e) { + Log.e("AppException", "an error occured when collect package info", e); + } catch (JSONException e) { + Log.e("AppException", "jsonException", e); + } + sb.append("[active Package]"); + sb.append(activePackageJson.toString()); + + return sb.toString(); + } + + /** + * 获取手机的硬件信息 + * + * @return + */ + public String getMobileInfo() { + JSONObject osJson = new JSONObject(); + // 通过反射获取系统的硬件信息 + + Field[] fields = Build.class.getDeclaredFields(); + for (Field field : fields) { + try { + field.setAccessible(true); + osJson.put(field.getName(), field.get(null).toString()); + Log.d("AppException", field.getName() + " : " + field.get(null)); + } catch (Exception e) { + Log.e("AppException", "an error occured when collect crash info", e); + } + } + + try { + return osJson.toString(4); + } catch (JSONException e) { + e.printStackTrace(); + return osJson.toString(); + } + } + + public String getScreenInfo(Context ctx) { + JSONObject osJson = new JSONObject(); + + DisplayMetrics displaymetrics = new DisplayMetrics(); + ((Activity) ctx).getWindowManager().getDefaultDisplay().getMetrics(displaymetrics); + for (Field field : displaymetrics.getClass().getDeclaredFields()) { + try { + field.setAccessible(true); + osJson.put(field.getName(), field.get(displaymetrics).toString()); + Log.d("AppException", field.getName() + " : " + field.get(displaymetrics)); + } catch (Exception e) { + Log.e("AppException", "an error occured when collect crash info", e); + } + } + + try { + return osJson.toString(4); + } catch (JSONException e) { + e.printStackTrace(); + return osJson.toString(); + } + } + +} diff --git a/src/ru/nsu/ccfit/zuev/osu/BeatmapData.java b/src/ru/nsu/ccfit/zuev/osu/BeatmapData.java index 706ca4e3..7f05e30f 100644 --- a/src/ru/nsu/ccfit/zuev/osu/BeatmapData.java +++ b/src/ru/nsu/ccfit/zuev/osu/BeatmapData.java @@ -5,39 +5,39 @@ import java.util.Map; public class BeatmapData { - private final Map> sections = new HashMap>(); - private final Map> dataSections = new HashMap>(); - private String folder; - - public void addSection(final String name, final Map data) { - sections.put(name, data); - } - - public void addSection(final String name, final ArrayList data) { - dataSections.put(name, data); - } - - public String getFolder() { - return folder; - } - - public void setFolder(final String path) { - folder = path; - } - - public String getData(final String section, final String name) { - if (sections.containsKey(section)) { - if (sections.get(section).containsKey(name)) { - return sections.get(section).get(name); - } - } - return ""; - } - - public ArrayList getData(final String section) { - if (dataSections.containsKey(section)) { - return dataSections.get(section); - } - return new ArrayList(); - } + private final Map> sections = new HashMap>(); + private final Map> dataSections = new HashMap>(); + private String folder; + + public void addSection(final String name, final Map data) { + sections.put(name, data); + } + + public void addSection(final String name, final ArrayList data) { + dataSections.put(name, data); + } + + public String getFolder() { + return folder; + } + + public void setFolder(final String path) { + folder = path; + } + + public String getData(final String section, final String name) { + if (sections.containsKey(section)) { + if (sections.get(section).containsKey(name)) { + return sections.get(section).get(name); + } + } + return ""; + } + + public ArrayList getData(final String section) { + if (dataSections.containsKey(section)) { + return dataSections.get(section); + } + return new ArrayList(); + } } diff --git a/src/ru/nsu/ccfit/zuev/osu/BeatmapInfo.java b/src/ru/nsu/ccfit/zuev/osu/BeatmapInfo.java index e34ad440..c161d648 100644 --- a/src/ru/nsu/ccfit/zuev/osu/BeatmapInfo.java +++ b/src/ru/nsu/ccfit/zuev/osu/BeatmapInfo.java @@ -4,121 +4,121 @@ import java.util.ArrayList; public class BeatmapInfo implements Serializable { - private static final long serialVersionUID = -3865268984942011628L; - private final ArrayList tracks = new ArrayList(); - private String title; - private String titleUnicode; - private String artist; - private String artistUnicode; - private String creator; - private String path; - private String source; - private String tags; - private String music = null; - private long date; - private int previewTime; - - public String getSource() { - return source; - } - - public void setSource(final String source) { - this.source = source; - } - - public String getTags() { - return tags; - } - - public void setTags(final String tags) { - this.tags = tags; - } - - public String getMusic() { - return music; - } - - public void setMusic(final String music) { - this.music = music; - } - - public String getTitle() { - return title; - } - - public void setTitle(final String title) { - this.title = title; - } - - public String getArtist() { - return artist; - } - - public void setArtist(final String artist) { - this.artist = artist; - } - - public String getTitleUnicode() { - return titleUnicode; - } - - public void setTitleUnicode(String titleUnicode) { - this.titleUnicode = titleUnicode; - } - - public String getArtistUnicode() { - return artistUnicode; - } - - public void setArtistUnicode(String artistUnicode) { - this.artistUnicode = artistUnicode; - } - - public String getCreator() { - return creator; - } - - public void setCreator(final String creator) { - this.creator = creator; - } - - public String getPath() { - return path; - } - - public void setPath(final String path) { - this.path = path; - } - - public void addTrack(final TrackInfo track) { - tracks.add(track); - } - - public TrackInfo getTrack(final int index) { - return tracks.get(index); - } - - public int getCount() { - return tracks.size(); - } - - public ArrayList getTracks() { - return tracks; - } - - public long getDate() { - return date; - } - - public void setDate(final long date) { - this.date = date; - } - - public int getPreviewTime() { - return previewTime; - } + private static final long serialVersionUID = -3865268984942011628L; + private final ArrayList tracks = new ArrayList(); + private String title; + private String titleUnicode; + private String artist; + private String artistUnicode; + private String creator; + private String path; + private String source; + private String tags; + private String music = null; + private long date; + private int previewTime; + + public String getSource() { + return source; + } + + public void setSource(final String source) { + this.source = source; + } + + public String getTags() { + return tags; + } + + public void setTags(final String tags) { + this.tags = tags; + } + + public String getMusic() { + return music; + } + + public void setMusic(final String music) { + this.music = music; + } + + public String getTitle() { + return title; + } + + public void setTitle(final String title) { + this.title = title; + } + + public String getArtist() { + return artist; + } + + public void setArtist(final String artist) { + this.artist = artist; + } + + public String getTitleUnicode() { + return titleUnicode; + } + + public void setTitleUnicode(String titleUnicode) { + this.titleUnicode = titleUnicode; + } + + public String getArtistUnicode() { + return artistUnicode; + } + + public void setArtistUnicode(String artistUnicode) { + this.artistUnicode = artistUnicode; + } + + public String getCreator() { + return creator; + } + + public void setCreator(final String creator) { + this.creator = creator; + } + + public String getPath() { + return path; + } + + public void setPath(final String path) { + this.path = path; + } + + public void addTrack(final TrackInfo track) { + tracks.add(track); + } + + public TrackInfo getTrack(final int index) { + return tracks.get(index); + } + + public int getCount() { + return tracks.size(); + } + + public ArrayList getTracks() { + return tracks; + } + + public long getDate() { + return date; + } + + public void setDate(final long date) { + this.date = date; + } + + public int getPreviewTime() { + return previewTime; + } - public void setPreviewTime(final int previewTime) { - this.previewTime = previewTime; - } + public void setPreviewTime(final int previewTime) { + this.previewTime = previewTime; + } } diff --git a/src/ru/nsu/ccfit/zuev/osu/BeatmapProperties.java b/src/ru/nsu/ccfit/zuev/osu/BeatmapProperties.java index e0f3c84d..71853870 100644 --- a/src/ru/nsu/ccfit/zuev/osu/BeatmapProperties.java +++ b/src/ru/nsu/ccfit/zuev/osu/BeatmapProperties.java @@ -3,25 +3,25 @@ import java.io.Serializable; public class BeatmapProperties implements Serializable { - private static final long serialVersionUID = -7229486402310659139L; + private static final long serialVersionUID = -7229486402310659139L; - public int offset; - public boolean favorite; + public int offset; + public boolean favorite; - public int getOffset() { - return (int) (Math.signum(offset) * Math.min(250, Math.abs(offset))); - } + public int getOffset() { + return (int) (Math.signum(offset) * Math.min(250, Math.abs(offset))); + } - public void setOffset(final int offset) { - this.offset = offset; - } + public void setOffset(final int offset) { + this.offset = offset; + } - public boolean isFavorite() { - return favorite; - } + public boolean isFavorite() { + return favorite; + } - public void setFavorite(final boolean favorite) { - this.favorite = favorite; - } + public void setFavorite(final boolean favorite) { + this.favorite = favorite; + } } diff --git a/src/ru/nsu/ccfit/zuev/osu/BuildType.java b/src/ru/nsu/ccfit/zuev/osu/BuildType.java index 25bb0a97..826383da 100644 --- a/src/ru/nsu/ccfit/zuev/osu/BuildType.java +++ b/src/ru/nsu/ccfit/zuev/osu/BuildType.java @@ -3,7 +3,7 @@ import ru.nsu.ccfit.zuev.osuplus.BuildConfig; public class BuildType { - public static boolean hasOnlineAccess() { - return BuildConfig.BUILD_TYPE.matches("(release|pre_release)"); - } + public static boolean hasOnlineAccess() { + return BuildConfig.BUILD_TYPE.matches("(release|pre_release)"); + } } diff --git a/src/ru/nsu/ccfit/zuev/osu/Config.java b/src/ru/nsu/ccfit/zuev/osu/Config.java index 6f18fe3a..a0e0eb30 100644 --- a/src/ru/nsu/ccfit/zuev/osu/Config.java +++ b/src/ru/nsu/ccfit/zuev/osu/Config.java @@ -25,755 +25,755 @@ import ru.nsu.ccfit.zuev.osu.helper.FileUtils; public class Config { - private static String corePath, - defaultCorePath, - beatmapPath, - cachePath, - skinPath, - skinTopPath, - scorePath, - localUsername, - onlineUsername, - onlinePassword, - onlineDeviceID; - - private static boolean DELETE_OSZ, - SCAN_DOWNLOAD, - showFirstApproachCircle, - comboburst, - useCustomSkins, - useCustomSounds, - corovans, - showFPS, - sliderBorders, - complexAnimations, - playMusicPreview, - showCursor, - accurateSlider, - shrinkPlayfieldDownwards, - hideNaviBar, - showScoreboard, - enablePP, - enableExtension, - loadAvatar, - stayOnline, - syncMusic, - burstEffects, - hitLighting, - useDither, - useParticles, - useLongTrail, - useCustomComboColors, - forceRomanized, - fixFrameOffset, - removeSliderLock, - calculateSliderPathInGameStart, - displayScorePP, - hideReplayMarquee, - hideInGameUI, - receiveAnnouncements, - useSuperSlider, - enableStoryboard, - safeBeatmapBg, - trianglesAnimation; - - private static int RES_WIDTH, - RES_HEIGHT, - errorMeter, - spinnerStyle, - backgroundQuality, - textureQuality, - metronomeSwitch; - - private static float soundVolume, - bgmVolume, - offset, - backgroundBrightness, - scaleMultiplier, - playfieldSize, - cursorSize; - - private static Map skins; - - private static RGBColor[] comboColors; - private static Context context; - - public static void loadConfig(final Context context) { - Config.context = context; - final SharedPreferences prefs = PreferenceManager - .getDefaultSharedPreferences(context); - String s; - // graphics - s = prefs.getString("background", "2"); - backgroundQuality = Integer.parseInt(s); - useCustomSkins = prefs.getBoolean("skin", false); - useCustomSounds = prefs.getBoolean("beatmapSounds", true); - comboburst = prefs.getBoolean("comboburst", false); - corovans = prefs.getBoolean("images", false); - showFPS = prefs.getBoolean("fps", false); - textureQuality = prefs.getBoolean("lowtextures", false) ? 2 : 1; - errorMeter = Integer.parseInt(prefs.getString("errormeter", "0")); - spinnerStyle = Integer.parseInt(prefs.getString("spinnerstyle", "0")); - showFirstApproachCircle = prefs.getBoolean("showfirstapproachcircle", false); - metronomeSwitch = Integer.parseInt(prefs.getString("metronomeswitch", "1")); - showScoreboard = prefs.getBoolean("showscoreboard", true); - enableStoryboard = prefs.getBoolean("enableStoryboard", false); - trianglesAnimation = prefs.getBoolean("trianglesAnimation", true); - - setSize(); - - setPlayfieldSize(Integer.parseInt(prefs.getString( - "playfieldsize", "100")) / 100f); - shrinkPlayfieldDownwards = prefs.getBoolean("shrinkPlayfieldDownwards", true); - sliderBorders = prefs.getBoolean("sliderborders", true); - complexAnimations = prefs.getBoolean("complexanimations", true); - accurateSlider = true; - - useSuperSlider = prefs.getBoolean("superSlider", false); - - try { - int off = prefs.getInt("offset", 0); - offset = (int) (Math.signum(off) * Math.min(250, Math.abs(off))); - backgroundBrightness = prefs.getInt("bgbrightness", 25) / 100f; - soundVolume = prefs.getInt("soundvolume", 100) / 100f; - bgmVolume = prefs.getInt("bgmvolume", 100) / 100f; - cursorSize = prefs.getInt("cursorSize", 50) / 100f; - }catch(RuntimeException e) { // migrate to integers to prevent crash - prefs.edit() - .putInt("offset", Integer.parseInt(prefs.getString("offset", "0"))) - .putInt("bgbrightness", Integer.parseInt(prefs.getString("bgbrightness", "25"))) - .putInt("soundvolume", Integer.parseInt(prefs.getString("soundvolume", "100"))) - .putInt("bgmvolume", Integer.parseInt(prefs.getString("bgmvolume", "100"))) - .putInt("cursorSize", Integer.parseInt(prefs.getString("cursorSize", "50"))) - .commit(); - Config.loadConfig(context); - } - - - //advanced - defaultCorePath = Environment.getExternalStorageDirectory() + "/osu!droid/"; - corePath = prefs.getString("corePath", defaultCorePath); - if (corePath.length() == 0) { - corePath = defaultCorePath; - } - if (corePath.charAt(corePath.length() - 1) != '/') { - corePath += "/"; - } - scorePath = corePath + "Scores/"; - - skinPath = prefs.getString("skinPath", corePath + "Skin/"); - if (skinPath.length() == 0) { - skinPath = corePath + "Skin/"; - } - if (skinPath.charAt(skinPath.length() - 1) != '/') { - skinPath += "/"; - } - - skinTopPath = prefs.getString("skinTopPath", skinPath); - if (skinTopPath.length() == 0) { - skinTopPath = skinPath; - } - if (skinTopPath.charAt(skinTopPath.length() - 1) != '/') { - skinTopPath += "/"; - } - - syncMusic = prefs.getBoolean("syncMusic", syncMusic); - if (prefs.getBoolean("lowDelay", true)) { - Engine.INPUT_PAUSE_DURATION = 0; - } else { - Engine.INPUT_PAUSE_DURATION = 20; - } - enableExtension = false;// prefs.getBoolean("enableExtension", false); - cachePath = context.getCacheDir().getPath(); - burstEffects = prefs.getBoolean("bursts", burstEffects); - hitLighting = prefs.getBoolean("hitlighting", hitLighting); - useDither = prefs.getBoolean("dither", useDither); - useParticles = prefs.getBoolean("particles", useParticles); - useLongTrail = prefs.getBoolean("longTrail", useLongTrail); - useCustomComboColors = prefs.getBoolean("useCustomColors", useCustomComboColors); - comboColors = new RGBColor[4]; - for (int i = 1; i <= 4; i++) { - comboColors[i - 1] = RGBColor.hex2Rgb(ColorPickerPreference.convertToRGB(prefs.getInt("combo" + i, 0xff000000))); - } - - // skins - File[] folders = FileUtils.listFiles(new File(skinTopPath), file -> file.isDirectory() && !file.getName().startsWith(".")); - skins = new HashMap(); - for(File folder : folders) { - skins.put(folder.getName(), folder.getPath()); - Debug.i("skins: " + folder.getName() + " - " + folder.getPath()); - } - - // beatmaps - DELETE_OSZ = prefs.getBoolean("deleteosz", true); - SCAN_DOWNLOAD = prefs.getBoolean("scandownload", false); - forceRomanized = prefs.getBoolean("forceromanized", false); - beatmapPath = prefs.getString("directory", corePath + "Songs/"); - if (beatmapPath.length() == 0) { - beatmapPath = corePath + "Songs/"; - } - if (beatmapPath.charAt(beatmapPath.length() - 1) != '/') { - beatmapPath += "/"; - } - - // other - playMusicPreview = prefs.getBoolean("musicpreview", true); - localUsername = prefs.getString("playername", ""); - showCursor = prefs.getBoolean("showcursor", false); - hideNaviBar = prefs.getBoolean("hidenavibar", false); - enablePP = false;//prefs.getBoolean("enablePP",true); - fixFrameOffset = prefs.getBoolean("fixFrameOffset", true); - removeSliderLock = prefs.getBoolean("removeSliderLock", false); - calculateSliderPathInGameStart = prefs.getBoolean("calculateSliderPathInGameStart", false); - displayScorePP = prefs.getBoolean("displayScorePP", false); - hideReplayMarquee = prefs.getBoolean("hideReplayMarquee", false); - hideInGameUI = prefs.getBoolean("hideInGameUI", false); - receiveAnnouncements = prefs.getBoolean("receiveAnnouncements", true); - safeBeatmapBg = prefs.getBoolean("safebeatmapbg", false); - - if(receiveAnnouncements) { - FirebaseMessaging.getInstance().subscribeToTopic("announcements"); - }else { - FirebaseMessaging.getInstance().unsubscribeFromTopic("announcements"); - } - - //Init - onlineDeviceID = prefs.getString("installID", null); - if (onlineDeviceID == null) { - onlineDeviceID = UUID.randomUUID().toString().replace("-", "").substring(0, 32); - Editor editor = prefs.edit(); - editor.putString("installID", onlineDeviceID); - editor.putString("corePath", corePath); - editor.putString("skinTopPath", skinTopPath); - editor.putString("skinPath", skinPath); - editor.commit(); - } - - loadOnlineConfig(context); - FavoriteLibrary.get().load(); - } - - public static void loadOnlineConfig(final Context context) { - final SharedPreferences prefs = PreferenceManager - .getDefaultSharedPreferences(context); - - onlineUsername = prefs.getString("onlineUsername", ""); - onlinePassword = prefs.getString("onlinePassword", null); - stayOnline = prefs.getBoolean("stayOnline", true); - loadAvatar = prefs.getBoolean("loadAvatar",false); - } - - public static void setSize() { - final DisplayMetrics dm = new DisplayMetrics(); - ((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(dm); - - int width = Math.max(dm.widthPixels, dm.heightPixels), height = Math.min(dm.widthPixels, dm.heightPixels); - //int width = dm.widthPixels, height = dm.heightPixels; - setSize(width, height); - //ToastLogger.showText("width=" + dm.widthPixels + " height=" + dm.heightPixels, true); - Debug.i("width=" + dm.widthPixels + " height=" + dm.heightPixels); - } - - public static void setSize(int width, int height) { - RES_WIDTH = 1280; - RES_HEIGHT = 1280 * height / width; - } - - public static boolean isEnableStoryboard() { - return backgroundBrightness > 0.02 && enableStoryboard; - } - - public static void setEnableStoryboard(boolean enableStoryboard) { - Config.enableStoryboard = enableStoryboard; - } - - public static boolean isUseSuperSlider() { - return useSuperSlider; - } - - public static boolean isFixFrameOffset() { - return fixFrameOffset; - } - - public static boolean isRemoveSliderLock() { - return removeSliderLock; - } - - public static boolean isCalculateSliderPathInGameStart() { - return calculateSliderPathInGameStart; - } - - public static boolean isDisplayScorePP() { - return displayScorePP; - } - - public static boolean isEnableExtension() { - return enableExtension; - } - - public static void setEnableExtension(boolean enableExtension) { - Config.enableExtension = enableExtension; - } - - public static boolean isShowFPS() { - return showFPS; - } - - public static void setShowFPS(final boolean showFPS) { - Config.showFPS = showFPS; - } - - public static boolean isShowScoreboard() { - return showScoreboard; - } - - public static void setShowScoreboard(final boolean showScoreboard) { - Config.showScoreboard = showScoreboard; - } - - public static boolean isCorovans() { - return corovans; - } - - public static void setCorovans(final boolean corovans) { - Config.corovans = corovans; - } - - public static float getSoundVolume() { - return soundVolume; - } - - public static void setSoundVolume(final float volume) { - Config.soundVolume = volume; - } - - public static float getBgmVolume() { - return bgmVolume; - } - - public static void setBgmVolume(float bgmVolume) { - Config.bgmVolume = bgmVolume; - } - - public static float getOffset() { - return offset; - } - - public static void setOffset(final float offset) { - Config.offset = offset; - } + private static String corePath, + defaultCorePath, + beatmapPath, + cachePath, + skinPath, + skinTopPath, + scorePath, + localUsername, + onlineUsername, + onlinePassword, + onlineDeviceID; + + private static boolean DELETE_OSZ, + SCAN_DOWNLOAD, + showFirstApproachCircle, + comboburst, + useCustomSkins, + useCustomSounds, + corovans, + showFPS, + sliderBorders, + complexAnimations, + playMusicPreview, + showCursor, + accurateSlider, + shrinkPlayfieldDownwards, + hideNaviBar, + showScoreboard, + enablePP, + enableExtension, + loadAvatar, + stayOnline, + syncMusic, + burstEffects, + hitLighting, + useDither, + useParticles, + useLongTrail, + useCustomComboColors, + forceRomanized, + fixFrameOffset, + removeSliderLock, + calculateSliderPathInGameStart, + displayScorePP, + hideReplayMarquee, + hideInGameUI, + receiveAnnouncements, + useSuperSlider, + enableStoryboard, + safeBeatmapBg, + trianglesAnimation; + + private static int RES_WIDTH, + RES_HEIGHT, + errorMeter, + spinnerStyle, + backgroundQuality, + textureQuality, + metronomeSwitch; + + private static float soundVolume, + bgmVolume, + offset, + backgroundBrightness, + scaleMultiplier, + playfieldSize, + cursorSize; + + private static Map skins; + + private static RGBColor[] comboColors; + private static Context context; + + public static void loadConfig(final Context context) { + Config.context = context; + final SharedPreferences prefs = PreferenceManager + .getDefaultSharedPreferences(context); + String s; + // graphics + s = prefs.getString("background", "2"); + backgroundQuality = Integer.parseInt(s); + useCustomSkins = prefs.getBoolean("skin", false); + useCustomSounds = prefs.getBoolean("beatmapSounds", true); + comboburst = prefs.getBoolean("comboburst", false); + corovans = prefs.getBoolean("images", false); + showFPS = prefs.getBoolean("fps", false); + textureQuality = prefs.getBoolean("lowtextures", false) ? 2 : 1; + errorMeter = Integer.parseInt(prefs.getString("errormeter", "0")); + spinnerStyle = Integer.parseInt(prefs.getString("spinnerstyle", "0")); + showFirstApproachCircle = prefs.getBoolean("showfirstapproachcircle", false); + metronomeSwitch = Integer.parseInt(prefs.getString("metronomeswitch", "1")); + showScoreboard = prefs.getBoolean("showscoreboard", true); + enableStoryboard = prefs.getBoolean("enableStoryboard", false); + trianglesAnimation = prefs.getBoolean("trianglesAnimation", true); + + setSize(); + + setPlayfieldSize(Integer.parseInt(prefs.getString( + "playfieldsize", "100")) / 100f); + shrinkPlayfieldDownwards = prefs.getBoolean("shrinkPlayfieldDownwards", true); + sliderBorders = prefs.getBoolean("sliderborders", true); + complexAnimations = prefs.getBoolean("complexanimations", true); + accurateSlider = true; + + useSuperSlider = prefs.getBoolean("superSlider", false); + + try { + int off = prefs.getInt("offset", 0); + offset = (int) (Math.signum(off) * Math.min(250, Math.abs(off))); + backgroundBrightness = prefs.getInt("bgbrightness", 25) / 100f; + soundVolume = prefs.getInt("soundvolume", 100) / 100f; + bgmVolume = prefs.getInt("bgmvolume", 100) / 100f; + cursorSize = prefs.getInt("cursorSize", 50) / 100f; + }catch(RuntimeException e) { // migrate to integers to prevent crash + prefs.edit() + .putInt("offset", Integer.parseInt(prefs.getString("offset", "0"))) + .putInt("bgbrightness", Integer.parseInt(prefs.getString("bgbrightness", "25"))) + .putInt("soundvolume", Integer.parseInt(prefs.getString("soundvolume", "100"))) + .putInt("bgmvolume", Integer.parseInt(prefs.getString("bgmvolume", "100"))) + .putInt("cursorSize", Integer.parseInt(prefs.getString("cursorSize", "50"))) + .commit(); + Config.loadConfig(context); + } + + + //advanced + defaultCorePath = Environment.getExternalStorageDirectory() + "/osu!droid/"; + corePath = prefs.getString("corePath", defaultCorePath); + if (corePath.length() == 0) { + corePath = defaultCorePath; + } + if (corePath.charAt(corePath.length() - 1) != '/') { + corePath += "/"; + } + scorePath = corePath + "Scores/"; + + skinPath = prefs.getString("skinPath", corePath + "Skin/"); + if (skinPath.length() == 0) { + skinPath = corePath + "Skin/"; + } + if (skinPath.charAt(skinPath.length() - 1) != '/') { + skinPath += "/"; + } + + skinTopPath = prefs.getString("skinTopPath", skinPath); + if (skinTopPath.length() == 0) { + skinTopPath = skinPath; + } + if (skinTopPath.charAt(skinTopPath.length() - 1) != '/') { + skinTopPath += "/"; + } + + syncMusic = prefs.getBoolean("syncMusic", syncMusic); + if (prefs.getBoolean("lowDelay", true)) { + Engine.INPUT_PAUSE_DURATION = 0; + } else { + Engine.INPUT_PAUSE_DURATION = 20; + } + enableExtension = false;// prefs.getBoolean("enableExtension", false); + cachePath = context.getCacheDir().getPath(); + burstEffects = prefs.getBoolean("bursts", burstEffects); + hitLighting = prefs.getBoolean("hitlighting", hitLighting); + useDither = prefs.getBoolean("dither", useDither); + useParticles = prefs.getBoolean("particles", useParticles); + useLongTrail = prefs.getBoolean("longTrail", useLongTrail); + useCustomComboColors = prefs.getBoolean("useCustomColors", useCustomComboColors); + comboColors = new RGBColor[4]; + for (int i = 1; i <= 4; i++) { + comboColors[i - 1] = RGBColor.hex2Rgb(ColorPickerPreference.convertToRGB(prefs.getInt("combo" + i, 0xff000000))); + } + + // skins + File[] folders = FileUtils.listFiles(new File(skinTopPath), file -> file.isDirectory() && !file.getName().startsWith(".")); + skins = new HashMap(); + for(File folder : folders) { + skins.put(folder.getName(), folder.getPath()); + Debug.i("skins: " + folder.getName() + " - " + folder.getPath()); + } + + // beatmaps + DELETE_OSZ = prefs.getBoolean("deleteosz", true); + SCAN_DOWNLOAD = prefs.getBoolean("scandownload", false); + forceRomanized = prefs.getBoolean("forceromanized", false); + beatmapPath = prefs.getString("directory", corePath + "Songs/"); + if (beatmapPath.length() == 0) { + beatmapPath = corePath + "Songs/"; + } + if (beatmapPath.charAt(beatmapPath.length() - 1) != '/') { + beatmapPath += "/"; + } + + // other + playMusicPreview = prefs.getBoolean("musicpreview", true); + localUsername = prefs.getString("playername", ""); + showCursor = prefs.getBoolean("showcursor", false); + hideNaviBar = prefs.getBoolean("hidenavibar", false); + enablePP = false;//prefs.getBoolean("enablePP",true); + fixFrameOffset = prefs.getBoolean("fixFrameOffset", true); + removeSliderLock = prefs.getBoolean("removeSliderLock", false); + calculateSliderPathInGameStart = prefs.getBoolean("calculateSliderPathInGameStart", false); + displayScorePP = prefs.getBoolean("displayScorePP", false); + hideReplayMarquee = prefs.getBoolean("hideReplayMarquee", false); + hideInGameUI = prefs.getBoolean("hideInGameUI", false); + receiveAnnouncements = prefs.getBoolean("receiveAnnouncements", true); + safeBeatmapBg = prefs.getBoolean("safebeatmapbg", false); + + if(receiveAnnouncements) { + FirebaseMessaging.getInstance().subscribeToTopic("announcements"); + }else { + FirebaseMessaging.getInstance().unsubscribeFromTopic("announcements"); + } + + //Init + onlineDeviceID = prefs.getString("installID", null); + if (onlineDeviceID == null) { + onlineDeviceID = UUID.randomUUID().toString().replace("-", "").substring(0, 32); + Editor editor = prefs.edit(); + editor.putString("installID", onlineDeviceID); + editor.putString("corePath", corePath); + editor.putString("skinTopPath", skinTopPath); + editor.putString("skinPath", skinPath); + editor.commit(); + } + + loadOnlineConfig(context); + FavoriteLibrary.get().load(); + } + + public static void loadOnlineConfig(final Context context) { + final SharedPreferences prefs = PreferenceManager + .getDefaultSharedPreferences(context); + + onlineUsername = prefs.getString("onlineUsername", ""); + onlinePassword = prefs.getString("onlinePassword", null); + stayOnline = prefs.getBoolean("stayOnline", true); + loadAvatar = prefs.getBoolean("loadAvatar",false); + } + + public static void setSize() { + final DisplayMetrics dm = new DisplayMetrics(); + ((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(dm); + + int width = Math.max(dm.widthPixels, dm.heightPixels), height = Math.min(dm.widthPixels, dm.heightPixels); + //int width = dm.widthPixels, height = dm.heightPixels; + setSize(width, height); + //ToastLogger.showText("width=" + dm.widthPixels + " height=" + dm.heightPixels, true); + Debug.i("width=" + dm.widthPixels + " height=" + dm.heightPixels); + } + + public static void setSize(int width, int height) { + RES_WIDTH = 1280; + RES_HEIGHT = 1280 * height / width; + } + + public static boolean isEnableStoryboard() { + return backgroundBrightness > 0.02 && enableStoryboard; + } + + public static void setEnableStoryboard(boolean enableStoryboard) { + Config.enableStoryboard = enableStoryboard; + } + + public static boolean isUseSuperSlider() { + return useSuperSlider; + } + + public static boolean isFixFrameOffset() { + return fixFrameOffset; + } + + public static boolean isRemoveSliderLock() { + return removeSliderLock; + } + + public static boolean isCalculateSliderPathInGameStart() { + return calculateSliderPathInGameStart; + } + + public static boolean isDisplayScorePP() { + return displayScorePP; + } + + public static boolean isEnableExtension() { + return enableExtension; + } + + public static void setEnableExtension(boolean enableExtension) { + Config.enableExtension = enableExtension; + } + + public static boolean isShowFPS() { + return showFPS; + } + + public static void setShowFPS(final boolean showFPS) { + Config.showFPS = showFPS; + } + + public static boolean isShowScoreboard() { + return showScoreboard; + } + + public static void setShowScoreboard(final boolean showScoreboard) { + Config.showScoreboard = showScoreboard; + } + + public static boolean isCorovans() { + return corovans; + } + + public static void setCorovans(final boolean corovans) { + Config.corovans = corovans; + } + + public static float getSoundVolume() { + return soundVolume; + } + + public static void setSoundVolume(final float volume) { + Config.soundVolume = volume; + } + + public static float getBgmVolume() { + return bgmVolume; + } + + public static void setBgmVolume(float bgmVolume) { + Config.bgmVolume = bgmVolume; + } + + public static float getOffset() { + return offset; + } + + public static void setOffset(final float offset) { + Config.offset = offset; + } - public static int getBackgroundQuality() { - return backgroundQuality; - } + public static int getBackgroundQuality() { + return backgroundQuality; + } - public static void setBackgroundQuality(final int backgroundQuality) { - Config.backgroundQuality = backgroundQuality; - } + public static void setBackgroundQuality(final int backgroundQuality) { + Config.backgroundQuality = backgroundQuality; + } - public static String getCorePath() { - return corePath; - } + public static String getCorePath() { + return corePath; + } - public static void setCorePath(final String corePath) { - Config.corePath = corePath; - } + public static void setCorePath(final String corePath) { + Config.corePath = corePath; + } - public static String getBeatmapPath() { - return beatmapPath; - } + public static String getBeatmapPath() { + return beatmapPath; + } - public static void setBeatmapPath(final String path) { - beatmapPath = path; - } + public static void setBeatmapPath(final String path) { + beatmapPath = path; + } - public static int getRES_WIDTH() { - return RES_WIDTH; - } + public static int getRES_WIDTH() { + return RES_WIDTH; + } - public static void setRES_WIDTH(final int rES_WIDTH) { - RES_WIDTH = rES_WIDTH; - } + public static void setRES_WIDTH(final int rES_WIDTH) { + RES_WIDTH = rES_WIDTH; + } - public static int getRES_HEIGHT() { - return RES_HEIGHT; - } + public static int getRES_HEIGHT() { + return RES_HEIGHT; + } - public static void setRES_HEIGHT(final int rES_HEIGHT) { - RES_HEIGHT = rES_HEIGHT; - } + public static void setRES_HEIGHT(final int rES_HEIGHT) { + RES_HEIGHT = rES_HEIGHT; + } - public static boolean isDELETE_OSZ() { - return DELETE_OSZ; - } + public static boolean isDELETE_OSZ() { + return DELETE_OSZ; + } - public static void setDELETE_OSZ(final boolean dELETE_OSZ) { - DELETE_OSZ = dELETE_OSZ; - } + public static void setDELETE_OSZ(final boolean dELETE_OSZ) { + DELETE_OSZ = dELETE_OSZ; + } - public static boolean isSCAN_DOWNLOAD() { - return SCAN_DOWNLOAD; - } + public static boolean isSCAN_DOWNLOAD() { + return SCAN_DOWNLOAD; + } - public static void setSCAN_DOWNLOAD(final boolean sCAN_DOWNLOAD) { - SCAN_DOWNLOAD = sCAN_DOWNLOAD; - } + public static void setSCAN_DOWNLOAD(final boolean sCAN_DOWNLOAD) { + SCAN_DOWNLOAD = sCAN_DOWNLOAD; + } - public static boolean isUseCustomSkins() { - return useCustomSkins; - } + public static boolean isUseCustomSkins() { + return useCustomSkins; + } - public static void setUseCustomSkins(final boolean useCustomSkins) { - Config.useCustomSkins = useCustomSkins; - } + public static void setUseCustomSkins(final boolean useCustomSkins) { + Config.useCustomSkins = useCustomSkins; + } - public static boolean isUseCustomSounds() { - return useCustomSounds; - } + public static boolean isUseCustomSounds() { + return useCustomSounds; + } - public static void setUseCustomSounds(boolean useCustomSounds) { - Config.useCustomSounds = useCustomSounds; - } + public static void setUseCustomSounds(boolean useCustomSounds) { + Config.useCustomSounds = useCustomSounds; + } - public static int getTextureQuality() { - return textureQuality; - } + public static int getTextureQuality() { + return textureQuality; + } - public static void setTextureQuality(final int textureQuality) { - Config.textureQuality = textureQuality; - } + public static void setTextureQuality(final int textureQuality) { + Config.textureQuality = textureQuality; + } - public static float getBackgroundBrightness() { - return backgroundBrightness; - } + public static float getBackgroundBrightness() { + return backgroundBrightness; + } - public static void setBackgroundBrightness(final float backgroundBrightness) { - Config.backgroundBrightness = backgroundBrightness; - } + public static void setBackgroundBrightness(final float backgroundBrightness) { + Config.backgroundBrightness = backgroundBrightness; + } - public static boolean isSliderBorders() { - return sliderBorders; - } + public static boolean isSliderBorders() { + return sliderBorders; + } - public static void setSliderBorders(final boolean sliderBorders) { - Config.sliderBorders = sliderBorders; - } + public static void setSliderBorders(final boolean sliderBorders) { + Config.sliderBorders = sliderBorders; + } - public static boolean isComplexAnimations() { - return complexAnimations; - } + public static boolean isComplexAnimations() { + return complexAnimations; + } - public static void setComplexAnimations(final boolean complexAnimations) { - Config.complexAnimations = complexAnimations; - } + public static void setComplexAnimations(final boolean complexAnimations) { + Config.complexAnimations = complexAnimations; + } - public static boolean isPlayMusicPreview() { - return playMusicPreview; - } + public static boolean isPlayMusicPreview() { + return playMusicPreview; + } - public static void setPlayMusicPreview(final boolean playMusicPreview) { - Config.playMusicPreview = playMusicPreview; - } + public static void setPlayMusicPreview(final boolean playMusicPreview) { + Config.playMusicPreview = playMusicPreview; + } - public static String getLocalUsername() { - return localUsername; - } + public static String getLocalUsername() { + return localUsername; + } - public static void setLocalUsername(final String localUsername) { - Config.localUsername = localUsername; - } + public static void setLocalUsername(final String localUsername) { + Config.localUsername = localUsername; + } - public static boolean isShowCursor() { - return showCursor; - } + public static boolean isShowCursor() { + return showCursor; + } - public static void setShowCursor(final boolean showCursor) { - Config.showCursor = showCursor; - } + public static void setShowCursor(final boolean showCursor) { + Config.showCursor = showCursor; + } - public static boolean isAccurateSlider() { - return accurateSlider; - } + public static boolean isAccurateSlider() { + return accurateSlider; + } - public static void setAccurateSlider(final boolean accurateSlider) { - Config.accurateSlider = accurateSlider; - } + public static void setAccurateSlider(final boolean accurateSlider) { + Config.accurateSlider = accurateSlider; + } - public static float getScaleMultiplier() { - return scaleMultiplier; - } + public static float getScaleMultiplier() { + return scaleMultiplier; + } - public static void setScaleMultiplier(final float scaleMultiplier) { - Config.scaleMultiplier = scaleMultiplier; - } + public static void setScaleMultiplier(final float scaleMultiplier) { + Config.scaleMultiplier = scaleMultiplier; + } - public static String getOnlineUsername() { - return onlineUsername; - } + public static String getOnlineUsername() { + return onlineUsername; + } - public static void setOnlineUsername(String onlineUsername) { - Config.onlineUsername = onlineUsername; - } + public static void setOnlineUsername(String onlineUsername) { + Config.onlineUsername = onlineUsername; + } - public static String getOnlinePassword() { - return onlinePassword; - } + public static String getOnlinePassword() { + return onlinePassword; + } - public static void setOnlinePassword(String onlinePassword) { - Config.onlinePassword = onlinePassword; - } + public static void setOnlinePassword(String onlinePassword) { + Config.onlinePassword = onlinePassword; + } - public static boolean isStayOnline() { - return stayOnline && BuildType.hasOnlineAccess(); - } + public static boolean isStayOnline() { + return stayOnline && BuildType.hasOnlineAccess(); + } - public static void setStayOnline(boolean stayOnline) { - Config.stayOnline = stayOnline; - } + public static void setStayOnline(boolean stayOnline) { + Config.stayOnline = stayOnline; + } - public static boolean getLoadAvatar() { - return loadAvatar; - } + public static boolean getLoadAvatar() { + return loadAvatar; + } - public static void setLoadAvatar(boolean loadAvatar) { - Config.loadAvatar = loadAvatar; - } + public static void setLoadAvatar(boolean loadAvatar) { + Config.loadAvatar = loadAvatar; + } - public static String getOnlineDeviceID() { - return onlineDeviceID; - } + public static String getOnlineDeviceID() { + return onlineDeviceID; + } - public static boolean isSyncMusic() { - return syncMusic; - } + public static boolean isSyncMusic() { + return syncMusic; + } - public static void setSyncMusic(boolean syncMusic) { - Config.syncMusic = syncMusic; - } + public static void setSyncMusic(boolean syncMusic) { + Config.syncMusic = syncMusic; + } - public static String getCachePath() { - return cachePath; - } + public static String getCachePath() { + return cachePath; + } - public static void setCachePath(String cachePath) { - Config.cachePath = cachePath; - } + public static void setCachePath(String cachePath) { + Config.cachePath = cachePath; + } - public static boolean isBurstEffects() { - return burstEffects; - } + public static boolean isBurstEffects() { + return burstEffects; + } - public static void setBurstEffects(boolean burstEffects) { - Config.burstEffects = burstEffects; - } + public static void setBurstEffects(boolean burstEffects) { + Config.burstEffects = burstEffects; + } - public static boolean isHitLighting() { - return hitLighting; - } + public static boolean isHitLighting() { + return hitLighting; + } - public static void setHitLighting(boolean hitLighting) { - Config.hitLighting = hitLighting; - } + public static void setHitLighting(boolean hitLighting) { + Config.hitLighting = hitLighting; + } - public static boolean isUseDither() { - return useDither; - } + public static boolean isUseDither() { + return useDither; + } - public static void setUseDither(boolean useDither) { - Config.useDither = useDither; - } + public static void setUseDither(boolean useDither) { + Config.useDither = useDither; + } - public static boolean isUseParticles() { - return useParticles; - } + public static boolean isUseParticles() { + return useParticles; + } - public static void setUseParticles(boolean useParticles) { - Config.useParticles = useParticles; - } + public static void setUseParticles(boolean useParticles) { + Config.useParticles = useParticles; + } - public static boolean isUseLongTrail() { - return useLongTrail; - } + public static boolean isUseLongTrail() { + return useLongTrail; + } - public static void setUseLongTrail(boolean useLongTrail) { - Config.useLongTrail = useLongTrail; - } + public static void setUseLongTrail(boolean useLongTrail) { + Config.useLongTrail = useLongTrail; + } - public static String getSkinPath() { - return skinPath; - } + public static String getSkinPath() { + return skinPath; + } - public static void setSkinPath(String skinPath) { - Config.skinPath = skinPath; - } + public static void setSkinPath(String skinPath) { + Config.skinPath = skinPath; + } - public static String getSkinTopPath() { - return skinTopPath; - } + public static String getSkinTopPath() { + return skinTopPath; + } - public static void setSkinTopPath(String skinTopPath) { - Config.skinTopPath = skinTopPath; - } + public static void setSkinTopPath(String skinTopPath) { + Config.skinTopPath = skinTopPath; + } - public static boolean isHideNaviBar() { - return hideNaviBar; - } + public static boolean isHideNaviBar() { + return hideNaviBar; + } - public static void setHideNaviBar(boolean hideNaviBar) { - Config.hideNaviBar = hideNaviBar; - } + public static void setHideNaviBar(boolean hideNaviBar) { + Config.hideNaviBar = hideNaviBar; + } - public static boolean isEnablePP() { - return enablePP; - } + public static boolean isEnablePP() { + return enablePP; + } - public static void setEnablePP(boolean enablePP) { - Config.enablePP = enablePP; - } + public static void setEnablePP(boolean enablePP) { + Config.enablePP = enablePP; + } - public static String getScorePath() { - return scorePath; - } + public static String getScorePath() { + return scorePath; + } - public static void setScorePath(String scorePath) { - Config.scorePath = scorePath; - } + public static void setScorePath(String scorePath) { + Config.scorePath = scorePath; + } - public static boolean isUseCustomComboColors() { - return useCustomComboColors; - } + public static boolean isUseCustomComboColors() { + return useCustomComboColors; + } - public static void setUseCustomComboColors(boolean useCustomComboColors) { - Config.useCustomComboColors = useCustomComboColors; - } + public static void setUseCustomComboColors(boolean useCustomComboColors) { + Config.useCustomComboColors = useCustomComboColors; + } - public static RGBColor[] getComboColors() { - return comboColors; - } + public static RGBColor[] getComboColors() { + return comboColors; + } - public static int getErrorMeter() { - return errorMeter; - } + public static int getErrorMeter() { + return errorMeter; + } - public static void setErrorMeter(int errorMeter) { - Config.errorMeter = errorMeter; - } + public static void setErrorMeter(int errorMeter) { + Config.errorMeter = errorMeter; + } - public static int getSpinnerStyle() { - return spinnerStyle; - } + public static int getSpinnerStyle() { + return spinnerStyle; + } - public static void setSpinnerStyle(int spinnerStyle) { - Config.spinnerStyle = spinnerStyle; - } + public static void setSpinnerStyle(int spinnerStyle) { + Config.spinnerStyle = spinnerStyle; + } - public static boolean isShowFirstApproachCircle() { - return showFirstApproachCircle; - } + public static boolean isShowFirstApproachCircle() { + return showFirstApproachCircle; + } - public static void setShowFirstApproachCircle(boolean showFirstApproachCircle) { - Config.showFirstApproachCircle = showFirstApproachCircle; - } + public static void setShowFirstApproachCircle(boolean showFirstApproachCircle) { + Config.showFirstApproachCircle = showFirstApproachCircle; + } - public static int getMetronomeSwitch() { - return metronomeSwitch; - } + public static int getMetronomeSwitch() { + return metronomeSwitch; + } - public static void setMetronomeSwitch(int metronomeSwitch) { - Config.metronomeSwitch = metronomeSwitch; - } + public static void setMetronomeSwitch(int metronomeSwitch) { + Config.metronomeSwitch = metronomeSwitch; + } - public static boolean isComboburst() { - return comboburst; - } + public static boolean isComboburst() { + return comboburst; + } - public static void setComboburst(boolean comboburst) { - Config.comboburst = comboburst; - } + public static void setComboburst(boolean comboburst) { + Config.comboburst = comboburst; + } - public static boolean isForceRomanized() { - return forceRomanized; - } + public static boolean isForceRomanized() { + return forceRomanized; + } - public static void setForceRomanized(boolean forceRomanized) { - Config.forceRomanized = forceRomanized; - } + public static void setForceRomanized(boolean forceRomanized) { + Config.forceRomanized = forceRomanized; + } - public static float getCursorSize() { - return cursorSize; - } + public static float getCursorSize() { + return cursorSize; + } - public static void setCursorSize() { - Config.cursorSize = cursorSize; - } + public static void setCursorSize() { + Config.cursorSize = cursorSize; + } - public static float getPlayfieldSize() { - return playfieldSize; - } + public static float getPlayfieldSize() { + return playfieldSize; + } - public static void setPlayfieldSize(final float playfieldSize) { - Config.playfieldSize = playfieldSize; - } + public static void setPlayfieldSize(final float playfieldSize) { + Config.playfieldSize = playfieldSize; + } - public static boolean isShrinkPlayfieldDownwards() { - return shrinkPlayfieldDownwards; - } + public static boolean isShrinkPlayfieldDownwards() { + return shrinkPlayfieldDownwards; + } - public static void setShrinkPlayfieldDownwards(boolean shrinkPlayfieldDownwards) { - Config.shrinkPlayfieldDownwards = shrinkPlayfieldDownwards; - } + public static void setShrinkPlayfieldDownwards(boolean shrinkPlayfieldDownwards) { + Config.shrinkPlayfieldDownwards = shrinkPlayfieldDownwards; + } - public static boolean isHideReplayMarquee() { - return hideReplayMarquee; - } + public static boolean isHideReplayMarquee() { + return hideReplayMarquee; + } - public static void setHideReplayMarquee(boolean hideReplayMarquee) { - Config.hideReplayMarquee = hideReplayMarquee; - } + public static void setHideReplayMarquee(boolean hideReplayMarquee) { + Config.hideReplayMarquee = hideReplayMarquee; + } - public static boolean isHideInGameUI() { - return hideInGameUI; - } + public static boolean isHideInGameUI() { + return hideInGameUI; + } - public static void setHideInGameUI(boolean hideInGameUI) { - Config.hideInGameUI = hideInGameUI; - } + public static void setHideInGameUI(boolean hideInGameUI) { + Config.hideInGameUI = hideInGameUI; + } - public static boolean isReceiveAnnouncements() { - return receiveAnnouncements; - } + public static boolean isReceiveAnnouncements() { + return receiveAnnouncements; + } - public static void setReceiveAnnouncements(boolean receiveAnnouncements) { - Config.receiveAnnouncements = receiveAnnouncements; - } + public static void setReceiveAnnouncements(boolean receiveAnnouncements) { + Config.receiveAnnouncements = receiveAnnouncements; + } - public static boolean isSafeBeatmapBg() { - return safeBeatmapBg; - } + public static boolean isSafeBeatmapBg() { + return safeBeatmapBg; + } - public static void setSafeBeatmapBg(boolean safeBeatmapBg) { - Config.safeBeatmapBg = safeBeatmapBg; - } + public static void setSafeBeatmapBg(boolean safeBeatmapBg) { + Config.safeBeatmapBg = safeBeatmapBg; + } - public static boolean isTrianglesAnimation() { - return trianglesAnimation; - } + public static boolean isTrianglesAnimation() { + return trianglesAnimation; + } - public static void setTrianglesAnimation(boolean trianglesAnimation) { - Config.trianglesAnimation = trianglesAnimation; - } + public static void setTrianglesAnimation(boolean trianglesAnimation) { + Config.trianglesAnimation = trianglesAnimation; + } - public static String getDefaultCorePath() { - return defaultCorePath; - } + public static String getDefaultCorePath() { + return defaultCorePath; + } - public static Map getSkins(){ - return skins; - } + public static Map getSkins(){ + return skins; + } - public static void addSkin(String name, String path) { - if(skins == null) skins = new HashMap(); - skins.put(name, path); - } + public static void addSkin(String name, String path) { + if(skins == null) skins = new HashMap(); + skins.put(name, path); + } -} \ No newline at end of file +} diff --git a/src/ru/nsu/ccfit/zuev/osu/Constants.java b/src/ru/nsu/ccfit/zuev/osu/Constants.java index 2e738093..520b71fe 100644 --- a/src/ru/nsu/ccfit/zuev/osu/Constants.java +++ b/src/ru/nsu/ccfit/zuev/osu/Constants.java @@ -1,20 +1,20 @@ package ru.nsu.ccfit.zuev.osu; public class Constants { - public static final int MAP_WIDTH = 512; - public static final int MAP_HEIGHT = 384; - public static final int MAP_ACTUAL_WIDTH_OLD = 820; - public static final int MAP_ACTUAL_HEIGHT_OLD = 570; - public static final int MAP_ACTUAL_HEIGHT = (int) (Config.getRES_HEIGHT() * 0.85f); - public static final int MAP_ACTUAL_WIDTH = MAP_ACTUAL_HEIGHT / 3 * 4; - public static final int SLIDER_STEP = 10; - public static final int HIGH_SLIDER_STEP = 14; - public static final String DDL_URL_HTTPS = "https://osu.yas-online.net"; - public static final String DDL_URL = "http://osu.yas-online.net"; - public static final String[] SAMPLE_PREFIX = {"", "normal", "soft", "drum"}; - public static final String SERVICE_ENDPOINT = "http://ops.dgsrz.com/api/"; - public static final String SERVICE_IDL_VERSION = "29"; + public static final int MAP_WIDTH = 512; + public static final int MAP_HEIGHT = 384; + public static final int MAP_ACTUAL_WIDTH_OLD = 820; + public static final int MAP_ACTUAL_HEIGHT_OLD = 570; + public static final int MAP_ACTUAL_HEIGHT = (int) (Config.getRES_HEIGHT() * 0.85f); + public static final int MAP_ACTUAL_WIDTH = MAP_ACTUAL_HEIGHT / 3 * 4; + public static final int SLIDER_STEP = 10; + public static final int HIGH_SLIDER_STEP = 14; + public static final String DDL_URL_HTTPS = "https://osu.yas-online.net"; + public static final String DDL_URL = "http://osu.yas-online.net"; + public static final String[] SAMPLE_PREFIX = {"", "normal", "soft", "drum"}; + public static final String SERVICE_ENDPOINT = "http://ops.dgsrz.com/api/"; + public static final String SERVICE_IDL_VERSION = "29"; - private Constants() { - } + private Constants() { + } } diff --git a/src/ru/nsu/ccfit/zuev/osu/GlobalManager.java b/src/ru/nsu/ccfit/zuev/osu/GlobalManager.java index 796ee3f7..50747c4d 100644 --- a/src/ru/nsu/ccfit/zuev/osu/GlobalManager.java +++ b/src/ru/nsu/ccfit/zuev/osu/GlobalManager.java @@ -16,164 +16,164 @@ * Created by Fuuko on 2015/4/24. */ public class GlobalManager { - private static GlobalManager instance; - private Engine engine; - private Camera camera; - private GameScene gameScene; - private MainScene mainScene; - private ScoringScene scoring; - private SongMenu songMenu; - private MainActivity mainActivity; - private int loadingProgress; - private String info; - private SongService songService; - private TrackInfo selectedTrack; - private SaveServiceObject saveServiceObject; - private String skinNow; - - public static GlobalManager getInstance() { - if (instance == null) { - instance = new GlobalManager(); - } - return instance; - } - - public TrackInfo getSelectedTrack() { - return selectedTrack; - } - - public void setSelectedTrack(TrackInfo selectedTrack) { - if (selectedTrack == null) return; - this.selectedTrack = selectedTrack; - } - - public void init() { - saveServiceObject = (SaveServiceObject) mainActivity.getApplication(); - songService = saveServiceObject.getSongService(); - setLoadingProgress(10); - setMainScene(new MainScene()); - getMainScene().load(mainActivity); - setInfo("Loading skin..."); - skinNow = Config.getSkinPath(); - ResourceManager.getInstance().loadSkin(skinNow); - ScoreLibrary.getInstance().load(mainActivity); - setLoadingProgress(20); - PropertiesLibrary.getInstance().load(mainActivity); - setLoadingProgress(30); - setGameScene(new GameScene(getEngine())); - setSongMenu(new SongMenu()); - setLoadingProgress(40); - getSongMenu().init(mainActivity, getEngine(), getGameScene()); - getSongMenu().load(); - setScoring(new ScoringScene(getEngine(), getGameScene(), getSongMenu())); - getSongMenu().setScoringScene(getScoring()); - getGameScene().setScoringScene(getScoring()); - getGameScene().setOldScene(getSongMenu().getScene()); - if (songService != null) { - songService.stop(); - songService.hideNotifyPanel(); - } - } - - public Engine getEngine() { - return engine; - } - - public void setEngine(Engine engine) { - this.engine = engine; - } - - public String getSkinNow() { - return skinNow; - } - - public void setSkinNow(String skinNow) { - this.skinNow = skinNow; - } - - public Camera getCamera() { - return camera; - } - - public void setCamera(Camera camera) { - this.camera = camera; - } - - public GameScene getGameScene() { - return gameScene; - } - - public void setGameScene(GameScene gameScene) { - this.gameScene = gameScene; - } - - public MainScene getMainScene() { - return mainScene; - } - - public void setMainScene(MainScene mainScene) { - this.mainScene = mainScene; - } - - public ScoringScene getScoring() { - return scoring; - } - - public void setScoring(ScoringScene scoring) { - this.scoring = scoring; - } - - public SongMenu getSongMenu() { - return songMenu; - } - - public void setSongMenu(SongMenu songMenu) { - this.songMenu = songMenu; - } - - public MainActivity getMainActivity() { - return mainActivity; - } - - public void setMainActivity(MainActivity mainActivity) { - this.mainActivity = mainActivity; - } - - public int getLoadingProgress() { - return loadingProgress; - } - - public void setLoadingProgress(int loadingProgress) { - this.loadingProgress = loadingProgress; - } - - public String getInfo() { - return info; - } - - public void setInfo(String info) { - this.info = info; - } - - public SongService getSongService() { - return songService; - } - - public void setSongService(SongService songService) { - this.songService = songService; - } - - public SaveServiceObject getSaveServiceObject() { - return saveServiceObject; - } - - public void setSaveServiceObject(SaveServiceObject saveServiceObject) { - this.saveServiceObject = saveServiceObject; - } - - public DisplayMetrics getDisplayMetrics() { - final DisplayMetrics dm = new DisplayMetrics(); - mainActivity.getWindowManager().getDefaultDisplay().getMetrics(dm); - return dm; - } + private static GlobalManager instance; + private Engine engine; + private Camera camera; + private GameScene gameScene; + private MainScene mainScene; + private ScoringScene scoring; + private SongMenu songMenu; + private MainActivity mainActivity; + private int loadingProgress; + private String info; + private SongService songService; + private TrackInfo selectedTrack; + private SaveServiceObject saveServiceObject; + private String skinNow; + + public static GlobalManager getInstance() { + if (instance == null) { + instance = new GlobalManager(); + } + return instance; + } + + public TrackInfo getSelectedTrack() { + return selectedTrack; + } + + public void setSelectedTrack(TrackInfo selectedTrack) { + if (selectedTrack == null) return; + this.selectedTrack = selectedTrack; + } + + public void init() { + saveServiceObject = (SaveServiceObject) mainActivity.getApplication(); + songService = saveServiceObject.getSongService(); + setLoadingProgress(10); + setMainScene(new MainScene()); + getMainScene().load(mainActivity); + setInfo("Loading skin..."); + skinNow = Config.getSkinPath(); + ResourceManager.getInstance().loadSkin(skinNow); + ScoreLibrary.getInstance().load(mainActivity); + setLoadingProgress(20); + PropertiesLibrary.getInstance().load(mainActivity); + setLoadingProgress(30); + setGameScene(new GameScene(getEngine())); + setSongMenu(new SongMenu()); + setLoadingProgress(40); + getSongMenu().init(mainActivity, getEngine(), getGameScene()); + getSongMenu().load(); + setScoring(new ScoringScene(getEngine(), getGameScene(), getSongMenu())); + getSongMenu().setScoringScene(getScoring()); + getGameScene().setScoringScene(getScoring()); + getGameScene().setOldScene(getSongMenu().getScene()); + if (songService != null) { + songService.stop(); + songService.hideNotifyPanel(); + } + } + + public Engine getEngine() { + return engine; + } + + public void setEngine(Engine engine) { + this.engine = engine; + } + + public String getSkinNow() { + return skinNow; + } + + public void setSkinNow(String skinNow) { + this.skinNow = skinNow; + } + + public Camera getCamera() { + return camera; + } + + public void setCamera(Camera camera) { + this.camera = camera; + } + + public GameScene getGameScene() { + return gameScene; + } + + public void setGameScene(GameScene gameScene) { + this.gameScene = gameScene; + } + + public MainScene getMainScene() { + return mainScene; + } + + public void setMainScene(MainScene mainScene) { + this.mainScene = mainScene; + } + + public ScoringScene getScoring() { + return scoring; + } + + public void setScoring(ScoringScene scoring) { + this.scoring = scoring; + } + + public SongMenu getSongMenu() { + return songMenu; + } + + public void setSongMenu(SongMenu songMenu) { + this.songMenu = songMenu; + } + + public MainActivity getMainActivity() { + return mainActivity; + } + + public void setMainActivity(MainActivity mainActivity) { + this.mainActivity = mainActivity; + } + + public int getLoadingProgress() { + return loadingProgress; + } + + public void setLoadingProgress(int loadingProgress) { + this.loadingProgress = loadingProgress; + } + + public String getInfo() { + return info; + } + + public void setInfo(String info) { + this.info = info; + } + + public SongService getSongService() { + return songService; + } + + public void setSongService(SongService songService) { + this.songService = songService; + } + + public SaveServiceObject getSaveServiceObject() { + return saveServiceObject; + } + + public void setSaveServiceObject(SaveServiceObject saveServiceObject) { + this.saveServiceObject = saveServiceObject; + } + + public DisplayMetrics getDisplayMetrics() { + final DisplayMetrics dm = new DisplayMetrics(); + mainActivity.getWindowManager().getDefaultDisplay().getMetrics(dm); + return dm; + } } diff --git a/src/ru/nsu/ccfit/zuev/osu/LibraryManager.java b/src/ru/nsu/ccfit/zuev/osu/LibraryManager.java index 98297f11..f40851a0 100644 --- a/src/ru/nsu/ccfit/zuev/osu/LibraryManager.java +++ b/src/ru/nsu/ccfit/zuev/osu/LibraryManager.java @@ -26,481 +26,481 @@ import ru.nsu.ccfit.zuev.osuplus.R; public class LibraryManager { - private static final String VERSION = "library3.4"; - private static LibraryManager mgr = new LibraryManager(); - private ArrayList library; - private Integer fileCount = 0; - private int currentIndex = 0; - - private LibraryManager() { - } - - public static LibraryManager getInstance() { - return mgr; - } - - public File getLibraryCacheFile() { - return new File(GlobalManager.getInstance().getMainActivity().getFilesDir(), String.format("library.%s.dat", VERSION)); - } - - @SuppressWarnings("unchecked") - public boolean loadLibraryCache(final Activity activity, boolean forceUpdate) { - library = new ArrayList(); - ToastLogger.addToLog("Loading library..."); - if (OSZParser.canUseSD() == false) { - ToastLogger.addToLog("Can't use SD card!"); - return true; - } - - final File replayDir = new File(Config.getScorePath()); - if (replayDir.exists() == false) { - if (replayDir.mkdir() == false) { - ToastLogger.showText(StringTable.format( - R.string.message_error_createdir, replayDir.getPath()), true); - return false; - } - final File nomedia = new File(replayDir.getParentFile(), ".nomedia"); - try { - nomedia.createNewFile(); - } catch (final IOException e) { - Debug.e("LibraryManager: " + e.getMessage(), e); - } - } - - final File lib = getLibraryCacheFile(); - //Log.i("ed-d", "load cache from " + lib.getAbsolutePath()); - final File dir = new File(Config.getBeatmapPath()); - if (!dir.exists()) { - return false; - } - try { - if (!lib.exists()) { - lib.createNewFile(); - } - final ObjectInputStream istream = new ObjectInputStream( - new FileInputStream(lib)); - Object obj = istream.readObject(); - //Log.i("ed-d", "load cache step 1"); - if (obj instanceof String) { - if (((String) obj).equals(VERSION) == false) { - istream.close(); - return false; - } - } else { - istream.close(); - return false; - } - //Log.i("ed-d", "load cache step 2"); - obj = istream.readObject(); - if (obj instanceof Integer) { - fileCount = (Integer) obj; - } else { - istream.close(); - return false; - } - //Log.i("ed-d", "load cache step 3"); - obj = istream.readObject(); - if (obj instanceof ArrayList) { - //Log.i("ed-d", "load cache step 4"); - library = (ArrayList) obj; - istream.close(); - ToastLogger.addToLog("Library loaded"); - //Log.i("ed-d", "load cache step 5"); - //for (BeatmapInfo info : library) { - // Log.i("ed-d", "cache : " + info.getPath()); - //} - if (forceUpdate) { - //Log.i("ed-d", "load cache step 6"); - checkLibrary(activity); - //Log.i("ed-d", "load cache step 7"); - } - return true; - } - istream.close(); - //Log.i("ed-d", "load cache"); - return false; - } catch (final FileNotFoundException e) { - Debug.e("LibraryManager: " + e.getMessage(), e); - } catch (final IOException e) { - Debug.e("LibraryManager: " + e.getMessage(), e); - } catch (final ClassNotFoundException e) { - Debug.e("LibraryManager: " + e.getMessage(), e); - } catch (final ClassCastException e) { - Debug.e("LibraryManager: " + e.getMessage(), e); - } - ToastLogger.addToLog("Cannot load library!"); - return false; - } - - private void checkLibrary(final Activity activity) { - final File dir = new File(Config.getBeatmapPath()); - final File[] files = FileUtils.listFiles(dir); - if (files.length == fileCount) { - return; - } - ToastLogger - .showText(StringTable.get(R.string.message_lib_update), true); - final int fileCount = files.length; - int fileCached = 0; - LinkedList cachedFiles = new LinkedList(); - for (final File f : files) { - GlobalManager.getInstance().setLoadingProgress(50 + 50 * fileCached / fileCount); - ToastLogger.setPercentage(fileCached * 100f / fileCount); - fileCached++; - addBeatmap(f, cachedFiles); - } - final LinkedList uncached = new LinkedList(); - for (final BeatmapInfo i : library) { - if (!cachedFiles.contains(i.getPath())) { - uncached.add(i); - } - } - for (final BeatmapInfo i : uncached) { - library.remove(i); - } - this.fileCount = files.length; - savetoCache(activity); - } - - public void scanLibrary(final Activity activity) { - //ToastLogger.showText(StringTable.get(R.string.message_lib_caching), - // false); - ToastLogger.addToLog("Caching library..."); - library.clear(); - - final File dir = new File(Config.getBeatmapPath()); - // Creating Osu directory if it doesn't exist - if (!dir.exists()) { - if (!dir.mkdirs()) { - ToastLogger.showText(StringTable.format( - R.string.message_error_createdir, dir.getPath()), true); - return; - } - final File nomedia = new File(dir.getParentFile(), ".nomedia"); - try { - nomedia.createNewFile(); - } catch (final IOException e) { - Debug.e("LibraryManager: " + e.getMessage(), e); - } - return; - } - // Getting all files - int totalMaps = 0; - final File[] filelist = FileUtils.listFiles(dir); - // Here we go! - final int fileCount = filelist.length; - this.fileCount = fileCount; - int fileCached = 0; - for (final File file : filelist) { - GlobalManager.getInstance().setLoadingProgress(50 + 50 * fileCached / fileCount); - ToastLogger.setPercentage(fileCached * 100f / fileCount); - fileCached++; - if (!file.isDirectory()) { - continue; - } - - GlobalManager.getInstance().setInfo("Loading " + file.getName() + "..."); - final BeatmapInfo info = new BeatmapInfo(); - info.setPath(file.getPath()); - scanFolder(info); - if (info.getCount() < 1) { - continue; - } - info.setCreator(info.getTrack(0).getCreator()); - if (info.getTitle().equals("")) { - info.setTitle("unknown"); - } - if (info.getArtist().equals("")) { - info.setArtist("unknown"); - } - if (info.getCreator().equals("")) { - info.setCreator("unknown"); - } - library.add(info); - totalMaps += info.getCount(); - // totalMaps += loadFolder(file); - } - - // sort(); - - savetoCache(activity); - ToastLogger.showText( - StringTable.format(R.string.message_lib_complete, totalMaps), - true); - } - - /* - public int loadFolder(File folder) { - final BeatmapInfo info = new BeatmapInfo(); - info.setPath(folder.getPath()); - scanFolder(info); - if (info.getCount() == 0) { - return 0; - } - - info.setCreator(info.getTrack(0).getCreator()); - if (info.getTitle().equals("")) { - info.setTitle("unknown"); - } - if (info.getArtist().equals("")) { - info.setArtist("unknown"); - } - if (info.getCreator().equals("")) { - info.setCreator("unknown"); - } - library.add(info); - return info.getCount(); - }*/ - - // NOTE: IS THIS EVEN USED????? - public void updateMapSet(File folder, BeatmapInfo beatmapInfo) { - library.remove(beatmapInfo); - // loadFolder(folder); - savetoCache(GlobalManager.getInstance().getMainActivity()); - } - - /* public void sort() { - * - * Collections.sort(library, new Comparator() { - * - * public int compare(final BeatmapInfo object1, final - * BeatmapInfo object2) { return object1.getTitle().compareToIgnoreCase( - * object2.getTitle()); } }); - * - }*/ - - public void deleteDir(final File dir) { - if (dir.exists() == false || dir.isDirectory() == false) { - return; - } - final File[] files = FileUtils.listFiles(dir); - if (files == null) { - return; - } - for (final File f : files) { - if (f.isDirectory()) { - deleteDir(f); - } else if (f.delete()) { - Debug.i(f.getPath() + " deleted"); - } - } - if (dir.delete()) { - Debug.i(dir.getPath() + " deleted"); - } - } - - public void deleteMap(final BeatmapInfo info) { - final File dir = new File(info.getPath()); - deleteDir(dir); - if (library != null) { - library.remove(info); - } - } - - public void savetoCache(final Activity activity) { - if (library.isEmpty()) { - return; - } - final File lib = getLibraryCacheFile(); - try { - if (!lib.exists()) { - lib.createNewFile(); - } - final ObjectOutputStream ostream = new ObjectOutputStream( - new FileOutputStream(lib)); - ostream.writeObject(VERSION); - ostream.writeObject(fileCount); - ostream.writeObject(library); - ostream.close(); - } catch (final FileNotFoundException e) { - ToastLogger.showText( - StringTable.format(R.string.message_error, e.getMessage()), - false); - Debug.e("LibraryManager: " + e.getMessage(), e); - } catch (final IOException e) { - ToastLogger.showText( - StringTable.format(R.string.message_error, e.getMessage()), - false); - Debug.e("LibraryManager: " + e.getMessage(), e); - } - shuffleLibrary(); - currentIndex = 0; - } - - public void clearCache() { - final File lib = getLibraryCacheFile(); - if (lib.exists()) { - lib.delete(); - ToastLogger.showText(StringTable.get(R.string.message_lib_cleared), - false); - } - currentIndex = 0; - } - - public void addBeatmap(final File file, LinkedList cachedFiles) { - if (file.isDirectory() == false) { - return; - } - GlobalManager.getInstance().setInfo("Loading " + file.getName() + " ..."); - final BeatmapInfo info = new BeatmapInfo(); - info.setPath(file.getPath()); - for (final BeatmapInfo i : library) { - if (i.getPath().substring(i.getPath().lastIndexOf('/')) - .equals(info.getPath().substring(info.getPath().lastIndexOf('/')))) { - //Log.i("ed-d", "found " + i.getPath()); - if (cachedFiles != null) { - cachedFiles.add(i.getPath()); - } - return; - } - } - //Log.i("ed-d", "not found " + info.getPath()); - if (cachedFiles != null) { - cachedFiles.add(info.getPath()); - } - - scanFolder(info); - if (info.getCount() == 0) { - return; - } - - info.setCreator(info.getTrack(0).getCreator()); - if (info.getTitle().equals("")) { - info.setTitle("unknown"); - } - if (info.getArtist().equals("")) { - info.setArtist("unknown"); - } - if (info.getCreator().equals("")) { - info.setCreator("unknown"); - } - - library.add(info); - } - - private void scanFolder(final BeatmapInfo info) { - final File dir = new File(info.getPath()); - info.setDate(dir.lastModified()); - File[] filelist = FileUtils.listFiles(dir, ".osu"); - - if (filelist == null) { - return; - } - for (final File file : filelist) { - final OSUParser parser = new OSUParser(file); - if (!parser.openFile()) { - continue; - } - - final TrackInfo track = new TrackInfo(info); - track.setFilename(file.getPath()); - track.setCreator("unknown"); - if (!parser.readMetaData(track, info)) { - continue; - } - if (track.getBackground() != null) { - track.setBackground(info.getPath() + "/" - + track.getBackground()); - } - info.addTrack(track); - } - - Collections.sort(info.getTracks(), new Comparator() { - public int compare(final TrackInfo object1, final TrackInfo object2) { - return Float.valueOf(object1.getDifficulty()).compareTo(object2.getDifficulty()); - } - }); - } - - public ArrayList getLibrary() { - return library; - } - - public void shuffleLibrary() { - if (library != null) { - Collections.shuffle(library); - } - } - - public int getSizeOfBeatmaps() { - if (library != null) { - return library.size(); - } else { - return 0; - } - } - - public BeatmapInfo getBeatmap() { - return getBeatmapByIndex(currentIndex); - } - - public BeatmapInfo getNextBeatmap() { - return getBeatmapByIndex(++currentIndex); - } - - public BeatmapInfo getPrevBeatmap() { - return getBeatmapByIndex(--currentIndex); - } - - public BeatmapInfo getBeatmapByIndex(int index) { - Debug.i("Music Changing Info: Require index :" + index + "/" + library.size()); - if (library == null || library.size() <= 0) return null; - if (index < 0 || index >= library.size()) { - shuffleLibrary(); - currentIndex = 0; - return library.get(0); - } else { - currentIndex = index; - return library.get(index); - } - } - - public int findBeatmap(BeatmapInfo info) { - if (library != null && library.size() > 0) { - for (int i = 0; i < library.size(); i++) { - if (library.get(i).equals(info)) { - return currentIndex = i; - } - } - } - return currentIndex = 0; - } - - public int findBeatmapById(int mapSetId) { - if (library != null && library.size() > 0) { - for (int i = 0; i < library.size(); i++) { - if (library.get(i).getTrack(0).getBeatmapSetID() == mapSetId) { - return currentIndex = i; - } - } - } - return currentIndex = 0; - } - - public int getCurrentIndex() { - return this.currentIndex; - } - - public void setCurrentIndex(int index) { - this.currentIndex = index; - } - - public TrackInfo findTrackByFileNameAndMD5(String fileName, String md5) { - if (library != null && library.size() > 0) { - for (int i = 0; i < library.size(); i++) { - BeatmapInfo info = library.get(i); - for (int j = 0; j < info.getCount(); j++) { - TrackInfo track = info.getTrack(j); - File trackFile = new File(track.getFilename()); - if (fileName.equals(trackFile.getName())) { - String trackMD5 = FileUtils.getMD5Checksum(trackFile); - if (md5.equals(trackMD5)) { - return track; - } - } - } - } - } - return null; - } + private static final String VERSION = "library3.4"; + private static LibraryManager mgr = new LibraryManager(); + private ArrayList library; + private Integer fileCount = 0; + private int currentIndex = 0; + + private LibraryManager() { + } + + public static LibraryManager getInstance() { + return mgr; + } + + public File getLibraryCacheFile() { + return new File(GlobalManager.getInstance().getMainActivity().getFilesDir(), String.format("library.%s.dat", VERSION)); + } + + @SuppressWarnings("unchecked") + public boolean loadLibraryCache(final Activity activity, boolean forceUpdate) { + library = new ArrayList(); + ToastLogger.addToLog("Loading library..."); + if (OSZParser.canUseSD() == false) { + ToastLogger.addToLog("Can't use SD card!"); + return true; + } + + final File replayDir = new File(Config.getScorePath()); + if (replayDir.exists() == false) { + if (replayDir.mkdir() == false) { + ToastLogger.showText(StringTable.format( + R.string.message_error_createdir, replayDir.getPath()), true); + return false; + } + final File nomedia = new File(replayDir.getParentFile(), ".nomedia"); + try { + nomedia.createNewFile(); + } catch (final IOException e) { + Debug.e("LibraryManager: " + e.getMessage(), e); + } + } + + final File lib = getLibraryCacheFile(); + //Log.i("ed-d", "load cache from " + lib.getAbsolutePath()); + final File dir = new File(Config.getBeatmapPath()); + if (!dir.exists()) { + return false; + } + try { + if (!lib.exists()) { + lib.createNewFile(); + } + final ObjectInputStream istream = new ObjectInputStream( + new FileInputStream(lib)); + Object obj = istream.readObject(); + //Log.i("ed-d", "load cache step 1"); + if (obj instanceof String) { + if (((String) obj).equals(VERSION) == false) { + istream.close(); + return false; + } + } else { + istream.close(); + return false; + } + //Log.i("ed-d", "load cache step 2"); + obj = istream.readObject(); + if (obj instanceof Integer) { + fileCount = (Integer) obj; + } else { + istream.close(); + return false; + } + //Log.i("ed-d", "load cache step 3"); + obj = istream.readObject(); + if (obj instanceof ArrayList) { + //Log.i("ed-d", "load cache step 4"); + library = (ArrayList) obj; + istream.close(); + ToastLogger.addToLog("Library loaded"); + //Log.i("ed-d", "load cache step 5"); + //for (BeatmapInfo info : library) { + // Log.i("ed-d", "cache : " + info.getPath()); + //} + if (forceUpdate) { + //Log.i("ed-d", "load cache step 6"); + checkLibrary(activity); + //Log.i("ed-d", "load cache step 7"); + } + return true; + } + istream.close(); + //Log.i("ed-d", "load cache"); + return false; + } catch (final FileNotFoundException e) { + Debug.e("LibraryManager: " + e.getMessage(), e); + } catch (final IOException e) { + Debug.e("LibraryManager: " + e.getMessage(), e); + } catch (final ClassNotFoundException e) { + Debug.e("LibraryManager: " + e.getMessage(), e); + } catch (final ClassCastException e) { + Debug.e("LibraryManager: " + e.getMessage(), e); + } + ToastLogger.addToLog("Cannot load library!"); + return false; + } + + private void checkLibrary(final Activity activity) { + final File dir = new File(Config.getBeatmapPath()); + final File[] files = FileUtils.listFiles(dir); + if (files.length == fileCount) { + return; + } + ToastLogger + .showText(StringTable.get(R.string.message_lib_update), true); + final int fileCount = files.length; + int fileCached = 0; + LinkedList cachedFiles = new LinkedList(); + for (final File f : files) { + GlobalManager.getInstance().setLoadingProgress(50 + 50 * fileCached / fileCount); + ToastLogger.setPercentage(fileCached * 100f / fileCount); + fileCached++; + addBeatmap(f, cachedFiles); + } + final LinkedList uncached = new LinkedList(); + for (final BeatmapInfo i : library) { + if (!cachedFiles.contains(i.getPath())) { + uncached.add(i); + } + } + for (final BeatmapInfo i : uncached) { + library.remove(i); + } + this.fileCount = files.length; + savetoCache(activity); + } + + public void scanLibrary(final Activity activity) { + //ToastLogger.showText(StringTable.get(R.string.message_lib_caching), + // false); + ToastLogger.addToLog("Caching library..."); + library.clear(); + + final File dir = new File(Config.getBeatmapPath()); + // Creating Osu directory if it doesn't exist + if (!dir.exists()) { + if (!dir.mkdirs()) { + ToastLogger.showText(StringTable.format( + R.string.message_error_createdir, dir.getPath()), true); + return; + } + final File nomedia = new File(dir.getParentFile(), ".nomedia"); + try { + nomedia.createNewFile(); + } catch (final IOException e) { + Debug.e("LibraryManager: " + e.getMessage(), e); + } + return; + } + // Getting all files + int totalMaps = 0; + final File[] filelist = FileUtils.listFiles(dir); + // Here we go! + final int fileCount = filelist.length; + this.fileCount = fileCount; + int fileCached = 0; + for (final File file : filelist) { + GlobalManager.getInstance().setLoadingProgress(50 + 50 * fileCached / fileCount); + ToastLogger.setPercentage(fileCached * 100f / fileCount); + fileCached++; + if (!file.isDirectory()) { + continue; + } + + GlobalManager.getInstance().setInfo("Loading " + file.getName() + "..."); + final BeatmapInfo info = new BeatmapInfo(); + info.setPath(file.getPath()); + scanFolder(info); + if (info.getCount() < 1) { + continue; + } + info.setCreator(info.getTrack(0).getCreator()); + if (info.getTitle().equals("")) { + info.setTitle("unknown"); + } + if (info.getArtist().equals("")) { + info.setArtist("unknown"); + } + if (info.getCreator().equals("")) { + info.setCreator("unknown"); + } + library.add(info); + totalMaps += info.getCount(); + // totalMaps += loadFolder(file); + } + + // sort(); + + savetoCache(activity); + ToastLogger.showText( + StringTable.format(R.string.message_lib_complete, totalMaps), + true); + } + + /* + public int loadFolder(File folder) { + final BeatmapInfo info = new BeatmapInfo(); + info.setPath(folder.getPath()); + scanFolder(info); + if (info.getCount() == 0) { + return 0; + } + + info.setCreator(info.getTrack(0).getCreator()); + if (info.getTitle().equals("")) { + info.setTitle("unknown"); + } + if (info.getArtist().equals("")) { + info.setArtist("unknown"); + } + if (info.getCreator().equals("")) { + info.setCreator("unknown"); + } + library.add(info); + return info.getCount(); + }*/ + + // NOTE: IS THIS EVEN USED????? + public void updateMapSet(File folder, BeatmapInfo beatmapInfo) { + library.remove(beatmapInfo); + // loadFolder(folder); + savetoCache(GlobalManager.getInstance().getMainActivity()); + } + + /* public void sort() { + * + * Collections.sort(library, new Comparator() { + * + * public int compare(final BeatmapInfo object1, final + * BeatmapInfo object2) { return object1.getTitle().compareToIgnoreCase( + * object2.getTitle()); } }); + * + }*/ + + public void deleteDir(final File dir) { + if (dir.exists() == false || dir.isDirectory() == false) { + return; + } + final File[] files = FileUtils.listFiles(dir); + if (files == null) { + return; + } + for (final File f : files) { + if (f.isDirectory()) { + deleteDir(f); + } else if (f.delete()) { + Debug.i(f.getPath() + " deleted"); + } + } + if (dir.delete()) { + Debug.i(dir.getPath() + " deleted"); + } + } + + public void deleteMap(final BeatmapInfo info) { + final File dir = new File(info.getPath()); + deleteDir(dir); + if (library != null) { + library.remove(info); + } + } + + public void savetoCache(final Activity activity) { + if (library.isEmpty()) { + return; + } + final File lib = getLibraryCacheFile(); + try { + if (!lib.exists()) { + lib.createNewFile(); + } + final ObjectOutputStream ostream = new ObjectOutputStream( + new FileOutputStream(lib)); + ostream.writeObject(VERSION); + ostream.writeObject(fileCount); + ostream.writeObject(library); + ostream.close(); + } catch (final FileNotFoundException e) { + ToastLogger.showText( + StringTable.format(R.string.message_error, e.getMessage()), + false); + Debug.e("LibraryManager: " + e.getMessage(), e); + } catch (final IOException e) { + ToastLogger.showText( + StringTable.format(R.string.message_error, e.getMessage()), + false); + Debug.e("LibraryManager: " + e.getMessage(), e); + } + shuffleLibrary(); + currentIndex = 0; + } + + public void clearCache() { + final File lib = getLibraryCacheFile(); + if (lib.exists()) { + lib.delete(); + ToastLogger.showText(StringTable.get(R.string.message_lib_cleared), + false); + } + currentIndex = 0; + } + + public void addBeatmap(final File file, LinkedList cachedFiles) { + if (file.isDirectory() == false) { + return; + } + GlobalManager.getInstance().setInfo("Loading " + file.getName() + " ..."); + final BeatmapInfo info = new BeatmapInfo(); + info.setPath(file.getPath()); + for (final BeatmapInfo i : library) { + if (i.getPath().substring(i.getPath().lastIndexOf('/')) + .equals(info.getPath().substring(info.getPath().lastIndexOf('/')))) { + //Log.i("ed-d", "found " + i.getPath()); + if (cachedFiles != null) { + cachedFiles.add(i.getPath()); + } + return; + } + } + //Log.i("ed-d", "not found " + info.getPath()); + if (cachedFiles != null) { + cachedFiles.add(info.getPath()); + } + + scanFolder(info); + if (info.getCount() == 0) { + return; + } + + info.setCreator(info.getTrack(0).getCreator()); + if (info.getTitle().equals("")) { + info.setTitle("unknown"); + } + if (info.getArtist().equals("")) { + info.setArtist("unknown"); + } + if (info.getCreator().equals("")) { + info.setCreator("unknown"); + } + + library.add(info); + } + + private void scanFolder(final BeatmapInfo info) { + final File dir = new File(info.getPath()); + info.setDate(dir.lastModified()); + File[] filelist = FileUtils.listFiles(dir, ".osu"); + + if (filelist == null) { + return; + } + for (final File file : filelist) { + final OSUParser parser = new OSUParser(file); + if (!parser.openFile()) { + continue; + } + + final TrackInfo track = new TrackInfo(info); + track.setFilename(file.getPath()); + track.setCreator("unknown"); + if (!parser.readMetaData(track, info)) { + continue; + } + if (track.getBackground() != null) { + track.setBackground(info.getPath() + "/" + + track.getBackground()); + } + info.addTrack(track); + } + + Collections.sort(info.getTracks(), new Comparator() { + public int compare(final TrackInfo object1, final TrackInfo object2) { + return Float.valueOf(object1.getDifficulty()).compareTo(object2.getDifficulty()); + } + }); + } + + public ArrayList getLibrary() { + return library; + } + + public void shuffleLibrary() { + if (library != null) { + Collections.shuffle(library); + } + } + + public int getSizeOfBeatmaps() { + if (library != null) { + return library.size(); + } else { + return 0; + } + } + + public BeatmapInfo getBeatmap() { + return getBeatmapByIndex(currentIndex); + } + + public BeatmapInfo getNextBeatmap() { + return getBeatmapByIndex(++currentIndex); + } + + public BeatmapInfo getPrevBeatmap() { + return getBeatmapByIndex(--currentIndex); + } + + public BeatmapInfo getBeatmapByIndex(int index) { + Debug.i("Music Changing Info: Require index :" + index + "/" + library.size()); + if (library == null || library.size() <= 0) return null; + if (index < 0 || index >= library.size()) { + shuffleLibrary(); + currentIndex = 0; + return library.get(0); + } else { + currentIndex = index; + return library.get(index); + } + } + + public int findBeatmap(BeatmapInfo info) { + if (library != null && library.size() > 0) { + for (int i = 0; i < library.size(); i++) { + if (library.get(i).equals(info)) { + return currentIndex = i; + } + } + } + return currentIndex = 0; + } + + public int findBeatmapById(int mapSetId) { + if (library != null && library.size() > 0) { + for (int i = 0; i < library.size(); i++) { + if (library.get(i).getTrack(0).getBeatmapSetID() == mapSetId) { + return currentIndex = i; + } + } + } + return currentIndex = 0; + } + + public int getCurrentIndex() { + return this.currentIndex; + } + + public void setCurrentIndex(int index) { + this.currentIndex = index; + } + + public TrackInfo findTrackByFileNameAndMD5(String fileName, String md5) { + if (library != null && library.size() > 0) { + for (int i = 0; i < library.size(); i++) { + BeatmapInfo info = library.get(i); + for (int j = 0; j < info.getCount(); j++) { + TrackInfo track = info.getTrack(j); + File trackFile = new File(track.getFilename()); + if (fileName.equals(trackFile.getName())) { + String trackMD5 = FileUtils.getMD5Checksum(trackFile); + if (md5.equals(trackMD5)) { + return track; + } + } + } + } + } + return null; + } } diff --git a/src/ru/nsu/ccfit/zuev/osu/MainActivity.java b/src/ru/nsu/ccfit/zuev/osu/MainActivity.java index b7253644..7c6f769c 100644 --- a/src/ru/nsu/ccfit/zuev/osu/MainActivity.java +++ b/src/ru/nsu/ccfit/zuev/osu/MainActivity.java @@ -1,927 +1,927 @@ -package ru.nsu.ccfit.zuev.osu; - -import android.Manifest; -import android.accessibilityservice.AccessibilityServiceInfo; -import android.annotation.SuppressLint; -import android.app.AlertDialog; -import android.content.BroadcastReceiver; -import android.content.ComponentName; -import android.content.ContentResolver; -import android.content.Context; -import android.content.DialogInterface; -import android.content.Intent; -import android.content.IntentFilter; -import android.content.ServiceConnection; -import android.content.SharedPreferences; -import android.content.SharedPreferences.Editor; -import android.content.pm.PackageInfo; -import android.content.pm.PackageManager; -import android.graphics.Color; -import android.graphics.PixelFormat; -import android.os.*; - -import androidx.annotation.NonNull; -import androidx.preference.PreferenceManager; -import androidx.core.content.PermissionChecker; - -import android.util.DisplayMetrics; -import android.view.Gravity; -import android.view.KeyEvent; -import android.view.View; -import android.view.ViewGroup; -import android.view.WindowManager; -import android.view.accessibility.AccessibilityManager; -import android.widget.EditText; -import android.widget.FrameLayout; -import android.widget.RelativeLayout; - -import android.widget.Toast; -import com.edlplan.ui.ActivityOverlay; -import com.edlplan.ui.fragment.ConfirmDialogFragment; -import com.edlplan.ui.fragment.BuildTypeNoticeFragment; - -import com.google.firebase.analytics.FirebaseAnalytics; -import com.google.firebase.crashlytics.FirebaseCrashlytics; - -import org.anddev.andengine.engine.Engine; -import org.anddev.andengine.engine.camera.Camera; -import org.anddev.andengine.engine.camera.SmoothCamera; -import org.anddev.andengine.engine.options.EngineOptions; -import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; -import org.anddev.andengine.entity.scene.Scene; -import org.anddev.andengine.extension.input.touch.controller.MultiTouch; -import org.anddev.andengine.extension.input.touch.controller.MultiTouchController; -import org.anddev.andengine.extension.input.touch.exception.MultiTouchException; -import org.anddev.andengine.input.touch.TouchEvent; -import org.anddev.andengine.opengl.view.RenderSurfaceView; -import org.anddev.andengine.sensor.accelerometer.AccelerometerData; -import org.anddev.andengine.sensor.accelerometer.IAccelerometerListener; -import org.anddev.andengine.ui.activity.BaseGameActivity; -import org.anddev.andengine.util.Debug; - -import java.io.File; -import java.io.IOException; -import java.math.RoundingMode; -import java.security.Security; -import java.text.DecimalFormat; -import java.util.ArrayList; -import java.util.List; -import java.util.Random; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.TimeUnit; - -import net.lingala.zip4j.ZipFile; - -import pub.devrel.easypermissions.AppSettingsDialog; -import pub.devrel.easypermissions.EasyPermissions; -import ru.nsu.ccfit.zuev.audio.BassAudioPlayer; -import ru.nsu.ccfit.zuev.audio.serviceAudio.SaveServiceObject; -import ru.nsu.ccfit.zuev.audio.serviceAudio.SongService; -import ru.nsu.ccfit.zuev.osu.async.AsyncTaskLoader; -import ru.nsu.ccfit.zuev.osu.async.OsuAsyncCallback; -import ru.nsu.ccfit.zuev.osu.async.SyncTaskManager; -import ru.nsu.ccfit.zuev.osu.game.SpritePool; -import ru.nsu.ccfit.zuev.osu.helper.FileUtils; -import ru.nsu.ccfit.zuev.osu.helper.InputManager; -import ru.nsu.ccfit.zuev.osu.helper.StringTable; -import ru.nsu.ccfit.zuev.osu.menu.FilterMenu; -import ru.nsu.ccfit.zuev.osu.menu.LoadingScreen; -import ru.nsu.ccfit.zuev.osu.menu.ModMenu; -import ru.nsu.ccfit.zuev.osu.menu.SettingsMenu; -import ru.nsu.ccfit.zuev.osu.menu.SplashScene; -import ru.nsu.ccfit.zuev.osu.online.OnlineManager; -import ru.nsu.ccfit.zuev.osuplus.BuildConfig; -import ru.nsu.ccfit.zuev.osuplus.R; - -public class MainActivity extends BaseGameActivity implements - IAccelerometerListener { - public static SongService songService; - public ServiceConnection connection; - public BroadcastReceiver onNotifyButtonClick; - private PowerManager.WakeLock wakeLock = null; - private String beatmapToAdd = null; - private SaveServiceObject saveServiceObject; - private IntentFilter filter; - private final Handler handler = new Handler(Looper.getMainLooper()); - private FirebaseAnalytics analytics; - private FirebaseCrashlytics crashlytics; - private boolean willReplay = false; - private static boolean activityVisible = true; - private boolean autoclickerDialogShown = false; - - @Override - public Engine onLoadEngine() { - if (!checkPermissions()) { - return null; - } - analytics = FirebaseAnalytics.getInstance(this); - crashlytics = FirebaseCrashlytics.getInstance(); - Config.loadConfig(this); - initialGameDirectory(); - //Debug.setDebugLevel(Debug.DebugLevel.NONE); - StringTable.setContext(this); - ToastLogger.init(this); - SyncTaskManager.getInstance().init(this); - InputManager.setContext(this); - OnlineManager.getInstance().Init(getApplicationContext()); - crashlytics.setUserId(Config.getOnlineDeviceID()); - - final DisplayMetrics dm = new DisplayMetrics(); - getWindowManager().getDefaultDisplay().getMetrics(dm); -/* final double screenSize = Math.sqrt(Utils.sqr(dm.widthPixels / dm.xdpi) - + Utils.sqr(dm.heightPixels / dm.ydpi));*/ - double screenInches = Math.sqrt(Math.pow(dm.heightPixels, 2) + Math.pow(dm.widthPixels, 2)) / (dm.density * 160.0f); - Debug.i("screen inches: " + screenInches); - Config.setScaleMultiplier((float) ((11 - 5.2450170716245195) / 5)); - - Config.setTextureQuality(1); - final PowerManager manager = (PowerManager) getSystemService(Context.POWER_SERVICE); - wakeLock = manager.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, - "osudroid:osu"); - - Camera mCamera = new SmoothCamera(0, 0, Config.getRES_WIDTH(), - Config.getRES_HEIGHT(), 0, 1800, 1); - final EngineOptions opt = new EngineOptions(true, - null, new RatioResolutionPolicy( - Config.getRES_WIDTH(), Config.getRES_HEIGHT()), - mCamera); - opt.setNeedsMusic(true); - opt.setNeedsSound(true); - opt.getRenderOptions().disableExtensionVertexBufferObjects(); - opt.getTouchOptions().enableRunOnUpdateThread(); - final Engine engine = new Engine(opt); - try { - if (MultiTouch.isSupported(this)) { - engine.setTouchController(new MultiTouchController()); - } else { - ToastLogger.showText( - StringTable.get(R.string.message_error_multitouch), - false); - } - } catch (final MultiTouchException e) { - ToastLogger.showText( - StringTable.get(R.string.message_error_multitouch), - false); - } - GlobalManager.getInstance().setCamera(mCamera); - GlobalManager.getInstance().setEngine(engine); - GlobalManager.getInstance().setMainActivity(this); - return GlobalManager.getInstance().getEngine(); - } - - private void initialGameDirectory() { - File dir = new File(Config.getBeatmapPath()); - // Creating Osu directory if it doesn't exist - if (!dir.exists()) { - if (!dir.mkdirs()) { - Config.setBeatmapPath(Config.getCorePath() + "Songs/"); - dir = new File(Config.getBeatmapPath()); - if (!(dir.exists() || dir.mkdirs())) { - ToastLogger.showText(StringTable.format( - R.string.message_error_createdir, dir.getPath()), - true); - } else { - final SharedPreferences prefs = PreferenceManager - .getDefaultSharedPreferences(this); - final SharedPreferences.Editor editor = prefs.edit(); - editor.putString("directory", dir.getPath()); - editor.commit(); - } - - } - final File nomedia = new File(dir.getParentFile(), ".nomedia"); - try { - nomedia.createNewFile(); - } catch (final IOException e) { - Debug.e("LibraryManager: " + e.getMessage(), e); - } - } - - final File skinDir = new File(Config.getCorePath() + "/Skin"); - // Creating Osu/Skin directory if it doesn't exist - if (!skinDir.exists()) { - skinDir.mkdirs(); - } - } - - private void initPreferences() { - final SharedPreferences prefs = PreferenceManager - .getDefaultSharedPreferences(this); - - if (prefs.getString("playername", "").equals("")) { - final SharedPreferences.Editor editor = prefs.edit(); - editor.putString("playername", "Guest"); - editor.commit(); - - final AlertDialog.Builder alert = new AlertDialog.Builder(this); - - alert.setTitle(StringTable.get(R.string.dialog_playername_title)); - alert.setMessage(StringTable - .get(R.string.dialog_playername_message)); - - final EditText input = new EditText(this); - input.setText("Guest"); - alert.setView(input); - - alert.setPositiveButton(StringTable.get(R.string.dialog_ok), - new DialogInterface.OnClickListener() { - - public void onClick(final DialogInterface dialog, - final int whichButton) { - final String value = input.getText().toString(); - editor.putString("playername", value); - editor.commit(); - } - }); - - alert.show(); - } - - if (prefs.getBoolean("qualitySet", false) == false) { - final SharedPreferences.Editor editor = prefs.edit(); - editor.putBoolean("qualitySet", true); - final DisplayMetrics dm = new DisplayMetrics(); - getWindowManager().getDefaultDisplay().getMetrics(dm); - - if (dm.densityDpi > DisplayMetrics.DENSITY_MEDIUM) { - editor.putBoolean("lowtextures", false); - } else { - editor.putBoolean("lowtextures", false); - } - editor.commit(); - } - - if (prefs.getBoolean("onlineSet", false) == false) { - - Editor editor = prefs.edit(); - editor.putBoolean("onlineSet", true); - editor.commit(); - - //TODO removed auto registration at first launch - /*OnlineInitializer initializer = new OnlineInitializer(this); - initializer.createInitDialog();*/ - } - } - - @Override - public void onLoadResources() { - Config.setTextureQuality(1); - ResourceManager.getInstance().Init(mEngine, this); - ResourceManager.getInstance().loadHighQualityAsset("logo", "logo.png"); - ResourceManager.getInstance().loadHighQualityAsset("play", "play.png"); - //ResourceManager.getInstance().loadHighQualityAsset("multiplayer", "multiplayer.png"); - //ResourceManager.getInstance().loadHighQualityAsset("solo", "solo.png"); - ResourceManager.getInstance().loadHighQualityAsset("exit", "exit.png"); - ResourceManager.getInstance().loadHighQualityAsset("options", "options.png"); - ResourceManager.getInstance().loadHighQualityAsset("offline-avatar", "offline-avatar.png"); - ResourceManager.getInstance().loadHighQualityAsset("star", "gfx/star.png"); - ResourceManager.getInstance().loadHighQualityAsset("music_play", "music_play.png"); - ResourceManager.getInstance().loadHighQualityAsset("music_pause", "music_pause.png"); - ResourceManager.getInstance().loadHighQualityAsset("music_stop", "music_stop.png"); - ResourceManager.getInstance().loadHighQualityAsset("music_next", "music_next.png"); - ResourceManager.getInstance().loadHighQualityAsset("music_prev", "music_prev.png"); - ResourceManager.getInstance().loadHighQualityAsset("music_np", "music_np.png"); - ResourceManager.getInstance().loadHighQualityAsset("songselect-top", "songselect-top.png"); - File bg; - if ((bg = new File(Config.getSkinPath() + "menu-background.png")).exists() - || (bg = new File(Config.getSkinPath() + "menu-background.jpg")).exists()) { - ResourceManager.getInstance().loadHighQualityFile("menu-background", bg); - } - // ResourceManager.getInstance().loadHighQualityAsset("exit", "exit.png"); - ResourceManager.getInstance().loadFont("font", null, 28, Color.WHITE); - ResourceManager.getInstance().loadFont("smallFont", null, 21, Color.WHITE); - ResourceManager.getInstance().loadStrokeFont("strokeFont", null, 36, Color.BLACK, Color.WHITE); - - BassAudioPlayer.initDevice(); - - } - - @Override - public Scene onLoadScene() { - return new SplashScene().getScene(); - } - - @Override - public void onLoadComplete() { - new AsyncTaskLoader().execute(new OsuAsyncCallback() { - public void run() { - GlobalManager.getInstance().init(); - analytics.logEvent(FirebaseAnalytics.Event.APP_OPEN, null); - GlobalManager.getInstance().setLoadingProgress(50); - checkNewSkins(); - checkNewBeatmaps(); - if (!LibraryManager.getInstance().loadLibraryCache(MainActivity.this, true)) { - LibraryManager.getInstance().scanLibrary(MainActivity.this); - System.gc(); - } - } - - public void onComplete() { - GlobalManager.getInstance().setInfo(""); - GlobalManager.getInstance().setLoadingProgress(100); - ResourceManager.getInstance().loadFont("font", null, 28, Color.WHITE); - GlobalManager.getInstance().getEngine().setScene(GlobalManager.getInstance().getMainScene().getScene()); - GlobalManager.getInstance().getMainScene().loadBeatmap(); - initPreferences(); - availableInternalMemory(); - initAccessibilityDetector(); - if (willReplay) { - GlobalManager.getInstance().getMainScene().watchReplay(beatmapToAdd); - willReplay = false; - } - } - }); - } - /* - Accuracy isn't the best, but it's sufficient enough - to determine whether storage is low or not - */ - private void availableInternalMemory() { - DecimalFormat df = new DecimalFormat("#.##"); - df.setRoundingMode(RoundingMode.HALF_EVEN); - - double availableMemory; - double minMem = 1073741824D; //1 GiB = 1073741824 bytes - File internal = Environment.getDataDirectory(); - StatFs stat = new StatFs(internal.getPath()); - availableMemory = (double) stat.getAvailableBytes(); - String toastMessage = String.format(StringTable.get(R.string.message_low_storage_space), df.format(availableMemory / minMem)); - if(availableMemory < 0.5 * minMem) { //I set 512MiB as a minimum - Toast.makeText(this, toastMessage, Toast.LENGTH_SHORT).show(); - } - Debug.i("Free Space: " + df.format(availableMemory / minMem)); - } - - @SuppressLint("ResourceType") - @Override - protected void onSetContentView() { - this.mRenderSurfaceView = new RenderSurfaceView(this); - if(Config.isUseDither()) { - this.mRenderSurfaceView.setEGLConfigChooser(8,8,8,8,24,0); - this.mRenderSurfaceView.getHolder().setFormat(PixelFormat.RGBA_8888); - } else { - this.mRenderSurfaceView.setEGLConfigChooser(true); - } - this.mRenderSurfaceView.setRenderer(this.mEngine); - - RelativeLayout layout = new RelativeLayout(this); - layout.setBackgroundColor(Color.argb(255, 0, 0, 0)); - layout.addView( - mRenderSurfaceView, - new RelativeLayout.LayoutParams( - ViewGroup.LayoutParams.MATCH_PARENT, - ViewGroup.LayoutParams.MATCH_PARENT){{ - addRule(RelativeLayout.CENTER_IN_PARENT); - }}); - - FrameLayout frameLayout = new FrameLayout(this); - frameLayout.setId(0x28371); - layout.addView(frameLayout, new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); - - View c = new View(this); - c.setBackgroundColor(Color.argb(0, 0, 0, 0)); - layout.addView(c, new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); - - this.setContentView( - layout, - new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT) {{ - gravity = Gravity.CENTER; - }}); - - ActivityOverlay.initial(this, frameLayout.getId()); - - if ("pre_release".equals(BuildConfig.BUILD_TYPE) || BuildConfig.DEBUG) { - BuildTypeNoticeFragment.single.get().show(); - } - } - - public void checkNewBeatmaps() { - GlobalManager.getInstance().setInfo("Checking for new maps..."); - final File mainDir = new File(Config.getCorePath()); - if (beatmapToAdd != null) { - File file = new File(beatmapToAdd); - if (file.getName().toLowerCase().endsWith(".osz")) { - ToastLogger.showText( - StringTable.get(R.string.message_lib_importing), - false); - - if(FileUtils.extractZip(beatmapToAdd, Config.getBeatmapPath())) { - String folderName = beatmapToAdd.substring(0, beatmapToAdd.length() - 4); - // We have imported the beatmap! - ToastLogger.showText( - StringTable.format(R.string.message_lib_imported, folderName), - true); - } - - // LibraryManager.getInstance().sort(); - LibraryManager.getInstance().savetoCache(MainActivity.this); - } else if (file.getName().endsWith(".odr")) { - willReplay = true; - } - } else if (mainDir.exists() && mainDir.isDirectory()) { - File[] filelist = FileUtils.listFiles(mainDir, ".osz"); - final ArrayList beatmaps = new ArrayList(); - for (final File file : filelist) { - ZipFile zip = new ZipFile(file); - if(zip.isValidZipFile()) { - beatmaps.add(file.getPath()); - } - } - - File beatmapDir = new File(Config.getBeatmapPath()); - if (beatmapDir.exists() - && beatmapDir.isDirectory()) { - filelist = FileUtils.listFiles(beatmapDir, ".osz"); - for (final File file : filelist) { - ZipFile zip = new ZipFile(file); - if(zip.isValidZipFile()) { - beatmaps.add(file.getPath()); - } - } - } - - File downloadDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS); - if (Config.isSCAN_DOWNLOAD() - && downloadDir.exists() - && downloadDir.isDirectory()) { - filelist = FileUtils.listFiles(downloadDir, ".osz"); - for (final File file : filelist) { - ZipFile zip = new ZipFile(file); - if(zip.isValidZipFile()) { - beatmaps.add(file.getPath()); - } - } - } - - if (beatmaps.size() > 0) { - // final boolean deleteOsz = Config.isDELETE_OSZ(); - // Config.setDELETE_OSZ(true); - ToastLogger.showText(StringTable.format( - R.string.message_lib_importing_several, - beatmaps.size()), false); - for (final String beatmap : beatmaps) { - if(FileUtils.extractZip(beatmap, Config.getBeatmapPath())) { - String folderName = beatmap.substring(0, beatmap.length() - 4); - // We have imported the beatmap! - ToastLogger.showText( - StringTable.format(R.string.message_lib_imported, folderName), - true); - } - } - // Config.setDELETE_OSZ(deleteOsz); - - // LibraryManager.getInstance().sort(); - LibraryManager.getInstance().savetoCache(MainActivity.this); - } - } - } - - public void checkNewSkins() { - GlobalManager.getInstance().setInfo("Checking new skins..."); - - final ArrayList skins = new ArrayList<>(); - - // Scanning skin directory - final File skinDir = new File(Config.getSkinTopPath()); - - if (skinDir.exists() && skinDir.isDirectory()) { - final File[] files = FileUtils.listFiles(skinDir, ".osk"); - - for (final File file : files) { - ZipFile zip = new ZipFile(file); - if(zip.isValidZipFile()) { - skins.add(file.getPath()); - } - } - } - - // Scanning download directory - final File downloadDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS); - - if (Config.isSCAN_DOWNLOAD() - && downloadDir.exists() - && downloadDir.isDirectory()) { - final File[] files = FileUtils.listFiles(downloadDir, ".osk"); - - for (final File file : files) { - ZipFile zip = new ZipFile(file); - if(zip.isValidZipFile()) { - skins.add(file.getPath()); - } - } - } - - if (skins.size() > 0) { - ToastLogger.showText(StringTable.format( - R.string.message_skin_importing_several, - skins.size()), false); - - for (final String skin : skins) { - if (FileUtils.extractZip(skin, Config.getSkinTopPath())) { - String folderName = skin.substring(0, skin.length() - 4); - // We have imported the skin! - ToastLogger.showText( - StringTable.format(R.string.message_lib_imported, folderName), - true); - Config.addSkin(folderName.substring(folderName.lastIndexOf("/") + 1), skin); - } - } - } - } - - public Handler getHandler() { - return handler; - } - - public FirebaseAnalytics getAnalytics() { - return analytics; - } - - public PowerManager.WakeLock getWakeLock() { - return wakeLock; - } - - public static boolean isActivityVisible() { - return activityVisible; - } - - @Override - protected void onCreate(Bundle pSavedInstanceState) { - super.onCreate(pSavedInstanceState); - if (this.mEngine == null) { - return; - } - - if (BuildConfig.DEBUG) { - //Toast.makeText(this,"this is debug version",Toast.LENGTH_LONG).show(); - try { - File d = new File(Environment.getExternalStorageDirectory(), "osu!droid/Log"); - if (!d.exists()) d.mkdirs(); - File f = new File(d, "rawlog.txt"); - if (!f.exists()) f.createNewFile(); - Runtime.getRuntime().exec("logcat -f " + (f.getAbsolutePath())); - } catch (IOException e) { - } - } - onBeginBindService(); - } - - public void onCreateNotifyReceiver() { - if (filter == null) { - //过滤器创建 - filter = new IntentFilter(); - filter.addAction("Notify_cancel"); - } - - //按钮广播监听 - onNotifyButtonClick = new BroadcastReceiver() { - @Override - public void onReceive(Context context, Intent intent) { - if (intent.getAction().equals("Notify_cancel")) { - songService.stop(); - GlobalManager.getInstance().getMainScene().exit(); - } - } - }; - registerReceiver(onNotifyButtonClick, filter); - } - - public void onBeginBindService() { - if (connection == null && songService == null) { - connection = new ServiceConnection() { - @Override - public void onServiceConnected(ComponentName name, IBinder service) { - songService = ((SongService.ReturnBindObject) service).getObject(); - saveServiceObject = (SaveServiceObject) getApplication(); - saveServiceObject.setSongService(songService); - GlobalManager.getInstance().setSongService(songService); - } - - @Override - public void onServiceDisconnected(ComponentName name) { - - } - - }; - - bindService(new Intent(MainActivity.this, SongService.class), connection, BIND_AUTO_CREATE); - if (Build.VERSION.SDK_INT > 10) { - onCreateNotifyReceiver(); - } - } - GlobalManager.getInstance().setSongService(songService); - GlobalManager.getInstance().setSaveServiceObject(saveServiceObject); - } - - @Override - protected void onStart() { -// this.enableAccelerometerSensor(this); - if (getIntent().getAction() != null - && getIntent().getAction().equals(Intent.ACTION_VIEW)) { - if (ContentResolver.SCHEME_FILE.equals(getIntent().getData().getScheme())) { - beatmapToAdd = getIntent().getData().getPath(); - } - if (BuildConfig.DEBUG) { - System.out.println(getIntent()); - System.out.println(getIntent().getData().getEncodedPath()); - } - } - super.onStart(); - } - - @Override - public void onResume() { - super.onResume(); - if (this.mEngine == null) { - return; - } - activityVisible = true; - if (GlobalManager.getInstance().getEngine() != null && GlobalManager.getInstance().getGameScene() != null - && GlobalManager.getInstance().getEngine().getScene() == GlobalManager.getInstance().getGameScene().getScene()) { - GlobalManager.getInstance().getEngine().getTextureManager().reloadTextures(); - } - if (GlobalManager.getInstance().getMainScene() != null) { - if (songService != null && Build.VERSION.SDK_INT > 10) { - if (songService.hideNotifyPanel()) { - if (wakeLock != null && wakeLock.isHeld()) wakeLock.release(); - GlobalManager.getInstance().getMainScene().loadBeatmapInfo(); - GlobalManager.getInstance().getMainScene().loadTimeingPoints(false); - GlobalManager.getInstance().getMainScene().progressBar.setTime(songService.getLength()); - GlobalManager.getInstance().getMainScene().progressBar.setPassedTime(songService.getPosition()); - GlobalManager.getInstance().getMainScene().musicControl(MainScene.MusicOption.SYNC); - } - } - } - } - - @Override - public void onPause() { - super.onPause(); - activityVisible = false; - if (this.mEngine == null) { - return; - } - if (GlobalManager.getInstance().getEngine() != null && GlobalManager.getInstance().getGameScene() != null - && GlobalManager.getInstance().getEngine().getScene() == GlobalManager.getInstance().getGameScene().getScene()) { - SpritePool.getInstance().purge(); - GlobalManager.getInstance().getGameScene().pause(); - } - if (GlobalManager.getInstance().getMainScene() != null) { - BeatmapInfo beatmapInfo = GlobalManager.getInstance().getMainScene().beatmapInfo; - if (songService != null && beatmapInfo != null && !songService.isGaming()/* && !songService.isSettingMenu()*/) { - if (Build.VERSION.SDK_INT > 10) { - songService.showNotifyPanel(); - - if (wakeLock == null) { - PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE); - wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "osudroid:MainActivity"); - } - wakeLock.acquire(); - - if (beatmapInfo.getArtistUnicode() != null && beatmapInfo.getTitleUnicode() != null) { - songService.updateTitleText(beatmapInfo.getTitleUnicode(), beatmapInfo.getArtistUnicode()); - } else if (beatmapInfo.getArtist() != null && beatmapInfo.getTitle() != null) { - songService.updateTitleText(beatmapInfo.getTitle(), beatmapInfo.getArtist()); - } else { - songService.updateTitleText("QAQ I cant load info", " "); - } - songService.updateCoverImage(beatmapInfo.getTrack(0).getBackground()); - songService.updateStatus(); - } else { - songService.stop(); - } - } else { - if (songService != null) { - songService.pause(); - } - } - } - } - - @Override - public void onStop() { - super.onStop(); - activityVisible = false; - } - - @Override - public void onWindowFocusChanged(boolean hasFocus) { - super.onWindowFocusChanged(hasFocus); - if (this.mEngine == null) { - return; - } - if (GlobalManager.getInstance().getEngine() != null - && GlobalManager.getInstance().getGameScene() != null - && !hasFocus - && GlobalManager.getInstance().getEngine().getScene() == GlobalManager.getInstance().getGameScene().getScene()) { - if (!GlobalManager.getInstance().getGameScene().isPaused()) { - GlobalManager.getInstance().getGameScene().pause(); - } - } - if (hasFocus && Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && Config.isHideNaviBar()) { - getWindow().getDecorView().setSystemUiVisibility( - View.SYSTEM_UI_FLAG_LAYOUT_STABLE - | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION - | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN - | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION - | View.SYSTEM_UI_FLAG_FULLSCREEN - | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY); - } - } - - @Override - public void onAccelerometerChanged(final AccelerometerData arg0) { - if (this.mEngine == null) { - return; - } - if (GlobalManager.getInstance().getCamera().getRotation() == 0 && arg0.getY() < -5) { - GlobalManager.getInstance().getCamera().setRotation(180); - } else if (GlobalManager.getInstance().getCamera().getRotation() == 180 && arg0.getY() > 5) { - GlobalManager.getInstance().getCamera().setRotation(0); - } - } - - @Override - public boolean onKeyDown(final int keyCode, final KeyEvent event) { - if (this.mEngine == null) { - return false; - } - - if(autoclickerDialogShown) { - return false; - } - - if (event.getAction() != KeyEvent.ACTION_DOWN) { - return super.onKeyDown(keyCode, event); - } - if (GlobalManager.getInstance().getEngine() == null) { - return super.onKeyDown(keyCode, event); - } - - if (event.getAction() == TouchEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_BACK && ActivityOverlay.onBackPress()) { - return true; - } - - if (GlobalManager.getInstance().getGameScene() != null - && (keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_MENU) - && GlobalManager.getInstance().getEngine().getScene() == GlobalManager.getInstance().getGameScene().getScene()) { - if (GlobalManager.getInstance().getGameScene().isPaused()) { - GlobalManager.getInstance().getGameScene().resume(); - } else { - GlobalManager.getInstance().getGameScene().pause(); - } - return true; - } - if (GlobalManager.getInstance().getScoring() != null && keyCode == KeyEvent.KEYCODE_BACK - && GlobalManager.getInstance().getEngine().getScene() == GlobalManager.getInstance().getScoring().getScene()) { - GlobalManager.getInstance().getScoring().replayMusic(); - GlobalManager.getInstance().getEngine().setScene(GlobalManager.getInstance().getSongMenu().getScene()); - GlobalManager.getInstance().getSongMenu().updateScore(); - ResourceManager.getInstance().getSound("applause").stop(); - GlobalManager.getInstance().getScoring().setReplayID(-1); - return true; - } - if ((keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_ENTER) - && GlobalManager.getInstance().getEngine() != null - && GlobalManager.getInstance().getSongMenu() != null - && GlobalManager.getInstance().getEngine().getScene() == GlobalManager.getInstance().getSongMenu().getScene() - && GlobalManager.getInstance().getSongMenu().getScene().hasChildScene()) { - if (FilterMenu.getInstance().getClass() == FilterMenu.class) { - if (GlobalManager.getInstance().getSongMenu().getScene().getChildScene() == FilterMenu.getInstance() - .getScene()) { - if (keyCode == KeyEvent.KEYCODE_ENTER) { - InputManager.getInstance().toggleKeyboard(); - } - FilterMenu.getInstance().hideMenu(); - } - } - - /*if (GlobalManager.getInstance().getSongMenu().getScene().getChildScene() == PropsMenu.getInstance() - .getScene()) { - PropsMenu.getInstance().saveChanges(); - if (keyCode == KeyEvent.KEYCODE_ENTER) { - InputManager.getInstance().toggleKeyboard(); - } - }*/ - - if (GlobalManager.getInstance().getSongMenu().getScene().getChildScene() == ModMenu.getInstance().getScene()) { - ModMenu.getInstance().hide(); - } - - return true; - } - if (GlobalManager.getInstance().getSongMenu() != null && GlobalManager.getInstance().getEngine() != null - && keyCode == KeyEvent.KEYCODE_MENU - && GlobalManager.getInstance().getEngine().getScene() == GlobalManager.getInstance().getSongMenu().getScene() - && GlobalManager.getInstance().getSongMenu().getScene().hasChildScene() == false) { - GlobalManager.getInstance().getSongMenu().stopScroll(0); - GlobalManager.getInstance().getSongMenu().showPropertiesMenu(null); - return true; - } - if (keyCode == KeyEvent.KEYCODE_BACK) { - if (GlobalManager.getInstance().getEngine() != null && GlobalManager.getInstance().getSongMenu() != null && - GlobalManager.getInstance().getEngine().getScene() == GlobalManager.getInstance().getSongMenu().getScene()) { - - //SongMenu 界面按返回按钮(系统按钮) - GlobalManager.getInstance().getSongMenu().back(); - } else { - - if (GlobalManager.getInstance().getEngine().getScene() instanceof LoadingScreen.LoadingScene) { - return true; - } - - GlobalManager.getInstance().getMainScene().showExitDialog(); - } - return true; - } - - if (InputManager.getInstance().isStarted()) { - if (keyCode == KeyEvent.KEYCODE_DEL) { - InputManager.getInstance().pop(); - } else if (keyCode != KeyEvent.KEYCODE_ENTER) { - final char c = (char) event.getUnicodeChar(); - if (c != 0) { - InputManager.getInstance().append(c); - } - } - } - return super.onKeyDown(keyCode, event); - } - - private void forcedExit() { - if(GlobalManager.getInstance().getEngine().getScene() == GlobalManager.getInstance().getGameScene().getScene()) { - GlobalManager.getInstance().getGameScene().quit(); - } - GlobalManager.getInstance().getEngine().setScene(GlobalManager.getInstance().getMainScene().getScene()); - GlobalManager.getInstance().getMainScene().exit(); - } - - private void initAccessibilityDetector() { - ScheduledExecutorService scheduledExecutorService = - Executors.newSingleThreadScheduledExecutor(); - scheduledExecutorService - .scheduleAtFixedRate(() -> { - AccessibilityManager manager = (AccessibilityManager) - getSystemService(Context.ACCESSIBILITY_SERVICE); - List activeServices = new ArrayList( - manager.getEnabledAccessibilityServiceList( - AccessibilityServiceInfo.FEEDBACK_ALL_MASK)); - - for(AccessibilityServiceInfo activeService : activeServices) { - int capabilities = activeService.getCapabilities(); - if((AccessibilityServiceInfo.CAPABILITY_CAN_PERFORM_GESTURES & capabilities) - == AccessibilityServiceInfo.CAPABILITY_CAN_PERFORM_GESTURES) { - if(!autoclickerDialogShown && activityVisible) { - runOnUiThread(() -> { - ConfirmDialogFragment dialog = new ConfirmDialogFragment() - .setMessage(R.string.message_autoclicker_detected); - dialog.setOnDismissListener(() -> forcedExit()); - dialog.showForResult(isAccepted -> forcedExit()); - }); - autoclickerDialogShown = true; - } - } - } - }, 0, 1, TimeUnit.SECONDS); - } - - public long getVersionCode() { - long versionCode = 0; - try { - PackageInfo packageInfo = getPackageManager().getPackageInfo( - getPackageName(), 0); - if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { - versionCode = packageInfo.getLongVersionCode(); - }else { - versionCode = packageInfo.versionCode; - } - } catch (PackageManager.NameNotFoundException e) { - Debug.e("PackageManager: " + e.getMessage(), e); - } - return versionCode; - } - - public float getRefreshRate() { - return ((WindowManager) getSystemService(Context.WINDOW_SERVICE)) - .getDefaultDisplay() - .getRefreshRate(); - } - - private boolean checkPermissions() { - if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.R && - Environment.isExternalStorageManager()) { - return true; - }else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R && - PermissionChecker.checkCallingOrSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) - == PermissionChecker.PERMISSION_GRANTED) { - return true; - } else { - Intent grantPermission = new Intent(this, PermissionActivity.class); - startActivity(grantPermission); - overridePendingTransition(R.anim.fast_activity_swap, R.anim.fast_activity_swap); - finish(); - return false; - } - } -} \ No newline at end of file +package ru.nsu.ccfit.zuev.osu; + +import android.Manifest; +import android.accessibilityservice.AccessibilityServiceInfo; +import android.annotation.SuppressLint; +import android.app.AlertDialog; +import android.content.BroadcastReceiver; +import android.content.ComponentName; +import android.content.ContentResolver; +import android.content.Context; +import android.content.DialogInterface; +import android.content.Intent; +import android.content.IntentFilter; +import android.content.ServiceConnection; +import android.content.SharedPreferences; +import android.content.SharedPreferences.Editor; +import android.content.pm.PackageInfo; +import android.content.pm.PackageManager; +import android.graphics.Color; +import android.graphics.PixelFormat; +import android.os.*; + +import androidx.annotation.NonNull; +import androidx.preference.PreferenceManager; +import androidx.core.content.PermissionChecker; + +import android.util.DisplayMetrics; +import android.view.Gravity; +import android.view.KeyEvent; +import android.view.View; +import android.view.ViewGroup; +import android.view.WindowManager; +import android.view.accessibility.AccessibilityManager; +import android.widget.EditText; +import android.widget.FrameLayout; +import android.widget.RelativeLayout; + +import android.widget.Toast; +import com.edlplan.ui.ActivityOverlay; +import com.edlplan.ui.fragment.ConfirmDialogFragment; +import com.edlplan.ui.fragment.BuildTypeNoticeFragment; + +import com.google.firebase.analytics.FirebaseAnalytics; +import com.google.firebase.crashlytics.FirebaseCrashlytics; + +import org.anddev.andengine.engine.Engine; +import org.anddev.andengine.engine.camera.Camera; +import org.anddev.andengine.engine.camera.SmoothCamera; +import org.anddev.andengine.engine.options.EngineOptions; +import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; +import org.anddev.andengine.entity.scene.Scene; +import org.anddev.andengine.extension.input.touch.controller.MultiTouch; +import org.anddev.andengine.extension.input.touch.controller.MultiTouchController; +import org.anddev.andengine.extension.input.touch.exception.MultiTouchException; +import org.anddev.andengine.input.touch.TouchEvent; +import org.anddev.andengine.opengl.view.RenderSurfaceView; +import org.anddev.andengine.sensor.accelerometer.AccelerometerData; +import org.anddev.andengine.sensor.accelerometer.IAccelerometerListener; +import org.anddev.andengine.ui.activity.BaseGameActivity; +import org.anddev.andengine.util.Debug; + +import java.io.File; +import java.io.IOException; +import java.math.RoundingMode; +import java.security.Security; +import java.text.DecimalFormat; +import java.util.ArrayList; +import java.util.List; +import java.util.Random; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; + +import net.lingala.zip4j.ZipFile; + +import pub.devrel.easypermissions.AppSettingsDialog; +import pub.devrel.easypermissions.EasyPermissions; +import ru.nsu.ccfit.zuev.audio.BassAudioPlayer; +import ru.nsu.ccfit.zuev.audio.serviceAudio.SaveServiceObject; +import ru.nsu.ccfit.zuev.audio.serviceAudio.SongService; +import ru.nsu.ccfit.zuev.osu.async.AsyncTaskLoader; +import ru.nsu.ccfit.zuev.osu.async.OsuAsyncCallback; +import ru.nsu.ccfit.zuev.osu.async.SyncTaskManager; +import ru.nsu.ccfit.zuev.osu.game.SpritePool; +import ru.nsu.ccfit.zuev.osu.helper.FileUtils; +import ru.nsu.ccfit.zuev.osu.helper.InputManager; +import ru.nsu.ccfit.zuev.osu.helper.StringTable; +import ru.nsu.ccfit.zuev.osu.menu.FilterMenu; +import ru.nsu.ccfit.zuev.osu.menu.LoadingScreen; +import ru.nsu.ccfit.zuev.osu.menu.ModMenu; +import ru.nsu.ccfit.zuev.osu.menu.SettingsMenu; +import ru.nsu.ccfit.zuev.osu.menu.SplashScene; +import ru.nsu.ccfit.zuev.osu.online.OnlineManager; +import ru.nsu.ccfit.zuev.osuplus.BuildConfig; +import ru.nsu.ccfit.zuev.osuplus.R; + +public class MainActivity extends BaseGameActivity implements + IAccelerometerListener { + public static SongService songService; + public ServiceConnection connection; + public BroadcastReceiver onNotifyButtonClick; + private PowerManager.WakeLock wakeLock = null; + private String beatmapToAdd = null; + private SaveServiceObject saveServiceObject; + private IntentFilter filter; + private final Handler handler = new Handler(Looper.getMainLooper()); + private FirebaseAnalytics analytics; + private FirebaseCrashlytics crashlytics; + private boolean willReplay = false; + private static boolean activityVisible = true; + private boolean autoclickerDialogShown = false; + + @Override + public Engine onLoadEngine() { + if (!checkPermissions()) { + return null; + } + analytics = FirebaseAnalytics.getInstance(this); + crashlytics = FirebaseCrashlytics.getInstance(); + Config.loadConfig(this); + initialGameDirectory(); + //Debug.setDebugLevel(Debug.DebugLevel.NONE); + StringTable.setContext(this); + ToastLogger.init(this); + SyncTaskManager.getInstance().init(this); + InputManager.setContext(this); + OnlineManager.getInstance().Init(getApplicationContext()); + crashlytics.setUserId(Config.getOnlineDeviceID()); + + final DisplayMetrics dm = new DisplayMetrics(); + getWindowManager().getDefaultDisplay().getMetrics(dm); +/* final double screenSize = Math.sqrt(Utils.sqr(dm.widthPixels / dm.xdpi) + + Utils.sqr(dm.heightPixels / dm.ydpi));*/ + double screenInches = Math.sqrt(Math.pow(dm.heightPixels, 2) + Math.pow(dm.widthPixels, 2)) / (dm.density * 160.0f); + Debug.i("screen inches: " + screenInches); + Config.setScaleMultiplier((float) ((11 - 5.2450170716245195) / 5)); + + Config.setTextureQuality(1); + final PowerManager manager = (PowerManager) getSystemService(Context.POWER_SERVICE); + wakeLock = manager.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, + "osudroid:osu"); + + Camera mCamera = new SmoothCamera(0, 0, Config.getRES_WIDTH(), + Config.getRES_HEIGHT(), 0, 1800, 1); + final EngineOptions opt = new EngineOptions(true, + null, new RatioResolutionPolicy( + Config.getRES_WIDTH(), Config.getRES_HEIGHT()), + mCamera); + opt.setNeedsMusic(true); + opt.setNeedsSound(true); + opt.getRenderOptions().disableExtensionVertexBufferObjects(); + opt.getTouchOptions().enableRunOnUpdateThread(); + final Engine engine = new Engine(opt); + try { + if (MultiTouch.isSupported(this)) { + engine.setTouchController(new MultiTouchController()); + } else { + ToastLogger.showText( + StringTable.get(R.string.message_error_multitouch), + false); + } + } catch (final MultiTouchException e) { + ToastLogger.showText( + StringTable.get(R.string.message_error_multitouch), + false); + } + GlobalManager.getInstance().setCamera(mCamera); + GlobalManager.getInstance().setEngine(engine); + GlobalManager.getInstance().setMainActivity(this); + return GlobalManager.getInstance().getEngine(); + } + + private void initialGameDirectory() { + File dir = new File(Config.getBeatmapPath()); + // Creating Osu directory if it doesn't exist + if (!dir.exists()) { + if (!dir.mkdirs()) { + Config.setBeatmapPath(Config.getCorePath() + "Songs/"); + dir = new File(Config.getBeatmapPath()); + if (!(dir.exists() || dir.mkdirs())) { + ToastLogger.showText(StringTable.format( + R.string.message_error_createdir, dir.getPath()), + true); + } else { + final SharedPreferences prefs = PreferenceManager + .getDefaultSharedPreferences(this); + final SharedPreferences.Editor editor = prefs.edit(); + editor.putString("directory", dir.getPath()); + editor.commit(); + } + + } + final File nomedia = new File(dir.getParentFile(), ".nomedia"); + try { + nomedia.createNewFile(); + } catch (final IOException e) { + Debug.e("LibraryManager: " + e.getMessage(), e); + } + } + + final File skinDir = new File(Config.getCorePath() + "/Skin"); + // Creating Osu/Skin directory if it doesn't exist + if (!skinDir.exists()) { + skinDir.mkdirs(); + } + } + + private void initPreferences() { + final SharedPreferences prefs = PreferenceManager + .getDefaultSharedPreferences(this); + + if (prefs.getString("playername", "").equals("")) { + final SharedPreferences.Editor editor = prefs.edit(); + editor.putString("playername", "Guest"); + editor.commit(); + + final AlertDialog.Builder alert = new AlertDialog.Builder(this); + + alert.setTitle(StringTable.get(R.string.dialog_playername_title)); + alert.setMessage(StringTable + .get(R.string.dialog_playername_message)); + + final EditText input = new EditText(this); + input.setText("Guest"); + alert.setView(input); + + alert.setPositiveButton(StringTable.get(R.string.dialog_ok), + new DialogInterface.OnClickListener() { + + public void onClick(final DialogInterface dialog, + final int whichButton) { + final String value = input.getText().toString(); + editor.putString("playername", value); + editor.commit(); + } + }); + + alert.show(); + } + + if (prefs.getBoolean("qualitySet", false) == false) { + final SharedPreferences.Editor editor = prefs.edit(); + editor.putBoolean("qualitySet", true); + final DisplayMetrics dm = new DisplayMetrics(); + getWindowManager().getDefaultDisplay().getMetrics(dm); + + if (dm.densityDpi > DisplayMetrics.DENSITY_MEDIUM) { + editor.putBoolean("lowtextures", false); + } else { + editor.putBoolean("lowtextures", false); + } + editor.commit(); + } + + if (prefs.getBoolean("onlineSet", false) == false) { + + Editor editor = prefs.edit(); + editor.putBoolean("onlineSet", true); + editor.commit(); + + //TODO removed auto registration at first launch + /*OnlineInitializer initializer = new OnlineInitializer(this); + initializer.createInitDialog();*/ + } + } + + @Override + public void onLoadResources() { + Config.setTextureQuality(1); + ResourceManager.getInstance().Init(mEngine, this); + ResourceManager.getInstance().loadHighQualityAsset("logo", "logo.png"); + ResourceManager.getInstance().loadHighQualityAsset("play", "play.png"); + //ResourceManager.getInstance().loadHighQualityAsset("multiplayer", "multiplayer.png"); + //ResourceManager.getInstance().loadHighQualityAsset("solo", "solo.png"); + ResourceManager.getInstance().loadHighQualityAsset("exit", "exit.png"); + ResourceManager.getInstance().loadHighQualityAsset("options", "options.png"); + ResourceManager.getInstance().loadHighQualityAsset("offline-avatar", "offline-avatar.png"); + ResourceManager.getInstance().loadHighQualityAsset("star", "gfx/star.png"); + ResourceManager.getInstance().loadHighQualityAsset("music_play", "music_play.png"); + ResourceManager.getInstance().loadHighQualityAsset("music_pause", "music_pause.png"); + ResourceManager.getInstance().loadHighQualityAsset("music_stop", "music_stop.png"); + ResourceManager.getInstance().loadHighQualityAsset("music_next", "music_next.png"); + ResourceManager.getInstance().loadHighQualityAsset("music_prev", "music_prev.png"); + ResourceManager.getInstance().loadHighQualityAsset("music_np", "music_np.png"); + ResourceManager.getInstance().loadHighQualityAsset("songselect-top", "songselect-top.png"); + File bg; + if ((bg = new File(Config.getSkinPath() + "menu-background.png")).exists() + || (bg = new File(Config.getSkinPath() + "menu-background.jpg")).exists()) { + ResourceManager.getInstance().loadHighQualityFile("menu-background", bg); + } + // ResourceManager.getInstance().loadHighQualityAsset("exit", "exit.png"); + ResourceManager.getInstance().loadFont("font", null, 28, Color.WHITE); + ResourceManager.getInstance().loadFont("smallFont", null, 21, Color.WHITE); + ResourceManager.getInstance().loadStrokeFont("strokeFont", null, 36, Color.BLACK, Color.WHITE); + + BassAudioPlayer.initDevice(); + + } + + @Override + public Scene onLoadScene() { + return new SplashScene().getScene(); + } + + @Override + public void onLoadComplete() { + new AsyncTaskLoader().execute(new OsuAsyncCallback() { + public void run() { + GlobalManager.getInstance().init(); + analytics.logEvent(FirebaseAnalytics.Event.APP_OPEN, null); + GlobalManager.getInstance().setLoadingProgress(50); + checkNewSkins(); + checkNewBeatmaps(); + if (!LibraryManager.getInstance().loadLibraryCache(MainActivity.this, true)) { + LibraryManager.getInstance().scanLibrary(MainActivity.this); + System.gc(); + } + } + + public void onComplete() { + GlobalManager.getInstance().setInfo(""); + GlobalManager.getInstance().setLoadingProgress(100); + ResourceManager.getInstance().loadFont("font", null, 28, Color.WHITE); + GlobalManager.getInstance().getEngine().setScene(GlobalManager.getInstance().getMainScene().getScene()); + GlobalManager.getInstance().getMainScene().loadBeatmap(); + initPreferences(); + availableInternalMemory(); + initAccessibilityDetector(); + if (willReplay) { + GlobalManager.getInstance().getMainScene().watchReplay(beatmapToAdd); + willReplay = false; + } + } + }); + } + /* + Accuracy isn't the best, but it's sufficient enough + to determine whether storage is low or not + */ + private void availableInternalMemory() { + DecimalFormat df = new DecimalFormat("#.##"); + df.setRoundingMode(RoundingMode.HALF_EVEN); + + double availableMemory; + double minMem = 1073741824D; //1 GiB = 1073741824 bytes + File internal = Environment.getDataDirectory(); + StatFs stat = new StatFs(internal.getPath()); + availableMemory = (double) stat.getAvailableBytes(); + String toastMessage = String.format(StringTable.get(R.string.message_low_storage_space), df.format(availableMemory / minMem)); + if(availableMemory < 0.5 * minMem) { //I set 512MiB as a minimum + Toast.makeText(this, toastMessage, Toast.LENGTH_SHORT).show(); + } + Debug.i("Free Space: " + df.format(availableMemory / minMem)); + } + + @SuppressLint("ResourceType") + @Override + protected void onSetContentView() { + this.mRenderSurfaceView = new RenderSurfaceView(this); + if(Config.isUseDither()) { + this.mRenderSurfaceView.setEGLConfigChooser(8,8,8,8,24,0); + this.mRenderSurfaceView.getHolder().setFormat(PixelFormat.RGBA_8888); + } else { + this.mRenderSurfaceView.setEGLConfigChooser(true); + } + this.mRenderSurfaceView.setRenderer(this.mEngine); + + RelativeLayout layout = new RelativeLayout(this); + layout.setBackgroundColor(Color.argb(255, 0, 0, 0)); + layout.addView( + mRenderSurfaceView, + new RelativeLayout.LayoutParams( + ViewGroup.LayoutParams.MATCH_PARENT, + ViewGroup.LayoutParams.MATCH_PARENT){{ + addRule(RelativeLayout.CENTER_IN_PARENT); + }}); + + FrameLayout frameLayout = new FrameLayout(this); + frameLayout.setId(0x28371); + layout.addView(frameLayout, new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); + + View c = new View(this); + c.setBackgroundColor(Color.argb(0, 0, 0, 0)); + layout.addView(c, new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); + + this.setContentView( + layout, + new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT) {{ + gravity = Gravity.CENTER; + }}); + + ActivityOverlay.initial(this, frameLayout.getId()); + + if ("pre_release".equals(BuildConfig.BUILD_TYPE) || BuildConfig.DEBUG) { + BuildTypeNoticeFragment.single.get().show(); + } + } + + public void checkNewBeatmaps() { + GlobalManager.getInstance().setInfo("Checking for new maps..."); + final File mainDir = new File(Config.getCorePath()); + if (beatmapToAdd != null) { + File file = new File(beatmapToAdd); + if (file.getName().toLowerCase().endsWith(".osz")) { + ToastLogger.showText( + StringTable.get(R.string.message_lib_importing), + false); + + if(FileUtils.extractZip(beatmapToAdd, Config.getBeatmapPath())) { + String folderName = beatmapToAdd.substring(0, beatmapToAdd.length() - 4); + // We have imported the beatmap! + ToastLogger.showText( + StringTable.format(R.string.message_lib_imported, folderName), + true); + } + + // LibraryManager.getInstance().sort(); + LibraryManager.getInstance().savetoCache(MainActivity.this); + } else if (file.getName().endsWith(".odr")) { + willReplay = true; + } + } else if (mainDir.exists() && mainDir.isDirectory()) { + File[] filelist = FileUtils.listFiles(mainDir, ".osz"); + final ArrayList beatmaps = new ArrayList(); + for (final File file : filelist) { + ZipFile zip = new ZipFile(file); + if(zip.isValidZipFile()) { + beatmaps.add(file.getPath()); + } + } + + File beatmapDir = new File(Config.getBeatmapPath()); + if (beatmapDir.exists() + && beatmapDir.isDirectory()) { + filelist = FileUtils.listFiles(beatmapDir, ".osz"); + for (final File file : filelist) { + ZipFile zip = new ZipFile(file); + if(zip.isValidZipFile()) { + beatmaps.add(file.getPath()); + } + } + } + + File downloadDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS); + if (Config.isSCAN_DOWNLOAD() + && downloadDir.exists() + && downloadDir.isDirectory()) { + filelist = FileUtils.listFiles(downloadDir, ".osz"); + for (final File file : filelist) { + ZipFile zip = new ZipFile(file); + if(zip.isValidZipFile()) { + beatmaps.add(file.getPath()); + } + } + } + + if (beatmaps.size() > 0) { + // final boolean deleteOsz = Config.isDELETE_OSZ(); + // Config.setDELETE_OSZ(true); + ToastLogger.showText(StringTable.format( + R.string.message_lib_importing_several, + beatmaps.size()), false); + for (final String beatmap : beatmaps) { + if(FileUtils.extractZip(beatmap, Config.getBeatmapPath())) { + String folderName = beatmap.substring(0, beatmap.length() - 4); + // We have imported the beatmap! + ToastLogger.showText( + StringTable.format(R.string.message_lib_imported, folderName), + true); + } + } + // Config.setDELETE_OSZ(deleteOsz); + + // LibraryManager.getInstance().sort(); + LibraryManager.getInstance().savetoCache(MainActivity.this); + } + } + } + + public void checkNewSkins() { + GlobalManager.getInstance().setInfo("Checking new skins..."); + + final ArrayList skins = new ArrayList<>(); + + // Scanning skin directory + final File skinDir = new File(Config.getSkinTopPath()); + + if (skinDir.exists() && skinDir.isDirectory()) { + final File[] files = FileUtils.listFiles(skinDir, ".osk"); + + for (final File file : files) { + ZipFile zip = new ZipFile(file); + if(zip.isValidZipFile()) { + skins.add(file.getPath()); + } + } + } + + // Scanning download directory + final File downloadDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS); + + if (Config.isSCAN_DOWNLOAD() + && downloadDir.exists() + && downloadDir.isDirectory()) { + final File[] files = FileUtils.listFiles(downloadDir, ".osk"); + + for (final File file : files) { + ZipFile zip = new ZipFile(file); + if(zip.isValidZipFile()) { + skins.add(file.getPath()); + } + } + } + + if (skins.size() > 0) { + ToastLogger.showText(StringTable.format( + R.string.message_skin_importing_several, + skins.size()), false); + + for (final String skin : skins) { + if (FileUtils.extractZip(skin, Config.getSkinTopPath())) { + String folderName = skin.substring(0, skin.length() - 4); + // We have imported the skin! + ToastLogger.showText( + StringTable.format(R.string.message_lib_imported, folderName), + true); + Config.addSkin(folderName.substring(folderName.lastIndexOf("/") + 1), skin); + } + } + } + } + + public Handler getHandler() { + return handler; + } + + public FirebaseAnalytics getAnalytics() { + return analytics; + } + + public PowerManager.WakeLock getWakeLock() { + return wakeLock; + } + + public static boolean isActivityVisible() { + return activityVisible; + } + + @Override + protected void onCreate(Bundle pSavedInstanceState) { + super.onCreate(pSavedInstanceState); + if (this.mEngine == null) { + return; + } + + if (BuildConfig.DEBUG) { + //Toast.makeText(this,"this is debug version",Toast.LENGTH_LONG).show(); + try { + File d = new File(Environment.getExternalStorageDirectory(), "osu!droid/Log"); + if (!d.exists()) d.mkdirs(); + File f = new File(d, "rawlog.txt"); + if (!f.exists()) f.createNewFile(); + Runtime.getRuntime().exec("logcat -f " + (f.getAbsolutePath())); + } catch (IOException e) { + } + } + onBeginBindService(); + } + + public void onCreateNotifyReceiver() { + if (filter == null) { + //过滤器创建 + filter = new IntentFilter(); + filter.addAction("Notify_cancel"); + } + + //按钮广播监听 + onNotifyButtonClick = new BroadcastReceiver() { + @Override + public void onReceive(Context context, Intent intent) { + if (intent.getAction().equals("Notify_cancel")) { + songService.stop(); + GlobalManager.getInstance().getMainScene().exit(); + } + } + }; + registerReceiver(onNotifyButtonClick, filter); + } + + public void onBeginBindService() { + if (connection == null && songService == null) { + connection = new ServiceConnection() { + @Override + public void onServiceConnected(ComponentName name, IBinder service) { + songService = ((SongService.ReturnBindObject) service).getObject(); + saveServiceObject = (SaveServiceObject) getApplication(); + saveServiceObject.setSongService(songService); + GlobalManager.getInstance().setSongService(songService); + } + + @Override + public void onServiceDisconnected(ComponentName name) { + + } + + }; + + bindService(new Intent(MainActivity.this, SongService.class), connection, BIND_AUTO_CREATE); + if (Build.VERSION.SDK_INT > 10) { + onCreateNotifyReceiver(); + } + } + GlobalManager.getInstance().setSongService(songService); + GlobalManager.getInstance().setSaveServiceObject(saveServiceObject); + } + + @Override + protected void onStart() { +// this.enableAccelerometerSensor(this); + if (getIntent().getAction() != null + && getIntent().getAction().equals(Intent.ACTION_VIEW)) { + if (ContentResolver.SCHEME_FILE.equals(getIntent().getData().getScheme())) { + beatmapToAdd = getIntent().getData().getPath(); + } + if (BuildConfig.DEBUG) { + System.out.println(getIntent()); + System.out.println(getIntent().getData().getEncodedPath()); + } + } + super.onStart(); + } + + @Override + public void onResume() { + super.onResume(); + if (this.mEngine == null) { + return; + } + activityVisible = true; + if (GlobalManager.getInstance().getEngine() != null && GlobalManager.getInstance().getGameScene() != null + && GlobalManager.getInstance().getEngine().getScene() == GlobalManager.getInstance().getGameScene().getScene()) { + GlobalManager.getInstance().getEngine().getTextureManager().reloadTextures(); + } + if (GlobalManager.getInstance().getMainScene() != null) { + if (songService != null && Build.VERSION.SDK_INT > 10) { + if (songService.hideNotifyPanel()) { + if (wakeLock != null && wakeLock.isHeld()) wakeLock.release(); + GlobalManager.getInstance().getMainScene().loadBeatmapInfo(); + GlobalManager.getInstance().getMainScene().loadTimeingPoints(false); + GlobalManager.getInstance().getMainScene().progressBar.setTime(songService.getLength()); + GlobalManager.getInstance().getMainScene().progressBar.setPassedTime(songService.getPosition()); + GlobalManager.getInstance().getMainScene().musicControl(MainScene.MusicOption.SYNC); + } + } + } + } + + @Override + public void onPause() { + super.onPause(); + activityVisible = false; + if (this.mEngine == null) { + return; + } + if (GlobalManager.getInstance().getEngine() != null && GlobalManager.getInstance().getGameScene() != null + && GlobalManager.getInstance().getEngine().getScene() == GlobalManager.getInstance().getGameScene().getScene()) { + SpritePool.getInstance().purge(); + GlobalManager.getInstance().getGameScene().pause(); + } + if (GlobalManager.getInstance().getMainScene() != null) { + BeatmapInfo beatmapInfo = GlobalManager.getInstance().getMainScene().beatmapInfo; + if (songService != null && beatmapInfo != null && !songService.isGaming()/* && !songService.isSettingMenu()*/) { + if (Build.VERSION.SDK_INT > 10) { + songService.showNotifyPanel(); + + if (wakeLock == null) { + PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE); + wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "osudroid:MainActivity"); + } + wakeLock.acquire(); + + if (beatmapInfo.getArtistUnicode() != null && beatmapInfo.getTitleUnicode() != null) { + songService.updateTitleText(beatmapInfo.getTitleUnicode(), beatmapInfo.getArtistUnicode()); + } else if (beatmapInfo.getArtist() != null && beatmapInfo.getTitle() != null) { + songService.updateTitleText(beatmapInfo.getTitle(), beatmapInfo.getArtist()); + } else { + songService.updateTitleText("QAQ I cant load info", " "); + } + songService.updateCoverImage(beatmapInfo.getTrack(0).getBackground()); + songService.updateStatus(); + } else { + songService.stop(); + } + } else { + if (songService != null) { + songService.pause(); + } + } + } + } + + @Override + public void onStop() { + super.onStop(); + activityVisible = false; + } + + @Override + public void onWindowFocusChanged(boolean hasFocus) { + super.onWindowFocusChanged(hasFocus); + if (this.mEngine == null) { + return; + } + if (GlobalManager.getInstance().getEngine() != null + && GlobalManager.getInstance().getGameScene() != null + && !hasFocus + && GlobalManager.getInstance().getEngine().getScene() == GlobalManager.getInstance().getGameScene().getScene()) { + if (!GlobalManager.getInstance().getGameScene().isPaused()) { + GlobalManager.getInstance().getGameScene().pause(); + } + } + if (hasFocus && Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && Config.isHideNaviBar()) { + getWindow().getDecorView().setSystemUiVisibility( + View.SYSTEM_UI_FLAG_LAYOUT_STABLE + | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION + | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN + | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION + | View.SYSTEM_UI_FLAG_FULLSCREEN + | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY); + } + } + + @Override + public void onAccelerometerChanged(final AccelerometerData arg0) { + if (this.mEngine == null) { + return; + } + if (GlobalManager.getInstance().getCamera().getRotation() == 0 && arg0.getY() < -5) { + GlobalManager.getInstance().getCamera().setRotation(180); + } else if (GlobalManager.getInstance().getCamera().getRotation() == 180 && arg0.getY() > 5) { + GlobalManager.getInstance().getCamera().setRotation(0); + } + } + + @Override + public boolean onKeyDown(final int keyCode, final KeyEvent event) { + if (this.mEngine == null) { + return false; + } + + if(autoclickerDialogShown) { + return false; + } + + if (event.getAction() != KeyEvent.ACTION_DOWN) { + return super.onKeyDown(keyCode, event); + } + if (GlobalManager.getInstance().getEngine() == null) { + return super.onKeyDown(keyCode, event); + } + + if (event.getAction() == TouchEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_BACK && ActivityOverlay.onBackPress()) { + return true; + } + + if (GlobalManager.getInstance().getGameScene() != null + && (keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_MENU) + && GlobalManager.getInstance().getEngine().getScene() == GlobalManager.getInstance().getGameScene().getScene()) { + if (GlobalManager.getInstance().getGameScene().isPaused()) { + GlobalManager.getInstance().getGameScene().resume(); + } else { + GlobalManager.getInstance().getGameScene().pause(); + } + return true; + } + if (GlobalManager.getInstance().getScoring() != null && keyCode == KeyEvent.KEYCODE_BACK + && GlobalManager.getInstance().getEngine().getScene() == GlobalManager.getInstance().getScoring().getScene()) { + GlobalManager.getInstance().getScoring().replayMusic(); + GlobalManager.getInstance().getEngine().setScene(GlobalManager.getInstance().getSongMenu().getScene()); + GlobalManager.getInstance().getSongMenu().updateScore(); + ResourceManager.getInstance().getSound("applause").stop(); + GlobalManager.getInstance().getScoring().setReplayID(-1); + return true; + } + if ((keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_ENTER) + && GlobalManager.getInstance().getEngine() != null + && GlobalManager.getInstance().getSongMenu() != null + && GlobalManager.getInstance().getEngine().getScene() == GlobalManager.getInstance().getSongMenu().getScene() + && GlobalManager.getInstance().getSongMenu().getScene().hasChildScene()) { + if (FilterMenu.getInstance().getClass() == FilterMenu.class) { + if (GlobalManager.getInstance().getSongMenu().getScene().getChildScene() == FilterMenu.getInstance() + .getScene()) { + if (keyCode == KeyEvent.KEYCODE_ENTER) { + InputManager.getInstance().toggleKeyboard(); + } + FilterMenu.getInstance().hideMenu(); + } + } + + /*if (GlobalManager.getInstance().getSongMenu().getScene().getChildScene() == PropsMenu.getInstance() + .getScene()) { + PropsMenu.getInstance().saveChanges(); + if (keyCode == KeyEvent.KEYCODE_ENTER) { + InputManager.getInstance().toggleKeyboard(); + } + }*/ + + if (GlobalManager.getInstance().getSongMenu().getScene().getChildScene() == ModMenu.getInstance().getScene()) { + ModMenu.getInstance().hide(); + } + + return true; + } + if (GlobalManager.getInstance().getSongMenu() != null && GlobalManager.getInstance().getEngine() != null + && keyCode == KeyEvent.KEYCODE_MENU + && GlobalManager.getInstance().getEngine().getScene() == GlobalManager.getInstance().getSongMenu().getScene() + && GlobalManager.getInstance().getSongMenu().getScene().hasChildScene() == false) { + GlobalManager.getInstance().getSongMenu().stopScroll(0); + GlobalManager.getInstance().getSongMenu().showPropertiesMenu(null); + return true; + } + if (keyCode == KeyEvent.KEYCODE_BACK) { + if (GlobalManager.getInstance().getEngine() != null && GlobalManager.getInstance().getSongMenu() != null && + GlobalManager.getInstance().getEngine().getScene() == GlobalManager.getInstance().getSongMenu().getScene()) { + + //SongMenu 界面按返回按钮(系统按钮) + GlobalManager.getInstance().getSongMenu().back(); + } else { + + if (GlobalManager.getInstance().getEngine().getScene() instanceof LoadingScreen.LoadingScene) { + return true; + } + + GlobalManager.getInstance().getMainScene().showExitDialog(); + } + return true; + } + + if (InputManager.getInstance().isStarted()) { + if (keyCode == KeyEvent.KEYCODE_DEL) { + InputManager.getInstance().pop(); + } else if (keyCode != KeyEvent.KEYCODE_ENTER) { + final char c = (char) event.getUnicodeChar(); + if (c != 0) { + InputManager.getInstance().append(c); + } + } + } + return super.onKeyDown(keyCode, event); + } + + private void forcedExit() { + if(GlobalManager.getInstance().getEngine().getScene() == GlobalManager.getInstance().getGameScene().getScene()) { + GlobalManager.getInstance().getGameScene().quit(); + } + GlobalManager.getInstance().getEngine().setScene(GlobalManager.getInstance().getMainScene().getScene()); + GlobalManager.getInstance().getMainScene().exit(); + } + + private void initAccessibilityDetector() { + ScheduledExecutorService scheduledExecutorService = + Executors.newSingleThreadScheduledExecutor(); + scheduledExecutorService + .scheduleAtFixedRate(() -> { + AccessibilityManager manager = (AccessibilityManager) + getSystemService(Context.ACCESSIBILITY_SERVICE); + List activeServices = new ArrayList( + manager.getEnabledAccessibilityServiceList( + AccessibilityServiceInfo.FEEDBACK_ALL_MASK)); + + for(AccessibilityServiceInfo activeService : activeServices) { + int capabilities = activeService.getCapabilities(); + if((AccessibilityServiceInfo.CAPABILITY_CAN_PERFORM_GESTURES & capabilities) + == AccessibilityServiceInfo.CAPABILITY_CAN_PERFORM_GESTURES) { + if(!autoclickerDialogShown && activityVisible) { + runOnUiThread(() -> { + ConfirmDialogFragment dialog = new ConfirmDialogFragment() + .setMessage(R.string.message_autoclicker_detected); + dialog.setOnDismissListener(() -> forcedExit()); + dialog.showForResult(isAccepted -> forcedExit()); + }); + autoclickerDialogShown = true; + } + } + } + }, 0, 1, TimeUnit.SECONDS); + } + + public long getVersionCode() { + long versionCode = 0; + try { + PackageInfo packageInfo = getPackageManager().getPackageInfo( + getPackageName(), 0); + if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { + versionCode = packageInfo.getLongVersionCode(); + }else { + versionCode = packageInfo.versionCode; + } + } catch (PackageManager.NameNotFoundException e) { + Debug.e("PackageManager: " + e.getMessage(), e); + } + return versionCode; + } + + public float getRefreshRate() { + return ((WindowManager) getSystemService(Context.WINDOW_SERVICE)) + .getDefaultDisplay() + .getRefreshRate(); + } + + private boolean checkPermissions() { + if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.R && + Environment.isExternalStorageManager()) { + return true; + }else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R && + PermissionChecker.checkCallingOrSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) + == PermissionChecker.PERMISSION_GRANTED) { + return true; + } else { + Intent grantPermission = new Intent(this, PermissionActivity.class); + startActivity(grantPermission); + overridePendingTransition(R.anim.fast_activity_swap, R.anim.fast_activity_swap); + finish(); + return false; + } + } +} diff --git a/src/ru/nsu/ccfit/zuev/osu/MainScene.java b/src/ru/nsu/ccfit/zuev/osu/MainScene.java index 68a9dbf9..63837dfd 100644 --- a/src/ru/nsu/ccfit/zuev/osu/MainScene.java +++ b/src/ru/nsu/ccfit/zuev/osu/MainScene.java @@ -81,1138 +81,1138 @@ * Created by Fuuko on 2015/4/24. */ public class MainScene implements IUpdateHandler { - public SongProgressBar progressBar; - public BeatmapInfo beatmapInfo; - private Context context; - private Sprite logo, logoOverlay, play, options, exit, background, lastBackground; - private Sprite music_nowplay; - private Scene scene; - private ChangeableText musicInfoText; - // private ArrayList beatmaps; - private Random random = new Random(); - private Rectangle[] spectrum = new Rectangle[120]; - private float[] peakLevel = new float[120]; - private float[] peakDownRate = new float[120]; - private float[] peakAlpha = new float[120]; - private Replay replay = null; - private TrackInfo selectedTrack; - private BeatmapData beatmapData; - private List timingPoints; - private TimingPoint currentTimingPoint, lastTimingPoint, firstTimingPoint; - - private int particleBeginTime = 0; - private boolean particleEnabled = false; - private boolean isContinuousKiai = false; - - private ParticleSystem[] particleSystem = new ParticleSystem[2]; - - //private BassAudioPlayer music; - - private boolean musicStarted; - private BassSoundProvider hitsound; - - private float bpmLength = 1000; - private float lastBpmLength = 0; - private float offset = 0; - private float beatPassTime = 0; - private float lastBeatPassTime = 0; - private boolean doChange = false; - private boolean doStop = false; - // private int playIndex = 0; -// private int lastPlayIndex = -1; - private long lastHit = 0; - private boolean isOnExitAnim = false; - - private boolean isMenuShowed = false; - private boolean doMenuShow = false; - private float showPassTime = 0, syncPassedTime = 0; - private float menuBarX = 0, playY, optionsY, exitY; - - - public void load(Context context) { - this.context = context; - Debug.i("Load: mainMenuLoaded()"); - scene = new Scene(); - - final TextureRegion tex = ResourceManager.getInstance().getTexture("menu-background"); - - if (tex != null) { - float height = tex.getHeight(); - height *= Config.getRES_WIDTH() - / (float) tex.getWidth(); - final Sprite menuBg = new Sprite( - 0, - (Config.getRES_HEIGHT() - height) / 2, - Config.getRES_WIDTH(), - height, tex); - scene.setBackground(new SpriteBackground(menuBg)); - } else { - scene.setBackground(new ColorBackground(70 / 255f, 129 / 255f, - 252 / 255f)); - } - lastBackground = new Sprite(0, 0, Config.getRES_WIDTH(), Config.getRES_HEIGHT(), ResourceManager.getInstance().getTexture("emptyavatar")); - final TextureRegion logotex = ResourceManager.getInstance().getTexture("logo"); - logo = new Sprite(Config.getRES_WIDTH() / 2 - logotex.getWidth() / 2, Config.getRES_HEIGHT() / 2 - logotex.getHeight() / 2, logotex) { - @Override - public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, - final float pTouchAreaLocalX, final float pTouchAreaLocalY) { - if (pSceneTouchEvent.isActionDown()) { - if (hitsound != null) { - hitsound.play(); - } - Debug.i("logo down"); - return true; - } - if (pSceneTouchEvent.isActionUp()) { - Debug.i("logo up"); - Debug.i("doMenuShow " + doMenuShow + " isMenuShowed " + isMenuShowed + " showPassTime " + showPassTime); - if (doMenuShow == true && isMenuShowed == true) { - showPassTime = 20000; - } - if (doMenuShow == false && isMenuShowed == false && logo.getX() == (Config.getRES_WIDTH() - logo.getWidth()) / 2) { - doMenuShow = true; - showPassTime = 0; - } - Debug.i("doMenuShow " + doMenuShow + " isMenuShowed " + isMenuShowed + " showPassTime " + showPassTime); - return true; - } - return super.onAreaTouched(pSceneTouchEvent, pTouchAreaLocalX, - pTouchAreaLocalY); - } - }; - - logoOverlay = new Sprite(Config.getRES_WIDTH() / 2 - logotex.getWidth() / 2, Config.getRES_HEIGHT() / 2 - logotex.getHeight() / 2, logotex); - logoOverlay.setScale(1.07f); - logoOverlay.setAlpha(0.2f); - - play = new Sprite(logo.getX() + logo.getWidth() - Config.getRES_WIDTH() / 3, - 60 + 82 - 32, ResourceManager.getInstance().getTexture("play")) { - - - @Override - public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, - final float pTouchAreaLocalX, final float pTouchAreaLocalY) { - if (pSceneTouchEvent.isActionDown()) { - setColor(0.7f, 0.7f, 0.7f); - if (hitsound != null) { - hitsound.play(); - } - return true; - } - if (pSceneTouchEvent.isActionUp()) { - setColor(1, 1, 1); - if (isOnExitAnim) return true; - GlobalManager.getInstance().getSongService().setGaming(true); - if (GlobalManager.getInstance().getCamera().getRotation() == 0) { - Utils.setAccelerometerSign(1); - } else { - Utils.setAccelerometerSign(-1); - } -// final Intent intent = new Intent( -// MainManager.getInstance().getMainActivity(), OsuActivity.class); -// MainManager.getInstance().getMainActivity().startActivity(intent); - new AsyncTaskLoader().execute(new OsuAsyncCallback() { - public void run() { - GlobalManager.getInstance().getEngine().setScene(new LoadingScreen().getScene()); - GlobalManager.getInstance().getMainActivity().checkNewBeatmaps(); - if (!LibraryManager.getInstance().loadLibraryCache(GlobalManager.getInstance().getMainActivity(), false)) { - LibraryManager.getInstance().scanLibrary(GlobalManager.getInstance().getMainActivity()); - } - GlobalManager.getInstance().getSongMenu().reload(); - /* To fixed skin load bug in some Android 10 - if (Build.VERSION.SDK_INT >= 29) { - String skinNow = Config.getSkinPath(); - ResourceManager.getInstance().loadSkin(skinNow); - } */ - } - - public void onComplete() { - - musicControl(MusicOption.PLAY); - GlobalManager.getInstance().getEngine().setScene(GlobalManager.getInstance().getSongMenu().getScene()); - GlobalManager.getInstance().getSongMenu().select(); - } - }); - return true; - } - return super.onAreaTouched(pSceneTouchEvent, pTouchAreaLocalX, - pTouchAreaLocalY); - } - - }; - - options = new Sprite(logo.getX() + logo.getWidth() - Config.getRES_WIDTH() / 3, - 60 + 3 * 82 - 64, ResourceManager.getInstance().getTexture( - "options")) { - - @Override - public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, - final float pTouchAreaLocalX, final float pTouchAreaLocalY) { - if (pSceneTouchEvent.isActionDown()) { - setColor(0.7f, 0.7f, 0.7f); - if (hitsound != null) { - hitsound.play(); - } - return true; - } - if (pSceneTouchEvent.isActionUp()) { - setColor(1, 1, 1); - if (isOnExitAnim) return true; - GlobalManager.getInstance().getSongService().setGaming(true); - // GlobalManager.getInstance().getSongService().setIsSettingMenu(true); - /* final Intent intent = new Intent(GlobalManager.getInstance().getMainActivity(), - SettingsMenu.class); - GlobalManager.getInstance().getMainActivity().startActivity(intent); */ - GlobalManager.getInstance().getMainActivity().runOnUiThread(() -> - new SettingsMenu().show()); - return true; - } - return super.onAreaTouched(pSceneTouchEvent, pTouchAreaLocalX, - pTouchAreaLocalY); - } - }; - - exit = new Sprite(logo.getX() + logo.getWidth() - Config.getRES_WIDTH() / 3, 60 - + 5 * 82 - 128 + 32, ResourceManager.getInstance().getTexture( - "exit")) { - - @Override - public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, - final float pTouchAreaLocalX, final float pTouchAreaLocalY) { - if (pSceneTouchEvent.isActionDown()) { - setColor(0.7f, 0.7f, 0.7f); - // if (hitsound != null) { - // hitsound.play(); - // } - return true; - } - if (pSceneTouchEvent.isActionUp()) { - if (GlobalManager.getInstance().getCamera().getRotation() == 0) { - Utils.setAccelerometerSign(1); - } else { - Utils.setAccelerometerSign(-1); - } - setColor(1, 1, 1); - - showExitDialog(); - - return true; - } - return super.onAreaTouched(pSceneTouchEvent, pTouchAreaLocalX, - pTouchAreaLocalY); - } - }; - - final Text author = new Text(10, 530, ResourceManager - .getInstance().getFont("font"), - String.format( - Locale.getDefault(), - "osu!droid %s\nby osu!droid Team\nosu! is \u00a9 peppy 2007-2021", - BuildConfig.VERSION_NAME + " (" + BuildConfig.BUILD_TYPE + ")" - )) { - - - @Override - public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, - final float pTouchAreaLocalX, final float pTouchAreaLocalY) { - if (pSceneTouchEvent.isActionDown()) { - new ConfirmDialogFragment().setMessage(R.string.dialog_visit_osu_website_message).showForResult( - isAccepted -> { - if(isAccepted) { - Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://osu.ppy.sh")); - GlobalManager.getInstance().getMainActivity().startActivity(browserIntent); - } - } - ); - return true; - } - return false; - } - }; - author.setPosition(10, Config.getRES_HEIGHT() - author.getHeight() - 10); - - final Text yasonline = new Text(720, 530, ResourceManager - .getInstance().getFont("font"), - " Performance Ranking\n Provided by iBancho") { - - @Override - public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, - final float pTouchAreaLocalX, final float pTouchAreaLocalY) { - if (pSceneTouchEvent.isActionDown()) { - new ConfirmDialogFragment().setMessage(R.string.dialog_visit_osudroid_website_message).showForResult( - isAccepted -> { - if(isAccepted) { - Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://" + OnlineManager.hostname)); - GlobalManager.getInstance().getMainActivity().startActivity(browserIntent); - } - } - ); - return true; - } - return false; - } - }; - yasonline.setPosition(Config.getRES_WIDTH() - yasonline.getWidth() - 40, Config.getRES_HEIGHT() - yasonline.getHeight() - 10); - - final Sprite music_prev = new Sprite(Config.getRES_WIDTH() - 50 * 6 + 35, - 47, 40, 40, ResourceManager.getInstance().getTexture( - "music_prev")) { - - @Override - public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, - final float pTouchAreaLocalX, final float pTouchAreaLocalY) { - if (pSceneTouchEvent.isActionDown()) { - setColor(0.7f, 0.7f, 0.7f); - doChange = true; - return true; - } - if (pSceneTouchEvent.isActionUp()) { - setColor(1, 1, 1); - if (lastHit == 0) { - lastHit = System.currentTimeMillis(); - } else { - if (System.currentTimeMillis() - lastHit <= 1000 && !isOnExitAnim) { - return true; - } - } - lastHit = System.currentTimeMillis(); - musicControl(MusicOption.PREV); - return true; - } - return super.onAreaTouched(pSceneTouchEvent, pTouchAreaLocalX, - pTouchAreaLocalY); - } - }; - - final Sprite music_play = new Sprite(Config.getRES_WIDTH() - 50 * 5 + 35, - 47, 40, 40, ResourceManager.getInstance().getTexture( - "music_play")) { - - @Override - public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, - final float pTouchAreaLocalX, final float pTouchAreaLocalY) { - if (pSceneTouchEvent.isActionDown()) { - setColor(0.7f, 0.7f, 0.7f); - return true; - } - if (pSceneTouchEvent.isActionUp()) { - setColor(1, 1, 1); - musicControl(MusicOption.PLAY); - return true; - } - return super.onAreaTouched(pSceneTouchEvent, pTouchAreaLocalX, - pTouchAreaLocalY); - } - }; - - final Sprite music_pause = new Sprite(Config.getRES_WIDTH() - 50 * 4 + 35, - 47, 40, 40, ResourceManager.getInstance().getTexture( - "music_pause")) { - - @Override - public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, - final float pTouchAreaLocalX, final float pTouchAreaLocalY) { - if (pSceneTouchEvent.isActionDown()) { - setColor(0.7f, 0.7f, 0.7f); - return true; - } - if (pSceneTouchEvent.isActionUp()) { - setColor(1, 1, 1); - musicControl(MusicOption.PAUSE); - return true; - } - return super.onAreaTouched(pSceneTouchEvent, pTouchAreaLocalX, - pTouchAreaLocalY); - } - }; - - final Sprite music_stop = new Sprite(Config.getRES_WIDTH() - 50 * 3 + 35, - 47, 40, 40, ResourceManager.getInstance().getTexture( - "music_stop")) { - - @Override - public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, - final float pTouchAreaLocalX, final float pTouchAreaLocalY) { - if (pSceneTouchEvent.isActionDown()) { - setColor(0.7f, 0.7f, 0.7f); - doStop = true; - return true; - } - if (pSceneTouchEvent.isActionUp()) { - setColor(1, 1, 1); - musicControl(MusicOption.STOP); - return true; - } - return super.onAreaTouched(pSceneTouchEvent, pTouchAreaLocalX, - pTouchAreaLocalY); - } - }; - - final Sprite music_next = new Sprite(Config.getRES_WIDTH() - 50 * 2 + 35, - 47, 40, 40, ResourceManager.getInstance().getTexture( - "music_next")) { - - @Override - public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, - final float pTouchAreaLocalX, final float pTouchAreaLocalY) { - if (pSceneTouchEvent.isActionDown()) { - setColor(0.7f, 0.7f, 0.7f); - doChange = true; - return true; - } - if (pSceneTouchEvent.isActionUp()) { - setColor(1, 1, 1); - if (lastHit == 0) { - lastHit = System.currentTimeMillis(); - } else { - if (System.currentTimeMillis() - lastHit <= 1000 && !isOnExitAnim) { - return true; - } - } - lastHit = System.currentTimeMillis(); - musicControl(MusicOption.NEXT); - return true; - } - return super.onAreaTouched(pSceneTouchEvent, pTouchAreaLocalX, - pTouchAreaLocalY); - } - }; - - musicInfoText = new ChangeableText(0, 0, ResourceManager.getInstance().getFont("font"), "", HorizontalAlign.RIGHT, 35); - - final TextureRegion nptex = ResourceManager.getInstance().getTexture("music_np"); - music_nowplay = new Sprite(Utils.toRes(Config.getRES_WIDTH() - 500), 0, 40 * nptex.getWidth() / nptex.getHeight(), 40, nptex); - - final Rectangle bgTopRect = new Rectangle(0, 0, Config.getRES_WIDTH(), Utils.toRes(120)); - bgTopRect.setColor(0, 0, 0, 0.3f); - - final Rectangle bgbottomRect = new Rectangle(0, 0, Config.getRES_WIDTH(), - Math.max(author.getHeight(), yasonline.getHeight()) + Utils.toRes(15)); - bgbottomRect.setPosition(0, Config.getRES_HEIGHT() - bgbottomRect.getHeight()); - bgbottomRect.setColor(0, 0, 0, 0.3f); - - for (int i = 0; i < 120; i++) { - final float pX = Config.getRES_WIDTH() / 2; - final float pY = Config.getRES_HEIGHT() / 2; - - spectrum[i] = new Rectangle(pX, pY, 260, 10); - spectrum[i].setRotationCenter(0, 5); - spectrum[i].setScaleCenter(0, 5); - spectrum[i].setRotation(-220 + i * 3f); - spectrum[i].setAlpha(0.0f); - - scene.attachChild(spectrum[i]); - } - - LibraryManager.getInstance().loadLibraryCache((Activity) context, false); - - TextureRegion starRegion = ResourceManager.getInstance().getTexture("star"); - - { - particleSystem[0] = new ParticleSystem(new PointParticleEmitter(-40, Config.getRES_HEIGHT() * 3 / 4), 32, 48, 128, starRegion); - particleSystem[0].setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); - - particleSystem[0].addParticleInitializer(new VelocityInitializer(150, 430, -480, -520)); - particleSystem[0].addParticleInitializer(new AccelerationInitializer(10, 30)); - particleSystem[0].addParticleInitializer(new RotationInitializer(0.0f, 360.0f)); - - particleSystem[0].addParticleModifier(new ScaleModifier(0.5f, 2.0f, 0.0f, 1.0f)); - particleSystem[0].addParticleModifier(new AlphaModifier(1.0f, 0.0f, 0.0f, 1.0f)); - particleSystem[0].addParticleModifier(new ExpireModifier(1.0f)); - - particleSystem[0].setParticlesSpawnEnabled(false); - - scene.attachChild(particleSystem[0]); - } - - { - particleSystem[1] = new ParticleSystem(new PointParticleEmitter(Config.getRES_WIDTH(), Config.getRES_HEIGHT() * 3 / 4), 32, 48, 128, starRegion); - particleSystem[1].setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); - - particleSystem[1].addParticleInitializer(new VelocityInitializer(-150, -430, -480, -520)); - particleSystem[1].addParticleInitializer(new AccelerationInitializer(-10, 30)); - particleSystem[1].addParticleInitializer(new RotationInitializer(0.0f, 360.0f)); - - particleSystem[1].addParticleModifier(new ScaleModifier(0.5f, 2.0f, 0.0f, 1.0f)); - particleSystem[1].addParticleModifier(new AlphaModifier(1.0f, 0.0f, 0.0f, 1.0f)); - particleSystem[1].addParticleModifier(new ExpireModifier(1.0f)); - - particleSystem[1].setParticlesSpawnEnabled(false); - - scene.attachChild(particleSystem[1]); - } - - play.setAlpha(0f); - options.setAlpha(0f); - exit.setAlpha(0f); - - logo.setPosition((Config.getRES_WIDTH() - logo.getWidth()) / 2, (Config.getRES_HEIGHT() - logo.getHeight()) / 2); - logoOverlay.setPosition((Config.getRES_WIDTH() - logo.getWidth()) / 2, (Config.getRES_HEIGHT() - logo.getHeight()) / 2); - options.setScale(Config.getRES_WIDTH() / 1024f); - play.setScale(Config.getRES_WIDTH() / 1024f); - exit.setScale(Config.getRES_WIDTH() / 1024f); - options.setPosition(options.getX(), (Config.getRES_HEIGHT() - options.getHeight()) / 2); - play.setPosition(play.getX(), options.getY() - play.getHeight() - 40 * Config.getRES_WIDTH() / 1024f); - exit.setPosition(exit.getX(), options.getY() + options.getHeight() + 40 * Config.getRES_WIDTH() / 1024f); - - menuBarX = play.getX(); - playY = play.getScaleY(); - exitY = exit.getScaleY(); - - scene.attachChild(lastBackground, 0); - scene.attachChild(bgTopRect); - scene.attachChild(bgbottomRect); - scene.attachChild(author); - scene.attachChild(yasonline); - scene.attachChild(play); - scene.attachChild(options); - scene.attachChild(exit); - scene.attachChild(logo); - scene.attachChild(logoOverlay); - scene.attachChild(music_nowplay); - scene.attachChild(musicInfoText); - scene.attachChild(music_prev); - scene.attachChild(music_play); - scene.attachChild(music_pause); - scene.attachChild(music_stop); - scene.attachChild(music_next); - - scene.registerTouchArea(logo); - scene.registerTouchArea(author); - scene.registerTouchArea(yasonline); - scene.registerTouchArea(music_prev); - scene.registerTouchArea(music_play); - scene.registerTouchArea(music_pause); - scene.registerTouchArea(music_stop); - scene.registerTouchArea(music_next); - scene.setTouchAreaBindingEnabled(true); - - progressBar = new SongProgressBar(null, scene, 0, 0, new PointF(Utils.toRes(Config.getRES_WIDTH() - 320), Utils.toRes(100))); - progressBar.setProgressRectColor(new RGBAColor(0.9f, 0.9f, 0.9f, 0.8f)); - - createOnlinePanel(scene); - scene.registerUpdateHandler(this); - - String[] welcomeSounds = {"welcome", "welcome_piano"}; - int randNum = new Random().nextInt((1 - 0) + 1) + 0; - String welcomeSound = welcomeSounds[randNum]; - ResourceManager.getInstance().loadSound(welcomeSound, String.format("sfx/%s.ogg", welcomeSound), false).play(); - hitsound = ResourceManager.getInstance().loadSound("menuhit", "sfx/menuhit.ogg", false); - - /*if (BuildConfig.DEBUG) { - SupportSprite supportSprite = new SupportSprite(Config.getRES_WIDTH(), Config.getRES_HEIGHT()) { - - TextureQuad[] quads; - - { - Bitmap bitmap = Bitmap.createBitmap(4, 1, Bitmap.Config.ARGB_8888); - for (int i = 0; i < 4; i++) { - bitmap.setPixel(i, 0, Color.argb(i * 80 + 10, i * 80 + 10, i * 80 + 10, i * 80 + 10)); - } - //bitmap.setPremultiplied(true); - TextureRegion region = TextureHelper.createRegion(bitmap); - quads = new TextureQuad[4]; - { - TextureQuad quad = new TextureQuad(); - quad.setTextureAndSize(region); - quad.enableScale().scale.set(10, 10); - quad.position.set(0, 0); - quads[0] = quad; - } - { - TextureQuad quad = new TextureQuad(); - quad.setTextureAndSize(region); - quad.enableScale().scale.set(10, 10); - quad.position.set(640, 480); - quads[1] = quad; - } - { - TextureQuad quad = new TextureQuad(); - quad.setTextureAndSize(region); - quad.enableScale().scale.set(10, 10); - quad.position.set(640, 0); - quads[2] = quad; - } - { - TextureQuad quad = new TextureQuad(); - quad.setTextureAndSize(region); - quad.enableScale().scale.set(10, 10); - quad.position.set(0, 480); - quads[3] = quad; - } - *//*for (int i = 0; i < quads.length; i++) { - TextureQuad quad = new TextureQuad(); - quad.setTextureAndSize(region); - quad.position.set((float) Math.random() * 1000, (float) Math.random() * 1000); - if (Math.random() > 0.2) { - //quad.enableColor().accentColor.set((float) Math.random(), (float) Math.random(), (float) Math.random(), 1); - } - if (Math.random() > 0.5) { - //quad.enableRotation().rotation.value = (float) (Math.PI * 2 * Math.random()); - } - //if (Math.random() > 0.7) { - quad.enableScale().scale.set(10, 10); - //.set((float) Math.random() * 5, (float) Math.random() * 5); - //} - quads[i] = quad; - }*//* - } - - @Override - protected void onSupportDraw(BaseCanvas canvas) { - super.onSupportDraw(canvas); - canvas.save(); - float scale = Math.max(640 / canvas.getWidth(), 480 / canvas.getHeight()); - Vec2 startOffset = new Vec2(canvas.getWidth() / 2, canvas.getHeight() / 2) - .minus(640 * 0.5f / scale, 480 * 0.5f / scale); - - canvas.translate(startOffset.x, startOffset.y).expendAxis(scale);//.translate(64, 48); - - - - TextureQuadBatch batch = TextureQuadBatch.getDefaultBatch(); - for (TextureQuad quad : quads) { - batch.add(quad); - } - - - canvas.restore(); - } - }; - scene.attachChild(supportSprite); - }*/ - } - - private void createOnlinePanel(Scene scene) { - Config.loadOnlineConfig(context); - OnlineManager.getInstance().Init(context); - - if (OnlineManager.getInstance().isStayOnline()) { - Debug.i("Stay online, creating panel"); - OnlineScoring.getInstance().createPanel(); - final OnlinePanel panel = OnlineScoring.getInstance().getPanel(); - panel.setPosition(5, 5); - scene.attachChild(panel); - scene.registerTouchArea(panel.rect); - } - - OnlineScoring.getInstance().login(); - } - - public void reloadOnlinePanel() { - scene.detachChild(OnlineScoring.getInstance().getPanel()); - createOnlinePanel(scene); - } - - public void musicControl(MusicOption option) { - if (GlobalManager.getInstance().getSongService() == null || beatmapInfo == null) { - return; - } - switch (option) { - case PREV: { - if (GlobalManager.getInstance().getSongService().getStatus() == Status.PLAYING || GlobalManager.getInstance().getSongService().getStatus() == Status.PAUSED) { - GlobalManager.getInstance().getSongService().stop(); - } - firstTimingPoint = null; - LibraryManager.getInstance().getPrevBeatmap(); - loadBeatmapInfo(); - loadTimeingPoints(true); - doChange = false; - doStop = false; - } - break; - case PLAY: { - if (GlobalManager.getInstance().getSongService().getStatus() == Status.PAUSED || GlobalManager.getInstance().getSongService().getStatus() == Status.STOPPED) { - if (GlobalManager.getInstance().getSongService().getStatus() == Status.STOPPED) { - loadTimeingPoints(false); - GlobalManager.getInstance().getSongService().preLoad(beatmapInfo.getMusic()); - if (firstTimingPoint != null) { - bpmLength = firstTimingPoint.getBeatLength() * 1000f; - if (lastTimingPoint != null) { - offset = lastTimingPoint.getTime() * 1000f % bpmLength; - } - } - } - if (GlobalManager.getInstance().getSongService().getStatus() == Status.PAUSED) { - bpmLength = lastBpmLength; - if (lastTimingPoint != null) { - int position = GlobalManager.getInstance().getSongService().getPosition(); - offset = (position - lastTimingPoint.getTime() * 1000f) % bpmLength; - } - } - Debug.i("BPM: " + 60 / bpmLength * 1000 + " Offset: " + offset); -// ToastLogger.showText("BPM: " + 60 / bpmLength * 1000 + " Offset: " + offset, false); - GlobalManager.getInstance().getSongService().play(); - doStop = false; - } - } - break; - case PAUSE: { - if (GlobalManager.getInstance().getSongService().getStatus() == Status.PLAYING) { - GlobalManager.getInstance().getSongService().pause(); - lastBpmLength = bpmLength; - bpmLength = 1000; - } - } - break; - case STOP: { - if (GlobalManager.getInstance().getSongService().getStatus() == Status.PLAYING || GlobalManager.getInstance().getSongService().getStatus() == Status.PAUSED) { - GlobalManager.getInstance().getSongService().stop(); - lastBpmLength = bpmLength; - bpmLength = 1000; - } - } - break; - case NEXT: { - if (GlobalManager.getInstance().getSongService().getStatus() == Status.PLAYING || GlobalManager.getInstance().getSongService().getStatus() == Status.PAUSED) { - GlobalManager.getInstance().getSongService().stop(); - } - LibraryManager.getInstance().getNextBeatmap(); - firstTimingPoint = null; - loadBeatmapInfo(); - loadTimeingPoints(true); - doChange = false; - doStop = false; - } - break; - case SYNC: { - if (GlobalManager.getInstance().getSongService().getStatus() == Status.PLAYING) { - if (lastTimingPoint != null) { - int position = GlobalManager.getInstance().getSongService().getPosition(); - offset = (position - lastTimingPoint.getTime() * 1000f) % bpmLength; - } - Debug.i("BPM: " + 60 / bpmLength * 1000 + " Offset: " + offset); - } - } - } - } - - @Override - public void onUpdate(final float pSecondsElapsed) { - beatPassTime += pSecondsElapsed * 1000f; - if (isOnExitAnim) { - for (Rectangle specRectangle : spectrum) { - specRectangle.setWidth(0); - specRectangle.setAlpha(0); - } - return; - } - - if (GlobalManager.getInstance().getSongService() == null || !musicStarted || GlobalManager.getInstance().getSongService().getStatus() == Status.STOPPED) { - bpmLength = 1000; - offset = 0; - } - - if (doMenuShow == true && isMenuShowed == false) { - logo.registerEntityModifier(new MoveXModifier(0.3f, Config.getRES_WIDTH() / 2 - logo.getWidth() / 2, Config.getRES_WIDTH() / 3 - logo.getWidth() / 2, EaseExponentialOut.getInstance())); - logoOverlay.registerEntityModifier(new MoveXModifier(0.3f, Config.getRES_WIDTH() / 2 - logo.getWidth() / 2, Config.getRES_WIDTH() / 3 - logo.getWidth() / 2, EaseExponentialOut.getInstance())); - for (int i = 0; i < spectrum.length; i++) { - spectrum[i].registerEntityModifier(new MoveXModifier(0.3f, Config.getRES_WIDTH() / 2, Config.getRES_WIDTH() / 3, EaseExponentialOut.getInstance())); - } - play.registerEntityModifier(new ParallelEntityModifier( - new MoveXModifier(0.5f, menuBarX - 100, menuBarX, EaseElasticOut.getInstance()), - new org.anddev.andengine.entity.modifier.AlphaModifier(0.5f, 0, 0.9f, EaseCubicOut.getInstance()))); - options.registerEntityModifier(new ParallelEntityModifier( - new MoveXModifier(0.5f, menuBarX - 100, menuBarX, EaseElasticOut.getInstance()), - new org.anddev.andengine.entity.modifier.AlphaModifier(0.5f, 0, 0.9f, EaseCubicOut.getInstance()))); - exit.registerEntityModifier(new ParallelEntityModifier( - new MoveXModifier(0.5f, menuBarX - 100, menuBarX, EaseElasticOut.getInstance()), - new org.anddev.andengine.entity.modifier.AlphaModifier(0.5f, 0, 0.9f, EaseCubicOut.getInstance()))); - scene.registerTouchArea(play); - scene.registerTouchArea(options); - scene.registerTouchArea(exit); - isMenuShowed = true; - } - - if (doMenuShow == true && isMenuShowed == true) { - if (showPassTime > 10000f) { - scene.unregisterTouchArea(play); - scene.unregisterTouchArea(options); - scene.unregisterTouchArea(exit); - play.registerEntityModifier(new ParallelEntityModifier( - new MoveXModifier(1f, menuBarX, menuBarX - 50, EaseExponentialOut.getInstance()), - new org.anddev.andengine.entity.modifier.AlphaModifier(1f, 0.9f, 0, EaseExponentialOut.getInstance()))); - options.registerEntityModifier(new ParallelEntityModifier( - new MoveXModifier(1f, menuBarX, menuBarX - 50, EaseExponentialOut.getInstance()), - new org.anddev.andengine.entity.modifier.AlphaModifier(1f, 0.9f, 0, EaseExponentialOut.getInstance()))); - exit.registerEntityModifier(new ParallelEntityModifier( - new MoveXModifier(1f, menuBarX, menuBarX - 50, EaseExponentialOut.getInstance()), - new org.anddev.andengine.entity.modifier.AlphaModifier(1f, 0.9f, 0, EaseExponentialOut.getInstance()))); - logo.registerEntityModifier(new MoveXModifier(1f, Config.getRES_WIDTH() / 3 - logo.getWidth() / 2, Config.getRES_WIDTH() / 2 - logo.getWidth() / 2, - EaseBounceOut.getInstance())); - logoOverlay.registerEntityModifier(new MoveXModifier(1f, Config.getRES_WIDTH() / 3 - logo.getWidth() / 2, Config.getRES_WIDTH() / 2 - logo.getWidth() / 2, - EaseBounceOut.getInstance())); - for (int i = 0; i < spectrum.length; i++) { - spectrum[i].registerEntityModifier(new MoveXModifier(1f, Config.getRES_WIDTH() / 3, Config.getRES_WIDTH() / 2, EaseBounceOut.getInstance())); - } - isMenuShowed = false; - doMenuShow = false; - showPassTime = 0; - } else { - showPassTime += pSecondsElapsed * 1000f; - } - } - -// if (offset != 0) { -// beatPassTime += offset; -// offset = 0; -// } - - if (beatPassTime - lastBeatPassTime >= bpmLength - offset) { - lastBeatPassTime = beatPassTime; - offset = 0; - if (logo != null) { -// logo.clearEntityModifiers(); - logo.registerEntityModifier(new SequenceEntityModifier(new org.anddev.andengine.entity.modifier.ScaleModifier(bpmLength / 1000 * 0.9f, 1f, 1.07f), - new org.anddev.andengine.entity.modifier.ScaleModifier(bpmLength / 1000 * 0.07f, 1.07f, 1f))); - } - } - - if (GlobalManager.getInstance().getSongService() != null) { - if (!musicStarted) { - if (firstTimingPoint != null) { - bpmLength = firstTimingPoint.getBeatLength() * 1000f; - } else { - return; - } - progressBar.setStartTime(0); - GlobalManager.getInstance().getSongService().play(); - if (lastTimingPoint != null) { - offset = lastTimingPoint.getTime() * 1000f % bpmLength; - } - Debug.i("BPM: " + 60 / bpmLength * 1000 + " Offset: " + offset); -// ToastLogger.showText("BPM: " + 60 / bpmLength * 1000 + " Offset: " + offset, false); - musicStarted = true; - } - - if (GlobalManager.getInstance().getSongService().getStatus() == Status.PLAYING) { -// syncPassedTime += pSecondsElapsed * 1000f; - int position = GlobalManager.getInstance().getSongService().getPosition(); - progressBar.setTime(GlobalManager.getInstance().getSongService().getLength()); - progressBar.setPassedTime(position); - progressBar.update(pSecondsElapsed * 1000); - -// if (syncPassedTime > bpmLength * 8) { -// musicControl(MusicOption.SYNC); -// syncPassedTime = 0; -// } - - if (currentTimingPoint != null && position > currentTimingPoint.getTime() * 1000) { - if (!isContinuousKiai && currentTimingPoint.isKiai()) { - for (ParticleSystem particleSpout : particleSystem) { - particleSpout.setParticlesSpawnEnabled(true); - } - particleBeginTime = position; - particleEnabled = true; - } - isContinuousKiai = currentTimingPoint.isKiai(); - - if (timingPoints.size() > 0) { - currentTimingPoint = timingPoints.remove(0); - if (!currentTimingPoint.wasInderited()) { - lastTimingPoint = currentTimingPoint; - bpmLength = currentTimingPoint.getBeatLength() * 1000; - offset = lastTimingPoint.getTime() * 1000f % bpmLength; - Debug.i("BPM: " + 60 / bpmLength * 1000 + " Offset: " + offset); -// ToastLogger.showText("BPM: " + 60 / bpmLength * 1000 + " Offset: " + offset, false); - } - } else { - currentTimingPoint = null; - } - } - - if (particleEnabled && (position - particleBeginTime > 2000)) { - for (ParticleSystem particleSpout : particleSystem) { - particleSpout.setParticlesSpawnEnabled(false); - } - particleEnabled = false; - } - - int windowSize = 240; - int spectrumWidth = 120; - float[] fft = GlobalManager.getInstance().getSongService().getSpectrum(); - if (fft == null) return; - for (int i = 0, leftBound = 0; i < spectrumWidth; i++) { - float peak = 0; - int rightBound = (int) Math.pow(2., i * 9. / (windowSize - 1)); - if (rightBound <= leftBound) rightBound = leftBound + 1; - if (rightBound > 511) rightBound = 511; - - for (; leftBound < rightBound; leftBound++) { - if (peak < fft[1 + leftBound]) - peak = fft[1 + leftBound]; - } - - float initialAlpha = 0.4f; - float gradient = 20; - float currPeakLevel = peak * 500; - - if (currPeakLevel > peakLevel[i]) { - peakLevel[i] = currPeakLevel; - peakDownRate[i] = peakLevel[i] / gradient; - peakAlpha[i] = initialAlpha; - - } else { - peakLevel[i] = Math.max(peakLevel[i] - peakDownRate[i], 0f); - peakAlpha[i] = Math.max(peakAlpha[i] - initialAlpha / gradient, 0f); - } - - spectrum[i].setWidth(250f + peakLevel[i]); - spectrum[i].setAlpha(peakAlpha[i]); - } - } else { - for (Rectangle specRectangle : spectrum) { - specRectangle.setWidth(0); - specRectangle.setAlpha(0); - } - if (!doChange && !doStop && GlobalManager.getInstance().getSongService() != null && GlobalManager.getInstance().getSongService().getPosition() >= GlobalManager.getInstance().getSongService().getLength()) { - musicControl(MusicOption.NEXT); - } - } - } - } - - @Override - public void reset() { - - } - - public void loadBeatmap() { - LibraryManager.getInstance().shuffleLibrary(); - loadBeatmapInfo(); - loadTimeingPoints(true); - } - - public void loadBeatmapInfo() { - if (LibraryManager.getInstance().getSizeOfBeatmaps() != 0) { - beatmapInfo = LibraryManager.getInstance().getBeatmap(); - Log.w("MainMenuActivity", "Next song: " + beatmapInfo.getMusic() + ", Start at: " + beatmapInfo.getPreviewTime()); - - if (musicInfoText == null) { - musicInfoText = new ChangeableText(Utils.toRes(Config.getRES_WIDTH() - 500), Utils.toRes(3), - ResourceManager.getInstance().getFont("font"), "None...", HorizontalAlign.RIGHT, 35); - } - if (beatmapInfo.getArtistUnicode() != null && beatmapInfo.getTitleUnicode() != null && Config.isForceRomanized() == false) { - musicInfoText.setText(beatmapInfo.getArtistUnicode() + " - " + beatmapInfo.getTitleUnicode(), true); - } else if (beatmapInfo.getArtist() != null && beatmapInfo.getTitle() != null) { - musicInfoText.setText(beatmapInfo.getArtist() + " - " + beatmapInfo.getTitle(), true); - } else { - musicInfoText.setText("Failure to load QAQ", true); - } - try { - musicInfoText.setPosition(Utils.toRes(Config.getRES_WIDTH() - 500 + 470 - musicInfoText.getWidth()), musicInfoText.getY()); - music_nowplay.setPosition(Utils.toRes(Config.getRES_WIDTH() - 500 + 470 - musicInfoText.getWidth() - 130), 0); - } catch (NullPointerException e) { - musicInfoText.setPosition(Utils.toRes(Config.getRES_WIDTH() - 500 + 470 - 200), 5); - music_nowplay.setPosition(Utils.toRes(Config.getRES_WIDTH() - 500 + 470 - 200 - 130), 0); - } - } - } - - public void loadTimeingPoints(boolean reloadMusic) { - if (beatmapInfo == null) { - return; - } - - for (ParticleSystem particleSpout : particleSystem) { - particleSpout.setParticlesSpawnEnabled(false); - } - particleEnabled = false; - - ArrayList trackInfos = beatmapInfo.getTracks(); - if (trackInfos != null && trackInfos.size() > 0) { - int trackIndex = random.nextInt(trackInfos.size()); - selectedTrack = trackInfos.get(trackIndex); - - if (selectedTrack.getBackground() != null) { - try { - final TextureRegion tex = Config.isSafeBeatmapBg() ? - ResourceManager.getInstance().getTexture("menu-background") : - ResourceManager.getInstance().loadBackground(selectedTrack.getBackground()); - - if (tex != null) { - float height = tex.getHeight(); - height *= Config.getRES_WIDTH() - / (float) tex.getWidth(); - background = new Sprite(0, - (Config.getRES_HEIGHT() - height) / 2, Config - .getRES_WIDTH(), height, tex); - lastBackground.registerEntityModifier(new org.anddev.andengine.entity.modifier.AlphaModifier(1.5f, 1, 0, new IEntityModifier.IEntityModifierListener() { - @Override - public void onModifierStarted(IModifier pModifier, IEntity pItem) { - scene.attachChild(background, 0); - } - - @Override - public void onModifierFinished(IModifier pModifier, final IEntity pItem) { - GlobalManager.getInstance().getMainActivity().runOnUpdateThread(new Runnable() { - @Override - public void run() { - // TODO Auto-generated method stub - pItem.detachSelf(); - } - }); - } - })); - lastBackground = background; - } - } catch (Exception e) { - Debug.e(e.toString()); - lastBackground.setAlpha(0); - } - } else { - lastBackground.setAlpha(0); - } - - if (reloadMusic) { - if (GlobalManager.getInstance().getSongService() != null) { - GlobalManager.getInstance().getSongService().preLoad(beatmapInfo.getMusic()); - musicStarted = false; - } else { - Log.w("nullpoint", "GlobalManager.getInstance().getSongService() is null while reload music (MainScene.loadTimeingPoints)"); - } - } - - Arrays.fill(peakLevel, 0f); - Arrays.fill(peakDownRate, 1f); - Arrays.fill(peakAlpha, 0f); - - OSUParser parser = new OSUParser(selectedTrack.getFilename()); - if (parser.openFile()) { - beatmapData = parser.readData(); - - timingPoints = new LinkedList(); - currentTimingPoint = null; - for (final String s : beatmapData.getData("TimingPoints")) { - final TimingPoint tp = new TimingPoint(s.split("[,]"), currentTimingPoint); - timingPoints.add(tp); - if (tp.wasInderited() == false || currentTimingPoint == null) { - currentTimingPoint = tp; - } - } - firstTimingPoint = timingPoints.remove(0); - currentTimingPoint = firstTimingPoint; - lastTimingPoint = currentTimingPoint; - bpmLength = firstTimingPoint.getBeatLength() * 1000f; - } - } - } - - public void showExitDialog() { - GlobalManager.getInstance().getMainActivity().runOnUiThread(new Runnable() { - public void run() { - new ConfirmDialogFragment().setMessage(R.string.dialog_exit_message).showForResult( - isAccepted -> { - if (isAccepted) { - exit(); - } - } - ); - } - }); - } - - public void exit() { - if (isOnExitAnim) { - return; - } - isOnExitAnim = true; - - PowerManager.WakeLock wakeLock = GlobalManager.getInstance().getMainActivity().getWakeLock(); - if (wakeLock != null && wakeLock.isHeld()) { - wakeLock.release(); - } - - scene.unregisterTouchArea(play); - scene.unregisterTouchArea(options); - scene.unregisterTouchArea(exit); - - play.setAlpha(0); - options.setAlpha(0); - exit.setAlpha(0); - - //ResourceManager.getInstance().loadSound("seeya", "sfx/seeya.wav", false).play(); - //Allow customize Seeya Sounds from Skins - BassSoundProvider exitsound = ResourceManager.getInstance().getSound("seeya"); - if (exitsound != null) { - exitsound.play(); - } - - Rectangle bg = new Rectangle(0, 0, Config.getRES_WIDTH(), - Config.getRES_HEIGHT()); - bg.setColor(0, 0, 0, 1.0f); - bg.registerEntityModifier(ModifierFactory.newAlphaModifier(3.0f, 0, 1)); - scene.attachChild(bg); - logo.registerEntityModifier(new ParallelEntityModifier( - new RotationModifier(3.0f, 0, -15), - ModifierFactory.newScaleModifier(3.0f, 1f, 0.8f) - )); - logoOverlay.registerEntityModifier(new ParallelEntityModifier( - new RotationModifier(3.0f, 0, -15), - ModifierFactory.newScaleModifier(3.0f, 1f, 0.8f) - )); - - ScheduledExecutorService taskPool = Executors.newScheduledThreadPool(1); - taskPool.schedule(new TimerTask() { - @Override - public void run() { - if (GlobalManager.getInstance().getSongService() != null) { - GlobalManager.getInstance().getSongService().hideNotifyPanel(); - if (Build.VERSION.SDK_INT > 10) - GlobalManager.getInstance().getMainActivity().unregisterReceiver(GlobalManager.getInstance().getMainActivity().onNotifyButtonClick); - GlobalManager.getInstance().getMainActivity().unbindService(GlobalManager.getInstance().getMainActivity().connection); - GlobalManager.getInstance().getMainActivity().stopService(new Intent(GlobalManager.getInstance().getMainActivity(), SongService.class)); - musicStarted = false; - } - android.os.Process.killProcess(android.os.Process.myPid()); - } - }, 3000, TimeUnit.MILLISECONDS); - } - - public Scene getScene() { - return scene; - } - - public BeatmapInfo getBeatmapInfo() { - return beatmapInfo; - } - - public void setBeatmap(BeatmapInfo info) { - int playIndex = LibraryManager.getInstance().findBeatmap(info); - Debug.i("index " + playIndex); - loadBeatmapInfo(); - loadTimeingPoints(false); - musicControl(MusicOption.SYNC); - } - - public void watchReplay(String replayFile) { - replay = new Replay(); - if (replay.loadInfo(replayFile)) { - if (replay.replayVersion >= 3) { - //replay - ScoringScene scorescene = GlobalManager.getInstance().getScoring(); - StatisticV2 stat = replay.getStat(); - TrackInfo track = LibraryManager.getInstance().findTrackByFileNameAndMD5(replay.getMapfile(), replay.getMd5()); - if (track != null) { - GlobalManager.getInstance().getMainScene().setBeatmap(track.getBeatmap()); - GlobalManager.getInstance().getSongMenu().select(); - ResourceManager.getInstance().loadBackground(track.getBackground()); - GlobalManager.getInstance().getSongService().preLoad(track.getBeatmap().getMusic()); - GlobalManager.getInstance().getSongService().play(); - scorescene.load(stat, null, ru.nsu.ccfit.zuev.osu.GlobalManager.getInstance().getSongService(), replayFile, null, track); - GlobalManager.getInstance().getEngine().setScene(scorescene.getScene()); - } - } - } - } - - public void show() { - GlobalManager.getInstance().getSongService().setGaming(false); - GlobalManager.getInstance().getEngine().setScene(getScene()); - if (GlobalManager.getInstance().getSelectedTrack() != null) { - setBeatmap(GlobalManager.getInstance().getSelectedTrack().getBeatmap()); - } - } - - public enum MusicOption {PREV, PLAY, PAUSE, STOP, NEXT, SYNC} + public SongProgressBar progressBar; + public BeatmapInfo beatmapInfo; + private Context context; + private Sprite logo, logoOverlay, play, options, exit, background, lastBackground; + private Sprite music_nowplay; + private Scene scene; + private ChangeableText musicInfoText; + // private ArrayList beatmaps; + private Random random = new Random(); + private Rectangle[] spectrum = new Rectangle[120]; + private float[] peakLevel = new float[120]; + private float[] peakDownRate = new float[120]; + private float[] peakAlpha = new float[120]; + private Replay replay = null; + private TrackInfo selectedTrack; + private BeatmapData beatmapData; + private List timingPoints; + private TimingPoint currentTimingPoint, lastTimingPoint, firstTimingPoint; + + private int particleBeginTime = 0; + private boolean particleEnabled = false; + private boolean isContinuousKiai = false; + + private ParticleSystem[] particleSystem = new ParticleSystem[2]; + + //private BassAudioPlayer music; + + private boolean musicStarted; + private BassSoundProvider hitsound; + + private float bpmLength = 1000; + private float lastBpmLength = 0; + private float offset = 0; + private float beatPassTime = 0; + private float lastBeatPassTime = 0; + private boolean doChange = false; + private boolean doStop = false; + // private int playIndex = 0; +// private int lastPlayIndex = -1; + private long lastHit = 0; + private boolean isOnExitAnim = false; + + private boolean isMenuShowed = false; + private boolean doMenuShow = false; + private float showPassTime = 0, syncPassedTime = 0; + private float menuBarX = 0, playY, optionsY, exitY; + + + public void load(Context context) { + this.context = context; + Debug.i("Load: mainMenuLoaded()"); + scene = new Scene(); + + final TextureRegion tex = ResourceManager.getInstance().getTexture("menu-background"); + + if (tex != null) { + float height = tex.getHeight(); + height *= Config.getRES_WIDTH() + / (float) tex.getWidth(); + final Sprite menuBg = new Sprite( + 0, + (Config.getRES_HEIGHT() - height) / 2, + Config.getRES_WIDTH(), + height, tex); + scene.setBackground(new SpriteBackground(menuBg)); + } else { + scene.setBackground(new ColorBackground(70 / 255f, 129 / 255f, + 252 / 255f)); + } + lastBackground = new Sprite(0, 0, Config.getRES_WIDTH(), Config.getRES_HEIGHT(), ResourceManager.getInstance().getTexture("emptyavatar")); + final TextureRegion logotex = ResourceManager.getInstance().getTexture("logo"); + logo = new Sprite(Config.getRES_WIDTH() / 2 - logotex.getWidth() / 2, Config.getRES_HEIGHT() / 2 - logotex.getHeight() / 2, logotex) { + @Override + public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, + final float pTouchAreaLocalX, final float pTouchAreaLocalY) { + if (pSceneTouchEvent.isActionDown()) { + if (hitsound != null) { + hitsound.play(); + } + Debug.i("logo down"); + return true; + } + if (pSceneTouchEvent.isActionUp()) { + Debug.i("logo up"); + Debug.i("doMenuShow " + doMenuShow + " isMenuShowed " + isMenuShowed + " showPassTime " + showPassTime); + if (doMenuShow == true && isMenuShowed == true) { + showPassTime = 20000; + } + if (doMenuShow == false && isMenuShowed == false && logo.getX() == (Config.getRES_WIDTH() - logo.getWidth()) / 2) { + doMenuShow = true; + showPassTime = 0; + } + Debug.i("doMenuShow " + doMenuShow + " isMenuShowed " + isMenuShowed + " showPassTime " + showPassTime); + return true; + } + return super.onAreaTouched(pSceneTouchEvent, pTouchAreaLocalX, + pTouchAreaLocalY); + } + }; + + logoOverlay = new Sprite(Config.getRES_WIDTH() / 2 - logotex.getWidth() / 2, Config.getRES_HEIGHT() / 2 - logotex.getHeight() / 2, logotex); + logoOverlay.setScale(1.07f); + logoOverlay.setAlpha(0.2f); + + play = new Sprite(logo.getX() + logo.getWidth() - Config.getRES_WIDTH() / 3, + 60 + 82 - 32, ResourceManager.getInstance().getTexture("play")) { + + + @Override + public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, + final float pTouchAreaLocalX, final float pTouchAreaLocalY) { + if (pSceneTouchEvent.isActionDown()) { + setColor(0.7f, 0.7f, 0.7f); + if (hitsound != null) { + hitsound.play(); + } + return true; + } + if (pSceneTouchEvent.isActionUp()) { + setColor(1, 1, 1); + if (isOnExitAnim) return true; + GlobalManager.getInstance().getSongService().setGaming(true); + if (GlobalManager.getInstance().getCamera().getRotation() == 0) { + Utils.setAccelerometerSign(1); + } else { + Utils.setAccelerometerSign(-1); + } +// final Intent intent = new Intent( +// MainManager.getInstance().getMainActivity(), OsuActivity.class); +// MainManager.getInstance().getMainActivity().startActivity(intent); + new AsyncTaskLoader().execute(new OsuAsyncCallback() { + public void run() { + GlobalManager.getInstance().getEngine().setScene(new LoadingScreen().getScene()); + GlobalManager.getInstance().getMainActivity().checkNewBeatmaps(); + if (!LibraryManager.getInstance().loadLibraryCache(GlobalManager.getInstance().getMainActivity(), false)) { + LibraryManager.getInstance().scanLibrary(GlobalManager.getInstance().getMainActivity()); + } + GlobalManager.getInstance().getSongMenu().reload(); + /* To fixed skin load bug in some Android 10 + if (Build.VERSION.SDK_INT >= 29) { + String skinNow = Config.getSkinPath(); + ResourceManager.getInstance().loadSkin(skinNow); + } */ + } + + public void onComplete() { + + musicControl(MusicOption.PLAY); + GlobalManager.getInstance().getEngine().setScene(GlobalManager.getInstance().getSongMenu().getScene()); + GlobalManager.getInstance().getSongMenu().select(); + } + }); + return true; + } + return super.onAreaTouched(pSceneTouchEvent, pTouchAreaLocalX, + pTouchAreaLocalY); + } + + }; + + options = new Sprite(logo.getX() + logo.getWidth() - Config.getRES_WIDTH() / 3, + 60 + 3 * 82 - 64, ResourceManager.getInstance().getTexture( + "options")) { + + @Override + public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, + final float pTouchAreaLocalX, final float pTouchAreaLocalY) { + if (pSceneTouchEvent.isActionDown()) { + setColor(0.7f, 0.7f, 0.7f); + if (hitsound != null) { + hitsound.play(); + } + return true; + } + if (pSceneTouchEvent.isActionUp()) { + setColor(1, 1, 1); + if (isOnExitAnim) return true; + GlobalManager.getInstance().getSongService().setGaming(true); + // GlobalManager.getInstance().getSongService().setIsSettingMenu(true); + /* final Intent intent = new Intent(GlobalManager.getInstance().getMainActivity(), + SettingsMenu.class); + GlobalManager.getInstance().getMainActivity().startActivity(intent); */ + GlobalManager.getInstance().getMainActivity().runOnUiThread(() -> + new SettingsMenu().show()); + return true; + } + return super.onAreaTouched(pSceneTouchEvent, pTouchAreaLocalX, + pTouchAreaLocalY); + } + }; + + exit = new Sprite(logo.getX() + logo.getWidth() - Config.getRES_WIDTH() / 3, 60 + + 5 * 82 - 128 + 32, ResourceManager.getInstance().getTexture( + "exit")) { + + @Override + public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, + final float pTouchAreaLocalX, final float pTouchAreaLocalY) { + if (pSceneTouchEvent.isActionDown()) { + setColor(0.7f, 0.7f, 0.7f); + // if (hitsound != null) { + // hitsound.play(); + // } + return true; + } + if (pSceneTouchEvent.isActionUp()) { + if (GlobalManager.getInstance().getCamera().getRotation() == 0) { + Utils.setAccelerometerSign(1); + } else { + Utils.setAccelerometerSign(-1); + } + setColor(1, 1, 1); + + showExitDialog(); + + return true; + } + return super.onAreaTouched(pSceneTouchEvent, pTouchAreaLocalX, + pTouchAreaLocalY); + } + }; + + final Text author = new Text(10, 530, ResourceManager + .getInstance().getFont("font"), + String.format( + Locale.getDefault(), + "osu!droid %s\nby osu!droid Team\nosu! is \u00a9 peppy 2007-2021", + BuildConfig.VERSION_NAME + " (" + BuildConfig.BUILD_TYPE + ")" + )) { + + + @Override + public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, + final float pTouchAreaLocalX, final float pTouchAreaLocalY) { + if (pSceneTouchEvent.isActionDown()) { + new ConfirmDialogFragment().setMessage(R.string.dialog_visit_osu_website_message).showForResult( + isAccepted -> { + if(isAccepted) { + Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://osu.ppy.sh")); + GlobalManager.getInstance().getMainActivity().startActivity(browserIntent); + } + } + ); + return true; + } + return false; + } + }; + author.setPosition(10, Config.getRES_HEIGHT() - author.getHeight() - 10); + + final Text yasonline = new Text(720, 530, ResourceManager + .getInstance().getFont("font"), + " Performance Ranking\n Provided by iBancho") { + + @Override + public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, + final float pTouchAreaLocalX, final float pTouchAreaLocalY) { + if (pSceneTouchEvent.isActionDown()) { + new ConfirmDialogFragment().setMessage(R.string.dialog_visit_osudroid_website_message).showForResult( + isAccepted -> { + if(isAccepted) { + Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://" + OnlineManager.hostname)); + GlobalManager.getInstance().getMainActivity().startActivity(browserIntent); + } + } + ); + return true; + } + return false; + } + }; + yasonline.setPosition(Config.getRES_WIDTH() - yasonline.getWidth() - 40, Config.getRES_HEIGHT() - yasonline.getHeight() - 10); + + final Sprite music_prev = new Sprite(Config.getRES_WIDTH() - 50 * 6 + 35, + 47, 40, 40, ResourceManager.getInstance().getTexture( + "music_prev")) { + + @Override + public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, + final float pTouchAreaLocalX, final float pTouchAreaLocalY) { + if (pSceneTouchEvent.isActionDown()) { + setColor(0.7f, 0.7f, 0.7f); + doChange = true; + return true; + } + if (pSceneTouchEvent.isActionUp()) { + setColor(1, 1, 1); + if (lastHit == 0) { + lastHit = System.currentTimeMillis(); + } else { + if (System.currentTimeMillis() - lastHit <= 1000 && !isOnExitAnim) { + return true; + } + } + lastHit = System.currentTimeMillis(); + musicControl(MusicOption.PREV); + return true; + } + return super.onAreaTouched(pSceneTouchEvent, pTouchAreaLocalX, + pTouchAreaLocalY); + } + }; + + final Sprite music_play = new Sprite(Config.getRES_WIDTH() - 50 * 5 + 35, + 47, 40, 40, ResourceManager.getInstance().getTexture( + "music_play")) { + + @Override + public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, + final float pTouchAreaLocalX, final float pTouchAreaLocalY) { + if (pSceneTouchEvent.isActionDown()) { + setColor(0.7f, 0.7f, 0.7f); + return true; + } + if (pSceneTouchEvent.isActionUp()) { + setColor(1, 1, 1); + musicControl(MusicOption.PLAY); + return true; + } + return super.onAreaTouched(pSceneTouchEvent, pTouchAreaLocalX, + pTouchAreaLocalY); + } + }; + + final Sprite music_pause = new Sprite(Config.getRES_WIDTH() - 50 * 4 + 35, + 47, 40, 40, ResourceManager.getInstance().getTexture( + "music_pause")) { + + @Override + public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, + final float pTouchAreaLocalX, final float pTouchAreaLocalY) { + if (pSceneTouchEvent.isActionDown()) { + setColor(0.7f, 0.7f, 0.7f); + return true; + } + if (pSceneTouchEvent.isActionUp()) { + setColor(1, 1, 1); + musicControl(MusicOption.PAUSE); + return true; + } + return super.onAreaTouched(pSceneTouchEvent, pTouchAreaLocalX, + pTouchAreaLocalY); + } + }; + + final Sprite music_stop = new Sprite(Config.getRES_WIDTH() - 50 * 3 + 35, + 47, 40, 40, ResourceManager.getInstance().getTexture( + "music_stop")) { + + @Override + public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, + final float pTouchAreaLocalX, final float pTouchAreaLocalY) { + if (pSceneTouchEvent.isActionDown()) { + setColor(0.7f, 0.7f, 0.7f); + doStop = true; + return true; + } + if (pSceneTouchEvent.isActionUp()) { + setColor(1, 1, 1); + musicControl(MusicOption.STOP); + return true; + } + return super.onAreaTouched(pSceneTouchEvent, pTouchAreaLocalX, + pTouchAreaLocalY); + } + }; + + final Sprite music_next = new Sprite(Config.getRES_WIDTH() - 50 * 2 + 35, + 47, 40, 40, ResourceManager.getInstance().getTexture( + "music_next")) { + + @Override + public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, + final float pTouchAreaLocalX, final float pTouchAreaLocalY) { + if (pSceneTouchEvent.isActionDown()) { + setColor(0.7f, 0.7f, 0.7f); + doChange = true; + return true; + } + if (pSceneTouchEvent.isActionUp()) { + setColor(1, 1, 1); + if (lastHit == 0) { + lastHit = System.currentTimeMillis(); + } else { + if (System.currentTimeMillis() - lastHit <= 1000 && !isOnExitAnim) { + return true; + } + } + lastHit = System.currentTimeMillis(); + musicControl(MusicOption.NEXT); + return true; + } + return super.onAreaTouched(pSceneTouchEvent, pTouchAreaLocalX, + pTouchAreaLocalY); + } + }; + + musicInfoText = new ChangeableText(0, 0, ResourceManager.getInstance().getFont("font"), "", HorizontalAlign.RIGHT, 35); + + final TextureRegion nptex = ResourceManager.getInstance().getTexture("music_np"); + music_nowplay = new Sprite(Utils.toRes(Config.getRES_WIDTH() - 500), 0, 40 * nptex.getWidth() / nptex.getHeight(), 40, nptex); + + final Rectangle bgTopRect = new Rectangle(0, 0, Config.getRES_WIDTH(), Utils.toRes(120)); + bgTopRect.setColor(0, 0, 0, 0.3f); + + final Rectangle bgbottomRect = new Rectangle(0, 0, Config.getRES_WIDTH(), + Math.max(author.getHeight(), yasonline.getHeight()) + Utils.toRes(15)); + bgbottomRect.setPosition(0, Config.getRES_HEIGHT() - bgbottomRect.getHeight()); + bgbottomRect.setColor(0, 0, 0, 0.3f); + + for (int i = 0; i < 120; i++) { + final float pX = Config.getRES_WIDTH() / 2; + final float pY = Config.getRES_HEIGHT() / 2; + + spectrum[i] = new Rectangle(pX, pY, 260, 10); + spectrum[i].setRotationCenter(0, 5); + spectrum[i].setScaleCenter(0, 5); + spectrum[i].setRotation(-220 + i * 3f); + spectrum[i].setAlpha(0.0f); + + scene.attachChild(spectrum[i]); + } + + LibraryManager.getInstance().loadLibraryCache((Activity) context, false); + + TextureRegion starRegion = ResourceManager.getInstance().getTexture("star"); + + { + particleSystem[0] = new ParticleSystem(new PointParticleEmitter(-40, Config.getRES_HEIGHT() * 3 / 4), 32, 48, 128, starRegion); + particleSystem[0].setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); + + particleSystem[0].addParticleInitializer(new VelocityInitializer(150, 430, -480, -520)); + particleSystem[0].addParticleInitializer(new AccelerationInitializer(10, 30)); + particleSystem[0].addParticleInitializer(new RotationInitializer(0.0f, 360.0f)); + + particleSystem[0].addParticleModifier(new ScaleModifier(0.5f, 2.0f, 0.0f, 1.0f)); + particleSystem[0].addParticleModifier(new AlphaModifier(1.0f, 0.0f, 0.0f, 1.0f)); + particleSystem[0].addParticleModifier(new ExpireModifier(1.0f)); + + particleSystem[0].setParticlesSpawnEnabled(false); + + scene.attachChild(particleSystem[0]); + } + + { + particleSystem[1] = new ParticleSystem(new PointParticleEmitter(Config.getRES_WIDTH(), Config.getRES_HEIGHT() * 3 / 4), 32, 48, 128, starRegion); + particleSystem[1].setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); + + particleSystem[1].addParticleInitializer(new VelocityInitializer(-150, -430, -480, -520)); + particleSystem[1].addParticleInitializer(new AccelerationInitializer(-10, 30)); + particleSystem[1].addParticleInitializer(new RotationInitializer(0.0f, 360.0f)); + + particleSystem[1].addParticleModifier(new ScaleModifier(0.5f, 2.0f, 0.0f, 1.0f)); + particleSystem[1].addParticleModifier(new AlphaModifier(1.0f, 0.0f, 0.0f, 1.0f)); + particleSystem[1].addParticleModifier(new ExpireModifier(1.0f)); + + particleSystem[1].setParticlesSpawnEnabled(false); + + scene.attachChild(particleSystem[1]); + } + + play.setAlpha(0f); + options.setAlpha(0f); + exit.setAlpha(0f); + + logo.setPosition((Config.getRES_WIDTH() - logo.getWidth()) / 2, (Config.getRES_HEIGHT() - logo.getHeight()) / 2); + logoOverlay.setPosition((Config.getRES_WIDTH() - logo.getWidth()) / 2, (Config.getRES_HEIGHT() - logo.getHeight()) / 2); + options.setScale(Config.getRES_WIDTH() / 1024f); + play.setScale(Config.getRES_WIDTH() / 1024f); + exit.setScale(Config.getRES_WIDTH() / 1024f); + options.setPosition(options.getX(), (Config.getRES_HEIGHT() - options.getHeight()) / 2); + play.setPosition(play.getX(), options.getY() - play.getHeight() - 40 * Config.getRES_WIDTH() / 1024f); + exit.setPosition(exit.getX(), options.getY() + options.getHeight() + 40 * Config.getRES_WIDTH() / 1024f); + + menuBarX = play.getX(); + playY = play.getScaleY(); + exitY = exit.getScaleY(); + + scene.attachChild(lastBackground, 0); + scene.attachChild(bgTopRect); + scene.attachChild(bgbottomRect); + scene.attachChild(author); + scene.attachChild(yasonline); + scene.attachChild(play); + scene.attachChild(options); + scene.attachChild(exit); + scene.attachChild(logo); + scene.attachChild(logoOverlay); + scene.attachChild(music_nowplay); + scene.attachChild(musicInfoText); + scene.attachChild(music_prev); + scene.attachChild(music_play); + scene.attachChild(music_pause); + scene.attachChild(music_stop); + scene.attachChild(music_next); + + scene.registerTouchArea(logo); + scene.registerTouchArea(author); + scene.registerTouchArea(yasonline); + scene.registerTouchArea(music_prev); + scene.registerTouchArea(music_play); + scene.registerTouchArea(music_pause); + scene.registerTouchArea(music_stop); + scene.registerTouchArea(music_next); + scene.setTouchAreaBindingEnabled(true); + + progressBar = new SongProgressBar(null, scene, 0, 0, new PointF(Utils.toRes(Config.getRES_WIDTH() - 320), Utils.toRes(100))); + progressBar.setProgressRectColor(new RGBAColor(0.9f, 0.9f, 0.9f, 0.8f)); + + createOnlinePanel(scene); + scene.registerUpdateHandler(this); + + String[] welcomeSounds = {"welcome", "welcome_piano"}; + int randNum = new Random().nextInt((1 - 0) + 1) + 0; + String welcomeSound = welcomeSounds[randNum]; + ResourceManager.getInstance().loadSound(welcomeSound, String.format("sfx/%s.ogg", welcomeSound), false).play(); + hitsound = ResourceManager.getInstance().loadSound("menuhit", "sfx/menuhit.ogg", false); + + /*if (BuildConfig.DEBUG) { + SupportSprite supportSprite = new SupportSprite(Config.getRES_WIDTH(), Config.getRES_HEIGHT()) { + + TextureQuad[] quads; + + { + Bitmap bitmap = Bitmap.createBitmap(4, 1, Bitmap.Config.ARGB_8888); + for (int i = 0; i < 4; i++) { + bitmap.setPixel(i, 0, Color.argb(i * 80 + 10, i * 80 + 10, i * 80 + 10, i * 80 + 10)); + } + //bitmap.setPremultiplied(true); + TextureRegion region = TextureHelper.createRegion(bitmap); + quads = new TextureQuad[4]; + { + TextureQuad quad = new TextureQuad(); + quad.setTextureAndSize(region); + quad.enableScale().scale.set(10, 10); + quad.position.set(0, 0); + quads[0] = quad; + } + { + TextureQuad quad = new TextureQuad(); + quad.setTextureAndSize(region); + quad.enableScale().scale.set(10, 10); + quad.position.set(640, 480); + quads[1] = quad; + } + { + TextureQuad quad = new TextureQuad(); + quad.setTextureAndSize(region); + quad.enableScale().scale.set(10, 10); + quad.position.set(640, 0); + quads[2] = quad; + } + { + TextureQuad quad = new TextureQuad(); + quad.setTextureAndSize(region); + quad.enableScale().scale.set(10, 10); + quad.position.set(0, 480); + quads[3] = quad; + } + *//*for (int i = 0; i < quads.length; i++) { + TextureQuad quad = new TextureQuad(); + quad.setTextureAndSize(region); + quad.position.set((float) Math.random() * 1000, (float) Math.random() * 1000); + if (Math.random() > 0.2) { + //quad.enableColor().accentColor.set((float) Math.random(), (float) Math.random(), (float) Math.random(), 1); + } + if (Math.random() > 0.5) { + //quad.enableRotation().rotation.value = (float) (Math.PI * 2 * Math.random()); + } + //if (Math.random() > 0.7) { + quad.enableScale().scale.set(10, 10); + //.set((float) Math.random() * 5, (float) Math.random() * 5); + //} + quads[i] = quad; + }*//* + } + + @Override + protected void onSupportDraw(BaseCanvas canvas) { + super.onSupportDraw(canvas); + canvas.save(); + float scale = Math.max(640 / canvas.getWidth(), 480 / canvas.getHeight()); + Vec2 startOffset = new Vec2(canvas.getWidth() / 2, canvas.getHeight() / 2) + .minus(640 * 0.5f / scale, 480 * 0.5f / scale); + + canvas.translate(startOffset.x, startOffset.y).expendAxis(scale);//.translate(64, 48); + + + + TextureQuadBatch batch = TextureQuadBatch.getDefaultBatch(); + for (TextureQuad quad : quads) { + batch.add(quad); + } + + + canvas.restore(); + } + }; + scene.attachChild(supportSprite); + }*/ + } + + private void createOnlinePanel(Scene scene) { + Config.loadOnlineConfig(context); + OnlineManager.getInstance().Init(context); + + if (OnlineManager.getInstance().isStayOnline()) { + Debug.i("Stay online, creating panel"); + OnlineScoring.getInstance().createPanel(); + final OnlinePanel panel = OnlineScoring.getInstance().getPanel(); + panel.setPosition(5, 5); + scene.attachChild(panel); + scene.registerTouchArea(panel.rect); + } + + OnlineScoring.getInstance().login(); + } + + public void reloadOnlinePanel() { + scene.detachChild(OnlineScoring.getInstance().getPanel()); + createOnlinePanel(scene); + } + + public void musicControl(MusicOption option) { + if (GlobalManager.getInstance().getSongService() == null || beatmapInfo == null) { + return; + } + switch (option) { + case PREV: { + if (GlobalManager.getInstance().getSongService().getStatus() == Status.PLAYING || GlobalManager.getInstance().getSongService().getStatus() == Status.PAUSED) { + GlobalManager.getInstance().getSongService().stop(); + } + firstTimingPoint = null; + LibraryManager.getInstance().getPrevBeatmap(); + loadBeatmapInfo(); + loadTimeingPoints(true); + doChange = false; + doStop = false; + } + break; + case PLAY: { + if (GlobalManager.getInstance().getSongService().getStatus() == Status.PAUSED || GlobalManager.getInstance().getSongService().getStatus() == Status.STOPPED) { + if (GlobalManager.getInstance().getSongService().getStatus() == Status.STOPPED) { + loadTimeingPoints(false); + GlobalManager.getInstance().getSongService().preLoad(beatmapInfo.getMusic()); + if (firstTimingPoint != null) { + bpmLength = firstTimingPoint.getBeatLength() * 1000f; + if (lastTimingPoint != null) { + offset = lastTimingPoint.getTime() * 1000f % bpmLength; + } + } + } + if (GlobalManager.getInstance().getSongService().getStatus() == Status.PAUSED) { + bpmLength = lastBpmLength; + if (lastTimingPoint != null) { + int position = GlobalManager.getInstance().getSongService().getPosition(); + offset = (position - lastTimingPoint.getTime() * 1000f) % bpmLength; + } + } + Debug.i("BPM: " + 60 / bpmLength * 1000 + " Offset: " + offset); +// ToastLogger.showText("BPM: " + 60 / bpmLength * 1000 + " Offset: " + offset, false); + GlobalManager.getInstance().getSongService().play(); + doStop = false; + } + } + break; + case PAUSE: { + if (GlobalManager.getInstance().getSongService().getStatus() == Status.PLAYING) { + GlobalManager.getInstance().getSongService().pause(); + lastBpmLength = bpmLength; + bpmLength = 1000; + } + } + break; + case STOP: { + if (GlobalManager.getInstance().getSongService().getStatus() == Status.PLAYING || GlobalManager.getInstance().getSongService().getStatus() == Status.PAUSED) { + GlobalManager.getInstance().getSongService().stop(); + lastBpmLength = bpmLength; + bpmLength = 1000; + } + } + break; + case NEXT: { + if (GlobalManager.getInstance().getSongService().getStatus() == Status.PLAYING || GlobalManager.getInstance().getSongService().getStatus() == Status.PAUSED) { + GlobalManager.getInstance().getSongService().stop(); + } + LibraryManager.getInstance().getNextBeatmap(); + firstTimingPoint = null; + loadBeatmapInfo(); + loadTimeingPoints(true); + doChange = false; + doStop = false; + } + break; + case SYNC: { + if (GlobalManager.getInstance().getSongService().getStatus() == Status.PLAYING) { + if (lastTimingPoint != null) { + int position = GlobalManager.getInstance().getSongService().getPosition(); + offset = (position - lastTimingPoint.getTime() * 1000f) % bpmLength; + } + Debug.i("BPM: " + 60 / bpmLength * 1000 + " Offset: " + offset); + } + } + } + } + + @Override + public void onUpdate(final float pSecondsElapsed) { + beatPassTime += pSecondsElapsed * 1000f; + if (isOnExitAnim) { + for (Rectangle specRectangle : spectrum) { + specRectangle.setWidth(0); + specRectangle.setAlpha(0); + } + return; + } + + if (GlobalManager.getInstance().getSongService() == null || !musicStarted || GlobalManager.getInstance().getSongService().getStatus() == Status.STOPPED) { + bpmLength = 1000; + offset = 0; + } + + if (doMenuShow == true && isMenuShowed == false) { + logo.registerEntityModifier(new MoveXModifier(0.3f, Config.getRES_WIDTH() / 2 - logo.getWidth() / 2, Config.getRES_WIDTH() / 3 - logo.getWidth() / 2, EaseExponentialOut.getInstance())); + logoOverlay.registerEntityModifier(new MoveXModifier(0.3f, Config.getRES_WIDTH() / 2 - logo.getWidth() / 2, Config.getRES_WIDTH() / 3 - logo.getWidth() / 2, EaseExponentialOut.getInstance())); + for (int i = 0; i < spectrum.length; i++) { + spectrum[i].registerEntityModifier(new MoveXModifier(0.3f, Config.getRES_WIDTH() / 2, Config.getRES_WIDTH() / 3, EaseExponentialOut.getInstance())); + } + play.registerEntityModifier(new ParallelEntityModifier( + new MoveXModifier(0.5f, menuBarX - 100, menuBarX, EaseElasticOut.getInstance()), + new org.anddev.andengine.entity.modifier.AlphaModifier(0.5f, 0, 0.9f, EaseCubicOut.getInstance()))); + options.registerEntityModifier(new ParallelEntityModifier( + new MoveXModifier(0.5f, menuBarX - 100, menuBarX, EaseElasticOut.getInstance()), + new org.anddev.andengine.entity.modifier.AlphaModifier(0.5f, 0, 0.9f, EaseCubicOut.getInstance()))); + exit.registerEntityModifier(new ParallelEntityModifier( + new MoveXModifier(0.5f, menuBarX - 100, menuBarX, EaseElasticOut.getInstance()), + new org.anddev.andengine.entity.modifier.AlphaModifier(0.5f, 0, 0.9f, EaseCubicOut.getInstance()))); + scene.registerTouchArea(play); + scene.registerTouchArea(options); + scene.registerTouchArea(exit); + isMenuShowed = true; + } + + if (doMenuShow == true && isMenuShowed == true) { + if (showPassTime > 10000f) { + scene.unregisterTouchArea(play); + scene.unregisterTouchArea(options); + scene.unregisterTouchArea(exit); + play.registerEntityModifier(new ParallelEntityModifier( + new MoveXModifier(1f, menuBarX, menuBarX - 50, EaseExponentialOut.getInstance()), + new org.anddev.andengine.entity.modifier.AlphaModifier(1f, 0.9f, 0, EaseExponentialOut.getInstance()))); + options.registerEntityModifier(new ParallelEntityModifier( + new MoveXModifier(1f, menuBarX, menuBarX - 50, EaseExponentialOut.getInstance()), + new org.anddev.andengine.entity.modifier.AlphaModifier(1f, 0.9f, 0, EaseExponentialOut.getInstance()))); + exit.registerEntityModifier(new ParallelEntityModifier( + new MoveXModifier(1f, menuBarX, menuBarX - 50, EaseExponentialOut.getInstance()), + new org.anddev.andengine.entity.modifier.AlphaModifier(1f, 0.9f, 0, EaseExponentialOut.getInstance()))); + logo.registerEntityModifier(new MoveXModifier(1f, Config.getRES_WIDTH() / 3 - logo.getWidth() / 2, Config.getRES_WIDTH() / 2 - logo.getWidth() / 2, + EaseBounceOut.getInstance())); + logoOverlay.registerEntityModifier(new MoveXModifier(1f, Config.getRES_WIDTH() / 3 - logo.getWidth() / 2, Config.getRES_WIDTH() / 2 - logo.getWidth() / 2, + EaseBounceOut.getInstance())); + for (int i = 0; i < spectrum.length; i++) { + spectrum[i].registerEntityModifier(new MoveXModifier(1f, Config.getRES_WIDTH() / 3, Config.getRES_WIDTH() / 2, EaseBounceOut.getInstance())); + } + isMenuShowed = false; + doMenuShow = false; + showPassTime = 0; + } else { + showPassTime += pSecondsElapsed * 1000f; + } + } + +// if (offset != 0) { +// beatPassTime += offset; +// offset = 0; +// } + + if (beatPassTime - lastBeatPassTime >= bpmLength - offset) { + lastBeatPassTime = beatPassTime; + offset = 0; + if (logo != null) { +// logo.clearEntityModifiers(); + logo.registerEntityModifier(new SequenceEntityModifier(new org.anddev.andengine.entity.modifier.ScaleModifier(bpmLength / 1000 * 0.9f, 1f, 1.07f), + new org.anddev.andengine.entity.modifier.ScaleModifier(bpmLength / 1000 * 0.07f, 1.07f, 1f))); + } + } + + if (GlobalManager.getInstance().getSongService() != null) { + if (!musicStarted) { + if (firstTimingPoint != null) { + bpmLength = firstTimingPoint.getBeatLength() * 1000f; + } else { + return; + } + progressBar.setStartTime(0); + GlobalManager.getInstance().getSongService().play(); + if (lastTimingPoint != null) { + offset = lastTimingPoint.getTime() * 1000f % bpmLength; + } + Debug.i("BPM: " + 60 / bpmLength * 1000 + " Offset: " + offset); +// ToastLogger.showText("BPM: " + 60 / bpmLength * 1000 + " Offset: " + offset, false); + musicStarted = true; + } + + if (GlobalManager.getInstance().getSongService().getStatus() == Status.PLAYING) { +// syncPassedTime += pSecondsElapsed * 1000f; + int position = GlobalManager.getInstance().getSongService().getPosition(); + progressBar.setTime(GlobalManager.getInstance().getSongService().getLength()); + progressBar.setPassedTime(position); + progressBar.update(pSecondsElapsed * 1000); + +// if (syncPassedTime > bpmLength * 8) { +// musicControl(MusicOption.SYNC); +// syncPassedTime = 0; +// } + + if (currentTimingPoint != null && position > currentTimingPoint.getTime() * 1000) { + if (!isContinuousKiai && currentTimingPoint.isKiai()) { + for (ParticleSystem particleSpout : particleSystem) { + particleSpout.setParticlesSpawnEnabled(true); + } + particleBeginTime = position; + particleEnabled = true; + } + isContinuousKiai = currentTimingPoint.isKiai(); + + if (timingPoints.size() > 0) { + currentTimingPoint = timingPoints.remove(0); + if (!currentTimingPoint.wasInderited()) { + lastTimingPoint = currentTimingPoint; + bpmLength = currentTimingPoint.getBeatLength() * 1000; + offset = lastTimingPoint.getTime() * 1000f % bpmLength; + Debug.i("BPM: " + 60 / bpmLength * 1000 + " Offset: " + offset); +// ToastLogger.showText("BPM: " + 60 / bpmLength * 1000 + " Offset: " + offset, false); + } + } else { + currentTimingPoint = null; + } + } + + if (particleEnabled && (position - particleBeginTime > 2000)) { + for (ParticleSystem particleSpout : particleSystem) { + particleSpout.setParticlesSpawnEnabled(false); + } + particleEnabled = false; + } + + int windowSize = 240; + int spectrumWidth = 120; + float[] fft = GlobalManager.getInstance().getSongService().getSpectrum(); + if (fft == null) return; + for (int i = 0, leftBound = 0; i < spectrumWidth; i++) { + float peak = 0; + int rightBound = (int) Math.pow(2., i * 9. / (windowSize - 1)); + if (rightBound <= leftBound) rightBound = leftBound + 1; + if (rightBound > 511) rightBound = 511; + + for (; leftBound < rightBound; leftBound++) { + if (peak < fft[1 + leftBound]) + peak = fft[1 + leftBound]; + } + + float initialAlpha = 0.4f; + float gradient = 20; + float currPeakLevel = peak * 500; + + if (currPeakLevel > peakLevel[i]) { + peakLevel[i] = currPeakLevel; + peakDownRate[i] = peakLevel[i] / gradient; + peakAlpha[i] = initialAlpha; + + } else { + peakLevel[i] = Math.max(peakLevel[i] - peakDownRate[i], 0f); + peakAlpha[i] = Math.max(peakAlpha[i] - initialAlpha / gradient, 0f); + } + + spectrum[i].setWidth(250f + peakLevel[i]); + spectrum[i].setAlpha(peakAlpha[i]); + } + } else { + for (Rectangle specRectangle : spectrum) { + specRectangle.setWidth(0); + specRectangle.setAlpha(0); + } + if (!doChange && !doStop && GlobalManager.getInstance().getSongService() != null && GlobalManager.getInstance().getSongService().getPosition() >= GlobalManager.getInstance().getSongService().getLength()) { + musicControl(MusicOption.NEXT); + } + } + } + } + + @Override + public void reset() { + + } + + public void loadBeatmap() { + LibraryManager.getInstance().shuffleLibrary(); + loadBeatmapInfo(); + loadTimeingPoints(true); + } + + public void loadBeatmapInfo() { + if (LibraryManager.getInstance().getSizeOfBeatmaps() != 0) { + beatmapInfo = LibraryManager.getInstance().getBeatmap(); + Log.w("MainMenuActivity", "Next song: " + beatmapInfo.getMusic() + ", Start at: " + beatmapInfo.getPreviewTime()); + + if (musicInfoText == null) { + musicInfoText = new ChangeableText(Utils.toRes(Config.getRES_WIDTH() - 500), Utils.toRes(3), + ResourceManager.getInstance().getFont("font"), "None...", HorizontalAlign.RIGHT, 35); + } + if (beatmapInfo.getArtistUnicode() != null && beatmapInfo.getTitleUnicode() != null && Config.isForceRomanized() == false) { + musicInfoText.setText(beatmapInfo.getArtistUnicode() + " - " + beatmapInfo.getTitleUnicode(), true); + } else if (beatmapInfo.getArtist() != null && beatmapInfo.getTitle() != null) { + musicInfoText.setText(beatmapInfo.getArtist() + " - " + beatmapInfo.getTitle(), true); + } else { + musicInfoText.setText("Failure to load QAQ", true); + } + try { + musicInfoText.setPosition(Utils.toRes(Config.getRES_WIDTH() - 500 + 470 - musicInfoText.getWidth()), musicInfoText.getY()); + music_nowplay.setPosition(Utils.toRes(Config.getRES_WIDTH() - 500 + 470 - musicInfoText.getWidth() - 130), 0); + } catch (NullPointerException e) { + musicInfoText.setPosition(Utils.toRes(Config.getRES_WIDTH() - 500 + 470 - 200), 5); + music_nowplay.setPosition(Utils.toRes(Config.getRES_WIDTH() - 500 + 470 - 200 - 130), 0); + } + } + } + + public void loadTimeingPoints(boolean reloadMusic) { + if (beatmapInfo == null) { + return; + } + + for (ParticleSystem particleSpout : particleSystem) { + particleSpout.setParticlesSpawnEnabled(false); + } + particleEnabled = false; + + ArrayList trackInfos = beatmapInfo.getTracks(); + if (trackInfos != null && trackInfos.size() > 0) { + int trackIndex = random.nextInt(trackInfos.size()); + selectedTrack = trackInfos.get(trackIndex); + + if (selectedTrack.getBackground() != null) { + try { + final TextureRegion tex = Config.isSafeBeatmapBg() ? + ResourceManager.getInstance().getTexture("menu-background") : + ResourceManager.getInstance().loadBackground(selectedTrack.getBackground()); + + if (tex != null) { + float height = tex.getHeight(); + height *= Config.getRES_WIDTH() + / (float) tex.getWidth(); + background = new Sprite(0, + (Config.getRES_HEIGHT() - height) / 2, Config + .getRES_WIDTH(), height, tex); + lastBackground.registerEntityModifier(new org.anddev.andengine.entity.modifier.AlphaModifier(1.5f, 1, 0, new IEntityModifier.IEntityModifierListener() { + @Override + public void onModifierStarted(IModifier pModifier, IEntity pItem) { + scene.attachChild(background, 0); + } + + @Override + public void onModifierFinished(IModifier pModifier, final IEntity pItem) { + GlobalManager.getInstance().getMainActivity().runOnUpdateThread(new Runnable() { + @Override + public void run() { + // TODO Auto-generated method stub + pItem.detachSelf(); + } + }); + } + })); + lastBackground = background; + } + } catch (Exception e) { + Debug.e(e.toString()); + lastBackground.setAlpha(0); + } + } else { + lastBackground.setAlpha(0); + } + + if (reloadMusic) { + if (GlobalManager.getInstance().getSongService() != null) { + GlobalManager.getInstance().getSongService().preLoad(beatmapInfo.getMusic()); + musicStarted = false; + } else { + Log.w("nullpoint", "GlobalManager.getInstance().getSongService() is null while reload music (MainScene.loadTimeingPoints)"); + } + } + + Arrays.fill(peakLevel, 0f); + Arrays.fill(peakDownRate, 1f); + Arrays.fill(peakAlpha, 0f); + + OSUParser parser = new OSUParser(selectedTrack.getFilename()); + if (parser.openFile()) { + beatmapData = parser.readData(); + + timingPoints = new LinkedList(); + currentTimingPoint = null; + for (final String s : beatmapData.getData("TimingPoints")) { + final TimingPoint tp = new TimingPoint(s.split("[,]"), currentTimingPoint); + timingPoints.add(tp); + if (tp.wasInderited() == false || currentTimingPoint == null) { + currentTimingPoint = tp; + } + } + firstTimingPoint = timingPoints.remove(0); + currentTimingPoint = firstTimingPoint; + lastTimingPoint = currentTimingPoint; + bpmLength = firstTimingPoint.getBeatLength() * 1000f; + } + } + } + + public void showExitDialog() { + GlobalManager.getInstance().getMainActivity().runOnUiThread(new Runnable() { + public void run() { + new ConfirmDialogFragment().setMessage(R.string.dialog_exit_message).showForResult( + isAccepted -> { + if (isAccepted) { + exit(); + } + } + ); + } + }); + } + + public void exit() { + if (isOnExitAnim) { + return; + } + isOnExitAnim = true; + + PowerManager.WakeLock wakeLock = GlobalManager.getInstance().getMainActivity().getWakeLock(); + if (wakeLock != null && wakeLock.isHeld()) { + wakeLock.release(); + } + + scene.unregisterTouchArea(play); + scene.unregisterTouchArea(options); + scene.unregisterTouchArea(exit); + + play.setAlpha(0); + options.setAlpha(0); + exit.setAlpha(0); + + //ResourceManager.getInstance().loadSound("seeya", "sfx/seeya.wav", false).play(); + //Allow customize Seeya Sounds from Skins + BassSoundProvider exitsound = ResourceManager.getInstance().getSound("seeya"); + if (exitsound != null) { + exitsound.play(); + } + + Rectangle bg = new Rectangle(0, 0, Config.getRES_WIDTH(), + Config.getRES_HEIGHT()); + bg.setColor(0, 0, 0, 1.0f); + bg.registerEntityModifier(ModifierFactory.newAlphaModifier(3.0f, 0, 1)); + scene.attachChild(bg); + logo.registerEntityModifier(new ParallelEntityModifier( + new RotationModifier(3.0f, 0, -15), + ModifierFactory.newScaleModifier(3.0f, 1f, 0.8f) + )); + logoOverlay.registerEntityModifier(new ParallelEntityModifier( + new RotationModifier(3.0f, 0, -15), + ModifierFactory.newScaleModifier(3.0f, 1f, 0.8f) + )); + + ScheduledExecutorService taskPool = Executors.newScheduledThreadPool(1); + taskPool.schedule(new TimerTask() { + @Override + public void run() { + if (GlobalManager.getInstance().getSongService() != null) { + GlobalManager.getInstance().getSongService().hideNotifyPanel(); + if (Build.VERSION.SDK_INT > 10) + GlobalManager.getInstance().getMainActivity().unregisterReceiver(GlobalManager.getInstance().getMainActivity().onNotifyButtonClick); + GlobalManager.getInstance().getMainActivity().unbindService(GlobalManager.getInstance().getMainActivity().connection); + GlobalManager.getInstance().getMainActivity().stopService(new Intent(GlobalManager.getInstance().getMainActivity(), SongService.class)); + musicStarted = false; + } + android.os.Process.killProcess(android.os.Process.myPid()); + } + }, 3000, TimeUnit.MILLISECONDS); + } + + public Scene getScene() { + return scene; + } + + public BeatmapInfo getBeatmapInfo() { + return beatmapInfo; + } + + public void setBeatmap(BeatmapInfo info) { + int playIndex = LibraryManager.getInstance().findBeatmap(info); + Debug.i("index " + playIndex); + loadBeatmapInfo(); + loadTimeingPoints(false); + musicControl(MusicOption.SYNC); + } + + public void watchReplay(String replayFile) { + replay = new Replay(); + if (replay.loadInfo(replayFile)) { + if (replay.replayVersion >= 3) { + //replay + ScoringScene scorescene = GlobalManager.getInstance().getScoring(); + StatisticV2 stat = replay.getStat(); + TrackInfo track = LibraryManager.getInstance().findTrackByFileNameAndMD5(replay.getMapfile(), replay.getMd5()); + if (track != null) { + GlobalManager.getInstance().getMainScene().setBeatmap(track.getBeatmap()); + GlobalManager.getInstance().getSongMenu().select(); + ResourceManager.getInstance().loadBackground(track.getBackground()); + GlobalManager.getInstance().getSongService().preLoad(track.getBeatmap().getMusic()); + GlobalManager.getInstance().getSongService().play(); + scorescene.load(stat, null, ru.nsu.ccfit.zuev.osu.GlobalManager.getInstance().getSongService(), replayFile, null, track); + GlobalManager.getInstance().getEngine().setScene(scorescene.getScene()); + } + } + } + } + + public void show() { + GlobalManager.getInstance().getSongService().setGaming(false); + GlobalManager.getInstance().getEngine().setScene(getScene()); + if (GlobalManager.getInstance().getSelectedTrack() != null) { + setBeatmap(GlobalManager.getInstance().getSelectedTrack().getBeatmap()); + } + } + + public enum MusicOption {PREV, PLAY, PAUSE, STOP, NEXT, SYNC} } diff --git a/src/ru/nsu/ccfit/zuev/osu/OSUParser.java b/src/ru/nsu/ccfit/zuev/osu/OSUParser.java index 24db5e9f..d21c8589 100644 --- a/src/ru/nsu/ccfit/zuev/osu/OSUParser.java +++ b/src/ru/nsu/ccfit/zuev/osu/OSUParser.java @@ -31,520 +31,520 @@ import test.tpdifficulty.tp.AiModtpDifficulty; public class OSUParser { - private final File file; - private BufferedSource source; - private boolean fileOpened = false; - private final ArrayList timingPoints = new ArrayList<>(); - private final ArrayList hitObjects = new ArrayList<>(); - private TimingPoint currentTimingPoint = null; - private BeatmapData data; - private float sliderSpeed; - private float sliderTick; - - public OSUParser(final File file) { - this.file = file; - } - - public OSUParser(final String path) { - file = new File(path); - } - - public boolean openFile() { - try { - source = Okio.buffer(Okio.source(file)); - } catch (final IOException e) { - Debug.e("OSUParser.openFile: " + e.getMessage(), e); - return false; - } - - try { - String head = source.readUtf8Line(); - Pattern pattern = Pattern.compile("osu file format v(\\d+)"); - Matcher matcher = pattern.matcher(head); - if (!matcher.find()) { - source.close(); - source = null; - return false; - } - } catch (IOException e) { - Debug.e("OSUParser.openFile: " + e.getMessage(), e); - } catch (Exception e) { - Debug.e("OSUParser.openFile: " + e.getMessage(), e); - } - - fileOpened = true; - return true; - } - - public boolean readMetaData(final TrackInfo track, final BeatmapInfo info) { - data = readData(); - - if (!data.getData("General", "Mode").equals("0") - && !data.getData("General", "Mode").equals("")) { - return false; - } - - for (BeatmapSection section : BeatmapSection.values()) { - if (!loadMetadata(track, info, section)) { - return false; - } - } - - // Calculate beatmap difficulty - try { - AiModtpDifficulty tpDifficulty = new AiModtpDifficulty(); - tpDifficulty.CalculateAll(this.hitObjects, track.getCircleSize()); - track.setDifficulty(GameHelper.Round(tpDifficulty.getStarRating(), 2)); - } catch (Exception e) { - Debug.e("Beatmap <" + info.getPath() + "> has bad parameter, so give it up"); - return false; - } - - // Debug.i("MaxCombo: " + track.getMaxCombo()); - // Debug.i("Caching " + track.getFilename()); - - return true; - } - - public int getMaxCombo() { - int combo = 0; - for (HitObject obj : hitObjects) { - combo += obj.getCombo(sliderTick, sliderSpeed); - } - return combo; - } - - public float tryParseFloat(String str, float defaultVal) { - float val; - try { - val = Float.parseFloat(str); - } catch (NumberFormatException ignored) { - val = defaultVal; - } - return val; - } - - public int tryParseInt(String str, int defaultVal) { - int val; - try { - val = Integer.parseInt(str); - } catch (NumberFormatException ignored) { - val = defaultVal; - } - return val; - } - - public BeatmapData readData() { - if (!fileOpened) { - return null; - } - fileOpened = false; - final BeatmapData data = new BeatmapData(); - - String previousSection; - String currentSection = null; - - // Events, TimingPoints, and HitObjects sections' data are stored in an instance - // of ArrayList, while others are stored in an instance of HashMap - final Map map = new HashMap<>(); - final ArrayList list = new ArrayList<>(); - - try { - while (true) { - String s = source.readUtf8Line(); - - // If s is null, it means we've reached the end of the file. - // End the loop and don't forget to add the last section, - // which would otherwise be ignored - if (s == null) { - if (currentSection != null) { - switch (currentSection) { - case "Events": - case "TimingPoints": - case "HitObjects": - data.addSection(currentSection, list); - break; - default: - data.addSection(currentSection, map); - } - } - source.close(); - break; - } - - // Handle space comments - if (s.startsWith(" ") || s.startsWith("_")) { - continue; - } - - // Now that we've handled space comments, we can trim space - s = s.trim(); - - // Handle C++ style comments and empty lines - if (s.startsWith("//") || s.isEmpty()) { - continue; - } - - // [SectionName] - if (s.startsWith("[")) { - // Record the current section before loading the new section. - // This is necessary so that we don't enter an empty data - // if we've just entered the first section (previousSection will - // be null) - previousSection = currentSection; - currentSection = s.substring(1, s.length() - 1); - - if (previousSection == null) { - continue; - } - - // Enter a deep copy of the original data holder so that - // we can use the original for the next section - switch (previousSection) { - case "Events": - case "TimingPoints": - case "HitObjects": - data.addSection(previousSection, new ArrayList<>(list)); - list.clear(); - break; - default: - data.addSection(previousSection, new HashMap<>(map)); - map.clear(); - } - continue; - } - - // If we're still not in a section yet, there is no need - // to start parsing data, just continue to the next line - if (currentSection == null) { - continue; - } - - // Collect and parse data depending on section - switch (currentSection) { - case "Events": - case "TimingPoints": - case "HitObjects": - list.add(s); - break; - default: - final String[] pair = s.split("\\s*:\\s*", 2); - if (pair.length > 1) { - map.put(pair[0], pair[1]); - } - } - } - } catch (IOException e) { - Debug.e("OSUParser.readData: " + e.getMessage(), e); - return data; - } - - data.setFolder(file.getParent()); - - return data; - } - - private enum BeatmapSection { - GENERAL, - EDITOR, - METADATA, - DIFFICULTY, - EVENTS, - TIMINGPOINTS, - HITOBJECTS - } - - private boolean loadMetadata(final TrackInfo track, final BeatmapInfo info, final BeatmapSection section) { - switch (section) { - case GENERAL: - return loadGeneralSection(info); - case METADATA: - return loadMetadataSection(track, info); - case DIFFICULTY: - return loadDifficultySection(track); - case EVENTS: - return loadEventsSection(track); - case TIMINGPOINTS: - return loadTimingPointsSection(track); - case HITOBJECTS: - return loadHitObjectsSection(track); - default: - return true; - } - } - - private boolean loadGeneralSection(final BeatmapInfo info) { - if (info.getTitle() == null) { - info.setTitle(data.getData("Metadata", "Title")); - } - if (info.getTitleUnicode() == null) { - String titleUnicode = data.getData("Metadata", "TitleUnicode"); - if (titleUnicode != null && titleUnicode.length() > 0) { - info.setTitleUnicode(titleUnicode); - } - } - if (info.getArtist() == null) { - info.setArtist(data.getData("Metadata", "Artist")); - } - if (info.getArtistUnicode() == null) { - String artistUnicode = data.getData("Metadata", "ArtistUnicode"); - if (artistUnicode != null && artistUnicode.length() > 0) { - info.setArtistUnicode(artistUnicode); - } - } - if (info.getSource() == null) { - info.setSource(data.getData("Metadata", "Source")); - } - if (info.getTags() == null) { - info.setTags(data.getData("Metadata", "Tags")); - } - - if (info.getMusic() == null) { - final File musicFile = new File(info.getPath(), data.getData( - "General", "AudioFilename")); - if (!musicFile.exists()) { - ToastLogger.showText(StringTable.format(R.string.osu_parser_music_not_found, - file.getName().substring(0, file.getName().length() - 4)), true); - return false; - } - info.setMusic(musicFile.getPath()); - final String prevTime = data.getData("General", "PreviewTime"); - try { - info.setPreviewTime(Integer.parseInt(prevTime)); - } catch (final NumberFormatException e) { - Debug.e("Cannot parse preview time"); - info.setPreviewTime(-1); - } - } - - return true; - } - - private boolean loadMetadataSection(final TrackInfo track, final BeatmapInfo info) { - track.setCreator(data.getData("Metadata", "Creator")); - track.setMode(data.getData("Metadata", "Version")); - - track.setPublicName(info.getArtist() + " - " + info.getTitle()); - - track.setBeatmapID(tryParseInt(data.getData("Metadata", "BeatmapID"), -1)); - track.setBeatmapSetID(tryParseInt(data.getData("Metadata", "BeatmapSetID"), -1)); - - return true; - } - - private boolean loadDifficultySection(final TrackInfo track) { - track.setOverallDifficulty(tryParseFloat(data.getData("Difficulty", "OverallDifficulty"), 5f)); - track.setApproachRate(tryParseFloat(data.getData("Difficulty", "ApproachRate"), track.getOverallDifficulty())); - track.setHpDrain(tryParseFloat(data.getData("Difficulty", "HPDrainRate"), 5f)); - track.setCircleSize(tryParseFloat(data.getData("Difficulty", "CircleSize"), 4f)); - - sliderTick = tryParseFloat(data.getData("Difficulty", "SliderTickRate"), 1.0f); - sliderSpeed = tryParseFloat(data.getData("Difficulty", "SliderMultiplier"), 1.0f); - - return true; - } - - private boolean loadEventsSection(final TrackInfo track) { - // We only need to load beatmap background - for (final String s : data.getData("Events")) { - final String[] pars = s.split("\\s*,\\s*"); - if (pars.length >= 3 && s.startsWith("0,0")) { - track.setBackground(pars[2].substring(1, pars[2].length() - 1)); - break; - } - } - - return true; - } - - private boolean loadTimingPointsSection(final TrackInfo track) { - timingPoints.clear(); - - // Get the first uninherited timing point - for (final String tempString : data.getData("TimingPoints")) { - String[] rawData = tempString.split("[,]"); - // Handle malformed timing point - if (rawData.length < 2) { - return false; - } - float bpm = tryParseFloat(rawData[1], Float.NaN); - if (Float.isNaN(bpm)) { - return false; - } - - // Uninherited: bpm > 0 - if (bpm > 0) { - float offset = tryParseFloat(rawData[0], Float.NaN); - if (Float.isNaN(offset)) { - return false; - } - currentTimingPoint = new TimingPoint(bpm, offset, 1f); - break; - } - } - - if (currentTimingPoint == null) { - ToastLogger.showText(StringTable.format(R.string.osu_parser_timing_error, - file.getName().substring(0, file.getName().length() - 4)), true); - return false; - } - - for (final String tempString : data.getData("TimingPoints")) { - String[] rawData = tempString.split("[,]"); - // Handle malformed timing point - if (rawData.length < 2) { - return false; - } - float offset = tryParseFloat(rawData[0], Float.NaN); - float bpm = tryParseFloat(rawData[1], Float.NaN); - if (Float.isNaN(offset) || Float.isNaN(bpm)) { - return false; - } - float speed = 1.0f; - boolean inherited = bpm < 0; - - if (inherited) { - speed = -100.0f / bpm; - bpm = currentTimingPoint.getBpm(); - } else { - bpm = 60000.0f / bpm; - } - TimingPoint timing = new TimingPoint(bpm, offset, speed); - if (!inherited) { - currentTimingPoint = timing; - } - try { - bpm = GameHelper.Round(bpm, 2); - } catch (NumberFormatException e) { - if (BuildConfig.DEBUG) { - e.printStackTrace(); - } - Log.e("Beatmap Error", "" + track.getMode()); - ToastLogger.showText(StringTable.get(R.string.osu_parser_error) + " " + track.getMode(), true); - return false; - } - track.setBpmMin(track.getBpmMin() != Float.MAX_VALUE ? Math.min(track.getBpmMin(), bpm) : bpm); - track.setBpmMax(track.getBpmMax() != 0 ? Math.max(track.getBpmMax(), bpm) : bpm); - timingPoints.add(timing); - } - - return timingPoints.size() > 0; - } - - private boolean loadHitObjectsSection(final TrackInfo track) { - final ArrayList hitObjects = data.getData("HitObjects"); - if (hitObjects.size() <= 0) { - return false; - } - - track.setTotalHitObjectCount(hitObjects.size()); - - this.hitObjects.clear(); - int tpIndex = 0; - currentTimingPoint = timingPoints.get(tpIndex); - - for (final String tempString : hitObjects) { - String[] hitObjectData = tempString.split("[,]"); - String[] rawData; - - // Ignoring v10 features - int dataSize = hitObjectData.length; - while (dataSize > 0 && hitObjectData[dataSize - 1].matches("([0-9][:][0-9][|]?)+")) { - dataSize--; - } - if (dataSize < hitObjectData.length) { - rawData = new String[dataSize]; - for (int i = 0; i < rawData.length; i++) { - rawData[i] = hitObjectData[i]; - } - } else { - rawData = hitObjectData; - } - - // Handle malformed hitobject - if (rawData.length < 4) { - return false; - } - - int time = tryParseInt(rawData[2], -1); - if (time <= -1) { - return false; - } - while (tpIndex < timingPoints.size() - 1 && timingPoints.get(tpIndex + 1).getOffset() <= time) { - tpIndex++; - } - currentTimingPoint = timingPoints.get(tpIndex); - HitObjectType hitObjectType = HitObjectType.valueOf(tryParseInt(rawData[3], -1) % 16); - PointF pos = new PointF( - tryParseFloat(rawData[0], Float.NaN), - tryParseFloat(rawData[1], Float.NaN) - ); - if (Float.isNaN(pos.x) || Float.isNaN(pos.y)) { - return false; - } - HitObject object = null; - if (hitObjectType == null) { - System.out.println(tempString); - return false; - } - - if (hitObjectType == HitObjectType.Normal || hitObjectType == HitObjectType.NormalNewCombo) { - // HitCircle - object = new HitCircle(time, pos, currentTimingPoint); - track.setHitCircleCount(track.getHitCircleCount() + 1); - } else if (hitObjectType == HitObjectType.Spinner) { - // Spinner - int endTime = tryParseInt(rawData[5], -1); - if (endTime <= -1) { - return false; - } - object = new Spinner(time, endTime, pos, currentTimingPoint); - track.setSpinnerCount(track.getSpinnerCount() + 1); - } else if (hitObjectType == HitObjectType.Slider || hitObjectType == HitObjectType.SliderNewCombo) { - // Slider - // Handle malformed slider - boolean isValidSlider = rawData.length >= 8; - if (!isValidSlider) { - return false; - } - - String[] curvePointsData = rawData[5].split("[|]"); - SliderType sliderType = SliderType.parse(curvePointsData[0].charAt(0)); - ArrayList curvePoints = new ArrayList<>(); - for (int i = 1; i < curvePointsData.length; i++) { - String[] curvePointData = curvePointsData[i].split("[:]"); - PointF curvePointPosition = new PointF( - tryParseFloat(curvePointData[0], Float.NaN), - tryParseFloat(curvePointData[1], Float.NaN) - ); - - if (Float.isNaN(curvePointPosition.x) || Float.isNaN(curvePointPosition.y)) { - isValidSlider = false; - break; - } - curvePoints.add(curvePointPosition); - } - if (!isValidSlider) { - return false; - } - - int repeat = tryParseInt(rawData[6], -1); - float rawLength = tryParseFloat(rawData[7], Float.NaN); - if (repeat <= -1 || Float.isNaN(rawLength)) { - continue; - } - - int endTime = time + (int) (rawLength * (600 / timingPoints.get(0).getBpm()) / sliderSpeed) * repeat; - object = new Slider(time, endTime, pos, currentTimingPoint, sliderType, repeat, curvePoints, rawLength); - track.setSliderCount(track.getSliderCount() + 1); - } - this.hitObjects.add(object); - } - - int length = (int) tryParseFloat(new GameObjectData(hitObjects.get(hitObjects.size() - 1)).getData()[2], 0); - track.setMusicLength(length); - track.setMaxCombo(getMaxCombo()); - - return this.hitObjects.size() > 0; - } + private final File file; + private BufferedSource source; + private boolean fileOpened = false; + private final ArrayList timingPoints = new ArrayList<>(); + private final ArrayList hitObjects = new ArrayList<>(); + private TimingPoint currentTimingPoint = null; + private BeatmapData data; + private float sliderSpeed; + private float sliderTick; + + public OSUParser(final File file) { + this.file = file; + } + + public OSUParser(final String path) { + file = new File(path); + } + + public boolean openFile() { + try { + source = Okio.buffer(Okio.source(file)); + } catch (final IOException e) { + Debug.e("OSUParser.openFile: " + e.getMessage(), e); + return false; + } + + try { + String head = source.readUtf8Line(); + Pattern pattern = Pattern.compile("osu file format v(\\d+)"); + Matcher matcher = pattern.matcher(head); + if (!matcher.find()) { + source.close(); + source = null; + return false; + } + } catch (IOException e) { + Debug.e("OSUParser.openFile: " + e.getMessage(), e); + } catch (Exception e) { + Debug.e("OSUParser.openFile: " + e.getMessage(), e); + } + + fileOpened = true; + return true; + } + + public boolean readMetaData(final TrackInfo track, final BeatmapInfo info) { + data = readData(); + + if (!data.getData("General", "Mode").equals("0") + && !data.getData("General", "Mode").equals("")) { + return false; + } + + for (BeatmapSection section : BeatmapSection.values()) { + if (!loadMetadata(track, info, section)) { + return false; + } + } + + // Calculate beatmap difficulty + try { + AiModtpDifficulty tpDifficulty = new AiModtpDifficulty(); + tpDifficulty.CalculateAll(this.hitObjects, track.getCircleSize()); + track.setDifficulty(GameHelper.Round(tpDifficulty.getStarRating(), 2)); + } catch (Exception e) { + Debug.e("Beatmap <" + info.getPath() + "> has bad parameter, so give it up"); + return false; + } + + // Debug.i("MaxCombo: " + track.getMaxCombo()); + // Debug.i("Caching " + track.getFilename()); + + return true; + } + + public int getMaxCombo() { + int combo = 0; + for (HitObject obj : hitObjects) { + combo += obj.getCombo(sliderTick, sliderSpeed); + } + return combo; + } + + public float tryParseFloat(String str, float defaultVal) { + float val; + try { + val = Float.parseFloat(str); + } catch (NumberFormatException ignored) { + val = defaultVal; + } + return val; + } + + public int tryParseInt(String str, int defaultVal) { + int val; + try { + val = Integer.parseInt(str); + } catch (NumberFormatException ignored) { + val = defaultVal; + } + return val; + } + + public BeatmapData readData() { + if (!fileOpened) { + return null; + } + fileOpened = false; + final BeatmapData data = new BeatmapData(); + + String previousSection; + String currentSection = null; + + // Events, TimingPoints, and HitObjects sections' data are stored in an instance + // of ArrayList, while others are stored in an instance of HashMap + final Map map = new HashMap<>(); + final ArrayList list = new ArrayList<>(); + + try { + while (true) { + String s = source.readUtf8Line(); + + // If s is null, it means we've reached the end of the file. + // End the loop and don't forget to add the last section, + // which would otherwise be ignored + if (s == null) { + if (currentSection != null) { + switch (currentSection) { + case "Events": + case "TimingPoints": + case "HitObjects": + data.addSection(currentSection, list); + break; + default: + data.addSection(currentSection, map); + } + } + source.close(); + break; + } + + // Handle space comments + if (s.startsWith(" ") || s.startsWith("_")) { + continue; + } + + // Now that we've handled space comments, we can trim space + s = s.trim(); + + // Handle C++ style comments and empty lines + if (s.startsWith("//") || s.isEmpty()) { + continue; + } + + // [SectionName] + if (s.startsWith("[")) { + // Record the current section before loading the new section. + // This is necessary so that we don't enter an empty data + // if we've just entered the first section (previousSection will + // be null) + previousSection = currentSection; + currentSection = s.substring(1, s.length() - 1); + + if (previousSection == null) { + continue; + } + + // Enter a deep copy of the original data holder so that + // we can use the original for the next section + switch (previousSection) { + case "Events": + case "TimingPoints": + case "HitObjects": + data.addSection(previousSection, new ArrayList<>(list)); + list.clear(); + break; + default: + data.addSection(previousSection, new HashMap<>(map)); + map.clear(); + } + continue; + } + + // If we're still not in a section yet, there is no need + // to start parsing data, just continue to the next line + if (currentSection == null) { + continue; + } + + // Collect and parse data depending on section + switch (currentSection) { + case "Events": + case "TimingPoints": + case "HitObjects": + list.add(s); + break; + default: + final String[] pair = s.split("\\s*:\\s*", 2); + if (pair.length > 1) { + map.put(pair[0], pair[1]); + } + } + } + } catch (IOException e) { + Debug.e("OSUParser.readData: " + e.getMessage(), e); + return data; + } + + data.setFolder(file.getParent()); + + return data; + } + + private enum BeatmapSection { + GENERAL, + EDITOR, + METADATA, + DIFFICULTY, + EVENTS, + TIMINGPOINTS, + HITOBJECTS + } + + private boolean loadMetadata(final TrackInfo track, final BeatmapInfo info, final BeatmapSection section) { + switch (section) { + case GENERAL: + return loadGeneralSection(info); + case METADATA: + return loadMetadataSection(track, info); + case DIFFICULTY: + return loadDifficultySection(track); + case EVENTS: + return loadEventsSection(track); + case TIMINGPOINTS: + return loadTimingPointsSection(track); + case HITOBJECTS: + return loadHitObjectsSection(track); + default: + return true; + } + } + + private boolean loadGeneralSection(final BeatmapInfo info) { + if (info.getTitle() == null) { + info.setTitle(data.getData("Metadata", "Title")); + } + if (info.getTitleUnicode() == null) { + String titleUnicode = data.getData("Metadata", "TitleUnicode"); + if (titleUnicode != null && titleUnicode.length() > 0) { + info.setTitleUnicode(titleUnicode); + } + } + if (info.getArtist() == null) { + info.setArtist(data.getData("Metadata", "Artist")); + } + if (info.getArtistUnicode() == null) { + String artistUnicode = data.getData("Metadata", "ArtistUnicode"); + if (artistUnicode != null && artistUnicode.length() > 0) { + info.setArtistUnicode(artistUnicode); + } + } + if (info.getSource() == null) { + info.setSource(data.getData("Metadata", "Source")); + } + if (info.getTags() == null) { + info.setTags(data.getData("Metadata", "Tags")); + } + + if (info.getMusic() == null) { + final File musicFile = new File(info.getPath(), data.getData( + "General", "AudioFilename")); + if (!musicFile.exists()) { + ToastLogger.showText(StringTable.format(R.string.osu_parser_music_not_found, + file.getName().substring(0, file.getName().length() - 4)), true); + return false; + } + info.setMusic(musicFile.getPath()); + final String prevTime = data.getData("General", "PreviewTime"); + try { + info.setPreviewTime(Integer.parseInt(prevTime)); + } catch (final NumberFormatException e) { + Debug.e("Cannot parse preview time"); + info.setPreviewTime(-1); + } + } + + return true; + } + + private boolean loadMetadataSection(final TrackInfo track, final BeatmapInfo info) { + track.setCreator(data.getData("Metadata", "Creator")); + track.setMode(data.getData("Metadata", "Version")); + + track.setPublicName(info.getArtist() + " - " + info.getTitle()); + + track.setBeatmapID(tryParseInt(data.getData("Metadata", "BeatmapID"), -1)); + track.setBeatmapSetID(tryParseInt(data.getData("Metadata", "BeatmapSetID"), -1)); + + return true; + } + + private boolean loadDifficultySection(final TrackInfo track) { + track.setOverallDifficulty(tryParseFloat(data.getData("Difficulty", "OverallDifficulty"), 5f)); + track.setApproachRate(tryParseFloat(data.getData("Difficulty", "ApproachRate"), track.getOverallDifficulty())); + track.setHpDrain(tryParseFloat(data.getData("Difficulty", "HPDrainRate"), 5f)); + track.setCircleSize(tryParseFloat(data.getData("Difficulty", "CircleSize"), 4f)); + + sliderTick = tryParseFloat(data.getData("Difficulty", "SliderTickRate"), 1.0f); + sliderSpeed = tryParseFloat(data.getData("Difficulty", "SliderMultiplier"), 1.0f); + + return true; + } + + private boolean loadEventsSection(final TrackInfo track) { + // We only need to load beatmap background + for (final String s : data.getData("Events")) { + final String[] pars = s.split("\\s*,\\s*"); + if (pars.length >= 3 && s.startsWith("0,0")) { + track.setBackground(pars[2].substring(1, pars[2].length() - 1)); + break; + } + } + + return true; + } + + private boolean loadTimingPointsSection(final TrackInfo track) { + timingPoints.clear(); + + // Get the first uninherited timing point + for (final String tempString : data.getData("TimingPoints")) { + String[] rawData = tempString.split("[,]"); + // Handle malformed timing point + if (rawData.length < 2) { + return false; + } + float bpm = tryParseFloat(rawData[1], Float.NaN); + if (Float.isNaN(bpm)) { + return false; + } + + // Uninherited: bpm > 0 + if (bpm > 0) { + float offset = tryParseFloat(rawData[0], Float.NaN); + if (Float.isNaN(offset)) { + return false; + } + currentTimingPoint = new TimingPoint(bpm, offset, 1f); + break; + } + } + + if (currentTimingPoint == null) { + ToastLogger.showText(StringTable.format(R.string.osu_parser_timing_error, + file.getName().substring(0, file.getName().length() - 4)), true); + return false; + } + + for (final String tempString : data.getData("TimingPoints")) { + String[] rawData = tempString.split("[,]"); + // Handle malformed timing point + if (rawData.length < 2) { + return false; + } + float offset = tryParseFloat(rawData[0], Float.NaN); + float bpm = tryParseFloat(rawData[1], Float.NaN); + if (Float.isNaN(offset) || Float.isNaN(bpm)) { + return false; + } + float speed = 1.0f; + boolean inherited = bpm < 0; + + if (inherited) { + speed = -100.0f / bpm; + bpm = currentTimingPoint.getBpm(); + } else { + bpm = 60000.0f / bpm; + } + TimingPoint timing = new TimingPoint(bpm, offset, speed); + if (!inherited) { + currentTimingPoint = timing; + } + try { + bpm = GameHelper.Round(bpm, 2); + } catch (NumberFormatException e) { + if (BuildConfig.DEBUG) { + e.printStackTrace(); + } + Log.e("Beatmap Error", "" + track.getMode()); + ToastLogger.showText(StringTable.get(R.string.osu_parser_error) + " " + track.getMode(), true); + return false; + } + track.setBpmMin(track.getBpmMin() != Float.MAX_VALUE ? Math.min(track.getBpmMin(), bpm) : bpm); + track.setBpmMax(track.getBpmMax() != 0 ? Math.max(track.getBpmMax(), bpm) : bpm); + timingPoints.add(timing); + } + + return timingPoints.size() > 0; + } + + private boolean loadHitObjectsSection(final TrackInfo track) { + final ArrayList hitObjects = data.getData("HitObjects"); + if (hitObjects.size() <= 0) { + return false; + } + + track.setTotalHitObjectCount(hitObjects.size()); + + this.hitObjects.clear(); + int tpIndex = 0; + currentTimingPoint = timingPoints.get(tpIndex); + + for (final String tempString : hitObjects) { + String[] hitObjectData = tempString.split("[,]"); + String[] rawData; + + // Ignoring v10 features + int dataSize = hitObjectData.length; + while (dataSize > 0 && hitObjectData[dataSize - 1].matches("([0-9][:][0-9][|]?)+")) { + dataSize--; + } + if (dataSize < hitObjectData.length) { + rawData = new String[dataSize]; + for (int i = 0; i < rawData.length; i++) { + rawData[i] = hitObjectData[i]; + } + } else { + rawData = hitObjectData; + } + + // Handle malformed hitobject + if (rawData.length < 4) { + return false; + } + + int time = tryParseInt(rawData[2], -1); + if (time <= -1) { + return false; + } + while (tpIndex < timingPoints.size() - 1 && timingPoints.get(tpIndex + 1).getOffset() <= time) { + tpIndex++; + } + currentTimingPoint = timingPoints.get(tpIndex); + HitObjectType hitObjectType = HitObjectType.valueOf(tryParseInt(rawData[3], -1) % 16); + PointF pos = new PointF( + tryParseFloat(rawData[0], Float.NaN), + tryParseFloat(rawData[1], Float.NaN) + ); + if (Float.isNaN(pos.x) || Float.isNaN(pos.y)) { + return false; + } + HitObject object = null; + if (hitObjectType == null) { + System.out.println(tempString); + return false; + } + + if (hitObjectType == HitObjectType.Normal || hitObjectType == HitObjectType.NormalNewCombo) { + // HitCircle + object = new HitCircle(time, pos, currentTimingPoint); + track.setHitCircleCount(track.getHitCircleCount() + 1); + } else if (hitObjectType == HitObjectType.Spinner) { + // Spinner + int endTime = tryParseInt(rawData[5], -1); + if (endTime <= -1) { + return false; + } + object = new Spinner(time, endTime, pos, currentTimingPoint); + track.setSpinnerCount(track.getSpinnerCount() + 1); + } else if (hitObjectType == HitObjectType.Slider || hitObjectType == HitObjectType.SliderNewCombo) { + // Slider + // Handle malformed slider + boolean isValidSlider = rawData.length >= 8; + if (!isValidSlider) { + return false; + } + + String[] curvePointsData = rawData[5].split("[|]"); + SliderType sliderType = SliderType.parse(curvePointsData[0].charAt(0)); + ArrayList curvePoints = new ArrayList<>(); + for (int i = 1; i < curvePointsData.length; i++) { + String[] curvePointData = curvePointsData[i].split("[:]"); + PointF curvePointPosition = new PointF( + tryParseFloat(curvePointData[0], Float.NaN), + tryParseFloat(curvePointData[1], Float.NaN) + ); + + if (Float.isNaN(curvePointPosition.x) || Float.isNaN(curvePointPosition.y)) { + isValidSlider = false; + break; + } + curvePoints.add(curvePointPosition); + } + if (!isValidSlider) { + return false; + } + + int repeat = tryParseInt(rawData[6], -1); + float rawLength = tryParseFloat(rawData[7], Float.NaN); + if (repeat <= -1 || Float.isNaN(rawLength)) { + continue; + } + + int endTime = time + (int) (rawLength * (600 / timingPoints.get(0).getBpm()) / sliderSpeed) * repeat; + object = new Slider(time, endTime, pos, currentTimingPoint, sliderType, repeat, curvePoints, rawLength); + track.setSliderCount(track.getSliderCount() + 1); + } + this.hitObjects.add(object); + } + + int length = (int) tryParseFloat(new GameObjectData(hitObjects.get(hitObjects.size() - 1)).getData()[2], 0); + track.setMusicLength(length); + track.setMaxCombo(getMaxCombo()); + + return this.hitObjects.size() > 0; + } } diff --git a/src/ru/nsu/ccfit/zuev/osu/OSZParser.java b/src/ru/nsu/ccfit/zuev/osu/OSZParser.java index 81f41316..779ac6b8 100644 --- a/src/ru/nsu/ccfit/zuev/osu/OSZParser.java +++ b/src/ru/nsu/ccfit/zuev/osu/OSZParser.java @@ -19,73 +19,73 @@ * directory; **/ public class OSZParser { - private OSZParser() { - } + private OSZParser() { + } - /** - * Parse an *.osz file. Location of decompressed files depends of settings - * and storage availability. - */ - public static boolean parseOSZ(final Activity activity, - final String filename) { - final File osz = new File(filename); + /** + * Parse an *.osz file. Location of decompressed files depends of settings + * and storage availability. + */ + public static boolean parseOSZ(final Activity activity, + final String filename) { + final File osz = new File(filename); - // Checking if we can use SD card for storage - if (!canUseSD()) { - return false; - } + // Checking if we can use SD card for storage + if (!canUseSD()) { + return false; + } - ToastLogger.addToLog("Importing " + filename); - // Getting file name without extention ^_^ - String folderName = osz.getName(); - folderName = folderName.substring(0, folderName.length() - 4); - final File folderFile = new File(Config.getBeatmapPath() + folderName); - if(!folderFile.exists()) { - folderFile.mkdirs(); - } + ToastLogger.addToLog("Importing " + filename); + // Getting file name without extention ^_^ + String folderName = osz.getName(); + folderName = folderName.substring(0, folderName.length() - 4); + final File folderFile = new File(Config.getBeatmapPath() + folderName); + if(!folderFile.exists()) { + folderFile.mkdirs(); + } - try { - new ZipFile(osz).extractAll(folderFile.getAbsolutePath()); - // Adding to library - LibraryManager.getInstance().addBeatmap( - new File(Config.getBeatmapPath() + folderName), null); - } catch (final ZipException e) { - Debug.e("OSZParser.ParseOSZ: " + e.getMessage(), e); - return false; - } catch (final Exception e) { - ToastLogger.showText( - StringTable.format(R.string.message_error, e.getMessage()), - false); - Debug.e("OSZParser.ParseOSZ: ", e); - osz.renameTo(new File(osz.getParentFile(), osz.getName() + ".badosz")); - LibraryManager.getInstance().deleteDir(folderFile); - return false; - } + try { + new ZipFile(osz).extractAll(folderFile.getAbsolutePath()); + // Adding to library + LibraryManager.getInstance().addBeatmap( + new File(Config.getBeatmapPath() + folderName), null); + } catch (final ZipException e) { + Debug.e("OSZParser.ParseOSZ: " + e.getMessage(), e); + return false; + } catch (final Exception e) { + ToastLogger.showText( + StringTable.format(R.string.message_error, e.getMessage()), + false); + Debug.e("OSZParser.ParseOSZ: ", e); + osz.renameTo(new File(osz.getParentFile(), osz.getName() + ".badosz")); + LibraryManager.getInstance().deleteDir(folderFile); + return false; + } - // And trying to delete .osz - if (Config.isDELETE_OSZ()) { - osz.delete(); - } + // And trying to delete .osz + if (Config.isDELETE_OSZ()) { + osz.delete(); + } - return true; - } + return true; + } - public static boolean canUseSD() { - if (Environment.getExternalStorageState().equals( - Environment.MEDIA_MOUNTED)) { - return true; - } else { - if (Environment.getExternalStorageState().equals( - Environment.MEDIA_MOUNTED_READ_ONLY)) { - ToastLogger.showText( - StringTable.get(R.string.message_error_sdcardread), - false); - } else { - ToastLogger.showText( - StringTable.get(R.string.message_error_sdcard), false); - } - } + public static boolean canUseSD() { + if (Environment.getExternalStorageState().equals( + Environment.MEDIA_MOUNTED)) { + return true; + } else { + if (Environment.getExternalStorageState().equals( + Environment.MEDIA_MOUNTED_READ_ONLY)) { + ToastLogger.showText( + StringTable.get(R.string.message_error_sdcardread), + false); + } else { + ToastLogger.showText( + StringTable.get(R.string.message_error_sdcard), false); + } + } - return false; - } + return false; + } } diff --git a/src/ru/nsu/ccfit/zuev/osu/PermissionActivity.java b/src/ru/nsu/ccfit/zuev/osu/PermissionActivity.java index 7da73c76..86b5e0a5 100644 --- a/src/ru/nsu/ccfit/zuev/osu/PermissionActivity.java +++ b/src/ru/nsu/ccfit/zuev/osu/PermissionActivity.java @@ -22,69 +22,69 @@ public class PermissionActivity extends AppCompatActivity implements EasyPermissions.PermissionCallbacks { - @Override - protected void onCreate(@Nullable Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_opening); - } + @Override + protected void onCreate(@Nullable Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_opening); + } - private void startGameActivity() { - Intent game = new Intent(this, MainActivity.class); - startActivity(game); - overridePendingTransition(R.anim.fast_activity_swap, R.anim.fast_activity_swap); - finish(); - } + private void startGameActivity() { + Intent game = new Intent(this, MainActivity.class); + startActivity(game); + overridePendingTransition(R.anim.fast_activity_swap, R.anim.fast_activity_swap); + finish(); + } - @Override - protected void onResume() { - super.onResume(); - checkPermissions(); - } + @Override + protected void onResume() { + super.onResume(); + checkPermissions(); + } - private void checkPermissions() { - if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { - if (Environment.isExternalStorageManager()) { - startGameActivity(); - } else { - Uri uri = Uri.parse("package:" + getPackageName()); - Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION, uri); - startActivityForResult(intent, 2444); - } - }else if(Build.VERSION.SDK_INT < Build.VERSION_CODES.R) { - if (PermissionChecker.checkCallingOrSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) - == PermissionChecker.PERMISSION_GRANTED) { - startGameActivity(); - } else { - ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 2333); - } - } - } + private void checkPermissions() { + if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { + if (Environment.isExternalStorageManager()) { + startGameActivity(); + } else { + Uri uri = Uri.parse("package:" + getPackageName()); + Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION, uri); + startActivityForResult(intent, 2444); + } + }else if(Build.VERSION.SDK_INT < Build.VERSION_CODES.R) { + if (PermissionChecker.checkCallingOrSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) + == PermissionChecker.PERMISSION_GRANTED) { + startGameActivity(); + } else { + ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 2333); + } + } + } - @Override - protected void onActivityResult(int requestCode, int resultCode, Intent data) { - super.onActivityResult(requestCode, resultCode, data); - if(requestCode == 2444) { - checkPermissions(); - } - } + @Override + protected void onActivityResult(int requestCode, int resultCode, Intent data) { + super.onActivityResult(requestCode, resultCode, data); + if(requestCode == 2444) { + checkPermissions(); + } + } - @Override - public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { - super.onRequestPermissionsResult(requestCode, permissions, grantResults); - EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this); - } + @Override + public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { + super.onRequestPermissionsResult(requestCode, permissions, grantResults); + EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this); + } - @Override - public void onPermissionsGranted(int requestCode, @NonNull List perms) { - checkPermissions(); - } + @Override + public void onPermissionsGranted(int requestCode, @NonNull List perms) { + checkPermissions(); + } - @Override - public void onPermissionsDenied(int requestCode, @NonNull List perms) { - if (PermissionChecker.checkCallingOrSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) - != PermissionChecker.PERMISSION_GRANTED - && EasyPermissions.somePermissionPermanentlyDenied(this, perms)) { - new AppSettingsDialog.Builder(this).build().show(); - } - } + @Override + public void onPermissionsDenied(int requestCode, @NonNull List perms) { + if (PermissionChecker.checkCallingOrSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) + != PermissionChecker.PERMISSION_GRANTED + && EasyPermissions.somePermissionPermanentlyDenied(this, perms)) { + new AppSettingsDialog.Builder(this).build().show(); + } + } } diff --git a/src/ru/nsu/ccfit/zuev/osu/PropertiesLibrary.java b/src/ru/nsu/ccfit/zuev/osu/PropertiesLibrary.java index 1d349140..58097a4a 100644 --- a/src/ru/nsu/ccfit/zuev/osu/PropertiesLibrary.java +++ b/src/ru/nsu/ccfit/zuev/osu/PropertiesLibrary.java @@ -21,119 +21,119 @@ import ru.nsu.ccfit.zuev.osuplus.R; public class PropertiesLibrary { - private static final PropertiesLibrary instance = new PropertiesLibrary(); - private final String version = "properties1"; - private Map props = new HashMap(); - private Context context = null; - private PropertiesLibrary() { - } - - public static PropertiesLibrary getInstance() { - return instance; - } - - @SuppressWarnings("unchecked") - public void load(final Activity activity) { - context = activity; - final File lib = new File(activity.getFilesDir(), "properties"); - if (lib.exists() == false) { - return; - } - - try { - final ObjectInputStream istream = new ObjectInputStream( - new FileInputStream(lib)); - Object obj = istream.readObject(); - if (obj instanceof String) { - if (((String) obj).equals(version) == false) { - istream.close(); - return; - } - } else { - istream.close(); - return; - } - obj = istream.readObject(); - if (obj instanceof Map) { - props = (Map) obj; - istream.close(); - Debug.i("Properties loaded"); - } - istream.close(); - } catch (final FileNotFoundException e) { - Debug.e("PropertiesLibrary: " + e.getMessage(), e); - } catch (final IOException e) { - Debug.e("PropertiesLibrary: " + e.getMessage(), e); - } catch (final ClassNotFoundException e) { - Debug.e("PropertiesLibrary: " + e.getMessage(), e); - } - ToastLogger.addToLog("Cannot load properties!"); - } - - public synchronized void save(final Context activity) { - final File lib = new File(activity.getFilesDir(), "properties"); - try { - final ObjectOutputStream ostream = new ObjectOutputStream( - new FileOutputStream(lib)); - ostream.writeObject(version); - ostream.writeObject(props); - ostream.close(); - } catch (final FileNotFoundException e) { - ToastLogger.showText( - StringTable.format(R.string.message_error, e.getMessage()), - false); - Debug.e("PropertiesLibrary: " + e.getMessage(), e); - } catch (final IOException e) { - ToastLogger.showText( - StringTable.format(R.string.message_error, e.getMessage()), - false); - Debug.e("PropertiesLibrary: " + e.getMessage(), e); - } - } - - public synchronized void clear(final Context activity) { - final File lib = new File(activity.getFilesDir(), "properties"); - lib.delete(); - props.clear(); - } - - public void save() { - if (context == null) { - return; - } - save(context); - } - - public void saveAsync() { - if (context == null) { - return; - } - new AsyncTaskLoader().execute(new OsuAsyncCallback() { - - - public void run() { - save(context); - } - - - public void onComplete() { - } - }); - } - - public BeatmapProperties getProperties(final String path) { - if (props.containsKey(path)) { - return props.get(path); - } - return null; - } - - public void setProperties(final String path, - final BeatmapProperties properties) { - this.load((Activity) context); - props.put(path, properties); - if (properties.favorite == false && properties.getOffset() == 0) { - props.remove(path); - } - } + private static final PropertiesLibrary instance = new PropertiesLibrary(); + private final String version = "properties1"; + private Map props = new HashMap(); + private Context context = null; + private PropertiesLibrary() { + } + + public static PropertiesLibrary getInstance() { + return instance; + } + + @SuppressWarnings("unchecked") + public void load(final Activity activity) { + context = activity; + final File lib = new File(activity.getFilesDir(), "properties"); + if (lib.exists() == false) { + return; + } + + try { + final ObjectInputStream istream = new ObjectInputStream( + new FileInputStream(lib)); + Object obj = istream.readObject(); + if (obj instanceof String) { + if (((String) obj).equals(version) == false) { + istream.close(); + return; + } + } else { + istream.close(); + return; + } + obj = istream.readObject(); + if (obj instanceof Map) { + props = (Map) obj; + istream.close(); + Debug.i("Properties loaded"); + } + istream.close(); + } catch (final FileNotFoundException e) { + Debug.e("PropertiesLibrary: " + e.getMessage(), e); + } catch (final IOException e) { + Debug.e("PropertiesLibrary: " + e.getMessage(), e); + } catch (final ClassNotFoundException e) { + Debug.e("PropertiesLibrary: " + e.getMessage(), e); + } + ToastLogger.addToLog("Cannot load properties!"); + } + + public synchronized void save(final Context activity) { + final File lib = new File(activity.getFilesDir(), "properties"); + try { + final ObjectOutputStream ostream = new ObjectOutputStream( + new FileOutputStream(lib)); + ostream.writeObject(version); + ostream.writeObject(props); + ostream.close(); + } catch (final FileNotFoundException e) { + ToastLogger.showText( + StringTable.format(R.string.message_error, e.getMessage()), + false); + Debug.e("PropertiesLibrary: " + e.getMessage(), e); + } catch (final IOException e) { + ToastLogger.showText( + StringTable.format(R.string.message_error, e.getMessage()), + false); + Debug.e("PropertiesLibrary: " + e.getMessage(), e); + } + } + + public synchronized void clear(final Context activity) { + final File lib = new File(activity.getFilesDir(), "properties"); + lib.delete(); + props.clear(); + } + + public void save() { + if (context == null) { + return; + } + save(context); + } + + public void saveAsync() { + if (context == null) { + return; + } + new AsyncTaskLoader().execute(new OsuAsyncCallback() { + + + public void run() { + save(context); + } + + + public void onComplete() { + } + }); + } + + public BeatmapProperties getProperties(final String path) { + if (props.containsKey(path)) { + return props.get(path); + } + return null; + } + + public void setProperties(final String path, + final BeatmapProperties properties) { + this.load((Activity) context); + props.put(path, properties); + if (properties.favorite == false && properties.getOffset() == 0) { + props.remove(path); + } + } } diff --git a/src/ru/nsu/ccfit/zuev/osu/RGBAColor.java b/src/ru/nsu/ccfit/zuev/osu/RGBAColor.java index a78a2dc0..f42cd2e9 100644 --- a/src/ru/nsu/ccfit/zuev/osu/RGBAColor.java +++ b/src/ru/nsu/ccfit/zuev/osu/RGBAColor.java @@ -1,45 +1,45 @@ package ru.nsu.ccfit.zuev.osu; public class RGBAColor { - private float cr; - private float cg; - private float cb; - private float ca; - - public RGBAColor() { - cr = 0; - cg = 0; - cb = 0; - ca = 1; - } - - public RGBAColor(final float r, final float g, final float b, final float a) { - cr = r; - cg = g; - cb = b; - ca = a; - } - - public float r() { - return cr; - } - - public float g() { - return cg; - } - - public float b() { - return cb; - } - - public float a() { - return ca; - } - - public void set(final float r, final float g, final float b, final float a) { - cr = r; - cg = g; - cb = b; - ca = a; - } + private float cr; + private float cg; + private float cb; + private float ca; + + public RGBAColor() { + cr = 0; + cg = 0; + cb = 0; + ca = 1; + } + + public RGBAColor(final float r, final float g, final float b, final float a) { + cr = r; + cg = g; + cb = b; + ca = a; + } + + public float r() { + return cr; + } + + public float g() { + return cg; + } + + public float b() { + return cb; + } + + public float a() { + return ca; + } + + public void set(final float r, final float g, final float b, final float a) { + cr = r; + cg = g; + cb = b; + ca = a; + } } diff --git a/src/ru/nsu/ccfit/zuev/osu/RGBColor.java b/src/ru/nsu/ccfit/zuev/osu/RGBColor.java index 0f652212..34b57811 100644 --- a/src/ru/nsu/ccfit/zuev/osu/RGBColor.java +++ b/src/ru/nsu/ccfit/zuev/osu/RGBColor.java @@ -3,62 +3,62 @@ import org.anddev.andengine.entity.Entity; public class RGBColor { - private float cr; - private float cg; - private float cb; + private float cr; + private float cg; + private float cb; - public RGBColor(RGBColor copy) { - this(copy.cr, copy.cg, copy.cb); - } + public RGBColor(RGBColor copy) { + this(copy.cr, copy.cg, copy.cb); + } - public RGBColor() { - cr = 0; - cg = 0; - cb = 0; - } + public RGBColor() { + cr = 0; + cg = 0; + cb = 0; + } - public RGBColor(final float r, final float g, final float b) { - cr = r; - cg = g; - cb = b; - } + public RGBColor(final float r, final float g, final float b) { + cr = r; + cg = g; + cb = b; + } - /** - * @param colorStr e.g. "#FFFFFF" - * @return - */ - public static RGBColor hex2Rgb(String colorStr) { - return new RGBColor( - Integer.valueOf(colorStr.substring(1, 3), 16) / 255.0f, - Integer.valueOf(colorStr.substring(3, 5), 16) / 255.0f, - Integer.valueOf(colorStr.substring(5, 7), 16) / 255.0f); - } + /** + * @param colorStr e.g. "#FFFFFF" + * @return + */ + public static RGBColor hex2Rgb(String colorStr) { + return new RGBColor( + Integer.valueOf(colorStr.substring(1, 3), 16) / 255.0f, + Integer.valueOf(colorStr.substring(3, 5), 16) / 255.0f, + Integer.valueOf(colorStr.substring(5, 7), 16) / 255.0f); + } - public float r() { - return cr; - } + public float r() { + return cr; + } - public float g() { - return cg; - } + public float g() { + return cg; + } - public float b() { - return cb; - } + public float b() { + return cb; + } - public void set(final float r, final float g, final float b) { - cr = r; - cg = g; - cb = b; - } + public void set(final float r, final float g, final float b) { + cr = r; + cg = g; + cb = b; + } - public void apply(Entity entity) { - entity.setColor(cr, cg, cb); - } + public void apply(Entity entity) { + entity.setColor(cr, cg, cb); + } - public void applyAll(Entity... entities) { - for (Entity entity : entities) { - entity.setColor(cr, cg, cb); - } - } + public void applyAll(Entity... entities) { + for (Entity entity : entities) { + entity.setColor(cr, cg, cb); + } + } } diff --git a/src/ru/nsu/ccfit/zuev/osu/ResourceManager.java b/src/ru/nsu/ccfit/zuev/osu/ResourceManager.java index bb2b5a32..e111e1f3 100644 --- a/src/ru/nsu/ccfit/zuev/osu/ResourceManager.java +++ b/src/ru/nsu/ccfit/zuev/osu/ResourceManager.java @@ -37,817 +37,817 @@ import ru.nsu.ccfit.zuev.osu.helper.ScaledBitmapSource; public class ResourceManager { - private static ResourceManager mgr = new ResourceManager(); - private final Map fonts = new HashMap(); - private final Map textures = new HashMap(); - private final Map sounds = new HashMap(); - private final Map customSounds = new HashMap(); - private final Map customTextures = new HashMap(); - private final Map customFrameCount = new HashMap(); - private Engine engine; - private Context context; - - private ResourceManager() { - } - - public static ResourceManager getInstance() { - return mgr; - } - - public Engine getEngine() { - return engine; - } - - public void Init(final Engine engine, final Context context) { - this.engine = engine; - this.context = context; - - fonts.clear(); - textures.clear(); - sounds.clear(); - - customSounds.clear(); - customTextures.clear(); - customFrameCount.clear(); - - initSecurityUtils(); - } - - public void loadSkin(String folder) { - loadFont("smallFont", null, 21, Color.WHITE); - loadFont("middleFont", null, 24, Color.WHITE); - loadFont("font", null, 28, Color.WHITE); - loadStrokeFont("strokeFont", null, 36, Color.BLACK, Color.WHITE); - loadFont("CaptionFont", null, 35, Color.WHITE); - - if (!folder.endsWith("/")) - folder = folder + "/"; - - loadCustomSkin(folder); - - loadTexture("::track", "gfx/hitcircle.png", false, - TextureOptions.BILINEAR_PREMULTIPLYALPHA); - loadTexture("::track2", "gfx/slidertrack.png", false); - loadTexture("::trackborder", "gfx/sliderborder.png", false, - TextureOptions.BILINEAR_PREMULTIPLYALPHA); - loadTexture("ranking_enabled", "ranking_enabled.png", false); - loadTexture("ranking_disabled", "ranking_disabled.png", false); - loadTexture("flashlight_cursor", "flashlight_cursor.png", false, TextureOptions.BILINEAR_PREMULTIPLYALPHA); - - if (textures.containsKey("lighting") == false) - textures.put("lighting", null); -// textures.put("fail-background", null); -// textures.put("pause-overlay", null); - } - - public void loadCustomSkin(String folder) { - - if (!folder.endsWith("/")) folder += "/"; - - File[] skinFiles = null; - File skinFolder = null; - if (folder != null) { - skinFolder = new File(folder); - if (!skinFolder.exists()) { - skinFolder = null; - } else { - skinFiles = FileUtils.listFiles(skinFolder); - } - } - if (skinFiles != null) { - JSONObject skinjson = null; - File skinJson = new File(folder, "skin.json"); - if (skinJson.exists()) { - try { - skinjson = new JSONObject(SkinJson.readFull(skinJson)); - } catch (Exception e) { - e.printStackTrace(); - skinjson = null; - } - } - if (skinjson == null) skinjson = new JSONObject(); - SkinJson.get().loadSkinJson(skinjson); - } - final Map availableFiles = new HashMap(); - if (skinFiles != null) { - for (final File f : skinFiles) { - if (f.isFile()) { - if (f.getName().startsWith("comboburst") - && (f.getName().endsWith(".wav") || f.getName().endsWith(".mp3"))) { - continue; - } - if (f.getName().length() < 5) continue; - final String filename = f.getName().substring(0, f.getName().length() - 4); - availableFiles.put(filename, f); - //if ((filename.startsWith("hit0") || filename.startsWith("hit50") || filename.startsWith("hit100") || filename.startsWith("hit300"))){ - // availableFiles.put(filename + "-0", f); - //} - - if (filename.equals("hitcircle")) { - if (!availableFiles.containsKey("sliderstartcircle")) { - availableFiles.put("sliderstartcircle", f); - } - if (!availableFiles.containsKey("sliderendcircle")) { - availableFiles.put("sliderendcircle", f); - } - } - if (filename.equals("hitcircleoverlay")) { - if (!availableFiles.containsKey("sliderstartcircleoverlay")) { - availableFiles.put("sliderstartcircleoverlay", f); - } - if (!availableFiles.containsKey("sliderendcircleoverlay")) { - availableFiles.put("sliderendcircleoverlay", f); - } - } - } - } - } - - customFrameCount.clear(); - - try { - for (final String s : context.getAssets().list("gfx")) { - final String name = s.substring(0, s.length() - 4); - if (Config.isCorovans() == false) { - if (name.equals("count1") || name.equals("count2") - || name.equals("count3") || name.equals("go") - || name.equals("ready")) { - continue; - } - } - if (availableFiles.containsKey(name)) { - loadTexture(name, availableFiles.get(name).getPath(), true); - if (Character.isDigit(name.charAt(name.length() - 1))) { - noticeFrameCount(name); - } - } else { - loadTexture(name, "gfx/" + s, false); - } - } - if (availableFiles.containsKey("scorebar-kidanger")) { - loadTexture("scorebar-kidanger", availableFiles.get("scorebar-kidanger").getPath(), true); - loadTexture("scorebar-kidanger2", - availableFiles.get( - availableFiles.containsKey("scorebar-kidanger2") ? "scorebar-kidanger2" : "scorebar-kidanger" - ).getPath(), true); - } - if (availableFiles.containsKey("comboburst")) - loadTexture("comboburst", availableFiles.get("comboburst").getPath(), true); - else unloadTexture("comboburst"); - for (int i = 0; i < 10; i++) { - String textureName = "comboburst-" + i; - if (availableFiles.containsKey(textureName)) - loadTexture(textureName, availableFiles.get(textureName).getPath(), true); - else unloadTexture(textureName); - } - for (int i = 0; i < 60; i++) { - String textureName = "play-skip-" + i; - if (availableFiles.containsKey(textureName)) - loadTexture(textureName, availableFiles.get(textureName).getPath(), true); - else unloadTexture(textureName); - } - for (int i = 0; i < 60; i++) { - String textureName = "menu-back-" + i; - if (availableFiles.containsKey(textureName)) - loadTexture(textureName, availableFiles.get(textureName).getPath(), true); - else unloadTexture(textureName); - } - for (int i = 0; i < 60; i++) { - String textureName = "scorebar-colour-" + i; - if (availableFiles.containsKey(textureName)) - loadTexture(textureName, availableFiles.get(textureName).getPath(), true); - else unloadTexture(textureName); - } - // - for (int i = 0; i < 60; i++) { - String textureName = "hit0-" + i; - if (availableFiles.containsKey(textureName)) - loadTexture(textureName, availableFiles.get(textureName).getPath(), true); - else unloadTexture(textureName); - } - for (int i = 0; i < 60; i++) { - String textureName = "hit50-" + i; - if (availableFiles.containsKey(textureName)) - loadTexture(textureName, availableFiles.get(textureName).getPath(), true); - else unloadTexture(textureName); - } - for (int i = 0; i < 60; i++) { - String textureName = "hit100-" + i; - if (availableFiles.containsKey(textureName)) - loadTexture(textureName, availableFiles.get(textureName).getPath(), true); - else unloadTexture(textureName); - } - for (int i = 0; i < 60; i++) { - String textureName = "hit100k-" + i; - if (availableFiles.containsKey(textureName)) - loadTexture(textureName, availableFiles.get(textureName).getPath(), true); - else unloadTexture(textureName); - } - for (int i = 0; i < 60; i++) { - String textureName = "hit300-" + i; - if (availableFiles.containsKey(textureName)) - loadTexture(textureName, availableFiles.get(textureName).getPath(), true); - else unloadTexture(textureName); - } - for (int i = 0; i < 60; i++) { - String textureName = "hit300k-" + i; - if (availableFiles.containsKey(textureName)) - loadTexture(textureName, availableFiles.get(textureName).getPath(), true); - else unloadTexture(textureName); - } - for (int i = 0; i < 60; i++) { - String textureName = "hit300g-" + i; - if (availableFiles.containsKey(textureName)) - loadTexture(textureName, availableFiles.get(textureName).getPath(), true); - else unloadTexture(textureName); - } - // - } catch (final IOException e) { - Debug.e("Resources: " + e.getMessage(), e); - } - - SkinManager.getInstance().presetFrameCount(); - - try { - // TODO: buggy? - for (final String s : context.getAssets().list("sfx")) { - final String name = s.substring(0, s.length() - 4); - if (availableFiles.containsKey(name)) { - loadSound(name, availableFiles.get(name).getPath(), true); - } else { - loadSound(name, "sfx/" + s, false); - } - } - if (skinFolder != null) { - loadSound("comboburst", folder + "comboburst.wav", true); - for (int i = 0; i < 10; i++) { - loadSound("comboburst-" + i, folder + "comboburst-" + i + ".wav", true); - } - } - } catch (final IOException e) { - Debug.e("Resources: " + e.getMessage(), e); - } - - loadTexture("::track", "gfx/hitcircle.png", false, - TextureOptions.BILINEAR_PREMULTIPLYALPHA); - loadTexture("::track2", "gfx/slidertrack.png", false); - loadTexture("::trackborder", "gfx/sliderborder.png", false, - TextureOptions.BILINEAR_PREMULTIPLYALPHA); - loadTexture("ranking_button", "ranking_button.png", false); - loadTexture("ranking_enabled", "ranking_enabled.png", false); - loadTexture("ranking_disabled", "ranking_disabled.png", false); - if (textures.containsKey("lighting") == false) - textures.put("lighting", null); -// textures.put("fail-background", null); -// textures.put("pause-overlay", null); - } - - private void noticeFrameCount(final String name) { - String resnameWN; - if (name.contains("-") == false) { - resnameWN = name.substring(0, name.length() - 1); - } else { - resnameWN = name.substring(0, name.lastIndexOf('-')); - } - int frameNum; - try { - frameNum = Integer.parseInt(name.substring(resnameWN.length())); - } catch (final NumberFormatException e) { - return; - } - if (frameNum < 0) { - frameNum *= -1; - } - if (customFrameCount.containsKey(resnameWN) == false - || customFrameCount.get(resnameWN) < frameNum) { - customFrameCount.put(resnameWN, frameNum); - } - } - - public Font loadFont(final String resname, final String file, int size, - final int color) { - size /= Config.getTextureQuality(); - final BitmapTextureAtlas texture = new BitmapTextureAtlas(512, 512, - TextureOptions.BILINEAR_PREMULTIPLYALPHA); - Font font; - if (file == null) { - font = new Font(texture, Typeface.create(Typeface.DEFAULT, - Typeface.NORMAL), size, true, color); - } else { - font = FontFactory.createFromAsset(texture, context, "fonts/" - + file, size, true, color); - } - engine.getTextureManager().loadTexture(texture); - engine.getFontManager().loadFont(font); - fonts.put(resname, font); - return font; - } - - public StrokeFont loadStrokeFont(final String resname, final String file, - int size, final int color1, final int color2) { - size /= Config.getTextureQuality(); - final BitmapTextureAtlas texture = new BitmapTextureAtlas(512, 256, - TextureOptions.BILINEAR_PREMULTIPLYALPHA); - StrokeFont font; - if (file == null) { - font = new StrokeFont(texture, Typeface.create(Typeface.DEFAULT, - Typeface.NORMAL), size, true, color1, - Config.getTextureQuality() == 1 ? 2 : 0.75f, color2); - } else { - font = FontFactory.createStrokeFromAsset(texture, context, "fonts/" - + file, size, true, color1, 2 / Config.getTextureQuality(), - color2); - } - engine.getTextureManager().loadTexture(texture); - engine.getFontManager().loadFont(font); - fonts.put(resname, font); - return font; - } - - public Font getFont(final String resname) { - if (fonts.containsKey(resname) == false) { - loadFont(resname, null, 35, Color.WHITE); - } - return fonts.get(resname); - } - - public TextureRegion loadTexture(final String resname, final String file, - final boolean external, final TextureOptions opt) { - return loadTexture(resname, file, external, opt, this.engine); - } - - public TextureRegion loadTexture(final String resname, final String file, - final boolean external) { - return loadTexture(resname, file, external, TextureOptions.BILINEAR, this.engine); - } - - public TextureRegion loadTexture(final String resname, final String file, - final boolean external, Engine engine) { - return loadTexture(resname, file, external, TextureOptions.BILINEAR, engine); - } - - public TextureRegion loadBackground(final String file) { - return loadBackground(file, this.engine); - } - - public TextureRegion loadBackground(final String file, Engine engine) { - if (textures.containsKey("::background")) { - engine.getTextureManager().unloadTexture( - textures.get("::background").getTexture()); - } - if (file == null) { - return null; - } - int tw = 16, th = 16; - TextureRegion region; - final ScaledBitmapSource source = new ScaledBitmapSource(new File(file)); - if (source.getWidth() == 0 || source.getHeight() == 0) { - return null; - } - while (tw < source.getWidth()) { - tw *= 2; - } - while (th < source.getHeight()) { - th *= 2; - } - if (source.preload() == false) { - textures.put("::background", textures.get("menu-background")); - return textures.get("::background"); - } - final BitmapTextureAtlas tex = new BitmapTextureAtlas(tw, th, - TextureOptions.BILINEAR); - region = TextureRegionFactory - .createFromSource(tex, source, 0, 0, false); - engine.getTextureManager().loadTexture(tex); - textures.put("::background", region); - return region; - } - - public TextureRegion loadTexture(final String resname, final String file, - final boolean external, final TextureOptions opt, Engine engine) { - int tw = 4, th = 4; - TextureRegion region; - if (external) { - final File texFile = new File(file); - if (texFile.exists() == false) { - return textures.values().iterator().next(); - } - final QualityFileBitmapSource source = new QualityFileBitmapSource( - texFile); - if (source.getWidth() == 0 || source.getHeight() == 0) { - return null; - } - while (tw < source.getWidth()) { - tw *= 2; - } - while (th < source.getHeight()) { - th *= 2; - } - - int errorCount = 0; - while (source.preload() == false && errorCount < 3) { - errorCount++; - } - if (errorCount >= 3) { - return null; - } - final BitmapTextureAtlas tex = new BitmapTextureAtlas(tw, th, opt); - region = TextureRegionFactory.createFromSource(tex, source, 0, 0, - false); - engine.getTextureManager().loadTexture(tex); - textures.put(resname, region); - } else { - final QualityAssetBitmapSource source; - - try { - source = new QualityAssetBitmapSource( - context, file); - } catch (NullPointerException e) { - return textures.values().iterator().next(); - } - - if (source.getWidth() == 0 || source.getHeight() == 0) { - return null; - } - while (tw < source.getWidth()) { - tw *= 2; - } - while (th < source.getHeight()) { - th *= 2; - } - int errorCount = 0; - while (source.preload() == false && errorCount < 3) { - errorCount++; - } - if (errorCount >= 3) { - return null; - } - final BitmapTextureAtlas tex = new BitmapTextureAtlas(tw, th, opt); - region = TextureRegionFactory.createFromSource(tex, source, 0, 0, - false); - engine.getTextureManager().loadTexture(tex); - textures.put(resname, region); - } - - if (region.getWidth() > 1) { - region.setWidth(region.getWidth() - 1); - } - if (region.getHeight() > 1) { - region.setHeight(region.getHeight() - 1); - } - - - return region; - } - - public TextureRegion loadHighQualityAsset(final String resname, - final String file) { - int tw = 16, th = 16; - TextureRegion region; - - final AssetBitmapTextureAtlasSource source = new AssetBitmapTextureAtlasSource( - context, file); - if (source.getWidth() == 0 || source.getHeight() == 0) { - return null; - } - while (tw < source.getWidth()) { - tw *= 2; - } - while (th < source.getHeight()) { - th *= 2; - } - final BitmapTextureAtlas tex = new BitmapTextureAtlas(tw, th, - TextureOptions.BILINEAR); - region = TextureRegionFactory - .createFromSource(tex, source, 0, 0, false); - engine.getTextureManager().loadTexture(tex); - textures.put(resname, region); - //region.setWidth(region.getWidth() - 1); - //region.setHeight(region.getHeight() - 1); - - return region; - } - - public TextureRegion loadHighQualityFile(final String resname, - final File file) { - int tw = 16, th = 16; - TextureRegion region; - - final FileBitmapTextureAtlasSource source = new FileBitmapTextureAtlasSource(file); - if (source.getWidth() == 0 || source.getHeight() == 0) { - return null; - } - while (tw < source.getWidth()) { - tw *= 2; - } - while (th < source.getHeight()) { - th *= 2; - } - final BitmapTextureAtlas tex = new BitmapTextureAtlas(tw, th, - TextureOptions.BILINEAR); - region = TextureRegionFactory - .createFromSource(tex, source, 0, 0, false); - engine.getTextureManager().loadTexture(tex); - textures.put(resname, region); - region.setWidth(region.getWidth() - 1); - region.setHeight(region.getHeight() - 1); - return region; - } - - public void loadHighQualityFileUnderFolder(File folder) { - File[] files = FileUtils.listFiles(folder, new String[]{ - ".png", ".jpg", ".bmp"}); - for (File file : files) { - if (file.isDirectory()) { - loadHighQualityFileUnderFolder(file); - } else { - Log.i("texture", "load: " + file.getPath()); - loadHighQualityFile(file.getPath(), file); - } - } - } - - public TextureRegion getTexture(final String resname) { - if (SkinManager.isSkinEnabled() && customTextures.containsKey(resname)) { - return customTextures.get(resname); - } - if (textures.containsKey(resname) == false) { - Debug.i("Loading texture: " + resname); - return loadTexture(resname, "gfx/" + resname + ".png", false); - } - return textures.get(resname); - } - - public TextureRegion getTextureIfLoaded(final String resname) { - if (textures.containsKey(resname)/* - * && - * textures.get(resname).getTexture(). - * isLoadedToHardware() - */) { - return textures.get(resname); - } - return null; - } - - public boolean isTextureLoaded(final String resname) { - return textures.containsKey(resname); - } - - public BassSoundProvider loadSound(final String resname, final String file, - final boolean external) { - BassSoundProvider snd = new BassSoundProvider(); - if (external) { - //若是来自储存文件 - try { - if (!snd.prepare(file)) { - // 外部文件加载失败尝试自带皮肤 - String shortName = file.substring(file.lastIndexOf("/") + 1); - if (!snd.prepare(context.getAssets(), "sfx/" + shortName)) { - return null; - } - } - } catch (final Exception e) { - Debug.e("ResourceManager.loadSoundFromExternal: " + e.getMessage(), e); - return null; - } - } else { - //若是没有自定义音效,则使用自带音效 - try { - if (!snd.prepare(context.getAssets(), file)) { - return null; - } - } catch (final Exception e) { - Debug.e("ResourceManager.loadSound: " + e.getMessage(), e); - return null; - } - } - - sounds.put(resname, snd); - - return snd; - } - - public BassSoundProvider getSound(final String resname) { - return sounds.get(resname); - } - - public void loadCustomSound(final File file) { - BassSoundProvider snd = new BassSoundProvider(); - String resName = file.getName(); - resName = resName.substring(0, resName.length() - 4); - if (resName.length() == 0) { - return; - } - Pattern pattern = Pattern.compile("([^\\d\\.]+)"); - Matcher matcher = pattern.matcher(resName); - if (matcher.find()) { - String setName = matcher.group(1); - if (!sounds.containsKey(setName)) { - // 剔除未知的音频文件 - return; - } - } - try { - snd.prepare(file.getPath()); - } catch (final Exception e) { - Debug.e("ResourceManager.loadCustomSound: " + e.getMessage(), e); - return; - } - - customSounds.put(resName, snd); - } - - public BassSoundProvider getCustomSound(final String resname, final int set) { - if (!SkinManager.isSkinEnabled()) { - return getSound(resname); - } - if (set >= 2) { - String fullName = resname + String.valueOf(set); - if (customSounds.containsKey(fullName)) { - return customSounds.get(fullName); - } else { - return sounds.get(resname); - } - } - if (customSounds.containsKey(resname)) { - return customSounds.get(resname); - } - - return sounds.get(resname); - } - - public void loadCustomTexture(final File file) { - String resname = file.getName(); - resname = resname.substring(0, resname.length() - 4).toLowerCase(); - boolean multiframe = false; - - String delimiter = "-"; - - if (Character.isDigit(resname.charAt(resname.length() - 1))) { - - String resnameWN; - if (resname.contains("-") == false) { - resnameWN = resname.substring(0, resname.length() - 1); - } else { - resnameWN = resname.substring(0, resname.lastIndexOf('-')); - } - - if (textures.containsKey(resname) == false - && SkinManager.getFrames(resnameWN) == 0) { - return; - } - - if (textures.containsKey(resnameWN) - || textures.containsKey(resnameWN + "-0") - || textures.containsKey(resnameWN + "0")) { - int frameNum = Integer.parseInt(resname.substring(resnameWN - .length())); - if (frameNum < 0) { - frameNum *= -1; - } - if (customFrameCount.containsKey(resnameWN) == false - || customFrameCount.get(resnameWN) < frameNum) { - customFrameCount.put(resnameWN, frameNum); - } - } - } else if (textures.containsKey(resname) == false) { - - if (textures.containsKey(resname + "-0") || textures.containsKey(resname + "0")) { - if (textures.containsKey(resname + "0")) - delimiter = ""; - if (SkinManager.getFrames(resname) != 0) { - customFrameCount.put(resname, 1); - } - multiframe = true; - } else { - return; - } - } - int tw = 16, th = 16; - final QualityFileBitmapSource source = new QualityFileBitmapSource(file); - while (tw < source.getWidth()) { - tw *= 2; - } - while (th < source.getHeight()) { - th *= 2; - } - if (source.preload() == false) { - return; - } - final BitmapTextureAtlas tex = new BitmapTextureAtlas(tw, th, - TextureOptions.BILINEAR); - final TextureRegion region = TextureRegionFactory.createFromSource(tex, - source, 0, 0, false); - // engine.getTextureManager().unloadTexture(textures.get(resname).getTexture()); - engine.getTextureManager().loadTexture(tex); - if (region.getWidth() > 1) { - region.setWidth(region.getWidth() - 1); - } - if (region.getHeight() > 1) { - region.setHeight(region.getHeight() - 1); - } - if (multiframe) { - int i = 0; - while (textures.containsKey(resname + delimiter + i)) { - customTextures.put(resname + delimiter + i, region); - i++; - } - } else { - customTextures.put(resname, region); - - if (resname.equals("hitcircle")) { - if (!customTextures.containsKey("sliderstartcircle")) { - customTextures.put("sliderstartcircle", region); - } - - if (!customTextures.containsKey("sliderendcircle")) { - customTextures.put("sliderendcircle", region); - } - } - - if (resname.equals("hitcircleoverlay")) { - if (!customTextures.containsKey("sliderstartcircleoverlay")) { - customTextures.put("sliderstartcircleoverlay", region); - } - - if (!customTextures.containsKey("sliderendcircleoverlay")) { - customTextures.put("sliderendcircleoverlay", region); - } - } - } - } - - public void unloadTexture(final String name) { - if (textures.get(name) != null) { - engine.getTextureManager().unloadTexture( - textures.get(name).getTexture()); - textures.remove(name); - Debug.i("Texture \"" + name + "\"unloaded"); - } - } - - public void initSecurityUtils() { - SecurityUtils.getAppSignature(context, context.getPackageName()); - } - - public void clearCustomResources() { - for (final BassSoundProvider s : customSounds.values()) { - s.free(); - } - final Set texnames = customTextures.keySet(); - for (final String s : texnames) { - if (customTextures.get(s).getTexture().isLoadedToHardware()) { - engine.getTextureManager().unloadTexture( - customTextures.get(s).getTexture()); - // engine.getTextureManager().loadTexture(textures.get(s).getTexture()); - } - } - customTextures.clear(); - customSounds.clear(); - customFrameCount.clear(); - } - - public int getFrameCount(final String texname) { - if (customFrameCount.containsKey(texname) == false) { - return -1; - } else { - return customFrameCount.get(texname); - } - } - - public void checkSpinnerTextures() { - final String[] names = {"spinner-background", "spinner-circle", - "spinner-metre", "spinner-approachcircle", "spinner-spin"}; - for (final String s : names) { - if (textures != null - && textures.get(s) != null - && textures.get(s).getTexture() != null - && !textures.get(s).getTexture().isLoadedToHardware()) { - engine.getTextureManager().reloadTextures(); - break; - } - } - } - - public void checkEvoSpinnerTextures() { - final String[] names = { - "spinner-bottom", - "spinner-top", - "spinner-glow", - "spinner-middle", - "spinner-middle2", - "spinner-spin", - "spinner-clear" - }; - for (final String s : names) { - if (textures != null - && textures.get(s) != null - && textures.get(s).getTexture() != null - && !textures.get(s).getTexture().isLoadedToHardware()) { - engine.getTextureManager().reloadTextures(); - break; - } - } - } + private static ResourceManager mgr = new ResourceManager(); + private final Map fonts = new HashMap(); + private final Map textures = new HashMap(); + private final Map sounds = new HashMap(); + private final Map customSounds = new HashMap(); + private final Map customTextures = new HashMap(); + private final Map customFrameCount = new HashMap(); + private Engine engine; + private Context context; + + private ResourceManager() { + } + + public static ResourceManager getInstance() { + return mgr; + } + + public Engine getEngine() { + return engine; + } + + public void Init(final Engine engine, final Context context) { + this.engine = engine; + this.context = context; + + fonts.clear(); + textures.clear(); + sounds.clear(); + + customSounds.clear(); + customTextures.clear(); + customFrameCount.clear(); + + initSecurityUtils(); + } + + public void loadSkin(String folder) { + loadFont("smallFont", null, 21, Color.WHITE); + loadFont("middleFont", null, 24, Color.WHITE); + loadFont("font", null, 28, Color.WHITE); + loadStrokeFont("strokeFont", null, 36, Color.BLACK, Color.WHITE); + loadFont("CaptionFont", null, 35, Color.WHITE); + + if (!folder.endsWith("/")) + folder = folder + "/"; + + loadCustomSkin(folder); + + loadTexture("::track", "gfx/hitcircle.png", false, + TextureOptions.BILINEAR_PREMULTIPLYALPHA); + loadTexture("::track2", "gfx/slidertrack.png", false); + loadTexture("::trackborder", "gfx/sliderborder.png", false, + TextureOptions.BILINEAR_PREMULTIPLYALPHA); + loadTexture("ranking_enabled", "ranking_enabled.png", false); + loadTexture("ranking_disabled", "ranking_disabled.png", false); + loadTexture("flashlight_cursor", "flashlight_cursor.png", false, TextureOptions.BILINEAR_PREMULTIPLYALPHA); + + if (textures.containsKey("lighting") == false) + textures.put("lighting", null); +// textures.put("fail-background", null); +// textures.put("pause-overlay", null); + } + + public void loadCustomSkin(String folder) { + + if (!folder.endsWith("/")) folder += "/"; + + File[] skinFiles = null; + File skinFolder = null; + if (folder != null) { + skinFolder = new File(folder); + if (!skinFolder.exists()) { + skinFolder = null; + } else { + skinFiles = FileUtils.listFiles(skinFolder); + } + } + if (skinFiles != null) { + JSONObject skinjson = null; + File skinJson = new File(folder, "skin.json"); + if (skinJson.exists()) { + try { + skinjson = new JSONObject(SkinJson.readFull(skinJson)); + } catch (Exception e) { + e.printStackTrace(); + skinjson = null; + } + } + if (skinjson == null) skinjson = new JSONObject(); + SkinJson.get().loadSkinJson(skinjson); + } + final Map availableFiles = new HashMap(); + if (skinFiles != null) { + for (final File f : skinFiles) { + if (f.isFile()) { + if (f.getName().startsWith("comboburst") + && (f.getName().endsWith(".wav") || f.getName().endsWith(".mp3"))) { + continue; + } + if (f.getName().length() < 5) continue; + final String filename = f.getName().substring(0, f.getName().length() - 4); + availableFiles.put(filename, f); + //if ((filename.startsWith("hit0") || filename.startsWith("hit50") || filename.startsWith("hit100") || filename.startsWith("hit300"))){ + // availableFiles.put(filename + "-0", f); + //} + + if (filename.equals("hitcircle")) { + if (!availableFiles.containsKey("sliderstartcircle")) { + availableFiles.put("sliderstartcircle", f); + } + if (!availableFiles.containsKey("sliderendcircle")) { + availableFiles.put("sliderendcircle", f); + } + } + if (filename.equals("hitcircleoverlay")) { + if (!availableFiles.containsKey("sliderstartcircleoverlay")) { + availableFiles.put("sliderstartcircleoverlay", f); + } + if (!availableFiles.containsKey("sliderendcircleoverlay")) { + availableFiles.put("sliderendcircleoverlay", f); + } + } + } + } + } + + customFrameCount.clear(); + + try { + for (final String s : context.getAssets().list("gfx")) { + final String name = s.substring(0, s.length() - 4); + if (Config.isCorovans() == false) { + if (name.equals("count1") || name.equals("count2") + || name.equals("count3") || name.equals("go") + || name.equals("ready")) { + continue; + } + } + if (availableFiles.containsKey(name)) { + loadTexture(name, availableFiles.get(name).getPath(), true); + if (Character.isDigit(name.charAt(name.length() - 1))) { + noticeFrameCount(name); + } + } else { + loadTexture(name, "gfx/" + s, false); + } + } + if (availableFiles.containsKey("scorebar-kidanger")) { + loadTexture("scorebar-kidanger", availableFiles.get("scorebar-kidanger").getPath(), true); + loadTexture("scorebar-kidanger2", + availableFiles.get( + availableFiles.containsKey("scorebar-kidanger2") ? "scorebar-kidanger2" : "scorebar-kidanger" + ).getPath(), true); + } + if (availableFiles.containsKey("comboburst")) + loadTexture("comboburst", availableFiles.get("comboburst").getPath(), true); + else unloadTexture("comboburst"); + for (int i = 0; i < 10; i++) { + String textureName = "comboburst-" + i; + if (availableFiles.containsKey(textureName)) + loadTexture(textureName, availableFiles.get(textureName).getPath(), true); + else unloadTexture(textureName); + } + for (int i = 0; i < 60; i++) { + String textureName = "play-skip-" + i; + if (availableFiles.containsKey(textureName)) + loadTexture(textureName, availableFiles.get(textureName).getPath(), true); + else unloadTexture(textureName); + } + for (int i = 0; i < 60; i++) { + String textureName = "menu-back-" + i; + if (availableFiles.containsKey(textureName)) + loadTexture(textureName, availableFiles.get(textureName).getPath(), true); + else unloadTexture(textureName); + } + for (int i = 0; i < 60; i++) { + String textureName = "scorebar-colour-" + i; + if (availableFiles.containsKey(textureName)) + loadTexture(textureName, availableFiles.get(textureName).getPath(), true); + else unloadTexture(textureName); + } + // + for (int i = 0; i < 60; i++) { + String textureName = "hit0-" + i; + if (availableFiles.containsKey(textureName)) + loadTexture(textureName, availableFiles.get(textureName).getPath(), true); + else unloadTexture(textureName); + } + for (int i = 0; i < 60; i++) { + String textureName = "hit50-" + i; + if (availableFiles.containsKey(textureName)) + loadTexture(textureName, availableFiles.get(textureName).getPath(), true); + else unloadTexture(textureName); + } + for (int i = 0; i < 60; i++) { + String textureName = "hit100-" + i; + if (availableFiles.containsKey(textureName)) + loadTexture(textureName, availableFiles.get(textureName).getPath(), true); + else unloadTexture(textureName); + } + for (int i = 0; i < 60; i++) { + String textureName = "hit100k-" + i; + if (availableFiles.containsKey(textureName)) + loadTexture(textureName, availableFiles.get(textureName).getPath(), true); + else unloadTexture(textureName); + } + for (int i = 0; i < 60; i++) { + String textureName = "hit300-" + i; + if (availableFiles.containsKey(textureName)) + loadTexture(textureName, availableFiles.get(textureName).getPath(), true); + else unloadTexture(textureName); + } + for (int i = 0; i < 60; i++) { + String textureName = "hit300k-" + i; + if (availableFiles.containsKey(textureName)) + loadTexture(textureName, availableFiles.get(textureName).getPath(), true); + else unloadTexture(textureName); + } + for (int i = 0; i < 60; i++) { + String textureName = "hit300g-" + i; + if (availableFiles.containsKey(textureName)) + loadTexture(textureName, availableFiles.get(textureName).getPath(), true); + else unloadTexture(textureName); + } + // + } catch (final IOException e) { + Debug.e("Resources: " + e.getMessage(), e); + } + + SkinManager.getInstance().presetFrameCount(); + + try { + // TODO: buggy? + for (final String s : context.getAssets().list("sfx")) { + final String name = s.substring(0, s.length() - 4); + if (availableFiles.containsKey(name)) { + loadSound(name, availableFiles.get(name).getPath(), true); + } else { + loadSound(name, "sfx/" + s, false); + } + } + if (skinFolder != null) { + loadSound("comboburst", folder + "comboburst.wav", true); + for (int i = 0; i < 10; i++) { + loadSound("comboburst-" + i, folder + "comboburst-" + i + ".wav", true); + } + } + } catch (final IOException e) { + Debug.e("Resources: " + e.getMessage(), e); + } + + loadTexture("::track", "gfx/hitcircle.png", false, + TextureOptions.BILINEAR_PREMULTIPLYALPHA); + loadTexture("::track2", "gfx/slidertrack.png", false); + loadTexture("::trackborder", "gfx/sliderborder.png", false, + TextureOptions.BILINEAR_PREMULTIPLYALPHA); + loadTexture("ranking_button", "ranking_button.png", false); + loadTexture("ranking_enabled", "ranking_enabled.png", false); + loadTexture("ranking_disabled", "ranking_disabled.png", false); + if (textures.containsKey("lighting") == false) + textures.put("lighting", null); +// textures.put("fail-background", null); +// textures.put("pause-overlay", null); + } + + private void noticeFrameCount(final String name) { + String resnameWN; + if (name.contains("-") == false) { + resnameWN = name.substring(0, name.length() - 1); + } else { + resnameWN = name.substring(0, name.lastIndexOf('-')); + } + int frameNum; + try { + frameNum = Integer.parseInt(name.substring(resnameWN.length())); + } catch (final NumberFormatException e) { + return; + } + if (frameNum < 0) { + frameNum *= -1; + } + if (customFrameCount.containsKey(resnameWN) == false + || customFrameCount.get(resnameWN) < frameNum) { + customFrameCount.put(resnameWN, frameNum); + } + } + + public Font loadFont(final String resname, final String file, int size, + final int color) { + size /= Config.getTextureQuality(); + final BitmapTextureAtlas texture = new BitmapTextureAtlas(512, 512, + TextureOptions.BILINEAR_PREMULTIPLYALPHA); + Font font; + if (file == null) { + font = new Font(texture, Typeface.create(Typeface.DEFAULT, + Typeface.NORMAL), size, true, color); + } else { + font = FontFactory.createFromAsset(texture, context, "fonts/" + + file, size, true, color); + } + engine.getTextureManager().loadTexture(texture); + engine.getFontManager().loadFont(font); + fonts.put(resname, font); + return font; + } + + public StrokeFont loadStrokeFont(final String resname, final String file, + int size, final int color1, final int color2) { + size /= Config.getTextureQuality(); + final BitmapTextureAtlas texture = new BitmapTextureAtlas(512, 256, + TextureOptions.BILINEAR_PREMULTIPLYALPHA); + StrokeFont font; + if (file == null) { + font = new StrokeFont(texture, Typeface.create(Typeface.DEFAULT, + Typeface.NORMAL), size, true, color1, + Config.getTextureQuality() == 1 ? 2 : 0.75f, color2); + } else { + font = FontFactory.createStrokeFromAsset(texture, context, "fonts/" + + file, size, true, color1, 2 / Config.getTextureQuality(), + color2); + } + engine.getTextureManager().loadTexture(texture); + engine.getFontManager().loadFont(font); + fonts.put(resname, font); + return font; + } + + public Font getFont(final String resname) { + if (fonts.containsKey(resname) == false) { + loadFont(resname, null, 35, Color.WHITE); + } + return fonts.get(resname); + } + + public TextureRegion loadTexture(final String resname, final String file, + final boolean external, final TextureOptions opt) { + return loadTexture(resname, file, external, opt, this.engine); + } + + public TextureRegion loadTexture(final String resname, final String file, + final boolean external) { + return loadTexture(resname, file, external, TextureOptions.BILINEAR, this.engine); + } + + public TextureRegion loadTexture(final String resname, final String file, + final boolean external, Engine engine) { + return loadTexture(resname, file, external, TextureOptions.BILINEAR, engine); + } + + public TextureRegion loadBackground(final String file) { + return loadBackground(file, this.engine); + } + + public TextureRegion loadBackground(final String file, Engine engine) { + if (textures.containsKey("::background")) { + engine.getTextureManager().unloadTexture( + textures.get("::background").getTexture()); + } + if (file == null) { + return null; + } + int tw = 16, th = 16; + TextureRegion region; + final ScaledBitmapSource source = new ScaledBitmapSource(new File(file)); + if (source.getWidth() == 0 || source.getHeight() == 0) { + return null; + } + while (tw < source.getWidth()) { + tw *= 2; + } + while (th < source.getHeight()) { + th *= 2; + } + if (source.preload() == false) { + textures.put("::background", textures.get("menu-background")); + return textures.get("::background"); + } + final BitmapTextureAtlas tex = new BitmapTextureAtlas(tw, th, + TextureOptions.BILINEAR); + region = TextureRegionFactory + .createFromSource(tex, source, 0, 0, false); + engine.getTextureManager().loadTexture(tex); + textures.put("::background", region); + return region; + } + + public TextureRegion loadTexture(final String resname, final String file, + final boolean external, final TextureOptions opt, Engine engine) { + int tw = 4, th = 4; + TextureRegion region; + if (external) { + final File texFile = new File(file); + if (texFile.exists() == false) { + return textures.values().iterator().next(); + } + final QualityFileBitmapSource source = new QualityFileBitmapSource( + texFile); + if (source.getWidth() == 0 || source.getHeight() == 0) { + return null; + } + while (tw < source.getWidth()) { + tw *= 2; + } + while (th < source.getHeight()) { + th *= 2; + } + + int errorCount = 0; + while (source.preload() == false && errorCount < 3) { + errorCount++; + } + if (errorCount >= 3) { + return null; + } + final BitmapTextureAtlas tex = new BitmapTextureAtlas(tw, th, opt); + region = TextureRegionFactory.createFromSource(tex, source, 0, 0, + false); + engine.getTextureManager().loadTexture(tex); + textures.put(resname, region); + } else { + final QualityAssetBitmapSource source; + + try { + source = new QualityAssetBitmapSource( + context, file); + } catch (NullPointerException e) { + return textures.values().iterator().next(); + } + + if (source.getWidth() == 0 || source.getHeight() == 0) { + return null; + } + while (tw < source.getWidth()) { + tw *= 2; + } + while (th < source.getHeight()) { + th *= 2; + } + int errorCount = 0; + while (source.preload() == false && errorCount < 3) { + errorCount++; + } + if (errorCount >= 3) { + return null; + } + final BitmapTextureAtlas tex = new BitmapTextureAtlas(tw, th, opt); + region = TextureRegionFactory.createFromSource(tex, source, 0, 0, + false); + engine.getTextureManager().loadTexture(tex); + textures.put(resname, region); + } + + if (region.getWidth() > 1) { + region.setWidth(region.getWidth() - 1); + } + if (region.getHeight() > 1) { + region.setHeight(region.getHeight() - 1); + } + + + return region; + } + + public TextureRegion loadHighQualityAsset(final String resname, + final String file) { + int tw = 16, th = 16; + TextureRegion region; + + final AssetBitmapTextureAtlasSource source = new AssetBitmapTextureAtlasSource( + context, file); + if (source.getWidth() == 0 || source.getHeight() == 0) { + return null; + } + while (tw < source.getWidth()) { + tw *= 2; + } + while (th < source.getHeight()) { + th *= 2; + } + final BitmapTextureAtlas tex = new BitmapTextureAtlas(tw, th, + TextureOptions.BILINEAR); + region = TextureRegionFactory + .createFromSource(tex, source, 0, 0, false); + engine.getTextureManager().loadTexture(tex); + textures.put(resname, region); + //region.setWidth(region.getWidth() - 1); + //region.setHeight(region.getHeight() - 1); + + return region; + } + + public TextureRegion loadHighQualityFile(final String resname, + final File file) { + int tw = 16, th = 16; + TextureRegion region; + + final FileBitmapTextureAtlasSource source = new FileBitmapTextureAtlasSource(file); + if (source.getWidth() == 0 || source.getHeight() == 0) { + return null; + } + while (tw < source.getWidth()) { + tw *= 2; + } + while (th < source.getHeight()) { + th *= 2; + } + final BitmapTextureAtlas tex = new BitmapTextureAtlas(tw, th, + TextureOptions.BILINEAR); + region = TextureRegionFactory + .createFromSource(tex, source, 0, 0, false); + engine.getTextureManager().loadTexture(tex); + textures.put(resname, region); + region.setWidth(region.getWidth() - 1); + region.setHeight(region.getHeight() - 1); + return region; + } + + public void loadHighQualityFileUnderFolder(File folder) { + File[] files = FileUtils.listFiles(folder, new String[]{ + ".png", ".jpg", ".bmp"}); + for (File file : files) { + if (file.isDirectory()) { + loadHighQualityFileUnderFolder(file); + } else { + Log.i("texture", "load: " + file.getPath()); + loadHighQualityFile(file.getPath(), file); + } + } + } + + public TextureRegion getTexture(final String resname) { + if (SkinManager.isSkinEnabled() && customTextures.containsKey(resname)) { + return customTextures.get(resname); + } + if (textures.containsKey(resname) == false) { + Debug.i("Loading texture: " + resname); + return loadTexture(resname, "gfx/" + resname + ".png", false); + } + return textures.get(resname); + } + + public TextureRegion getTextureIfLoaded(final String resname) { + if (textures.containsKey(resname)/* + * && + * textures.get(resname).getTexture(). + * isLoadedToHardware() + */) { + return textures.get(resname); + } + return null; + } + + public boolean isTextureLoaded(final String resname) { + return textures.containsKey(resname); + } + + public BassSoundProvider loadSound(final String resname, final String file, + final boolean external) { + BassSoundProvider snd = new BassSoundProvider(); + if (external) { + //若是来自储存文件 + try { + if (!snd.prepare(file)) { + // 外部文件加载失败尝试自带皮肤 + String shortName = file.substring(file.lastIndexOf("/") + 1); + if (!snd.prepare(context.getAssets(), "sfx/" + shortName)) { + return null; + } + } + } catch (final Exception e) { + Debug.e("ResourceManager.loadSoundFromExternal: " + e.getMessage(), e); + return null; + } + } else { + //若是没有自定义音效,则使用自带音效 + try { + if (!snd.prepare(context.getAssets(), file)) { + return null; + } + } catch (final Exception e) { + Debug.e("ResourceManager.loadSound: " + e.getMessage(), e); + return null; + } + } + + sounds.put(resname, snd); + + return snd; + } + + public BassSoundProvider getSound(final String resname) { + return sounds.get(resname); + } + + public void loadCustomSound(final File file) { + BassSoundProvider snd = new BassSoundProvider(); + String resName = file.getName(); + resName = resName.substring(0, resName.length() - 4); + if (resName.length() == 0) { + return; + } + Pattern pattern = Pattern.compile("([^\\d\\.]+)"); + Matcher matcher = pattern.matcher(resName); + if (matcher.find()) { + String setName = matcher.group(1); + if (!sounds.containsKey(setName)) { + // 剔除未知的音频文件 + return; + } + } + try { + snd.prepare(file.getPath()); + } catch (final Exception e) { + Debug.e("ResourceManager.loadCustomSound: " + e.getMessage(), e); + return; + } + + customSounds.put(resName, snd); + } + + public BassSoundProvider getCustomSound(final String resname, final int set) { + if (!SkinManager.isSkinEnabled()) { + return getSound(resname); + } + if (set >= 2) { + String fullName = resname + String.valueOf(set); + if (customSounds.containsKey(fullName)) { + return customSounds.get(fullName); + } else { + return sounds.get(resname); + } + } + if (customSounds.containsKey(resname)) { + return customSounds.get(resname); + } + + return sounds.get(resname); + } + + public void loadCustomTexture(final File file) { + String resname = file.getName(); + resname = resname.substring(0, resname.length() - 4).toLowerCase(); + boolean multiframe = false; + + String delimiter = "-"; + + if (Character.isDigit(resname.charAt(resname.length() - 1))) { + + String resnameWN; + if (resname.contains("-") == false) { + resnameWN = resname.substring(0, resname.length() - 1); + } else { + resnameWN = resname.substring(0, resname.lastIndexOf('-')); + } + + if (textures.containsKey(resname) == false + && SkinManager.getFrames(resnameWN) == 0) { + return; + } + + if (textures.containsKey(resnameWN) + || textures.containsKey(resnameWN + "-0") + || textures.containsKey(resnameWN + "0")) { + int frameNum = Integer.parseInt(resname.substring(resnameWN + .length())); + if (frameNum < 0) { + frameNum *= -1; + } + if (customFrameCount.containsKey(resnameWN) == false + || customFrameCount.get(resnameWN) < frameNum) { + customFrameCount.put(resnameWN, frameNum); + } + } + } else if (textures.containsKey(resname) == false) { + + if (textures.containsKey(resname + "-0") || textures.containsKey(resname + "0")) { + if (textures.containsKey(resname + "0")) + delimiter = ""; + if (SkinManager.getFrames(resname) != 0) { + customFrameCount.put(resname, 1); + } + multiframe = true; + } else { + return; + } + } + int tw = 16, th = 16; + final QualityFileBitmapSource source = new QualityFileBitmapSource(file); + while (tw < source.getWidth()) { + tw *= 2; + } + while (th < source.getHeight()) { + th *= 2; + } + if (source.preload() == false) { + return; + } + final BitmapTextureAtlas tex = new BitmapTextureAtlas(tw, th, + TextureOptions.BILINEAR); + final TextureRegion region = TextureRegionFactory.createFromSource(tex, + source, 0, 0, false); + // engine.getTextureManager().unloadTexture(textures.get(resname).getTexture()); + engine.getTextureManager().loadTexture(tex); + if (region.getWidth() > 1) { + region.setWidth(region.getWidth() - 1); + } + if (region.getHeight() > 1) { + region.setHeight(region.getHeight() - 1); + } + if (multiframe) { + int i = 0; + while (textures.containsKey(resname + delimiter + i)) { + customTextures.put(resname + delimiter + i, region); + i++; + } + } else { + customTextures.put(resname, region); + + if (resname.equals("hitcircle")) { + if (!customTextures.containsKey("sliderstartcircle")) { + customTextures.put("sliderstartcircle", region); + } + + if (!customTextures.containsKey("sliderendcircle")) { + customTextures.put("sliderendcircle", region); + } + } + + if (resname.equals("hitcircleoverlay")) { + if (!customTextures.containsKey("sliderstartcircleoverlay")) { + customTextures.put("sliderstartcircleoverlay", region); + } + + if (!customTextures.containsKey("sliderendcircleoverlay")) { + customTextures.put("sliderendcircleoverlay", region); + } + } + } + } + + public void unloadTexture(final String name) { + if (textures.get(name) != null) { + engine.getTextureManager().unloadTexture( + textures.get(name).getTexture()); + textures.remove(name); + Debug.i("Texture \"" + name + "\"unloaded"); + } + } + + public void initSecurityUtils() { + SecurityUtils.getAppSignature(context, context.getPackageName()); + } + + public void clearCustomResources() { + for (final BassSoundProvider s : customSounds.values()) { + s.free(); + } + final Set texnames = customTextures.keySet(); + for (final String s : texnames) { + if (customTextures.get(s).getTexture().isLoadedToHardware()) { + engine.getTextureManager().unloadTexture( + customTextures.get(s).getTexture()); + // engine.getTextureManager().loadTexture(textures.get(s).getTexture()); + } + } + customTextures.clear(); + customSounds.clear(); + customFrameCount.clear(); + } + + public int getFrameCount(final String texname) { + if (customFrameCount.containsKey(texname) == false) { + return -1; + } else { + return customFrameCount.get(texname); + } + } + + public void checkSpinnerTextures() { + final String[] names = {"spinner-background", "spinner-circle", + "spinner-metre", "spinner-approachcircle", "spinner-spin"}; + for (final String s : names) { + if (textures != null + && textures.get(s) != null + && textures.get(s).getTexture() != null + && !textures.get(s).getTexture().isLoadedToHardware()) { + engine.getTextureManager().reloadTextures(); + break; + } + } + } + + public void checkEvoSpinnerTextures() { + final String[] names = { + "spinner-bottom", + "spinner-top", + "spinner-glow", + "spinner-middle", + "spinner-middle2", + "spinner-spin", + "spinner-clear" + }; + for (final String s : names) { + if (textures != null + && textures.get(s) != null + && textures.get(s).getTexture() != null + && !textures.get(s).getTexture().isLoadedToHardware()) { + engine.getTextureManager().reloadTextures(); + break; + } + } + } } diff --git a/src/ru/nsu/ccfit/zuev/osu/SkinJson.java b/src/ru/nsu/ccfit/zuev/osu/SkinJson.java index 2a9959b4..3d818477 100644 --- a/src/ru/nsu/ccfit/zuev/osu/SkinJson.java +++ b/src/ru/nsu/ccfit/zuev/osu/SkinJson.java @@ -16,250 +16,250 @@ public class SkinJson { - private static SkinJson skinJson = new SkinJson(); - private boolean forceOverrideComboColor = false; - private ArrayList comboColor; - private RGBColor sliderBorderColor = null; - private boolean sliderFollowComboColor = true; - private RGBColor sliderBodyColor; - private float sliderBodyBaseAlpha = 0.7f; - private boolean limitComboTextLength = false; - private float comboTextScale = 1; - private boolean disableKiai = false; - private float sliderBodyWidth = 61; - private float sliderBorderWidth = 5.2f; - private int sliderType = 1; - private boolean sliderHintEnable = false; - private float sliderHintWidth = 3; - private float sliderHintAlpha = 0; - private RGBColor sliderHintColor; - private float sliderHintShowMinLength = 300; - private boolean useNewLayout = false; - private HashMap layoutData = new HashMap<>(); - private HashMap colorData = new HashMap<>(); - - public static SkinJson get() { - return skinJson; - } - - private static RGBColor parseColor(JSONObject data, String name, RGBColor fallback) { - return data.optString(name, null) == null ? - fallback : RGBColor.hex2Rgb(data.optString(name)); - } - - public static String readFull(File file) throws IOException { - BufferedSource source = Okio.buffer(Okio.source(file)); - String result = source.readUtf8(); - source.close(); - return result; - } - - public float getComboTextScale() { - return comboTextScale; - } - - public boolean isUseNewLayout() { - return useNewLayout; - } - - public boolean isSliderHintEnable() { - return sliderHintEnable; - } - - public float getSliderHintAlpha() { - return sliderHintAlpha; - } - - public float getSliderHintWidth() { - return sliderHintWidth; - } - - public RGBColor getSliderHintColor() { - return sliderHintColor; - } - - public float getSliderHintShowMinLength() { - return sliderHintShowMinLength; - } - - public float getSliderBodyWidth() { - return sliderBodyWidth; - } - - public float getSliderBorderWidth() { - return sliderBorderWidth; - } - - public boolean isDisableKiai() { - return disableKiai; - } - - public boolean isLimitComboTextLength() { - return limitComboTextLength; - } - - public float getSliderBodyBaseAlpha() { - return sliderBodyBaseAlpha; - } - - public boolean isForceOverrideComboColor() { - return forceOverrideComboColor; - } - - public ArrayList getComboColor() { - if (comboColor == null) { - comboColor = new ArrayList<>(); - comboColor.add(RGBColor.hex2Rgb("#FFFFFF")); - } - return comboColor; - } - - public boolean isForceOverrideSliderBorderColor() { - return sliderBorderColor != null; - } - - public RGBColor getSliderBorderColor() { - return sliderBorderColor; - } - - public boolean isSliderFollowComboColor() { - return sliderFollowComboColor; - } - - public RGBColor getSliderBodyColor() { - return sliderBodyColor; - } - - public Layout getLayout(String name) { - return layoutData.get(name); - } - - public RGBColor getColor(String name, RGBColor fallback) { - RGBColor color = colorData.get(name); - return color == null ? fallback : color; - } - - public void reset() { - layoutData.clear(); - colorData.clear(); - } - - public void loadSkinJson(JSONObject json) { - reset(); - load("ComboColor", json, this::loadComboColorSetting); - load("Slider", json, this::loadSlider); - load("Utils", json, this::loadUtils); - load("Layout", json, this::loadLayout); - load("Color", json, this::loadColor); - } - - public void loadSlider(JSONObject data) { - sliderBodyWidth = (float) data.optDouble("sliderBodyWidth", 61); - sliderBorderWidth = (float) data.optDouble("sliderBorderWidth", 5.2f); - - sliderBodyBaseAlpha = (float) data.optDouble("sliderBodyBaseAlpha", 0.7f); - - sliderFollowComboColor = data.optBoolean("sliderFollowComboColor", true); - sliderBodyColor = data.optString("sliderBodyColor", null) == null ? - RGBColor.hex2Rgb("#FFFFFF") : RGBColor.hex2Rgb(data.optString("sliderBodyColor")); - - sliderBorderColor = data.optString("sliderBorderColor", null) == null ? - null : RGBColor.hex2Rgb(data.optString("sliderBorderColor")); - - sliderHintEnable = data.optBoolean("sliderHintEnable", false); - sliderHintAlpha = (float) data.optDouble("sliderHintAlpha", 0.3f); - sliderHintColor = parseColor(data, "sliderHintColor", null); - sliderHintWidth = (float) data.optDouble("sliderHintWidth", 3); - sliderHintShowMinLength = (float) data.optDouble("sliderHintShowMinLength", 300); - } - - public void loadColor(JSONObject jsonObject) { - JSONArray names = jsonObject.names(); - if (names == null) return; - for (int i = 0; i < names.length(); i++) { - colorData.put(names.optString(i), RGBColor.hex2Rgb(jsonObject.optString(names.optString(i)))); - } - } - - public void loadLayout(JSONObject jsonObject) { - useNewLayout = jsonObject.optBoolean("useNewLayout", false); - JSONArray names = jsonObject.names(); - if (names == null) return; - for (int i = 0; i < names.length(); i++) { - if (names.optString(i).equals("useNewLayout")) { - continue; - } - putLayout(names.optString(i), jsonObject.optJSONObject(names.optString(i))); - } - } - - public void putLayout(String name, JSONObject object) { - layoutData.put(name, Layout.load(object)); - } - - public void load(String tag, JSONObject data, Consumer consumer) { - JSONObject object = data.optJSONObject(tag); - if (object == null) { - object = new JSONObject(); - } - consumer.consume(object); - } - - public void loadComboColorSetting(JSONObject data) { - forceOverrideComboColor = data.optBoolean("forceOverride", false); - comboColor = new ArrayList<>(); - JSONArray array = data.optJSONArray("colors"); - if (array == null || array.length() == 0) { - comboColor.add(RGBColor.hex2Rgb("#FFFFFF")); - } else { - for (int i = 0; i < array.length(); i++) { - comboColor.add(RGBColor.hex2Rgb(array.optString(i, "#FFFFFF"))); - } - } - } - - public void loadUtils(JSONObject data) { - limitComboTextLength = data.optBoolean("limitComboTextLength", false); - disableKiai = data.optBoolean("disableKiai", false); - comboTextScale = (float) data.optDouble("comboTextScale", 1); - } - - public static class SliderType { - public static final int FLAT = 1; - public static final int STABLE = 2; - } - - public static class Layout { - - public JSONObject property; - - public float width, height, xOffset, yOffset; - - public float scale = 1; - - public static Layout load(JSONObject object) { - Layout layout = new Layout(); - layout.property = object; - layout.width = (float) object.optDouble("w", -1); - layout.height = (float) object.optDouble("h", -1); - layout.xOffset = (float) object.optDouble("x", 0); - layout.yOffset = (float) object.optDouble("y", 0); - layout.scale = (float) object.optDouble("scale", -1); - return layout; - } - - public void baseApply(Sprite entity) { - entity.setPosition(xOffset, yOffset); - if (scale != -1) { - entity.setScale(scale); - } - if (width != -1) { - entity.setWidth(width); - } - if (height != -1) { - entity.setHeight(height); - } - } - - } + private static SkinJson skinJson = new SkinJson(); + private boolean forceOverrideComboColor = false; + private ArrayList comboColor; + private RGBColor sliderBorderColor = null; + private boolean sliderFollowComboColor = true; + private RGBColor sliderBodyColor; + private float sliderBodyBaseAlpha = 0.7f; + private boolean limitComboTextLength = false; + private float comboTextScale = 1; + private boolean disableKiai = false; + private float sliderBodyWidth = 61; + private float sliderBorderWidth = 5.2f; + private int sliderType = 1; + private boolean sliderHintEnable = false; + private float sliderHintWidth = 3; + private float sliderHintAlpha = 0; + private RGBColor sliderHintColor; + private float sliderHintShowMinLength = 300; + private boolean useNewLayout = false; + private HashMap layoutData = new HashMap<>(); + private HashMap colorData = new HashMap<>(); + + public static SkinJson get() { + return skinJson; + } + + private static RGBColor parseColor(JSONObject data, String name, RGBColor fallback) { + return data.optString(name, null) == null ? + fallback : RGBColor.hex2Rgb(data.optString(name)); + } + + public static String readFull(File file) throws IOException { + BufferedSource source = Okio.buffer(Okio.source(file)); + String result = source.readUtf8(); + source.close(); + return result; + } + + public float getComboTextScale() { + return comboTextScale; + } + + public boolean isUseNewLayout() { + return useNewLayout; + } + + public boolean isSliderHintEnable() { + return sliderHintEnable; + } + + public float getSliderHintAlpha() { + return sliderHintAlpha; + } + + public float getSliderHintWidth() { + return sliderHintWidth; + } + + public RGBColor getSliderHintColor() { + return sliderHintColor; + } + + public float getSliderHintShowMinLength() { + return sliderHintShowMinLength; + } + + public float getSliderBodyWidth() { + return sliderBodyWidth; + } + + public float getSliderBorderWidth() { + return sliderBorderWidth; + } + + public boolean isDisableKiai() { + return disableKiai; + } + + public boolean isLimitComboTextLength() { + return limitComboTextLength; + } + + public float getSliderBodyBaseAlpha() { + return sliderBodyBaseAlpha; + } + + public boolean isForceOverrideComboColor() { + return forceOverrideComboColor; + } + + public ArrayList getComboColor() { + if (comboColor == null) { + comboColor = new ArrayList<>(); + comboColor.add(RGBColor.hex2Rgb("#FFFFFF")); + } + return comboColor; + } + + public boolean isForceOverrideSliderBorderColor() { + return sliderBorderColor != null; + } + + public RGBColor getSliderBorderColor() { + return sliderBorderColor; + } + + public boolean isSliderFollowComboColor() { + return sliderFollowComboColor; + } + + public RGBColor getSliderBodyColor() { + return sliderBodyColor; + } + + public Layout getLayout(String name) { + return layoutData.get(name); + } + + public RGBColor getColor(String name, RGBColor fallback) { + RGBColor color = colorData.get(name); + return color == null ? fallback : color; + } + + public void reset() { + layoutData.clear(); + colorData.clear(); + } + + public void loadSkinJson(JSONObject json) { + reset(); + load("ComboColor", json, this::loadComboColorSetting); + load("Slider", json, this::loadSlider); + load("Utils", json, this::loadUtils); + load("Layout", json, this::loadLayout); + load("Color", json, this::loadColor); + } + + public void loadSlider(JSONObject data) { + sliderBodyWidth = (float) data.optDouble("sliderBodyWidth", 61); + sliderBorderWidth = (float) data.optDouble("sliderBorderWidth", 5.2f); + + sliderBodyBaseAlpha = (float) data.optDouble("sliderBodyBaseAlpha", 0.7f); + + sliderFollowComboColor = data.optBoolean("sliderFollowComboColor", true); + sliderBodyColor = data.optString("sliderBodyColor", null) == null ? + RGBColor.hex2Rgb("#FFFFFF") : RGBColor.hex2Rgb(data.optString("sliderBodyColor")); + + sliderBorderColor = data.optString("sliderBorderColor", null) == null ? + null : RGBColor.hex2Rgb(data.optString("sliderBorderColor")); + + sliderHintEnable = data.optBoolean("sliderHintEnable", false); + sliderHintAlpha = (float) data.optDouble("sliderHintAlpha", 0.3f); + sliderHintColor = parseColor(data, "sliderHintColor", null); + sliderHintWidth = (float) data.optDouble("sliderHintWidth", 3); + sliderHintShowMinLength = (float) data.optDouble("sliderHintShowMinLength", 300); + } + + public void loadColor(JSONObject jsonObject) { + JSONArray names = jsonObject.names(); + if (names == null) return; + for (int i = 0; i < names.length(); i++) { + colorData.put(names.optString(i), RGBColor.hex2Rgb(jsonObject.optString(names.optString(i)))); + } + } + + public void loadLayout(JSONObject jsonObject) { + useNewLayout = jsonObject.optBoolean("useNewLayout", false); + JSONArray names = jsonObject.names(); + if (names == null) return; + for (int i = 0; i < names.length(); i++) { + if (names.optString(i).equals("useNewLayout")) { + continue; + } + putLayout(names.optString(i), jsonObject.optJSONObject(names.optString(i))); + } + } + + public void putLayout(String name, JSONObject object) { + layoutData.put(name, Layout.load(object)); + } + + public void load(String tag, JSONObject data, Consumer consumer) { + JSONObject object = data.optJSONObject(tag); + if (object == null) { + object = new JSONObject(); + } + consumer.consume(object); + } + + public void loadComboColorSetting(JSONObject data) { + forceOverrideComboColor = data.optBoolean("forceOverride", false); + comboColor = new ArrayList<>(); + JSONArray array = data.optJSONArray("colors"); + if (array == null || array.length() == 0) { + comboColor.add(RGBColor.hex2Rgb("#FFFFFF")); + } else { + for (int i = 0; i < array.length(); i++) { + comboColor.add(RGBColor.hex2Rgb(array.optString(i, "#FFFFFF"))); + } + } + } + + public void loadUtils(JSONObject data) { + limitComboTextLength = data.optBoolean("limitComboTextLength", false); + disableKiai = data.optBoolean("disableKiai", false); + comboTextScale = (float) data.optDouble("comboTextScale", 1); + } + + public static class SliderType { + public static final int FLAT = 1; + public static final int STABLE = 2; + } + + public static class Layout { + + public JSONObject property; + + public float width, height, xOffset, yOffset; + + public float scale = 1; + + public static Layout load(JSONObject object) { + Layout layout = new Layout(); + layout.property = object; + layout.width = (float) object.optDouble("w", -1); + layout.height = (float) object.optDouble("h", -1); + layout.xOffset = (float) object.optDouble("x", 0); + layout.yOffset = (float) object.optDouble("y", 0); + layout.scale = (float) object.optDouble("scale", -1); + return layout; + } + + public void baseApply(Sprite entity) { + entity.setPosition(xOffset, yOffset); + if (scale != -1) { + entity.setScale(scale); + } + if (width != -1) { + entity.setWidth(width); + } + if (height != -1) { + entity.setHeight(height); + } + } + + } } diff --git a/src/ru/nsu/ccfit/zuev/osu/SkinManager.java b/src/ru/nsu/ccfit/zuev/osu/SkinManager.java index dc41da80..aeefbdef 100644 --- a/src/ru/nsu/ccfit/zuev/osu/SkinManager.java +++ b/src/ru/nsu/ccfit/zuev/osu/SkinManager.java @@ -7,120 +7,120 @@ import ru.nsu.ccfit.zuev.osu.helper.FileUtils; public class SkinManager { - private static SkinManager instance = new SkinManager(); - private static Map frameCount = new HashMap(); - private static Map stdframeCount = new HashMap(); - private static boolean skinEnabled = true; - - static { - stdframeCount.put("sliderb", 10); - stdframeCount.put("followpoint", 1); - stdframeCount.put("scorebar-colour", 4); - stdframeCount.put("play-skip", 1); - stdframeCount.put("sliderfollowcircle", 1); - frameCount.putAll(stdframeCount); - } - - private final RGBColor sliderColor = new RGBColor(1, 1, 1); - private String skinname = ""; - - private SkinManager() { - - } - - public static SkinManager getInstance() { - return instance; - } - - public static boolean isSkinEnabled() { - return skinEnabled; - } - - public static void setSkinEnabled(final boolean skinEnabled) { - SkinManager.skinEnabled = skinEnabled; - } - - public static int getFrames(final String texname) { - if (frameCount.containsKey(texname) == false) { - return 0; - } - return frameCount.get(texname); - } - - public static void setFrames(final String texname, final int frames) { - frameCount.put(texname, frames); - } - - public RGBColor getSliderColor() { - return sliderColor; - } - - public void presetFrameCount() { - stdframeCount.put("sliderb", 10); - stdframeCount.put("followpoint", 1); - stdframeCount.put("scorebar-colour", 4); - stdframeCount.put("play-skip", 1); - stdframeCount.put("sliderfollowcircle", 1); - - for (final String s : stdframeCount.keySet()) { - final int fcount = ResourceManager.getInstance().getFrameCount(s); - if (fcount >= 0) { - stdframeCount.put(s, fcount); - } - } - frameCount.clear(); - frameCount.putAll(stdframeCount); - } - - public void loadBeatmapSkin(final String beatmapFolder) { - skinEnabled = true; - if (skinname.equals(beatmapFolder)) { - return; - } - clearSkin(); - skinname = beatmapFolder; - final File folderFile = new File(beatmapFolder); - File[] folderFiles = FileUtils.listFiles(folderFile, new String[]{ - ".wav", ".mp3", ".ogg", ".png", ".jpg"}); - for (final File f : folderFiles) { - if (!f.isFile()) { - continue; - } - if (Config.isUseCustomSounds() - && (f.getName().toLowerCase().matches(".*[.]wav") - || f.getName().toLowerCase().matches(".*[.]mp3") - || f.getName().toLowerCase().matches(".*[.]ogg")) - && f.length() >= 1024) { - ResourceManager.getInstance().loadCustomSound(f); - } else if (Config.isUseCustomSkins() - && (f.getName().toLowerCase().matches(".*[.]png") - || f.getName().toLowerCase().matches(".*[.]jpg"))) { - ResourceManager.getInstance().loadCustomTexture(f); - } - - } - - if (!Config.isUseCustomSkins()) return; - - for (final String s : frameCount.keySet()) { - final int fcount = ResourceManager.getInstance().getFrameCount(s); - if (fcount >= 0) { - frameCount.put(s, fcount); - } - } - } - - public void clearSkin() { - if (skinname.equals("")) { - return; - } - skinname = ""; - frameCount.put("sliderb", stdframeCount.get("sliderb")); - frameCount.put("followpoint", stdframeCount.get("followpoint")); - frameCount.put("scorebar-colour", stdframeCount.get("scorebar-colour")); - frameCount.put("play-skip", stdframeCount.get("play-skip")); - frameCount.put("sliderfollowcircle", - stdframeCount.get("sliderfollowcircle")); - ResourceManager.getInstance().clearCustomResources(); - } + private static SkinManager instance = new SkinManager(); + private static Map frameCount = new HashMap(); + private static Map stdframeCount = new HashMap(); + private static boolean skinEnabled = true; + + static { + stdframeCount.put("sliderb", 10); + stdframeCount.put("followpoint", 1); + stdframeCount.put("scorebar-colour", 4); + stdframeCount.put("play-skip", 1); + stdframeCount.put("sliderfollowcircle", 1); + frameCount.putAll(stdframeCount); + } + + private final RGBColor sliderColor = new RGBColor(1, 1, 1); + private String skinname = ""; + + private SkinManager() { + + } + + public static SkinManager getInstance() { + return instance; + } + + public static boolean isSkinEnabled() { + return skinEnabled; + } + + public static void setSkinEnabled(final boolean skinEnabled) { + SkinManager.skinEnabled = skinEnabled; + } + + public static int getFrames(final String texname) { + if (frameCount.containsKey(texname) == false) { + return 0; + } + return frameCount.get(texname); + } + + public static void setFrames(final String texname, final int frames) { + frameCount.put(texname, frames); + } + + public RGBColor getSliderColor() { + return sliderColor; + } + + public void presetFrameCount() { + stdframeCount.put("sliderb", 10); + stdframeCount.put("followpoint", 1); + stdframeCount.put("scorebar-colour", 4); + stdframeCount.put("play-skip", 1); + stdframeCount.put("sliderfollowcircle", 1); + + for (final String s : stdframeCount.keySet()) { + final int fcount = ResourceManager.getInstance().getFrameCount(s); + if (fcount >= 0) { + stdframeCount.put(s, fcount); + } + } + frameCount.clear(); + frameCount.putAll(stdframeCount); + } + + public void loadBeatmapSkin(final String beatmapFolder) { + skinEnabled = true; + if (skinname.equals(beatmapFolder)) { + return; + } + clearSkin(); + skinname = beatmapFolder; + final File folderFile = new File(beatmapFolder); + File[] folderFiles = FileUtils.listFiles(folderFile, new String[]{ + ".wav", ".mp3", ".ogg", ".png", ".jpg"}); + for (final File f : folderFiles) { + if (!f.isFile()) { + continue; + } + if (Config.isUseCustomSounds() + && (f.getName().toLowerCase().matches(".*[.]wav") + || f.getName().toLowerCase().matches(".*[.]mp3") + || f.getName().toLowerCase().matches(".*[.]ogg")) + && f.length() >= 1024) { + ResourceManager.getInstance().loadCustomSound(f); + } else if (Config.isUseCustomSkins() + && (f.getName().toLowerCase().matches(".*[.]png") + || f.getName().toLowerCase().matches(".*[.]jpg"))) { + ResourceManager.getInstance().loadCustomTexture(f); + } + + } + + if (!Config.isUseCustomSkins()) return; + + for (final String s : frameCount.keySet()) { + final int fcount = ResourceManager.getInstance().getFrameCount(s); + if (fcount >= 0) { + frameCount.put(s, fcount); + } + } + } + + public void clearSkin() { + if (skinname.equals("")) { + return; + } + skinname = ""; + frameCount.put("sliderb", stdframeCount.get("sliderb")); + frameCount.put("followpoint", stdframeCount.get("followpoint")); + frameCount.put("scorebar-colour", stdframeCount.get("scorebar-colour")); + frameCount.put("play-skip", stdframeCount.get("play-skip")); + frameCount.put("sliderfollowcircle", + stdframeCount.get("sliderfollowcircle")); + ResourceManager.getInstance().clearCustomResources(); + } } diff --git a/src/ru/nsu/ccfit/zuev/osu/StartingMapManager.java b/src/ru/nsu/ccfit/zuev/osu/StartingMapManager.java index 361da9d9..857a618d 100644 --- a/src/ru/nsu/ccfit/zuev/osu/StartingMapManager.java +++ b/src/ru/nsu/ccfit/zuev/osu/StartingMapManager.java @@ -19,95 +19,95 @@ import ru.nsu.ccfit.zuev.osuplus.R; public class StartingMapManager { - private final Activity activity; - - public StartingMapManager(final Activity activity) { - this.activity = activity; - } - - public boolean checkStartingMaps() { - final SharedPreferences prefs = PreferenceManager - .getDefaultSharedPreferences(activity); - return prefs.getBoolean("initialized", false); - } - - public void copyStartingMaps() { - if (checkStartingMaps()) { - return; - } - ToastLogger.showText("Preparing for the first launch", false); - String dirList[]; - try { - dirList = activity.getAssets().list("Songs"); - } catch (final IOException e) { - Debug.e("StartingMapManager: " + e.getMessage(), e); - return; - } - - for (final String dir : dirList) { - copyAllFiles(dir); - } - - final SharedPreferences prefs = PreferenceManager - .getDefaultSharedPreferences(activity); - final SharedPreferences.Editor editor = prefs.edit(); - editor.putBoolean("initialized", true); - editor.commit(); - } - - private void copyAllFiles(final String dirname) { - final File dir = new File(Config.getBeatmapPath() + "/" + dirname); - if (dir.exists() == false && dir.mkdirs() == false) { - ToastLogger.showText("Cannot create " + dir.getPath(), false); - return; - } - String fileList[]; - try { - fileList = activity.getAssets().list("Songs/" + dirname); - } catch (final IOException e) { - Debug.e("StartingMapManager: " + e.getMessage(), e); - return; - } - - final AssetManager mgr = activity.getAssets(); - for (final String file : fileList) { - final String fullname = "Songs/" + dirname + "/" + file; - try { - final InputStream istream = mgr.open(fullname); - copyFile(dirname + "/" + file, istream); - } catch (final IOException e) { - Debug.e("StartingMapManager: " + e.getMessage(), e); - } - } - } - - private void copyFile(final String filename, final InputStream istream) { - OutputStream out; - - try { - out = new FileOutputStream(Config.getBeatmapPath() + "/" + filename); - } catch (final FileNotFoundException e) { - ToastLogger.showText( - StringTable.format(R.string.message_error, e.getMessage()), - false); - Debug.e("StartingMapManager: " + e.getMessage(), e); - return; - } - - try { - final byte[] buffer = new byte[4096]; - int read; - while ((read = istream.read(buffer)) != -1) { - out.write(buffer, 0, read); - } - - istream.close(); - out.flush(); - out.close(); - } catch (final IOException e) { - ToastLogger.showText(e.getMessage(), false); - Debug.e("StartingMapManager: " + e.getMessage(), e); - return; - } - } + private final Activity activity; + + public StartingMapManager(final Activity activity) { + this.activity = activity; + } + + public boolean checkStartingMaps() { + final SharedPreferences prefs = PreferenceManager + .getDefaultSharedPreferences(activity); + return prefs.getBoolean("initialized", false); + } + + public void copyStartingMaps() { + if (checkStartingMaps()) { + return; + } + ToastLogger.showText("Preparing for the first launch", false); + String dirList[]; + try { + dirList = activity.getAssets().list("Songs"); + } catch (final IOException e) { + Debug.e("StartingMapManager: " + e.getMessage(), e); + return; + } + + for (final String dir : dirList) { + copyAllFiles(dir); + } + + final SharedPreferences prefs = PreferenceManager + .getDefaultSharedPreferences(activity); + final SharedPreferences.Editor editor = prefs.edit(); + editor.putBoolean("initialized", true); + editor.commit(); + } + + private void copyAllFiles(final String dirname) { + final File dir = new File(Config.getBeatmapPath() + "/" + dirname); + if (dir.exists() == false && dir.mkdirs() == false) { + ToastLogger.showText("Cannot create " + dir.getPath(), false); + return; + } + String fileList[]; + try { + fileList = activity.getAssets().list("Songs/" + dirname); + } catch (final IOException e) { + Debug.e("StartingMapManager: " + e.getMessage(), e); + return; + } + + final AssetManager mgr = activity.getAssets(); + for (final String file : fileList) { + final String fullname = "Songs/" + dirname + "/" + file; + try { + final InputStream istream = mgr.open(fullname); + copyFile(dirname + "/" + file, istream); + } catch (final IOException e) { + Debug.e("StartingMapManager: " + e.getMessage(), e); + } + } + } + + private void copyFile(final String filename, final InputStream istream) { + OutputStream out; + + try { + out = new FileOutputStream(Config.getBeatmapPath() + "/" + filename); + } catch (final FileNotFoundException e) { + ToastLogger.showText( + StringTable.format(R.string.message_error, e.getMessage()), + false); + Debug.e("StartingMapManager: " + e.getMessage(), e); + return; + } + + try { + final byte[] buffer = new byte[4096]; + int read; + while ((read = istream.read(buffer)) != -1) { + out.write(buffer, 0, read); + } + + istream.close(); + out.flush(); + out.close(); + } catch (final IOException e) { + ToastLogger.showText(e.getMessage(), false); + Debug.e("StartingMapManager: " + e.getMessage(), e); + return; + } + } } diff --git a/src/ru/nsu/ccfit/zuev/osu/ToastLogger.java b/src/ru/nsu/ccfit/zuev/osu/ToastLogger.java index 9281a4ff..d1d2770b 100644 --- a/src/ru/nsu/ccfit/zuev/osu/ToastLogger.java +++ b/src/ru/nsu/ccfit/zuev/osu/ToastLogger.java @@ -10,64 +10,64 @@ import ru.nsu.ccfit.zuev.osu.helper.StringTable; public class ToastLogger { - private static ToastLogger instance = null; - Activity activity; - String message = ""; - boolean showlong = false; - ArrayList debugLog = new ArrayList(); - float percentage; + private static ToastLogger instance = null; + Activity activity; + String message = ""; + boolean showlong = false; + ArrayList debugLog = new ArrayList(); + float percentage; - private ToastLogger(final Activity activity) { - this.activity = activity; - } + private ToastLogger(final Activity activity) { + this.activity = activity; + } - public static void init(final Activity activity) { - instance = new ToastLogger(activity); - } + public static void init(final Activity activity) { + instance = new ToastLogger(activity); + } - public static void showText(final String message, final boolean showlong) { - if (instance == null) { - return; - } + public static void showText(final String message, final boolean showlong) { + if (instance == null) { + return; + } - instance.activity.runOnUiThread(() -> - Toast.makeText(instance.activity, message, - showlong ? Toast.LENGTH_LONG : Toast.LENGTH_SHORT).show()); - } + instance.activity.runOnUiThread(() -> + Toast.makeText(instance.activity, message, + showlong ? Toast.LENGTH_LONG : Toast.LENGTH_SHORT).show()); + } - public static void showTextId(@StringRes final int resID, final boolean showlong) { - showText(StringTable.get(resID), showlong); - } + public static void showTextId(@StringRes final int resID, final boolean showlong) { + showText(StringTable.get(resID), showlong); + } - public static void addToLog(final String str) { - if (instance == null) { - return; - /* - * if (instance.debugLog.size() >= 20) instance.debugLog.remove(0); - * instance.debugLog.add(str); - */ - } - } + public static void addToLog(final String str) { + if (instance == null) { + return; + /* + * if (instance.debugLog.size() >= 20) instance.debugLog.remove(0); + * instance.debugLog.add(str); + */ + } + } - public static ArrayList getLog() { - if (instance == null) { - return null; - } - return instance.debugLog; - } + public static ArrayList getLog() { + if (instance == null) { + return null; + } + return instance.debugLog; + } - public static float getPercentage() { - if (instance == null) { - return -1; - } - return instance.percentage; - } + public static float getPercentage() { + if (instance == null) { + return -1; + } + return instance.percentage; + } - public static void setPercentage(final float perc) { - if (instance == null) { - return; - } - instance.percentage = perc; - } + public static void setPercentage(final float perc) { + if (instance == null) { + return; + } + instance.percentage = perc; + } -} \ No newline at end of file +} diff --git a/src/ru/nsu/ccfit/zuev/osu/TrackInfo.java b/src/ru/nsu/ccfit/zuev/osu/TrackInfo.java index 53e505cf..701d2f80 100644 --- a/src/ru/nsu/ccfit/zuev/osu/TrackInfo.java +++ b/src/ru/nsu/ccfit/zuev/osu/TrackInfo.java @@ -3,201 +3,201 @@ import java.io.Serializable; public class TrackInfo implements Serializable { - private static final long serialVersionUID = 2049627581836712912L; - - private String filename; - - private String publicName; - private String mode; - private String creator; - private String background = null; - private int beatmapID = 0; - private int beatmapSetID = 0; - private float difficulty; - private float hpDrain; - private float overallDifficulty; - private float approachRate; - private float circleSize; - private float bpmMax = 0; - private float bpmMin = Float.MAX_VALUE; - private long musicLength = 0; - private int hitCircleCount = 0; - private int sliderCount = 0; - private int spinnerCount = 0; - private int totalHitObjectCount = 0; - private int maxCombo = 0; - - private BeatmapInfo beatmap; - - public TrackInfo(BeatmapInfo beatmap) { - this.beatmap = beatmap; - } - - public String getFilename() { - return filename; - } - - public void setFilename(final String filename) { - this.filename = filename; - } - - public String getMode() { - return mode; - } - - public void setMode(final String mode) { - this.mode = mode; - } - - public String getCreator() { - return creator; - } - - public void setCreator(final String creator) { - this.creator = creator; - } - - public float getDifficulty() { - return difficulty; - } - - public void setDifficulty(final float difficulty) { - this.difficulty = difficulty; - } - - public String getBackground() { - return background; - } - - public void setBackground(final String background) { - this.background = background; - } - - public String getPublicName() { - return publicName; - } - - public void setPublicName(final String publicName) { - this.publicName = publicName; - } - - public BeatmapInfo getBeatmap() { - return beatmap; - } - - public void setBeatmap(BeatmapInfo beatmap) { - this.beatmap = beatmap; - } - - public float getHpDrain() { - return hpDrain; - } - - public void setHpDrain(float hpDrain) { - this.hpDrain = hpDrain; - } - - public float getOverallDifficulty() { - return overallDifficulty; - } - - public void setOverallDifficulty(float overallDifficulty) { - this.overallDifficulty = overallDifficulty; - } - - public float getApproachRate() { - return approachRate; - } - - public void setApproachRate(float approachRate) { - this.approachRate = approachRate; - } - - public float getCircleSize() { - return circleSize; - } - - public void setCircleSize(float circleSize) { - this.circleSize = circleSize; - } - - public float getBpmMax() { - return bpmMax; - } + private static final long serialVersionUID = 2049627581836712912L; + + private String filename; + + private String publicName; + private String mode; + private String creator; + private String background = null; + private int beatmapID = 0; + private int beatmapSetID = 0; + private float difficulty; + private float hpDrain; + private float overallDifficulty; + private float approachRate; + private float circleSize; + private float bpmMax = 0; + private float bpmMin = Float.MAX_VALUE; + private long musicLength = 0; + private int hitCircleCount = 0; + private int sliderCount = 0; + private int spinnerCount = 0; + private int totalHitObjectCount = 0; + private int maxCombo = 0; + + private BeatmapInfo beatmap; + + public TrackInfo(BeatmapInfo beatmap) { + this.beatmap = beatmap; + } + + public String getFilename() { + return filename; + } + + public void setFilename(final String filename) { + this.filename = filename; + } + + public String getMode() { + return mode; + } + + public void setMode(final String mode) { + this.mode = mode; + } + + public String getCreator() { + return creator; + } + + public void setCreator(final String creator) { + this.creator = creator; + } + + public float getDifficulty() { + return difficulty; + } + + public void setDifficulty(final float difficulty) { + this.difficulty = difficulty; + } + + public String getBackground() { + return background; + } + + public void setBackground(final String background) { + this.background = background; + } + + public String getPublicName() { + return publicName; + } + + public void setPublicName(final String publicName) { + this.publicName = publicName; + } + + public BeatmapInfo getBeatmap() { + return beatmap; + } + + public void setBeatmap(BeatmapInfo beatmap) { + this.beatmap = beatmap; + } + + public float getHpDrain() { + return hpDrain; + } + + public void setHpDrain(float hpDrain) { + this.hpDrain = hpDrain; + } + + public float getOverallDifficulty() { + return overallDifficulty; + } + + public void setOverallDifficulty(float overallDifficulty) { + this.overallDifficulty = overallDifficulty; + } + + public float getApproachRate() { + return approachRate; + } + + public void setApproachRate(float approachRate) { + this.approachRate = approachRate; + } + + public float getCircleSize() { + return circleSize; + } + + public void setCircleSize(float circleSize) { + this.circleSize = circleSize; + } + + public float getBpmMax() { + return bpmMax; + } - public void setBpmMax(float bpmMax) { - this.bpmMax = bpmMax; - } + public void setBpmMax(float bpmMax) { + this.bpmMax = bpmMax; + } - public float getBpmMin() { - return bpmMin; - } + public float getBpmMin() { + return bpmMin; + } - public void setBpmMin(float bpmMin) { - this.bpmMin = bpmMin; - } + public void setBpmMin(float bpmMin) { + this.bpmMin = bpmMin; + } - public long getMusicLength() { - return musicLength; - } + public long getMusicLength() { + return musicLength; + } - public void setMusicLength(long musicLength) { - this.musicLength = musicLength; - } + public void setMusicLength(long musicLength) { + this.musicLength = musicLength; + } - public int getHitCircleCount() { - return hitCircleCount; - } + public int getHitCircleCount() { + return hitCircleCount; + } - public void setHitCircleCount(int hitCircleCount) { - this.hitCircleCount = hitCircleCount; - } + public void setHitCircleCount(int hitCircleCount) { + this.hitCircleCount = hitCircleCount; + } - public int getSliderCount() { - return sliderCount; - } + public int getSliderCount() { + return sliderCount; + } - public void setSliderCount(int sliderCount) { - this.sliderCount = sliderCount; - } + public void setSliderCount(int sliderCount) { + this.sliderCount = sliderCount; + } - public int getSpinnerCount() { - return spinnerCount; - } + public int getSpinnerCount() { + return spinnerCount; + } - public void setSpinnerCount(int spinnerCount) { - this.spinnerCount = spinnerCount; - } + public void setSpinnerCount(int spinnerCount) { + this.spinnerCount = spinnerCount; + } - public int getTotalHitObjectCount() { - return totalHitObjectCount; - } + public int getTotalHitObjectCount() { + return totalHitObjectCount; + } - public void setTotalHitObjectCount(int totalHitObjectCount) { - this.totalHitObjectCount = totalHitObjectCount; - } + public void setTotalHitObjectCount(int totalHitObjectCount) { + this.totalHitObjectCount = totalHitObjectCount; + } - public int getBeatmapID() { - return beatmapID; - } + public int getBeatmapID() { + return beatmapID; + } - public void setBeatmapID(int beatmapID) { - this.beatmapID = beatmapID; - } + public void setBeatmapID(int beatmapID) { + this.beatmapID = beatmapID; + } - public int getBeatmapSetID() { - return beatmapSetID; - } + public int getBeatmapSetID() { + return beatmapSetID; + } - public void setBeatmapSetID(int beatmapSetID) { - this.beatmapSetID = beatmapSetID; - } + public void setBeatmapSetID(int beatmapSetID) { + this.beatmapSetID = beatmapSetID; + } - public int getMaxCombo() { - return maxCombo; - } + public int getMaxCombo() { + return maxCombo; + } - public void setMaxCombo(int maxCombo) { - this.maxCombo = maxCombo; - } + public void setMaxCombo(int maxCombo) { + this.maxCombo = maxCombo; + } } diff --git a/src/ru/nsu/ccfit/zuev/osu/Updater.java b/src/ru/nsu/ccfit/zuev/osu/Updater.java index 2ec2a8e9..3a6058b6 100644 --- a/src/ru/nsu/ccfit/zuev/osu/Updater.java +++ b/src/ru/nsu/ccfit/zuev/osu/Updater.java @@ -1,114 +1,114 @@ -package ru.nsu.ccfit.zuev.osu; - -import android.os.Build; - -import com.edlplan.ui.fragment.LoadingFragment; -import com.edlplan.ui.fragment.UpdateDialogFragment; - -import com.google.android.material.snackbar.Snackbar; - -import com.google.gson.Gson; - -import java.io.IOException; - -import okhttp3.ResponseBody; -import okhttp3.Request; - -import org.anddev.andengine.util.Debug; - -import java.util.ArrayList; -import java.util.List; - -import ru.nsu.ccfit.zuev.osu.async.AsyncTaskLoader; -import ru.nsu.ccfit.zuev.osu.async.OsuAsyncCallback; -import ru.nsu.ccfit.zuev.osu.helper.StringTable; -import ru.nsu.ccfit.zuev.osu.model.vo.GithubReleaseVO; -import ru.nsu.ccfit.zuev.osu.model.vo.GithubReleaseVO.Asset; -import ru.nsu.ccfit.zuev.osu.model.vo.VersionCodeVO; -import ru.nsu.ccfit.zuev.osu.online.OnlineManager; -import ru.nsu.ccfit.zuev.osuplus.R; - -public class Updater { - - private boolean newUpdate = false; - private String changelogMsg, downloadUrl; - private LoadingFragment loadingFragment; - private MainActivity mActivity; - - private static Updater instance = new Updater(); - - private Updater() { - mActivity = GlobalManager.getInstance().getMainActivity(); - } - - public static Updater getInstance() { - return instance; - } - - private ResponseBody httpGet(String url) throws IOException { - Request request = new Request.Builder() - .url(url) - .build(); - return OnlineManager.client.newCall(request).execute().body(); - } - - public void checkForUpdates() { - new AsyncTaskLoader().execute(new OsuAsyncCallback() { - public void run() { - try { - mActivity.runOnUiThread(() -> { - Snackbar.make(mActivity.findViewById(android.R.id.content), - StringTable.get(R.string.update_info_checking), 1500).show(); - if(loadingFragment == null) { - loadingFragment = new LoadingFragment(); - loadingFragment.show(); - } - }); - - ResponseBody response = httpGet("https://api.github.com/repos/kairusds-testing/osu-droid/releases"); - GithubReleaseVO updateInfo = new Gson().fromJson(response.string(), GithubReleaseVO[].class)[0]; - Debug.i("updateInfo body: " + updateInfo.getBody()); - ArrayList assets = new ArrayList(updateInfo.getAssets()); - Debug.i("assets size: " + String.valueOf(assets.size())); - - for(Asset asset : assets) { - // equal comparison doesn't seem to work for some reason - if(asset.getName().endsWith("info.json") && !newUpdate) { - ResponseBody versionResponse = httpGet(asset.getBrowser_download_url()); - VersionCodeVO updateVersionCode = new Gson().fromJson(versionResponse.string(), VersionCodeVO.class); - - if(updateVersionCode.getValue() > mActivity.getVersionCode()) { - changelogMsg = updateInfo.getBody(); - newUpdate = true; - } - }else if(asset.getName().endsWith(".apk") && newUpdate) { - downloadUrl = asset.getBrowser_download_url(); - } - } - }catch(IOException e) { - Debug.e("Updater onRun: " + e.getMessage(), e); - } - } - - public void onComplete() { - mActivity.runOnUiThread(() -> { - if(loadingFragment != null) { - loadingFragment.dismiss(); - loadingFragment = null; - } - - if(newUpdate) { - new UpdateDialogFragment() - .setChangelogMessage(changelogMsg) - .setDownloadUrl(downloadUrl) - .show(); - }else { - Snackbar.make(mActivity.findViewById(android.R.id.content), - StringTable.get(R.string.update_info_latest), 1500).show(); - } - }); - } - }); - } - -} \ No newline at end of file +package ru.nsu.ccfit.zuev.osu; + +import android.os.Build; + +import com.edlplan.ui.fragment.LoadingFragment; +import com.edlplan.ui.fragment.UpdateDialogFragment; + +import com.google.android.material.snackbar.Snackbar; + +import com.google.gson.Gson; + +import java.io.IOException; + +import okhttp3.ResponseBody; +import okhttp3.Request; + +import org.anddev.andengine.util.Debug; + +import java.util.ArrayList; +import java.util.List; + +import ru.nsu.ccfit.zuev.osu.async.AsyncTaskLoader; +import ru.nsu.ccfit.zuev.osu.async.OsuAsyncCallback; +import ru.nsu.ccfit.zuev.osu.helper.StringTable; +import ru.nsu.ccfit.zuev.osu.model.vo.GithubReleaseVO; +import ru.nsu.ccfit.zuev.osu.model.vo.GithubReleaseVO.Asset; +import ru.nsu.ccfit.zuev.osu.model.vo.VersionCodeVO; +import ru.nsu.ccfit.zuev.osu.online.OnlineManager; +import ru.nsu.ccfit.zuev.osuplus.R; + +public class Updater { + + private boolean newUpdate = false; + private String changelogMsg, downloadUrl; + private LoadingFragment loadingFragment; + private MainActivity mActivity; + + private static Updater instance = new Updater(); + + private Updater() { + mActivity = GlobalManager.getInstance().getMainActivity(); + } + + public static Updater getInstance() { + return instance; + } + + private ResponseBody httpGet(String url) throws IOException { + Request request = new Request.Builder() + .url(url) + .build(); + return OnlineManager.client.newCall(request).execute().body(); + } + + public void checkForUpdates() { + new AsyncTaskLoader().execute(new OsuAsyncCallback() { + public void run() { + try { + mActivity.runOnUiThread(() -> { + Snackbar.make(mActivity.findViewById(android.R.id.content), + StringTable.get(R.string.update_info_checking), 1500).show(); + if(loadingFragment == null) { + loadingFragment = new LoadingFragment(); + loadingFragment.show(); + } + }); + + ResponseBody response = httpGet("https://api.github.com/repos/kairusds-testing/osu-droid/releases"); + GithubReleaseVO updateInfo = new Gson().fromJson(response.string(), GithubReleaseVO[].class)[0]; + Debug.i("updateInfo body: " + updateInfo.getBody()); + ArrayList assets = new ArrayList(updateInfo.getAssets()); + Debug.i("assets size: " + String.valueOf(assets.size())); + + for(Asset asset : assets) { + // equal comparison doesn't seem to work for some reason + if(asset.getName().endsWith("info.json") && !newUpdate) { + ResponseBody versionResponse = httpGet(asset.getBrowser_download_url()); + VersionCodeVO updateVersionCode = new Gson().fromJson(versionResponse.string(), VersionCodeVO.class); + + if(updateVersionCode.getValue() > mActivity.getVersionCode()) { + changelogMsg = updateInfo.getBody(); + newUpdate = true; + } + }else if(asset.getName().endsWith(".apk") && newUpdate) { + downloadUrl = asset.getBrowser_download_url(); + } + } + }catch(IOException e) { + Debug.e("Updater onRun: " + e.getMessage(), e); + } + } + + public void onComplete() { + mActivity.runOnUiThread(() -> { + if(loadingFragment != null) { + loadingFragment.dismiss(); + loadingFragment = null; + } + + if(newUpdate) { + new UpdateDialogFragment() + .setChangelogMessage(changelogMsg) + .setDownloadUrl(downloadUrl) + .show(); + }else { + Snackbar.make(mActivity.findViewById(android.R.id.content), + StringTable.get(R.string.update_info_latest), 1500).show(); + } + }); + } + }); + } + +} diff --git a/src/ru/nsu/ccfit/zuev/osu/Utils.java b/src/ru/nsu/ccfit/zuev/osu/Utils.java index 1bff77e7..5e96543b 100644 --- a/src/ru/nsu/ccfit/zuev/osu/Utils.java +++ b/src/ru/nsu/ccfit/zuev/osu/Utils.java @@ -13,241 +13,241 @@ import ru.nsu.ccfit.zuev.osu.game.GameObjectListener; public class Utils { - private static final String FSReservedChars = "|\\?*<\":>+[]/"; - private static int accSign = 0; - private static int soundMask = 0; - - public static T[] oneObjectArray(T object, T[] ary) { - for (int i = 0; i < ary.length; i++) { - ary[i] = object; - } - return ary; - } - - public static void setAccelerometerSign(final int sign) { - accSign = sign; - } - - public static int getAccselerometerSign() { - return accSign; - } - - public static float sqr(final float x) { - return (x * x); - } - - public static PointF inter(final PointF v1, final PointF v2, - final float percent) { - return new PointF(v1.x * (1 - percent) + v2.x * percent, v1.y - * (1 - percent) + v2.y * percent); - } - - public static void putSpriteAnchorCenter(float x, float y, Sprite sprite) { - final TextureRegion tex = sprite.getTextureRegion(); - sprite.setPosition(x - tex.getWidth() / 2f, y - tex.getHeight() / 2f); - } - - public static void putSpriteAnchorCenter(PointF pos, Sprite sprite) { - final TextureRegion tex = sprite.getTextureRegion(); - sprite.setPosition(pos.x - tex.getWidth() / 2f, pos.y - tex.getHeight() / 2f); - } - - public static PointF trackToRealCoords(final PointF coords) { - final PointF pos = scaleToReal(coords); - pos.y += (Config.getRES_HEIGHT() - toRes(Constants.MAP_ACTUAL_HEIGHT)) / 2f; - pos.x += (Config.getRES_WIDTH() - toRes(Constants.MAP_ACTUAL_WIDTH)) / 2f; - if (GameHelper.isHardrock()) { - pos.y -= Config.getRES_HEIGHT() / 2; - pos.y *= -1; - pos.y += Config.getRES_HEIGHT() / 2; - } - /*if (pos.y < 18) { - pos.y = 18; - }*/ - /*if (pos.y > Config.getRES_HEIGHT() - 18) { - pos.y = Config.getRES_HEIGHT() - 18; - }*/ - return pos; - } - - public static void changeTrackToRealCoords(final PointF coords) { - final PointF pos = scaleToRealC(coords); - pos.y += (Config.getRES_HEIGHT() - toRes(Constants.MAP_ACTUAL_HEIGHT)) / 2f; - pos.x += (Config.getRES_WIDTH() - toRes(Constants.MAP_ACTUAL_WIDTH)) / 2f; - if (GameHelper.isHardrock()) { - pos.y -= Config.getRES_HEIGHT() / 2; - pos.y *= -1; - pos.y += Config.getRES_HEIGHT() / 2; - } - } - - public static PointF realToTrackCoords(final PointF coords) { - return realToTrackCoords(coords, Config.getRES_WIDTH(), Config.getRES_HEIGHT(), false); - } - - public static PointF realToTrackCoords(final PointF coords, float width, float height, boolean isOld) { - final PointF pos = new PointF(coords.x, coords.y); - if (GameHelper.isHardrock()) { - pos.y -= height / 2; - pos.y *= -1; - pos.y += height / 2; - } - pos.y -= (height - toRes((isOld ? Constants.MAP_ACTUAL_HEIGHT_OLD : Constants.MAP_ACTUAL_HEIGHT))) / 2f; - pos.x -= (width - toRes((isOld ? Constants.MAP_ACTUAL_WIDTH_OLD : Constants.MAP_ACTUAL_WIDTH))) / 2f; - return scaleToTrack(pos, isOld); - } - - public static short flipY(final short y) { - final int height = Config.getRES_HEIGHT() / 2; - return (short) (((y - height) * -1) + height); - } - - public static PointF scaleToReal(final PointF v) { - final PointF pos = new PointF(v.x, v.y); - pos.x *= toRes(Constants.MAP_ACTUAL_WIDTH) - / (float) Constants.MAP_WIDTH; - pos.y *= toRes(Constants.MAP_ACTUAL_HEIGHT) - / (float) Constants.MAP_HEIGHT; - return pos; - } - - public static PointF scaleToRealC(final PointF v) { - v.x *= toRes(Constants.MAP_ACTUAL_WIDTH) / (float) Constants.MAP_WIDTH; - v.y *= toRes(Constants.MAP_ACTUAL_HEIGHT) - / (float) Constants.MAP_HEIGHT; - return v; - } - - public static PointF scaleToTrack(final PointF v, boolean isOld) { - final PointF pos = new PointF(v.x, v.y); - pos.x *= Constants.MAP_WIDTH - / toRes((float) (isOld ? Constants.MAP_ACTUAL_WIDTH_OLD : Constants.MAP_ACTUAL_WIDTH)); - pos.y *= Constants.MAP_HEIGHT - / toRes((float) (isOld ? Constants.MAP_ACTUAL_HEIGHT_OLD : Constants.MAP_ACTUAL_HEIGHT)); - return pos; - } - - public static float direction(final float x, final float y) { - float len = (float) Math.sqrt(x * x + y * y); - if (Math.abs(len) < 0.0001f) { - return 0; - } - if (x > 0) { - len = (float) Math.asin(y / len); - } else { - len = (float) (Math.PI - Math.asin(y / len)); - } - return len; - } - - public static float direction(final PointF vector) { - return direction(vector.x, vector.y); - } - - public static float direction(final PointF v1, final PointF v2) { - return direction(v2.x - v1.x, v2.y - v1.y); - } - - public static float length(final PointF vector) { - return (float) Math.sqrt(vector.x * vector.x + vector.y * vector.y); - } - - public static PointF normalize(final PointF vector) { - final float len = length(vector); - if (Math.abs(len) < 0.0001f) { - return new PointF(0, 0); - } - return new PointF(vector.x / len, vector.y / len); - } - - public static float distance(final PointF v1, final PointF v2) { - return MathUtils.distance(v1.x, v1.y, v2.x, v2.y); - } - - public static float squaredDistance(final PointF v1, final PointF v2) { - return ((v2.x - v1.x) * (v2.x - v1.x) + (v2.y - v1.y) * (v2.y - v1.y)); - } - - public static float squaredDistance(final float v1x, final float v1y, - final float v2x, final float v2y) { - return ((v2x - v1x) * (v2x - v1x) + (v2y - v1y) * (v2y - v1y)); - } - - public static void clearSoundMask() { - soundMask = 0; - } - - public static boolean isEmpty(final String str) { - return str == null || str.isEmpty(); - } - - public static void playHitSound(final GameObjectListener listener, - final int soundId) { - playHitSound(listener, soundId, 0, 0); - } - - public static void playHitSound(final GameObjectListener listener, - final int soundId, final int sampleSet, final int addition) { - if ((soundId & 32) > 0) { - return; - } - - if ((soundId & 16) > 0 && (soundMask & 16) == 0) { - soundMask |= 16; - listener.playSound("slidertick", sampleSet, addition); - return; - } - - if ((soundMask & 1) == 0) { - soundMask |= 1; - listener.playSound("hitnormal", sampleSet, addition); - } - if ((soundId & 2) > 0 && (soundMask & 2) == 0) { - soundMask |= 2; - listener.playSound("hitwhistle", sampleSet, addition); - } - if ((soundId & 4) > 0 && (soundMask & 4) == 0) { - soundMask |= 4; - listener.playSound("hitfinish", sampleSet, addition); - } - if ((soundId & 8) > 0 && (soundMask & 8) == 0) { - soundMask |= 8; - listener.playSound("hitclap", sampleSet, addition); - } - } - - static public int toRes(final int i) { - return i / Config.getTextureQuality(); - } - - public static float toRes(final float i) { - return i / Config.getTextureQuality(); - } - - public static String toFSValidString(final String s) { - final StringBuilder nameBuilder = new StringBuilder(); - for (int i = 0; i < s.length(); i++) { - if (FSReservedChars.indexOf(s.charAt(i)) == -1) { - nameBuilder.append(s.charAt(i)); - } - } - return nameBuilder.toString(); - } - - /** - * 判断当前网络是否是wifi网络 - * - * @param context - * @return boolean - */ - public static boolean isWifi(Context context) { - ConnectivityManager connectivityManager = (ConnectivityManager) context - .getSystemService(Context.CONNECTIVITY_SERVICE); - NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo(); - if (activeNetInfo != null - && activeNetInfo.getType() == ConnectivityManager.TYPE_WIFI) { - return true; - } - return false; - } + private static final String FSReservedChars = "|\\?*<\":>+[]/"; + private static int accSign = 0; + private static int soundMask = 0; + + public static T[] oneObjectArray(T object, T[] ary) { + for (int i = 0; i < ary.length; i++) { + ary[i] = object; + } + return ary; + } + + public static void setAccelerometerSign(final int sign) { + accSign = sign; + } + + public static int getAccselerometerSign() { + return accSign; + } + + public static float sqr(final float x) { + return (x * x); + } + + public static PointF inter(final PointF v1, final PointF v2, + final float percent) { + return new PointF(v1.x * (1 - percent) + v2.x * percent, v1.y + * (1 - percent) + v2.y * percent); + } + + public static void putSpriteAnchorCenter(float x, float y, Sprite sprite) { + final TextureRegion tex = sprite.getTextureRegion(); + sprite.setPosition(x - tex.getWidth() / 2f, y - tex.getHeight() / 2f); + } + + public static void putSpriteAnchorCenter(PointF pos, Sprite sprite) { + final TextureRegion tex = sprite.getTextureRegion(); + sprite.setPosition(pos.x - tex.getWidth() / 2f, pos.y - tex.getHeight() / 2f); + } + + public static PointF trackToRealCoords(final PointF coords) { + final PointF pos = scaleToReal(coords); + pos.y += (Config.getRES_HEIGHT() - toRes(Constants.MAP_ACTUAL_HEIGHT)) / 2f; + pos.x += (Config.getRES_WIDTH() - toRes(Constants.MAP_ACTUAL_WIDTH)) / 2f; + if (GameHelper.isHardrock()) { + pos.y -= Config.getRES_HEIGHT() / 2; + pos.y *= -1; + pos.y += Config.getRES_HEIGHT() / 2; + } + /*if (pos.y < 18) { + pos.y = 18; + }*/ + /*if (pos.y > Config.getRES_HEIGHT() - 18) { + pos.y = Config.getRES_HEIGHT() - 18; + }*/ + return pos; + } + + public static void changeTrackToRealCoords(final PointF coords) { + final PointF pos = scaleToRealC(coords); + pos.y += (Config.getRES_HEIGHT() - toRes(Constants.MAP_ACTUAL_HEIGHT)) / 2f; + pos.x += (Config.getRES_WIDTH() - toRes(Constants.MAP_ACTUAL_WIDTH)) / 2f; + if (GameHelper.isHardrock()) { + pos.y -= Config.getRES_HEIGHT() / 2; + pos.y *= -1; + pos.y += Config.getRES_HEIGHT() / 2; + } + } + + public static PointF realToTrackCoords(final PointF coords) { + return realToTrackCoords(coords, Config.getRES_WIDTH(), Config.getRES_HEIGHT(), false); + } + + public static PointF realToTrackCoords(final PointF coords, float width, float height, boolean isOld) { + final PointF pos = new PointF(coords.x, coords.y); + if (GameHelper.isHardrock()) { + pos.y -= height / 2; + pos.y *= -1; + pos.y += height / 2; + } + pos.y -= (height - toRes((isOld ? Constants.MAP_ACTUAL_HEIGHT_OLD : Constants.MAP_ACTUAL_HEIGHT))) / 2f; + pos.x -= (width - toRes((isOld ? Constants.MAP_ACTUAL_WIDTH_OLD : Constants.MAP_ACTUAL_WIDTH))) / 2f; + return scaleToTrack(pos, isOld); + } + + public static short flipY(final short y) { + final int height = Config.getRES_HEIGHT() / 2; + return (short) (((y - height) * -1) + height); + } + + public static PointF scaleToReal(final PointF v) { + final PointF pos = new PointF(v.x, v.y); + pos.x *= toRes(Constants.MAP_ACTUAL_WIDTH) + / (float) Constants.MAP_WIDTH; + pos.y *= toRes(Constants.MAP_ACTUAL_HEIGHT) + / (float) Constants.MAP_HEIGHT; + return pos; + } + + public static PointF scaleToRealC(final PointF v) { + v.x *= toRes(Constants.MAP_ACTUAL_WIDTH) / (float) Constants.MAP_WIDTH; + v.y *= toRes(Constants.MAP_ACTUAL_HEIGHT) + / (float) Constants.MAP_HEIGHT; + return v; + } + + public static PointF scaleToTrack(final PointF v, boolean isOld) { + final PointF pos = new PointF(v.x, v.y); + pos.x *= Constants.MAP_WIDTH + / toRes((float) (isOld ? Constants.MAP_ACTUAL_WIDTH_OLD : Constants.MAP_ACTUAL_WIDTH)); + pos.y *= Constants.MAP_HEIGHT + / toRes((float) (isOld ? Constants.MAP_ACTUAL_HEIGHT_OLD : Constants.MAP_ACTUAL_HEIGHT)); + return pos; + } + + public static float direction(final float x, final float y) { + float len = (float) Math.sqrt(x * x + y * y); + if (Math.abs(len) < 0.0001f) { + return 0; + } + if (x > 0) { + len = (float) Math.asin(y / len); + } else { + len = (float) (Math.PI - Math.asin(y / len)); + } + return len; + } + + public static float direction(final PointF vector) { + return direction(vector.x, vector.y); + } + + public static float direction(final PointF v1, final PointF v2) { + return direction(v2.x - v1.x, v2.y - v1.y); + } + + public static float length(final PointF vector) { + return (float) Math.sqrt(vector.x * vector.x + vector.y * vector.y); + } + + public static PointF normalize(final PointF vector) { + final float len = length(vector); + if (Math.abs(len) < 0.0001f) { + return new PointF(0, 0); + } + return new PointF(vector.x / len, vector.y / len); + } + + public static float distance(final PointF v1, final PointF v2) { + return MathUtils.distance(v1.x, v1.y, v2.x, v2.y); + } + + public static float squaredDistance(final PointF v1, final PointF v2) { + return ((v2.x - v1.x) * (v2.x - v1.x) + (v2.y - v1.y) * (v2.y - v1.y)); + } + + public static float squaredDistance(final float v1x, final float v1y, + final float v2x, final float v2y) { + return ((v2x - v1x) * (v2x - v1x) + (v2y - v1y) * (v2y - v1y)); + } + + public static void clearSoundMask() { + soundMask = 0; + } + + public static boolean isEmpty(final String str) { + return str == null || str.isEmpty(); + } + + public static void playHitSound(final GameObjectListener listener, + final int soundId) { + playHitSound(listener, soundId, 0, 0); + } + + public static void playHitSound(final GameObjectListener listener, + final int soundId, final int sampleSet, final int addition) { + if ((soundId & 32) > 0) { + return; + } + + if ((soundId & 16) > 0 && (soundMask & 16) == 0) { + soundMask |= 16; + listener.playSound("slidertick", sampleSet, addition); + return; + } + + if ((soundMask & 1) == 0) { + soundMask |= 1; + listener.playSound("hitnormal", sampleSet, addition); + } + if ((soundId & 2) > 0 && (soundMask & 2) == 0) { + soundMask |= 2; + listener.playSound("hitwhistle", sampleSet, addition); + } + if ((soundId & 4) > 0 && (soundMask & 4) == 0) { + soundMask |= 4; + listener.playSound("hitfinish", sampleSet, addition); + } + if ((soundId & 8) > 0 && (soundMask & 8) == 0) { + soundMask |= 8; + listener.playSound("hitclap", sampleSet, addition); + } + } + + static public int toRes(final int i) { + return i / Config.getTextureQuality(); + } + + public static float toRes(final float i) { + return i / Config.getTextureQuality(); + } + + public static String toFSValidString(final String s) { + final StringBuilder nameBuilder = new StringBuilder(); + for (int i = 0; i < s.length(); i++) { + if (FSReservedChars.indexOf(s.charAt(i)) == -1) { + nameBuilder.append(s.charAt(i)); + } + } + return nameBuilder.toString(); + } + + /** + * 判断当前网络是否是wifi网络 + * + * @param context + * @return boolean + */ + public static boolean isWifi(Context context) { + ConnectivityManager connectivityManager = (ConnectivityManager) context + .getSystemService(Context.CONNECTIVITY_SERVICE); + NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo(); + if (activeNetInfo != null + && activeNetInfo.getType() == ConnectivityManager.TYPE_WIFI) { + return true; + } + return false; + } } diff --git a/src/ru/nsu/ccfit/zuev/osu/async/AsyncTaskLoader.java b/src/ru/nsu/ccfit/zuev/osu/async/AsyncTaskLoader.java index 8551ae44..f492fc88 100644 --- a/src/ru/nsu/ccfit/zuev/osu/async/AsyncTaskLoader.java +++ b/src/ru/nsu/ccfit/zuev/osu/async/AsyncTaskLoader.java @@ -3,28 +3,28 @@ import android.os.AsyncTask; public class AsyncTaskLoader extends - AsyncTask { + AsyncTask { - private OsuAsyncCallback[] mparams; + private OsuAsyncCallback[] mparams; - @Override - protected Boolean doInBackground(final OsuAsyncCallback... params) { - this.mparams = params; - final int count = params.length; - for (int i = 0; i < count; i++) { - params[i].run(); - } - return true; - } + @Override + protected Boolean doInBackground(final OsuAsyncCallback... params) { + this.mparams = params; + final int count = params.length; + for (int i = 0; i < count; i++) { + params[i].run(); + } + return true; + } - @Override - protected void onPostExecute(final Boolean result) { - final int count = this.mparams.length; - for (int i = 0; i < count; i++) { - this.mparams[i].onComplete(); - } - } + @Override + protected void onPostExecute(final Boolean result) { + final int count = this.mparams.length; + for (int i = 0; i < count; i++) { + this.mparams[i].onComplete(); + } + } } diff --git a/src/ru/nsu/ccfit/zuev/osu/async/OsuAsyncCallback.java b/src/ru/nsu/ccfit/zuev/osu/async/OsuAsyncCallback.java index 8af26896..10e24398 100644 --- a/src/ru/nsu/ccfit/zuev/osu/async/OsuAsyncCallback.java +++ b/src/ru/nsu/ccfit/zuev/osu/async/OsuAsyncCallback.java @@ -2,7 +2,7 @@ public interface OsuAsyncCallback { - public abstract void onComplete(); + public abstract void onComplete(); - public abstract void run(); + public abstract void run(); } diff --git a/src/ru/nsu/ccfit/zuev/osu/async/SyncTaskManager.java b/src/ru/nsu/ccfit/zuev/osu/async/SyncTaskManager.java index 760cb6d9..2345e9bf 100644 --- a/src/ru/nsu/ccfit/zuev/osu/async/SyncTaskManager.java +++ b/src/ru/nsu/ccfit/zuev/osu/async/SyncTaskManager.java @@ -3,22 +3,22 @@ import org.anddev.andengine.ui.activity.BaseGameActivity; public class SyncTaskManager { - private static SyncTaskManager mgr = new SyncTaskManager(); - private BaseGameActivity activity; + private static SyncTaskManager mgr = new SyncTaskManager(); + private BaseGameActivity activity; - private SyncTaskManager() { + private SyncTaskManager() { - } + } - public static SyncTaskManager getInstance() { - return mgr; - } + public static SyncTaskManager getInstance() { + return mgr; + } - public void init(final BaseGameActivity act) { - activity = act; - } + public void init(final BaseGameActivity act) { + activity = act; + } - public void run(final Runnable runnable) { - activity.runOnUpdateThread(runnable); - } + public void run(final Runnable runnable) { + activity.runOnUpdateThread(runnable); + } } diff --git a/src/ru/nsu/ccfit/zuev/osu/game/BreakAnimator.java b/src/ru/nsu/ccfit/zuev/osu/game/BreakAnimator.java index e9b35cb1..b17a0b5f 100644 --- a/src/ru/nsu/ccfit/zuev/osu/game/BreakAnimator.java +++ b/src/ru/nsu/ccfit/zuev/osu/game/BreakAnimator.java @@ -18,165 +18,165 @@ import ru.nsu.ccfit.zuev.osu.scoring.StatisticV2; public class BreakAnimator extends GameObject { - private final Scene scene; - private final StatisticV2 stat; - private final Sprite[] arrows = new Sprite[4]; - private float length = 0; - private float time; - private Sprite passfail; - private String ending; - private Sprite mark = null; - private boolean showMark = false; - private boolean isbreak = false; - private boolean over = false; - private Sprite bgSprite = null; - - public BreakAnimator(final GameObjectListener listener, final Scene scene, - final StatisticV2 stat, final boolean showMark, Sprite bgSprtie) { - length = 0; - this.showMark = showMark; - this.scene = scene; - this.stat = stat; - this.bgSprite = bgSprtie; - listener.addPassiveObject(this); - - for (int i = 0; i < 4; i++) { - arrows[i] = new Sprite(0, 0, ResourceManager.getInstance() - .getTexture("play-warningarrow").deepCopy()); - arrows[i] - .registerEntityModifier(new LoopEntityModifier( - new SequenceEntityModifier( - new FadeInModifier(0.05f), - new DelayModifier(0.1f), - new FadeOutModifier(0.1f)))); - if (i > 1) { - arrows[i].setFlippedHorizontal(true); - } - } - arrows[0].setPosition(Utils.toRes(64), Utils.toRes(72)); - arrows[1].setPosition(Utils.toRes(64), Config.getRES_HEIGHT() - - arrows[1].getHeight()); - arrows[2].setPosition(Config.getRES_WIDTH() - arrows[1].getWidth() - - Utils.toRes(64), Utils.toRes(72)); - arrows[3].setPosition(Config.getRES_WIDTH() - arrows[1].getWidth() - - Utils.toRes(64), - Config.getRES_HEIGHT() - arrows[1].getHeight()); - - } - - public boolean isBreak() { - return isbreak; - } - - public boolean isOver() { - final boolean isover = over; - over = false; - return isover; - } - - public void init(final float length) { - if (this.length > 0 && time < this.length) { - return; - } - isbreak = true; - over = false; - this.length = length; - time = 0; - ending = stat.getHp() > 0.5f ? "pass" : "fail"; - final PointF center = new PointF(Config.getRES_WIDTH() / 2, - Config.getRES_HEIGHT() / 2); - passfail = SpritePool.getInstance().getCenteredSprite( - "section-" + ending, center); - scene.attachChild(passfail, 0); - passfail.setVisible(false); - - for (int i = 0; i < 4; i++) { - arrows[i].setVisible(false); - arrows[i].setIgnoreUpdate(true); - scene.attachChild(arrows[i], 0); - } - if (showMark) { - final TextureRegion zeroRect = ResourceManager.getInstance() - .getTexture("score-0"); - mark = new Sprite(Config.getRES_WIDTH() - zeroRect.getWidth() * 11, - Utils.toRes(5), ResourceManager.getInstance().getTexture( - "ranking-" + stat.getMark() + "-small")); - mark.setScale(1.2f); - scene.attachChild(mark, 0); - } - - System.gc(); - } - - private void setBgFade(float percent) { - if (bgSprite != null) { - float brightness = Config.getBackgroundBrightness(); - bgSprite.setColor(brightness + percent * (1 - brightness), - brightness + percent * (1 - brightness), - brightness + percent * (1 - brightness)); - } - } - - private void resumeBgFade() { - if (bgSprite != null) { - float brightness = Config.getBackgroundBrightness(); - bgSprite.setColor(brightness, brightness, brightness); - } - } - - - @Override - public void update(final float dt) { - if (length == 0 || time >= length) { - return; - } - time += dt; - - if (length > 3 && time > (length - 1) / 2 - && time - dt < (length - 1) / 2) { - passfail.setVisible(true); - passfail.registerEntityModifier(new SequenceEntityModifier( - new DelayModifier(0.25f), new FadeOutModifier(0.025f), - new DelayModifier(0.025f), new FadeInModifier(0.025f), - new DelayModifier(0.6725f), new FadeOutModifier(0.3f))); - if (ResourceManager.getInstance().getCustomSound("section" + ending, 1) != null) - ResourceManager.getInstance().getCustomSound("section" + ending, 1).play(); - } - if (length - time <= 1 && length - time + dt > 1) { - for (final Sprite sp : arrows) { - sp.setVisible(true); - sp.setIgnoreUpdate(false); - } - } - if (length > 1) { - if (time < 0.5f) { - setBgFade(time * 2); - } else if (length - time < 0.5f) { - setBgFade((length - time) * 2); - } else if (time >= 0.5f && time - dt < 0.5f) - setBgFade(1); - } - - if (time >= length) { - isbreak = false; - over = true; - resumeBgFade(); - SyncTaskManager.getInstance().run(new Runnable() { - - - public void run() { - if (mark != null) { - mark.detachSelf(); - } - for (final Sprite sp : arrows) { - sp.detachSelf(); - } - passfail.detachSelf(); - SpritePool.getInstance().putSprite("section-" + ending, - passfail); - } - }); - } - } + private final Scene scene; + private final StatisticV2 stat; + private final Sprite[] arrows = new Sprite[4]; + private float length = 0; + private float time; + private Sprite passfail; + private String ending; + private Sprite mark = null; + private boolean showMark = false; + private boolean isbreak = false; + private boolean over = false; + private Sprite bgSprite = null; + + public BreakAnimator(final GameObjectListener listener, final Scene scene, + final StatisticV2 stat, final boolean showMark, Sprite bgSprtie) { + length = 0; + this.showMark = showMark; + this.scene = scene; + this.stat = stat; + this.bgSprite = bgSprtie; + listener.addPassiveObject(this); + + for (int i = 0; i < 4; i++) { + arrows[i] = new Sprite(0, 0, ResourceManager.getInstance() + .getTexture("play-warningarrow").deepCopy()); + arrows[i] + .registerEntityModifier(new LoopEntityModifier( + new SequenceEntityModifier( + new FadeInModifier(0.05f), + new DelayModifier(0.1f), + new FadeOutModifier(0.1f)))); + if (i > 1) { + arrows[i].setFlippedHorizontal(true); + } + } + arrows[0].setPosition(Utils.toRes(64), Utils.toRes(72)); + arrows[1].setPosition(Utils.toRes(64), Config.getRES_HEIGHT() + - arrows[1].getHeight()); + arrows[2].setPosition(Config.getRES_WIDTH() - arrows[1].getWidth() + - Utils.toRes(64), Utils.toRes(72)); + arrows[3].setPosition(Config.getRES_WIDTH() - arrows[1].getWidth() + - Utils.toRes(64), + Config.getRES_HEIGHT() - arrows[1].getHeight()); + + } + + public boolean isBreak() { + return isbreak; + } + + public boolean isOver() { + final boolean isover = over; + over = false; + return isover; + } + + public void init(final float length) { + if (this.length > 0 && time < this.length) { + return; + } + isbreak = true; + over = false; + this.length = length; + time = 0; + ending = stat.getHp() > 0.5f ? "pass" : "fail"; + final PointF center = new PointF(Config.getRES_WIDTH() / 2, + Config.getRES_HEIGHT() / 2); + passfail = SpritePool.getInstance().getCenteredSprite( + "section-" + ending, center); + scene.attachChild(passfail, 0); + passfail.setVisible(false); + + for (int i = 0; i < 4; i++) { + arrows[i].setVisible(false); + arrows[i].setIgnoreUpdate(true); + scene.attachChild(arrows[i], 0); + } + if (showMark) { + final TextureRegion zeroRect = ResourceManager.getInstance() + .getTexture("score-0"); + mark = new Sprite(Config.getRES_WIDTH() - zeroRect.getWidth() * 11, + Utils.toRes(5), ResourceManager.getInstance().getTexture( + "ranking-" + stat.getMark() + "-small")); + mark.setScale(1.2f); + scene.attachChild(mark, 0); + } + + System.gc(); + } + + private void setBgFade(float percent) { + if (bgSprite != null) { + float brightness = Config.getBackgroundBrightness(); + bgSprite.setColor(brightness + percent * (1 - brightness), + brightness + percent * (1 - brightness), + brightness + percent * (1 - brightness)); + } + } + + private void resumeBgFade() { + if (bgSprite != null) { + float brightness = Config.getBackgroundBrightness(); + bgSprite.setColor(brightness, brightness, brightness); + } + } + + + @Override + public void update(final float dt) { + if (length == 0 || time >= length) { + return; + } + time += dt; + + if (length > 3 && time > (length - 1) / 2 + && time - dt < (length - 1) / 2) { + passfail.setVisible(true); + passfail.registerEntityModifier(new SequenceEntityModifier( + new DelayModifier(0.25f), new FadeOutModifier(0.025f), + new DelayModifier(0.025f), new FadeInModifier(0.025f), + new DelayModifier(0.6725f), new FadeOutModifier(0.3f))); + if (ResourceManager.getInstance().getCustomSound("section" + ending, 1) != null) + ResourceManager.getInstance().getCustomSound("section" + ending, 1).play(); + } + if (length - time <= 1 && length - time + dt > 1) { + for (final Sprite sp : arrows) { + sp.setVisible(true); + sp.setIgnoreUpdate(false); + } + } + if (length > 1) { + if (time < 0.5f) { + setBgFade(time * 2); + } else if (length - time < 0.5f) { + setBgFade((length - time) * 2); + } else if (time >= 0.5f && time - dt < 0.5f) + setBgFade(1); + } + + if (time >= length) { + isbreak = false; + over = true; + resumeBgFade(); + SyncTaskManager.getInstance().run(new Runnable() { + + + public void run() { + if (mark != null) { + mark.detachSelf(); + } + for (final Sprite sp : arrows) { + sp.detachSelf(); + } + passfail.detachSelf(); + SpritePool.getInstance().putSprite("section-" + ending, + passfail); + } + }); + } + } } diff --git a/src/ru/nsu/ccfit/zuev/osu/game/BreakPeriod.java b/src/ru/nsu/ccfit/zuev/osu/game/BreakPeriod.java index d91740dd..67788b00 100644 --- a/src/ru/nsu/ccfit/zuev/osu/game/BreakPeriod.java +++ b/src/ru/nsu/ccfit/zuev/osu/game/BreakPeriod.java @@ -1,19 +1,19 @@ package ru.nsu.ccfit.zuev.osu.game; public class BreakPeriod { - private final float length; - private final float start; + private final float length; + private final float start; - public BreakPeriod(final float starttime, final float endtime) { - start = starttime; - length = endtime - starttime; - } + public BreakPeriod(final float starttime, final float endtime) { + start = starttime; + length = endtime - starttime; + } - public float getLength() { - return length; - } + public float getLength() { + return length; + } - public float getStart() { - return start; - } + public float getStart() { + return start; + } } diff --git a/src/ru/nsu/ccfit/zuev/osu/game/CircleNumber.java b/src/ru/nsu/ccfit/zuev/osu/game/CircleNumber.java index b088efdd..64eebe19 100644 --- a/src/ru/nsu/ccfit/zuev/osu/game/CircleNumber.java +++ b/src/ru/nsu/ccfit/zuev/osu/game/CircleNumber.java @@ -13,74 +13,74 @@ import ru.nsu.ccfit.zuev.osu.async.SyncTaskManager; public class CircleNumber extends GameObject { - private final Sprite[] digits; - private final int num; - - public CircleNumber(final int number) { - num = number; - final String snum = String.valueOf(Math.abs(number)); - - digits = new Sprite[snum.length()]; - for (int i = 0; i < snum.length(); i++) { - final TextureRegion tex = ResourceManager.getInstance().getTexture( - "default-" + snum.charAt(i)); - digits[i] = new Sprite(0, 0, tex); - } - } - - public void init(final Scene scene, final PointF pos, float scale, - final IEntityModifier... entityModifiers) { - scale *= SkinJson.get().getComboTextScale(); - final String snum = String.valueOf(Math.abs(num)); - - float twidth = 0; - final PointF hitpos = new PointF(); - for (int i = 0; i < snum.length(); i++) { - final TextureRegion tex = digits[i].getTextureRegion(); - hitpos.set(twidth + pos.x, pos.y - tex.getHeight() / 2); - twidth += (snum.charAt(i) == '1' && snum.length() > 1) ? scale - * tex.getWidth() / 1.5f : scale * tex.getWidth(); - digits[i].setPosition(hitpos.x, hitpos.y); - - digits[i].registerEntityModifier(new ParallelEntityModifier( - entityModifiers)); - digits[i].setScale(scale); - scene.attachChild(digits[i], 0); - } - - twidth /= 2; - - for (final Sprite sp : digits) { - sp.setPosition(sp.getX() - twidth / scale, sp.getY()); - } - } - - public int getNum() { - return num; - } - - public void detach(final boolean sync) { - if (sync) { - SyncTaskManager.getInstance().run(new Runnable() { - - - public void run() { - for (final Sprite sp : digits) { - sp.clearEntityModifiers(); - sp.detachSelf(); - } - } - }); - } else { - for (final Sprite sp : digits) { - sp.clearEntityModifiers(); - sp.detachSelf(); - } - } // if (sync) - } - - - @Override - public void update(final float dt) { - } + private final Sprite[] digits; + private final int num; + + public CircleNumber(final int number) { + num = number; + final String snum = String.valueOf(Math.abs(number)); + + digits = new Sprite[snum.length()]; + for (int i = 0; i < snum.length(); i++) { + final TextureRegion tex = ResourceManager.getInstance().getTexture( + "default-" + snum.charAt(i)); + digits[i] = new Sprite(0, 0, tex); + } + } + + public void init(final Scene scene, final PointF pos, float scale, + final IEntityModifier... entityModifiers) { + scale *= SkinJson.get().getComboTextScale(); + final String snum = String.valueOf(Math.abs(num)); + + float twidth = 0; + final PointF hitpos = new PointF(); + for (int i = 0; i < snum.length(); i++) { + final TextureRegion tex = digits[i].getTextureRegion(); + hitpos.set(twidth + pos.x, pos.y - tex.getHeight() / 2); + twidth += (snum.charAt(i) == '1' && snum.length() > 1) ? scale + * tex.getWidth() / 1.5f : scale * tex.getWidth(); + digits[i].setPosition(hitpos.x, hitpos.y); + + digits[i].registerEntityModifier(new ParallelEntityModifier( + entityModifiers)); + digits[i].setScale(scale); + scene.attachChild(digits[i], 0); + } + + twidth /= 2; + + for (final Sprite sp : digits) { + sp.setPosition(sp.getX() - twidth / scale, sp.getY()); + } + } + + public int getNum() { + return num; + } + + public void detach(final boolean sync) { + if (sync) { + SyncTaskManager.getInstance().run(new Runnable() { + + + public void run() { + for (final Sprite sp : digits) { + sp.clearEntityModifiers(); + sp.detachSelf(); + } + } + }); + } else { + for (final Sprite sp : digits) { + sp.clearEntityModifiers(); + sp.detachSelf(); + } + } // if (sync) + } + + + @Override + public void update(final float dt) { + } } diff --git a/src/ru/nsu/ccfit/zuev/osu/game/ComboBurst.java b/src/ru/nsu/ccfit/zuev/osu/game/ComboBurst.java index e6c57a3f..e95d6955 100644 --- a/src/ru/nsu/ccfit/zuev/osu/game/ComboBurst.java +++ b/src/ru/nsu/ccfit/zuev/osu/game/ComboBurst.java @@ -26,129 +26,129 @@ */ public class ComboBurst { - private final List comboBursts = new ArrayList(); - private final List comboBurstVocals = new ArrayList(); - - private final float rightX; - private final float bottomY; - - private int nextKeyComboNum = 0; - private float fromX = 0; - private int nextShowId = 0; - private int nextSoundId = 0; - - public ComboBurst(float rightX, float bottomY) { - this.rightX = rightX; - this.bottomY = bottomY; - breakCombo(); - - TextureRegion globalTex = ResourceManager.getInstance().getTexture("comboburst"); - if (globalTex != null) { - Sprite sprite = new Sprite(0, 0, globalTex); - sprite.setAlpha(0f); - sprite.setIgnoreUpdate(true); - comboBursts.add(sprite); - } - BassSoundProvider sound = ResourceManager.getInstance().getSound("comboburst"); - if (sound != null) { - comboBurstVocals.add(sound); - } - for (int i = 0; i < 10; i++) { - TextureRegion tex = ResourceManager.getInstance().getTexture("comboburst-" + i); - if (tex != null) { - Sprite sprite = new Sprite(0, 0, tex); - sprite.setAlpha(0f); - sprite.setIgnoreUpdate(true); - comboBursts.add(sprite); - } - sound = ResourceManager.getInstance().getSound("comboburst-" + i); - if (sound != null) { - comboBurstVocals.add(sound); - } - } - } - - public void checkAndShow(int currentCombo) { - if (Config.isComboburst() && currentCombo >= nextKeyComboNum) { - if (comboBurstVocals.size() > 0) { - comboBurstVocals.get(nextSoundId).play(0.8f); - } - if (comboBursts.size() > 0) { - Sprite sprite = comboBursts.get(nextShowId); - float toX; - if (fromX > 0) { - toX = fromX - sprite.getWidth(); - } else { - fromX = -sprite.getWidth(); - toX = 0; - } - sprite.setIgnoreUpdate(false); - sprite.setPosition(fromX, bottomY - sprite.getHeight()); - sprite.registerEntityModifier(new SequenceEntityModifier( - new IEntityModifier.IEntityModifierListener() { - @Override - public void onModifierStarted(IModifier pModifier, IEntity pItem) { - - } - - @Override - public void onModifierFinished(IModifier pModifier, IEntity pItem) { - pItem.setAlpha(0f); - pItem.setIgnoreUpdate(true); - } - }, - new ParallelEntityModifier( - new MoveXModifier(0.5f, fromX, toX, EaseSineOut.getInstance()), - new FadeInModifier(0.5f) - ), - new DelayModifier(1.0f), - new ParallelEntityModifier( - new MoveXModifier(0.5f, toX, fromX, EaseSineOut.getInstance()), - new FadeOutModifier(0.5f) - ) - )); - } - - if (comboBursts.size() > 0) { - int length = comboBursts.size(); - nextShowId = (nextShowId + 1) % length; - } - if (comboBurstVocals.size() > 0) { - int length = comboBurstVocals.size(); - nextSoundId = (nextSoundId + 1) % length; - } - if (nextKeyComboNum == 30) { - nextKeyComboNum = 60; - fromX = rightX; - } else if (nextKeyComboNum == 60) { - nextKeyComboNum = 100; - fromX = -1; - } else { - nextKeyComboNum += 100; - int mod = nextKeyComboNum / 100; - if (mod % 2 == 0) { - fromX = rightX; - } else { - fromX = -1; - } - } - } - } - - public void breakCombo() { - fromX = 0; - nextKeyComboNum = 30; - } - - public void attachAll(Scene scene) { - for (final Sprite sprite : comboBursts) { - scene.attachChild(sprite); - } - } - - public void detachAll() { - for (final Sprite sprite : comboBursts) { - sprite.detachSelf(); - } - } + private final List comboBursts = new ArrayList(); + private final List comboBurstVocals = new ArrayList(); + + private final float rightX; + private final float bottomY; + + private int nextKeyComboNum = 0; + private float fromX = 0; + private int nextShowId = 0; + private int nextSoundId = 0; + + public ComboBurst(float rightX, float bottomY) { + this.rightX = rightX; + this.bottomY = bottomY; + breakCombo(); + + TextureRegion globalTex = ResourceManager.getInstance().getTexture("comboburst"); + if (globalTex != null) { + Sprite sprite = new Sprite(0, 0, globalTex); + sprite.setAlpha(0f); + sprite.setIgnoreUpdate(true); + comboBursts.add(sprite); + } + BassSoundProvider sound = ResourceManager.getInstance().getSound("comboburst"); + if (sound != null) { + comboBurstVocals.add(sound); + } + for (int i = 0; i < 10; i++) { + TextureRegion tex = ResourceManager.getInstance().getTexture("comboburst-" + i); + if (tex != null) { + Sprite sprite = new Sprite(0, 0, tex); + sprite.setAlpha(0f); + sprite.setIgnoreUpdate(true); + comboBursts.add(sprite); + } + sound = ResourceManager.getInstance().getSound("comboburst-" + i); + if (sound != null) { + comboBurstVocals.add(sound); + } + } + } + + public void checkAndShow(int currentCombo) { + if (Config.isComboburst() && currentCombo >= nextKeyComboNum) { + if (comboBurstVocals.size() > 0) { + comboBurstVocals.get(nextSoundId).play(0.8f); + } + if (comboBursts.size() > 0) { + Sprite sprite = comboBursts.get(nextShowId); + float toX; + if (fromX > 0) { + toX = fromX - sprite.getWidth(); + } else { + fromX = -sprite.getWidth(); + toX = 0; + } + sprite.setIgnoreUpdate(false); + sprite.setPosition(fromX, bottomY - sprite.getHeight()); + sprite.registerEntityModifier(new SequenceEntityModifier( + new IEntityModifier.IEntityModifierListener() { + @Override + public void onModifierStarted(IModifier pModifier, IEntity pItem) { + + } + + @Override + public void onModifierFinished(IModifier pModifier, IEntity pItem) { + pItem.setAlpha(0f); + pItem.setIgnoreUpdate(true); + } + }, + new ParallelEntityModifier( + new MoveXModifier(0.5f, fromX, toX, EaseSineOut.getInstance()), + new FadeInModifier(0.5f) + ), + new DelayModifier(1.0f), + new ParallelEntityModifier( + new MoveXModifier(0.5f, toX, fromX, EaseSineOut.getInstance()), + new FadeOutModifier(0.5f) + ) + )); + } + + if (comboBursts.size() > 0) { + int length = comboBursts.size(); + nextShowId = (nextShowId + 1) % length; + } + if (comboBurstVocals.size() > 0) { + int length = comboBurstVocals.size(); + nextSoundId = (nextSoundId + 1) % length; + } + if (nextKeyComboNum == 30) { + nextKeyComboNum = 60; + fromX = rightX; + } else if (nextKeyComboNum == 60) { + nextKeyComboNum = 100; + fromX = -1; + } else { + nextKeyComboNum += 100; + int mod = nextKeyComboNum / 100; + if (mod % 2 == 0) { + fromX = rightX; + } else { + fromX = -1; + } + } + } + } + + public void breakCombo() { + fromX = 0; + nextKeyComboNum = 30; + } + + public void attachAll(Scene scene) { + for (final Sprite sprite : comboBursts) { + scene.attachChild(sprite); + } + } + + public void detachAll() { + for (final Sprite sprite : comboBursts) { + sprite.detachSelf(); + } + } } diff --git a/src/ru/nsu/ccfit/zuev/osu/game/Countdown.java b/src/ru/nsu/ccfit/zuev/osu/game/Countdown.java index 394427ee..42c29533 100644 --- a/src/ru/nsu/ccfit/zuev/osu/game/Countdown.java +++ b/src/ru/nsu/ccfit/zuev/osu/game/Countdown.java @@ -21,150 +21,150 @@ import ru.nsu.ccfit.zuev.osu.helper.CentredSprite; public class Countdown extends GameObject { - public static final float COUNTDOWN_LENGTH = 3f; - private final Sprite ready; - private final Sprite count1, count2, count3; - private final Sprite go; - private final GameObjectListener listener; - private final float speed; - private float timepassed; - private Scene scene; - - public Countdown(final GameObjectListener listener, final Scene scene, - final float speed, final float offset, final float time) { - this.listener = listener; - this.speed = speed; - this.scene = scene; - timepassed = -time + COUNTDOWN_LENGTH * speed; - final PointF center = Utils.trackToRealCoords(new PointF( - Constants.MAP_WIDTH / 2, Constants.MAP_HEIGHT / 2)); - ready = new CentredSprite(center.x, center.y, ResourceManager - .getInstance().getTexture("ready")); - ready.registerEntityModifier(new SequenceEntityModifier( - new ParallelEntityModifier(new FadeInModifier(COUNTDOWN_LENGTH - * speed / 9), new RotationModifier(COUNTDOWN_LENGTH - * speed / 9, -90, 0)), new DelayModifier( - COUNTDOWN_LENGTH * speed / 9), - new ParallelEntityModifier(new FadeOutModifier(COUNTDOWN_LENGTH - * speed / 9), new ScaleModifier(COUNTDOWN_LENGTH - * speed / 9, 1, 1.5f)))); - ready.setRotation(-90); - ready.setVisible(false); - ready.setIgnoreUpdate(true); - - count3 = new Sprite(0, 0, ResourceManager.getInstance().getTexture( - "count3")); - count3.setPosition(0, center.y - count3.getHeight() / 2); - count3.setVisible(false); - count3.setIgnoreUpdate(true); - count3.registerEntityModifier(new SequenceEntityModifier( - new FadeInModifier(COUNTDOWN_LENGTH * speed / 18), - new DelayModifier(COUNTDOWN_LENGTH * speed * 8 / 18), - new FadeOutModifier(COUNTDOWN_LENGTH * speed / 18))); - - count2 = new Sprite(0, 0, ResourceManager.getInstance().getTexture( - "count2")); - count2.setPosition(Config.getRES_WIDTH() - count2.getWidth(), center.y - - count2.getHeight() / 2); - count2.setVisible(false); - count2.setIgnoreUpdate(true); - count2.registerEntityModifier(new SequenceEntityModifier( - new FadeInModifier(COUNTDOWN_LENGTH * speed / 18), - new DelayModifier(COUNTDOWN_LENGTH * speed * 5 / 18), - new FadeOutModifier(COUNTDOWN_LENGTH * speed / 18))); - - count1 = new Sprite(0, 0, ResourceManager.getInstance().getTexture( - "count1")); - count1.setPosition(center.x - count1.getWidth() / 2, - center.y - count1.getHeight() / 2); - count1.setVisible(false); - count1.setIgnoreUpdate(true); - count1.registerEntityModifier(new SequenceEntityModifier( - new FadeInModifier(COUNTDOWN_LENGTH * speed / 18), - new DelayModifier(COUNTDOWN_LENGTH * speed * 2 / 18), - new FadeOutModifier(COUNTDOWN_LENGTH * speed / 18))); - - go = new CentredSprite(center.x, center.y, ResourceManager - .getInstance().getTexture("go")); - go.registerEntityModifier(new SequenceEntityModifier( - new ParallelEntityModifier(new FadeInModifier(COUNTDOWN_LENGTH - * speed / 18), new RotationModifier(COUNTDOWN_LENGTH - * speed / 18, -180, 0)), new DelayModifier( - COUNTDOWN_LENGTH * speed / 18), new FadeOutModifier( - COUNTDOWN_LENGTH * speed / 18))); - go.setRotation(-180); - go.setVisible(false); - go.setIgnoreUpdate(true); - - scene.attachChild(ready, 0); - scene.attachChild(go, 0); - scene.attachChild(count1, 0); - scene.attachChild(count2, 0); - scene.attachChild(count3, 0); - } - - - @Override - public void update(final float dt) { - if (scene == null) { - return; - } - timepassed += dt; - - if (timepassed >= 0 && timepassed - dt < 0) { - BassSoundProvider provider = ResourceManager.getInstance().getCustomSound("readys", 1); - if (provider != null) { - provider.play(); - //TODO : Fix the bug of crashing on countdown - } - ready.setVisible(true); - ready.setIgnoreUpdate(false); - } - - if (timepassed >= COUNTDOWN_LENGTH * speed * 2 / 6 - && timepassed - dt < COUNTDOWN_LENGTH * speed * 2 / 6) { - ResourceManager.getInstance().getCustomSound("count3s", 1).play(); - count3.setVisible(true); - count3.setIgnoreUpdate(false); - } - - if (timepassed >= COUNTDOWN_LENGTH * speed * 3 / 6 - && timepassed - dt < COUNTDOWN_LENGTH * speed * 3 / 6) { - ResourceManager.getInstance().getCustomSound("count2s", 1).play(); - count2.setVisible(true); - count2.setIgnoreUpdate(false); - } - - if (timepassed >= COUNTDOWN_LENGTH * speed * 4 / 6 - && timepassed - dt < COUNTDOWN_LENGTH * speed * 4 / 6) { - ResourceManager.getInstance().getCustomSound("count1s", 1).play(); - count1.setVisible(true); - count1.setIgnoreUpdate(false); - } - - if (timepassed >= COUNTDOWN_LENGTH * speed * 5 / 6 - && timepassed - dt < COUNTDOWN_LENGTH * speed * 5 / 6) { - ResourceManager.getInstance().getCustomSound("gos", 1).play(); - go.setVisible(true); - go.setIgnoreUpdate(false); - } - - if (timepassed >= COUNTDOWN_LENGTH * speed - && timepassed - dt < COUNTDOWN_LENGTH * speed) { - scene = null; - SyncTaskManager.getInstance().run(new Runnable() { - - - public void run() { - listener.removePassiveObject(Countdown.this); - ready.detachSelf(); - go.detachSelf(); - count1.detachSelf(); - count2.detachSelf(); - count3.detachSelf(); - } - }); - } - } + public static final float COUNTDOWN_LENGTH = 3f; + private final Sprite ready; + private final Sprite count1, count2, count3; + private final Sprite go; + private final GameObjectListener listener; + private final float speed; + private float timepassed; + private Scene scene; + + public Countdown(final GameObjectListener listener, final Scene scene, + final float speed, final float offset, final float time) { + this.listener = listener; + this.speed = speed; + this.scene = scene; + timepassed = -time + COUNTDOWN_LENGTH * speed; + final PointF center = Utils.trackToRealCoords(new PointF( + Constants.MAP_WIDTH / 2, Constants.MAP_HEIGHT / 2)); + ready = new CentredSprite(center.x, center.y, ResourceManager + .getInstance().getTexture("ready")); + ready.registerEntityModifier(new SequenceEntityModifier( + new ParallelEntityModifier(new FadeInModifier(COUNTDOWN_LENGTH + * speed / 9), new RotationModifier(COUNTDOWN_LENGTH + * speed / 9, -90, 0)), new DelayModifier( + COUNTDOWN_LENGTH * speed / 9), + new ParallelEntityModifier(new FadeOutModifier(COUNTDOWN_LENGTH + * speed / 9), new ScaleModifier(COUNTDOWN_LENGTH + * speed / 9, 1, 1.5f)))); + ready.setRotation(-90); + ready.setVisible(false); + ready.setIgnoreUpdate(true); + + count3 = new Sprite(0, 0, ResourceManager.getInstance().getTexture( + "count3")); + count3.setPosition(0, center.y - count3.getHeight() / 2); + count3.setVisible(false); + count3.setIgnoreUpdate(true); + count3.registerEntityModifier(new SequenceEntityModifier( + new FadeInModifier(COUNTDOWN_LENGTH * speed / 18), + new DelayModifier(COUNTDOWN_LENGTH * speed * 8 / 18), + new FadeOutModifier(COUNTDOWN_LENGTH * speed / 18))); + + count2 = new Sprite(0, 0, ResourceManager.getInstance().getTexture( + "count2")); + count2.setPosition(Config.getRES_WIDTH() - count2.getWidth(), center.y + - count2.getHeight() / 2); + count2.setVisible(false); + count2.setIgnoreUpdate(true); + count2.registerEntityModifier(new SequenceEntityModifier( + new FadeInModifier(COUNTDOWN_LENGTH * speed / 18), + new DelayModifier(COUNTDOWN_LENGTH * speed * 5 / 18), + new FadeOutModifier(COUNTDOWN_LENGTH * speed / 18))); + + count1 = new Sprite(0, 0, ResourceManager.getInstance().getTexture( + "count1")); + count1.setPosition(center.x - count1.getWidth() / 2, + center.y - count1.getHeight() / 2); + count1.setVisible(false); + count1.setIgnoreUpdate(true); + count1.registerEntityModifier(new SequenceEntityModifier( + new FadeInModifier(COUNTDOWN_LENGTH * speed / 18), + new DelayModifier(COUNTDOWN_LENGTH * speed * 2 / 18), + new FadeOutModifier(COUNTDOWN_LENGTH * speed / 18))); + + go = new CentredSprite(center.x, center.y, ResourceManager + .getInstance().getTexture("go")); + go.registerEntityModifier(new SequenceEntityModifier( + new ParallelEntityModifier(new FadeInModifier(COUNTDOWN_LENGTH + * speed / 18), new RotationModifier(COUNTDOWN_LENGTH + * speed / 18, -180, 0)), new DelayModifier( + COUNTDOWN_LENGTH * speed / 18), new FadeOutModifier( + COUNTDOWN_LENGTH * speed / 18))); + go.setRotation(-180); + go.setVisible(false); + go.setIgnoreUpdate(true); + + scene.attachChild(ready, 0); + scene.attachChild(go, 0); + scene.attachChild(count1, 0); + scene.attachChild(count2, 0); + scene.attachChild(count3, 0); + } + + + @Override + public void update(final float dt) { + if (scene == null) { + return; + } + timepassed += dt; + + if (timepassed >= 0 && timepassed - dt < 0) { + BassSoundProvider provider = ResourceManager.getInstance().getCustomSound("readys", 1); + if (provider != null) { + provider.play(); + //TODO : Fix the bug of crashing on countdown + } + ready.setVisible(true); + ready.setIgnoreUpdate(false); + } + + if (timepassed >= COUNTDOWN_LENGTH * speed * 2 / 6 + && timepassed - dt < COUNTDOWN_LENGTH * speed * 2 / 6) { + ResourceManager.getInstance().getCustomSound("count3s", 1).play(); + count3.setVisible(true); + count3.setIgnoreUpdate(false); + } + + if (timepassed >= COUNTDOWN_LENGTH * speed * 3 / 6 + && timepassed - dt < COUNTDOWN_LENGTH * speed * 3 / 6) { + ResourceManager.getInstance().getCustomSound("count2s", 1).play(); + count2.setVisible(true); + count2.setIgnoreUpdate(false); + } + + if (timepassed >= COUNTDOWN_LENGTH * speed * 4 / 6 + && timepassed - dt < COUNTDOWN_LENGTH * speed * 4 / 6) { + ResourceManager.getInstance().getCustomSound("count1s", 1).play(); + count1.setVisible(true); + count1.setIgnoreUpdate(false); + } + + if (timepassed >= COUNTDOWN_LENGTH * speed * 5 / 6 + && timepassed - dt < COUNTDOWN_LENGTH * speed * 5 / 6) { + ResourceManager.getInstance().getCustomSound("gos", 1).play(); + go.setVisible(true); + go.setIgnoreUpdate(false); + } + + if (timepassed >= COUNTDOWN_LENGTH * speed + && timepassed - dt < COUNTDOWN_LENGTH * speed) { + scene = null; + SyncTaskManager.getInstance().run(new Runnable() { + + + public void run() { + listener.removePassiveObject(Countdown.this); + ready.detachSelf(); + go.detachSelf(); + count1.detachSelf(); + count2.detachSelf(); + count3.detachSelf(); + } + }); + } + } } diff --git a/src/ru/nsu/ccfit/zuev/osu/game/DuringGameScoreBoard.java b/src/ru/nsu/ccfit/zuev/osu/game/DuringGameScoreBoard.java index 78feab4c..afc89ec4 100644 --- a/src/ru/nsu/ccfit/zuev/osu/game/DuringGameScoreBoard.java +++ b/src/ru/nsu/ccfit/zuev/osu/game/DuringGameScoreBoard.java @@ -20,135 +20,135 @@ import ru.nsu.ccfit.zuev.osu.scoring.StatisticV2; public class DuringGameScoreBoard extends GameObject { - private final StatisticV2 stat; - private Sprite[] boards; - private ChangeableText[] ranks; - private ScoreBoard.ScoreBoardItems[] scoreBoardDatas; - private int posNow; - private String currentUsername; - private ChangeableText playerRank; - private ChangeableText playerText; - private Sprite playerSprite; - private float itemHeight; - private long lastRankChange; + private final StatisticV2 stat; + private Sprite[] boards; + private ChangeableText[] ranks; + private ScoreBoard.ScoreBoardItems[] scoreBoardDatas; + private int posNow; + private String currentUsername; + private ChangeableText playerRank; + private ChangeableText playerText; + private Sprite playerSprite; + private float itemHeight; + private long lastRankChange; - private float paddingTop = 15, paddingLeft = 10; + private float paddingTop = 15, paddingLeft = 10; - public DuringGameScoreBoard(final Scene scene, final StatisticV2 stat, String isNotMe) { - final ScoreBoard.ScoreBoardItems[] items = GlobalManager.getInstance().getSongMenu().getBoard(); - this.stat = stat; - int replayid = GlobalManager.getInstance().getScoring().getReplayID(); - if (replayid == -1) scoreBoardDatas = items; - else { - int replayIndex = -1; - scoreBoardDatas = new ScoreBoard.ScoreBoardItems[items.length - 1]; - for (int i = 0; i < items.length; i++) { - if (replayid == items[i].scoreId) { - replayIndex = i; - continue; - } - scoreBoardDatas[i - (replayIndex != -1 ? 1 : 0)] = items[i]; - } - } - posNow = scoreBoardDatas.length; - currentUsername = isNotMe != null ? isNotMe : - OnlineScoring.getInstance().getPanel() == null ? - Config.getLocalUsername() : - Config.getOnlineUsername(); - TextureRegion tex = ResourceManager.getInstance().getTexture("menu-button-background").deepCopy(); - tex.setHeight(90); - tex.setWidth(130); - boards = new Sprite[scoreBoardDatas.length + 1]; - ranks = new ChangeableText[scoreBoardDatas.length]; - for (int i = 0; i < scoreBoardDatas.length; i++) { - Sprite s = new Sprite(0, 0, tex); - s.setAlpha(0.5f); - s.setColor(scoreBoardDatas[i].userName.equals(currentUsername) && !currentUsername.equals("osu!") ? 1 : 0.5f, 0.5f, 0.5f); - final Text info = new Text(paddingLeft, paddingTop, - ResourceManager.getInstance().getFont("font"), scoreBoardDatas[i].get()); - info.setScaleCenter(0, 0); - info.setScale(0.65f); - info.setColor(0.85f, 0.85f, 0.9f); - ranks[i] = new ChangeableText(paddingLeft, paddingTop, - ResourceManager.getInstance().getFont("CaptionFont"), "#1", 5); - ranks[i].setBlendFunction(GLES20.GL_SRC_ALPHA, GLES20.GL_ONE_MINUS_SRC_ALPHA); - ranks[i].setScaleCenter(0, 0); - ranks[i].setScale(1.7f); - ranks[i].setColor(0.6f, 0.6f, 0.6f, 0.9f); - ranks[i].setText("#" + (i + 1)); - ranks[i].setPosition(100 - ranks[i].getWidth(), paddingTop * 2); - s.attachChild(ranks[i]); - s.attachChild(info); - s.setVisible(i == 0 || scoreBoardDatas.length - i < 3); - boards[i] = s; - scene.attachChild(s); - } - playerSprite = new Sprite(0, 0, tex); - playerSprite.setBlendFunction(GLES20.GL_SRC_ALPHA, GLES20.GL_ONE_MINUS_SRC_ALPHA); - playerSprite.setAlpha(0.5f); - playerSprite.setColor(0.5f, 0.5f, 1); - playerText = new ChangeableText(paddingLeft, paddingTop, - ResourceManager.getInstance().getFont("font"), - currentUsername + "\n0\n0x", 100); - playerText.setScaleCenter(0, 0); - playerText.setScale(0.65f); - playerText.setColor(0.85f, 0.85f, 0.9f); - playerRank = new ChangeableText(paddingLeft, paddingTop, - ResourceManager.getInstance().getFont("CaptionFont"), - "#1", 5); - playerRank.setBlendFunction(GLES20.GL_SRC_ALPHA, GLES20.GL_ONE_MINUS_SRC_ALPHA); - playerRank.setScaleCenter(0, 0); - playerRank.setScale(1.7f); - playerRank.setColor(0.6f, 0.6f, 0.6f, 0.9f); - playerRank.setText("#" + (!GlobalManager.getInstance().getSongMenu().isBoardOnline() || posNow < (replayid == -1 ? 20 : 19) ? - String.valueOf(posNow + 1) : "?")); - playerRank.setPosition(100 - playerRank.getWidth(), paddingTop * 2); - playerSprite.attachChild(playerRank); - playerSprite.attachChild(playerText); - itemHeight = 83;//playerSprite.getHeight(); - boards[posNow] = playerSprite; - scene.attachChild(playerSprite); - lastRankChange = System.currentTimeMillis(); - } + public DuringGameScoreBoard(final Scene scene, final StatisticV2 stat, String isNotMe) { + final ScoreBoard.ScoreBoardItems[] items = GlobalManager.getInstance().getSongMenu().getBoard(); + this.stat = stat; + int replayid = GlobalManager.getInstance().getScoring().getReplayID(); + if (replayid == -1) scoreBoardDatas = items; + else { + int replayIndex = -1; + scoreBoardDatas = new ScoreBoard.ScoreBoardItems[items.length - 1]; + for (int i = 0; i < items.length; i++) { + if (replayid == items[i].scoreId) { + replayIndex = i; + continue; + } + scoreBoardDatas[i - (replayIndex != -1 ? 1 : 0)] = items[i]; + } + } + posNow = scoreBoardDatas.length; + currentUsername = isNotMe != null ? isNotMe : + OnlineScoring.getInstance().getPanel() == null ? + Config.getLocalUsername() : + Config.getOnlineUsername(); + TextureRegion tex = ResourceManager.getInstance().getTexture("menu-button-background").deepCopy(); + tex.setHeight(90); + tex.setWidth(130); + boards = new Sprite[scoreBoardDatas.length + 1]; + ranks = new ChangeableText[scoreBoardDatas.length]; + for (int i = 0; i < scoreBoardDatas.length; i++) { + Sprite s = new Sprite(0, 0, tex); + s.setAlpha(0.5f); + s.setColor(scoreBoardDatas[i].userName.equals(currentUsername) && !currentUsername.equals("osu!") ? 1 : 0.5f, 0.5f, 0.5f); + final Text info = new Text(paddingLeft, paddingTop, + ResourceManager.getInstance().getFont("font"), scoreBoardDatas[i].get()); + info.setScaleCenter(0, 0); + info.setScale(0.65f); + info.setColor(0.85f, 0.85f, 0.9f); + ranks[i] = new ChangeableText(paddingLeft, paddingTop, + ResourceManager.getInstance().getFont("CaptionFont"), "#1", 5); + ranks[i].setBlendFunction(GLES20.GL_SRC_ALPHA, GLES20.GL_ONE_MINUS_SRC_ALPHA); + ranks[i].setScaleCenter(0, 0); + ranks[i].setScale(1.7f); + ranks[i].setColor(0.6f, 0.6f, 0.6f, 0.9f); + ranks[i].setText("#" + (i + 1)); + ranks[i].setPosition(100 - ranks[i].getWidth(), paddingTop * 2); + s.attachChild(ranks[i]); + s.attachChild(info); + s.setVisible(i == 0 || scoreBoardDatas.length - i < 3); + boards[i] = s; + scene.attachChild(s); + } + playerSprite = new Sprite(0, 0, tex); + playerSprite.setBlendFunction(GLES20.GL_SRC_ALPHA, GLES20.GL_ONE_MINUS_SRC_ALPHA); + playerSprite.setAlpha(0.5f); + playerSprite.setColor(0.5f, 0.5f, 1); + playerText = new ChangeableText(paddingLeft, paddingTop, + ResourceManager.getInstance().getFont("font"), + currentUsername + "\n0\n0x", 100); + playerText.setScaleCenter(0, 0); + playerText.setScale(0.65f); + playerText.setColor(0.85f, 0.85f, 0.9f); + playerRank = new ChangeableText(paddingLeft, paddingTop, + ResourceManager.getInstance().getFont("CaptionFont"), + "#1", 5); + playerRank.setBlendFunction(GLES20.GL_SRC_ALPHA, GLES20.GL_ONE_MINUS_SRC_ALPHA); + playerRank.setScaleCenter(0, 0); + playerRank.setScale(1.7f); + playerRank.setColor(0.6f, 0.6f, 0.6f, 0.9f); + playerRank.setText("#" + (!GlobalManager.getInstance().getSongMenu().isBoardOnline() || posNow < (replayid == -1 ? 20 : 19) ? + String.valueOf(posNow + 1) : "?")); + playerRank.setPosition(100 - playerRank.getWidth(), paddingTop * 2); + playerSprite.attachChild(playerRank); + playerSprite.attachChild(playerText); + itemHeight = 83;//playerSprite.getHeight(); + boards[posNow] = playerSprite; + scene.attachChild(playerSprite); + lastRankChange = System.currentTimeMillis(); + } - @Override - public void update(float dt) { - float passedAfterChange = (System.currentTimeMillis() - lastRankChange) * 0.001f; - playerSprite.setColor(passedAfterChange < 1 ? 1 - 0.5f * passedAfterChange : 0.5f, passedAfterChange < 1 ? 1 - 0.5f * passedAfterChange : 0.5f, 1, passedAfterChange < 1 ? 1 - 0.5f * passedAfterChange : 0.5f); - int score = stat.getAutoTotalScore(); - playerText.setText(currentUsername + "\n" + - NumberFormat.getNumberInstance(Locale.US).format(score) + "\n" + - NumberFormat.getNumberInstance(Locale.US).format(stat.getMaxCombo()) + "x"); - playerText.setScaleCenter(0, 0); - playerText.setScale(0.65f); - for (int i = posNow - 1; i >= 0; i--) { - if (score > scoreBoardDatas[i].playScore) { - posNow = i; - ranks[i].setText("#" + (i + 2)); - ranks[i].setPosition(100 - ranks[i].getWidth(), paddingTop * 2); - playerRank.setText("#" + (i + 1)); - playerRank.setPosition(100 - playerRank.getWidth(), paddingTop * 2); - lastRankChange = System.currentTimeMillis(); - if (i > 2) { - boards[i].setVisible(false); - boards[i - 2].setVisible(true); - } - playerSprite.setColor(1, 1, 1); - playerSprite.setAlpha(1); - } - } - if (boards.length > 4 && posNow > 3) { - playerSprite.setPosition(0, Config.getRES_HEIGHT() / 2); - boards[posNow - 1].setPosition(0, Config.getRES_HEIGHT() / 2 - itemHeight * 1); - boards[posNow - 2].setPosition(0, Config.getRES_HEIGHT() / 2 - itemHeight * 2); - boards[0].setPosition(0, Config.getRES_HEIGHT() / 2 - itemHeight * 3); - } else { - for (int i = 0; i < 4; i++) { - if (boards.length <= i) break; - boards[i].setPosition(0, - Config.getRES_HEIGHT() / 2 + itemHeight * (i - (posNow <= i ? 2 : 3))); - } - playerSprite.setPosition(0, Config.getRES_HEIGHT() / 2 + itemHeight * (posNow - 3)); - } - } + @Override + public void update(float dt) { + float passedAfterChange = (System.currentTimeMillis() - lastRankChange) * 0.001f; + playerSprite.setColor(passedAfterChange < 1 ? 1 - 0.5f * passedAfterChange : 0.5f, passedAfterChange < 1 ? 1 - 0.5f * passedAfterChange : 0.5f, 1, passedAfterChange < 1 ? 1 - 0.5f * passedAfterChange : 0.5f); + int score = stat.getAutoTotalScore(); + playerText.setText(currentUsername + "\n" + + NumberFormat.getNumberInstance(Locale.US).format(score) + "\n" + + NumberFormat.getNumberInstance(Locale.US).format(stat.getMaxCombo()) + "x"); + playerText.setScaleCenter(0, 0); + playerText.setScale(0.65f); + for (int i = posNow - 1; i >= 0; i--) { + if (score > scoreBoardDatas[i].playScore) { + posNow = i; + ranks[i].setText("#" + (i + 2)); + ranks[i].setPosition(100 - ranks[i].getWidth(), paddingTop * 2); + playerRank.setText("#" + (i + 1)); + playerRank.setPosition(100 - playerRank.getWidth(), paddingTop * 2); + lastRankChange = System.currentTimeMillis(); + if (i > 2) { + boards[i].setVisible(false); + boards[i - 2].setVisible(true); + } + playerSprite.setColor(1, 1, 1); + playerSprite.setAlpha(1); + } + } + if (boards.length > 4 && posNow > 3) { + playerSprite.setPosition(0, Config.getRES_HEIGHT() / 2); + boards[posNow - 1].setPosition(0, Config.getRES_HEIGHT() / 2 - itemHeight * 1); + boards[posNow - 2].setPosition(0, Config.getRES_HEIGHT() / 2 - itemHeight * 2); + boards[0].setPosition(0, Config.getRES_HEIGHT() / 2 - itemHeight * 3); + } else { + for (int i = 0; i < 4; i++) { + if (boards.length <= i) break; + boards[i].setPosition(0, + Config.getRES_HEIGHT() / 2 + itemHeight * (i - (posNow <= i ? 2 : 3))); + } + playerSprite.setPosition(0, Config.getRES_HEIGHT() / 2 + itemHeight * (posNow - 3)); + } + } } diff --git a/src/ru/nsu/ccfit/zuev/osu/game/FollowTrack.java b/src/ru/nsu/ccfit/zuev/osu/game/FollowTrack.java index df329267..2e0548c4 100644 --- a/src/ru/nsu/ccfit/zuev/osu/game/FollowTrack.java +++ b/src/ru/nsu/ccfit/zuev/osu/game/FollowTrack.java @@ -15,136 +15,136 @@ import ru.nsu.ccfit.zuev.osu.helper.AnimSprite; public class FollowTrack extends GameObject { - private final ArrayList points = new ArrayList(); - private final int frameCount; - private GameObjectListener listener; - private float timeLeft; - private float time; - private boolean empty; - private float approach; - - public FollowTrack() { - frameCount = SkinManager.getFrames("followpoint"); - } - - public void init(final GameObjectListener listener, final Scene scene, - final PointF start, final PointF end, final float time, - final float approachtime, final float scale) { - this.listener = listener; - this.approach = approachtime; - timeLeft = time; - this.time = 0; - - final float dist = Utils.distance(start, end); - final float angle = (float) Math.atan2(end.y - start.y, end.x - start.x); - TextureRegion region = ResourceManager.getInstance().getTexture( - frameCount > 1 ? "followpoint-0" : "followpoint"); - if (region == null) { - region = ResourceManager.getInstance().getTexture("followpoint"); - } - final float pointSize = region.getWidth() * scale; - int count = (int) ((dist - 64 * scale) / pointSize); - if (count > 0) { - count--; - } - count = Math.min(count, 30); - if (count <= 0) { - empty = true; - GameObjectPool.getInstance().putTrac(this); - return; - } - empty = false; - - points.clear(); - final PointF pos = new PointF(); - float percent; - for (int i = 0; i < count; i++) { - percent = 1 - (i + 1) / (float) (count + 1)/* - 32 * scale / dist */; - pos.x = start.x * percent + end.x * (1 - percent); - pos.y = start.y * percent + end.y * (1 - percent); - final Sprite point; - if (frameCount == 1) { - point = SpritePool.getInstance().getCenteredSprite( - "followpoint", pos); - } else { - point = SpritePool.getInstance().getAnimSprite("followpoint-", - frameCount); - point.setPosition(pos.x - pointSize * 0.5f, pos.y - pointSize - * 0.5f); - } - point.setScale(scale); - point.setAlpha(0); - point.setRotation((float) (angle * 180 / Math.PI)); - scene.attachChild(point, 0); - points.add(point); - } - - listener.addPassiveObject(this); - } - - - @Override - public void update(final float dt) { - if (empty) { - return; - } - time += dt; - - if (timeLeft <= approach) { - float percent = (time) / (approach * 0.5f); - if (percent > 1) { - percent = 1; - } - for (int i = 0; i < points.size(); i++) { - points.get(i).setAlpha(percent); - } - } else if (time < timeLeft - approach) { - float percent = (time) / (timeLeft - approach); - if (percent > 1) { - percent = 1; - } - for (int i = 0; i < percent * points.size(); i++) { - points.get(i).setAlpha(1); - } - if (percent < 1) { - points.get((int) (percent * points.size())).setAlpha( - percent - (int) percent); - } - } else { - float percent = 1 - (timeLeft - time) / approach; - if (percent > 1) { - percent = 1; - } - for (int i = 0; i < percent * points.size(); i++) { - points.get(i).setAlpha(0); - } - if (percent >= 0 && percent < 1) { - points.get((int) (percent * points.size())).setAlpha( - 1 - percent + (int) percent); - } - } - - if (time >= timeLeft) { - empty = true; - SyncTaskManager.getInstance().run(new Runnable() { - - - public void run() { - for (final Sprite sp : points) { - sp.detachSelf(); - if (sp instanceof AnimSprite) { - SpritePool.getInstance().putAnimSprite( - "followpoint-", (AnimSprite) sp); - } else { - SpritePool.getInstance().putSprite("followpoint", - sp); - } - } - listener.removePassiveObject(FollowTrack.this); - GameObjectPool.getInstance().putTrac(FollowTrack.this); - } - }); - } - } + private final ArrayList points = new ArrayList(); + private final int frameCount; + private GameObjectListener listener; + private float timeLeft; + private float time; + private boolean empty; + private float approach; + + public FollowTrack() { + frameCount = SkinManager.getFrames("followpoint"); + } + + public void init(final GameObjectListener listener, final Scene scene, + final PointF start, final PointF end, final float time, + final float approachtime, final float scale) { + this.listener = listener; + this.approach = approachtime; + timeLeft = time; + this.time = 0; + + final float dist = Utils.distance(start, end); + final float angle = (float) Math.atan2(end.y - start.y, end.x - start.x); + TextureRegion region = ResourceManager.getInstance().getTexture( + frameCount > 1 ? "followpoint-0" : "followpoint"); + if (region == null) { + region = ResourceManager.getInstance().getTexture("followpoint"); + } + final float pointSize = region.getWidth() * scale; + int count = (int) ((dist - 64 * scale) / pointSize); + if (count > 0) { + count--; + } + count = Math.min(count, 30); + if (count <= 0) { + empty = true; + GameObjectPool.getInstance().putTrac(this); + return; + } + empty = false; + + points.clear(); + final PointF pos = new PointF(); + float percent; + for (int i = 0; i < count; i++) { + percent = 1 - (i + 1) / (float) (count + 1)/* - 32 * scale / dist */; + pos.x = start.x * percent + end.x * (1 - percent); + pos.y = start.y * percent + end.y * (1 - percent); + final Sprite point; + if (frameCount == 1) { + point = SpritePool.getInstance().getCenteredSprite( + "followpoint", pos); + } else { + point = SpritePool.getInstance().getAnimSprite("followpoint-", + frameCount); + point.setPosition(pos.x - pointSize * 0.5f, pos.y - pointSize + * 0.5f); + } + point.setScale(scale); + point.setAlpha(0); + point.setRotation((float) (angle * 180 / Math.PI)); + scene.attachChild(point, 0); + points.add(point); + } + + listener.addPassiveObject(this); + } + + + @Override + public void update(final float dt) { + if (empty) { + return; + } + time += dt; + + if (timeLeft <= approach) { + float percent = (time) / (approach * 0.5f); + if (percent > 1) { + percent = 1; + } + for (int i = 0; i < points.size(); i++) { + points.get(i).setAlpha(percent); + } + } else if (time < timeLeft - approach) { + float percent = (time) / (timeLeft - approach); + if (percent > 1) { + percent = 1; + } + for (int i = 0; i < percent * points.size(); i++) { + points.get(i).setAlpha(1); + } + if (percent < 1) { + points.get((int) (percent * points.size())).setAlpha( + percent - (int) percent); + } + } else { + float percent = 1 - (timeLeft - time) / approach; + if (percent > 1) { + percent = 1; + } + for (int i = 0; i < percent * points.size(); i++) { + points.get(i).setAlpha(0); + } + if (percent >= 0 && percent < 1) { + points.get((int) (percent * points.size())).setAlpha( + 1 - percent + (int) percent); + } + } + + if (time >= timeLeft) { + empty = true; + SyncTaskManager.getInstance().run(new Runnable() { + + + public void run() { + for (final Sprite sp : points) { + sp.detachSelf(); + if (sp instanceof AnimSprite) { + SpritePool.getInstance().putAnimSprite( + "followpoint-", (AnimSprite) sp); + } else { + SpritePool.getInstance().putSprite("followpoint", + sp); + } + } + listener.removePassiveObject(FollowTrack.this); + GameObjectPool.getInstance().putTrac(FollowTrack.this); + } + }); + } + } } diff --git a/src/ru/nsu/ccfit/zuev/osu/game/GameEffect.java b/src/ru/nsu/ccfit/zuev/osu/game/GameEffect.java index 329ae43a..80cd0801 100644 --- a/src/ru/nsu/ccfit/zuev/osu/game/GameEffect.java +++ b/src/ru/nsu/ccfit/zuev/osu/game/GameEffect.java @@ -23,78 +23,78 @@ import ru.nsu.ccfit.zuev.osu.helper.AnimSprite; public class GameEffect extends GameObject implements IEntityModifierListener { - private static final HashSet animationEffects = new HashSet<>(Arrays.asList( - "hit0", "hit50", "hit100", "hit100k", "hit300", "hit300k", "hit300g" - )); - - Sprite hit; - String texname; - - public GameEffect(final String texname) { - this.texname = texname; - - if (isAnimationEffect(texname) && ResourceManager.getInstance().isTextureLoaded(texname + "-0")) { - List loadedScoreBarTextures = new ArrayList<>(); - for (int i = 0; i < 60; i++) { - if (ResourceManager.getInstance().isTextureLoaded(texname + "-" + i)) - loadedScoreBarTextures.add(texname + "-" + i); - else break; - } - AnimSprite hit = new AnimSprite(0, 0, 60, loadedScoreBarTextures.toArray(new String[0])); - hit.setLoopType(AnimSprite.LoopType.STOP); - this.hit = hit; - } else { - hit = new Sprite(0, 0, ResourceManager.getInstance().getTexture(texname)); - } - } - - private static boolean isAnimationEffect(String textureName) { - return animationEffects.contains(textureName); - } - - public void setColor(final RGBColor color) { - hit.setColor(color.r(), color.g(), color.b()); - } - - public void init(final Scene scene, final PointF pos, final float scale, - final IEntityModifier... entityModifiers) { - if (hit instanceof AnimSprite) { - ((AnimSprite) hit).setAnimTime(0); - } - hit.setPosition(pos.x - hit.getTextureRegion().getWidth() / 2f, pos.y - - hit.getTextureRegion().getHeight() / 2f); - hit.registerEntityModifier(new ParallelEntityModifier(this, - entityModifiers)); - hit.setScale(scale); - hit.setAlpha(1); - hit.detachSelf(); - hit.setBlendFunction(Shape.BLENDFUNCTION_SOURCE_DEFAULT, Shape.BLENDFUNCTION_DESTINATION_DEFAULT); - scene.attachChild(hit); - } - - public void setBlendFunction(int sourceBlend, int destBlend) { - hit.setBlendFunction(sourceBlend, destBlend); - } - - public String getTexname() { - return texname; - } - - @Override - public void update(final float dt) { - } - - @Override - public void onModifierStarted(final IModifier pModifier, final IEntity pItem) { - - } - - @Override - public void onModifierFinished(final IModifier pModifier, final IEntity pItem) { - SyncTaskManager.getInstance().run(() -> { - hit.detachSelf(); - hit.clearEntityModifiers(); - GameObjectPool.getInstance().putEffect(GameEffect.this); - }); - } + private static final HashSet animationEffects = new HashSet<>(Arrays.asList( + "hit0", "hit50", "hit100", "hit100k", "hit300", "hit300k", "hit300g" + )); + + Sprite hit; + String texname; + + public GameEffect(final String texname) { + this.texname = texname; + + if (isAnimationEffect(texname) && ResourceManager.getInstance().isTextureLoaded(texname + "-0")) { + List loadedScoreBarTextures = new ArrayList<>(); + for (int i = 0; i < 60; i++) { + if (ResourceManager.getInstance().isTextureLoaded(texname + "-" + i)) + loadedScoreBarTextures.add(texname + "-" + i); + else break; + } + AnimSprite hit = new AnimSprite(0, 0, 60, loadedScoreBarTextures.toArray(new String[0])); + hit.setLoopType(AnimSprite.LoopType.STOP); + this.hit = hit; + } else { + hit = new Sprite(0, 0, ResourceManager.getInstance().getTexture(texname)); + } + } + + private static boolean isAnimationEffect(String textureName) { + return animationEffects.contains(textureName); + } + + public void setColor(final RGBColor color) { + hit.setColor(color.r(), color.g(), color.b()); + } + + public void init(final Scene scene, final PointF pos, final float scale, + final IEntityModifier... entityModifiers) { + if (hit instanceof AnimSprite) { + ((AnimSprite) hit).setAnimTime(0); + } + hit.setPosition(pos.x - hit.getTextureRegion().getWidth() / 2f, pos.y + - hit.getTextureRegion().getHeight() / 2f); + hit.registerEntityModifier(new ParallelEntityModifier(this, + entityModifiers)); + hit.setScale(scale); + hit.setAlpha(1); + hit.detachSelf(); + hit.setBlendFunction(Shape.BLENDFUNCTION_SOURCE_DEFAULT, Shape.BLENDFUNCTION_DESTINATION_DEFAULT); + scene.attachChild(hit); + } + + public void setBlendFunction(int sourceBlend, int destBlend) { + hit.setBlendFunction(sourceBlend, destBlend); + } + + public String getTexname() { + return texname; + } + + @Override + public void update(final float dt) { + } + + @Override + public void onModifierStarted(final IModifier pModifier, final IEntity pItem) { + + } + + @Override + public void onModifierFinished(final IModifier pModifier, final IEntity pItem) { + SyncTaskManager.getInstance().run(() -> { + hit.detachSelf(); + hit.clearEntityModifiers(); + GameObjectPool.getInstance().putEffect(GameEffect.this); + }); + } } diff --git a/src/ru/nsu/ccfit/zuev/osu/game/GameHelper.java b/src/ru/nsu/ccfit/zuev/osu/game/GameHelper.java index 51dbaabe..1bf9201f 100644 --- a/src/ru/nsu/ccfit/zuev/osu/game/GameHelper.java +++ b/src/ru/nsu/ccfit/zuev/osu/game/GameHelper.java @@ -20,529 +20,529 @@ import ru.nsu.ccfit.zuev.osu.polygon.Spline; public class GameHelper { - public static ControlPoints controlPoints; - private static double binomTable[][]; - private static int binomTableN; - private static float tickRate = 1; - private static float scale = 1; - private static float speed = 1; - private static float difficulty = 1; - private static float approachRate = 1; - private static float drain = 0; - private static float stackLatient = 0; - private static float timeMultiplier = 0; - private static RGBColor sliderColor = new RGBColor(); - private static boolean hidden = false; - private static boolean flashLight = false; - private static boolean hardrock = false; - private static boolean relaxMod = false; - private static boolean doubleTime = false; - private static boolean nightCore = false; - private static boolean speedUp = false; - private static boolean halfTime = false; - private static boolean autopilotMod = false; - private static boolean suddenDeath = false; - private static boolean perfect = false; - private static boolean useReplay; - private static boolean isKiai = false; - private static boolean auto = false; - private static float beatLength = 0; - private static float timingOffset = 0; - private static int timeSignature = 4; - private static float initalBeatLength = 0; - private static float globalTime = 0; - private static Spline.CurveTypes curveType; - private static int gameid = 0; - private static Queue pathPool = new LinkedList(); - private static Queue pointPool = new LinkedList(); - - private static DifficultyHelper difficultyHelper = DifficultyHelper.StdDifficulty; - - static { - binomTableN = 35; - binomTable = new double[binomTableN][binomTableN]; - for (int n = 0; n < binomTableN; n++) { - for (int k = 0; k < binomTableN; k++) { - if (n == 0) { - binomTable[n][k] = 0; - continue; - } - if (k == 0) { - binomTable[n][k] = 1; - continue; - } - binomTable[n][k] = 1; - for (int i = 1; i <= k; i++) { - binomTable[n][k] *= (n - k + i) / (double) i; - } - } - } - } - - public static DifficultyHelper getDifficultyHelper() { - return difficultyHelper; - } - - public static void setDifficultyHelper(DifficultyHelper difficultyHelper) { - GameHelper.difficultyHelper = difficultyHelper; - } - - public static float getDrain() { - return drain; - } - - public static void setDrain(final float drain) { - GameHelper.drain = drain; - } - - public static float getDifficulty() { - return difficulty; - } - - public static void setDifficulty(final float difficulty) { - GameHelper.difficulty = difficulty; - } - - public static float getTickRate() { - return tickRate; - } - - public static void setTickRate(final float tickRate) { - GameHelper.tickRate = tickRate; - } - - public static int getGameid() { - return gameid; - } - - public static void updateGameid() { - gameid = (new Random().nextInt(233333333) + 1); - } - - public static PointF getBezier(final float t, final ArrayList points) { - final PointF b = newPointF(); - b.set(0, 0); - final int n = points.size() - 1; - // This is formula for Bezier curve from wiki: - // B(t) = Sum[i = 0..n]( Bi(t) * Pi ) - for (int i = 0; i <= n; i++) { - // Bi(t) = C(n,i) * t^i * (1-t)^(n-i) - final double bi = binomial(n, i) * Math.pow(t, i) - * Math.pow(1 - t, n - i); - b.x += points.get(i).x * bi; - b.y += points.get(i).y * bi; - } - - return b; - } - - private static double binomial(final int n, final int k) { - if (n <= 0) { - return 0; - } - if (k <= 0) { - return 1; - } - if (n < binomTableN && k < binomTableN) { - return binomTable[n][k]; - } else { - return binomial(n - 1, k - 1) + binomial(n - 1, k); - } - } - - public static ArrayList parseSection( - final ArrayList rawPoints) { - final ArrayList result = new ArrayList(); - final PointF pos = rawPoints.get(0); - final PointF endpos = rawPoints.get(rawPoints.size() - 1); - - if (rawPoints.size() < 2) { - result.add(pos); - return result; - } - - result.add(pos); - result.add(getBezier(0.5f, rawPoints)); - result.add(endpos); - int index = 0; - - final ArrayList ts = new ArrayList(); - ts.add(new Float(0)); - ts.add(new Float(0.5f)); - ts.add(new Float(1)); - float step2 = Constants.SLIDER_STEP * scale; -// if (Config.isLowpolySliders() == false) { -// step2 = Constants.HIGH_SLIDER_STEP * scale; -// } - step2 *= step2; - while (index < result.size() - 1) { - while (Utils.squaredDistance(result.get(index).x, - result.get(index).y, result.get(index + 1).x, - result.get(index + 1).y) > step2) { - final float t = (ts.get(index) + ts.get(index + 1)) / 2f; - result.add(index + 1, getBezier(t, rawPoints)); - ts.add(index + 1, t); - } - index++; - } - - return result; - } - - public static SliderPath calculatePath(final PointF pos, - final String[] data, final float maxLength, final float offset) { - final ArrayList> points = new ArrayList>(); - points.add(new ArrayList()); - int lastIndex = 0; - points.get(lastIndex).add(pos); - - final SliderPath path = newPath(); - - for (final String s : data) { - if (s == data[0]) { - curveType = Spline.getCurveType(s.charAt(0)); - continue; - } - final String[] nums = s.split("[:]"); - final PointF point = newPointF(); - point.set(Integer.parseInt(nums[0]), Integer.parseInt(nums[1])); - point.x += offset; - point.y += offset; - final PointF ppoint = points.get(lastIndex).get( - points.get(lastIndex).size() - 1); - if (point.x == ppoint.x && point.y == ppoint.y - || (Config.isAccurateSlider() == false && (data[0].equals("L") || data[0].equals("C")))) { - if (Config.isAccurateSlider() == false && (data[0].equals("L") || data[0].equals("C"))) { - points.get(lastIndex).add(point); - } - points.add(new ArrayList()); - lastIndex++; - } - points.get(lastIndex).add(point); - } - - ArrayList section; - int pind = -1; - float trackLength = 0; - final PointF vec = newPointF(); - - MainCycle: - for (final ArrayList plist : points) { - if (Config.isAccurateSlider() == true) { - final Spline spline = Spline.getInstance(); - spline.setControlPoints(plist); - spline.setType(curveType); - spline.Refresh(); - section = spline.getPoints(); - } else { - section = parseSection(plist); - } - // Debug.i("section size=" + section.size()); - boolean firstPut = false; - for (final PointF p : section) { - if (pind < 0 - || Math.abs(p.x - path.points.get(pind).x) - + Math.abs(p.y - path.points.get(pind).y) > 1f) { - if (firstPut == false) { - firstPut = true; - path.boundIndexes.add(path.points.size()); - } - if (path.points.isEmpty() == false) { - vec.set(p.x - path.points.get(path.points.size() - 1).x, - p.y - path.points.get(path.points.size() - 1).y); - trackLength += Utils.length(vec); - path.length.add(trackLength); - } - path.points.add(p); - pind++; - - if (trackLength >= maxLength) { - if (path.points.isEmpty() == false) { - path.boundIndexes.add(path.points.size() - 1); - } - break MainCycle; - } - } - } - if (path.points.isEmpty() == false) { - path.boundIndexes.add(path.points.size() - 1); - } - } - - for (int i = 0; i < path.points.size(); i++) { - path.points.set(i, Utils.trackToRealCoords(path.points.get(i))); - } - - if (path.points.size() == 1) { - path.points.add(new PointF(path.points.get(0).x, - path.points.get(0).y)); - path.length.add(new Float(0)); - } - - return path; - } - - public static float getScale() { - return scale; - } - - public static void setScale(final float scale) { - GameHelper.scale = scale; - } - - public static float getApproachRate() { - return approachRate; - } - - public static void setApproachRate(float approachRate) { - GameHelper.approachRate = approachRate; - } - - public static float getTimeMultiplier() { - return timeMultiplier; - } - - public static void setTimeMultiplier(float timeMultiplier) { - GameHelper.timeMultiplier = timeMultiplier; - } - - public static float getSpeed() { - return speed; - } - - public static void setSpeed(final float speed) { - GameHelper.speed = speed; - } - - public static void putPath(final SliderPath path) { - for (final PointF p : path.points) { - pointPool.add(p); - } - path.points.clear(); - path.length.clear(); - path.boundIndexes.clear(); - pathPool.add(path); - } - - private static SliderPath newPath() { - if (pathPool.isEmpty()) { - return new SliderPath(); - } - return pathPool.poll(); - } - - private static PointF newPointF() { - if (pointPool.isEmpty()) { - return new PointF(); - } - return pointPool.poll(); - } - - public static float getStackLatient() { - return stackLatient; - } - - public static void setStackLatient(final float stackLatient) { - GameHelper.stackLatient = stackLatient; - } - - public static RGBColor getSliderColor() { - return sliderColor; - } - - public static void setSliderColor(final RGBColor sliderColor) { - GameHelper.sliderColor = sliderColor; - } - - public static boolean isHardrock() { - return hardrock; - } - - public static void setHardrock(final boolean hardrock) { - GameHelper.hardrock = hardrock; - } - - public static boolean isHidden() { - return hidden; - } - - public static void setHidden(final boolean hidden) { - GameHelper.hidden = hidden; - } - - public static boolean isFlashLight() { - return flashLight; - } - - public static void setFlashLight(final boolean flashLight) { - GameHelper.flashLight = flashLight; - } - public static boolean isHalfTime() { - return halfTime; - } - - public static void setHalfTime(final boolean halfTime) { - GameHelper.halfTime = halfTime; - } - - public static boolean isNightCore() { - return nightCore; - } - - public static void setNightCore(final boolean nightCore) { - GameHelper.nightCore = nightCore; - } - - public static boolean isDoubleTime() { - return doubleTime; - } - - public static void setDoubleTime(final boolean doubleTime) { - GameHelper.doubleTime = doubleTime; - } - - public static boolean isSpeedUp() { - return speedUp; - } - - public static void setSpeedUp(final boolean speedUp) { - GameHelper.speedUp = speedUp; - } - public static boolean isSuddenDeath() { - return suddenDeath; - } - - public static void setSuddenDeath(final boolean suddenDeath) { - GameHelper.suddenDeath = suddenDeath; - } - - public static boolean isPerfect() { - return perfect; - } - - public static void setPerfect(final boolean perfect) { - GameHelper.perfect = perfect; - } - - public static boolean isUseReplay() { - return useReplay; - } - - public static void setUseReplay(final boolean useReplay) { - GameHelper.useReplay = useReplay; - } - - public static boolean isKiai() { - if (SkinJson.get().isDisableKiai()) return false; - return isKiai; - } - - public static void setKiai(final boolean isKiai) { - GameHelper.isKiai = isKiai; - } - - public static float getGlobalTime() { - return globalTime; - } - - public static void setGlobalTime(final float globalTime) { - GameHelper.globalTime = globalTime; - } - - public static float getBeatLength() { - return beatLength; - } - - public static void setBeatLength(final float beatLength) { - GameHelper.beatLength = beatLength; - } - - public static float getTimingOffset() { - return timingOffset; - } - - public static void setTimingOffset(float timingOffset) { - GameHelper.timingOffset = timingOffset; - } - - public static int getTimeSignature() { - return timeSignature; - } - - public static void setTimeSignature(int timeSignature) { - GameHelper.timeSignature = timeSignature; - } - - public static float getInitalBeatLength() { - return initalBeatLength; - } - - public static void setInitalBeatLength(float initalBeatLength) { - GameHelper.initalBeatLength = initalBeatLength; - } - - public static float getSliderTickLength() { - return 100f * initalBeatLength / speed; - } - - public static float getKiaiTickLength() { - return initalBeatLength; - } - - public static boolean isRelaxMod() { - return relaxMod; - } - - public static void setRelaxMod(boolean relaxMod) { - GameHelper.relaxMod = relaxMod; - } - - public static boolean isAutopilotMod() { - return autopilotMod; - } - - public static void setAutopilotMod(boolean autopilotMod) { - GameHelper.autopilotMod = autopilotMod; - } - - public static boolean isAuto() { - return auto; - } - - public static void setAuto(boolean auto) { - GameHelper.auto = auto; - } - - public static float Round(double value, int digits) throws NumberFormatException { - if (Math.abs(value) < Double.MAX_VALUE) { - float f1 = 0; - BigDecimal b = new BigDecimal(value); - f1 = b.setScale(digits, RoundingMode.HALF_UP).floatValue(); - return f1; - } else { - return value > 0 ? Float.POSITIVE_INFINITY : Float.NEGATIVE_INFINITY; - } - } - - public static double ar2ms(double ar) { - return Round((ar <= 5) ? (1800 - 120 * ar) : (1950 - 150 * ar), 0); - } - - public static double ms2ar(double ms) { - return (ms <= 1200) ? ((1200 - ms) / 150.0 + 5) : (1800 - ms) / 120.0; - } - - public static double ms2od(double ms) { - return (80 - ms) / 6.0; - } - - public static double od2ms(double od) { - return Round(80 - od * 6, 1); - } - - public static class SliderPath { - public ArrayList points = new ArrayList(); - public ArrayList length = new ArrayList(); - public ArrayList boundIndexes = new ArrayList(); - } + public static ControlPoints controlPoints; + private static double binomTable[][]; + private static int binomTableN; + private static float tickRate = 1; + private static float scale = 1; + private static float speed = 1; + private static float difficulty = 1; + private static float approachRate = 1; + private static float drain = 0; + private static float stackLatient = 0; + private static float timeMultiplier = 0; + private static RGBColor sliderColor = new RGBColor(); + private static boolean hidden = false; + private static boolean flashLight = false; + private static boolean hardrock = false; + private static boolean relaxMod = false; + private static boolean doubleTime = false; + private static boolean nightCore = false; + private static boolean speedUp = false; + private static boolean halfTime = false; + private static boolean autopilotMod = false; + private static boolean suddenDeath = false; + private static boolean perfect = false; + private static boolean useReplay; + private static boolean isKiai = false; + private static boolean auto = false; + private static float beatLength = 0; + private static float timingOffset = 0; + private static int timeSignature = 4; + private static float initalBeatLength = 0; + private static float globalTime = 0; + private static Spline.CurveTypes curveType; + private static int gameid = 0; + private static Queue pathPool = new LinkedList(); + private static Queue pointPool = new LinkedList(); + + private static DifficultyHelper difficultyHelper = DifficultyHelper.StdDifficulty; + + static { + binomTableN = 35; + binomTable = new double[binomTableN][binomTableN]; + for (int n = 0; n < binomTableN; n++) { + for (int k = 0; k < binomTableN; k++) { + if (n == 0) { + binomTable[n][k] = 0; + continue; + } + if (k == 0) { + binomTable[n][k] = 1; + continue; + } + binomTable[n][k] = 1; + for (int i = 1; i <= k; i++) { + binomTable[n][k] *= (n - k + i) / (double) i; + } + } + } + } + + public static DifficultyHelper getDifficultyHelper() { + return difficultyHelper; + } + + public static void setDifficultyHelper(DifficultyHelper difficultyHelper) { + GameHelper.difficultyHelper = difficultyHelper; + } + + public static float getDrain() { + return drain; + } + + public static void setDrain(final float drain) { + GameHelper.drain = drain; + } + + public static float getDifficulty() { + return difficulty; + } + + public static void setDifficulty(final float difficulty) { + GameHelper.difficulty = difficulty; + } + + public static float getTickRate() { + return tickRate; + } + + public static void setTickRate(final float tickRate) { + GameHelper.tickRate = tickRate; + } + + public static int getGameid() { + return gameid; + } + + public static void updateGameid() { + gameid = (new Random().nextInt(233333333) + 1); + } + + public static PointF getBezier(final float t, final ArrayList points) { + final PointF b = newPointF(); + b.set(0, 0); + final int n = points.size() - 1; + // This is formula for Bezier curve from wiki: + // B(t) = Sum[i = 0..n]( Bi(t) * Pi ) + for (int i = 0; i <= n; i++) { + // Bi(t) = C(n,i) * t^i * (1-t)^(n-i) + final double bi = binomial(n, i) * Math.pow(t, i) + * Math.pow(1 - t, n - i); + b.x += points.get(i).x * bi; + b.y += points.get(i).y * bi; + } + + return b; + } + + private static double binomial(final int n, final int k) { + if (n <= 0) { + return 0; + } + if (k <= 0) { + return 1; + } + if (n < binomTableN && k < binomTableN) { + return binomTable[n][k]; + } else { + return binomial(n - 1, k - 1) + binomial(n - 1, k); + } + } + + public static ArrayList parseSection( + final ArrayList rawPoints) { + final ArrayList result = new ArrayList(); + final PointF pos = rawPoints.get(0); + final PointF endpos = rawPoints.get(rawPoints.size() - 1); + + if (rawPoints.size() < 2) { + result.add(pos); + return result; + } + + result.add(pos); + result.add(getBezier(0.5f, rawPoints)); + result.add(endpos); + int index = 0; + + final ArrayList ts = new ArrayList(); + ts.add(new Float(0)); + ts.add(new Float(0.5f)); + ts.add(new Float(1)); + float step2 = Constants.SLIDER_STEP * scale; +// if (Config.isLowpolySliders() == false) { +// step2 = Constants.HIGH_SLIDER_STEP * scale; +// } + step2 *= step2; + while (index < result.size() - 1) { + while (Utils.squaredDistance(result.get(index).x, + result.get(index).y, result.get(index + 1).x, + result.get(index + 1).y) > step2) { + final float t = (ts.get(index) + ts.get(index + 1)) / 2f; + result.add(index + 1, getBezier(t, rawPoints)); + ts.add(index + 1, t); + } + index++; + } + + return result; + } + + public static SliderPath calculatePath(final PointF pos, + final String[] data, final float maxLength, final float offset) { + final ArrayList> points = new ArrayList>(); + points.add(new ArrayList()); + int lastIndex = 0; + points.get(lastIndex).add(pos); + + final SliderPath path = newPath(); + + for (final String s : data) { + if (s == data[0]) { + curveType = Spline.getCurveType(s.charAt(0)); + continue; + } + final String[] nums = s.split("[:]"); + final PointF point = newPointF(); + point.set(Integer.parseInt(nums[0]), Integer.parseInt(nums[1])); + point.x += offset; + point.y += offset; + final PointF ppoint = points.get(lastIndex).get( + points.get(lastIndex).size() - 1); + if (point.x == ppoint.x && point.y == ppoint.y + || (Config.isAccurateSlider() == false && (data[0].equals("L") || data[0].equals("C")))) { + if (Config.isAccurateSlider() == false && (data[0].equals("L") || data[0].equals("C"))) { + points.get(lastIndex).add(point); + } + points.add(new ArrayList()); + lastIndex++; + } + points.get(lastIndex).add(point); + } + + ArrayList section; + int pind = -1; + float trackLength = 0; + final PointF vec = newPointF(); + + MainCycle: + for (final ArrayList plist : points) { + if (Config.isAccurateSlider() == true) { + final Spline spline = Spline.getInstance(); + spline.setControlPoints(plist); + spline.setType(curveType); + spline.Refresh(); + section = spline.getPoints(); + } else { + section = parseSection(plist); + } + // Debug.i("section size=" + section.size()); + boolean firstPut = false; + for (final PointF p : section) { + if (pind < 0 + || Math.abs(p.x - path.points.get(pind).x) + + Math.abs(p.y - path.points.get(pind).y) > 1f) { + if (firstPut == false) { + firstPut = true; + path.boundIndexes.add(path.points.size()); + } + if (path.points.isEmpty() == false) { + vec.set(p.x - path.points.get(path.points.size() - 1).x, + p.y - path.points.get(path.points.size() - 1).y); + trackLength += Utils.length(vec); + path.length.add(trackLength); + } + path.points.add(p); + pind++; + + if (trackLength >= maxLength) { + if (path.points.isEmpty() == false) { + path.boundIndexes.add(path.points.size() - 1); + } + break MainCycle; + } + } + } + if (path.points.isEmpty() == false) { + path.boundIndexes.add(path.points.size() - 1); + } + } + + for (int i = 0; i < path.points.size(); i++) { + path.points.set(i, Utils.trackToRealCoords(path.points.get(i))); + } + + if (path.points.size() == 1) { + path.points.add(new PointF(path.points.get(0).x, + path.points.get(0).y)); + path.length.add(new Float(0)); + } + + return path; + } + + public static float getScale() { + return scale; + } + + public static void setScale(final float scale) { + GameHelper.scale = scale; + } + + public static float getApproachRate() { + return approachRate; + } + + public static void setApproachRate(float approachRate) { + GameHelper.approachRate = approachRate; + } + + public static float getTimeMultiplier() { + return timeMultiplier; + } + + public static void setTimeMultiplier(float timeMultiplier) { + GameHelper.timeMultiplier = timeMultiplier; + } + + public static float getSpeed() { + return speed; + } + + public static void setSpeed(final float speed) { + GameHelper.speed = speed; + } + + public static void putPath(final SliderPath path) { + for (final PointF p : path.points) { + pointPool.add(p); + } + path.points.clear(); + path.length.clear(); + path.boundIndexes.clear(); + pathPool.add(path); + } + + private static SliderPath newPath() { + if (pathPool.isEmpty()) { + return new SliderPath(); + } + return pathPool.poll(); + } + + private static PointF newPointF() { + if (pointPool.isEmpty()) { + return new PointF(); + } + return pointPool.poll(); + } + + public static float getStackLatient() { + return stackLatient; + } + + public static void setStackLatient(final float stackLatient) { + GameHelper.stackLatient = stackLatient; + } + + public static RGBColor getSliderColor() { + return sliderColor; + } + + public static void setSliderColor(final RGBColor sliderColor) { + GameHelper.sliderColor = sliderColor; + } + + public static boolean isHardrock() { + return hardrock; + } + + public static void setHardrock(final boolean hardrock) { + GameHelper.hardrock = hardrock; + } + + public static boolean isHidden() { + return hidden; + } + + public static void setHidden(final boolean hidden) { + GameHelper.hidden = hidden; + } + + public static boolean isFlashLight() { + return flashLight; + } + + public static void setFlashLight(final boolean flashLight) { + GameHelper.flashLight = flashLight; + } + public static boolean isHalfTime() { + return halfTime; + } + + public static void setHalfTime(final boolean halfTime) { + GameHelper.halfTime = halfTime; + } + + public static boolean isNightCore() { + return nightCore; + } + + public static void setNightCore(final boolean nightCore) { + GameHelper.nightCore = nightCore; + } + + public static boolean isDoubleTime() { + return doubleTime; + } + + public static void setDoubleTime(final boolean doubleTime) { + GameHelper.doubleTime = doubleTime; + } + + public static boolean isSpeedUp() { + return speedUp; + } + + public static void setSpeedUp(final boolean speedUp) { + GameHelper.speedUp = speedUp; + } + public static boolean isSuddenDeath() { + return suddenDeath; + } + + public static void setSuddenDeath(final boolean suddenDeath) { + GameHelper.suddenDeath = suddenDeath; + } + + public static boolean isPerfect() { + return perfect; + } + + public static void setPerfect(final boolean perfect) { + GameHelper.perfect = perfect; + } + + public static boolean isUseReplay() { + return useReplay; + } + + public static void setUseReplay(final boolean useReplay) { + GameHelper.useReplay = useReplay; + } + + public static boolean isKiai() { + if (SkinJson.get().isDisableKiai()) return false; + return isKiai; + } + + public static void setKiai(final boolean isKiai) { + GameHelper.isKiai = isKiai; + } + + public static float getGlobalTime() { + return globalTime; + } + + public static void setGlobalTime(final float globalTime) { + GameHelper.globalTime = globalTime; + } + + public static float getBeatLength() { + return beatLength; + } + + public static void setBeatLength(final float beatLength) { + GameHelper.beatLength = beatLength; + } + + public static float getTimingOffset() { + return timingOffset; + } + + public static void setTimingOffset(float timingOffset) { + GameHelper.timingOffset = timingOffset; + } + + public static int getTimeSignature() { + return timeSignature; + } + + public static void setTimeSignature(int timeSignature) { + GameHelper.timeSignature = timeSignature; + } + + public static float getInitalBeatLength() { + return initalBeatLength; + } + + public static void setInitalBeatLength(float initalBeatLength) { + GameHelper.initalBeatLength = initalBeatLength; + } + + public static float getSliderTickLength() { + return 100f * initalBeatLength / speed; + } + + public static float getKiaiTickLength() { + return initalBeatLength; + } + + public static boolean isRelaxMod() { + return relaxMod; + } + + public static void setRelaxMod(boolean relaxMod) { + GameHelper.relaxMod = relaxMod; + } + + public static boolean isAutopilotMod() { + return autopilotMod; + } + + public static void setAutopilotMod(boolean autopilotMod) { + GameHelper.autopilotMod = autopilotMod; + } + + public static boolean isAuto() { + return auto; + } + + public static void setAuto(boolean auto) { + GameHelper.auto = auto; + } + + public static float Round(double value, int digits) throws NumberFormatException { + if (Math.abs(value) < Double.MAX_VALUE) { + float f1 = 0; + BigDecimal b = new BigDecimal(value); + f1 = b.setScale(digits, RoundingMode.HALF_UP).floatValue(); + return f1; + } else { + return value > 0 ? Float.POSITIVE_INFINITY : Float.NEGATIVE_INFINITY; + } + } + + public static double ar2ms(double ar) { + return Round((ar <= 5) ? (1800 - 120 * ar) : (1950 - 150 * ar), 0); + } + + public static double ms2ar(double ms) { + return (ms <= 1200) ? ((1200 - ms) / 150.0 + 5) : (1800 - ms) / 120.0; + } + + public static double ms2od(double ms) { + return (80 - ms) / 6.0; + } + + public static double od2ms(double od) { + return Round(80 - od * 6, 1); + } + + public static class SliderPath { + public ArrayList points = new ArrayList(); + public ArrayList length = new ArrayList(); + public ArrayList boundIndexes = new ArrayList(); + } } diff --git a/src/ru/nsu/ccfit/zuev/osu/game/GameObject.java b/src/ru/nsu/ccfit/zuev/osu/game/GameObject.java index 70a54cbc..17f6d925 100644 --- a/src/ru/nsu/ccfit/zuev/osu/game/GameObject.java +++ b/src/ru/nsu/ccfit/zuev/osu/game/GameObject.java @@ -5,53 +5,53 @@ import ru.nsu.ccfit.zuev.osu.scoring.Replay.ReplayObjectData; public abstract class GameObject { - protected boolean endsCombo; - protected boolean autoPlay = false; - protected float hitTime = 0; - protected int id = -1; - protected ReplayObjectData replayData = null; - protected boolean startHit = false; - protected PointF pos = new PointF(); + protected boolean endsCombo; + protected boolean autoPlay = false; + protected float hitTime = 0; + protected int id = -1; + protected ReplayObjectData replayData = null; + protected boolean startHit = false; + protected PointF pos = new PointF(); - public ReplayObjectData getReplayData() { - return replayData; - } + public ReplayObjectData getReplayData() { + return replayData; + } - public void setReplayData(ReplayObjectData replayData) { - this.replayData = replayData; - } + public void setReplayData(ReplayObjectData replayData) { + this.replayData = replayData; + } - public void setEndsCombo(final boolean endsCombo) { - this.endsCombo = endsCombo; - } + public void setEndsCombo(final boolean endsCombo) { + this.endsCombo = endsCombo; + } - public void setAutoPlay() { - autoPlay = true; - } + public void setAutoPlay() { + autoPlay = true; + } - public abstract void update(float dt); + public abstract void update(float dt); - public float getHitTime() { - return hitTime; - } + public float getHitTime() { + return hitTime; + } - public void setHitTime(final float hitTime) { - this.hitTime = hitTime; - } + public void setHitTime(final float hitTime) { + this.hitTime = hitTime; + } - public int getId() { - return id; - } + public int getId() { + return id; + } - public void setId(int id) { - this.id = id; - } + public void setId(int id) { + this.id = id; + } - public boolean isStartHit(){ - return startHit; - } + public boolean isStartHit(){ + return startHit; + } - public void tryHit(float dt) {return;}; + public void tryHit(float dt) {return;}; - public PointF getPos() {return pos;}; + public PointF getPos() {return pos;}; } diff --git a/src/ru/nsu/ccfit/zuev/osu/game/GameObjectData.java b/src/ru/nsu/ccfit/zuev/osu/game/GameObjectData.java index 529be7aa..3ed51b96 100644 --- a/src/ru/nsu/ccfit/zuev/osu/game/GameObjectData.java +++ b/src/ru/nsu/ccfit/zuev/osu/game/GameObjectData.java @@ -5,81 +5,81 @@ import ru.nsu.ccfit.zuev.osu.Utils; public class GameObjectData { - private final int time; - private final int comboCode; - private final String[] rawdata; - // private SliderHelper.SliderPath path = null; - private final PointF pos; - private float posOffset; + private final int time; + private final int comboCode; + private final String[] rawdata; + // private SliderHelper.SliderPath path = null; + private final PointF pos; + private float posOffset; - public GameObjectData(final String line) { - String[] data = line.split("[,]"); + public GameObjectData(final String line) { + String[] data = line.split("[,]"); - //Ignoring v10 features - int dataSize = data.length; - while (dataSize > 0 && data[dataSize - 1].matches("([0-9][:][0-9][|]?)+")) { - dataSize--; - } - if (dataSize < data.length) { - rawdata = new String[dataSize]; - for (int i = 0; i < rawdata.length; i++) { - rawdata[i] = data[i]; - } - } else - rawdata = data; + //Ignoring v10 features + int dataSize = data.length; + while (dataSize > 0 && data[dataSize - 1].matches("([0-9][:][0-9][|]?)+")) { + dataSize--; + } + if (dataSize < data.length) { + rawdata = new String[dataSize]; + for (int i = 0; i < rawdata.length; i++) { + rawdata[i] = data[i]; + } + } else + rawdata = data; - time = Integer.parseInt(rawdata[2]); - comboCode = Integer.parseInt(rawdata[3]); - pos = Utils.trackToRealCoords(new PointF(Float.parseFloat(rawdata[0]), - Float.parseFloat(rawdata[1]))); - posOffset = 0; - } + time = Integer.parseInt(rawdata[2]); + comboCode = Integer.parseInt(rawdata[3]); + pos = Utils.trackToRealCoords(new PointF(Float.parseFloat(rawdata[0]), + Float.parseFloat(rawdata[1]))); + posOffset = 0; + } - public PointF getPos() { - return pos; - } + public PointF getPos() { + return pos; + } - public float getPosOffset() { - return posOffset; - } + public float getPosOffset() { + return posOffset; + } - public void setPosOffset(final float posOffset) { - this.posOffset = posOffset; - } + public void setPosOffset(final float posOffset) { + this.posOffset = posOffset; + } - public PointF getEnd() { - if (rawdata.length >= 8) { - final int repeats = Integer.parseInt(rawdata[6]); - if ((repeats % 2) != 1) { - return pos; - } - final String[] endP = rawdata[5].substring( - rawdata[5].lastIndexOf('|') + 1).split("[:]"); - PointF end; - try { - end = Utils.trackToRealCoords(new PointF(Float - .parseFloat(endP[0]), Float.parseFloat(endP[1]))); - } catch (final NumberFormatException e) { - end = pos; - } - return end; - } - return pos; - } + public PointF getEnd() { + if (rawdata.length >= 8) { + final int repeats = Integer.parseInt(rawdata[6]); + if ((repeats % 2) != 1) { + return pos; + } + final String[] endP = rawdata[5].substring( + rawdata[5].lastIndexOf('|') + 1).split("[:]"); + PointF end; + try { + end = Utils.trackToRealCoords(new PointF(Float + .parseFloat(endP[0]), Float.parseFloat(endP[1]))); + } catch (final NumberFormatException e) { + end = pos; + } + return end; + } + return pos; + } - public boolean isNewCombo() { - return (comboCode & 4) > 0; - } + public boolean isNewCombo() { + return (comboCode & 4) > 0; + } - public float getTime() { - return time / 1000.0f; - } + public float getTime() { + return time / 1000.0f; + } - public int getRawTime() { - return time; - } + public int getRawTime() { + return time; + } - public String[] getData() { - return rawdata; - } + public String[] getData() { + return rawdata; + } } diff --git a/src/ru/nsu/ccfit/zuev/osu/game/GameObjectListener.java b/src/ru/nsu/ccfit/zuev/osu/game/GameObjectListener.java index f0135dd3..cbc9e6ab 100644 --- a/src/ru/nsu/ccfit/zuev/osu/game/GameObjectListener.java +++ b/src/ru/nsu/ccfit/zuev/osu/game/GameObjectListener.java @@ -8,44 +8,44 @@ public interface GameObjectListener { - int SLIDER_START = 1, SLIDER_REPEAT = 2, SLIDER_END = 3, SLIDER_TICK = 4; + int SLIDER_START = 1, SLIDER_REPEAT = 2, SLIDER_END = 3, SLIDER_TICK = 4; - void onCircleHit(int id, float accuracy, PointF pos, boolean endCombo, byte forcedScore, RGBColor color); + void onCircleHit(int id, float accuracy, PointF pos, boolean endCombo, byte forcedScore, RGBColor color); - void onSliderHit(int id, int score, PointF start, PointF end, - boolean endCombo, RGBColor color, int type); + void onSliderHit(int id, int score, PointF start, PointF end, + boolean endCombo, RGBColor color, int type); - void onSliderEnd(int id, int accuracy, BitSet tickSet); + void onSliderEnd(int id, int accuracy, BitSet tickSet); - void onSpinnerHit(int id, int score, boolean endCombo, int totalScore); + void onSpinnerHit(int id, int score, boolean endCombo, int totalScore); - void playSound(String name, int sampleSet, int addition); + void playSound(String name, int sampleSet, int addition); - void stopSound(String name); + void stopSound(String name); - void addObject(GameObject object); + void addObject(GameObject object); - void removeObject(GameObject object); + void removeObject(GameObject object); - void addPassiveObject(GameObject object); + void addPassiveObject(GameObject object); - void removePassiveObject(GameObject object); + void removePassiveObject(GameObject object); - PointF getMousePos(int index); + PointF getMousePos(int index); - boolean isMouseDown(int index); + boolean isMouseDown(int index); - boolean isMousePressed(GameObject object, int index); + boolean isMousePressed(GameObject object, int index); - double downFrameOffset(int index); + double downFrameOffset(int index); - int getCursorsCount(); + int getCursorsCount(); - void registerAccuracy(float acc); - - void updateAutoBasedPos(float pX, float pY); + void registerAccuracy(float acc); + + void updateAutoBasedPos(float pX, float pY); - void onTrackingSliders(boolean isTrackingSliders); + void onTrackingSliders(boolean isTrackingSliders); - void onUpdatedAutoCursor(float pX, float pY); -} \ No newline at end of file + void onUpdatedAutoCursor(float pX, float pY); +} diff --git a/src/ru/nsu/ccfit/zuev/osu/game/GameObjectPool.java b/src/ru/nsu/ccfit/zuev/osu/game/GameObjectPool.java index b8492548..87ff1eeb 100644 --- a/src/ru/nsu/ccfit/zuev/osu/game/GameObjectPool.java +++ b/src/ru/nsu/ccfit/zuev/osu/game/GameObjectPool.java @@ -7,133 +7,133 @@ import ru.nsu.ccfit.zuev.osu.Config; public class GameObjectPool { - public static GameObjectPool instance = new GameObjectPool(); - public LinkedList circles = new LinkedList(); - public Map> numbers = new HashMap>(); - public Map> effects = new HashMap>(); - public LinkedList sliders = new LinkedList(); - public LinkedList tracks = new LinkedList(); - public LinkedList spinners = new LinkedList(); - private int objectsCreated = 0; - private GameObjectPool() { - } - - public static GameObjectPool getInstance() { - return instance; - } - - public HitCircle getCircle() { - if (circles.isEmpty() == false) { - return circles.poll(); - } - - objectsCreated++; - return new HitCircle(); - } - - public void putCircle(final HitCircle circle) { - circles.add(circle); - } - - public Spinner getSpinner() { - if (spinners.isEmpty() == false) { - return spinners.poll(); - } - - objectsCreated++; - if (Config.getSpinnerStyle() == 1) { - return new ModernSpinner(); - } else { - return new Spinner(); - } - } - - public void putSpinner(final Spinner spinner) { - spinners.add(spinner); - } - - public CircleNumber getNumber(final int num) { - if (numbers.containsKey(num) && numbers.get(num).isEmpty() == false) { - return numbers.get(num).poll(); - } - - objectsCreated++; - return new CircleNumber(num); - } - - public void putNumber(final CircleNumber number) { - if (numbers.containsKey(number.getNum()) == false) { - numbers.put(number.getNum(), new LinkedList()); - } - numbers.get(number.getNum()).add(number); - } - - public GameEffect getEffect(final String texname) { - if (effects.containsKey(texname) - && effects.get(texname).isEmpty() == false) { - return effects.get(texname).poll(); - } - - objectsCreated++; - return new GameEffect(texname); - } - - public void putEffect(final GameEffect effect) { - if (effects.containsKey(effect.getTexname()) == false) { - effects.put(effect.getTexname(), new LinkedList()); - } - effects.get(effect.getTexname()).add(effect); - } - - public Slider getSlider() { - if (sliders.isEmpty() == false) { - return sliders.poll(); - } - - objectsCreated++; - return new Slider(); - } - - public void putSlider(final Slider slider) { - sliders.add(slider); - } - - public FollowTrack getTrack() { - if (tracks.isEmpty() == false) { - return tracks.poll(); - } - - objectsCreated++; - return new FollowTrack(); - } - - public void putTrac(final FollowTrack track) { - tracks.add(track); - } - - public int getObjectsCreated() { - return objectsCreated; - } - - public void purge() { - effects.clear(); - circles.clear(); - numbers.clear(); - sliders.clear(); - tracks.clear(); - objectsCreated = 0; - } - - public void preload() { - for (int i = 0; i < 10; i++) { - putCircle(new HitCircle()); - putNumber(new CircleNumber(i + 1)); - } - for (int i = 0; i < 5; i++) { - putSlider(new Slider()); - putTrac(new FollowTrack()); - } - new Spinner(); - objectsCreated = 31; - } + public static GameObjectPool instance = new GameObjectPool(); + public LinkedList circles = new LinkedList(); + public Map> numbers = new HashMap>(); + public Map> effects = new HashMap>(); + public LinkedList sliders = new LinkedList(); + public LinkedList tracks = new LinkedList(); + public LinkedList spinners = new LinkedList(); + private int objectsCreated = 0; + private GameObjectPool() { + } + + public static GameObjectPool getInstance() { + return instance; + } + + public HitCircle getCircle() { + if (circles.isEmpty() == false) { + return circles.poll(); + } + + objectsCreated++; + return new HitCircle(); + } + + public void putCircle(final HitCircle circle) { + circles.add(circle); + } + + public Spinner getSpinner() { + if (spinners.isEmpty() == false) { + return spinners.poll(); + } + + objectsCreated++; + if (Config.getSpinnerStyle() == 1) { + return new ModernSpinner(); + } else { + return new Spinner(); + } + } + + public void putSpinner(final Spinner spinner) { + spinners.add(spinner); + } + + public CircleNumber getNumber(final int num) { + if (numbers.containsKey(num) && numbers.get(num).isEmpty() == false) { + return numbers.get(num).poll(); + } + + objectsCreated++; + return new CircleNumber(num); + } + + public void putNumber(final CircleNumber number) { + if (numbers.containsKey(number.getNum()) == false) { + numbers.put(number.getNum(), new LinkedList()); + } + numbers.get(number.getNum()).add(number); + } + + public GameEffect getEffect(final String texname) { + if (effects.containsKey(texname) + && effects.get(texname).isEmpty() == false) { + return effects.get(texname).poll(); + } + + objectsCreated++; + return new GameEffect(texname); + } + + public void putEffect(final GameEffect effect) { + if (effects.containsKey(effect.getTexname()) == false) { + effects.put(effect.getTexname(), new LinkedList()); + } + effects.get(effect.getTexname()).add(effect); + } + + public Slider getSlider() { + if (sliders.isEmpty() == false) { + return sliders.poll(); + } + + objectsCreated++; + return new Slider(); + } + + public void putSlider(final Slider slider) { + sliders.add(slider); + } + + public FollowTrack getTrack() { + if (tracks.isEmpty() == false) { + return tracks.poll(); + } + + objectsCreated++; + return new FollowTrack(); + } + + public void putTrac(final FollowTrack track) { + tracks.add(track); + } + + public int getObjectsCreated() { + return objectsCreated; + } + + public void purge() { + effects.clear(); + circles.clear(); + numbers.clear(); + sliders.clear(); + tracks.clear(); + objectsCreated = 0; + } + + public void preload() { + for (int i = 0; i < 10; i++) { + putCircle(new HitCircle()); + putNumber(new CircleNumber(i + 1)); + } + for (int i = 0; i < 5; i++) { + putSlider(new Slider()); + putTrac(new FollowTrack()); + } + new Spinner(); + objectsCreated = 31; + } } diff --git a/src/ru/nsu/ccfit/zuev/osu/game/GameObjectSize.java b/src/ru/nsu/ccfit/zuev/osu/game/GameObjectSize.java index 3d3cd2e4..bd19a3f9 100644 --- a/src/ru/nsu/ccfit/zuev/osu/game/GameObjectSize.java +++ b/src/ru/nsu/ccfit/zuev/osu/game/GameObjectSize.java @@ -2,6 +2,6 @@ public class GameObjectSize { - public static final float BASE_OBJECT_SIZE = 128; + public static final float BASE_OBJECT_SIZE = 128; } diff --git a/src/ru/nsu/ccfit/zuev/osu/game/GameScene.java b/src/ru/nsu/ccfit/zuev/osu/game/GameScene.java index 0d82e7ee..1b8cedcf 100644 --- a/src/ru/nsu/ccfit/zuev/osu/game/GameScene.java +++ b/src/ru/nsu/ccfit/zuev/osu/game/GameScene.java @@ -96,2725 +96,2725 @@ import ru.nsu.ccfit.zuev.osuplus.R; public class GameScene implements IUpdateHandler, GameObjectListener, - IOnSceneTouchListener { - public static final int CursorCount = 10; - private final Engine engine; - private final Cursor[] cursors = new Cursor[CursorCount]; - private final boolean[] cursorIIsDown = new boolean[CursorCount]; - private final StringBuilder strBuilder = new StringBuilder(); - public String filePath = null; - private Scene scene; - private Scene bgScene, mgScene, fgScene; - private Scene oldScene; - private BeatmapData beatmapData; - private TrackInfo lastTrack; - private ScoringScene scoringScene; - private TimingPoint currentTimingPoint; - private TimingPoint soundTimingPoint; - private TimingPoint firstTimingPoint; - private Queue timingPoints; - private Queue activeTimingPoints; - private String trackMD5; - private int lastObjectId = -1; - private float secPassed = 0; - private float leadOut = 0; - private LinkedList objects; - private ArrayList combos; - private int comboNum; // use this to show combo color - private int currentComboNum; - private boolean comboWasMissed = false; - private boolean comboWas100 = false; - private Queue activeObjects; - private LinkedList passiveObjects = new LinkedList(); - private GameScoreText comboText, accText, scoreText; //显示的文字 连击数 ACC 分数 - private GameScoreTextShadow scoreShadow; - private Queue breakPeriods = new LinkedList(); - private BreakAnimator breakAnimator; - private ScoreBar scorebar; - private SongProgressBar progressBar; - private DuringGameScoreBoard scoreBoard; - private HitErrorMeter hitErrorMeter; - private Metronome metronome; - private boolean isFirst = true; - private float scale; - private float approachRate; - private float rawDifficulty; - private float overallDifficulty; - private float rawDrain; - private float drain; - private StatisticV2 stat; - private boolean gameStarted; - private float totalOffset; - //private IMusicPlayer music = null; - private int totalLength = Integer.MAX_VALUE; - private boolean loadComplete; - private boolean paused; - private Sprite skipBtn; - private float skipTime; - private boolean musicStarted; - private float distToNextObject; - private float timeMultiplier = 1.0f; - private CursorEntity[] cursorSprites; - private AutoCursor autoCursor; - private FlashLightEntity flashlightSprite; - private int mainCursorId = -1; - private Replay replay; - private boolean replaying; - private String replayFile; - private float avgOffset; - private int offsetRegs; - private boolean kiai = false; - private Rectangle kiaiRect = null; - private Sprite bgSprite = null; - private Sprite unranked; - private ChangeableText replayText; - private String title, artist, version; - private ComboBurst comboBurst; - private VideoSprite mVideo = null; - private Sprite[] ScoreBoardSprite; - private int failcount = 0; - private float lastObjectHitTime = 0; - private SliderPath[] sliderPaths = null; - private int sliderIndex = 0; - - private StoryboardSprite storyboardSprite; - private ProxySprite storyboardOverlayProxy; - - private DifficultyHelper difficultyHelper = DifficultyHelper.StdDifficulty; - - private long previousFrameTime; - - public GameScene(final Engine engine) { - this.engine = engine; - scene = new Scene(); - bgScene = new Scene(); - fgScene = new Scene(); - mgScene = new Scene(); - scene.attachChild(bgScene); - scene.attachChild(mgScene); - scene.attachChild(fgScene); - } - - public void setScoringScene(final ScoringScene sc) { - scoringScene = sc; - } - - public void setOldScene(final Scene oscene) { - oldScene = oscene; - } - - private void setBackground() { - boolean bgset = false; - bgSprite = null; - if (storyboardSprite != null) { - if (storyboardSprite.isStoryboardAvailable()) { - storyboardSprite.setBrightness(Config.getBackgroundBrightness()); - return; - } - } - for (final String s : beatmapData.getData("Events")) { - final String[] pars = s.split("\\s*,\\s*"); - if (pars.length >= 3 && pars[0].equals("0") && pars[1].equals("0")) { - // String filename = pars[2].substring(1, pars[2].length() - 1); - - if (Config.getBackgroundQuality() == 0) { - scene.setBackground(new ColorBackground(0, 0, 0)); - continue; - } - - bgset = true; - final TextureRegion tex = Config.isSafeBeatmapBg() ? - ResourceManager.getInstance().getTexture("menu-background") : - ResourceManager.getInstance().getTextureIfLoaded("::background"); - if (tex == null) { - continue; - } - float brightness = Config.getBackgroundBrightness(); - float height = tex.getHeight() * Config.getBackgroundQuality(); - height *= Config.getRES_WIDTH() - / (float) (tex.getWidth() * Config - .getBackgroundQuality()); - bgSprite = new Sprite(0, - (Config.getRES_HEIGHT() - height) / 2, - Config.getRES_WIDTH(), height, tex); - bgSprite.setColor(brightness, brightness, brightness); - scene.setBackground(new SpriteBackground(bgSprite)); - } else if (pars.length >= 3 && pars[0].equals("2")) { - - } else if (bgset == false && pars.length == 5 - && pars[0].equals("3") && pars[1].equals("100")) { - bgset = true; - final float bright = Config.getBackgroundBrightness(); - scene.setBackground(new ColorBackground( - Integer.parseInt(pars[2]) * bright / 255f, - Integer.parseInt(pars[3]) * bright / 255f, - Integer.parseInt(pars[4]) * bright / 255f)); - } - } - } - - private boolean loadGame(final TrackInfo track, final String rFile) { - InGameSettingMenu.getInstance().dismiss(); - if (rFile != null && rFile.startsWith("https://")) { - this.replayFile = Config.getCachePath() + "/" + - MD5Calcuator.getStringMD5(rFile) + ".odr"; - Debug.i("ReplayFile = " + replayFile); - if (!OnlineFileOperator.downloadFile(rFile, this.replayFile)) { - ToastLogger.showTextId(R.string.replay_cantdownload, true); - return false; - } - } else - this.replayFile = rFile; - - OSUParser parser = new OSUParser(track.getFilename()); - if (parser.openFile()) { - beatmapData = parser.readData(); - } else { - Debug.e("startGame: cannot open file"); - ToastLogger.showText( - StringTable.format(R.string.message_error_open, - track.getFilename()), true); - return false; - } - parser = null; - -// try { -// float height = 720; -// height *= 1. * Config.getRES_WIDTH() / 1280; -// mVideo = new VideoSprite(0, 0, Config.getRES_WIDTH(), Config.getRES_HEIGHT()); -// mVideo.setDataSource(Environment.getExternalStorageDirectory().getPath() + "/PV.mp4"); -// mVideo.setAlpha(0f); -// // mVideo.play(); -// } catch (IOException e) { -// Log.i("Load avi", e.getMessage()); -// } - - // TODO skin manager - SkinManager.getInstance().loadBeatmapSkin(beatmapData.getFolder()); - - if (beatmapData.getData("General", "Mode").equals("0") == false) { - if (beatmapData.getData("General", "Mode").equals("") == false) { - ToastLogger.showText(StringTable.format( - R.string.message_error_mapmode, - beatmapData.getData("General", "Mode")), true); - return false; - } - } - - breakPeriods = new LinkedList(); - for (final String s : beatmapData.getData("Events")) { - final String[] pars = s.split("\\s*,\\s*"); - if ((pars.length >= 3) && pars[0].equals("0") && pars[1].equals("0")) { - - } else if (pars.length >= 3 && pars[0].equals("2")) { - breakPeriods.add(new BreakPeriod( - Float.parseFloat(pars[1]) / 1000f, Float - .parseFloat(pars[2]) / 1000f)); - } - } - - totalOffset = Config.getOffset(); - String beatmapName = track.getFilename(); - beatmapName = beatmapName.substring(0, beatmapName.lastIndexOf('/')); - final BeatmapProperties props = PropertiesLibrary.getInstance() - .getProperties(beatmapName); - if (props != null) { - totalOffset += props.getOffset(); - } - - try { - final File musicFile = new File(beatmapData.getFolder(), - beatmapData.getData("General", "AudioFilename")); - - if (musicFile.exists() == false) { - throw new FileNotFoundException(musicFile.getPath()); - } - - /* - if (musicFile.getName().endsWith(".ogg")) { - totalOffset += Config.getOggOffset(); - } */ - - //music = new BassAudioPlayer(musicFile.getPath()); - filePath = musicFile.getPath(); - - } catch (final Exception e) { - Debug.e("Load Music: " + e.getMessage()); - ToastLogger.showText(e.getMessage(), true); - return false; - } - - title = beatmapData.getData("Metadata", "Title"); - artist = beatmapData.getData("Metadata", "Artist"); - version = beatmapData.getData("Metadata", "Version"); - - // r = 54.42 - 4.48 * cs - // Reading beatmap settings - - //TextureRegion appcircleTex = ResourceManager.getInstance().getTexture("approachcircle"); - - scale = (float) ((Config.getRES_HEIGHT() / 480.0f) - * (54.42 - Float.parseFloat(beatmapData.getData("Difficulty", "CircleSize")) * 4.48) - * 2 / GameObjectSize.BASE_OBJECT_SIZE) - + 0.5f * Config.getScaleMultiplier(); - -/* scale = (10 - Float.parseFloat(beatmapData.getData("Difficulty", - "CircleSize"))) - * 0.125f - + 0.625f - + 0.125f - * Config.getScaleMultiplier();*/ - - String rawRate = beatmapData.getData("Difficulty", "ApproachRate"); - if (rawRate.equals("")) { - rawRate = beatmapData.getData("Difficulty", "OverallDifficulty"); - } - float rawApproachRate = Float.parseFloat(rawRate); - approachRate = (float) GameHelper.ar2ms(rawApproachRate) / 1000f; - final String rawSliderSpeed = beatmapData.getData("Difficulty", - "SliderMultiplier"); - - overallDifficulty = Float.parseFloat(beatmapData.getData("Difficulty", - "OverallDifficulty")); - drain = Float.parseFloat(beatmapData.getData("Difficulty", - "HPDrainRate")); - rawDifficulty = overallDifficulty; - rawDrain = drain; - - if (ModMenu.getInstance().getMod().contains(GameMod.MOD_EASY)) { - scale += 0.125f; - drain *= 0.5f; - overallDifficulty *= 0.5f; - approachRate = (float) GameHelper.ar2ms(rawApproachRate / 2f) / 1000f; - } - - GameHelper.setHardrock(false); - if (ModMenu.getInstance().getMod().contains(GameMod.MOD_HARDROCK)) { - scale -= 0.125f; - drain = Math.min(1.4f * drain, 10f); - overallDifficulty = Math.min(1.4f * overallDifficulty, 10f); - approachRate = (float) GameHelper.ar2ms(Math.min(1.4f * rawApproachRate, 10f)) / 1000f; - GameHelper.setHardrock(true); - } - - timeMultiplier = 1f; - GameHelper.setDoubleTime(false); - GameHelper.setNightCore(false); - GameHelper.setHalfTime(false); - GameHelper.setSpeedUp(false); - - GlobalManager.getInstance().getSongService().preLoad(filePath, PlayMode.MODE_NONE); - GameHelper.setTimeMultiplier(1f); - //Speed Change - if (ModMenu.getInstance().getChangeSpeed() != 1.00f){ - timeMultiplier = ModMenu.getInstance().getSpeed(); - GlobalManager.getInstance().getSongService().preLoad(filePath, timeMultiplier, ModMenu.getInstance().isEnableNCWhenSpeedChange()); - GameHelper.setTimeMultiplier(1 / timeMultiplier); - } else if (ModMenu.getInstance().getMod().contains(GameMod.MOD_DOUBLETIME)) { - GlobalManager.getInstance().getSongService().preLoad(filePath, PlayMode.MODE_DT); - /*music.setUseSoftDecoder(1); - music.setDecoderMultiplier(150);*/ - timeMultiplier = 1.5f; - GameHelper.setDoubleTime(true); - GameHelper.setTimeMultiplier(2 / 3f); - } else if (ModMenu.getInstance().getMod().contains(GameMod.MOD_NIGHTCORE)) { - GlobalManager.getInstance().getSongService().preLoad(filePath, PlayMode.MODE_NC); - /*music.setUseSoftDecoder(2); - music.setDecoderMultiplier(150);*/ - timeMultiplier = 1.5f; - GameHelper.setNightCore(true); - GameHelper.setTimeMultiplier(2 / 3f); - } else if (ModMenu.getInstance().getMod().contains(GameMod.MOD_HALFTIME)) { - GlobalManager.getInstance().getSongService().preLoad(filePath, PlayMode.MODE_HT); - /*music.setUseSoftDecoder(1); - music.setDecoderMultiplier(75);*/ - timeMultiplier = 0.75f; - GameHelper.setHalfTime(true); - GameHelper.setTimeMultiplier(4 / 3f); - } - - /* - if (ModMenu.getInstance().getMod().contains(GameMod.MOD_DOUBLETIME) || ModMenu.getInstance().getMod().contains(GameMod.MOD_NIGHTCORE)) { -// approachRate = approachRate * 2 / 3; -// overallDifficulty = (float) GameHelper.ms2od(GameHelper.od2ms(overallDifficulty) * 2 / 3); - GameHelper.setTimeMultiplier(2 / 3f); - } else if (ModMenu.getInstance().getMod().contains(GameMod.MOD_HALFTIME)) { -// approachRate = approachRate * 4 / 3; -// overallDifficulty = (float) GameHelper.ms2od(GameHelper.od2ms(overallDifficulty) * 4 / 3); - GameHelper.setTimeMultiplier(4 / 3f); - } else if (ModMenu.getInstance().getMod().contains(GameMod.MOD_SPEEDUP)) { - GameHelper.setTimeMultiplier(4 / 5f); - } else { - GameHelper.setTimeMultiplier(1f); - } - */ - - if (ModMenu.getInstance().getMod().contains(GameMod.MOD_REALLYEASY)) { - scale += 0.125f; - drain *= 0.5f; - overallDifficulty *= 0.5f; - float ar = (float)GameHelper.ms2ar(approachRate * 1000f); - if (ModMenu.getInstance().getMod().contains(GameMod.MOD_EASY)) { - ar *= 2; - ar -= 0.5f; - } - ar -= (timeMultiplier - 1.0f) + 0.5f; - approachRate = (float)(GameHelper.ar2ms(ar) / 1000f); - } - - if (ModMenu.getInstance().getMod().contains(GameMod.MOD_SMALLCIRCLE)) { - scale -= (float) ((Config.getRES_HEIGHT() / 480.0f) * (4 * 4.48) - * 2 / GameObjectSize.BASE_OBJECT_SIZE); - } - //Force AR - if (ModMenu.getInstance().isEnableForceAR()){ - approachRate = (float) GameHelper.ar2ms(ModMenu.getInstance().getForceAR()) / 1000f * timeMultiplier; - } - - GameHelper.setRelaxMod(ModMenu.getInstance().getMod().contains(GameMod.MOD_RELAX)); - GameHelper.setAutopilotMod(ModMenu.getInstance().getMod().contains(GameMod.MOD_AUTOPILOT)); - GameHelper.setAuto(ModMenu.getInstance().getMod().contains(GameMod.MOD_AUTO)); - - final String stackLatiency = beatmapData.getData("General", - "StackLeniency"); - if (stackLatiency.equals("") == false) { - GameHelper.setStackLatient(Float.parseFloat(stackLatiency)); - } else { - GameHelper.setStackLatient(0); - } - if (scale < 0.001f){ - scale = 0.001f; - } - GameHelper.setSpeed(Float.parseFloat(rawSliderSpeed) * 100); - GameHelper.setTickRate(Float.parseFloat(beatmapData.getData( - "Difficulty", "SliderTickRate"))); - GameHelper.setScale(scale); - GameHelper.setDifficulty(overallDifficulty); - GameHelper.setDrain(drain); - GameHelper.setApproachRate(approachRate); - - // Parsing hit objects - objects = new LinkedList(); - for (final String s : beatmapData.getData("HitObjects")) { - objects.add(new GameObjectData(s)); - } - - if (objects.size() <= 0) { - ToastLogger.showText("Empty Beatmap", true); - return false; - } - - activeObjects = new LinkedList(); - passiveObjects = new LinkedList(); - lastObjectId = -1; - - GameHelper.setSliderColor(SkinManager.getInstance().getSliderColor()); - final String slidercolor = beatmapData.getData("Colours", - "SliderBorder"); - if (slidercolor.equals("") == false) { - final String[] sliderColors = slidercolor.split("[,]"); - GameHelper.setSliderColor(new RGBColor(Integer - .parseInt(sliderColors[0]) / 255.0f, Integer - .parseInt(sliderColors[1]) / 255.0f, Integer - .parseInt(sliderColors[2]) / 255.0f)); - } - - if (SkinJson.get().isForceOverrideSliderBorderColor()) { - GameHelper.setSliderColor(new RGBColor(SkinJson.get().getSliderBorderColor())); - } - - combos = new ArrayList(); - comboNum = 2; - String ccolor = beatmapData.getData("Colours", "Combo1"); - while (ccolor.equals("") == false) { - final String[] colors = ccolor.replace(" ", "").split("[,]"); - combos.add(new RGBColor(Integer.parseInt(colors[0]) / 255.0f, - Integer.parseInt(colors[1]) / 255.0f, Integer - .parseInt(colors[2]) / 255.0f)); - - ccolor = beatmapData.getData("Colours", "Combo" + comboNum++); - } - if (combos.isEmpty() || Config.isUseCustomComboColors()) { -// combos.add(new RGBColor(255 / 255.0f, 150 / 255.0f, 0 / 255.0f)); -// combos.add(new RGBColor(5 / 255.0f, 240 / 255.0f, 5 / 255.0f)); -// combos.add(new RGBColor(5 / 255.0f, 2 / 255.0f, 240 / 255.0f)); -// combos.add(new RGBColor(240 / 255.0f, 5 / 255.0f, 5 / 255.0f)); - combos.clear(); - combos.addAll(Arrays.asList(Config.getComboColors())); - } - if (SkinJson.get().isForceOverrideComboColor()) { - combos.clear(); - combos.addAll(SkinJson.get().getComboColor()); - } - comboNum = -1; - // if (combos.size() > 1) comboNum = 1; - currentComboNum = 0; - lastObjectHitTime = 0; - final String defSound = beatmapData.getData("General", "SampleSet"); - if (defSound.equals("Soft")) { - TimingPoint.setDefaultSound("soft"); - } else { - TimingPoint.setDefaultSound("normal"); - } - timingPoints = new LinkedList(); - activeTimingPoints = new LinkedList(); - currentTimingPoint = null; - for (final String s : beatmapData.getData("TimingPoints")) { - final TimingPoint tp = new TimingPoint(s.split("[,]"), - currentTimingPoint); - timingPoints.add(tp); - if (tp.wasInderited() == false || currentTimingPoint == null) { - currentTimingPoint = tp; - } - } - GameHelper.controlPoints = new ControlPoints(); - GameHelper.controlPoints.load(TimingPoints.parse(beatmapData.getData("TimingPoints"))); - currentTimingPoint = timingPoints.peek(); - firstTimingPoint = currentTimingPoint; - soundTimingPoint = currentTimingPoint; - if (soundTimingPoint != null) { - GameHelper.setTimingOffset(soundTimingPoint.getTime()); - GameHelper.setBeatLength(soundTimingPoint.getBeatLength() * GameHelper.getSpeed() / 100f); - GameHelper.setTimeSignature(soundTimingPoint.getSignature()); - GameHelper.setKiai(soundTimingPoint.isKiai()); - } else { - GameHelper.setTimingOffset(0); - GameHelper.setBeatLength(1); - GameHelper.setTimeSignature(4); - GameHelper.setKiai(false); - } - GameHelper.setInitalBeatLength(GameHelper.getBeatLength()); - - GameObjectPool.getInstance().purge(); - SpritePool.getInstance().purge(); - ModifierFactory.clear(); - - // TODO replay - avgOffset = 0; - offsetRegs = 0; - - File trackFile = new File(track.getFilename()); - trackMD5 = FileUtils.getMD5Checksum(trackFile); - replaying = false; - replay = new Replay(); - replay.setObjectCount(objects.size()); - replay.setMap(trackFile.getParentFile().getName(), trackFile.getName(), trackMD5); - - if (replayFile != null) { - replaying = replay.load(replayFile); - if (!replaying) { - ToastLogger.showTextId(R.string.replay_invalid, true); - return false; - } else - replay.countMarks(overallDifficulty); - //} else if (!OnlineManager.getInstance().isStayOnline()) { - // replay = null; - } else if (ModMenu.getInstance().getMod().contains(GameMod.MOD_AUTO)) { - replay = null; - } - /* - else if (ModMenu.getInstance().getMod().contains(GameMod.MOD_AUTO) || - ModMenu.getInstance().getMod().contains(GameMod.MOD_RELAX) || - ModMenu.getInstance().getMod().contains(GameMod.MOD_AUTOPILOT)) { - replay = null; - } - */ - //TODO fix replays ^^ - // replay = null; - - //TODO online - if (!replaying) - OnlineScoring.getInstance().startPlay(track, trackMD5); - - if (Config.isEnableStoryboard()) { - storyboardSprite.loadStoryboard(track.getFilename()); - } - - - System.gc(); - - GameObjectPool.getInstance().preload(); - - /* try { - music.prepare(); - - } catch (final Exception e) { - }*/ - - lastTrack = track; - if (Config.isCalculateSliderPathInGameStart()){ - stackNotes(); - calculateAllSliderPaths(); - } - paused = false; - gameStarted = false; - - return true; - } - - public Scene getScene() { - return scene; - } - - public void restartGame() { - if (!replaying) { - EdExtensionHelper.onRestartGame(lastTrack); - } - startGame(null, null); - } - - public void startGame(final TrackInfo track, final String replayFile) { - GameHelper.updateGameid(); - if (!replaying) { - EdExtensionHelper.onStartGame(track); - } - - scene = new Scene(); - if (Config.isEnableStoryboard()) { - if (storyboardSprite == null) { - storyboardSprite = new StoryboardSprite(Config.getRES_WIDTH(), Config.getRES_HEIGHT()); - storyboardOverlayProxy = new ProxySprite(Config.getRES_WIDTH(), Config.getRES_HEIGHT()); - storyboardSprite.setOverlayDrawProxy(storyboardOverlayProxy); - scene.attachChild(storyboardSprite); - } - storyboardSprite.detachSelf(); - scene.attachChild(storyboardSprite); - } - bgScene = new Scene(); - mgScene = new Scene(); - fgScene = new Scene(); - scene.attachChild(bgScene); - scene.attachChild(mgScene); - if (storyboardOverlayProxy != null) { - storyboardOverlayProxy.detachSelf(); - scene.attachChild(storyboardOverlayProxy); - } - scene.attachChild(fgScene); - scene.setBackground(new ColorBackground(0, 0, 0)); - bgScene.setBackgroundEnabled(false); - mgScene.setBackgroundEnabled(false); - fgScene.setBackgroundEnabled(false); - isFirst = true; - failcount = 0; - mainCursorId = -1; - final LoadingScreen screen = new LoadingScreen(); - engine.setScene(screen.getScene()); - - final String rfile = track != null ? replayFile : this.replayFile; - - new AsyncTaskLoader().execute(new OsuAsyncCallback() { - - public void run() { - loadComplete = loadGame(track != null ? track : lastTrack, rfile); - } - - public void onComplete() { - if (loadComplete == true) { - prepareScene(); - } else { - ModMenu.getInstance().setMod(Replay.oldMod); - ModMenu.getInstance().setChangeSpeed(Replay.oldChangeSpeed); - ModMenu.getInstance().setForceAR(Replay.oldForceAR); - ModMenu.getInstance().setEnableForceAR(Replay.oldEnableForceAR); - ModMenu.getInstance().setFLfollowDelay(Replay.oldFLFollowDelay); - quit(); - } - } - }); - ResourceManager.getInstance().getSound("failsound").stop(); - } - - private void prepareScene() { - scene.setOnSceneTouchListener(this); - // bgScene.attachChild(mVideo); - if (GlobalManager.getInstance().getCamera() instanceof SmoothCamera) { - SmoothCamera camera = (SmoothCamera) (GlobalManager.getInstance().getCamera()); - camera.setZoomFactorDirect(Config.getPlayfieldSize()); - if (Config.isShrinkPlayfieldDownwards()) { - camera.setCenterDirect(Config.getRES_WIDTH() / 2, Config.getRES_HEIGHT() / 2 * Config.getPlayfieldSize()); - } - } - setBackground(); - - if (Config.isShowFPS()) { - final Font font = ResourceManager.getInstance().getFont( - "smallFont"); - final ChangeableText fpsText = new ChangeableText(Utils.toRes(790), - Utils.toRes(520), font, "00.00 FPS"); - final ChangeableText accText = new ChangeableText(Utils.toRes(720), - Utils.toRes(480), font, "Avg offset: 0ms "); - fpsText.setPosition(Config.getRES_WIDTH() - fpsText.getWidth() - 5, Config.getRES_HEIGHT() - fpsText.getHeight() - 10); - accText.setPosition(Config.getRES_WIDTH() - accText.getWidth() - 5, fpsText.getY() - accText.getHeight()); - fgScene.attachChild(fpsText); - fgScene.attachChild(accText); - - ChangeableText memText = null; - if (BuildConfig.DEBUG) { - memText = new ChangeableText(Utils.toRes(780), - Utils.toRes(520), font, "M: 100/100"); - fgScene.attachChild(memText); - } - - final ChangeableText fmemText = memText; - fgScene.registerUpdateHandler(new FPSCounter() { - int elapsedInt = 0; - - @Override - public void onUpdate(final float pSecondsElapsed) { - super.onUpdate(pSecondsElapsed); - elapsedInt++; - fpsText.setText(Math.round(this.getFPS()) + " FPS"); - if (offsetRegs != 0 && elapsedInt > 200) { - accText.setText("Avg offset: " - + (int) (avgOffset * 1000f / offsetRegs) - + "ms"); - elapsedInt = 0; - } - fpsText.setPosition(Config.getRES_WIDTH() - fpsText.getWidth() - 5, Config.getRES_HEIGHT() - fpsText.getHeight() - 10); - accText.setPosition(Config.getRES_WIDTH() - accText.getWidth() - 5, fpsText.getY() - accText.getHeight()); - - if (fmemText != null) { - fmemText.setText("M: " - + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / 1024 / 1024 - + "/" + Runtime.getRuntime().totalMemory() / 1024 / 1024); - fmemText.setPosition(Config.getRES_WIDTH() - fmemText.getWidth() - 5, accText.getY() - fmemText.getHeight()); - } - - } - }); - } - - stat = new StatisticV2(); - stat.setMod(ModMenu.getInstance().getMod()); - float multiplier = 1 + rawDifficulty / 10f + rawDrain / 10f; - multiplier += (Float.parseFloat(beatmapData.getData("Difficulty", - "CircleSize")) - 3) / 4f; - - stat.setDiffModifier(multiplier); - stat.setMaxObjectsCount(lastTrack.getTotalHitObjectCount()); - stat.setMaxHighestCombo(lastTrack.getMaxCombo()); - stat.setEnableForceAR(ModMenu.getInstance().isEnableForceAR()); - stat.setForceAR(ModMenu.getInstance().getForceAR()); - stat.setChangeSpeed(ModMenu.getInstance().getChangeSpeed()); - stat.setFLFollowDelay(ModMenu.getInstance().getFLfollowDelay()); - - GameHelper.setHardrock(stat.getMod().contains(GameMod.MOD_HARDROCK)); - GameHelper.setDoubleTime(stat.getMod().contains(GameMod.MOD_DOUBLETIME)); - GameHelper.setNightCore(stat.getMod().contains(GameMod.MOD_NIGHTCORE)); - GameHelper.setSpeedUp(stat.getMod().contains(GameMod.MOD_SPEEDUP)); - GameHelper.setHalfTime(stat.getMod().contains(GameMod.MOD_HALFTIME)); - GameHelper.setHidden(stat.getMod().contains(GameMod.MOD_HIDDEN)); - GameHelper.setFlashLight(stat.getMod().contains(GameMod.MOD_FLASHLIGHT)); - GameHelper.setRelaxMod(stat.getMod().contains(GameMod.MOD_RELAX)); - GameHelper.setAutopilotMod(stat.getMod().contains(GameMod.MOD_AUTOPILOT)); - GameHelper.setSuddenDeath(stat.getMod().contains(GameMod.MOD_SUDDENDEATH)); - GameHelper.setPerfect(stat.getMod().contains(GameMod.MOD_PERFECT)); - difficultyHelper = stat.getMod().contains(GameMod.MOD_PRECISE) ? - DifficultyHelper.HighDifficulty : DifficultyHelper.StdDifficulty; - GameHelper.setDifficultyHelper(difficultyHelper); - - for (int i = 0; i < CursorCount; i++) { - cursors[i] = new Cursor(); - cursors[i].mouseDown = false; - cursors[i].mousePressed = false; - cursors[i].mouseOldDown = false; - } - - for (int i = 0; i < CursorCount; i++) { - cursorIIsDown[i] = false; - } - - comboWas100 = false; - comboWasMissed = false; - - final String leadin = beatmapData.getData("General", "AudioLeadIn"); - secPassed = -Integer.parseInt(leadin.equals("") ? "0" : leadin) / 1000f; - if (secPassed > -1) { - secPassed = -1; - } - - if (objects.isEmpty() == false) { - skipTime = objects.peek().getTime() - approachRate - 1f; - } else { - skipTime = 0; - } - - metronome = null; - if ((Config.getMetronomeSwitch() == 1 && GameHelper.isNightCore()) - || Config.getMetronomeSwitch() == 2) { - metronome = new Metronome(); - } - - secPassed -= Config.getOffset() / 1000f; - if (secPassed > 0) { - skipTime -= secPassed; - secPassed = 0; - } - distToNextObject = 0; - - // TODO passive objects - if ((replaying || Config.isShowCursor()) && !GameHelper.isAuto() && !GameHelper.isAutopilotMod()) { - cursorSprites = new CursorEntity[CursorCount]; - for (int i = 0; i < CursorCount; i++) { - cursorSprites[i] = new CursorEntity(); - cursorSprites[i].attachToScene(fgScene); - } - } else { - cursorSprites = null; - } - - if (GameHelper.isAuto() || GameHelper.isAutopilotMod()) { - autoCursor = new AutoCursor(); - autoCursor.attachToScene(fgScene); - } - - final String countdownPar = beatmapData.getData("General", "Countdown"); - if (Config.isCorovans() && countdownPar.equals("") == false) { - float cdSpeed = 0; - if (countdownPar.equals("1")) { - cdSpeed = 1; - } else if (countdownPar.equals("2")) { - cdSpeed = 2; - } else if (countdownPar.equals("3")) { - cdSpeed = 0.5f; - } - skipTime -= cdSpeed * Countdown.COUNTDOWN_LENGTH; - if (cdSpeed != 0 - && objects.peek().getTime() - secPassed >= cdSpeed - * Countdown.COUNTDOWN_LENGTH) { - addPassiveObject(new Countdown(this, bgScene, cdSpeed, 0, - objects.peek().getTime() - secPassed)); - } - } - - float lastObjectTme = 0; - if (objects.isEmpty() == false) - lastObjectTme = objects.getLast().getTime(); - - if(!Config.isHideInGameUI()) { - progressBar = new SongProgressBar(this, bgScene, lastObjectTme, objects - .getFirst().getTime(), new PointF(0, Config.getRES_HEIGHT() - 7), Config.getRES_WIDTH(), 7); - progressBar.setProgressRectColor(new RGBAColor(153f / 255f, 204f / 255f, 51f / 255f, 0.4f)); - } - - if (Config.getErrorMeter() == 1 - || (Config.getErrorMeter() == 2 && replaying)) { - hitErrorMeter = new HitErrorMeter( - bgScene, - new PointF(Config.getRES_WIDTH() / 2, Config.getRES_HEIGHT() - 20), - overallDifficulty, - 12, - difficultyHelper); - } - - skipBtn = null; - if (skipTime > 1) { - final TextureRegion tex; - if (ResourceManager.getInstance().isTextureLoaded("play-skip-0")) { - List loadedSkipTextures = new ArrayList<>(); - for (int i = 0; i < 60; i++) { - if (ResourceManager.getInstance().isTextureLoaded("play-skip-" + i)) - loadedSkipTextures.add("play-skip-" + i); - } - tex = ResourceManager.getInstance().getTexture("play-skip-0"); - skipBtn = new AnimSprite(Config.getRES_WIDTH() - tex.getWidth(), - Config.getRES_HEIGHT() - tex.getHeight(), loadedSkipTextures.size(), - loadedSkipTextures.toArray(new String[loadedSkipTextures.size()])); - } else { - tex = ResourceManager.getInstance().getTexture("play-skip"); - skipBtn = new Sprite(Config.getRES_WIDTH() - tex.getWidth(), - Config.getRES_HEIGHT() - tex.getHeight(), tex); - } - skipBtn.setAlpha(0.7f); - fgScene.attachChild(skipBtn); - /*if (SkinManager.getFrames("play-skip") <= 1) { - tex = ResourceManager.getInstance().getTexture("play-skip"); - skipBtn = new Sprite(Config.getRES_WIDTH() - tex.getWidth(), - Config.getRES_HEIGHT() - tex.getHeight(), tex); - fgScene.attachChild(skipBtn); - } else { - if (SkinManager.getFrames("play-skip") == 1) { - final int frames = SkinManager.getFrames("play-skip"); - tex = ResourceManager.getInstance().getTexture( - "play-skip-0"); - skipBtn = new AnimSprite(Config.getRES_WIDTH() - - tex.getWidth(), Config.getRES_HEIGHT() - - tex.getHeight(), "play-skip-", frames, frames); - fgScene.attachChild(skipBtn); - } - }*/ - } - GameHelper.setGlobalTime(0); - - float effectOffset = 155 - 25; - breakAnimator = new BreakAnimator(this, fgScene, stat, beatmapData - .getData("General", "LetterboxInBreaks").equals("1"), bgSprite); - if(!Config.isHideInGameUI()){ - scorebar = new ScoreBar(this, fgScene, stat); - addPassiveObject(scorebar); - final TextureRegion scoreDigitTex = ResourceManager.getInstance() - .getTexture("score-0"); - accText = new GameScoreText(Config.getRES_WIDTH() - - scoreDigitTex.getWidth() * 4.75f, 50, - "000.00%", 0.6f); - comboText = new GameScoreText(Utils.toRes(2), Config.getRES_HEIGHT() - - Utils.toRes(95), "0000x", 1.5f); - comboText.changeText(new StringBuilder("0****")); - scoreText = new GameScoreText(Config.getRES_WIDTH() - - scoreDigitTex.getWidth() * 7.25f, 0, "0000000000", 0.9f); - comboText.attachToScene(fgScene); - accText.attachToScene(fgScene); - scoreText.attachToScene(fgScene); - if (Config.isComplexAnimations()) { - scoreShadow = new GameScoreTextShadow(0, Config.getRES_HEIGHT() - - Utils.toRes(90), "0000x", 1.5f); - scoreShadow.attachToScene(bgScene); - passiveObjects.add(scoreShadow); - } - if (stat.getMod().contains(GameMod.MOD_AUTO)) { - final Sprite autoIcon = new Sprite(Utils.toRes(Config.getRES_WIDTH() - 140), - Utils.toRes(100), ResourceManager.getInstance().getTexture( - "selection-mod-autoplay")); - bgScene.attachChild(autoIcon); - effectOffset += 25; - } else if (stat.getMod().contains(GameMod.MOD_RELAX)) { - final Sprite autoIcon = new Sprite(Utils.toRes(Config.getRES_WIDTH() - 140), - Utils.toRes(98), ResourceManager.getInstance().getTexture( - "selection-mod-relax")); - bgScene.attachChild(autoIcon); - effectOffset += 25; - } else if (stat.getMod().contains(GameMod.MOD_AUTOPILOT)) { - final Sprite autoIcon = new Sprite(Utils.toRes(Config.getRES_WIDTH() - 140), - Utils.toRes(98), ResourceManager.getInstance().getTexture( - "selection-mod-relax2")); - bgScene.attachChild(autoIcon); - effectOffset += 25; - } - - if (Config.isComboburst()) { - comboBurst = new ComboBurst(Config.getRES_WIDTH(), Config.getRES_HEIGHT()); - comboBurst.attachAll(bgScene); - } - } - - float timeOffset = 0; - if (stat.getMod().contains(GameMod.MOD_SCOREV2)) { - final GameEffect effect = GameObjectPool.getInstance().getEffect( - "selection-mod-scorev2"); - effect.init( - fgScene, - new PointF(Utils.toRes(Config.getRES_WIDTH() - effectOffset), Utils - .toRes(130)), - scale, - new SequenceEntityModifier(ModifierFactory - .newScaleModifier(0.25f, 1.2f, 1), ModifierFactory - .newDelayModifier(2), new ParallelEntityModifier( - ModifierFactory.newFadeOutModifier(0.5f), - ModifierFactory.newScaleModifier(0.5f, 1, 1.5f)))); - effectOffset += 25; - timeOffset += 0.25f; - } - if (stat.getMod().contains(GameMod.MOD_EASY)) { - final GameEffect effect = GameObjectPool.getInstance().getEffect( - "selection-mod-easy"); - effect.init( - fgScene, - new PointF(Utils.toRes(Config.getRES_WIDTH() - effectOffset), Utils - .toRes(130)), - scale, - new SequenceEntityModifier(ModifierFactory - .newScaleModifier(0.25f, 1.2f, 1), ModifierFactory - .newDelayModifier(2), new ParallelEntityModifier( - ModifierFactory.newFadeOutModifier(0.5f), - ModifierFactory.newScaleModifier(0.5f, 1, 1.5f)))); - effectOffset += 25; - timeOffset += 0.25f; - } else if (stat.getMod().contains(GameMod.MOD_HARDROCK)) { - final GameEffect effect = GameObjectPool.getInstance().getEffect( - "selection-mod-hardrock"); - effect.init( - fgScene, - new PointF(Utils.toRes(Config.getRES_WIDTH() - effectOffset), Utils - .toRes(130)), - scale, - new SequenceEntityModifier(ModifierFactory - .newScaleModifier(0.25f, 1.2f, 1), ModifierFactory - .newDelayModifier(2), new ParallelEntityModifier( - ModifierFactory.newFadeOutModifier(0.5f), - ModifierFactory.newScaleModifier(0.5f, 1, 1.5f)))); - effectOffset += 25; - timeOffset += 0.25f; - } - if (stat.getMod().contains(GameMod.MOD_NOFAIL)) { - final GameEffect effect = GameObjectPool.getInstance().getEffect( - "selection-mod-nofail"); - effect.init( - fgScene, - new PointF(Utils.toRes(Config.getRES_WIDTH() - effectOffset), Utils - .toRes(130)), - scale, - new SequenceEntityModifier(ModifierFactory - .newScaleModifier(0.25f, 1.2f, 1), ModifierFactory - .newDelayModifier(2 - timeOffset), - new ParallelEntityModifier(ModifierFactory - .newFadeOutModifier(0.5f), ModifierFactory - .newScaleModifier(0.5f, 1, 1.5f)))); - effectOffset += 25; - timeOffset += 0.25f; - } - if (stat.getMod().contains(GameMod.MOD_HIDDEN)) { - final GameEffect effect = GameObjectPool.getInstance().getEffect( - "selection-mod-hidden"); - effect.init( - fgScene, - new PointF(Utils.toRes(Config.getRES_WIDTH() - effectOffset), Utils - .toRes(130)), - scale, - new SequenceEntityModifier(ModifierFactory - .newScaleModifier(0.25f, 1.2f, 1), ModifierFactory - .newDelayModifier(2 - timeOffset), - new ParallelEntityModifier(ModifierFactory - .newFadeOutModifier(0.5f), ModifierFactory - .newScaleModifier(0.5f, 1, 1.5f)))); - effectOffset += 25; - timeOffset += 0.25f; - } - - if (stat.getMod().contains(GameMod.MOD_DOUBLETIME)) { - final GameEffect effect = GameObjectPool.getInstance().getEffect( - "selection-mod-doubletime"); - effect.init( - fgScene, - new PointF(Utils.toRes(Config.getRES_WIDTH() - effectOffset), Utils - .toRes(130)), - scale, - new SequenceEntityModifier(ModifierFactory - .newScaleModifier(0.25f, 1.2f, 1), ModifierFactory - .newDelayModifier(2 - timeOffset), - new ParallelEntityModifier(ModifierFactory - .newFadeOutModifier(0.5f), ModifierFactory - .newScaleModifier(0.5f, 1, 1.5f)))); - effectOffset += 25; - timeOffset += 0.25f; - } - if (stat.getMod().contains(GameMod.MOD_NIGHTCORE)) { - final GameEffect effect = GameObjectPool.getInstance().getEffect( - "selection-mod-nightcore"); - effect.init( - fgScene, - new PointF(Utils.toRes(Config.getRES_WIDTH() - effectOffset), Utils - .toRes(130)), - scale, - new SequenceEntityModifier(ModifierFactory - .newScaleModifier(0.25f, 1.2f, 1), ModifierFactory - .newDelayModifier(2 - timeOffset), - new ParallelEntityModifier(ModifierFactory - .newFadeOutModifier(0.5f), ModifierFactory - .newScaleModifier(0.5f, 1, 1.5f)))); - effectOffset += 25; - timeOffset += 0.25f; - } - if (stat.getMod().contains(GameMod.MOD_HALFTIME)) { - final GameEffect effect = GameObjectPool.getInstance().getEffect( - "selection-mod-halftime"); - effect.init( - fgScene, - new PointF(Utils.toRes(Config.getRES_WIDTH() - effectOffset), Utils - .toRes(130)), - scale, - new SequenceEntityModifier(ModifierFactory - .newScaleModifier(0.25f, 1.2f, 1), ModifierFactory - .newDelayModifier(2 - timeOffset), - new ParallelEntityModifier(ModifierFactory - .newFadeOutModifier(0.5f), ModifierFactory - .newScaleModifier(0.5f, 1, 1.5f)))); - effectOffset += 25; - timeOffset += 0.25f; - } - if (stat.getMod().contains(GameMod.MOD_PRECISE)) { - final GameEffect effect = GameObjectPool.getInstance().getEffect( - "selection-mod-precise"); - effect.init( - fgScene, - new PointF(Utils.toRes(Config.getRES_WIDTH() - effectOffset), Utils - .toRes(130)), - scale, - new SequenceEntityModifier(ModifierFactory - .newScaleModifier(0.25f, 1.2f, 1), ModifierFactory - .newDelayModifier(2 - timeOffset), - new ParallelEntityModifier(ModifierFactory - .newFadeOutModifier(0.5f), ModifierFactory - .newScaleModifier(0.5f, 1, 1.5f)))); - effectOffset += 25; - timeOffset += 0.25f; - } - if (stat.getMod().contains(GameMod.MOD_SUDDENDEATH)) { - final GameEffect effect = GameObjectPool.getInstance().getEffect( - "selection-mod-suddendeath"); - effect.init( - fgScene, - new PointF(Utils.toRes(Config.getRES_WIDTH() - effectOffset), Utils - .toRes(130)), - scale, - new SequenceEntityModifier(ModifierFactory - .newScaleModifier(0.25f, 1.2f, 1), ModifierFactory - .newDelayModifier(2 - timeOffset), - new ParallelEntityModifier(ModifierFactory - .newFadeOutModifier(0.5f), ModifierFactory - .newScaleModifier(0.5f, 1, 1.5f)))); - effectOffset += 25; - timeOffset += 0.25f; - } - else if (stat.getMod().contains(GameMod.MOD_PERFECT)) { - final GameEffect effect = GameObjectPool.getInstance().getEffect( - "selection-mod-perfect"); - effect.init( - fgScene, - new PointF(Utils.toRes(Config.getRES_WIDTH() - effectOffset), Utils - .toRes(130)), - scale, - new SequenceEntityModifier(ModifierFactory - .newScaleModifier(0.25f, 1.2f, 1), ModifierFactory - .newDelayModifier(2 - timeOffset), - new ParallelEntityModifier(ModifierFactory - .newFadeOutModifier(0.5f), ModifierFactory - .newScaleModifier(0.5f, 1, 1.5f)))); - effectOffset += 25; - timeOffset += 0.25f; - } - if (stat.getMod().contains(GameMod.MOD_FLASHLIGHT)) { - final GameEffect effect = GameObjectPool.getInstance().getEffect( - "selection-mod-flashlight"); - effect.init( - fgScene, - new PointF(Utils.toRes(Config.getRES_WIDTH() - effectOffset), Utils - .toRes(130)), - scale, - new SequenceEntityModifier(ModifierFactory - .newScaleModifier(0.25f, 1.2f, 1), ModifierFactory - .newDelayModifier(2 - timeOffset), - new ParallelEntityModifier(ModifierFactory - .newFadeOutModifier(0.5f), ModifierFactory - .newScaleModifier(0.5f, 1, 1.5f)))); - effectOffset += 25; - timeOffset += 0.25f; - } - if (stat.getMod().contains(GameMod.MOD_SMALLCIRCLE)) { - final GameEffect effect = GameObjectPool.getInstance().getEffect( - "selection-mod-smallcircle"); - effect.init( - fgScene, - new PointF(Utils.toRes(Config.getRES_WIDTH() - effectOffset), Utils - .toRes(130)), - scale, - new SequenceEntityModifier(ModifierFactory - .newScaleModifier(0.25f, 1.2f, 1), ModifierFactory - .newDelayModifier(2 - timeOffset), - new ParallelEntityModifier(ModifierFactory - .newFadeOutModifier(0.5f), ModifierFactory - .newScaleModifier(0.5f, 1, 1.5f)))); - effectOffset += 25; - timeOffset += 0.25f; - } - if (stat.getMod().contains(GameMod.MOD_REALLYEASY)) { - final GameEffect effect = GameObjectPool.getInstance().getEffect( - "selection-mod-reallyeasy"); - effect.init( - fgScene, - new PointF(Utils.toRes(Config.getRES_WIDTH() - effectOffset), Utils - .toRes(130)), - scale, - new SequenceEntityModifier(ModifierFactory - .newScaleModifier(0.25f, 1.2f, 1), ModifierFactory - .newDelayModifier(2 - timeOffset), - new ParallelEntityModifier(ModifierFactory - .newFadeOutModifier(0.5f), ModifierFactory - .newScaleModifier(0.5f, 1, 1.5f)))); - effectOffset += 25; - timeOffset += 0.25f; - } - - kiai = false; - kiaiRect = new Rectangle(0, 0, Config.getRES_WIDTH(), - Config.getRES_HEIGHT()); - kiaiRect.setVisible(false); - kiaiRect.setColor(1, 1, 1); - bgScene.attachChild(kiaiRect, 0); - - unranked = new Sprite(0, 0, ResourceManager.getInstance().getTexture("play-unranked")); - unranked.setPosition(Config.getRES_WIDTH() / 2 - unranked.getWidth() / 2, 80); - unranked.setVisible(false); - fgScene.attachChild(unranked); - - boolean hasUnrankedMod = SmartIterator.wrap(stat.getMod().iterator()) - .applyFilter(m -> m.unranked).hasNext(); - if (hasUnrankedMod - || Config.isRemoveSliderLock() - || ModMenu.getInstance().isChangeSpeed() - || ModMenu.getInstance().isEnableForceAR()) { - unranked.setVisible(true); - } - - String playname = null; - replayText = new ChangeableText(0, 0, ResourceManager.getInstance().getFont("font"), "", 1000); - replayText.setVisible(false); - replayText.setPosition(0, 140); - replayText.setAlpha(0.7f); - fgScene.attachChild(replayText, 0); - if (stat.getMod().contains(GameMod.MOD_AUTO) || replaying) { - playname = replaying ? GlobalManager.getInstance().getScoring().getReplayStat().getPlayerName() : "osu!"; - replayText.setText("Watching " + playname + " play " + artist + " - " + title + " [" + version + "]"); - replayText.registerEntityModifier(new LoopEntityModifier(new MoveXModifier(40, - Config.getRES_WIDTH() + 5, -replayText.getWidth() - 5))); - replayText.setVisible(!Config.isHideReplayMarquee()); - } - if (Config.isShowScoreboard()) { - scoreBoard = new DuringGameScoreBoard(fgScene, stat, playname); - addPassiveObject(scoreBoard); - } - - if (GameHelper.isFlashLight()){ - flashlightSprite = new FlashLightEntity(); - fgScene.attachChild(flashlightSprite, 0); - } - -/* PointF point1 = Utils.trackToRealCoords(new PointF(0, 0)); - PointF point2 = Utils.trackToRealCoords(new PointF(0, Constants.MAP_HEIGHT)); - PointF point3 = Utils.trackToRealCoords(new PointF(Constants.MAP_WIDTH, Constants.MAP_HEIGHT)); - PointF point4 = Utils.trackToRealCoords(new PointF(Constants.MAP_WIDTH, 0)); - - Line line1 = new Line(point1.x, point1.y, point2.x, point2.y); - line1.setColor(255 / 255f, 0, 0); - bgScene.attachChild(line1); - - Line line2 = new Line(point2.x, point2.y, point3.x, point3.y); - line2.setColor(255 / 255f, 0, 0); - bgScene.attachChild(line2); - - Line line3 = new Line(point3.x, point3.y, point4.x, point4.y); - line3.setColor(255 / 255f, 0, 0); - bgScene.attachChild(line3); - - Line line4 = new Line(point4.x, point4.y, point1.x, point1.y); - line4.setColor(255 / 255f, 0, 0); - bgScene.attachChild(line4);*/ - - leadOut = 0; - musicStarted = false; - engine.setScene(scene); - scene.registerUpdateHandler(this); - } - - - - - public RGBColor getComboColor(int num) { - return combos.get(num % combos.size()); - } - - // TODO update - - public void onUpdate(final float pSecondsElapsed) { - previousFrameTime = SystemClock.uptimeMillis(); - Utils.clearSoundMask(); - float dt = pSecondsElapsed * timeMultiplier; - if (GlobalManager.getInstance().getSongService().getStatus() == Status.PLAYING) { - //处理时间差过于庞大的情况 - final float offset = totalOffset / 1000f; - final float realsecPassed = //Config.isSyncMusic() ? - GlobalManager.getInstance().getSongService().getPosition() / 1000.0f;// : realTime; - final float criticalError = Config.isSyncMusic() ? 0.1f : 0.5f; - final float normalError = Config.isSyncMusic() ? dt : 0.05f; - - if (secPassed + offset - realsecPassed > criticalError) { - return; - } - - if (Math.abs(secPassed + offset - realsecPassed) > normalError) { - if (secPassed + offset > realsecPassed) { - dt /= 2f; - } else { - dt *= 2f; - } - } - secPassed += dt; - } - float gtime; - if (soundTimingPoint == null || soundTimingPoint.getTime() > secPassed) { - gtime = 0; - } else { - gtime = (secPassed - firstTimingPoint.getTime()) - % (GameHelper.getKiaiTickLength()); - } - GameHelper.setGlobalTime(gtime); - - if (Config.isEnableStoryboard()) { - if (storyboardSprite != null) { - storyboardSprite.updateTime(secPassed * 1000); - } - } - - if (replaying) { - int cIndex; - for (int i = 0; i < replay.cursorIndex.length; i++) { - if (replay.cursorMoves.size() <= i){ - break; - } - cIndex = replay.cursorIndex[i]; - //Emulating moves - while (cIndex < replay.cursorMoves.get(i).size && - replay.cursorMoves.get(i).time[cIndex] <= (secPassed + dt / 4) * 1000) { - final Replay.MoveArray move = replay.cursorMoves.get(i); - - if (move.id[cIndex] == Replay.ID_DOWN) { - cursors[i].mouseDown = true; - for (int j = 0; j < replay.cursorIndex.length; j++) - cursors[j].mouseOldDown = false; - cursors[i].mousePos.x = move.x[cIndex]; - cursors[i].mousePos.y = move.y[cIndex]; - replay.lastMoveIndex[i] = -1; - } else if (move.id[cIndex] == Replay.ID_MOVE) { - cursors[i].mousePos.x = move.x[cIndex]; - cursors[i].mousePos.y = move.y[cIndex]; - replay.lastMoveIndex[i] = cIndex; - } else { - cursors[i].mouseDown = false; - } - - replay.cursorIndex[i]++; - cIndex++; - } - //Interpolating cursor movements - if (cIndex < replay.cursorMoves.get(i).size && - replay.cursorMoves.get(i).id[cIndex] == Replay.ID_MOVE && - replay.lastMoveIndex[i] >= 0) { - final Replay.MoveArray move = replay.cursorMoves.get(i); - final int lIndex = replay.lastMoveIndex[i]; - float t = (secPassed * 1000 - move.time[cIndex]) / (move.time[lIndex] - move.time[cIndex]); - cursors[i].mousePos.x = move.x[lIndex] * t + move.x[cIndex] * (1 - t); - cursors[i].mousePos.y = move.y[lIndex] * t + move.y[cIndex] * (1 - t); - } - } - } - - if (GameHelper.isAuto() || GameHelper.isAutopilotMod()) { - autoCursor.update(dt); - } else if (cursorSprites != null) { - for (int i = 0; i < CursorCount; i++) { - cursorSprites[i].setPosition(cursors[i].mousePos.x, cursors[i].mousePos.y); - cursorSprites[i].update(dt); - if (cursors[i].mouseDown) { - cursorSprites[i].setShowing(true); - if (cursors[i].mousePressed) { - cursorSprites[i].click(); - } - } else { - cursorSprites[i].setShowing(false); - } - } - } - - for (final Cursor c : cursors) { - if (c.mouseDown == true && c.mouseOldDown == false) { - c.mousePressed = true; - c.mouseOldDown = true; - } else { - c.mousePressed = false; - } - } - if(GameHelper.isFlashLight()){ - if (!GameHelper.isAuto() && !GameHelper.isAutopilotMod()) { - if (mainCursorId < 0){ - int i = 0; - for (final Cursor c : cursors) { - if (c.mousePressed == true && isFirstObjectsNear(c.mousePos)) { - mainCursorId = i; - flashlightSprite.onMouseMove(c.mousePos.x, c.mousePos.y); - break; - } - ++i; - } - } else if(cursors[mainCursorId].mouseDown == false){ - mainCursorId = -1; - } else if(cursors[mainCursorId].mouseDown == true){ - flashlightSprite.onMouseMove( - cursors[mainCursorId].mousePos.x, cursors[mainCursorId].mousePos.y - ); - } - } - flashlightSprite.onUpdate(stat.getCombo()); - } - - while (timingPoints.isEmpty() == false - && timingPoints.peek().getTime() <= secPassed + approachRate) { - currentTimingPoint = timingPoints.poll(); - activeTimingPoints.add(currentTimingPoint); - } - while (activeTimingPoints.isEmpty() == false - && activeTimingPoints.peek().getTime() <= secPassed) { - soundTimingPoint = activeTimingPoints.poll(); - if (!soundTimingPoint.inherited) { - GameHelper.setBeatLength(soundTimingPoint.getBeatLength()); - GameHelper.setTimingOffset(soundTimingPoint.getTime()); - } - GameHelper.setTimeSignature(soundTimingPoint.getSignature()); - GameHelper.setKiai(soundTimingPoint.isKiai()); - } - - if (!breakPeriods.isEmpty()) { - if (!breakAnimator.isBreak() - && breakPeriods.peek().getStart() <= secPassed) { - gameStarted = false; - breakAnimator.init(breakPeriods.peek().getLength()); - if(GameHelper.isFlashLight()){ - flashlightSprite.onBreak(true); - } - if(scorebar != null) scorebar.setVisible(false); - breakPeriods.poll(); - } - } - if (breakAnimator.isOver()) { - gameStarted = true; - if(scorebar != null) scorebar.setVisible(true); - if(GameHelper.isFlashLight()){ - flashlightSprite.onBreak(false); - } - } - - if (objects.isEmpty() && activeObjects.isEmpty()) { - if (GameHelper.isFlashLight()) { - flashlightSprite.onBreak(true); - } - } - - if (gameStarted) { - float rate = 0.375f; - if (drain > 0 && distToNextObject > 0) { - rate = 1 + drain / (2f * distToNextObject); - } - stat.changeHp(-rate * 0.01f * dt); - if (stat.getHp() <= 0 - && stat.getMod().contains(GameMod.MOD_NOFAIL) == false - && stat.getMod().contains(GameMod.MOD_RELAX) == false - && stat.getMod().contains(GameMod.MOD_AUTOPILOT) == false - && stat.getMod().contains(GameMod.MOD_AUTO) == false) { - if (stat.getMod().contains(GameMod.MOD_EASY) && failcount < 3) { - failcount++; - stat.changeHp(1f); - } - else { - gameover(); - } - return; - } - } - - if (hitErrorMeter != null) { - hitErrorMeter.update(dt); - } - - if(!Config.isHideInGameUI()) { - //连击数//////////////////////// - final StringBuilder comboBuilder = new StringBuilder(); - comboBuilder.setLength(0); - comboBuilder.append(stat.getCombo()); - while (comboBuilder.length() < 5) { - comboBuilder.append('*'); - } - if (Config.isComplexAnimations()) { - scoreShadow.changeText(comboBuilder); - scoreShadow.registerEntityModifier(new DelayModifier(0.2f, new IEntityModifier.IEntityModifierListener() { - @Override - public void onModifierStarted(IModifier iModifier, IEntity iEntity) { - } - @Override - public void onModifierFinished(IModifier iModifier, IEntity iEntity) { - //当CB数字阴影缩小完成的时候 更改CB数字 - comboText.changeText(comboBuilder); - } - })); - } else { - comboText.changeText(comboBuilder); - } - - //连击数//////////////////////// - strBuilder.setLength(0); - float rawAccuracy = stat.getAccuracy() * 100f; - strBuilder.append((int) rawAccuracy); - if ((int) rawAccuracy < 10) { - strBuilder.insert(0, '0'); - } - strBuilder.append('.'); - rawAccuracy -= (int) rawAccuracy; - rawAccuracy *= 100; - if ((int) rawAccuracy < 10) { - strBuilder.append('0'); - } - strBuilder.append((int) rawAccuracy); - if (strBuilder.length() < 6) { - strBuilder.insert(0, '*'); - } - accText.changeText(strBuilder); - strBuilder.setLength(0); - strBuilder.append(stat.getAutoTotalScore()); - while (strBuilder.length() < 8) { - strBuilder.insert(0, '0'); - } - int scoreTextOffset = 0; - while (strBuilder.length() < 10) { - strBuilder.insert(0, '*'); - scoreTextOffset++; - } - - scoreText.setPosition(Config.getRES_WIDTH() - - ResourceManager.getInstance().getTexture("score-0").getWidth() * (9.25f - scoreTextOffset), 0); - scoreText.changeText(strBuilder); - } - - if (comboBurst != null) { - if (stat.getCombo() == 0) { - comboBurst.breakCombo(); - } else { - comboBurst.checkAndShow(stat.getCombo()); - } - } - - for (final GameObject obj : passiveObjects) { - obj.update(dt); - } - - if (Config.isRemoveSliderLock()){ - GameObject lastObject = getLastTobeclickObject(); - if (lastObject != null) { - lastObjectHitTime = getLastTobeclickObject().getHitTime(); - } - } - - for (final GameObject obj : activeObjects) { - obj.update(dt); - } - - if (GameHelper.isAuto() || GameHelper.isAutopilotMod()) { - autoCursor.moveToObject(activeObjects.peek(), secPassed, this); - } - - int clickCount = 0; - for (final boolean c : cursorIIsDown){ - if (c == true) clickCount++; - } - for (int i = 0; i < CursorCount; i++) { - cursorIIsDown[i] = false; - } - - for (int i = 0; i < clickCount - 1; i++){ - if (Config.isRemoveSliderLock()){ - GameObject lastObject = getLastTobeclickObject(); - if (lastObject != null) { - lastObjectHitTime = getLastTobeclickObject().getHitTime(); - } - } - for (final GameObject obj : activeObjects) { - obj.tryHit(dt); - } - } - - if (secPassed >= 0 && musicStarted == false) { - GlobalManager.getInstance().getSongService().play(); - GlobalManager.getInstance().getSongService().setVolume(Config.getBgmVolume()); - totalLength = GlobalManager.getInstance().getSongService().getLength(); - musicStarted = true; - secPassed = 0; - return; - } -// if (secPassed >= 0) { -// if (!mVideo.getIsPlaying()) { -// mVideo.play(); -// } -// if (mVideo.getAlpha() < 1.0f) { -// float alpha = mVideo.getAlpha(); -// mVideo.setAlpha(Math.min(alpha + 0.03f, 1.0f)); -// } -// } - - boolean shouldBePunished = false; - - while (objects.isEmpty() == false - && secPassed + approachRate > objects.peek().getTime()) { - gameStarted = true; - final GameObjectData data = objects.poll(); - final String[] params = data.getData(); - - final PointF pos = data.getPos(); - // Fix matching error on new beatmaps - final int objDefine = Integer.parseInt(params[3]); - - final float time = data.getRawTime(); - if (time > totalLength) { - shouldBePunished = true; - } - - // Stack notes - // If Config.isCalculateSliderPathInGameStart(), do this in stackNotes() - if (Config.isCalculateSliderPathInGameStart() == false && - objects.isEmpty() == false && (objDefine & 1) > 0) { - if (objects.peek().getTime() - data.getTime() < 2f * GameHelper.getStackLatient() - && Utils.squaredDistance(pos, objects.peek().getPos()) < scale) { - objects.peek().setPosOffset( - data.getPosOffset() + Utils.toRes(4) * scale); - } - } - // If this object is silder and isCalculateSliderPathInGameStart(), the pos is += in calculateAllSliderPaths() - if (Config.isCalculateSliderPathInGameStart() == false || (objDefine & 2) <= 0){ - pos.x += data.getPosOffset(); - pos.y += data.getPosOffset(); - } - if (objects.isEmpty() == false) { - distToNextObject = objects.peek().getTime() - data.getTime(); - if (soundTimingPoint != null - && distToNextObject < soundTimingPoint.getBeatLength() / 2) { - distToNextObject = soundTimingPoint.getBeatLength() / 2; - } - } else { - distToNextObject = 0; - } - // Calculate combo color - int comboCode = objDefine; - if (comboCode == 12) { - currentComboNum = 0; - } else if (comboNum == -1) { - comboNum = 1; - currentComboNum = 0; - } else if ((comboCode & 4) > 0) { - currentComboNum = 0; - if (comboCode / 15 > 0) { - comboCode /= 15; - for (int i = 0; true; i++) { - if (comboCode >> i == 1) { - comboNum = i; - break; - } - } - } else { - comboNum = (comboNum + 1) % combos.size(); - } - } - - if ((objDefine & 1) > 0) { - final RGBColor col = getComboColor(comboNum); - final HitCircle circle = GameObjectPool.getInstance().getCircle(); - String tempSound = null; - if (params.length > 5) { - tempSound = params[5]; - } - - circle.init(this, mgScene, pos, data.getTime() - secPassed, - col.r(), col.g(), col.b(), scale, currentComboNum, - Integer.parseInt(params[4]), tempSound, isFirst); - circle.setEndsCombo(objects.isEmpty() - || objects.peek().isNewCombo()); - addObject(circle); - isFirst = false; - if (objects.isEmpty() == false - && objects.peek().isNewCombo() == false) { - final FollowTrack track = GameObjectPool.getInstance() - .getTrack(); - PointF end; - if (objects.peek().getTime() > data.getTime()) { - end = data.getEnd(); - } else { - end = data.getPos(); - } - track.init(this, bgScene, end, objects.peek().getPos(), - objects.peek().getTime() - secPassed, approachRate, - scale); - } - if (stat.getMod().contains(GameMod.MOD_AUTO)) { - circle.setAutoPlay(); - } - circle.setHitTime(data.getTime()); - - if (objects.isEmpty() == false) { - if (objects.peek().getTime() > data.getTime()) { - currentComboNum++; - } - } - - circle.setId(++lastObjectId); - if (replaying) { - circle.setReplayData(replay.objectData[circle.getId()]); - } - - } else if ((objDefine & 8) > 0) { - final float endTime = Integer.parseInt(params[5]) / 1000.0f; - final float rps = 2 + 2 * overallDifficulty / 10f; - final Spinner spinner = GameObjectPool.getInstance().getSpinner(); - String tempSound = null; - if (params.length > 6) { - tempSound = params[6]; - } - spinner.init(this, bgScene, (data.getTime() - secPassed) / timeMultiplier, - (endTime - data.getTime()) / timeMultiplier, rps, Integer.parseInt(params[4]), - tempSound, stat); - spinner.setEndsCombo(objects.isEmpty() - || objects.peek().isNewCombo()); - addObject(spinner); - isFirst = false; - - if (stat.getMod().contains(GameMod.MOD_AUTO) || - stat.getMod().contains(GameMod.MOD_AUTOPILOT)) { - spinner.setAutoPlay(); - } - - spinner.setId(++lastObjectId); - if (replaying) { - spinner.setReplayData(replay.objectData[spinner.getId()]); - } - - } else if ((objDefine & 2) > 0) { - final RGBColor col = getComboColor(comboNum); - final String soundspec = params.length > 8 ? params[8] : null; - final Slider slider = GameObjectPool.getInstance().getSlider(); - String tempSound = null; - if (params.length > 9) { - tempSound = params[9]; - } - if (Config.isCalculateSliderPathInGameStart()){ - SliderPath sliderPath = getSliderPath(sliderIndex); - slider.init(this, mgScene, pos, data.getPosOffset(), data.getTime() - secPassed, - col.r(), col.g(), col.b(), scale, currentComboNum, - Integer.parseInt(params[4]), - Integer.parseInt(params[6]), - Float.parseFloat(params[7]), params[5], - currentTimingPoint, soundspec, tempSound, isFirst, Double.parseDouble(params[2]), - sliderPath); - sliderIndex++; - } - else{ - slider.init(this, mgScene, pos, data.getPosOffset(), data.getTime() - secPassed, - col.r(), col.g(), col.b(), scale, currentComboNum, - Integer.parseInt(params[4]), - Integer.parseInt(params[6]), - Float.parseFloat(params[7]), params[5], - currentTimingPoint, soundspec, tempSound, isFirst, Double.parseDouble(params[2])); - } - slider.setEndsCombo(objects.isEmpty() - || objects.peek().isNewCombo()); - addObject(slider); - isFirst = false; - - if (objects.isEmpty() == false - && objects.peek().isNewCombo() == false) { - final FollowTrack track = GameObjectPool.getInstance() - .getTrack(); - PointF end; - if (objects.peek().getTime() > data.getTime()) { - end = data.getEnd(); - } else { - end = data.getPos(); - } - track.init(this, bgScene, end, objects.peek().getPos(), - objects.peek().getTime() - secPassed, approachRate, - scale); - } - if (stat.getMod().contains(GameMod.MOD_AUTO)) { - slider.setAutoPlay(); - } - slider.setHitTime(data.getTime()); - - - if (objects.isEmpty() == false) { - if (objects.peek().getTime() > data.getTime()) { - currentComboNum++; - } - } - - slider.setId(++lastObjectId); - if (replaying) { - slider.setReplayData(replay.objectData[slider.getId()]); - if (slider.getReplayData().tickSet == null) - slider.getReplayData().tickSet = new BitSet(); - } - } - } - - // 节拍器 - if (metronome != null) { - metronome.update(secPassed); - } - - //Status playerStatus = music.getStatus(); - Status playerStatus = GlobalManager.getInstance().getSongService().getStatus(); - - if (playerStatus != Status.PLAYING) { - secPassed += dt; - } - - if (shouldBePunished || (objects.isEmpty() && activeObjects.isEmpty() && leadOut > 2)) { - scene = new Scene(); - SkinManager.setSkinEnabled(false); - GameObjectPool.getInstance().purge(); - SpritePool.getInstance().purge(); - passiveObjects.clear(); - breakPeriods.clear(); - cursorSprites = null; - String replayFile = null; - stat.setTime(System.currentTimeMillis()); - if (replay != null && replaying == false) { - String ctime = String.valueOf(System.currentTimeMillis()); - replayFile = Config.getCorePath() + "Scores/" - + MD5Calcuator.getStringMD5(lastTrack.getFilename() + ctime) - + ctime.substring(0, Math.min(3, ctime.length())) + ".odr"; - replay.setStat(stat); - replay.save(replayFile); - } - if (GlobalManager.getInstance().getCamera() instanceof SmoothCamera) { - SmoothCamera camera = (SmoothCamera) (GlobalManager.getInstance().getCamera()); - camera.setZoomFactorDirect(1f); - if (Config.isShrinkPlayfieldDownwards()) { - camera.setCenterDirect(Config.getRES_WIDTH() / 2, Config.getRES_HEIGHT() / 2); - } - } - if (scoringScene != null) { - if (replaying) { - ModMenu.getInstance().setMod(Replay.oldMod); - ModMenu.getInstance().setChangeSpeed(Replay.oldChangeSpeed); - ModMenu.getInstance().setForceAR(Replay.oldForceAR); - ModMenu.getInstance().setEnableForceAR(Replay.oldEnableForceAR); - ModMenu.getInstance().setFLfollowDelay(Replay.oldFLFollowDelay); - } - - if (replaying) - scoringScene.load(scoringScene.getReplayStat(), null, GlobalManager.getInstance().getSongService(), replayFile, null, lastTrack); - else { - if (stat.getMod().contains(GameMod.MOD_AUTO)) { - stat.setPlayerName("osu!"); - } - - EdExtensionHelper.onEndGame(lastTrack, stat); - if (storyboardSprite != null) { - storyboardSprite.releaseStoryboard(); - storyboardSprite = null; - storyboardOverlayProxy.setDrawProxy(null); - } - - scoringScene.load(stat, lastTrack, GlobalManager.getInstance().getSongService(), replayFile, trackMD5, null); - } - GlobalManager.getInstance().getSongService().setVolume(0.2f); - engine.setScene(scoringScene.getScene()); - } else { - engine.setScene(oldScene); - } - - } else if (objects.isEmpty() && activeObjects.isEmpty()) { - gameStarted = false; - leadOut += dt; - } - - // TODO skip button - if (secPassed > skipTime - 1f && skipBtn != null) { - skipBtn.detachSelf(); - skipBtn = null; - } else if (skipBtn != null) { - for (final Cursor c : cursors) { - if (c.mouseDown == true - && Utils.distance( - c.mousePos, - new PointF(Config.getRES_WIDTH(), Config - .getRES_HEIGHT())) < 250) { - - /*if (music.getStatus() != Status.PLAYING) { - music.play(); - music.setVolume(Config.getBgmVolume()); - totalLength = music.getLength(); - musicStarted = true; - }*/ - if (GlobalManager.getInstance().getSongService().getStatus() != Status.PLAYING) { - GlobalManager.getInstance().getSongService().play(); - GlobalManager.getInstance().getSongService().setVolume(Config.getBgmVolume()); - totalLength = GlobalManager.getInstance().getSongService().getLength(); - musicStarted = true; - } - ResourceManager.getInstance().getSound("menuhit").play(); - final float difference = skipTime - 0.5f - secPassed; - for (final GameObject obj : passiveObjects) { - obj.update(difference); - } - //music.seekTo((int) Math.ceil((skipTime - 0.5f) * 1000)); - GlobalManager.getInstance().getSongService().seekTo((int) Math.ceil((skipTime - 0.5f) * 1000)); - secPassed = skipTime - 0.5f; - skipBtn.detachSelf(); - skipBtn = null; - return; - } - } - } - -/* if (GameHelper.isKiai() && Config.isComplexAnimations() && Config.getBackgroundBrightness() != 0) { - final float kiaiModifier = Math - .max(0, - 1 - GameHelper.getGlobalTime() / - GameHelper.getKiaiTickLength()) * 0.15f; - final float a = Math.min(1, kiaiModifier); - if (kiai == false) { - kiaiRect.setVisible(true); - } - kiai = true; - kiaiRect.setAlpha(a); - } else if (kiai == true) { - kiaiRect.setVisible(false); - kiai = false; - }*/ - } // update(float dt) - - private void onExit() { - - //游戏退出 - - if (!replaying) { - EdExtensionHelper.onExitGame(lastTrack); - } - - SkinManager.setSkinEnabled(false); - GameObjectPool.getInstance().purge(); - SpritePool.getInstance().purge(); - passiveObjects.clear(); - breakPeriods.clear(); - cursorSprites = null; - - if (GlobalManager.getInstance().getSongService() != null) { - GlobalManager.getInstance().getSongService().stop(); - GlobalManager.getInstance().getSongService().preLoad(filePath); - GlobalManager.getInstance().getSongService().play(); - } - - /*try { - android.os.Debug.dumpHprofData(Environment.getExternalStorageDirectory().getPath()+"/dd.hprof"); - } catch (IOException e) { - e.printStackTrace(); - }*/ - if (replaying) { - replayFile = null; - ModMenu.getInstance().setMod(Replay.oldMod); - ModMenu.getInstance().setChangeSpeed(Replay.oldChangeSpeed); - ModMenu.getInstance().setForceAR(Replay.oldForceAR); - ModMenu.getInstance().setEnableForceAR(Replay.oldEnableForceAR); - } - } - - public void quit() { - - //游戏中退出,通过暂停菜单 - - if (!replaying) { - EdExtensionHelper.onQuitGame(lastTrack); - } - - if (storyboardSprite != null) { - storyboardSprite.releaseStoryboard(); - storyboardSprite = null; - storyboardOverlayProxy.setDrawProxy(null); - } - - onExit(); - ResourceManager.getInstance().getSound("failsound").stop(); - if (GlobalManager.getInstance().getCamera() instanceof SmoothCamera) { - SmoothCamera camera = (SmoothCamera) (GlobalManager.getInstance().getCamera()); - camera.setZoomFactorDirect(1f); - if (Config.isShrinkPlayfieldDownwards()) { - camera.setCenterDirect(Config.getRES_WIDTH() / 2, Config.getRES_HEIGHT() / 2); - } - } - scene = new Scene(); - engine.setScene(oldScene); - } - - - public void reset() { - } - - //CB打击处理 - private String registerHit(final int objectId, final int score, final boolean endCombo) { - boolean writeReplay = objectId != -1 && replay != null && !replaying; - if (score == 0) { - if (stat.getCombo() > 30) { - ResourceManager.getInstance().getCustomSound("combobreak", 1) - .play(); - } - comboWasMissed = true; - stat.registerHit(0, false, false); - if (writeReplay) replay.addObjectScore(objectId, Replay.RESULT_0); - if(GameHelper.isPerfect()){ - gameover(); - restartGame(); - } - if(GameHelper.isSuddenDeath())stat.changeHp(-1.0f); - return "hit0"; - } - - String scoreName = "hit300"; - if (score == 50) { - stat.registerHit(50, false, false); - if (writeReplay) replay.addObjectScore(objectId, Replay.RESULT_50); - scoreName = "hit50"; - comboWas100 = true; - if(GameHelper.isPerfect()){ - gameover(); - restartGame(); - } - } else if (score == 100) { - comboWas100 = true; - if (writeReplay) replay.addObjectScore(objectId, Replay.RESULT_100); - if (endCombo && comboWasMissed == false) { - stat.registerHit(100, true, false); - scoreName = "hit100k"; - } else { - stat.registerHit(100, false, false); - scoreName = "hit100"; - } - if(GameHelper.isPerfect()){ - gameover(); - restartGame(); - } - } else if (score == 300) { - if (writeReplay) replay.addObjectScore(objectId, Replay.RESULT_300); - if (endCombo && comboWasMissed == false) { - if (comboWas100 == false) { - stat.registerHit(300, true, true); - scoreName = "hit300g"; - } else { - stat.registerHit(300, true, false); - scoreName = "hit300k"; - } - } else { - stat.registerHit(300, false, false); - scoreName = "hit300"; - } - } - - if (endCombo) { - comboWas100 = false; - comboWasMissed = false; - } - - return scoreName; - } - - - public void onCircleHit(int id, final float acc, final PointF pos, - final boolean endCombo, byte forcedScore, RGBColor color) { - if (GameHelper.isAuto()) { - autoCursor.click(); - } - - float accuracy = Math.abs(acc); - boolean writeReplay = replay != null && !replaying; - if (writeReplay) { - short sacc = (short) (acc * 1000); - replay.addObjectResult(id, sacc, null); - } - if(GameHelper.isFlashLight() && !GameHelper.isAuto() && !GameHelper.isAutopilotMod()){ - int nearestCursorId = getNearestCursorId(pos.x, pos.y); - if (nearestCursorId >= 0) { - mainCursorId = nearestCursorId; - flashlightSprite.onMouseMove( - cursors[mainCursorId].mousePos.x, - cursors[mainCursorId].mousePos.y - ); - } - } - - //(30 - overallDifficulty) / 100f - if (accuracy > difficultyHelper.hitWindowFor50(overallDifficulty) || forcedScore == Replay.RESULT_0) { - createHitEffect(pos, "hit0", color); - registerHit(id, 0, endCombo); - return; - } - - String scoreName = "hit300"; - if (forcedScore == Replay.RESULT_300 || - forcedScore == 0 && accuracy <= difficultyHelper.hitWindowFor300(overallDifficulty)) { - //(75 + 25 * (5 - overallDifficulty) / 5) / 1000) - scoreName = registerHit(id, 300, endCombo); - } else if (forcedScore == Replay.RESULT_100 || - forcedScore == 0 && accuracy <= difficultyHelper.hitWindowFor100(overallDifficulty)) { - //(150 + 50 * (5 - overallDifficulty) / 5) / 1000) - scoreName = registerHit(id, 100, endCombo); - } else { - scoreName = registerHit(id, 50, endCombo); - } - - createBurstEffect(pos, color); - createHitEffect(pos, scoreName, color); - - - } - - public void onSliderReverse(PointF pos, float ang, RGBColor color) { - createBurstEffectSliderReverse(pos, ang, color); - } - - public void onSliderHit(int id, final int score, final PointF start, - final PointF end, final boolean endCombo, RGBColor color, int type) { - if (score == 0) { - createHitEffect(start, "hit0", color); - createHitEffect(end, "hit0", color); - registerHit(id, 0, endCombo); - return; - } - - if (score == -1) { - if (stat.getCombo() > 30) { - ResourceManager.getInstance().getCustomSound("combobreak", 1) - .play(); - } - if(GameHelper.isSuddenDeath()) stat.changeHp(-1.0f); - stat.registerHit(0, true, false); - return; - } - - String scoreName = "hit0"; - switch (score) { - case 300: - scoreName = registerHit(id, 300, endCombo); - break; - case 100: - scoreName = registerHit(id, 100, endCombo); - stat.setPerfect(false); - break; - case 50: - scoreName = registerHit(id, 50, endCombo); - stat.setPerfect(false); - break; - case 30: - scoreName = "sliderpoint30"; - stat.registerHit(30, false, false); - break; - case 10: - scoreName = "sliderpoint10"; - stat.registerHit(10, false, false); - break; - } - - if (score > 10) { - switch (type) { - case GameObjectListener.SLIDER_START: - createBurstEffectSliderStart(end, color); - break; - case GameObjectListener.SLIDER_END: - createBurstEffectSliderEnd(end, color); - break; - case GameObjectListener.SLIDER_REPEAT: - break; - default: - createBurstEffect(end, color); - } - } - createHitEffect(end, scoreName, color); - } - - - public void onSpinnerHit(int id, final int score, final boolean endCombo, int totalScore) { - if (score == 1000) { - stat.registerHit(score, false, false); - return; - } - - if (replay != null && !replaying) { - short acc = (short) (totalScore * 4); - switch (score) { - case 300: - acc += 3; - break; - case 100: - acc += 2; - break; - case 50: - acc += 1; - break; - } - replay.addObjectResult(id, acc, null); - } - - final PointF pos = new PointF(Config.getRES_WIDTH() / 2, - Config.getRES_HEIGHT() / 2); - if (score == 0) { - final GameEffect effect = GameObjectPool.getInstance().getEffect( - "hit0"); - effect.init( - scene, - pos, - scale, - new SequenceEntityModifier(ModifierFactory - .newFadeInModifier(0.15f), ModifierFactory - .newDelayModifier(0.35f), ModifierFactory - .newFadeOutModifier(0.25f))); - registerHit(id, 0, endCombo); - return; - } - - String scoreName = "hit0"; - switch (score) { - case 300: - scoreName = registerHit(id, 300, endCombo); - break; - case 100: - scoreName = registerHit(id, 100, endCombo); - break; - case 50: - scoreName = registerHit(id, 50, endCombo); - break; - } - - if (ResourceManager.getInstance().getTexture("lighting") != null) { - final GameEffect light = GameObjectPool.getInstance().getEffect( - "lighting"); - light.init( - mgScene, - pos, - scale, - new FadeOutModifier(0.7f), - new SequenceEntityModifier(ModifierFactory - .newScaleModifier(0.25f, scale, 1.5f * scale), - ModifierFactory.newScaleModifier(0.45f, - scale * 1.5f, 2f * scale))); - } - - GameEffect effect = GameObjectPool.getInstance().getEffect(scoreName); - effect.init( - mgScene, - pos, - scale, - new SequenceEntityModifier(ModifierFactory.newScaleModifier( - 0.15f, 1.0f * scale, 1.2f * scale), ModifierFactory - .newScaleModifier(0.05f, 1.2f * scale, 1.0f * scale), - ModifierFactory.newAlphaModifier(1f, 1, 0))); - - pos.y /= 2f; - effect = GameObjectPool.getInstance().getEffect("spinner-osu"); - effect.init(mgScene, pos, 1, ModifierFactory.newFadeOutModifier(1.5f)); - } - - public void playSound(final String name, final int sampleSet, final int addition) { - if (addition > 0 && !name.equals("hitnormal") && addition < Constants.SAMPLE_PREFIX.length) { - playSound(Constants.SAMPLE_PREFIX[addition], name); - return; - } - if (sampleSet > 0 && sampleSet < Constants.SAMPLE_PREFIX.length) { - playSound(Constants.SAMPLE_PREFIX[sampleSet], name); - } else { - playSound(soundTimingPoint.getHitSound(), name); - } - } - - public void playSound(final String prefix, final String name) { - final String fullName = prefix + "-" + name; - BassSoundProvider snd; - if (soundTimingPoint.getCustomSound() == 0) { - snd = ResourceManager.getInstance().getSound(fullName); - } else { - snd = ResourceManager.getInstance().getCustomSound(fullName, - soundTimingPoint.getCustomSound()); - } - if(snd == null) { - return; - } - if (name.equals("sliderslide") || name.equals("sliderwhistle")) { - snd.setLooping(true); - } - if (name.equals("hitnormal")) { - snd.play(soundTimingPoint.getVolume() * 0.8f); - return; - } - if (name.equals("hitwhistle") - || name.equals("hitclap")) { - snd.play(soundTimingPoint.getVolume() * 0.85f); - return; - } - snd.play(soundTimingPoint.getVolume()); - } - - - public void addObject(final GameObject object) { - activeObjects.add(object); - } - - - public PointF getMousePos(final int index) { - return cursors[index].mousePos; - } - - - public boolean isMouseDown(final int index) { - return cursors[index].mouseDown; - } - - - public boolean isMousePressed(final GameObject object, final int index) { - if (stat.getMod().contains(GameMod.MOD_AUTO)) { - return false; - } - if (Config.isRemoveSliderLock()){ - if(activeObjects.isEmpty() - || Math.abs(object.getHitTime() - lastObjectHitTime) > 0.001f) { - return false; - } - } - else if (activeObjects.isEmpty() - || Math.abs(object.getHitTime() - - activeObjects.peek().getHitTime()) > 0.001f) { - return false; - } - return cursors[index].mousePressed; - } - - private GameObject getLastTobeclickObject(){ - Iterator iterator = activeObjects.iterator(); - while(iterator.hasNext()){ - GameObject note = (GameObject)iterator.next(); - if(note.isStartHit() == false)return note; - } - return null; - } - - @Override - public double downFrameOffset(int index) { - return cursors[index].mouseDownOffsetMS; - } - - public void removeObject(final GameObject object) { - activeObjects.remove(object); - } - - public boolean onSceneTouchEvent(final Scene pScene, - final TouchEvent pSceneTouchEvent) { - if (pSceneTouchEvent.getPointerID() < 0 - || pSceneTouchEvent.getPointerID() >= CursorCount) { - Debug.e("Invalid pointerID: " + pSceneTouchEvent.getPointerID()); - return false; - } - if (replaying) { - return false; - } - final int i = pSceneTouchEvent.getPointerID(); - float pTouchX = FMath.clamp(pSceneTouchEvent.getX(), 0, Config.getRES_WIDTH()); - float pTouchY = FMath.clamp(pSceneTouchEvent.getY(), 0, Config.getRES_HEIGHT()); - if (pSceneTouchEvent.isActionDown()) { - cursors[i].mouseDown = true; - cursors[i].mouseDownOffsetMS = (pSceneTouchEvent.getMotionEvent().getEventTime() - previousFrameTime) * timeMultiplier; - for (int j = 0; j < cursors.length; j++) - cursors[j].mouseOldDown = false; - PointF gamePoint = Utils.realToTrackCoords(new PointF(pTouchX, pTouchY)); - cursors[i].mousePos.x = pTouchX; - cursors[i].mousePos.y = pTouchY; - if (replay != null) { - replay.addPress(secPassed, gamePoint, i); - } - cursorIIsDown[i] = true; - } else if (pSceneTouchEvent.isActionMove()) { - PointF gamePoint = Utils.realToTrackCoords(new PointF(pTouchX, pTouchY)); - cursors[i].mousePos.x = pTouchX; - cursors[i].mousePos.y = pTouchY; - if (replay != null) { - replay.addMove(secPassed, gamePoint, i); - } - } else if (pSceneTouchEvent.isActionUp()) { - cursors[i].mouseDown = false; - if (replay != null) { - replay.addUp(secPassed, i); - } - } else { - return false; - } - return true; - } - - - public void stopSound(final String name) { - final String prefix = soundTimingPoint.getHitSound() + "-"; - final BassSoundProvider snd = ResourceManager.getInstance().getSound(prefix + name); - if (snd != null) { - snd.stop(); - } - } - - public void pause() { - if (paused) { - return; - } - - if (!replaying) { - EdExtensionHelper.onPauseGame(lastTrack); - } - - // totalOffset += Config.getPauseOffset(); - final PauseMenu menu = new PauseMenu(engine, this, false); - /*if (music != null && music.getStatus() == Status.PLAYING) { - music.pause(); - }*/ - if (GlobalManager.getInstance().getSongService() != null && GlobalManager.getInstance().getSongService().getStatus() == Status.PLAYING) { - GlobalManager.getInstance().getSongService().pause(); - } - paused = true; - scene.setChildScene(menu.getScene(), false, true, true); - } - - public void gameover() { - - if (!replaying) { - EdExtensionHelper.onGameover(lastTrack); - } - - if(scorebar != null) scorebar.flush(); - ResourceManager.getInstance().getSound("failsound").play(); - final PauseMenu menu = new PauseMenu(engine, this, true); - gameStarted = false; - /*if (music != null && music.getStatus() == Status.PLAYING) { - music.pause(); - }*/ - if (GlobalManager.getInstance().getSongService() != null && GlobalManager.getInstance().getSongService().getStatus() == Status.PLAYING) { - GlobalManager.getInstance().getSongService().pause(); - } - paused = true; - scene.setChildScene(menu.getScene(), false, true, true); - } - - public void resume() { - if (!paused) { - return; - } - - scene.getChildScene().back(); - paused = false; - if (stat.getHp() <= 0 && stat.getMod().contains(GameMod.MOD_NOFAIL) == false - && stat.getMod().contains(GameMod.MOD_RELAX) == false - && stat.getMod().contains(GameMod.MOD_AUTOPILOT) == false) { - quit(); - return; - } - /*if (music != null && music.getStatus() != Status.PLAYING && secPassed > 0) { - music.play(); - music.setVolume(Config.getBgmVolume()); - totalLength = music.getLength(); - }*/ - - if (!replaying) { - EdExtensionHelper.onResume(lastTrack); - } - - if (GlobalManager.getInstance().getSongService() != null && GlobalManager.getInstance().getSongService().getStatus() != Status.PLAYING && secPassed > 0) { - GlobalManager.getInstance().getSongService().play(); - GlobalManager.getInstance().getSongService().setVolume(Config.getBgmVolume()); - totalLength = GlobalManager.getInstance().getSongService().getLength(); - } - } - - public boolean isPaused() { - return paused; - } - - - public void addPassiveObject(final GameObject object) { - passiveObjects.add(object); - } - - - public void removePassiveObject(final GameObject object) { - passiveObjects.remove(object); - } - - private void createHitEffect(final PointF pos, final String name, RGBColor color) { - final GameEffect effect = GameObjectPool.getInstance().getEffect(name); - if (name.equals("hit0")) { - if(GameHelper.isSuddenDeath()){ - effect.init( - mgScene, - pos, - scale * 3, - new SequenceEntityModifier(ModifierFactory - .newFadeInModifier(0.15f), ModifierFactory - .newDelayModifier(0.35f), ModifierFactory - .newFadeOutModifier(0.25f))); - return; - } - effect.init( - mgScene, - pos, - scale, - new SequenceEntityModifier(ModifierFactory - .newFadeInModifier(0.15f), ModifierFactory - .newDelayModifier(0.35f), ModifierFactory - .newFadeOutModifier(0.25f))); - return; - } - - if (Config.isComplexAnimations() - && name.equals("sliderpoint10") == false - && name.equals("sliderpoint30") == false - && ResourceManager.getInstance().getTexture("lighting") != null - && Config.isHitLighting()) { - final GameEffect light = GameObjectPool.getInstance().getEffect("lighting"); - light.setColor(color); - light.init( - bgScene, - pos, - scale, - ModifierFactory.newFadeOutModifier(1f), - new SequenceEntityModifier(ModifierFactory - .newScaleModifier(0.25f, scale, 1.5f * scale), - ModifierFactory.newScaleModifier(0.45f, - scale * 1.5f, 1.9f * scale), - ModifierFactory.newScaleModifier(0.3f, scale * 1.9f, scale * 2f) - )); - light.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_DST_ALPHA); - } - - effect.init( - mgScene, - pos, - scale, - new SequenceEntityModifier(ModifierFactory.newScaleModifier( - 0.15f, 1.0f * scale, 1.2f * scale), ModifierFactory - .newScaleModifier(0.05f, 1.2f * scale, 1.0f * scale), - ModifierFactory.newAlphaModifier(0.5f, 1, 0))); - } - - private void createBurstEffect(final PointF pos, final RGBColor color) { - if (!Config.isComplexAnimations() || !Config.isBurstEffects()) return; - final GameEffect burst1 = GameObjectPool.getInstance().getEffect("hitcircle"); - burst1.init(mgScene, pos, scale, - ModifierFactory.newScaleModifier(0.25f, scale, 1.5f * scale), - ModifierFactory.newAlphaModifier(0.25f, 0.8f, 0) - ); - burst1.setColor(color); - - final GameEffect burst2 = GameObjectPool.getInstance().getEffect("hitcircleoverlay"); - burst2.init(mgScene, pos, scale, - ModifierFactory.newScaleModifier(0.25f, scale, 1.5f * scale), - ModifierFactory.newAlphaModifier(0.25f, 0.8f, 0) - ); - - } - - private void createBurstEffectSliderStart(final PointF pos, final RGBColor color) { - if (!Config.isComplexAnimations() || !Config.isBurstEffects()) return; - final GameEffect burst1 = GameObjectPool.getInstance().getEffect("sliderstartcircle"); - burst1.init(mgScene, pos, scale, - ModifierFactory.newScaleModifier(0.25f, scale, 1.5f * scale), - ModifierFactory.newAlphaModifier(0.25f, 0.8f, 0) - ); - burst1.setColor(color); - - final GameEffect burst2 = GameObjectPool.getInstance().getEffect("sliderstartcircleoverlay"); - burst2.init(mgScene, pos, scale, - ModifierFactory.newScaleModifier(0.25f, scale, 1.5f * scale), - ModifierFactory.newAlphaModifier(0.25f, 0.8f, 0) - ); - - } - - private void createBurstEffectSliderEnd(final PointF pos, final RGBColor color) { - if (!Config.isComplexAnimations() || !Config.isBurstEffects()) return; - final GameEffect burst1 = GameObjectPool.getInstance().getEffect("sliderendcircle"); - burst1.init(mgScene, pos, scale, - ModifierFactory.newScaleModifier(0.25f, scale, 1.5f * scale), - ModifierFactory.newAlphaModifier(0.25f, 0.8f, 0) - ); - burst1.setColor(color); - - final GameEffect burst2 = GameObjectPool.getInstance().getEffect("sliderendcircleoverlay"); - burst2.init(mgScene, pos, scale, - ModifierFactory.newScaleModifier(0.25f, scale, 1.5f * scale), - ModifierFactory.newAlphaModifier(0.25f, 0.8f, 0) - ); - - } - - private void createBurstEffectSliderReverse(final PointF pos, float ang, final RGBColor color) { - if (!Config.isComplexAnimations() || !Config.isBurstEffects()) return; - final GameEffect burst1 = GameObjectPool.getInstance().getEffect("reversearrow"); - burst1.hit.setRotation(ang); - burst1.init(mgScene, pos, scale, - ModifierFactory.newScaleModifier(0.25f, scale, 1.5f * scale), - ModifierFactory.newAlphaModifier(0.25f, 0.8f, 0) - ); - - } - - public int getCursorsCount() { - return CursorCount; - } - - - public void registerAccuracy(final float acc) { - if (hitErrorMeter != null) { - hitErrorMeter.putErrorResult(acc); - } - avgOffset += acc; - offsetRegs++; - } - - - public void onSliderEnd(int id, int accuracy, BitSet tickSet) { - onTrackingSliders(false); - if (GameHelper.isAuto()) { - autoCursor.onSliderEnd(); - } - if (replay != null && !replaying) { - short acc = (short) (accuracy); - replay.addObjectResult(id, acc, (BitSet) tickSet.clone()); - } - } - - public void onTrackingSliders(boolean isTrackingSliders) { - if (GameHelper.isAuto()) { - autoCursor.onSliderTracking(); - } - if (GameHelper.isFlashLight()) { - flashlightSprite.onTrackingSliders(isTrackingSliders); - } - } - - public void onUpdatedAutoCursor(float pX, float pY) { - if (GameHelper.isFlashLight()) { - flashlightSprite.onMouseMove(pX, pY); - } - } - - public void updateAutoBasedPos(float pX, float pY) { - if (GameHelper.isAuto() || GameHelper.isAutopilotMod()) { - autoCursor.setPosition(pX, pY, this); - } - } - - private int getNearestCursorId(float pX, float pY){ - float distance = Float.POSITIVE_INFINITY, cursorDistance, dx, dy; - int id = -1, i = 0; - for (Cursor c : cursors) { - if(c.mouseDown == true || c.mousePressed == true || c.mouseOldDown == true){ - dx = c.mousePos.x - pX; - dy = c.mousePos.y - pY; - cursorDistance = dx * dx + dy * dy; - if(cursorDistance < distance){ - id = i; - distance = cursorDistance; - } - } - ++i; - } - return id; - } - - private boolean isFirstObjectsNear(PointF pos){ - if (activeObjects.isEmpty()) { - return true; - } - if (activeObjects.peek() instanceof Spinner || activeObjects.peek() instanceof Slider) { - return true; - } - else if (Utils.squaredDistance(pos, activeObjects.peek().getPos()) < 180f * 180f) { - return true; - } - return false; - } - - private void stackNotes(){ - // Stack notes - int i = 0; - for (GameObjectData data : objects){ - final PointF pos = data.getPos(); - final String[] params = data.getData(); - final int objDefine = Integer.parseInt(params[3]); - if (objects.isEmpty() == false && (objDefine & 1) > 0 && i + 1 < objects.size()) { - if (objects.get(i + 1).getTime() - data.getTime() < 2f * GameHelper.getStackLatient() - && Utils.squaredDistance(pos, objects.get(i + 1).getPos()) < scale) { - objects.get(i + 1).setPosOffset( - data.getPosOffset() + Utils.toRes(4) * scale); - } - } - i++; - } - } - - private void calculateAllSliderPaths(){ - if (objects.isEmpty()){ - return; - } - else { - if (lastTrack.getSliderCount() <= 0){ - return; - } - sliderPaths = new SliderPath[lastTrack.getSliderCount()]; - for (SliderPath path : sliderPaths){ - path = null; - } - int i = 0; - sliderIndex = 0; - for (GameObjectData data : objects){ - final String[] params = data.getData(); - final int objDefine = Integer.parseInt(params[3]); - //is slider - if ((objDefine & 2) > 0) { - final PointF pos = data.getPos(); - final float length = Float.parseFloat(params[7]); - final float offset = data.getPosOffset(); - pos.x += data.getPosOffset(); - pos.y += data.getPosOffset(); - if (length < 0){ - sliderPaths[sliderIndex] = GameHelper.calculatePath(Utils.realToTrackCoords(pos), - params[5].split("[|]"), 0, offset); - } - else{ - sliderPaths[sliderIndex] = GameHelper.calculatePath(Utils.realToTrackCoords(pos), - params[5].split("[|]"), length, offset); - } - sliderIndex++; - } - i++; - } - sliderIndex = 0; - } - } - - private SliderPath getSliderPath(int index){ - if (sliderPaths != null && index < sliderPaths.length && index >= 0){ - return sliderPaths[index]; - } - else { - return null; - } - } - - public boolean getReplaying() { - return replaying; - } - - public boolean saveFailedReplay() { - stat.setTime(System.currentTimeMillis()); - if (replay != null && replaying == false) { - //write misses to replay - for (GameObject obj : activeObjects) { - stat.registerHit(0, false, false); - replay.addObjectScore(obj.getId(), Replay.RESULT_0); - } - while (objects.isEmpty() == false){ - objects.poll(); - stat.registerHit(0, false, false); - replay.addObjectScore(++lastObjectId, Replay.RESULT_0); - } - //save replay - String ctime = String.valueOf(System.currentTimeMillis()); - replayFile = Config.getCorePath() + "Scores/" - + MD5Calcuator.getStringMD5(lastTrack.getFilename() + ctime) - + ctime.substring(0, Math.min(3, ctime.length())) + ".odr"; - replay.setStat(stat); - replay.save(replayFile); - ScoreLibrary.getInstance().addScore(lastTrack.getFilename(), stat, replayFile); - ToastLogger.showText(StringTable.get(R.string.message_save_replay_successful), true); - return true; - } - else{ - ToastLogger.showText(StringTable.get(R.string.message_save_replay_failed), true); - return false; - } - } + IOnSceneTouchListener { + public static final int CursorCount = 10; + private final Engine engine; + private final Cursor[] cursors = new Cursor[CursorCount]; + private final boolean[] cursorIIsDown = new boolean[CursorCount]; + private final StringBuilder strBuilder = new StringBuilder(); + public String filePath = null; + private Scene scene; + private Scene bgScene, mgScene, fgScene; + private Scene oldScene; + private BeatmapData beatmapData; + private TrackInfo lastTrack; + private ScoringScene scoringScene; + private TimingPoint currentTimingPoint; + private TimingPoint soundTimingPoint; + private TimingPoint firstTimingPoint; + private Queue timingPoints; + private Queue activeTimingPoints; + private String trackMD5; + private int lastObjectId = -1; + private float secPassed = 0; + private float leadOut = 0; + private LinkedList objects; + private ArrayList combos; + private int comboNum; // use this to show combo color + private int currentComboNum; + private boolean comboWasMissed = false; + private boolean comboWas100 = false; + private Queue activeObjects; + private LinkedList passiveObjects = new LinkedList(); + private GameScoreText comboText, accText, scoreText; //显示的文字 连击数 ACC 分数 + private GameScoreTextShadow scoreShadow; + private Queue breakPeriods = new LinkedList(); + private BreakAnimator breakAnimator; + private ScoreBar scorebar; + private SongProgressBar progressBar; + private DuringGameScoreBoard scoreBoard; + private HitErrorMeter hitErrorMeter; + private Metronome metronome; + private boolean isFirst = true; + private float scale; + private float approachRate; + private float rawDifficulty; + private float overallDifficulty; + private float rawDrain; + private float drain; + private StatisticV2 stat; + private boolean gameStarted; + private float totalOffset; + //private IMusicPlayer music = null; + private int totalLength = Integer.MAX_VALUE; + private boolean loadComplete; + private boolean paused; + private Sprite skipBtn; + private float skipTime; + private boolean musicStarted; + private float distToNextObject; + private float timeMultiplier = 1.0f; + private CursorEntity[] cursorSprites; + private AutoCursor autoCursor; + private FlashLightEntity flashlightSprite; + private int mainCursorId = -1; + private Replay replay; + private boolean replaying; + private String replayFile; + private float avgOffset; + private int offsetRegs; + private boolean kiai = false; + private Rectangle kiaiRect = null; + private Sprite bgSprite = null; + private Sprite unranked; + private ChangeableText replayText; + private String title, artist, version; + private ComboBurst comboBurst; + private VideoSprite mVideo = null; + private Sprite[] ScoreBoardSprite; + private int failcount = 0; + private float lastObjectHitTime = 0; + private SliderPath[] sliderPaths = null; + private int sliderIndex = 0; + + private StoryboardSprite storyboardSprite; + private ProxySprite storyboardOverlayProxy; + + private DifficultyHelper difficultyHelper = DifficultyHelper.StdDifficulty; + + private long previousFrameTime; + + public GameScene(final Engine engine) { + this.engine = engine; + scene = new Scene(); + bgScene = new Scene(); + fgScene = new Scene(); + mgScene = new Scene(); + scene.attachChild(bgScene); + scene.attachChild(mgScene); + scene.attachChild(fgScene); + } + + public void setScoringScene(final ScoringScene sc) { + scoringScene = sc; + } + + public void setOldScene(final Scene oscene) { + oldScene = oscene; + } + + private void setBackground() { + boolean bgset = false; + bgSprite = null; + if (storyboardSprite != null) { + if (storyboardSprite.isStoryboardAvailable()) { + storyboardSprite.setBrightness(Config.getBackgroundBrightness()); + return; + } + } + for (final String s : beatmapData.getData("Events")) { + final String[] pars = s.split("\\s*,\\s*"); + if (pars.length >= 3 && pars[0].equals("0") && pars[1].equals("0")) { + // String filename = pars[2].substring(1, pars[2].length() - 1); + + if (Config.getBackgroundQuality() == 0) { + scene.setBackground(new ColorBackground(0, 0, 0)); + continue; + } + + bgset = true; + final TextureRegion tex = Config.isSafeBeatmapBg() ? + ResourceManager.getInstance().getTexture("menu-background") : + ResourceManager.getInstance().getTextureIfLoaded("::background"); + if (tex == null) { + continue; + } + float brightness = Config.getBackgroundBrightness(); + float height = tex.getHeight() * Config.getBackgroundQuality(); + height *= Config.getRES_WIDTH() + / (float) (tex.getWidth() * Config + .getBackgroundQuality()); + bgSprite = new Sprite(0, + (Config.getRES_HEIGHT() - height) / 2, + Config.getRES_WIDTH(), height, tex); + bgSprite.setColor(brightness, brightness, brightness); + scene.setBackground(new SpriteBackground(bgSprite)); + } else if (pars.length >= 3 && pars[0].equals("2")) { + + } else if (bgset == false && pars.length == 5 + && pars[0].equals("3") && pars[1].equals("100")) { + bgset = true; + final float bright = Config.getBackgroundBrightness(); + scene.setBackground(new ColorBackground( + Integer.parseInt(pars[2]) * bright / 255f, + Integer.parseInt(pars[3]) * bright / 255f, + Integer.parseInt(pars[4]) * bright / 255f)); + } + } + } + + private boolean loadGame(final TrackInfo track, final String rFile) { + InGameSettingMenu.getInstance().dismiss(); + if (rFile != null && rFile.startsWith("https://")) { + this.replayFile = Config.getCachePath() + "/" + + MD5Calcuator.getStringMD5(rFile) + ".odr"; + Debug.i("ReplayFile = " + replayFile); + if (!OnlineFileOperator.downloadFile(rFile, this.replayFile)) { + ToastLogger.showTextId(R.string.replay_cantdownload, true); + return false; + } + } else + this.replayFile = rFile; + + OSUParser parser = new OSUParser(track.getFilename()); + if (parser.openFile()) { + beatmapData = parser.readData(); + } else { + Debug.e("startGame: cannot open file"); + ToastLogger.showText( + StringTable.format(R.string.message_error_open, + track.getFilename()), true); + return false; + } + parser = null; + +// try { +// float height = 720; +// height *= 1. * Config.getRES_WIDTH() / 1280; +// mVideo = new VideoSprite(0, 0, Config.getRES_WIDTH(), Config.getRES_HEIGHT()); +// mVideo.setDataSource(Environment.getExternalStorageDirectory().getPath() + "/PV.mp4"); +// mVideo.setAlpha(0f); +// // mVideo.play(); +// } catch (IOException e) { +// Log.i("Load avi", e.getMessage()); +// } + + // TODO skin manager + SkinManager.getInstance().loadBeatmapSkin(beatmapData.getFolder()); + + if (beatmapData.getData("General", "Mode").equals("0") == false) { + if (beatmapData.getData("General", "Mode").equals("") == false) { + ToastLogger.showText(StringTable.format( + R.string.message_error_mapmode, + beatmapData.getData("General", "Mode")), true); + return false; + } + } + + breakPeriods = new LinkedList(); + for (final String s : beatmapData.getData("Events")) { + final String[] pars = s.split("\\s*,\\s*"); + if ((pars.length >= 3) && pars[0].equals("0") && pars[1].equals("0")) { + + } else if (pars.length >= 3 && pars[0].equals("2")) { + breakPeriods.add(new BreakPeriod( + Float.parseFloat(pars[1]) / 1000f, Float + .parseFloat(pars[2]) / 1000f)); + } + } + + totalOffset = Config.getOffset(); + String beatmapName = track.getFilename(); + beatmapName = beatmapName.substring(0, beatmapName.lastIndexOf('/')); + final BeatmapProperties props = PropertiesLibrary.getInstance() + .getProperties(beatmapName); + if (props != null) { + totalOffset += props.getOffset(); + } + + try { + final File musicFile = new File(beatmapData.getFolder(), + beatmapData.getData("General", "AudioFilename")); + + if (musicFile.exists() == false) { + throw new FileNotFoundException(musicFile.getPath()); + } + + /* + if (musicFile.getName().endsWith(".ogg")) { + totalOffset += Config.getOggOffset(); + } */ + + //music = new BassAudioPlayer(musicFile.getPath()); + filePath = musicFile.getPath(); + + } catch (final Exception e) { + Debug.e("Load Music: " + e.getMessage()); + ToastLogger.showText(e.getMessage(), true); + return false; + } + + title = beatmapData.getData("Metadata", "Title"); + artist = beatmapData.getData("Metadata", "Artist"); + version = beatmapData.getData("Metadata", "Version"); + + // r = 54.42 - 4.48 * cs + // Reading beatmap settings + + //TextureRegion appcircleTex = ResourceManager.getInstance().getTexture("approachcircle"); + + scale = (float) ((Config.getRES_HEIGHT() / 480.0f) + * (54.42 - Float.parseFloat(beatmapData.getData("Difficulty", "CircleSize")) * 4.48) + * 2 / GameObjectSize.BASE_OBJECT_SIZE) + + 0.5f * Config.getScaleMultiplier(); + +/* scale = (10 - Float.parseFloat(beatmapData.getData("Difficulty", + "CircleSize"))) + * 0.125f + + 0.625f + + 0.125f + * Config.getScaleMultiplier();*/ + + String rawRate = beatmapData.getData("Difficulty", "ApproachRate"); + if (rawRate.equals("")) { + rawRate = beatmapData.getData("Difficulty", "OverallDifficulty"); + } + float rawApproachRate = Float.parseFloat(rawRate); + approachRate = (float) GameHelper.ar2ms(rawApproachRate) / 1000f; + final String rawSliderSpeed = beatmapData.getData("Difficulty", + "SliderMultiplier"); + + overallDifficulty = Float.parseFloat(beatmapData.getData("Difficulty", + "OverallDifficulty")); + drain = Float.parseFloat(beatmapData.getData("Difficulty", + "HPDrainRate")); + rawDifficulty = overallDifficulty; + rawDrain = drain; + + if (ModMenu.getInstance().getMod().contains(GameMod.MOD_EASY)) { + scale += 0.125f; + drain *= 0.5f; + overallDifficulty *= 0.5f; + approachRate = (float) GameHelper.ar2ms(rawApproachRate / 2f) / 1000f; + } + + GameHelper.setHardrock(false); + if (ModMenu.getInstance().getMod().contains(GameMod.MOD_HARDROCK)) { + scale -= 0.125f; + drain = Math.min(1.4f * drain, 10f); + overallDifficulty = Math.min(1.4f * overallDifficulty, 10f); + approachRate = (float) GameHelper.ar2ms(Math.min(1.4f * rawApproachRate, 10f)) / 1000f; + GameHelper.setHardrock(true); + } + + timeMultiplier = 1f; + GameHelper.setDoubleTime(false); + GameHelper.setNightCore(false); + GameHelper.setHalfTime(false); + GameHelper.setSpeedUp(false); + + GlobalManager.getInstance().getSongService().preLoad(filePath, PlayMode.MODE_NONE); + GameHelper.setTimeMultiplier(1f); + //Speed Change + if (ModMenu.getInstance().getChangeSpeed() != 1.00f){ + timeMultiplier = ModMenu.getInstance().getSpeed(); + GlobalManager.getInstance().getSongService().preLoad(filePath, timeMultiplier, ModMenu.getInstance().isEnableNCWhenSpeedChange()); + GameHelper.setTimeMultiplier(1 / timeMultiplier); + } else if (ModMenu.getInstance().getMod().contains(GameMod.MOD_DOUBLETIME)) { + GlobalManager.getInstance().getSongService().preLoad(filePath, PlayMode.MODE_DT); + /*music.setUseSoftDecoder(1); + music.setDecoderMultiplier(150);*/ + timeMultiplier = 1.5f; + GameHelper.setDoubleTime(true); + GameHelper.setTimeMultiplier(2 / 3f); + } else if (ModMenu.getInstance().getMod().contains(GameMod.MOD_NIGHTCORE)) { + GlobalManager.getInstance().getSongService().preLoad(filePath, PlayMode.MODE_NC); + /*music.setUseSoftDecoder(2); + music.setDecoderMultiplier(150);*/ + timeMultiplier = 1.5f; + GameHelper.setNightCore(true); + GameHelper.setTimeMultiplier(2 / 3f); + } else if (ModMenu.getInstance().getMod().contains(GameMod.MOD_HALFTIME)) { + GlobalManager.getInstance().getSongService().preLoad(filePath, PlayMode.MODE_HT); + /*music.setUseSoftDecoder(1); + music.setDecoderMultiplier(75);*/ + timeMultiplier = 0.75f; + GameHelper.setHalfTime(true); + GameHelper.setTimeMultiplier(4 / 3f); + } + + /* + if (ModMenu.getInstance().getMod().contains(GameMod.MOD_DOUBLETIME) || ModMenu.getInstance().getMod().contains(GameMod.MOD_NIGHTCORE)) { +// approachRate = approachRate * 2 / 3; +// overallDifficulty = (float) GameHelper.ms2od(GameHelper.od2ms(overallDifficulty) * 2 / 3); + GameHelper.setTimeMultiplier(2 / 3f); + } else if (ModMenu.getInstance().getMod().contains(GameMod.MOD_HALFTIME)) { +// approachRate = approachRate * 4 / 3; +// overallDifficulty = (float) GameHelper.ms2od(GameHelper.od2ms(overallDifficulty) * 4 / 3); + GameHelper.setTimeMultiplier(4 / 3f); + } else if (ModMenu.getInstance().getMod().contains(GameMod.MOD_SPEEDUP)) { + GameHelper.setTimeMultiplier(4 / 5f); + } else { + GameHelper.setTimeMultiplier(1f); + } + */ + + if (ModMenu.getInstance().getMod().contains(GameMod.MOD_REALLYEASY)) { + scale += 0.125f; + drain *= 0.5f; + overallDifficulty *= 0.5f; + float ar = (float)GameHelper.ms2ar(approachRate * 1000f); + if (ModMenu.getInstance().getMod().contains(GameMod.MOD_EASY)) { + ar *= 2; + ar -= 0.5f; + } + ar -= (timeMultiplier - 1.0f) + 0.5f; + approachRate = (float)(GameHelper.ar2ms(ar) / 1000f); + } + + if (ModMenu.getInstance().getMod().contains(GameMod.MOD_SMALLCIRCLE)) { + scale -= (float) ((Config.getRES_HEIGHT() / 480.0f) * (4 * 4.48) + * 2 / GameObjectSize.BASE_OBJECT_SIZE); + } + //Force AR + if (ModMenu.getInstance().isEnableForceAR()){ + approachRate = (float) GameHelper.ar2ms(ModMenu.getInstance().getForceAR()) / 1000f * timeMultiplier; + } + + GameHelper.setRelaxMod(ModMenu.getInstance().getMod().contains(GameMod.MOD_RELAX)); + GameHelper.setAutopilotMod(ModMenu.getInstance().getMod().contains(GameMod.MOD_AUTOPILOT)); + GameHelper.setAuto(ModMenu.getInstance().getMod().contains(GameMod.MOD_AUTO)); + + final String stackLatiency = beatmapData.getData("General", + "StackLeniency"); + if (stackLatiency.equals("") == false) { + GameHelper.setStackLatient(Float.parseFloat(stackLatiency)); + } else { + GameHelper.setStackLatient(0); + } + if (scale < 0.001f){ + scale = 0.001f; + } + GameHelper.setSpeed(Float.parseFloat(rawSliderSpeed) * 100); + GameHelper.setTickRate(Float.parseFloat(beatmapData.getData( + "Difficulty", "SliderTickRate"))); + GameHelper.setScale(scale); + GameHelper.setDifficulty(overallDifficulty); + GameHelper.setDrain(drain); + GameHelper.setApproachRate(approachRate); + + // Parsing hit objects + objects = new LinkedList(); + for (final String s : beatmapData.getData("HitObjects")) { + objects.add(new GameObjectData(s)); + } + + if (objects.size() <= 0) { + ToastLogger.showText("Empty Beatmap", true); + return false; + } + + activeObjects = new LinkedList(); + passiveObjects = new LinkedList(); + lastObjectId = -1; + + GameHelper.setSliderColor(SkinManager.getInstance().getSliderColor()); + final String slidercolor = beatmapData.getData("Colours", + "SliderBorder"); + if (slidercolor.equals("") == false) { + final String[] sliderColors = slidercolor.split("[,]"); + GameHelper.setSliderColor(new RGBColor(Integer + .parseInt(sliderColors[0]) / 255.0f, Integer + .parseInt(sliderColors[1]) / 255.0f, Integer + .parseInt(sliderColors[2]) / 255.0f)); + } + + if (SkinJson.get().isForceOverrideSliderBorderColor()) { + GameHelper.setSliderColor(new RGBColor(SkinJson.get().getSliderBorderColor())); + } + + combos = new ArrayList(); + comboNum = 2; + String ccolor = beatmapData.getData("Colours", "Combo1"); + while (ccolor.equals("") == false) { + final String[] colors = ccolor.replace(" ", "").split("[,]"); + combos.add(new RGBColor(Integer.parseInt(colors[0]) / 255.0f, + Integer.parseInt(colors[1]) / 255.0f, Integer + .parseInt(colors[2]) / 255.0f)); + + ccolor = beatmapData.getData("Colours", "Combo" + comboNum++); + } + if (combos.isEmpty() || Config.isUseCustomComboColors()) { +// combos.add(new RGBColor(255 / 255.0f, 150 / 255.0f, 0 / 255.0f)); +// combos.add(new RGBColor(5 / 255.0f, 240 / 255.0f, 5 / 255.0f)); +// combos.add(new RGBColor(5 / 255.0f, 2 / 255.0f, 240 / 255.0f)); +// combos.add(new RGBColor(240 / 255.0f, 5 / 255.0f, 5 / 255.0f)); + combos.clear(); + combos.addAll(Arrays.asList(Config.getComboColors())); + } + if (SkinJson.get().isForceOverrideComboColor()) { + combos.clear(); + combos.addAll(SkinJson.get().getComboColor()); + } + comboNum = -1; + // if (combos.size() > 1) comboNum = 1; + currentComboNum = 0; + lastObjectHitTime = 0; + final String defSound = beatmapData.getData("General", "SampleSet"); + if (defSound.equals("Soft")) { + TimingPoint.setDefaultSound("soft"); + } else { + TimingPoint.setDefaultSound("normal"); + } + timingPoints = new LinkedList(); + activeTimingPoints = new LinkedList(); + currentTimingPoint = null; + for (final String s : beatmapData.getData("TimingPoints")) { + final TimingPoint tp = new TimingPoint(s.split("[,]"), + currentTimingPoint); + timingPoints.add(tp); + if (tp.wasInderited() == false || currentTimingPoint == null) { + currentTimingPoint = tp; + } + } + GameHelper.controlPoints = new ControlPoints(); + GameHelper.controlPoints.load(TimingPoints.parse(beatmapData.getData("TimingPoints"))); + currentTimingPoint = timingPoints.peek(); + firstTimingPoint = currentTimingPoint; + soundTimingPoint = currentTimingPoint; + if (soundTimingPoint != null) { + GameHelper.setTimingOffset(soundTimingPoint.getTime()); + GameHelper.setBeatLength(soundTimingPoint.getBeatLength() * GameHelper.getSpeed() / 100f); + GameHelper.setTimeSignature(soundTimingPoint.getSignature()); + GameHelper.setKiai(soundTimingPoint.isKiai()); + } else { + GameHelper.setTimingOffset(0); + GameHelper.setBeatLength(1); + GameHelper.setTimeSignature(4); + GameHelper.setKiai(false); + } + GameHelper.setInitalBeatLength(GameHelper.getBeatLength()); + + GameObjectPool.getInstance().purge(); + SpritePool.getInstance().purge(); + ModifierFactory.clear(); + + // TODO replay + avgOffset = 0; + offsetRegs = 0; + + File trackFile = new File(track.getFilename()); + trackMD5 = FileUtils.getMD5Checksum(trackFile); + replaying = false; + replay = new Replay(); + replay.setObjectCount(objects.size()); + replay.setMap(trackFile.getParentFile().getName(), trackFile.getName(), trackMD5); + + if (replayFile != null) { + replaying = replay.load(replayFile); + if (!replaying) { + ToastLogger.showTextId(R.string.replay_invalid, true); + return false; + } else + replay.countMarks(overallDifficulty); + //} else if (!OnlineManager.getInstance().isStayOnline()) { + // replay = null; + } else if (ModMenu.getInstance().getMod().contains(GameMod.MOD_AUTO)) { + replay = null; + } + /* + else if (ModMenu.getInstance().getMod().contains(GameMod.MOD_AUTO) || + ModMenu.getInstance().getMod().contains(GameMod.MOD_RELAX) || + ModMenu.getInstance().getMod().contains(GameMod.MOD_AUTOPILOT)) { + replay = null; + } + */ + //TODO fix replays ^^ + // replay = null; + + //TODO online + if (!replaying) + OnlineScoring.getInstance().startPlay(track, trackMD5); + + if (Config.isEnableStoryboard()) { + storyboardSprite.loadStoryboard(track.getFilename()); + } + + + System.gc(); + + GameObjectPool.getInstance().preload(); + + /* try { + music.prepare(); + + } catch (final Exception e) { + }*/ + + lastTrack = track; + if (Config.isCalculateSliderPathInGameStart()){ + stackNotes(); + calculateAllSliderPaths(); + } + paused = false; + gameStarted = false; + + return true; + } + + public Scene getScene() { + return scene; + } + + public void restartGame() { + if (!replaying) { + EdExtensionHelper.onRestartGame(lastTrack); + } + startGame(null, null); + } + + public void startGame(final TrackInfo track, final String replayFile) { + GameHelper.updateGameid(); + if (!replaying) { + EdExtensionHelper.onStartGame(track); + } + + scene = new Scene(); + if (Config.isEnableStoryboard()) { + if (storyboardSprite == null) { + storyboardSprite = new StoryboardSprite(Config.getRES_WIDTH(), Config.getRES_HEIGHT()); + storyboardOverlayProxy = new ProxySprite(Config.getRES_WIDTH(), Config.getRES_HEIGHT()); + storyboardSprite.setOverlayDrawProxy(storyboardOverlayProxy); + scene.attachChild(storyboardSprite); + } + storyboardSprite.detachSelf(); + scene.attachChild(storyboardSprite); + } + bgScene = new Scene(); + mgScene = new Scene(); + fgScene = new Scene(); + scene.attachChild(bgScene); + scene.attachChild(mgScene); + if (storyboardOverlayProxy != null) { + storyboardOverlayProxy.detachSelf(); + scene.attachChild(storyboardOverlayProxy); + } + scene.attachChild(fgScene); + scene.setBackground(new ColorBackground(0, 0, 0)); + bgScene.setBackgroundEnabled(false); + mgScene.setBackgroundEnabled(false); + fgScene.setBackgroundEnabled(false); + isFirst = true; + failcount = 0; + mainCursorId = -1; + final LoadingScreen screen = new LoadingScreen(); + engine.setScene(screen.getScene()); + + final String rfile = track != null ? replayFile : this.replayFile; + + new AsyncTaskLoader().execute(new OsuAsyncCallback() { + + public void run() { + loadComplete = loadGame(track != null ? track : lastTrack, rfile); + } + + public void onComplete() { + if (loadComplete == true) { + prepareScene(); + } else { + ModMenu.getInstance().setMod(Replay.oldMod); + ModMenu.getInstance().setChangeSpeed(Replay.oldChangeSpeed); + ModMenu.getInstance().setForceAR(Replay.oldForceAR); + ModMenu.getInstance().setEnableForceAR(Replay.oldEnableForceAR); + ModMenu.getInstance().setFLfollowDelay(Replay.oldFLFollowDelay); + quit(); + } + } + }); + ResourceManager.getInstance().getSound("failsound").stop(); + } + + private void prepareScene() { + scene.setOnSceneTouchListener(this); + // bgScene.attachChild(mVideo); + if (GlobalManager.getInstance().getCamera() instanceof SmoothCamera) { + SmoothCamera camera = (SmoothCamera) (GlobalManager.getInstance().getCamera()); + camera.setZoomFactorDirect(Config.getPlayfieldSize()); + if (Config.isShrinkPlayfieldDownwards()) { + camera.setCenterDirect(Config.getRES_WIDTH() / 2, Config.getRES_HEIGHT() / 2 * Config.getPlayfieldSize()); + } + } + setBackground(); + + if (Config.isShowFPS()) { + final Font font = ResourceManager.getInstance().getFont( + "smallFont"); + final ChangeableText fpsText = new ChangeableText(Utils.toRes(790), + Utils.toRes(520), font, "00.00 FPS"); + final ChangeableText accText = new ChangeableText(Utils.toRes(720), + Utils.toRes(480), font, "Avg offset: 0ms "); + fpsText.setPosition(Config.getRES_WIDTH() - fpsText.getWidth() - 5, Config.getRES_HEIGHT() - fpsText.getHeight() - 10); + accText.setPosition(Config.getRES_WIDTH() - accText.getWidth() - 5, fpsText.getY() - accText.getHeight()); + fgScene.attachChild(fpsText); + fgScene.attachChild(accText); + + ChangeableText memText = null; + if (BuildConfig.DEBUG) { + memText = new ChangeableText(Utils.toRes(780), + Utils.toRes(520), font, "M: 100/100"); + fgScene.attachChild(memText); + } + + final ChangeableText fmemText = memText; + fgScene.registerUpdateHandler(new FPSCounter() { + int elapsedInt = 0; + + @Override + public void onUpdate(final float pSecondsElapsed) { + super.onUpdate(pSecondsElapsed); + elapsedInt++; + fpsText.setText(Math.round(this.getFPS()) + " FPS"); + if (offsetRegs != 0 && elapsedInt > 200) { + accText.setText("Avg offset: " + + (int) (avgOffset * 1000f / offsetRegs) + + "ms"); + elapsedInt = 0; + } + fpsText.setPosition(Config.getRES_WIDTH() - fpsText.getWidth() - 5, Config.getRES_HEIGHT() - fpsText.getHeight() - 10); + accText.setPosition(Config.getRES_WIDTH() - accText.getWidth() - 5, fpsText.getY() - accText.getHeight()); + + if (fmemText != null) { + fmemText.setText("M: " + + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / 1024 / 1024 + + "/" + Runtime.getRuntime().totalMemory() / 1024 / 1024); + fmemText.setPosition(Config.getRES_WIDTH() - fmemText.getWidth() - 5, accText.getY() - fmemText.getHeight()); + } + + } + }); + } + + stat = new StatisticV2(); + stat.setMod(ModMenu.getInstance().getMod()); + float multiplier = 1 + rawDifficulty / 10f + rawDrain / 10f; + multiplier += (Float.parseFloat(beatmapData.getData("Difficulty", + "CircleSize")) - 3) / 4f; + + stat.setDiffModifier(multiplier); + stat.setMaxObjectsCount(lastTrack.getTotalHitObjectCount()); + stat.setMaxHighestCombo(lastTrack.getMaxCombo()); + stat.setEnableForceAR(ModMenu.getInstance().isEnableForceAR()); + stat.setForceAR(ModMenu.getInstance().getForceAR()); + stat.setChangeSpeed(ModMenu.getInstance().getChangeSpeed()); + stat.setFLFollowDelay(ModMenu.getInstance().getFLfollowDelay()); + + GameHelper.setHardrock(stat.getMod().contains(GameMod.MOD_HARDROCK)); + GameHelper.setDoubleTime(stat.getMod().contains(GameMod.MOD_DOUBLETIME)); + GameHelper.setNightCore(stat.getMod().contains(GameMod.MOD_NIGHTCORE)); + GameHelper.setSpeedUp(stat.getMod().contains(GameMod.MOD_SPEEDUP)); + GameHelper.setHalfTime(stat.getMod().contains(GameMod.MOD_HALFTIME)); + GameHelper.setHidden(stat.getMod().contains(GameMod.MOD_HIDDEN)); + GameHelper.setFlashLight(stat.getMod().contains(GameMod.MOD_FLASHLIGHT)); + GameHelper.setRelaxMod(stat.getMod().contains(GameMod.MOD_RELAX)); + GameHelper.setAutopilotMod(stat.getMod().contains(GameMod.MOD_AUTOPILOT)); + GameHelper.setSuddenDeath(stat.getMod().contains(GameMod.MOD_SUDDENDEATH)); + GameHelper.setPerfect(stat.getMod().contains(GameMod.MOD_PERFECT)); + difficultyHelper = stat.getMod().contains(GameMod.MOD_PRECISE) ? + DifficultyHelper.HighDifficulty : DifficultyHelper.StdDifficulty; + GameHelper.setDifficultyHelper(difficultyHelper); + + for (int i = 0; i < CursorCount; i++) { + cursors[i] = new Cursor(); + cursors[i].mouseDown = false; + cursors[i].mousePressed = false; + cursors[i].mouseOldDown = false; + } + + for (int i = 0; i < CursorCount; i++) { + cursorIIsDown[i] = false; + } + + comboWas100 = false; + comboWasMissed = false; + + final String leadin = beatmapData.getData("General", "AudioLeadIn"); + secPassed = -Integer.parseInt(leadin.equals("") ? "0" : leadin) / 1000f; + if (secPassed > -1) { + secPassed = -1; + } + + if (objects.isEmpty() == false) { + skipTime = objects.peek().getTime() - approachRate - 1f; + } else { + skipTime = 0; + } + + metronome = null; + if ((Config.getMetronomeSwitch() == 1 && GameHelper.isNightCore()) + || Config.getMetronomeSwitch() == 2) { + metronome = new Metronome(); + } + + secPassed -= Config.getOffset() / 1000f; + if (secPassed > 0) { + skipTime -= secPassed; + secPassed = 0; + } + distToNextObject = 0; + + // TODO passive objects + if ((replaying || Config.isShowCursor()) && !GameHelper.isAuto() && !GameHelper.isAutopilotMod()) { + cursorSprites = new CursorEntity[CursorCount]; + for (int i = 0; i < CursorCount; i++) { + cursorSprites[i] = new CursorEntity(); + cursorSprites[i].attachToScene(fgScene); + } + } else { + cursorSprites = null; + } + + if (GameHelper.isAuto() || GameHelper.isAutopilotMod()) { + autoCursor = new AutoCursor(); + autoCursor.attachToScene(fgScene); + } + + final String countdownPar = beatmapData.getData("General", "Countdown"); + if (Config.isCorovans() && countdownPar.equals("") == false) { + float cdSpeed = 0; + if (countdownPar.equals("1")) { + cdSpeed = 1; + } else if (countdownPar.equals("2")) { + cdSpeed = 2; + } else if (countdownPar.equals("3")) { + cdSpeed = 0.5f; + } + skipTime -= cdSpeed * Countdown.COUNTDOWN_LENGTH; + if (cdSpeed != 0 + && objects.peek().getTime() - secPassed >= cdSpeed + * Countdown.COUNTDOWN_LENGTH) { + addPassiveObject(new Countdown(this, bgScene, cdSpeed, 0, + objects.peek().getTime() - secPassed)); + } + } + + float lastObjectTme = 0; + if (objects.isEmpty() == false) + lastObjectTme = objects.getLast().getTime(); + + if(!Config.isHideInGameUI()) { + progressBar = new SongProgressBar(this, bgScene, lastObjectTme, objects + .getFirst().getTime(), new PointF(0, Config.getRES_HEIGHT() - 7), Config.getRES_WIDTH(), 7); + progressBar.setProgressRectColor(new RGBAColor(153f / 255f, 204f / 255f, 51f / 255f, 0.4f)); + } + + if (Config.getErrorMeter() == 1 + || (Config.getErrorMeter() == 2 && replaying)) { + hitErrorMeter = new HitErrorMeter( + bgScene, + new PointF(Config.getRES_WIDTH() / 2, Config.getRES_HEIGHT() - 20), + overallDifficulty, + 12, + difficultyHelper); + } + + skipBtn = null; + if (skipTime > 1) { + final TextureRegion tex; + if (ResourceManager.getInstance().isTextureLoaded("play-skip-0")) { + List loadedSkipTextures = new ArrayList<>(); + for (int i = 0; i < 60; i++) { + if (ResourceManager.getInstance().isTextureLoaded("play-skip-" + i)) + loadedSkipTextures.add("play-skip-" + i); + } + tex = ResourceManager.getInstance().getTexture("play-skip-0"); + skipBtn = new AnimSprite(Config.getRES_WIDTH() - tex.getWidth(), + Config.getRES_HEIGHT() - tex.getHeight(), loadedSkipTextures.size(), + loadedSkipTextures.toArray(new String[loadedSkipTextures.size()])); + } else { + tex = ResourceManager.getInstance().getTexture("play-skip"); + skipBtn = new Sprite(Config.getRES_WIDTH() - tex.getWidth(), + Config.getRES_HEIGHT() - tex.getHeight(), tex); + } + skipBtn.setAlpha(0.7f); + fgScene.attachChild(skipBtn); + /*if (SkinManager.getFrames("play-skip") <= 1) { + tex = ResourceManager.getInstance().getTexture("play-skip"); + skipBtn = new Sprite(Config.getRES_WIDTH() - tex.getWidth(), + Config.getRES_HEIGHT() - tex.getHeight(), tex); + fgScene.attachChild(skipBtn); + } else { + if (SkinManager.getFrames("play-skip") == 1) { + final int frames = SkinManager.getFrames("play-skip"); + tex = ResourceManager.getInstance().getTexture( + "play-skip-0"); + skipBtn = new AnimSprite(Config.getRES_WIDTH() + - tex.getWidth(), Config.getRES_HEIGHT() + - tex.getHeight(), "play-skip-", frames, frames); + fgScene.attachChild(skipBtn); + } + }*/ + } + GameHelper.setGlobalTime(0); + + float effectOffset = 155 - 25; + breakAnimator = new BreakAnimator(this, fgScene, stat, beatmapData + .getData("General", "LetterboxInBreaks").equals("1"), bgSprite); + if(!Config.isHideInGameUI()){ + scorebar = new ScoreBar(this, fgScene, stat); + addPassiveObject(scorebar); + final TextureRegion scoreDigitTex = ResourceManager.getInstance() + .getTexture("score-0"); + accText = new GameScoreText(Config.getRES_WIDTH() + - scoreDigitTex.getWidth() * 4.75f, 50, + "000.00%", 0.6f); + comboText = new GameScoreText(Utils.toRes(2), Config.getRES_HEIGHT() + - Utils.toRes(95), "0000x", 1.5f); + comboText.changeText(new StringBuilder("0****")); + scoreText = new GameScoreText(Config.getRES_WIDTH() + - scoreDigitTex.getWidth() * 7.25f, 0, "0000000000", 0.9f); + comboText.attachToScene(fgScene); + accText.attachToScene(fgScene); + scoreText.attachToScene(fgScene); + if (Config.isComplexAnimations()) { + scoreShadow = new GameScoreTextShadow(0, Config.getRES_HEIGHT() + - Utils.toRes(90), "0000x", 1.5f); + scoreShadow.attachToScene(bgScene); + passiveObjects.add(scoreShadow); + } + if (stat.getMod().contains(GameMod.MOD_AUTO)) { + final Sprite autoIcon = new Sprite(Utils.toRes(Config.getRES_WIDTH() - 140), + Utils.toRes(100), ResourceManager.getInstance().getTexture( + "selection-mod-autoplay")); + bgScene.attachChild(autoIcon); + effectOffset += 25; + } else if (stat.getMod().contains(GameMod.MOD_RELAX)) { + final Sprite autoIcon = new Sprite(Utils.toRes(Config.getRES_WIDTH() - 140), + Utils.toRes(98), ResourceManager.getInstance().getTexture( + "selection-mod-relax")); + bgScene.attachChild(autoIcon); + effectOffset += 25; + } else if (stat.getMod().contains(GameMod.MOD_AUTOPILOT)) { + final Sprite autoIcon = new Sprite(Utils.toRes(Config.getRES_WIDTH() - 140), + Utils.toRes(98), ResourceManager.getInstance().getTexture( + "selection-mod-relax2")); + bgScene.attachChild(autoIcon); + effectOffset += 25; + } + + if (Config.isComboburst()) { + comboBurst = new ComboBurst(Config.getRES_WIDTH(), Config.getRES_HEIGHT()); + comboBurst.attachAll(bgScene); + } + } + + float timeOffset = 0; + if (stat.getMod().contains(GameMod.MOD_SCOREV2)) { + final GameEffect effect = GameObjectPool.getInstance().getEffect( + "selection-mod-scorev2"); + effect.init( + fgScene, + new PointF(Utils.toRes(Config.getRES_WIDTH() - effectOffset), Utils + .toRes(130)), + scale, + new SequenceEntityModifier(ModifierFactory + .newScaleModifier(0.25f, 1.2f, 1), ModifierFactory + .newDelayModifier(2), new ParallelEntityModifier( + ModifierFactory.newFadeOutModifier(0.5f), + ModifierFactory.newScaleModifier(0.5f, 1, 1.5f)))); + effectOffset += 25; + timeOffset += 0.25f; + } + if (stat.getMod().contains(GameMod.MOD_EASY)) { + final GameEffect effect = GameObjectPool.getInstance().getEffect( + "selection-mod-easy"); + effect.init( + fgScene, + new PointF(Utils.toRes(Config.getRES_WIDTH() - effectOffset), Utils + .toRes(130)), + scale, + new SequenceEntityModifier(ModifierFactory + .newScaleModifier(0.25f, 1.2f, 1), ModifierFactory + .newDelayModifier(2), new ParallelEntityModifier( + ModifierFactory.newFadeOutModifier(0.5f), + ModifierFactory.newScaleModifier(0.5f, 1, 1.5f)))); + effectOffset += 25; + timeOffset += 0.25f; + } else if (stat.getMod().contains(GameMod.MOD_HARDROCK)) { + final GameEffect effect = GameObjectPool.getInstance().getEffect( + "selection-mod-hardrock"); + effect.init( + fgScene, + new PointF(Utils.toRes(Config.getRES_WIDTH() - effectOffset), Utils + .toRes(130)), + scale, + new SequenceEntityModifier(ModifierFactory + .newScaleModifier(0.25f, 1.2f, 1), ModifierFactory + .newDelayModifier(2), new ParallelEntityModifier( + ModifierFactory.newFadeOutModifier(0.5f), + ModifierFactory.newScaleModifier(0.5f, 1, 1.5f)))); + effectOffset += 25; + timeOffset += 0.25f; + } + if (stat.getMod().contains(GameMod.MOD_NOFAIL)) { + final GameEffect effect = GameObjectPool.getInstance().getEffect( + "selection-mod-nofail"); + effect.init( + fgScene, + new PointF(Utils.toRes(Config.getRES_WIDTH() - effectOffset), Utils + .toRes(130)), + scale, + new SequenceEntityModifier(ModifierFactory + .newScaleModifier(0.25f, 1.2f, 1), ModifierFactory + .newDelayModifier(2 - timeOffset), + new ParallelEntityModifier(ModifierFactory + .newFadeOutModifier(0.5f), ModifierFactory + .newScaleModifier(0.5f, 1, 1.5f)))); + effectOffset += 25; + timeOffset += 0.25f; + } + if (stat.getMod().contains(GameMod.MOD_HIDDEN)) { + final GameEffect effect = GameObjectPool.getInstance().getEffect( + "selection-mod-hidden"); + effect.init( + fgScene, + new PointF(Utils.toRes(Config.getRES_WIDTH() - effectOffset), Utils + .toRes(130)), + scale, + new SequenceEntityModifier(ModifierFactory + .newScaleModifier(0.25f, 1.2f, 1), ModifierFactory + .newDelayModifier(2 - timeOffset), + new ParallelEntityModifier(ModifierFactory + .newFadeOutModifier(0.5f), ModifierFactory + .newScaleModifier(0.5f, 1, 1.5f)))); + effectOffset += 25; + timeOffset += 0.25f; + } + + if (stat.getMod().contains(GameMod.MOD_DOUBLETIME)) { + final GameEffect effect = GameObjectPool.getInstance().getEffect( + "selection-mod-doubletime"); + effect.init( + fgScene, + new PointF(Utils.toRes(Config.getRES_WIDTH() - effectOffset), Utils + .toRes(130)), + scale, + new SequenceEntityModifier(ModifierFactory + .newScaleModifier(0.25f, 1.2f, 1), ModifierFactory + .newDelayModifier(2 - timeOffset), + new ParallelEntityModifier(ModifierFactory + .newFadeOutModifier(0.5f), ModifierFactory + .newScaleModifier(0.5f, 1, 1.5f)))); + effectOffset += 25; + timeOffset += 0.25f; + } + if (stat.getMod().contains(GameMod.MOD_NIGHTCORE)) { + final GameEffect effect = GameObjectPool.getInstance().getEffect( + "selection-mod-nightcore"); + effect.init( + fgScene, + new PointF(Utils.toRes(Config.getRES_WIDTH() - effectOffset), Utils + .toRes(130)), + scale, + new SequenceEntityModifier(ModifierFactory + .newScaleModifier(0.25f, 1.2f, 1), ModifierFactory + .newDelayModifier(2 - timeOffset), + new ParallelEntityModifier(ModifierFactory + .newFadeOutModifier(0.5f), ModifierFactory + .newScaleModifier(0.5f, 1, 1.5f)))); + effectOffset += 25; + timeOffset += 0.25f; + } + if (stat.getMod().contains(GameMod.MOD_HALFTIME)) { + final GameEffect effect = GameObjectPool.getInstance().getEffect( + "selection-mod-halftime"); + effect.init( + fgScene, + new PointF(Utils.toRes(Config.getRES_WIDTH() - effectOffset), Utils + .toRes(130)), + scale, + new SequenceEntityModifier(ModifierFactory + .newScaleModifier(0.25f, 1.2f, 1), ModifierFactory + .newDelayModifier(2 - timeOffset), + new ParallelEntityModifier(ModifierFactory + .newFadeOutModifier(0.5f), ModifierFactory + .newScaleModifier(0.5f, 1, 1.5f)))); + effectOffset += 25; + timeOffset += 0.25f; + } + if (stat.getMod().contains(GameMod.MOD_PRECISE)) { + final GameEffect effect = GameObjectPool.getInstance().getEffect( + "selection-mod-precise"); + effect.init( + fgScene, + new PointF(Utils.toRes(Config.getRES_WIDTH() - effectOffset), Utils + .toRes(130)), + scale, + new SequenceEntityModifier(ModifierFactory + .newScaleModifier(0.25f, 1.2f, 1), ModifierFactory + .newDelayModifier(2 - timeOffset), + new ParallelEntityModifier(ModifierFactory + .newFadeOutModifier(0.5f), ModifierFactory + .newScaleModifier(0.5f, 1, 1.5f)))); + effectOffset += 25; + timeOffset += 0.25f; + } + if (stat.getMod().contains(GameMod.MOD_SUDDENDEATH)) { + final GameEffect effect = GameObjectPool.getInstance().getEffect( + "selection-mod-suddendeath"); + effect.init( + fgScene, + new PointF(Utils.toRes(Config.getRES_WIDTH() - effectOffset), Utils + .toRes(130)), + scale, + new SequenceEntityModifier(ModifierFactory + .newScaleModifier(0.25f, 1.2f, 1), ModifierFactory + .newDelayModifier(2 - timeOffset), + new ParallelEntityModifier(ModifierFactory + .newFadeOutModifier(0.5f), ModifierFactory + .newScaleModifier(0.5f, 1, 1.5f)))); + effectOffset += 25; + timeOffset += 0.25f; + } + else if (stat.getMod().contains(GameMod.MOD_PERFECT)) { + final GameEffect effect = GameObjectPool.getInstance().getEffect( + "selection-mod-perfect"); + effect.init( + fgScene, + new PointF(Utils.toRes(Config.getRES_WIDTH() - effectOffset), Utils + .toRes(130)), + scale, + new SequenceEntityModifier(ModifierFactory + .newScaleModifier(0.25f, 1.2f, 1), ModifierFactory + .newDelayModifier(2 - timeOffset), + new ParallelEntityModifier(ModifierFactory + .newFadeOutModifier(0.5f), ModifierFactory + .newScaleModifier(0.5f, 1, 1.5f)))); + effectOffset += 25; + timeOffset += 0.25f; + } + if (stat.getMod().contains(GameMod.MOD_FLASHLIGHT)) { + final GameEffect effect = GameObjectPool.getInstance().getEffect( + "selection-mod-flashlight"); + effect.init( + fgScene, + new PointF(Utils.toRes(Config.getRES_WIDTH() - effectOffset), Utils + .toRes(130)), + scale, + new SequenceEntityModifier(ModifierFactory + .newScaleModifier(0.25f, 1.2f, 1), ModifierFactory + .newDelayModifier(2 - timeOffset), + new ParallelEntityModifier(ModifierFactory + .newFadeOutModifier(0.5f), ModifierFactory + .newScaleModifier(0.5f, 1, 1.5f)))); + effectOffset += 25; + timeOffset += 0.25f; + } + if (stat.getMod().contains(GameMod.MOD_SMALLCIRCLE)) { + final GameEffect effect = GameObjectPool.getInstance().getEffect( + "selection-mod-smallcircle"); + effect.init( + fgScene, + new PointF(Utils.toRes(Config.getRES_WIDTH() - effectOffset), Utils + .toRes(130)), + scale, + new SequenceEntityModifier(ModifierFactory + .newScaleModifier(0.25f, 1.2f, 1), ModifierFactory + .newDelayModifier(2 - timeOffset), + new ParallelEntityModifier(ModifierFactory + .newFadeOutModifier(0.5f), ModifierFactory + .newScaleModifier(0.5f, 1, 1.5f)))); + effectOffset += 25; + timeOffset += 0.25f; + } + if (stat.getMod().contains(GameMod.MOD_REALLYEASY)) { + final GameEffect effect = GameObjectPool.getInstance().getEffect( + "selection-mod-reallyeasy"); + effect.init( + fgScene, + new PointF(Utils.toRes(Config.getRES_WIDTH() - effectOffset), Utils + .toRes(130)), + scale, + new SequenceEntityModifier(ModifierFactory + .newScaleModifier(0.25f, 1.2f, 1), ModifierFactory + .newDelayModifier(2 - timeOffset), + new ParallelEntityModifier(ModifierFactory + .newFadeOutModifier(0.5f), ModifierFactory + .newScaleModifier(0.5f, 1, 1.5f)))); + effectOffset += 25; + timeOffset += 0.25f; + } + + kiai = false; + kiaiRect = new Rectangle(0, 0, Config.getRES_WIDTH(), + Config.getRES_HEIGHT()); + kiaiRect.setVisible(false); + kiaiRect.setColor(1, 1, 1); + bgScene.attachChild(kiaiRect, 0); + + unranked = new Sprite(0, 0, ResourceManager.getInstance().getTexture("play-unranked")); + unranked.setPosition(Config.getRES_WIDTH() / 2 - unranked.getWidth() / 2, 80); + unranked.setVisible(false); + fgScene.attachChild(unranked); + + boolean hasUnrankedMod = SmartIterator.wrap(stat.getMod().iterator()) + .applyFilter(m -> m.unranked).hasNext(); + if (hasUnrankedMod + || Config.isRemoveSliderLock() + || ModMenu.getInstance().isChangeSpeed() + || ModMenu.getInstance().isEnableForceAR()) { + unranked.setVisible(true); + } + + String playname = null; + replayText = new ChangeableText(0, 0, ResourceManager.getInstance().getFont("font"), "", 1000); + replayText.setVisible(false); + replayText.setPosition(0, 140); + replayText.setAlpha(0.7f); + fgScene.attachChild(replayText, 0); + if (stat.getMod().contains(GameMod.MOD_AUTO) || replaying) { + playname = replaying ? GlobalManager.getInstance().getScoring().getReplayStat().getPlayerName() : "osu!"; + replayText.setText("Watching " + playname + " play " + artist + " - " + title + " [" + version + "]"); + replayText.registerEntityModifier(new LoopEntityModifier(new MoveXModifier(40, + Config.getRES_WIDTH() + 5, -replayText.getWidth() - 5))); + replayText.setVisible(!Config.isHideReplayMarquee()); + } + if (Config.isShowScoreboard()) { + scoreBoard = new DuringGameScoreBoard(fgScene, stat, playname); + addPassiveObject(scoreBoard); + } + + if (GameHelper.isFlashLight()){ + flashlightSprite = new FlashLightEntity(); + fgScene.attachChild(flashlightSprite, 0); + } + +/* PointF point1 = Utils.trackToRealCoords(new PointF(0, 0)); + PointF point2 = Utils.trackToRealCoords(new PointF(0, Constants.MAP_HEIGHT)); + PointF point3 = Utils.trackToRealCoords(new PointF(Constants.MAP_WIDTH, Constants.MAP_HEIGHT)); + PointF point4 = Utils.trackToRealCoords(new PointF(Constants.MAP_WIDTH, 0)); + + Line line1 = new Line(point1.x, point1.y, point2.x, point2.y); + line1.setColor(255 / 255f, 0, 0); + bgScene.attachChild(line1); + + Line line2 = new Line(point2.x, point2.y, point3.x, point3.y); + line2.setColor(255 / 255f, 0, 0); + bgScene.attachChild(line2); + + Line line3 = new Line(point3.x, point3.y, point4.x, point4.y); + line3.setColor(255 / 255f, 0, 0); + bgScene.attachChild(line3); + + Line line4 = new Line(point4.x, point4.y, point1.x, point1.y); + line4.setColor(255 / 255f, 0, 0); + bgScene.attachChild(line4);*/ + + leadOut = 0; + musicStarted = false; + engine.setScene(scene); + scene.registerUpdateHandler(this); + } + + + + + public RGBColor getComboColor(int num) { + return combos.get(num % combos.size()); + } + + // TODO update + + public void onUpdate(final float pSecondsElapsed) { + previousFrameTime = SystemClock.uptimeMillis(); + Utils.clearSoundMask(); + float dt = pSecondsElapsed * timeMultiplier; + if (GlobalManager.getInstance().getSongService().getStatus() == Status.PLAYING) { + //处理时间差过于庞大的情况 + final float offset = totalOffset / 1000f; + final float realsecPassed = //Config.isSyncMusic() ? + GlobalManager.getInstance().getSongService().getPosition() / 1000.0f;// : realTime; + final float criticalError = Config.isSyncMusic() ? 0.1f : 0.5f; + final float normalError = Config.isSyncMusic() ? dt : 0.05f; + + if (secPassed + offset - realsecPassed > criticalError) { + return; + } + + if (Math.abs(secPassed + offset - realsecPassed) > normalError) { + if (secPassed + offset > realsecPassed) { + dt /= 2f; + } else { + dt *= 2f; + } + } + secPassed += dt; + } + float gtime; + if (soundTimingPoint == null || soundTimingPoint.getTime() > secPassed) { + gtime = 0; + } else { + gtime = (secPassed - firstTimingPoint.getTime()) + % (GameHelper.getKiaiTickLength()); + } + GameHelper.setGlobalTime(gtime); + + if (Config.isEnableStoryboard()) { + if (storyboardSprite != null) { + storyboardSprite.updateTime(secPassed * 1000); + } + } + + if (replaying) { + int cIndex; + for (int i = 0; i < replay.cursorIndex.length; i++) { + if (replay.cursorMoves.size() <= i){ + break; + } + cIndex = replay.cursorIndex[i]; + //Emulating moves + while (cIndex < replay.cursorMoves.get(i).size && + replay.cursorMoves.get(i).time[cIndex] <= (secPassed + dt / 4) * 1000) { + final Replay.MoveArray move = replay.cursorMoves.get(i); + + if (move.id[cIndex] == Replay.ID_DOWN) { + cursors[i].mouseDown = true; + for (int j = 0; j < replay.cursorIndex.length; j++) + cursors[j].mouseOldDown = false; + cursors[i].mousePos.x = move.x[cIndex]; + cursors[i].mousePos.y = move.y[cIndex]; + replay.lastMoveIndex[i] = -1; + } else if (move.id[cIndex] == Replay.ID_MOVE) { + cursors[i].mousePos.x = move.x[cIndex]; + cursors[i].mousePos.y = move.y[cIndex]; + replay.lastMoveIndex[i] = cIndex; + } else { + cursors[i].mouseDown = false; + } + + replay.cursorIndex[i]++; + cIndex++; + } + //Interpolating cursor movements + if (cIndex < replay.cursorMoves.get(i).size && + replay.cursorMoves.get(i).id[cIndex] == Replay.ID_MOVE && + replay.lastMoveIndex[i] >= 0) { + final Replay.MoveArray move = replay.cursorMoves.get(i); + final int lIndex = replay.lastMoveIndex[i]; + float t = (secPassed * 1000 - move.time[cIndex]) / (move.time[lIndex] - move.time[cIndex]); + cursors[i].mousePos.x = move.x[lIndex] * t + move.x[cIndex] * (1 - t); + cursors[i].mousePos.y = move.y[lIndex] * t + move.y[cIndex] * (1 - t); + } + } + } + + if (GameHelper.isAuto() || GameHelper.isAutopilotMod()) { + autoCursor.update(dt); + } else if (cursorSprites != null) { + for (int i = 0; i < CursorCount; i++) { + cursorSprites[i].setPosition(cursors[i].mousePos.x, cursors[i].mousePos.y); + cursorSprites[i].update(dt); + if (cursors[i].mouseDown) { + cursorSprites[i].setShowing(true); + if (cursors[i].mousePressed) { + cursorSprites[i].click(); + } + } else { + cursorSprites[i].setShowing(false); + } + } + } + + for (final Cursor c : cursors) { + if (c.mouseDown == true && c.mouseOldDown == false) { + c.mousePressed = true; + c.mouseOldDown = true; + } else { + c.mousePressed = false; + } + } + if(GameHelper.isFlashLight()){ + if (!GameHelper.isAuto() && !GameHelper.isAutopilotMod()) { + if (mainCursorId < 0){ + int i = 0; + for (final Cursor c : cursors) { + if (c.mousePressed == true && isFirstObjectsNear(c.mousePos)) { + mainCursorId = i; + flashlightSprite.onMouseMove(c.mousePos.x, c.mousePos.y); + break; + } + ++i; + } + } else if(cursors[mainCursorId].mouseDown == false){ + mainCursorId = -1; + } else if(cursors[mainCursorId].mouseDown == true){ + flashlightSprite.onMouseMove( + cursors[mainCursorId].mousePos.x, cursors[mainCursorId].mousePos.y + ); + } + } + flashlightSprite.onUpdate(stat.getCombo()); + } + + while (timingPoints.isEmpty() == false + && timingPoints.peek().getTime() <= secPassed + approachRate) { + currentTimingPoint = timingPoints.poll(); + activeTimingPoints.add(currentTimingPoint); + } + while (activeTimingPoints.isEmpty() == false + && activeTimingPoints.peek().getTime() <= secPassed) { + soundTimingPoint = activeTimingPoints.poll(); + if (!soundTimingPoint.inherited) { + GameHelper.setBeatLength(soundTimingPoint.getBeatLength()); + GameHelper.setTimingOffset(soundTimingPoint.getTime()); + } + GameHelper.setTimeSignature(soundTimingPoint.getSignature()); + GameHelper.setKiai(soundTimingPoint.isKiai()); + } + + if (!breakPeriods.isEmpty()) { + if (!breakAnimator.isBreak() + && breakPeriods.peek().getStart() <= secPassed) { + gameStarted = false; + breakAnimator.init(breakPeriods.peek().getLength()); + if(GameHelper.isFlashLight()){ + flashlightSprite.onBreak(true); + } + if(scorebar != null) scorebar.setVisible(false); + breakPeriods.poll(); + } + } + if (breakAnimator.isOver()) { + gameStarted = true; + if(scorebar != null) scorebar.setVisible(true); + if(GameHelper.isFlashLight()){ + flashlightSprite.onBreak(false); + } + } + + if (objects.isEmpty() && activeObjects.isEmpty()) { + if (GameHelper.isFlashLight()) { + flashlightSprite.onBreak(true); + } + } + + if (gameStarted) { + float rate = 0.375f; + if (drain > 0 && distToNextObject > 0) { + rate = 1 + drain / (2f * distToNextObject); + } + stat.changeHp(-rate * 0.01f * dt); + if (stat.getHp() <= 0 + && stat.getMod().contains(GameMod.MOD_NOFAIL) == false + && stat.getMod().contains(GameMod.MOD_RELAX) == false + && stat.getMod().contains(GameMod.MOD_AUTOPILOT) == false + && stat.getMod().contains(GameMod.MOD_AUTO) == false) { + if (stat.getMod().contains(GameMod.MOD_EASY) && failcount < 3) { + failcount++; + stat.changeHp(1f); + } + else { + gameover(); + } + return; + } + } + + if (hitErrorMeter != null) { + hitErrorMeter.update(dt); + } + + if(!Config.isHideInGameUI()) { + //连击数//////////////////////// + final StringBuilder comboBuilder = new StringBuilder(); + comboBuilder.setLength(0); + comboBuilder.append(stat.getCombo()); + while (comboBuilder.length() < 5) { + comboBuilder.append('*'); + } + if (Config.isComplexAnimations()) { + scoreShadow.changeText(comboBuilder); + scoreShadow.registerEntityModifier(new DelayModifier(0.2f, new IEntityModifier.IEntityModifierListener() { + @Override + public void onModifierStarted(IModifier iModifier, IEntity iEntity) { + } + @Override + public void onModifierFinished(IModifier iModifier, IEntity iEntity) { + //当CB数字阴影缩小完成的时候 更改CB数字 + comboText.changeText(comboBuilder); + } + })); + } else { + comboText.changeText(comboBuilder); + } + + //连击数//////////////////////// + strBuilder.setLength(0); + float rawAccuracy = stat.getAccuracy() * 100f; + strBuilder.append((int) rawAccuracy); + if ((int) rawAccuracy < 10) { + strBuilder.insert(0, '0'); + } + strBuilder.append('.'); + rawAccuracy -= (int) rawAccuracy; + rawAccuracy *= 100; + if ((int) rawAccuracy < 10) { + strBuilder.append('0'); + } + strBuilder.append((int) rawAccuracy); + if (strBuilder.length() < 6) { + strBuilder.insert(0, '*'); + } + accText.changeText(strBuilder); + strBuilder.setLength(0); + strBuilder.append(stat.getAutoTotalScore()); + while (strBuilder.length() < 8) { + strBuilder.insert(0, '0'); + } + int scoreTextOffset = 0; + while (strBuilder.length() < 10) { + strBuilder.insert(0, '*'); + scoreTextOffset++; + } + + scoreText.setPosition(Config.getRES_WIDTH() + - ResourceManager.getInstance().getTexture("score-0").getWidth() * (9.25f - scoreTextOffset), 0); + scoreText.changeText(strBuilder); + } + + if (comboBurst != null) { + if (stat.getCombo() == 0) { + comboBurst.breakCombo(); + } else { + comboBurst.checkAndShow(stat.getCombo()); + } + } + + for (final GameObject obj : passiveObjects) { + obj.update(dt); + } + + if (Config.isRemoveSliderLock()){ + GameObject lastObject = getLastTobeclickObject(); + if (lastObject != null) { + lastObjectHitTime = getLastTobeclickObject().getHitTime(); + } + } + + for (final GameObject obj : activeObjects) { + obj.update(dt); + } + + if (GameHelper.isAuto() || GameHelper.isAutopilotMod()) { + autoCursor.moveToObject(activeObjects.peek(), secPassed, this); + } + + int clickCount = 0; + for (final boolean c : cursorIIsDown){ + if (c == true) clickCount++; + } + for (int i = 0; i < CursorCount; i++) { + cursorIIsDown[i] = false; + } + + for (int i = 0; i < clickCount - 1; i++){ + if (Config.isRemoveSliderLock()){ + GameObject lastObject = getLastTobeclickObject(); + if (lastObject != null) { + lastObjectHitTime = getLastTobeclickObject().getHitTime(); + } + } + for (final GameObject obj : activeObjects) { + obj.tryHit(dt); + } + } + + if (secPassed >= 0 && musicStarted == false) { + GlobalManager.getInstance().getSongService().play(); + GlobalManager.getInstance().getSongService().setVolume(Config.getBgmVolume()); + totalLength = GlobalManager.getInstance().getSongService().getLength(); + musicStarted = true; + secPassed = 0; + return; + } +// if (secPassed >= 0) { +// if (!mVideo.getIsPlaying()) { +// mVideo.play(); +// } +// if (mVideo.getAlpha() < 1.0f) { +// float alpha = mVideo.getAlpha(); +// mVideo.setAlpha(Math.min(alpha + 0.03f, 1.0f)); +// } +// } + + boolean shouldBePunished = false; + + while (objects.isEmpty() == false + && secPassed + approachRate > objects.peek().getTime()) { + gameStarted = true; + final GameObjectData data = objects.poll(); + final String[] params = data.getData(); + + final PointF pos = data.getPos(); + // Fix matching error on new beatmaps + final int objDefine = Integer.parseInt(params[3]); + + final float time = data.getRawTime(); + if (time > totalLength) { + shouldBePunished = true; + } + + // Stack notes + // If Config.isCalculateSliderPathInGameStart(), do this in stackNotes() + if (Config.isCalculateSliderPathInGameStart() == false && + objects.isEmpty() == false && (objDefine & 1) > 0) { + if (objects.peek().getTime() - data.getTime() < 2f * GameHelper.getStackLatient() + && Utils.squaredDistance(pos, objects.peek().getPos()) < scale) { + objects.peek().setPosOffset( + data.getPosOffset() + Utils.toRes(4) * scale); + } + } + // If this object is silder and isCalculateSliderPathInGameStart(), the pos is += in calculateAllSliderPaths() + if (Config.isCalculateSliderPathInGameStart() == false || (objDefine & 2) <= 0){ + pos.x += data.getPosOffset(); + pos.y += data.getPosOffset(); + } + if (objects.isEmpty() == false) { + distToNextObject = objects.peek().getTime() - data.getTime(); + if (soundTimingPoint != null + && distToNextObject < soundTimingPoint.getBeatLength() / 2) { + distToNextObject = soundTimingPoint.getBeatLength() / 2; + } + } else { + distToNextObject = 0; + } + // Calculate combo color + int comboCode = objDefine; + if (comboCode == 12) { + currentComboNum = 0; + } else if (comboNum == -1) { + comboNum = 1; + currentComboNum = 0; + } else if ((comboCode & 4) > 0) { + currentComboNum = 0; + if (comboCode / 15 > 0) { + comboCode /= 15; + for (int i = 0; true; i++) { + if (comboCode >> i == 1) { + comboNum = i; + break; + } + } + } else { + comboNum = (comboNum + 1) % combos.size(); + } + } + + if ((objDefine & 1) > 0) { + final RGBColor col = getComboColor(comboNum); + final HitCircle circle = GameObjectPool.getInstance().getCircle(); + String tempSound = null; + if (params.length > 5) { + tempSound = params[5]; + } + + circle.init(this, mgScene, pos, data.getTime() - secPassed, + col.r(), col.g(), col.b(), scale, currentComboNum, + Integer.parseInt(params[4]), tempSound, isFirst); + circle.setEndsCombo(objects.isEmpty() + || objects.peek().isNewCombo()); + addObject(circle); + isFirst = false; + if (objects.isEmpty() == false + && objects.peek().isNewCombo() == false) { + final FollowTrack track = GameObjectPool.getInstance() + .getTrack(); + PointF end; + if (objects.peek().getTime() > data.getTime()) { + end = data.getEnd(); + } else { + end = data.getPos(); + } + track.init(this, bgScene, end, objects.peek().getPos(), + objects.peek().getTime() - secPassed, approachRate, + scale); + } + if (stat.getMod().contains(GameMod.MOD_AUTO)) { + circle.setAutoPlay(); + } + circle.setHitTime(data.getTime()); + + if (objects.isEmpty() == false) { + if (objects.peek().getTime() > data.getTime()) { + currentComboNum++; + } + } + + circle.setId(++lastObjectId); + if (replaying) { + circle.setReplayData(replay.objectData[circle.getId()]); + } + + } else if ((objDefine & 8) > 0) { + final float endTime = Integer.parseInt(params[5]) / 1000.0f; + final float rps = 2 + 2 * overallDifficulty / 10f; + final Spinner spinner = GameObjectPool.getInstance().getSpinner(); + String tempSound = null; + if (params.length > 6) { + tempSound = params[6]; + } + spinner.init(this, bgScene, (data.getTime() - secPassed) / timeMultiplier, + (endTime - data.getTime()) / timeMultiplier, rps, Integer.parseInt(params[4]), + tempSound, stat); + spinner.setEndsCombo(objects.isEmpty() + || objects.peek().isNewCombo()); + addObject(spinner); + isFirst = false; + + if (stat.getMod().contains(GameMod.MOD_AUTO) || + stat.getMod().contains(GameMod.MOD_AUTOPILOT)) { + spinner.setAutoPlay(); + } + + spinner.setId(++lastObjectId); + if (replaying) { + spinner.setReplayData(replay.objectData[spinner.getId()]); + } + + } else if ((objDefine & 2) > 0) { + final RGBColor col = getComboColor(comboNum); + final String soundspec = params.length > 8 ? params[8] : null; + final Slider slider = GameObjectPool.getInstance().getSlider(); + String tempSound = null; + if (params.length > 9) { + tempSound = params[9]; + } + if (Config.isCalculateSliderPathInGameStart()){ + SliderPath sliderPath = getSliderPath(sliderIndex); + slider.init(this, mgScene, pos, data.getPosOffset(), data.getTime() - secPassed, + col.r(), col.g(), col.b(), scale, currentComboNum, + Integer.parseInt(params[4]), + Integer.parseInt(params[6]), + Float.parseFloat(params[7]), params[5], + currentTimingPoint, soundspec, tempSound, isFirst, Double.parseDouble(params[2]), + sliderPath); + sliderIndex++; + } + else{ + slider.init(this, mgScene, pos, data.getPosOffset(), data.getTime() - secPassed, + col.r(), col.g(), col.b(), scale, currentComboNum, + Integer.parseInt(params[4]), + Integer.parseInt(params[6]), + Float.parseFloat(params[7]), params[5], + currentTimingPoint, soundspec, tempSound, isFirst, Double.parseDouble(params[2])); + } + slider.setEndsCombo(objects.isEmpty() + || objects.peek().isNewCombo()); + addObject(slider); + isFirst = false; + + if (objects.isEmpty() == false + && objects.peek().isNewCombo() == false) { + final FollowTrack track = GameObjectPool.getInstance() + .getTrack(); + PointF end; + if (objects.peek().getTime() > data.getTime()) { + end = data.getEnd(); + } else { + end = data.getPos(); + } + track.init(this, bgScene, end, objects.peek().getPos(), + objects.peek().getTime() - secPassed, approachRate, + scale); + } + if (stat.getMod().contains(GameMod.MOD_AUTO)) { + slider.setAutoPlay(); + } + slider.setHitTime(data.getTime()); + + + if (objects.isEmpty() == false) { + if (objects.peek().getTime() > data.getTime()) { + currentComboNum++; + } + } + + slider.setId(++lastObjectId); + if (replaying) { + slider.setReplayData(replay.objectData[slider.getId()]); + if (slider.getReplayData().tickSet == null) + slider.getReplayData().tickSet = new BitSet(); + } + } + } + + // 节拍器 + if (metronome != null) { + metronome.update(secPassed); + } + + //Status playerStatus = music.getStatus(); + Status playerStatus = GlobalManager.getInstance().getSongService().getStatus(); + + if (playerStatus != Status.PLAYING) { + secPassed += dt; + } + + if (shouldBePunished || (objects.isEmpty() && activeObjects.isEmpty() && leadOut > 2)) { + scene = new Scene(); + SkinManager.setSkinEnabled(false); + GameObjectPool.getInstance().purge(); + SpritePool.getInstance().purge(); + passiveObjects.clear(); + breakPeriods.clear(); + cursorSprites = null; + String replayFile = null; + stat.setTime(System.currentTimeMillis()); + if (replay != null && replaying == false) { + String ctime = String.valueOf(System.currentTimeMillis()); + replayFile = Config.getCorePath() + "Scores/" + + MD5Calcuator.getStringMD5(lastTrack.getFilename() + ctime) + + ctime.substring(0, Math.min(3, ctime.length())) + ".odr"; + replay.setStat(stat); + replay.save(replayFile); + } + if (GlobalManager.getInstance().getCamera() instanceof SmoothCamera) { + SmoothCamera camera = (SmoothCamera) (GlobalManager.getInstance().getCamera()); + camera.setZoomFactorDirect(1f); + if (Config.isShrinkPlayfieldDownwards()) { + camera.setCenterDirect(Config.getRES_WIDTH() / 2, Config.getRES_HEIGHT() / 2); + } + } + if (scoringScene != null) { + if (replaying) { + ModMenu.getInstance().setMod(Replay.oldMod); + ModMenu.getInstance().setChangeSpeed(Replay.oldChangeSpeed); + ModMenu.getInstance().setForceAR(Replay.oldForceAR); + ModMenu.getInstance().setEnableForceAR(Replay.oldEnableForceAR); + ModMenu.getInstance().setFLfollowDelay(Replay.oldFLFollowDelay); + } + + if (replaying) + scoringScene.load(scoringScene.getReplayStat(), null, GlobalManager.getInstance().getSongService(), replayFile, null, lastTrack); + else { + if (stat.getMod().contains(GameMod.MOD_AUTO)) { + stat.setPlayerName("osu!"); + } + + EdExtensionHelper.onEndGame(lastTrack, stat); + if (storyboardSprite != null) { + storyboardSprite.releaseStoryboard(); + storyboardSprite = null; + storyboardOverlayProxy.setDrawProxy(null); + } + + scoringScene.load(stat, lastTrack, GlobalManager.getInstance().getSongService(), replayFile, trackMD5, null); + } + GlobalManager.getInstance().getSongService().setVolume(0.2f); + engine.setScene(scoringScene.getScene()); + } else { + engine.setScene(oldScene); + } + + } else if (objects.isEmpty() && activeObjects.isEmpty()) { + gameStarted = false; + leadOut += dt; + } + + // TODO skip button + if (secPassed > skipTime - 1f && skipBtn != null) { + skipBtn.detachSelf(); + skipBtn = null; + } else if (skipBtn != null) { + for (final Cursor c : cursors) { + if (c.mouseDown == true + && Utils.distance( + c.mousePos, + new PointF(Config.getRES_WIDTH(), Config + .getRES_HEIGHT())) < 250) { + + /*if (music.getStatus() != Status.PLAYING) { + music.play(); + music.setVolume(Config.getBgmVolume()); + totalLength = music.getLength(); + musicStarted = true; + }*/ + if (GlobalManager.getInstance().getSongService().getStatus() != Status.PLAYING) { + GlobalManager.getInstance().getSongService().play(); + GlobalManager.getInstance().getSongService().setVolume(Config.getBgmVolume()); + totalLength = GlobalManager.getInstance().getSongService().getLength(); + musicStarted = true; + } + ResourceManager.getInstance().getSound("menuhit").play(); + final float difference = skipTime - 0.5f - secPassed; + for (final GameObject obj : passiveObjects) { + obj.update(difference); + } + //music.seekTo((int) Math.ceil((skipTime - 0.5f) * 1000)); + GlobalManager.getInstance().getSongService().seekTo((int) Math.ceil((skipTime - 0.5f) * 1000)); + secPassed = skipTime - 0.5f; + skipBtn.detachSelf(); + skipBtn = null; + return; + } + } + } + +/* if (GameHelper.isKiai() && Config.isComplexAnimations() && Config.getBackgroundBrightness() != 0) { + final float kiaiModifier = Math + .max(0, + 1 - GameHelper.getGlobalTime() / + GameHelper.getKiaiTickLength()) * 0.15f; + final float a = Math.min(1, kiaiModifier); + if (kiai == false) { + kiaiRect.setVisible(true); + } + kiai = true; + kiaiRect.setAlpha(a); + } else if (kiai == true) { + kiaiRect.setVisible(false); + kiai = false; + }*/ + } // update(float dt) + + private void onExit() { + + //游戏退出 + + if (!replaying) { + EdExtensionHelper.onExitGame(lastTrack); + } + + SkinManager.setSkinEnabled(false); + GameObjectPool.getInstance().purge(); + SpritePool.getInstance().purge(); + passiveObjects.clear(); + breakPeriods.clear(); + cursorSprites = null; + + if (GlobalManager.getInstance().getSongService() != null) { + GlobalManager.getInstance().getSongService().stop(); + GlobalManager.getInstance().getSongService().preLoad(filePath); + GlobalManager.getInstance().getSongService().play(); + } + + /*try { + android.os.Debug.dumpHprofData(Environment.getExternalStorageDirectory().getPath()+"/dd.hprof"); + } catch (IOException e) { + e.printStackTrace(); + }*/ + if (replaying) { + replayFile = null; + ModMenu.getInstance().setMod(Replay.oldMod); + ModMenu.getInstance().setChangeSpeed(Replay.oldChangeSpeed); + ModMenu.getInstance().setForceAR(Replay.oldForceAR); + ModMenu.getInstance().setEnableForceAR(Replay.oldEnableForceAR); + } + } + + public void quit() { + + //游戏中退出,通过暂停菜单 + + if (!replaying) { + EdExtensionHelper.onQuitGame(lastTrack); + } + + if (storyboardSprite != null) { + storyboardSprite.releaseStoryboard(); + storyboardSprite = null; + storyboardOverlayProxy.setDrawProxy(null); + } + + onExit(); + ResourceManager.getInstance().getSound("failsound").stop(); + if (GlobalManager.getInstance().getCamera() instanceof SmoothCamera) { + SmoothCamera camera = (SmoothCamera) (GlobalManager.getInstance().getCamera()); + camera.setZoomFactorDirect(1f); + if (Config.isShrinkPlayfieldDownwards()) { + camera.setCenterDirect(Config.getRES_WIDTH() / 2, Config.getRES_HEIGHT() / 2); + } + } + scene = new Scene(); + engine.setScene(oldScene); + } + + + public void reset() { + } + + //CB打击处理 + private String registerHit(final int objectId, final int score, final boolean endCombo) { + boolean writeReplay = objectId != -1 && replay != null && !replaying; + if (score == 0) { + if (stat.getCombo() > 30) { + ResourceManager.getInstance().getCustomSound("combobreak", 1) + .play(); + } + comboWasMissed = true; + stat.registerHit(0, false, false); + if (writeReplay) replay.addObjectScore(objectId, Replay.RESULT_0); + if(GameHelper.isPerfect()){ + gameover(); + restartGame(); + } + if(GameHelper.isSuddenDeath())stat.changeHp(-1.0f); + return "hit0"; + } + + String scoreName = "hit300"; + if (score == 50) { + stat.registerHit(50, false, false); + if (writeReplay) replay.addObjectScore(objectId, Replay.RESULT_50); + scoreName = "hit50"; + comboWas100 = true; + if(GameHelper.isPerfect()){ + gameover(); + restartGame(); + } + } else if (score == 100) { + comboWas100 = true; + if (writeReplay) replay.addObjectScore(objectId, Replay.RESULT_100); + if (endCombo && comboWasMissed == false) { + stat.registerHit(100, true, false); + scoreName = "hit100k"; + } else { + stat.registerHit(100, false, false); + scoreName = "hit100"; + } + if(GameHelper.isPerfect()){ + gameover(); + restartGame(); + } + } else if (score == 300) { + if (writeReplay) replay.addObjectScore(objectId, Replay.RESULT_300); + if (endCombo && comboWasMissed == false) { + if (comboWas100 == false) { + stat.registerHit(300, true, true); + scoreName = "hit300g"; + } else { + stat.registerHit(300, true, false); + scoreName = "hit300k"; + } + } else { + stat.registerHit(300, false, false); + scoreName = "hit300"; + } + } + + if (endCombo) { + comboWas100 = false; + comboWasMissed = false; + } + + return scoreName; + } + + + public void onCircleHit(int id, final float acc, final PointF pos, + final boolean endCombo, byte forcedScore, RGBColor color) { + if (GameHelper.isAuto()) { + autoCursor.click(); + } + + float accuracy = Math.abs(acc); + boolean writeReplay = replay != null && !replaying; + if (writeReplay) { + short sacc = (short) (acc * 1000); + replay.addObjectResult(id, sacc, null); + } + if(GameHelper.isFlashLight() && !GameHelper.isAuto() && !GameHelper.isAutopilotMod()){ + int nearestCursorId = getNearestCursorId(pos.x, pos.y); + if (nearestCursorId >= 0) { + mainCursorId = nearestCursorId; + flashlightSprite.onMouseMove( + cursors[mainCursorId].mousePos.x, + cursors[mainCursorId].mousePos.y + ); + } + } + + //(30 - overallDifficulty) / 100f + if (accuracy > difficultyHelper.hitWindowFor50(overallDifficulty) || forcedScore == Replay.RESULT_0) { + createHitEffect(pos, "hit0", color); + registerHit(id, 0, endCombo); + return; + } + + String scoreName = "hit300"; + if (forcedScore == Replay.RESULT_300 || + forcedScore == 0 && accuracy <= difficultyHelper.hitWindowFor300(overallDifficulty)) { + //(75 + 25 * (5 - overallDifficulty) / 5) / 1000) + scoreName = registerHit(id, 300, endCombo); + } else if (forcedScore == Replay.RESULT_100 || + forcedScore == 0 && accuracy <= difficultyHelper.hitWindowFor100(overallDifficulty)) { + //(150 + 50 * (5 - overallDifficulty) / 5) / 1000) + scoreName = registerHit(id, 100, endCombo); + } else { + scoreName = registerHit(id, 50, endCombo); + } + + createBurstEffect(pos, color); + createHitEffect(pos, scoreName, color); + + + } + + public void onSliderReverse(PointF pos, float ang, RGBColor color) { + createBurstEffectSliderReverse(pos, ang, color); + } + + public void onSliderHit(int id, final int score, final PointF start, + final PointF end, final boolean endCombo, RGBColor color, int type) { + if (score == 0) { + createHitEffect(start, "hit0", color); + createHitEffect(end, "hit0", color); + registerHit(id, 0, endCombo); + return; + } + + if (score == -1) { + if (stat.getCombo() > 30) { + ResourceManager.getInstance().getCustomSound("combobreak", 1) + .play(); + } + if(GameHelper.isSuddenDeath()) stat.changeHp(-1.0f); + stat.registerHit(0, true, false); + return; + } + + String scoreName = "hit0"; + switch (score) { + case 300: + scoreName = registerHit(id, 300, endCombo); + break; + case 100: + scoreName = registerHit(id, 100, endCombo); + stat.setPerfect(false); + break; + case 50: + scoreName = registerHit(id, 50, endCombo); + stat.setPerfect(false); + break; + case 30: + scoreName = "sliderpoint30"; + stat.registerHit(30, false, false); + break; + case 10: + scoreName = "sliderpoint10"; + stat.registerHit(10, false, false); + break; + } + + if (score > 10) { + switch (type) { + case GameObjectListener.SLIDER_START: + createBurstEffectSliderStart(end, color); + break; + case GameObjectListener.SLIDER_END: + createBurstEffectSliderEnd(end, color); + break; + case GameObjectListener.SLIDER_REPEAT: + break; + default: + createBurstEffect(end, color); + } + } + createHitEffect(end, scoreName, color); + } + + + public void onSpinnerHit(int id, final int score, final boolean endCombo, int totalScore) { + if (score == 1000) { + stat.registerHit(score, false, false); + return; + } + + if (replay != null && !replaying) { + short acc = (short) (totalScore * 4); + switch (score) { + case 300: + acc += 3; + break; + case 100: + acc += 2; + break; + case 50: + acc += 1; + break; + } + replay.addObjectResult(id, acc, null); + } + + final PointF pos = new PointF(Config.getRES_WIDTH() / 2, + Config.getRES_HEIGHT() / 2); + if (score == 0) { + final GameEffect effect = GameObjectPool.getInstance().getEffect( + "hit0"); + effect.init( + scene, + pos, + scale, + new SequenceEntityModifier(ModifierFactory + .newFadeInModifier(0.15f), ModifierFactory + .newDelayModifier(0.35f), ModifierFactory + .newFadeOutModifier(0.25f))); + registerHit(id, 0, endCombo); + return; + } + + String scoreName = "hit0"; + switch (score) { + case 300: + scoreName = registerHit(id, 300, endCombo); + break; + case 100: + scoreName = registerHit(id, 100, endCombo); + break; + case 50: + scoreName = registerHit(id, 50, endCombo); + break; + } + + if (ResourceManager.getInstance().getTexture("lighting") != null) { + final GameEffect light = GameObjectPool.getInstance().getEffect( + "lighting"); + light.init( + mgScene, + pos, + scale, + new FadeOutModifier(0.7f), + new SequenceEntityModifier(ModifierFactory + .newScaleModifier(0.25f, scale, 1.5f * scale), + ModifierFactory.newScaleModifier(0.45f, + scale * 1.5f, 2f * scale))); + } + + GameEffect effect = GameObjectPool.getInstance().getEffect(scoreName); + effect.init( + mgScene, + pos, + scale, + new SequenceEntityModifier(ModifierFactory.newScaleModifier( + 0.15f, 1.0f * scale, 1.2f * scale), ModifierFactory + .newScaleModifier(0.05f, 1.2f * scale, 1.0f * scale), + ModifierFactory.newAlphaModifier(1f, 1, 0))); + + pos.y /= 2f; + effect = GameObjectPool.getInstance().getEffect("spinner-osu"); + effect.init(mgScene, pos, 1, ModifierFactory.newFadeOutModifier(1.5f)); + } + + public void playSound(final String name, final int sampleSet, final int addition) { + if (addition > 0 && !name.equals("hitnormal") && addition < Constants.SAMPLE_PREFIX.length) { + playSound(Constants.SAMPLE_PREFIX[addition], name); + return; + } + if (sampleSet > 0 && sampleSet < Constants.SAMPLE_PREFIX.length) { + playSound(Constants.SAMPLE_PREFIX[sampleSet], name); + } else { + playSound(soundTimingPoint.getHitSound(), name); + } + } + + public void playSound(final String prefix, final String name) { + final String fullName = prefix + "-" + name; + BassSoundProvider snd; + if (soundTimingPoint.getCustomSound() == 0) { + snd = ResourceManager.getInstance().getSound(fullName); + } else { + snd = ResourceManager.getInstance().getCustomSound(fullName, + soundTimingPoint.getCustomSound()); + } + if(snd == null) { + return; + } + if (name.equals("sliderslide") || name.equals("sliderwhistle")) { + snd.setLooping(true); + } + if (name.equals("hitnormal")) { + snd.play(soundTimingPoint.getVolume() * 0.8f); + return; + } + if (name.equals("hitwhistle") + || name.equals("hitclap")) { + snd.play(soundTimingPoint.getVolume() * 0.85f); + return; + } + snd.play(soundTimingPoint.getVolume()); + } + + + public void addObject(final GameObject object) { + activeObjects.add(object); + } + + + public PointF getMousePos(final int index) { + return cursors[index].mousePos; + } + + + public boolean isMouseDown(final int index) { + return cursors[index].mouseDown; + } + + + public boolean isMousePressed(final GameObject object, final int index) { + if (stat.getMod().contains(GameMod.MOD_AUTO)) { + return false; + } + if (Config.isRemoveSliderLock()){ + if(activeObjects.isEmpty() + || Math.abs(object.getHitTime() - lastObjectHitTime) > 0.001f) { + return false; + } + } + else if (activeObjects.isEmpty() + || Math.abs(object.getHitTime() + - activeObjects.peek().getHitTime()) > 0.001f) { + return false; + } + return cursors[index].mousePressed; + } + + private GameObject getLastTobeclickObject(){ + Iterator iterator = activeObjects.iterator(); + while(iterator.hasNext()){ + GameObject note = (GameObject)iterator.next(); + if(note.isStartHit() == false)return note; + } + return null; + } + + @Override + public double downFrameOffset(int index) { + return cursors[index].mouseDownOffsetMS; + } + + public void removeObject(final GameObject object) { + activeObjects.remove(object); + } + + public boolean onSceneTouchEvent(final Scene pScene, + final TouchEvent pSceneTouchEvent) { + if (pSceneTouchEvent.getPointerID() < 0 + || pSceneTouchEvent.getPointerID() >= CursorCount) { + Debug.e("Invalid pointerID: " + pSceneTouchEvent.getPointerID()); + return false; + } + if (replaying) { + return false; + } + final int i = pSceneTouchEvent.getPointerID(); + float pTouchX = FMath.clamp(pSceneTouchEvent.getX(), 0, Config.getRES_WIDTH()); + float pTouchY = FMath.clamp(pSceneTouchEvent.getY(), 0, Config.getRES_HEIGHT()); + if (pSceneTouchEvent.isActionDown()) { + cursors[i].mouseDown = true; + cursors[i].mouseDownOffsetMS = (pSceneTouchEvent.getMotionEvent().getEventTime() - previousFrameTime) * timeMultiplier; + for (int j = 0; j < cursors.length; j++) + cursors[j].mouseOldDown = false; + PointF gamePoint = Utils.realToTrackCoords(new PointF(pTouchX, pTouchY)); + cursors[i].mousePos.x = pTouchX; + cursors[i].mousePos.y = pTouchY; + if (replay != null) { + replay.addPress(secPassed, gamePoint, i); + } + cursorIIsDown[i] = true; + } else if (pSceneTouchEvent.isActionMove()) { + PointF gamePoint = Utils.realToTrackCoords(new PointF(pTouchX, pTouchY)); + cursors[i].mousePos.x = pTouchX; + cursors[i].mousePos.y = pTouchY; + if (replay != null) { + replay.addMove(secPassed, gamePoint, i); + } + } else if (pSceneTouchEvent.isActionUp()) { + cursors[i].mouseDown = false; + if (replay != null) { + replay.addUp(secPassed, i); + } + } else { + return false; + } + return true; + } + + + public void stopSound(final String name) { + final String prefix = soundTimingPoint.getHitSound() + "-"; + final BassSoundProvider snd = ResourceManager.getInstance().getSound(prefix + name); + if (snd != null) { + snd.stop(); + } + } + + public void pause() { + if (paused) { + return; + } + + if (!replaying) { + EdExtensionHelper.onPauseGame(lastTrack); + } + + // totalOffset += Config.getPauseOffset(); + final PauseMenu menu = new PauseMenu(engine, this, false); + /*if (music != null && music.getStatus() == Status.PLAYING) { + music.pause(); + }*/ + if (GlobalManager.getInstance().getSongService() != null && GlobalManager.getInstance().getSongService().getStatus() == Status.PLAYING) { + GlobalManager.getInstance().getSongService().pause(); + } + paused = true; + scene.setChildScene(menu.getScene(), false, true, true); + } + + public void gameover() { + + if (!replaying) { + EdExtensionHelper.onGameover(lastTrack); + } + + if(scorebar != null) scorebar.flush(); + ResourceManager.getInstance().getSound("failsound").play(); + final PauseMenu menu = new PauseMenu(engine, this, true); + gameStarted = false; + /*if (music != null && music.getStatus() == Status.PLAYING) { + music.pause(); + }*/ + if (GlobalManager.getInstance().getSongService() != null && GlobalManager.getInstance().getSongService().getStatus() == Status.PLAYING) { + GlobalManager.getInstance().getSongService().pause(); + } + paused = true; + scene.setChildScene(menu.getScene(), false, true, true); + } + + public void resume() { + if (!paused) { + return; + } + + scene.getChildScene().back(); + paused = false; + if (stat.getHp() <= 0 && stat.getMod().contains(GameMod.MOD_NOFAIL) == false + && stat.getMod().contains(GameMod.MOD_RELAX) == false + && stat.getMod().contains(GameMod.MOD_AUTOPILOT) == false) { + quit(); + return; + } + /*if (music != null && music.getStatus() != Status.PLAYING && secPassed > 0) { + music.play(); + music.setVolume(Config.getBgmVolume()); + totalLength = music.getLength(); + }*/ + + if (!replaying) { + EdExtensionHelper.onResume(lastTrack); + } + + if (GlobalManager.getInstance().getSongService() != null && GlobalManager.getInstance().getSongService().getStatus() != Status.PLAYING && secPassed > 0) { + GlobalManager.getInstance().getSongService().play(); + GlobalManager.getInstance().getSongService().setVolume(Config.getBgmVolume()); + totalLength = GlobalManager.getInstance().getSongService().getLength(); + } + } + + public boolean isPaused() { + return paused; + } + + + public void addPassiveObject(final GameObject object) { + passiveObjects.add(object); + } + + + public void removePassiveObject(final GameObject object) { + passiveObjects.remove(object); + } + + private void createHitEffect(final PointF pos, final String name, RGBColor color) { + final GameEffect effect = GameObjectPool.getInstance().getEffect(name); + if (name.equals("hit0")) { + if(GameHelper.isSuddenDeath()){ + effect.init( + mgScene, + pos, + scale * 3, + new SequenceEntityModifier(ModifierFactory + .newFadeInModifier(0.15f), ModifierFactory + .newDelayModifier(0.35f), ModifierFactory + .newFadeOutModifier(0.25f))); + return; + } + effect.init( + mgScene, + pos, + scale, + new SequenceEntityModifier(ModifierFactory + .newFadeInModifier(0.15f), ModifierFactory + .newDelayModifier(0.35f), ModifierFactory + .newFadeOutModifier(0.25f))); + return; + } + + if (Config.isComplexAnimations() + && name.equals("sliderpoint10") == false + && name.equals("sliderpoint30") == false + && ResourceManager.getInstance().getTexture("lighting") != null + && Config.isHitLighting()) { + final GameEffect light = GameObjectPool.getInstance().getEffect("lighting"); + light.setColor(color); + light.init( + bgScene, + pos, + scale, + ModifierFactory.newFadeOutModifier(1f), + new SequenceEntityModifier(ModifierFactory + .newScaleModifier(0.25f, scale, 1.5f * scale), + ModifierFactory.newScaleModifier(0.45f, + scale * 1.5f, 1.9f * scale), + ModifierFactory.newScaleModifier(0.3f, scale * 1.9f, scale * 2f) + )); + light.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_DST_ALPHA); + } + + effect.init( + mgScene, + pos, + scale, + new SequenceEntityModifier(ModifierFactory.newScaleModifier( + 0.15f, 1.0f * scale, 1.2f * scale), ModifierFactory + .newScaleModifier(0.05f, 1.2f * scale, 1.0f * scale), + ModifierFactory.newAlphaModifier(0.5f, 1, 0))); + } + + private void createBurstEffect(final PointF pos, final RGBColor color) { + if (!Config.isComplexAnimations() || !Config.isBurstEffects()) return; + final GameEffect burst1 = GameObjectPool.getInstance().getEffect("hitcircle"); + burst1.init(mgScene, pos, scale, + ModifierFactory.newScaleModifier(0.25f, scale, 1.5f * scale), + ModifierFactory.newAlphaModifier(0.25f, 0.8f, 0) + ); + burst1.setColor(color); + + final GameEffect burst2 = GameObjectPool.getInstance().getEffect("hitcircleoverlay"); + burst2.init(mgScene, pos, scale, + ModifierFactory.newScaleModifier(0.25f, scale, 1.5f * scale), + ModifierFactory.newAlphaModifier(0.25f, 0.8f, 0) + ); + + } + + private void createBurstEffectSliderStart(final PointF pos, final RGBColor color) { + if (!Config.isComplexAnimations() || !Config.isBurstEffects()) return; + final GameEffect burst1 = GameObjectPool.getInstance().getEffect("sliderstartcircle"); + burst1.init(mgScene, pos, scale, + ModifierFactory.newScaleModifier(0.25f, scale, 1.5f * scale), + ModifierFactory.newAlphaModifier(0.25f, 0.8f, 0) + ); + burst1.setColor(color); + + final GameEffect burst2 = GameObjectPool.getInstance().getEffect("sliderstartcircleoverlay"); + burst2.init(mgScene, pos, scale, + ModifierFactory.newScaleModifier(0.25f, scale, 1.5f * scale), + ModifierFactory.newAlphaModifier(0.25f, 0.8f, 0) + ); + + } + + private void createBurstEffectSliderEnd(final PointF pos, final RGBColor color) { + if (!Config.isComplexAnimations() || !Config.isBurstEffects()) return; + final GameEffect burst1 = GameObjectPool.getInstance().getEffect("sliderendcircle"); + burst1.init(mgScene, pos, scale, + ModifierFactory.newScaleModifier(0.25f, scale, 1.5f * scale), + ModifierFactory.newAlphaModifier(0.25f, 0.8f, 0) + ); + burst1.setColor(color); + + final GameEffect burst2 = GameObjectPool.getInstance().getEffect("sliderendcircleoverlay"); + burst2.init(mgScene, pos, scale, + ModifierFactory.newScaleModifier(0.25f, scale, 1.5f * scale), + ModifierFactory.newAlphaModifier(0.25f, 0.8f, 0) + ); + + } + + private void createBurstEffectSliderReverse(final PointF pos, float ang, final RGBColor color) { + if (!Config.isComplexAnimations() || !Config.isBurstEffects()) return; + final GameEffect burst1 = GameObjectPool.getInstance().getEffect("reversearrow"); + burst1.hit.setRotation(ang); + burst1.init(mgScene, pos, scale, + ModifierFactory.newScaleModifier(0.25f, scale, 1.5f * scale), + ModifierFactory.newAlphaModifier(0.25f, 0.8f, 0) + ); + + } + + public int getCursorsCount() { + return CursorCount; + } + + + public void registerAccuracy(final float acc) { + if (hitErrorMeter != null) { + hitErrorMeter.putErrorResult(acc); + } + avgOffset += acc; + offsetRegs++; + } + + + public void onSliderEnd(int id, int accuracy, BitSet tickSet) { + onTrackingSliders(false); + if (GameHelper.isAuto()) { + autoCursor.onSliderEnd(); + } + if (replay != null && !replaying) { + short acc = (short) (accuracy); + replay.addObjectResult(id, acc, (BitSet) tickSet.clone()); + } + } + + public void onTrackingSliders(boolean isTrackingSliders) { + if (GameHelper.isAuto()) { + autoCursor.onSliderTracking(); + } + if (GameHelper.isFlashLight()) { + flashlightSprite.onTrackingSliders(isTrackingSliders); + } + } + + public void onUpdatedAutoCursor(float pX, float pY) { + if (GameHelper.isFlashLight()) { + flashlightSprite.onMouseMove(pX, pY); + } + } + + public void updateAutoBasedPos(float pX, float pY) { + if (GameHelper.isAuto() || GameHelper.isAutopilotMod()) { + autoCursor.setPosition(pX, pY, this); + } + } + + private int getNearestCursorId(float pX, float pY){ + float distance = Float.POSITIVE_INFINITY, cursorDistance, dx, dy; + int id = -1, i = 0; + for (Cursor c : cursors) { + if(c.mouseDown == true || c.mousePressed == true || c.mouseOldDown == true){ + dx = c.mousePos.x - pX; + dy = c.mousePos.y - pY; + cursorDistance = dx * dx + dy * dy; + if(cursorDistance < distance){ + id = i; + distance = cursorDistance; + } + } + ++i; + } + return id; + } + + private boolean isFirstObjectsNear(PointF pos){ + if (activeObjects.isEmpty()) { + return true; + } + if (activeObjects.peek() instanceof Spinner || activeObjects.peek() instanceof Slider) { + return true; + } + else if (Utils.squaredDistance(pos, activeObjects.peek().getPos()) < 180f * 180f) { + return true; + } + return false; + } + + private void stackNotes(){ + // Stack notes + int i = 0; + for (GameObjectData data : objects){ + final PointF pos = data.getPos(); + final String[] params = data.getData(); + final int objDefine = Integer.parseInt(params[3]); + if (objects.isEmpty() == false && (objDefine & 1) > 0 && i + 1 < objects.size()) { + if (objects.get(i + 1).getTime() - data.getTime() < 2f * GameHelper.getStackLatient() + && Utils.squaredDistance(pos, objects.get(i + 1).getPos()) < scale) { + objects.get(i + 1).setPosOffset( + data.getPosOffset() + Utils.toRes(4) * scale); + } + } + i++; + } + } + + private void calculateAllSliderPaths(){ + if (objects.isEmpty()){ + return; + } + else { + if (lastTrack.getSliderCount() <= 0){ + return; + } + sliderPaths = new SliderPath[lastTrack.getSliderCount()]; + for (SliderPath path : sliderPaths){ + path = null; + } + int i = 0; + sliderIndex = 0; + for (GameObjectData data : objects){ + final String[] params = data.getData(); + final int objDefine = Integer.parseInt(params[3]); + //is slider + if ((objDefine & 2) > 0) { + final PointF pos = data.getPos(); + final float length = Float.parseFloat(params[7]); + final float offset = data.getPosOffset(); + pos.x += data.getPosOffset(); + pos.y += data.getPosOffset(); + if (length < 0){ + sliderPaths[sliderIndex] = GameHelper.calculatePath(Utils.realToTrackCoords(pos), + params[5].split("[|]"), 0, offset); + } + else{ + sliderPaths[sliderIndex] = GameHelper.calculatePath(Utils.realToTrackCoords(pos), + params[5].split("[|]"), length, offset); + } + sliderIndex++; + } + i++; + } + sliderIndex = 0; + } + } + + private SliderPath getSliderPath(int index){ + if (sliderPaths != null && index < sliderPaths.length && index >= 0){ + return sliderPaths[index]; + } + else { + return null; + } + } + + public boolean getReplaying() { + return replaying; + } + + public boolean saveFailedReplay() { + stat.setTime(System.currentTimeMillis()); + if (replay != null && replaying == false) { + //write misses to replay + for (GameObject obj : activeObjects) { + stat.registerHit(0, false, false); + replay.addObjectScore(obj.getId(), Replay.RESULT_0); + } + while (objects.isEmpty() == false){ + objects.poll(); + stat.registerHit(0, false, false); + replay.addObjectScore(++lastObjectId, Replay.RESULT_0); + } + //save replay + String ctime = String.valueOf(System.currentTimeMillis()); + replayFile = Config.getCorePath() + "Scores/" + + MD5Calcuator.getStringMD5(lastTrack.getFilename() + ctime) + + ctime.substring(0, Math.min(3, ctime.length())) + ".odr"; + replay.setStat(stat); + replay.save(replayFile); + ScoreLibrary.getInstance().addScore(lastTrack.getFilename(), stat, replayFile); + ToastLogger.showText(StringTable.get(R.string.message_save_replay_successful), true); + return true; + } + else{ + ToastLogger.showText(StringTable.get(R.string.message_save_replay_failed), true); + return false; + } + } } diff --git a/src/ru/nsu/ccfit/zuev/osu/game/GameScoreText.java b/src/ru/nsu/ccfit/zuev/osu/game/GameScoreText.java index 0de5a160..e26ab6a1 100644 --- a/src/ru/nsu/ccfit/zuev/osu/game/GameScoreText.java +++ b/src/ru/nsu/ccfit/zuev/osu/game/GameScoreText.java @@ -10,96 +10,96 @@ import ru.nsu.ccfit.zuev.osu.helper.AnimSprite; public class GameScoreText { - private final AnimSprite[] letters; - private final Map characters; - private final ArrayList digits = new ArrayList(); - private float scale = 0; - private boolean hasX = false; + private final AnimSprite[] letters; + private final Map characters; + private final ArrayList digits = new ArrayList(); + private float scale = 0; + private boolean hasX = false; - public GameScoreText(final float x, final float y, final String mask, - final float scale) { - AnimSprite scoreComma = null; - AnimSprite scorePercent = null; - AnimSprite scoreX = null; - letters = new AnimSprite[mask.length()]; - float width = 0; - for (int i = 0; i < mask.length(); i++) { - if (mask.charAt(i) == '0') { - letters[i] = new AnimSprite(x + width, y, "score-", 10, 0); - digits.add(letters[i]); - } else if (mask.charAt(i) == '.') { - letters[i] = new AnimSprite(x + width, y, 0, "score-comma"); - scoreComma = letters[i]; - } else if (mask.charAt(i) == '%') { - letters[i] = new AnimSprite(x + width, y, 0, "score-percent"); - scorePercent = letters[i]; - } else { - letters[i] = new AnimSprite(x + width, y, 0, "score-x"); - scoreX = letters[i]; - hasX = true; - } - letters[i].setSize(letters[i].getWidth() * scale, - letters[i].getHeight() * scale); - width += letters[i].getWidth(); - } - this.scale = scale; - this.characters = new HashMap(); - this.characters.put('.', scoreComma); - this.characters.put('%', scorePercent); - this.characters.put('x', scoreX); - } + public GameScoreText(final float x, final float y, final String mask, + final float scale) { + AnimSprite scoreComma = null; + AnimSprite scorePercent = null; + AnimSprite scoreX = null; + letters = new AnimSprite[mask.length()]; + float width = 0; + for (int i = 0; i < mask.length(); i++) { + if (mask.charAt(i) == '0') { + letters[i] = new AnimSprite(x + width, y, "score-", 10, 0); + digits.add(letters[i]); + } else if (mask.charAt(i) == '.') { + letters[i] = new AnimSprite(x + width, y, 0, "score-comma"); + scoreComma = letters[i]; + } else if (mask.charAt(i) == '%') { + letters[i] = new AnimSprite(x + width, y, 0, "score-percent"); + scorePercent = letters[i]; + } else { + letters[i] = new AnimSprite(x + width, y, 0, "score-x"); + scoreX = letters[i]; + hasX = true; + } + letters[i].setSize(letters[i].getWidth() * scale, + letters[i].getHeight() * scale); + width += letters[i].getWidth(); + } + this.scale = scale; + this.characters = new HashMap(); + this.characters.put('.', scoreComma); + this.characters.put('%', scorePercent); + this.characters.put('x', scoreX); + } - public void changeText(final StringBuilder text) { - int j = 0; - float digitsWidth = 0; - for (int i = 0; i < text.length(); i++) { - if (j >= digits.size()) { - break; - } - if (text.charAt(i) >= '0' && text.charAt(i) <= '9') { - int digit = text.charAt(i) - '0'; - digits.get(j).setVisible(true); - digits.get(j).setFrame(digit); - digits.get(j).setWidth(digits.get(j).getFrameWidth() * scale); - digits.get(j).setPosition(digits.get(0).getX() + digitsWidth, digits.get(j).getY()); - digitsWidth += digits.get(j).getWidth(); - j++; - } else if (text.charAt(i) == '*') { - digits.get(j).setVisible(false); - j++; - // TODO - } else { - char character = text.charAt(i); - if (characters.containsKey(character)) { - AnimSprite sprite = characters.get(character); - sprite.setPosition(digits.get(0).getX() + digitsWidth, sprite.getY()); - digitsWidth += sprite.getWidth(); - } - } - } - if (hasX) { - letters[letters.length - 1].setPosition(digits.get(0).getX() - + digitsWidth, letters[letters.length - 1].getY()); - } - } + public void changeText(final StringBuilder text) { + int j = 0; + float digitsWidth = 0; + for (int i = 0; i < text.length(); i++) { + if (j >= digits.size()) { + break; + } + if (text.charAt(i) >= '0' && text.charAt(i) <= '9') { + int digit = text.charAt(i) - '0'; + digits.get(j).setVisible(true); + digits.get(j).setFrame(digit); + digits.get(j).setWidth(digits.get(j).getFrameWidth() * scale); + digits.get(j).setPosition(digits.get(0).getX() + digitsWidth, digits.get(j).getY()); + digitsWidth += digits.get(j).getWidth(); + j++; + } else if (text.charAt(i) == '*') { + digits.get(j).setVisible(false); + j++; + // TODO + } else { + char character = text.charAt(i); + if (characters.containsKey(character)) { + AnimSprite sprite = characters.get(character); + sprite.setPosition(digits.get(0).getX() + digitsWidth, sprite.getY()); + digitsWidth += sprite.getWidth(); + } + } + } + if (hasX) { + letters[letters.length - 1].setPosition(digits.get(0).getX() + + digitsWidth, letters[letters.length - 1].getY()); + } + } - public void attachToScene(final Scene scene) { - for (final Sprite sp : letters) { - scene.attachChild(sp, 0); - } - } + public void attachToScene(final Scene scene) { + for (final Sprite sp : letters) { + scene.attachChild(sp, 0); + } + } - public void detachFromScene() { - for (final Sprite sp : letters) { - sp.detachSelf(); - } - } + public void detachFromScene() { + for (final Sprite sp : letters) { + sp.detachSelf(); + } + } - public void setPosition(float x, float y){ - float width = 0; - for (final Sprite sp : letters){ - sp.setPosition(x + width, y); - width += sp.getWidth(); - } - } + public void setPosition(float x, float y){ + float width = 0; + for (final Sprite sp : letters){ + sp.setPosition(x + width, y); + width += sp.getWidth(); + } + } } diff --git a/src/ru/nsu/ccfit/zuev/osu/game/GameScoreTextShadow.java b/src/ru/nsu/ccfit/zuev/osu/game/GameScoreTextShadow.java index c2c10871..bcd85e48 100644 --- a/src/ru/nsu/ccfit/zuev/osu/game/GameScoreTextShadow.java +++ b/src/ru/nsu/ccfit/zuev/osu/game/GameScoreTextShadow.java @@ -10,98 +10,98 @@ import ru.nsu.ccfit.zuev.osu.helper.AnimSprite; public class GameScoreTextShadow extends GameObject { - private final AnimSprite[] letters; - private final ArrayList digits = new ArrayList(); - private boolean hasX = false; - private String text = ""; + private final AnimSprite[] letters; + private final ArrayList digits = new ArrayList(); + private boolean hasX = false; + private String text = ""; - public GameScoreTextShadow(float x, float y, final String mask, - final float scale) { - letters = new AnimSprite[mask.length()]; - float width = 0; - for (int i = 0; i < mask.length(); i++) { - if (mask.charAt(i) == '0') { - letters[i] = new AnimSprite(x + width, y, "score-", 10, 0); - digits.add(letters[i]); - } else if (mask.charAt(i) == '.') { - letters[i] = new AnimSprite(x + width, y, 0, "score-comma"); - } else if (mask.charAt(i) == '%') { - letters[i] = new AnimSprite(x + width, y, 0, "score-percent"); - } else { - letters[i] = new AnimSprite(x + width, y, 0, "score-x"); - hasX = true; - } - letters[i].setSize(letters[i].getWidth() * scale, - letters[i].getHeight() * scale); - width += letters[i].getWidth(); - letters[i].setAlpha(0); - if (i == 0) { - x = 0; - y = 0; - } else { - letters[0].attachChild(letters[i]); - } - } - text = "0****"; - } + public GameScoreTextShadow(float x, float y, final String mask, + final float scale) { + letters = new AnimSprite[mask.length()]; + float width = 0; + for (int i = 0; i < mask.length(); i++) { + if (mask.charAt(i) == '0') { + letters[i] = new AnimSprite(x + width, y, "score-", 10, 0); + digits.add(letters[i]); + } else if (mask.charAt(i) == '.') { + letters[i] = new AnimSprite(x + width, y, 0, "score-comma"); + } else if (mask.charAt(i) == '%') { + letters[i] = new AnimSprite(x + width, y, 0, "score-percent"); + } else { + letters[i] = new AnimSprite(x + width, y, 0, "score-x"); + hasX = true; + } + letters[i].setSize(letters[i].getWidth() * scale, + letters[i].getHeight() * scale); + width += letters[i].getWidth(); + letters[i].setAlpha(0); + if (i == 0) { + x = 0; + y = 0; + } else { + letters[0].attachChild(letters[i]); + } + } + text = "0****"; + } - public void changeText(final StringBuilder text) { - if (this.text.equals(text.toString())) { - return; - } - int j = 0; - float digitsWidth = 0; - for (int i = 0; i < text.length(); i++) { - if (j >= digits.size()) { - break; - } - if (text.charAt(i) >= '0' && text.charAt(i) <= '9') { - digits.get(j).setVisible(true); - digits.get(j).setFrame(text.charAt(i) - '0'); - digitsWidth += digits.get(j).getWidth(); - j++; - } else if (text.charAt(i) == '*') { - digits.get(j).setVisible(false); - j++; - } - } - if (hasX) { - letters[letters.length - 1].setPosition(digits.get(0).getX() - + digitsWidth, letters[letters.length - 1].getY()); - } - this.text = text.toString(); + public void changeText(final StringBuilder text) { + if (this.text.equals(text.toString())) { + return; + } + int j = 0; + float digitsWidth = 0; + for (int i = 0; i < text.length(); i++) { + if (j >= digits.size()) { + break; + } + if (text.charAt(i) >= '0' && text.charAt(i) <= '9') { + digits.get(j).setVisible(true); + digits.get(j).setFrame(text.charAt(i) - '0'); + digitsWidth += digits.get(j).getWidth(); + j++; + } else if (text.charAt(i) == '*') { + digits.get(j).setVisible(false); + j++; + } + } + if (hasX) { + letters[letters.length - 1].setPosition(digits.get(0).getX() + + digitsWidth, letters[letters.length - 1].getY()); + } + this.text = text.toString(); - letters[0].setAlpha(0.6f); - } + letters[0].setAlpha(0.6f); + } - public void attachToScene(final Scene scene) { - scene.attachChild(letters[0], 0); - } + public void attachToScene(final Scene scene) { + scene.attachChild(letters[0], 0); + } - public void detachFromScene() { - letters[0].detachSelf(); - } + public void detachFromScene() { + letters[0].detachSelf(); + } - @Override - public void update(final float dt) { - if (letters[0].getAlpha() > 0) { - float alpha = letters[0].getAlpha() - dt; - if (alpha < 0) { - alpha = 0; - } + @Override + public void update(final float dt) { + if (letters[0].getAlpha() > 0) { + float alpha = letters[0].getAlpha() - dt; + if (alpha < 0) { + alpha = 0; + } - letters[0].setScale(1.5f - Math.abs(0.6f - alpha)); - letters[0].setPosition(Utils.toRes(20), Config.getRES_HEIGHT() - - letters[0].getHeightScaled() - Utils.toRes(20)); - for (final AnimSprite sp : letters) { - sp.setAlpha(alpha); - } - } + letters[0].setScale(1.5f - Math.abs(0.6f - alpha)); + letters[0].setPosition(Utils.toRes(20), Config.getRES_HEIGHT() + - letters[0].getHeightScaled() - Utils.toRes(20)); + for (final AnimSprite sp : letters) { + sp.setAlpha(alpha); + } + } - } + } - public void registerEntityModifier(IEntityModifier modifier) { - letters[0].registerEntityModifier(modifier); - } + public void registerEntityModifier(IEntityModifier modifier) { + letters[0].registerEntityModifier(modifier); + } } diff --git a/src/ru/nsu/ccfit/zuev/osu/game/HitCircle.java b/src/ru/nsu/ccfit/zuev/osu/game/HitCircle.java index 9f75fbd8..5cce2d53 100644 --- a/src/ru/nsu/ccfit/zuev/osu/game/HitCircle.java +++ b/src/ru/nsu/ccfit/zuev/osu/game/HitCircle.java @@ -17,322 +17,322 @@ import ru.nsu.ccfit.zuev.osu.scoring.Replay; public class HitCircle extends GameObject { - private final Sprite circle; - private final Sprite overlay; - private final Sprite approachCircle; - private final RGBColor color = new RGBColor(); - private CircleNumber number; - private float scale; - private GameObjectListener listener; - private Scene scene; - private int soundId; - private int sampleSet; - private int addition; - private String externalSound; - //private PointF pos; - private float radius; - private float passedTime; - private float time; - private boolean isFirstNote; - private boolean kiai; + private final Sprite circle; + private final Sprite overlay; + private final Sprite approachCircle; + private final RGBColor color = new RGBColor(); + private CircleNumber number; + private float scale; + private GameObjectListener listener; + private Scene scene; + private int soundId; + private int sampleSet; + private int addition; + private String externalSound; + //private PointF pos; + private float radius; + private float passedTime; + private float time; + private boolean isFirstNote; + private boolean kiai; - public HitCircle() { - // Getting sprites from sprite pool - circle = SpritePool.getInstance().getSprite("hitcircle"); - overlay = SpritePool.getInstance().getSprite("hitcircleoverlay"); - approachCircle = SpritePool.getInstance().getSprite("approachcircle"); - } + public HitCircle() { + // Getting sprites from sprite pool + circle = SpritePool.getInstance().getSprite("hitcircle"); + overlay = SpritePool.getInstance().getSprite("hitcircleoverlay"); + approachCircle = SpritePool.getInstance().getSprite("approachcircle"); + } - public void init(final GameObjectListener listener, final Scene pScene, - final PointF pos, final float time, final float r, final float g, - final float b, final float scale, int num, final int sound, final String tempSound, final boolean isFirstNote) { - // Storing parameters into fields - //Log.i("note-ini", time + "s"); - this.replayData = null; - this.scale = scale; - this.pos = pos; - this.listener = listener; - this.scene = pScene; - this.soundId = sound; - this.sampleSet = 0; - this.addition = 0; - // TODO: 外部音效文件支持 - this.externalSound = ""; - this.time = time; - this.isFirstNote = isFirstNote; - passedTime = 0; - startHit = false; - kiai = GameHelper.isKiai(); - color.set(r, g, b); + public void init(final GameObjectListener listener, final Scene pScene, + final PointF pos, final float time, final float r, final float g, + final float b, final float scale, int num, final int sound, final String tempSound, final boolean isFirstNote) { + // Storing parameters into fields + //Log.i("note-ini", time + "s"); + this.replayData = null; + this.scale = scale; + this.pos = pos; + this.listener = listener; + this.scene = pScene; + this.soundId = sound; + this.sampleSet = 0; + this.addition = 0; + // TODO: 外部音效文件支持 + this.externalSound = ""; + this.time = time; + this.isFirstNote = isFirstNote; + passedTime = 0; + startHit = false; + kiai = GameHelper.isKiai(); + color.set(r, g, b); - if (!Utils.isEmpty(tempSound)) { - final String[] group = tempSound.split(":"); - this.sampleSet = Integer.parseInt(group[0]); - this.addition = Integer.parseInt(group[1]); - if (group.length > 4) { - this.externalSound = group[4]; - } - } + if (!Utils.isEmpty(tempSound)) { + final String[] group = tempSound.split(":"); + this.sampleSet = Integer.parseInt(group[0]); + this.addition = Integer.parseInt(group[1]); + if (group.length > 4) { + this.externalSound = group[4]; + } + } - // Calculating position of top/left corner for sprites and hit radius - final TextureRegion tex = circle.getTextureRegion(); - /*final PointF rpos = new PointF(pos.x - tex.getWidth() / 2, pos.y - - tex.getHeight() / 2);*/ - radius = Utils.toRes(128) * scale / 2; - radius *= radius; + // Calculating position of top/left corner for sprites and hit radius + final TextureRegion tex = circle.getTextureRegion(); + /*final PointF rpos = new PointF(pos.x - tex.getWidth() / 2, pos.y + - tex.getHeight() / 2);*/ + radius = Utils.toRes(128) * scale / 2; + radius *= radius; - // Initializing sprites - //circle.setPosition(rpos.x, rpos.y); - circle.setColor(r, g, b); - circle.setScale(scale); - circle.setAlpha(0); - Utils.putSpriteAnchorCenter(pos, circle); + // Initializing sprites + //circle.setPosition(rpos.x, rpos.y); + circle.setColor(r, g, b); + circle.setScale(scale); + circle.setAlpha(0); + Utils.putSpriteAnchorCenter(pos, circle); - //overlay.setPosition(rpos.x, rpos.y); - overlay.setScale(scale); - overlay.setAlpha(0); - Utils.putSpriteAnchorCenter(pos, overlay); + //overlay.setPosition(rpos.x, rpos.y); + overlay.setScale(scale); + overlay.setAlpha(0); + Utils.putSpriteAnchorCenter(pos, overlay); - //approachCircle.setPosition(rpos.x, rpos.y); - approachCircle.setColor(r, g, b); - approachCircle.setScale(scale * 2); - approachCircle.setAlpha(0); - Utils.putSpriteAnchorCenter(pos, approachCircle); - if (GameHelper.isHidden()) { - approachCircle.setVisible(Config.isShowFirstApproachCircle() && this.isFirstNote); - } + //approachCircle.setPosition(rpos.x, rpos.y); + approachCircle.setColor(r, g, b); + approachCircle.setScale(scale * 2); + approachCircle.setAlpha(0); + Utils.putSpriteAnchorCenter(pos, approachCircle); + if (GameHelper.isHidden()) { + approachCircle.setVisible(Config.isShowFirstApproachCircle() && this.isFirstNote); + } - // Attach sprites to scene - scene.attachChild(overlay, 0); - // and getting new number from sprite pool - num += 1; - if (SkinJson.get().isLimitComboTextLength()) { - num %= 10; - } - number = GameObjectPool.getInstance().getNumber(num); - if (GameHelper.isHidden()) { - number.init(scene, pos, GameHelper.getScale(), - new SequenceEntityModifier(new FadeInModifier(time / 4 * GameHelper.getTimeMultiplier()), - new FadeOutModifier(time * 0.35f * GameHelper.getTimeMultiplier()))); - overlay.registerEntityModifier(new SequenceEntityModifier(new FadeInModifier(time / 4 * GameHelper.getTimeMultiplier()), - new FadeOutModifier(time * 0.35f * GameHelper.getTimeMultiplier()))); - circle.registerEntityModifier(new SequenceEntityModifier(new FadeInModifier(time / 4 * GameHelper.getTimeMultiplier()), - new FadeOutModifier(time * 0.35f * GameHelper.getTimeMultiplier()))); - } else { - number.init(scene, pos, GameHelper.getScale(), new FadeInModifier( - time / 2 * GameHelper.getTimeMultiplier())); - } - scene.attachChild(circle, 0); - scene.attachChild(approachCircle); - } + // Attach sprites to scene + scene.attachChild(overlay, 0); + // and getting new number from sprite pool + num += 1; + if (SkinJson.get().isLimitComboTextLength()) { + num %= 10; + } + number = GameObjectPool.getInstance().getNumber(num); + if (GameHelper.isHidden()) { + number.init(scene, pos, GameHelper.getScale(), + new SequenceEntityModifier(new FadeInModifier(time / 4 * GameHelper.getTimeMultiplier()), + new FadeOutModifier(time * 0.35f * GameHelper.getTimeMultiplier()))); + overlay.registerEntityModifier(new SequenceEntityModifier(new FadeInModifier(time / 4 * GameHelper.getTimeMultiplier()), + new FadeOutModifier(time * 0.35f * GameHelper.getTimeMultiplier()))); + circle.registerEntityModifier(new SequenceEntityModifier(new FadeInModifier(time / 4 * GameHelper.getTimeMultiplier()), + new FadeOutModifier(time * 0.35f * GameHelper.getTimeMultiplier()))); + } else { + number.init(scene, pos, GameHelper.getScale(), new FadeInModifier( + time / 2 * GameHelper.getTimeMultiplier())); + } + scene.attachChild(circle, 0); + scene.attachChild(approachCircle); + } - private void playSound() { - // Sound is playing only if we hit in time - if (approachCircle.getScaleX() <= scale * 1.5f) { - Utils.playHitSound(listener, soundId, sampleSet, addition); - } - } + private void playSound() { + // Sound is playing only if we hit in time + if (approachCircle.getScaleX() <= scale * 1.5f) { + Utils.playHitSound(listener, soundId, sampleSet, addition); + } + } - private void removeFromScene() { - if (scene == null) { - return; - } - // Detach all objects - overlay.detachSelf(); - circle.detachSelf(); - approachCircle.detachSelf(); - number.detach(false); - listener.removeObject(this); - // Put circle and number into pool - GameObjectPool.getInstance().putCircle(this); - GameObjectPool.getInstance().putNumber(number); - scene = null; - } + private void removeFromScene() { + if (scene == null) { + return; + } + // Detach all objects + overlay.detachSelf(); + circle.detachSelf(); + approachCircle.detachSelf(); + number.detach(false); + listener.removeObject(this); + // Put circle and number into pool + GameObjectPool.getInstance().putCircle(this); + GameObjectPool.getInstance().putNumber(number); + scene = null; + } - private boolean isHit() { - // 因为这里是阻塞队列, 所以提前点的地方会影响判断 - for (int i = 0; i < listener.getCursorsCount(); i++) { - if (listener.isMousePressed(this, i) - && Utils.squaredDistance(pos, listener.getMousePos(i)) <= radius) { - return true; - } else if (GameHelper.isAutopilotMod() && listener.isMousePressed(this, i)) { - return true; - } else if (GameHelper.isRelaxMod() && passedTime - time >= 0 && - Utils.squaredDistance(pos, listener.getMousePos(i)) <= radius) { - return true; - } - } - return false; - } + private boolean isHit() { + // 因为这里是阻塞队列, 所以提前点的地方会影响判断 + for (int i = 0; i < listener.getCursorsCount(); i++) { + if (listener.isMousePressed(this, i) + && Utils.squaredDistance(pos, listener.getMousePos(i)) <= radius) { + return true; + } else if (GameHelper.isAutopilotMod() && listener.isMousePressed(this, i)) { + return true; + } else if (GameHelper.isRelaxMod() && passedTime - time >= 0 && + Utils.squaredDistance(pos, listener.getMousePos(i)) <= radius) { + return true; + } + } + return false; + } - private double hitOffsetToPreviousFrame() { - // 因为这里是阻塞队列, 所以提前点的地方会影响判断 - for (int i = 0; i < listener.getCursorsCount(); i++) { - if (listener.isMousePressed(this, i) - && Utils.squaredDistance(pos, listener.getMousePos(i)) <= radius) { - return listener.downFrameOffset(i); - } else if (GameHelper.isAutopilotMod() && listener.isMousePressed(this, i)) { - return 0; - } else if (GameHelper.isRelaxMod() && passedTime - time >= 0 && - Utils.squaredDistance(pos, listener.getMousePos(i)) <= radius) { - return 0; - } - } - return 0; - } + private double hitOffsetToPreviousFrame() { + // 因为这里是阻塞队列, 所以提前点的地方会影响判断 + for (int i = 0; i < listener.getCursorsCount(); i++) { + if (listener.isMousePressed(this, i) + && Utils.squaredDistance(pos, listener.getMousePos(i)) <= radius) { + return listener.downFrameOffset(i); + } else if (GameHelper.isAutopilotMod() && listener.isMousePressed(this, i)) { + return 0; + } else if (GameHelper.isRelaxMod() && passedTime - time >= 0 && + Utils.squaredDistance(pos, listener.getMousePos(i)) <= radius) { + return 0; + } + } + return 0; + } - @Override - public void update(final float dt) { - // PassedTime < 0 means circle logic is over - if (passedTime < 0) { - return; - } - // If we have clicked circle - if (replayData != null) { - if (passedTime - time + dt / 2 > replayData.accuracy / 1000f) { - final float acc = Math.abs(replayData.accuracy / 1000f); - if (acc <= GameHelper.getDifficultyHelper().hitWindowFor50(GameHelper.getDifficulty())) { - playSound(); - } - listener.registerAccuracy(replayData.accuracy / 1000f); - passedTime = -1; - // Remove circle and register hit in update thread - SyncTaskManager.getInstance().run(new Runnable() { - public void run() { - HitCircle.this.listener - .onCircleHit(id, replayData.accuracy / 1000f, pos, - endsCombo, replayData.result, color); - removeFromScene(); - } - }); - return; - } - } else if (passedTime * 2 > time && isHit()) { - float signAcc = passedTime - time; - if (Config.isFixFrameOffset()) { - signAcc += (float) hitOffsetToPreviousFrame() / 1000f; - } - final float acc = Math.abs(signAcc); - //Log.i("note-ini", "signAcc: " + signAcc); - if (acc <= GameHelper.getDifficultyHelper().hitWindowFor50(GameHelper.getDifficulty())) { - playSound(); - } - listener.registerAccuracy(signAcc); - passedTime = -1; - // Remove circle and register hit in update thread - float finalSignAcc = signAcc; - startHit = true; - SyncTaskManager.getInstance().run(() -> { - HitCircle.this.listener - .onCircleHit(id, finalSignAcc, pos, endsCombo, (byte) 0, color); - removeFromScene(); - }); - return; - } + @Override + public void update(final float dt) { + // PassedTime < 0 means circle logic is over + if (passedTime < 0) { + return; + } + // If we have clicked circle + if (replayData != null) { + if (passedTime - time + dt / 2 > replayData.accuracy / 1000f) { + final float acc = Math.abs(replayData.accuracy / 1000f); + if (acc <= GameHelper.getDifficultyHelper().hitWindowFor50(GameHelper.getDifficulty())) { + playSound(); + } + listener.registerAccuracy(replayData.accuracy / 1000f); + passedTime = -1; + // Remove circle and register hit in update thread + SyncTaskManager.getInstance().run(new Runnable() { + public void run() { + HitCircle.this.listener + .onCircleHit(id, replayData.accuracy / 1000f, pos, + endsCombo, replayData.result, color); + removeFromScene(); + } + }); + return; + } + } else if (passedTime * 2 > time && isHit()) { + float signAcc = passedTime - time; + if (Config.isFixFrameOffset()) { + signAcc += (float) hitOffsetToPreviousFrame() / 1000f; + } + final float acc = Math.abs(signAcc); + //Log.i("note-ini", "signAcc: " + signAcc); + if (acc <= GameHelper.getDifficultyHelper().hitWindowFor50(GameHelper.getDifficulty())) { + playSound(); + } + listener.registerAccuracy(signAcc); + passedTime = -1; + // Remove circle and register hit in update thread + float finalSignAcc = signAcc; + startHit = true; + SyncTaskManager.getInstance().run(() -> { + HitCircle.this.listener + .onCircleHit(id, finalSignAcc, pos, endsCombo, (byte) 0, color); + removeFromScene(); + }); + return; + } - if (GameHelper.isKiai()) { - final float kiaiModifier = Math - .max(0, - 1 - GameHelper.getGlobalTime() - / GameHelper.getKiaiTickLength()) * 0.50f; - final float r = Math.min(1, color.r() + (1 - color.r()) - * kiaiModifier); - final float g = Math.min(1, color.g() + (1 - color.g()) - * kiaiModifier); - final float b = Math.min(1, color.b() + (1 - color.b()) - * kiaiModifier); - kiai = true; - circle.setColor(r, g, b); - } else if (kiai == true) { - circle.setColor(color.r(), color.g(), color.b()); - kiai = false; - } + if (GameHelper.isKiai()) { + final float kiaiModifier = Math + .max(0, + 1 - GameHelper.getGlobalTime() + / GameHelper.getKiaiTickLength()) * 0.50f; + final float r = Math.min(1, color.r() + (1 - color.r()) + * kiaiModifier); + final float g = Math.min(1, color.g() + (1 - color.g()) + * kiaiModifier); + final float b = Math.min(1, color.b() + (1 - color.b()) + * kiaiModifier); + kiai = true; + circle.setColor(r, g, b); + } else if (kiai == true) { + circle.setColor(color.r(), color.g(), color.b()); + kiai = false; + } - if (autoPlay && passedTime - time >= 0) { - playSound(); - passedTime = -1; - // Remove circle and register hit in update thread - SyncTaskManager.getInstance().run(new Runnable() { + if (autoPlay && passedTime - time >= 0) { + playSound(); + passedTime = -1; + // Remove circle and register hit in update thread + SyncTaskManager.getInstance().run(new Runnable() { - public void run() { - HitCircle.this.listener.onCircleHit(id, 0, pos, endsCombo, Replay.RESULT_300, color); - removeFromScene(); - } - }); - return; - } + public void run() { + HitCircle.this.listener.onCircleHit(id, 0, pos, endsCombo, Replay.RESULT_300, color); + removeFromScene(); + } + }); + return; + } - passedTime += dt; + passedTime += dt; - // if it's too early to click - if (passedTime < time) { - float percentage = passedTime / time; - // calculating size of approach circle - approachCircle.setScale(scale * (1 + 2f * (1 - percentage))); - // and if we just begun - if (GameHelper.isHidden() == false || (isFirstNote && Config.isShowFirstApproachCircle())) { - if (passedTime < time / 2) { - // calculating alpha of all sprites - percentage = passedTime * 2 / time; - overlay.setAlpha(percentage); - circle.setAlpha(percentage); - approachCircle.setAlpha(percentage); -// } else if (GameHelper.isHidden()) { -// if (passedTime < time * 0.9f) { -//// percentage = 1 - passedTime / (time * 0.85f); -//// overlay.setAlpha(percentage); -//// circle.setAlpha(percentage); -//// } else { -// overlay.setAlpha(0); -// circle.setAlpha(0); -// } - } else if (!GameHelper.isHidden())// if circle already has to be shown, set all alphas to 1 - { - overlay.setAlpha(1); - circle.setAlpha(1); - approachCircle.setAlpha(1); - } - } - } else if (autoPlay == false)// if player didn't click circle in time - { - approachCircle.setAlpha(0); - // If passed too many time, counting it as miss - if (passedTime > time + GameHelper.getDifficultyHelper().hitWindowFor50(GameHelper.getDifficulty())) { - passedTime = -1; - final byte forcedScore = (replayData == null) ? 0 : replayData.result; - SyncTaskManager.getInstance().run(() -> { - removeFromScene(); - HitCircle.this.listener.onCircleHit(id, 10, pos, false, forcedScore, color); - }); - } - } - } // update(float dt) + // if it's too early to click + if (passedTime < time) { + float percentage = passedTime / time; + // calculating size of approach circle + approachCircle.setScale(scale * (1 + 2f * (1 - percentage))); + // and if we just begun + if (GameHelper.isHidden() == false || (isFirstNote && Config.isShowFirstApproachCircle())) { + if (passedTime < time / 2) { + // calculating alpha of all sprites + percentage = passedTime * 2 / time; + overlay.setAlpha(percentage); + circle.setAlpha(percentage); + approachCircle.setAlpha(percentage); +// } else if (GameHelper.isHidden()) { +// if (passedTime < time * 0.9f) { +//// percentage = 1 - passedTime / (time * 0.85f); +//// overlay.setAlpha(percentage); +//// circle.setAlpha(percentage); +//// } else { +// overlay.setAlpha(0); +// circle.setAlpha(0); +// } + } else if (!GameHelper.isHidden())// if circle already has to be shown, set all alphas to 1 + { + overlay.setAlpha(1); + circle.setAlpha(1); + approachCircle.setAlpha(1); + } + } + } else if (autoPlay == false)// if player didn't click circle in time + { + approachCircle.setAlpha(0); + // If passed too many time, counting it as miss + if (passedTime > time + GameHelper.getDifficultyHelper().hitWindowFor50(GameHelper.getDifficulty())) { + passedTime = -1; + final byte forcedScore = (replayData == null) ? 0 : replayData.result; + SyncTaskManager.getInstance().run(() -> { + removeFromScene(); + HitCircle.this.listener.onCircleHit(id, 10, pos, false, forcedScore, color); + }); + } + } + } // update(float dt) - @Override - public void tryHit(final float dt){ - if (passedTime * 2 > time && isHit()) { - float signAcc = passedTime - time; - if (Config.isFixFrameOffset()) { - signAcc += (float) hitOffsetToPreviousFrame() / 1000f; - } - final float acc = Math.abs(signAcc); - //Log.i("note-ini", "signAcc: " + signAcc); - if (acc <= GameHelper.getDifficultyHelper().hitWindowFor50(GameHelper.getDifficulty())) { - playSound(); - } - listener.registerAccuracy(signAcc); - passedTime = -1; - // Remove circle and register hit in update thread - float finalSignAcc = signAcc; - SyncTaskManager.getInstance().run(() -> { - HitCircle.this.listener - .onCircleHit(id, finalSignAcc, pos, endsCombo, (byte) 0, color); - removeFromScene(); - }); - - } - } + @Override + public void tryHit(final float dt){ + if (passedTime * 2 > time && isHit()) { + float signAcc = passedTime - time; + if (Config.isFixFrameOffset()) { + signAcc += (float) hitOffsetToPreviousFrame() / 1000f; + } + final float acc = Math.abs(signAcc); + //Log.i("note-ini", "signAcc: " + signAcc); + if (acc <= GameHelper.getDifficultyHelper().hitWindowFor50(GameHelper.getDifficulty())) { + playSound(); + } + listener.registerAccuracy(signAcc); + passedTime = -1; + // Remove circle and register hit in update thread + float finalSignAcc = signAcc; + SyncTaskManager.getInstance().run(() -> { + HitCircle.this.listener + .onCircleHit(id, finalSignAcc, pos, endsCombo, (byte) 0, color); + removeFromScene(); + }); + + } + } } diff --git a/src/ru/nsu/ccfit/zuev/osu/game/HitErrorMeter.java b/src/ru/nsu/ccfit/zuev/osu/game/HitErrorMeter.java index 812e8719..5c485296 100644 --- a/src/ru/nsu/ccfit/zuev/osu/game/HitErrorMeter.java +++ b/src/ru/nsu/ccfit/zuev/osu/game/HitErrorMeter.java @@ -15,96 +15,96 @@ */ public class HitErrorMeter extends GameObject { - private final Scene bgScene; - private final PointF barAnchor; - private final float barHeight; - private final float boundary; - private final List onDisplayIndicators; - private final List recycledIndicators; - private DifficultyHelper difficultyHelper; - - public HitErrorMeter(Scene scene, PointF anchor, float difficulty, float height, DifficultyHelper difficultyHelper) { - barAnchor = anchor; - barHeight = height; - bgScene = scene; - - onDisplayIndicators = new LinkedList(); - recycledIndicators = new LinkedList(); - - this.difficultyHelper = difficultyHelper; - - boundary = difficultyHelper.hitWindowFor50(difficulty); - - float totalLen = boundary * 1500; - Rectangle hitMeter = new Rectangle(anchor.x - totalLen / 2, anchor.y - height, totalLen, height * 2); - hitMeter.setColor(0f, 0f, 0f, 0.8f); - scene.attachChild(hitMeter); - - float hit50Len = totalLen; - Rectangle hit50 = new Rectangle(anchor.x - hit50Len / 2, anchor.y - height / 2, hit50Len, height); - hit50.setColor(200f / 255f, 180f / 255f, 110f / 255f, 0.8f); - scene.attachChild(hit50); - - float hit100Len = difficultyHelper.hitWindowFor100(difficulty) * 1500; - Rectangle hit100 = new Rectangle(anchor.x - hit100Len / 2, anchor.y - height / 2, hit100Len, height); - hit100.setColor(100f / 255f, 220f / 255f, 40f / 255f, 0.8f); - scene.attachChild(hit100); - - float hit300Len = difficultyHelper.hitWindowFor300(difficulty) * 1500; - Rectangle hit300 = new Rectangle(anchor.x - hit300Len / 2, anchor.y - height / 2, hit300Len, height); - hit300.setColor(70f / 255f, 180f / 255f, 220f / 255f, 0.8f); - scene.attachChild(hit300); - - Rectangle hitIndicator = new Rectangle(anchor.x - 2, anchor.y - height, 4, height * 2); - hitIndicator.setColor(1f, 1f, 1f, 0.8f); - hitIndicator.setZIndex(15); - scene.attachChild(hitIndicator); - } - - @Override - public void update(float dt) { - while (!onDisplayIndicators.isEmpty()) { - if (onDisplayIndicators.get(0).getAlpha() <= 0) { - Rectangle removed = onDisplayIndicators.remove(0); - removed.setVisible(false); - removed.setIgnoreUpdate(true); - removed.detachSelf(); - recycledIndicators.add(removed); - } else { - break; - } - } - for (final Rectangle result : onDisplayIndicators) { - float currentAlpha = result.getAlpha() - 0.002f; - result.setAlpha(currentAlpha); - } - } - - public void putErrorResult(float errorResult) { - if (Math.abs(errorResult) > boundary) { - return; - } - errorResult = errorResult * 750; - if (recycledIndicators.isEmpty()) { - Rectangle indicator = new Rectangle(barAnchor.x - 2, barAnchor.y - barHeight, 4, barHeight * 2); - float posX = indicator.getX() + errorResult; - float posY = indicator.getY(); - indicator.setPosition(posX, posY); - indicator.setColor(70f / 255f, 180f / 255f, 220f / 255f, 0.6f); - indicator.setZIndex(10); - bgScene.attachChild(indicator); - onDisplayIndicators.add(indicator); - } else { - Rectangle indicator = recycledIndicators.remove(0); - float posX = barAnchor.x - 2 + errorResult; - float posY = indicator.getY(); - indicator.setPosition(posX, posY); - indicator.setColor(70f / 255f, 180f / 255f, 220f / 255f, 0.6f); - indicator.setZIndex(10); - indicator.setVisible(true); - indicator.setIgnoreUpdate(false); - bgScene.attachChild(indicator); - onDisplayIndicators.add(indicator); - } - } + private final Scene bgScene; + private final PointF barAnchor; + private final float barHeight; + private final float boundary; + private final List onDisplayIndicators; + private final List recycledIndicators; + private DifficultyHelper difficultyHelper; + + public HitErrorMeter(Scene scene, PointF anchor, float difficulty, float height, DifficultyHelper difficultyHelper) { + barAnchor = anchor; + barHeight = height; + bgScene = scene; + + onDisplayIndicators = new LinkedList(); + recycledIndicators = new LinkedList(); + + this.difficultyHelper = difficultyHelper; + + boundary = difficultyHelper.hitWindowFor50(difficulty); + + float totalLen = boundary * 1500; + Rectangle hitMeter = new Rectangle(anchor.x - totalLen / 2, anchor.y - height, totalLen, height * 2); + hitMeter.setColor(0f, 0f, 0f, 0.8f); + scene.attachChild(hitMeter); + + float hit50Len = totalLen; + Rectangle hit50 = new Rectangle(anchor.x - hit50Len / 2, anchor.y - height / 2, hit50Len, height); + hit50.setColor(200f / 255f, 180f / 255f, 110f / 255f, 0.8f); + scene.attachChild(hit50); + + float hit100Len = difficultyHelper.hitWindowFor100(difficulty) * 1500; + Rectangle hit100 = new Rectangle(anchor.x - hit100Len / 2, anchor.y - height / 2, hit100Len, height); + hit100.setColor(100f / 255f, 220f / 255f, 40f / 255f, 0.8f); + scene.attachChild(hit100); + + float hit300Len = difficultyHelper.hitWindowFor300(difficulty) * 1500; + Rectangle hit300 = new Rectangle(anchor.x - hit300Len / 2, anchor.y - height / 2, hit300Len, height); + hit300.setColor(70f / 255f, 180f / 255f, 220f / 255f, 0.8f); + scene.attachChild(hit300); + + Rectangle hitIndicator = new Rectangle(anchor.x - 2, anchor.y - height, 4, height * 2); + hitIndicator.setColor(1f, 1f, 1f, 0.8f); + hitIndicator.setZIndex(15); + scene.attachChild(hitIndicator); + } + + @Override + public void update(float dt) { + while (!onDisplayIndicators.isEmpty()) { + if (onDisplayIndicators.get(0).getAlpha() <= 0) { + Rectangle removed = onDisplayIndicators.remove(0); + removed.setVisible(false); + removed.setIgnoreUpdate(true); + removed.detachSelf(); + recycledIndicators.add(removed); + } else { + break; + } + } + for (final Rectangle result : onDisplayIndicators) { + float currentAlpha = result.getAlpha() - 0.002f; + result.setAlpha(currentAlpha); + } + } + + public void putErrorResult(float errorResult) { + if (Math.abs(errorResult) > boundary) { + return; + } + errorResult = errorResult * 750; + if (recycledIndicators.isEmpty()) { + Rectangle indicator = new Rectangle(barAnchor.x - 2, barAnchor.y - barHeight, 4, barHeight * 2); + float posX = indicator.getX() + errorResult; + float posY = indicator.getY(); + indicator.setPosition(posX, posY); + indicator.setColor(70f / 255f, 180f / 255f, 220f / 255f, 0.6f); + indicator.setZIndex(10); + bgScene.attachChild(indicator); + onDisplayIndicators.add(indicator); + } else { + Rectangle indicator = recycledIndicators.remove(0); + float posX = barAnchor.x - 2 + errorResult; + float posY = indicator.getY(); + indicator.setPosition(posX, posY); + indicator.setColor(70f / 255f, 180f / 255f, 220f / 255f, 0.6f); + indicator.setZIndex(10); + indicator.setVisible(true); + indicator.setIgnoreUpdate(false); + bgScene.attachChild(indicator); + onDisplayIndicators.add(indicator); + } + } } diff --git a/src/ru/nsu/ccfit/zuev/osu/game/ISliderListener.java b/src/ru/nsu/ccfit/zuev/osu/game/ISliderListener.java index 47165563..c0865008 100644 --- a/src/ru/nsu/ccfit/zuev/osu/game/ISliderListener.java +++ b/src/ru/nsu/ccfit/zuev/osu/game/ISliderListener.java @@ -1,7 +1,7 @@ -package ru.nsu.ccfit.zuev.osu.game; - -public interface ISliderListener { - void onSliderStart(); - void onSliderTracking(); - void onSliderEnd(); -} \ No newline at end of file +package ru.nsu.ccfit.zuev.osu.game; + +public interface ISliderListener { + void onSliderStart(); + void onSliderTracking(); + void onSliderEnd(); +} diff --git a/src/ru/nsu/ccfit/zuev/osu/game/ModernSpinner.java b/src/ru/nsu/ccfit/zuev/osu/game/ModernSpinner.java index 5f70816e..ba9e2a59 100644 --- a/src/ru/nsu/ccfit/zuev/osu/game/ModernSpinner.java +++ b/src/ru/nsu/ccfit/zuev/osu/game/ModernSpinner.java @@ -25,258 +25,258 @@ */ public class ModernSpinner extends Spinner { - private final Sprite middle; - private final Sprite middle2; - private final Sprite bottom; - private final Sprite top; - private final Sprite glow; - // private final Sprite spin; - // private final Sprite clear; + private final Sprite middle; + private final Sprite middle2; + private final Sprite bottom; + private final Sprite top; + private final Sprite glow; + // private final Sprite spin; + // private final Sprite clear; - private GameObjectListener listener; - private Scene scene; - public PointF center; - private float needRotations; - private int fullRotations = 0; - private float rotations = 0; - private int soundId; - private boolean clear; - private int score = 1; - private StatisticV2 stat; - private ScoreNumber bonusScore; - private PointF oldMouse; - private float totalTime; + private GameObjectListener listener; + private Scene scene; + public PointF center; + private float needRotations; + private int fullRotations = 0; + private float rotations = 0; + private int soundId; + private boolean clear; + private int score = 1; + private StatisticV2 stat; + private ScoreNumber bonusScore; + private PointF oldMouse; + private float totalTime; - public ModernSpinner() { - ResourceManager.getInstance().checkEvoSpinnerTextures(); - center = Utils.trackToRealCoords(new PointF(Constants.MAP_WIDTH / 2, - Constants.MAP_HEIGHT / 2)); - middle = SpritePool.getInstance().getCenteredSprite( - "spinner-middle", center); - middle2 = SpritePool.getInstance().getCenteredSprite( - "spinner-middle2", center); - bottom = SpritePool.getInstance().getCenteredSprite( - "spinner-bottom", center); - top = SpritePool.getInstance().getCenteredSprite( - "spinner-top", center); - glow = SpritePool.getInstance().getCenteredSprite( - "spinner-glow", center); - } + public ModernSpinner() { + ResourceManager.getInstance().checkEvoSpinnerTextures(); + center = Utils.trackToRealCoords(new PointF(Constants.MAP_WIDTH / 2, + Constants.MAP_HEIGHT / 2)); + middle = SpritePool.getInstance().getCenteredSprite( + "spinner-middle", center); + middle2 = SpritePool.getInstance().getCenteredSprite( + "spinner-middle2", center); + bottom = SpritePool.getInstance().getCenteredSprite( + "spinner-bottom", center); + top = SpritePool.getInstance().getCenteredSprite( + "spinner-top", center); + glow = SpritePool.getInstance().getCenteredSprite( + "spinner-glow", center); + } - public void init(GameObjectListener listener, Scene scene, - float aheadTime, float time, float rps, - int sound, String tempSound, StatisticV2 stat) { - this.scene = scene; - this.needRotations = rps * time; - this.listener = listener; - this.soundId = sound; - this.stat = stat; - this.clear = false; - this.fullRotations = 0; - this.rotations = 0; + public void init(GameObjectListener listener, Scene scene, + float aheadTime, float time, float rps, + int sound, String tempSound, StatisticV2 stat) { + this.scene = scene; + this.needRotations = rps * time; + this.listener = listener; + this.soundId = sound; + this.stat = stat; + this.clear = false; + this.fullRotations = 0; + this.rotations = 0; - glow.setAlpha(0f); - glow.setScale(0.9f); - glow.setColor(0f, 0.8f, 1f); + glow.setAlpha(0f); + glow.setScale(0.9f); + glow.setColor(0f, 0.8f, 1f); - middle.setAlpha(0f); - middle.setScale(0.9f); + middle.setAlpha(0f); + middle.setScale(0.9f); - middle2.setAlpha(0f); - middle2.setScale(0.9f); + middle2.setAlpha(0f); + middle2.setScale(0.9f); - bottom.setAlpha(0f); - bottom.setScale(0.9f); + bottom.setAlpha(0f); + bottom.setScale(0.9f); - top.setAlpha(0f); - top.setScale(0.9f); + top.setAlpha(0f); + top.setScale(0.9f); - scene.attachChild(glow); - scene.attachChild(bottom); - scene.attachChild(top); - scene.attachChild(middle); - scene.attachChild(middle2); + scene.attachChild(glow); + scene.attachChild(bottom); + scene.attachChild(top); + scene.attachChild(middle); + scene.attachChild(middle2); - top.registerEntityModifier( - new SequenceEntityModifier( - new IEntityModifier.IEntityModifierListener() { - @Override - public void onModifierStarted(final IModifier pModifier, final IEntity pItem) { - } + top.registerEntityModifier( + new SequenceEntityModifier( + new IEntityModifier.IEntityModifierListener() { + @Override + public void onModifierStarted(final IModifier pModifier, final IEntity pItem) { + } - @Override - public void onModifierFinished(final IModifier pModifier, final IEntity pItem) { - SyncTaskManager.getInstance().run(new Runnable() { - public void run() { - removeFromScene(); - } - }); - } - }, - new SequenceEntityModifier( - new AlphaModifier(aheadTime, 0, 1f), - new DelayModifier(time) - ) - )); - bottom.registerEntityModifier(new AlphaModifier(aheadTime, 0, 1f)); - middle.registerEntityModifier(new AlphaModifier(aheadTime, 0, 1f)); - middle2.registerEntityModifier(new AlphaModifier(aheadTime, 0, 1f)); - } + @Override + public void onModifierFinished(final IModifier pModifier, final IEntity pItem) { + SyncTaskManager.getInstance().run(new Runnable() { + public void run() { + removeFromScene(); + } + }); + } + }, + new SequenceEntityModifier( + new AlphaModifier(aheadTime, 0, 1f), + new DelayModifier(time) + ) + )); + bottom.registerEntityModifier(new AlphaModifier(aheadTime, 0, 1f)); + middle.registerEntityModifier(new AlphaModifier(aheadTime, 0, 1f)); + middle2.registerEntityModifier(new AlphaModifier(aheadTime, 0, 1f)); + } - @Override - public void update(float dt) { - boolean isTouched = false; - int cursorIndex = -1; - for (int i = 0; i < listener.getCursorsCount(); i++) { - if (listener.isMouseDown(i)) { - cursorIndex = i; - isTouched = true; - break; - } - } - if (!isTouched && !autoPlay) { - return; - } + @Override + public void update(float dt) { + boolean isTouched = false; + int cursorIndex = -1; + for (int i = 0; i < listener.getCursorsCount(); i++) { + if (listener.isMouseDown(i)) { + cursorIndex = i; + isTouched = true; + break; + } + } + if (!isTouched && !autoPlay) { + return; + } - final PointF mouse = autoPlay ? center : listener.getMousePos(cursorIndex); - final PointF v = new PointF(mouse.x - center.x, mouse.y - center.y); - for (int i = 0; i < listener.getCursorsCount(); i++) { - if (oldMouse == null || listener.isMousePressed(this, i)) { - oldMouse = v; - return; - } - } - float degree = MathUtils.radToDeg(Utils.direction(v)); - top.setRotation(degree); - bottom.setRotation(degree / 2); - // bottom.setRotation(-degree); - final PointF v1 = Utils.normalize(v); - final PointF v2 = Utils.normalize(oldMouse); - float dfill = v1.x * v2.y - v1.y * v2.x; - if (autoPlay) { - dfill = 5 * 4 * dt; - degree = (rotations + dfill / 4f) * 360; - top.setRotation(degree); - //auto时,FL光圈绕中心旋转 - if (GameHelper.isAutopilotMod() || GameHelper.isAuto()) { - float pX = center.x + 50 * (float) Math.sin(degree); - float pY = center.y + 50 * (float) Math.cos(degree); - listener.updateAutoBasedPos(pX, pY); - } - // bottom.setRotation(-degree); - } - rotations += dfill / 4f; - float percentfill = (Math.abs(rotations) + fullRotations) / needRotations; - float percent = percentfill > 1 ? 1 : percentfill; + final PointF mouse = autoPlay ? center : listener.getMousePos(cursorIndex); + final PointF v = new PointF(mouse.x - center.x, mouse.y - center.y); + for (int i = 0; i < listener.getCursorsCount(); i++) { + if (oldMouse == null || listener.isMousePressed(this, i)) { + oldMouse = v; + return; + } + } + float degree = MathUtils.radToDeg(Utils.direction(v)); + top.setRotation(degree); + bottom.setRotation(degree / 2); + // bottom.setRotation(-degree); + final PointF v1 = Utils.normalize(v); + final PointF v2 = Utils.normalize(oldMouse); + float dfill = v1.x * v2.y - v1.y * v2.x; + if (autoPlay) { + dfill = 5 * 4 * dt; + degree = (rotations + dfill / 4f) * 360; + top.setRotation(degree); + //auto时,FL光圈绕中心旋转 + if (GameHelper.isAutopilotMod() || GameHelper.isAuto()) { + float pX = center.x + 50 * (float) Math.sin(degree); + float pY = center.y + 50 * (float) Math.cos(degree); + listener.updateAutoBasedPos(pX, pY); + } + // bottom.setRotation(-degree); + } + rotations += dfill / 4f; + float percentfill = (Math.abs(rotations) + fullRotations) / needRotations; + float percent = percentfill > 1 ? 1 : percentfill; - middle.setColor(1, 1 - percent, 1 - percent); - top.setScale(0.9f + percent * 0.1f); - bottom.setScale(0.9f + percent * 0.1f); - middle.setScale(0.9f + percent * 0.1f); - middle2.setScale(0.9f + percent * 0.1f); - glow.setAlpha(percent * 0.8f); - glow.setScale(0.9f + percent * 0.1f); + middle.setColor(1, 1 - percent, 1 - percent); + top.setScale(0.9f + percent * 0.1f); + bottom.setScale(0.9f + percent * 0.1f); + middle.setScale(0.9f + percent * 0.1f); + middle2.setScale(0.9f + percent * 0.1f); + glow.setAlpha(percent * 0.8f); + glow.setScale(0.9f + percent * 0.1f); - if (percentfill > 1 || clear) { - percentfill = 1; - if (!clear) { - // Clear Sprite - clear = true; - } else if (Math.abs(rotations) > 1) { - if (bonusScore != null) { - bonusScore.detachFromScene(scene); - } - rotations -= 1 * Math.signum(rotations); - bonusScore = new ScoreNumber(center.x, center.y + 100, - String.valueOf(score * 1000), 1.1f, true); - listener.onSpinnerHit(id, 1000, false, 0); - score++; - bonusScore.attachToScene(scene); - ResourceManager.getInstance().getSound("spinnerbonus").play(); - glow.registerEntityModifier(new SequenceEntityModifier( - new ColorModifier(0.1f, 0f, 1f, 0.8f, 1f, 1f, 1f), - new ColorModifier(0.1f, 1f, 0f, 1f, 0.8f, 1f, 1f) - )); - float rate = 0.375f; - if (GameHelper.getDrain() > 0) { - rate = 1 + (GameHelper.getDrain() / 4f); - } - stat.changeHp(rate * 0.01f * totalTime / needRotations); - } - } else if (Math.abs(rotations) > 1) { - rotations -= 1 * Math.signum(rotations); - if (replayData == null || replayData.accuracy / 4 > fullRotations) { - fullRotations++; - stat.registerSpinnerHit(); - float rate = 0.375f; - if (GameHelper.getDrain() > 0) { - rate = 1 + (GameHelper.getDrain() / 2f); - } - stat.changeHp(rate * 0.01f * totalTime / needRotations); - } - } - oldMouse = v; - } + if (percentfill > 1 || clear) { + percentfill = 1; + if (!clear) { + // Clear Sprite + clear = true; + } else if (Math.abs(rotations) > 1) { + if (bonusScore != null) { + bonusScore.detachFromScene(scene); + } + rotations -= 1 * Math.signum(rotations); + bonusScore = new ScoreNumber(center.x, center.y + 100, + String.valueOf(score * 1000), 1.1f, true); + listener.onSpinnerHit(id, 1000, false, 0); + score++; + bonusScore.attachToScene(scene); + ResourceManager.getInstance().getSound("spinnerbonus").play(); + glow.registerEntityModifier(new SequenceEntityModifier( + new ColorModifier(0.1f, 0f, 1f, 0.8f, 1f, 1f, 1f), + new ColorModifier(0.1f, 1f, 0f, 1f, 0.8f, 1f, 1f) + )); + float rate = 0.375f; + if (GameHelper.getDrain() > 0) { + rate = 1 + (GameHelper.getDrain() / 4f); + } + stat.changeHp(rate * 0.01f * totalTime / needRotations); + } + } else if (Math.abs(rotations) > 1) { + rotations -= 1 * Math.signum(rotations); + if (replayData == null || replayData.accuracy / 4 > fullRotations) { + fullRotations++; + stat.registerSpinnerHit(); + float rate = 0.375f; + if (GameHelper.getDrain() > 0) { + rate = 1 + (GameHelper.getDrain() / 2f); + } + stat.changeHp(rate * 0.01f * totalTime / needRotations); + } + } + oldMouse = v; + } - public void removeFromScene() { -// if (clearText != null) { -// scene.detachChild(clearText); -// SpritePool.getInstance().putSprite("spinner-clear", clearText); -// } - glow.clearEntityModifiers(); - scene.detachChild(middle); - scene.detachChild(middle2); - scene.detachChild(bottom); - scene.detachChild(top); - scene.detachChild(glow); - // GameObjectPool.getInstance().putSpinner(this); + public void removeFromScene() { +// if (clearText != null) { +// scene.detachChild(clearText); +// SpritePool.getInstance().putSprite("spinner-clear", clearText); +// } + glow.clearEntityModifiers(); + scene.detachChild(middle); + scene.detachChild(middle2); + scene.detachChild(bottom); + scene.detachChild(top); + scene.detachChild(glow); + // GameObjectPool.getInstance().putSpinner(this); - if (bonusScore != null) { - bonusScore.detachFromScene(scene); - } - listener.removeObject(ModernSpinner.this); - int score = 0; - if (replayData != null) { - if (fullRotations < replayData.accuracy / 4) - fullRotations = replayData.accuracy / 4; - if (fullRotations >= needRotations) - clear = true; - int bonusRot = (int) (replayData.accuracy / 4 - needRotations + 1); - while (bonusRot < score) { - bonusRot++; - listener.onSpinnerHit(id, 1000, false, 0); - } - } - float percentfill = (Math.abs(rotations) + fullRotations) - / needRotations; - if (percentfill > 0.9f) { - score = 50; - } - if (percentfill > 0.95f) { - score = 100; - } - if (clear) { - score = 300; - } - if (replayData != null) { - switch (replayData.accuracy % 4) { - case 0: - score = 0; - break; - case 1: - score = 50; - break; - case 2: - score = 100; - break; - case 3: - score = 300; - break; - } - } - listener.onSpinnerHit(id, score, endsCombo, this.score + fullRotations - 1); - if (score > 0) { - Utils.playHitSound(listener, soundId); - } - } + if (bonusScore != null) { + bonusScore.detachFromScene(scene); + } + listener.removeObject(ModernSpinner.this); + int score = 0; + if (replayData != null) { + if (fullRotations < replayData.accuracy / 4) + fullRotations = replayData.accuracy / 4; + if (fullRotations >= needRotations) + clear = true; + int bonusRot = (int) (replayData.accuracy / 4 - needRotations + 1); + while (bonusRot < score) { + bonusRot++; + listener.onSpinnerHit(id, 1000, false, 0); + } + } + float percentfill = (Math.abs(rotations) + fullRotations) + / needRotations; + if (percentfill > 0.9f) { + score = 50; + } + if (percentfill > 0.95f) { + score = 100; + } + if (clear) { + score = 300; + } + if (replayData != null) { + switch (replayData.accuracy % 4) { + case 0: + score = 0; + break; + case 1: + score = 50; + break; + case 2: + score = 100; + break; + case 3: + score = 300; + break; + } + } + listener.onSpinnerHit(id, score, endsCombo, this.score + fullRotations - 1); + if (score > 0) { + Utils.playHitSound(listener, soundId); + } + } } diff --git a/src/ru/nsu/ccfit/zuev/osu/game/ScoreBar.java b/src/ru/nsu/ccfit/zuev/osu/game/ScoreBar.java index 8840bc91..15a84743 100644 --- a/src/ru/nsu/ccfit/zuev/osu/game/ScoreBar.java +++ b/src/ru/nsu/ccfit/zuev/osu/game/ScoreBar.java @@ -12,90 +12,90 @@ import ru.nsu.ccfit.zuev.osu.scoring.StatisticV2; public class ScoreBar extends GameObject { - private static float speed = 0.75f; - private final StatisticV2 stat; - private final Sprite bg; - private final Sprite colour; - private final AnimSprite ki; - private final float width; - private float lasthp = 0; + private static float speed = 0.75f; + private final StatisticV2 stat; + private final Sprite bg; + private final Sprite colour; + private final AnimSprite ki; + private final float width; + private float lasthp = 0; - public ScoreBar(final GameObjectListener listener, final Scene scene, - final StatisticV2 stat) { - this.stat = stat; - bg = new Sprite(0, 0, ResourceManager.getInstance().getTexture( - "scorebar-bg")); - bg.setScaleCenter(0, 0); - /*final int colourFrames = SkinManager.getFrames("scorebar-colour"); - colour = new AnimSprite(Utils.toRes(5), Utils.toRes(16), - "scorebar-colour-", colourFrames, colourFrames);*/ - if (ResourceManager.getInstance().isTextureLoaded("scorebar-colour-0")) { - List loadedScoreBarTextures = new ArrayList<>(); - for (int i = 0; i < 60; i++) { - if (ResourceManager.getInstance().isTextureLoaded("scorebar-colour-" + i)) - loadedScoreBarTextures.add("scorebar-colour-" + i); - } - colour = new AnimSprite(Utils.toRes(5), Utils.toRes(16), loadedScoreBarTextures.size(), - loadedScoreBarTextures.toArray(new String[loadedScoreBarTextures.size()])); - } else { - colour = new Sprite(Utils.toRes(5), Utils.toRes(16), - ResourceManager.getInstance().getTexture("scorebar-colour")); - } - width = colour.getWidth(); - /*for (int i = 0; i < colour.getTextureRegionCount(); i++) { - colour.setTextureRegion(i, colour.getTextureRegionAt(i).deepCopy()); - }*/ - ki = ResourceManager.getInstance().isTextureLoaded("scorebar-kidanger") - ? new AnimSprite(0, 0, 0, "scorebar-ki", "scorebar-kidanger", "scorebar-kidanger2") - : new AnimSprite(0, 0, 0, "scorebar-ki"); - ki.setPosition(Utils.toRes(5) + colour.getWidth() - ki.getWidth() / 2, - Utils.toRes(16) + colour.getHeight() / 2 - Utils.toRes(58)); + public ScoreBar(final GameObjectListener listener, final Scene scene, + final StatisticV2 stat) { + this.stat = stat; + bg = new Sprite(0, 0, ResourceManager.getInstance().getTexture( + "scorebar-bg")); + bg.setScaleCenter(0, 0); + /*final int colourFrames = SkinManager.getFrames("scorebar-colour"); + colour = new AnimSprite(Utils.toRes(5), Utils.toRes(16), + "scorebar-colour-", colourFrames, colourFrames);*/ + if (ResourceManager.getInstance().isTextureLoaded("scorebar-colour-0")) { + List loadedScoreBarTextures = new ArrayList<>(); + for (int i = 0; i < 60; i++) { + if (ResourceManager.getInstance().isTextureLoaded("scorebar-colour-" + i)) + loadedScoreBarTextures.add("scorebar-colour-" + i); + } + colour = new AnimSprite(Utils.toRes(5), Utils.toRes(16), loadedScoreBarTextures.size(), + loadedScoreBarTextures.toArray(new String[loadedScoreBarTextures.size()])); + } else { + colour = new Sprite(Utils.toRes(5), Utils.toRes(16), + ResourceManager.getInstance().getTexture("scorebar-colour")); + } + width = colour.getWidth(); + /*for (int i = 0; i < colour.getTextureRegionCount(); i++) { + colour.setTextureRegion(i, colour.getTextureRegionAt(i).deepCopy()); + }*/ + ki = ResourceManager.getInstance().isTextureLoaded("scorebar-kidanger") + ? new AnimSprite(0, 0, 0, "scorebar-ki", "scorebar-kidanger", "scorebar-kidanger2") + : new AnimSprite(0, 0, 0, "scorebar-ki"); + ki.setPosition(Utils.toRes(5) + colour.getWidth() - ki.getWidth() / 2, + Utils.toRes(16) + colour.getHeight() / 2 - Utils.toRes(58)); - scene.attachChild(ki, 0); - scene.attachChild(colour, 0); - scene.attachChild(bg, 0); - } + scene.attachChild(ki, 0); + scene.attachChild(colour, 0); + scene.attachChild(bg, 0); + } - public void setVisible(final boolean visible) { - bg.setVisible(visible); - colour.setVisible(visible); - ki.setVisible(visible); - } + public void setVisible(final boolean visible) { + bg.setVisible(visible); + colour.setVisible(visible); + ki.setVisible(visible); + } - @Override - public void update(final float dt) { - float hp = stat.getHp(); - if (Math.abs(hp - lasthp) > speed * dt) { - hp = speed * dt * Math.signum(hp - lasthp) + lasthp; - } + @Override + public void update(final float dt) { + float hp = stat.getHp(); + if (Math.abs(hp - lasthp) > speed * dt) { + hp = speed * dt * Math.signum(hp - lasthp) + lasthp; + } - /*for (int i = 0; i < colour.getTextureRegionCount(); i++) { - colour.getTextureRegionAt(i).setWidth((int) (width * hp)); - }*/ - colour.setWidth(width * hp); + /*for (int i = 0; i < colour.getTextureRegionCount(); i++) { + colour.getTextureRegionAt(i).setWidth((int) (width * hp)); + }*/ + colour.setWidth(width * hp); - ki.setPosition(Utils.toRes(5) + colour.getWidth() - ki.getWidth() / 2, - Utils.toRes(16) + colour.getHeight() / 2 - ki.getHeight() / 2); - //ki.setScale(hp>lasthp?1.2f:1); - ki.setFrame(hp > 0.49 ? 0 - : hp > 0.24 ? 1 - : 2); - lasthp = hp; - /*if (hp < 0.5f) { - if (hp < 0.25f) { - ki.setFrame(2); - } else { - ki.setFrame(1); - } - } else { - ki.setFrame(0); - }*/ - } + ki.setPosition(Utils.toRes(5) + colour.getWidth() - ki.getWidth() / 2, + Utils.toRes(16) + colour.getHeight() / 2 - ki.getHeight() / 2); + //ki.setScale(hp>lasthp?1.2f:1); + ki.setFrame(hp > 0.49 ? 0 + : hp > 0.24 ? 1 + : 2); + lasthp = hp; + /*if (hp < 0.5f) { + if (hp < 0.25f) { + ki.setFrame(2); + } else { + ki.setFrame(1); + } + } else { + ki.setFrame(0); + }*/ + } - public void flush() { - lasthp = stat.getHp(); - update(0); - } - + public void flush() { + lasthp = stat.getHp(); + update(0); + } + } diff --git a/src/ru/nsu/ccfit/zuev/osu/game/Slider.java b/src/ru/nsu/ccfit/zuev/osu/game/Slider.java index 4e371d81..b98a5377 100644 --- a/src/ru/nsu/ccfit/zuev/osu/game/Slider.java +++ b/src/ru/nsu/ccfit/zuev/osu/game/Slider.java @@ -37,1260 +37,1260 @@ import ru.nsu.ccfit.zuev.osu.polygon.Polygon; public class Slider extends GameObject { - private final Sprite startCircle, endCircle; - private final Sprite startOverlay, endOverlay; - private final Sprite approachCircle; - private final Sprite startArrow, endArrow; - private final ArrayList trackSprites = new ArrayList(); - private final ArrayList trackBorders = new ArrayList(); - private final ArrayList ticks = new ArrayList(); - private final ArrayList trackBoundaries = new ArrayList(); - private Scene scene; - private GameObjectListener listener; - private TimingPoint timing; - private CircleNumber number; - private SliderPath path; - private float passedTime; - private float preTime; - private float tickTime; - private float maxTime; - private float scale; - private float length; - private int repeatCount; - private boolean reverse; - private int[] soundId = new int[3]; - private int[] sampleSet = new int[3]; - private int[] addition = new int[3]; - - private int soundIdIndex; - private int ticksGot; - private int ticksTotal; - private int currentTick; - private double tickInterval; - - private AnimSprite ball; - private Sprite followcircle; - - private PointF tmpPoint = new PointF(); - private Float ballAngle = new Float(0); - private SpriteGroup group = null; - private SpriteGroup borderGroup = null; - private Polygon trackPoly = null; - private Polygon borderPoly = null; - private float trackPolyVerts[] = null; - private float borderPolyVerts[] = null; - - private boolean kiai; - private boolean isHiddenFadeOutActive = false; - private RGBColor color = new RGBColor(); - private RGBColor circleColor = color; - - //for replay - private int firstHitAccuracy; - private BitSet tickSet = new BitSet(); - private int tickIndex; - - private TrianglePack body = null, border = null; - private LinePath superPath = null; - private float sliderLength; - private boolean preStageFinish = false; - - private SliderBody2D abstractSliderBody = null; - - public Slider() { - startCircle = SpritePool.getInstance().getSprite("sliderstartcircle"); - endCircle = SpritePool.getInstance().getSprite("sliderendcircle"); - startOverlay = SpritePool.getInstance().getSprite("sliderstartcircleoverlay"); - endOverlay = SpritePool.getInstance().getSprite("sliderendcircleoverlay"); - approachCircle = SpritePool.getInstance().getSprite("approachcircle"); - startArrow = SpritePool.getInstance().getSprite("reversearrow"); - endArrow = SpritePool.getInstance().getSprite("reversearrow"); - } - - public void init(final GameObjectListener listener, final Scene scene, - final PointF pos, final float offset, final float time, final float r, final float g, - final float b, final float scale, int num, final int sound, final int repeats, - final float length, final String data, final TimingPoint timing, - final String customSound, final String tempSound, final boolean isFirstNote, final double realTime) { - init(listener,scene,pos,offset,time,r,g,b,scale,num,sound,repeats,length,data,timing,customSound,tempSound,isFirstNote,realTime,null); - } - - public void init(final GameObjectListener listener, final Scene scene, - final PointF pos, final float offset, final float time, final float r, final float g, - final float b, final float scale, int num, final int sound, final int repeats, - final float length, final String data, final TimingPoint timing, - final String customSound, final String tempSound, final boolean isFirstNote, final double realTime, - SliderPath sliderPath) { - this.listener = listener; - this.scene = scene; - this.timing = timing; - this.scale = scale; - this.pos = pos; - this.length = length; - passedTime = -time; - preTime = time; - if (sliderPath != null){ - path = sliderPath; - } else{ - //if (Config.isUseSuperSlider()) { - // path = SupportSliderPath.parseDroidLinePath(pos, data, length); - //} else { - //fixed negative length silder bug - if (length < 0){ - path = GameHelper.calculatePath(Utils.realToTrackCoords(pos), - data.split("[|]"), 0, offset); - } - else { - path = GameHelper.calculatePath(Utils.realToTrackCoords(pos), - data.split("[|]"), length, offset); - } - //} - } - - num += 1; - if (SkinJson.get().isLimitComboTextLength()) { - num %= 10; - } - number = GameObjectPool.getInstance().getNumber(num); - - - TimingControlPoint timingPoint = GameHelper.controlPoints.getTimingPointAt(realTime); - double speedMultiplier = GameHelper.controlPoints.getDifficultyPointAt(realTime).getSpeedMultiplier(); - - double scoringDistance = GameHelper.getSpeed() * speedMultiplier; - double velocity = scoringDistance / timingPoint.getBeatLength(); - double spanDuration = length / velocity; - //fixed negative length silder bug - if(spanDuration <= 0){ - spanDuration = 0; - } - /*System.out.println("vel " + velocity); - System.out.println("span " + spanDuration); - System.out.println("sm " + speedMultiplier); - System.out.println("l " + length); - System.out.println("sd " + scoringDistance); - System.out.println("bpm " + 60 * 1000 / timingPoint.getBeatLength());*/ - - maxTime = (float) (spanDuration / 1000);//length * timing.getBeatLength() / GameHelper.getSpeed(); - ball = null; - followcircle = null; - repeatCount = repeats; - reverse = false; - startHit = false; - ticksGot = 0; - ticksTotal = 1; - tickTime = 0; - currentTick = 0; - tickIndex = 0; - firstHitAccuracy = 0; - tickSet.clear(); - kiai = GameHelper.isKiai(); - preStageFinish = false; - color.set(r, g, b); - if (!SkinJson.get().isSliderFollowComboColor()) { - circleColor = color; - color = new RGBColor(SkinJson.get().getSliderBodyColor()); - } - - if (soundId.length < repeats + 1) { - soundId = new int[repeats + 1]; - sampleSet = new int[repeats + 1]; - addition = new int[repeats + 1]; - } - - Arrays.fill(soundId, sound); - Arrays.fill(sampleSet, 0); - Arrays.fill(addition, 0); - - if (customSound != null) { - final String pars[] = customSound.split("[|]"); - for (int i = 0; i < soundId.length; i++) { - if (i < pars.length) { - soundId[i] = Integer.parseInt(pars[i]); - } - } - } - - if (!Utils.isEmpty(tempSound)) { - final String pars[] = tempSound.split("[|]"); - for (int i = 0; i < pars.length; i++) { - final String[] group = pars[i].split(":"); - if (i < sampleSet.length) { - sampleSet[i] = Integer.parseInt(group[0]); - } - if (i < addition.length) { - addition[i] = Integer.parseInt(group[1]); - } - } - } - soundIdIndex = 1; - - // Calculating position of top/left corner for sprites and hit radius - final TextureRegion tex = startCircle.getTextureRegion(); - /*final PointF startPos = new PointF(pos.x - tex.getWidth() / 2, pos.y - - tex.getHeight() / 2);*/ - - /* Initializing sprites */ - - // Start circle - //startCircle.setPosition(startPos.x, startPos.y); - startCircle.setScale(scale); - startCircle.setColor(r, g, b); - startCircle.setAlpha(0); - Utils.putSpriteAnchorCenter(pos, startCircle); - - //startOverlay.setPosition(startPos.x, startPos.y); - startOverlay.setScale(scale); - startOverlay.setAlpha(0); - Utils.putSpriteAnchorCenter(pos, startOverlay); - - //approachCircle.setPosition(startPos.x, startPos.y); - approachCircle.setColor(r, g, b); - approachCircle.setScale(scale * 2); - approachCircle.setAlpha(0); - Utils.putSpriteAnchorCenter(pos, approachCircle); - if (GameHelper.isHidden()) { - approachCircle.setVisible(Config.isShowFirstApproachCircle() && isFirstNote); - } - - // End circle - final int lastIndex = path.points.size() - 1; - final PointF endPos = path.points.get(lastIndex); - /*new PointF(path.points.get(lastIndex).x - - tex.getWidth() / 2, path.points.get(lastIndex).y - - tex.getHeight() / 2);*/ - - //endCircle.setPosition(endPos.x, endPos.y); - endCircle.setScale(scale); - endCircle.setColor(r, g, b); - endCircle.setAlpha(0); - Utils.putSpriteAnchorCenter(endPos, endCircle); - - - //endOverlay.setPosition(endPos.x, endPos.y); - endOverlay.setScale(scale); - endOverlay.setAlpha(0); - Utils.putSpriteAnchorCenter(endPos, endOverlay); - - scene.attachChild(startOverlay, 0); - // Repeat arrow at start - if (repeatCount > 2) { - //startArrow.setPosition(startPos.x, startPos.y); - startArrow.setAlpha(0); - startArrow.setScale(scale); - startArrow.setRotation(MathUtils.radToDeg(Utils.direction( - path.points.get(0), path.points.get(1)))); - Utils.putSpriteAnchorCenter(pos, startArrow); - scene.attachChild(startArrow, 0); - } - if (GameHelper.isHidden()) { - number.init(scene, pos, scale, - new SequenceEntityModifier(new FadeInModifier(time / 4 * GameHelper.getTimeMultiplier()), - new FadeOutModifier(time / 4 * GameHelper.getTimeMultiplier()))); - } else { - number.init(scene, pos, scale, new FadeInModifier( - time / 2 * GameHelper.getTimeMultiplier())); - } - scene.attachChild(startCircle, 0); - scene.attachChild(approachCircle); - scene.attachChild(endOverlay, 0); - // Repeat arrow at end - if (repeatCount > 1) { - //endArrow.setPosition(endPos.x, endPos.y); - endArrow.setAlpha(0); - endArrow.setScale(scale); - endArrow.setRotation(MathUtils.radToDeg(Utils.direction( - path.points.get(lastIndex), path.points.get(lastIndex - 1)))); - Utils.putSpriteAnchorCenter(endPos, endArrow); - scene.attachChild(endArrow, 0); - } - scene.attachChild(endCircle, 0); - - // Ticks - // Try to fix incorrect slider tick count bug - tickInterval = timing.getBeatLength() * speedMultiplier; - int tickCount = (int) (maxTime * GameHelper.getTickRate() / tickInterval); - if(Double.isNaN(tickInterval) || tickInterval < GameHelper.getSliderTickLength() / 1000){ - tickCount = 0; - } - if ((maxTime * GameHelper.getTickRate() / tickInterval) - - (int) (maxTime * GameHelper.getTickRate() / tickInterval) < 0.001f){ - tickCount--; - } - ticks.clear(); - for (int i = 1; i <= tickCount; i++) { - final Sprite tick = SpritePool.getInstance().getCenteredSprite( - "sliderscorepoint", - getPercentPosition((float)(i * tickInterval - / (maxTime * GameHelper.getTickRate())), null)); - tick.setScale(scale); - tick.setAlpha(0); - ticks.add(tick); - scene.attachChild(tick, 0); - } - - // Slider track - if (Config.isUseSuperSlider()) { - superPath = new LinePath(); - for (PointF p : path.points) { - superPath.add(new Vec2(p.x, p.y)); - } - superPath.measure(); - superPath.bufferLength(sliderLength = path.length.get(path.length.size() - 1)); - superPath = superPath.fitToLinePath(); - superPath.measure(); - - abstractSliderBody = new SliderBody2D(superPath); - abstractSliderBody.setBodyWidth( - Utils.toRes(SkinJson.get().getSliderBodyWidth() - SkinJson.get().getSliderBorderWidth()) - * scale); - abstractSliderBody.setBorderWidth(Utils.toRes(SkinJson.get().getSliderBodyWidth()) * scale); - abstractSliderBody.setSliderBodyBaseAlpha(SkinJson.get().getSliderBodyBaseAlpha()); - - if (SkinJson.get().isSliderHintEnable()) { - if (length > SkinJson.get().getSliderHintShowMinLength()) { - abstractSliderBody.setEnableHint(true); - abstractSliderBody.setHintAlpha(SkinJson.get().getSliderHintAlpha()); - abstractSliderBody.setHintWidth(Utils.toRes(SkinJson.get().getSliderHintWidth())); - RGBColor hintColor = SkinJson.get().getSliderHintColor(); - if (hintColor != null) { - abstractSliderBody.setHintColor(hintColor.r(), hintColor.g(), hintColor.b()); - } else { - abstractSliderBody.setHintColor(color.r(), color.g(), color.b()); - } - } - } - - abstractSliderBody.applyToScene(scene, Config.isComplexAnimations()); - abstractSliderBody.setBodyColor(color.r(), color.g(), color.b()); - RGBColor scolor = GameHelper.getSliderColor(); - abstractSliderBody.setBorderColor(scolor.r(), scolor.g(), scolor.b()); - - } else { - initLowPolyTrack(); - } -// if (Config.isLowpolySliders()) { -// initLowPolyTrack(); -// } else { -// initTrack(); -// } - } - - private void initTrack() { - final TextureRegion tex = startCircle.getTextureRegion(); - final PointF startPos = new PointF(path.points.get(0).x - - tex.getWidth() / 2, path.points.get(0).y - tex.getHeight() - / 2); - trackSprites.clear(); - group = new SpriteGroup(ResourceManager.getInstance() - .getTexture("::track").getTexture(), path.points.size()); - group.setColor(color.r(), color.g(), color.b()); - for (int i = 0; i < path.points.size(); i++) { - final PointF p = path.points.get(i); - final Sprite sprite = SpritePool.getInstance().getSprite("::track"); - if (Config.isComplexAnimations() == false) { - sprite.setPosition(p.x - sprite.getWidth() / 2, - p.y - sprite.getHeight() / 2); - } else { - sprite.setPosition(startPos.x, startPos.y); - } - sprite.setScale(scale); - sprite.setColor(color.r(), color.g(), color.b()); - sprite.setAlpha(1); - if (i < path.points.size() - 1) { - sprite.setRotation(MathUtils.radToDeg(Utils.direction(p, - path.points.get(i + 1)))); - } else if (i > 0) { - sprite.setRotation(MathUtils.radToDeg(Utils.direction( - path.points.get(i - 1), p))); - } - trackSprites.add(sprite); - group.attachChild(sprite); - // scene.attachChild(sprite, 0); - } - scene.attachChild(group, 0); - - // Slider track border - if (Config.isSliderBorders()) { - trackBorders.clear(); - borderGroup = new SpriteGroup(ResourceManager.getInstance() - .getTexture("::trackborder").getTexture(), - path.points.size()); - for (final PointF p : path.points) { - final Sprite sprite = SpritePool.getInstance().getSprite( - "::trackborder"); - if (Config.isComplexAnimations() == false) { - sprite.setPosition(p.x - sprite.getWidth() / 2, p.y - - sprite.getHeight() / 2); - } else { - sprite.setPosition(startPos.x, startPos.y); - } - sprite.setScale(scale); - sprite.setAlpha(1); - trackBorders.add(sprite); - borderGroup.attachChild(sprite); - } - final RGBColor scolor = GameHelper.getSliderColor(); - borderGroup.setColor(scolor.r(), scolor.g(), scolor.b()); - scene.attachChild(borderGroup, 0); - } - } - - private void initLowPolyTrack() { - final TextureRegion tex = startCircle.getTextureRegion(); - final PointF startPos = new PointF(path.points.get(0).x - - tex.getWidth() / 2, path.points.get(0).y - tex.getHeight() - / 2); - trackPolyVerts = createPolygon(Utils.toRes(54) * scale); - float verts[]; - if (Config.isComplexAnimations()) { - verts = new float[trackPolyVerts.length]; - for (int i = 0; i < verts.length; i++) { - verts[i] = trackPolyVerts[(i % 2)]; - } - } else { - verts = trackPolyVerts; - trackPolyVerts = null; - } - trackPoly = new Polygon(0, 0, verts); - trackPoly.setColor(color.r(), color.g(), color.b()); -// trackPoly.setAlpha(0.5f); - scene.attachChild(trackPoly, 0); - - trackBoundaries.clear(); - for (final Integer i : path.boundIndexes) { - final Sprite sprite = SpritePool.getInstance() - .getSprite("::track2"); - if (Config.isComplexAnimations() == false) { - sprite.setPosition( - path.points.get(i).x - sprite.getWidth() / 2, - path.points.get(i).y - sprite.getHeight() / 2); - } else { - sprite.setPosition(startPos.x, startPos.y); - } - sprite.setScale(scale); - sprite.setColor(color.r(), color.g(), color.b()); - sprite.setAlpha(0.7f); - scene.attachChild(sprite, 0); - trackBoundaries.add(sprite); - } - - if (Config.isSliderBorders()) { - final RGBColor scolor = GameHelper.getSliderColor(); - - borderPolyVerts = createPolygon(Utils.toRes(57) - * scale); - if (Config.isComplexAnimations()) { - verts = new float[borderPolyVerts.length]; - for (int i = 0; i < verts.length; i++) { - verts[i] = borderPolyVerts[(i % 2)]; - } - } else { - verts = borderPolyVerts; - borderPolyVerts = null; - } - borderPoly = new Polygon(0, 0, verts); - borderPoly.setColor(scolor.r(), scolor.g(), scolor.b()); -// borderPoly.setAlpha(0.1f); - scene.attachChild(borderPoly, 0); - -// trackBorders.clear(); -// for (final Integer i : path.boundIndexes) { -// final Sprite sprite = SpritePool.getInstance().getSprite( -// "::trackborder"); -// if (Config.isComplexAnimations() == false) { -// sprite.setPosition(path.points.get(i).x - sprite.getWidth() -// / 2, path.points.get(i).y - sprite.getHeight() / 2); -// } else { -// sprite.setPosition(startPos.x, startPos.y); -// } -// sprite.setScale(scale); -// sprite.setColor(scolor.r(), scolor.g(), scolor.b()); -// sprite.setAlpha(0.1f); -// scene.attachChild(sprite, 0); -// trackBorders.add(sprite); -// } - } - } - - private float[] createPolygon(final float size) { - int vi = 0; - - final LinkedList points = new LinkedList(); - for (int i = 0; i < path.points.size(); i++) { - points.add(getPointPos(i, -1, size)); - points.add(getPointPos(i, 1, size)); - } - - final ArrayList addPoints = new ArrayList(); - final ListIterator iterator = points.listIterator(); - final float sqrDist = Utils - .sqr(((scale * Constants.HIGH_SLIDER_STEP)) - 1); - for (int i = 0; i < points.size(); i++) { - if (i + 2 >= points.size()) { - break; - } - if (iterator.hasNext() == false) { - break; - } - final PointF p1 = iterator.next(); - if (iterator.hasNext() == false) { - break; - } - iterator.next(); - if (iterator.hasNext() == false) { - break; - } - final PointF p2 = iterator.next(); - iterator.previous(); - iterator.previous(); - - if (addPoints.isEmpty() == false) { - for (int j = 0; j < addPoints.size(); j++) { - iterator.add(addPoints.get(j)); - iterator.add(Utils.inter(p1, p2, (j + 1) - / (float) (addPoints.size() + 1))); - } - addPoints.clear(); - } - - int numPoints = (int) (Utils.squaredDistance(p1, p2) / sqrDist); - if (numPoints < 1) { - continue; - } - numPoints = (int) Math.sqrt(numPoints); - - for (int j = 0; j < numPoints; j++) { - final float t = (j + 1) / (float) (numPoints + 1); - final PointF p = Utils.inter(p1, p2, t); - final int idx = i / 2; - final float dx = path.points.get(idx).x * (1 - t) - + path.points.get(idx + 1).x * t; - final float dy = path.points.get(idx).y * (1 - t) - + path.points.get(idx + 1).y * t; - p.x -= dx; - p.y -= dy; - float len = Utils.length(p); - len = size / len; - if (Math.abs(len - 1) < 0.025f) { - continue; - } - p.x *= len; - p.y *= len; - p.x += dx; - p.y += dy; - - addPoints.add(p); - } - } - - final float verts[] = new float[points.size() * 2]; - for (final PointF p : points) { - verts[vi++] = p.x; - verts[vi++] = p.y; - } - return verts; - } - - private PointF getPercentPosition(final float percentage, final Float angle) { - if (percentage >= 1) { - tmpPoint.set(path.points.get(path.points.size() - 1).x, - path.points.get(path.points.size() - 1).y); - return tmpPoint; - } else if (percentage <= 0) { - if (angle != null) { - ballAngle = MathUtils.radToDeg(Utils.direction( - path.points.get(1), path.points.get(0))); - } - tmpPoint.set(path.points.get(0).x, path.points.get(0).y); - return tmpPoint; - } - - if (path.length.size() == 1) { - final PointF p = tmpPoint; - p.x = path.points.get(0).x * percentage + path.points.get(1).x - * (1 - percentage); - p.y = path.points.get(0).y * percentage + path.points.get(1).y - * (1 - percentage); - return p; - } - int left = 0, right = path.length.size(); - int index = right / 2; - final float realLength = percentage - * path.length.get(path.length.size() - 1); - while (left < right) { - if (index < path.length.size() - 1 - && path.length.get(index + 1) < realLength) { - left = index; - } else if (path.length.get(index) >= realLength) { - right = index; - } else { - break; - } - index = (right + left) / 2; - } - - float addlength = realLength - path.length.get(index); - addlength /= path.length.get(index) - path.length.get(index + 1); - final PointF p = tmpPoint; - p.x = path.points.get(index).x * addlength - + path.points.get(index + 1).x * (1 - addlength); - p.y = path.points.get(index).y * addlength - + path.points.get(index + 1).y * (1 - addlength); - if (angle != null) { - // Well, i should just add flag "save angle" instead of passing - // PointF, but... screw it - ballAngle = MathUtils.radToDeg(Utils.direction( - path.points.get(index), path.points.get(index + 1))); - } - return p; - } - - private PointF getPointPos(final int i, final int sign, final float size) { - int j = i; - if (j + 1 >= path.points.size()) { - j = path.points.size() - 2; - } - float nx = -path.points.get(j + 1).y + path.points.get(j).y; - float ny = path.points.get(j + 1).x - path.points.get(j).x; - if (sign < 0) { - nx *= -1; - ny *= -1; - } - final PointF p = new PointF(); - p.x = path.points.get(i).x; - p.y = path.points.get(i).y; - final float nlen = (float) Math.sqrt(nx * nx + ny * ny); - if (nlen > 0) { - nx /= nlen; - ny /= nlen; - nx *= size; - ny *= size; - p.x += nx; - p.y += ny; - } - return p; - } - - private void removeFromScene() { - if (scene == null) { - return; - } - // Detach all objects - if (group != null) { - group.detachSelf(); - } - if (trackPoly != null) { - trackPoly.detachSelf(); - } - if (borderPoly != null) { - borderPoly.detachSelf(); - } - if (borderGroup != null) { - borderGroup.detachSelf(); - } - if (body != null) { - body.detachSelf(); - } - if (border != null) { - border.detachSelf(); - } - if (abstractSliderBody != null) { - abstractSliderBody.removeFromScene(scene); - } - startCircle.detachSelf(); - endCircle.detachSelf(); - startOverlay.detachSelf(); - endOverlay.detachSelf(); - approachCircle.detachSelf(); - startArrow.detachSelf(); - endArrow.detachSelf(); - ball.detachSelf(); - followcircle.detachSelf(); - SpritePool.getInstance().putAnimSprite("sliderb", ball); - SpritePool.getInstance().putSprite("sliderfollowcircle", followcircle); - for (final Sprite sp : trackSprites) { - sp.detachSelf(); - SpritePool.getInstance().putSprite("::track", sp); - } - for (final Sprite sp : trackBoundaries) { - sp.detachSelf(); - SpritePool.getInstance().putSprite("::track2", sp); - } - trackBoundaries.clear(); - for (final Sprite sp : trackBorders) { - sp.detachSelf(); - SpritePool.getInstance().putSprite("::trackborder", sp); - } - for (final Sprite sp : ticks) { - sp.detachSelf(); - SpritePool.getInstance().putSprite("sliderscorepoint", sp); - } - listener.removeObject(this); - // Put this and number into pool - GameHelper.putPath(path); - GameObjectPool.getInstance().putSlider(this); - GameObjectPool.getInstance().putNumber(number); - scene = null; - isHiddenFadeOutActive = false; - } - - private void over() { - //int type = repeatCount > 0 ? GameObjectListener.SLIDER_REPEAT : GameObjectListener.SLIDER_END; - repeatCount--; - // If alpha > 0 means cursor in slider ball bounds - if (followcircle.getAlpha() > 0 && replayData == null || - replayData != null && replayData.tickSet.get(tickIndex)) { - if (soundIdIndex < soundId.length) - Utils.playHitSound(listener, soundId[soundIdIndex], - sampleSet[soundIdIndex], addition[soundIdIndex]); - ticksGot++; - tickSet.set(tickIndex++, true); - if (repeatCount > 0) { - listener.onSliderHit(id, 30, null, - path.points.get(reverse ? 0 : path.points.size() - 1), - false, color, GameObjectListener.SLIDER_REPEAT); - } - } else { - tickSet.set(tickIndex++, false); - if (repeatCount > 0) { - listener.onSliderHit(id, -1, null, - path.points.get(reverse ? 0 : path.points.size() - 1), - false, color, GameObjectListener.SLIDER_REPEAT); - } - } - soundIdIndex++; - ticksTotal++; - // If slider has more repeats - if (repeatCount > 0) { - reverse = !reverse; - passedTime -= maxTime; - tickTime = passedTime; - ball.setFlippedHorizontal(reverse); - // Restore ticks - for (final Sprite sp : ticks) { - sp.setAlpha(1); - } - currentTick = reverse ? ticks.size() - 1 : 0; - // Setting visibility of repeat arrows - if (reverse && repeatCount <= 2) { - endArrow.setAlpha(0); - } - - if (reverse && repeatCount > 1) { - startArrow.setAlpha(1); - } - - if (!reverse && repeatCount <= 2) { - startArrow.setAlpha(0); - } - //if (repeatCount > 1) { - ((GameScene) listener).onSliderReverse( - path.points.get(!reverse ? 0 : path.points.size() - 1), - reverse ? endArrow.getRotation() : startArrow.getRotation(), - color); - //} - // and go on... - if (passedTime >= maxTime){ - over(); - } - return; - } - // Calculating score - int score = 0; - if (ticksGot > 0) { - score = 50; - } - if (ticksGot >= ticksTotal / 2) { - score = 100; - } - if (ticksGot >= ticksTotal) { - score = 300; - } - // If slider was in reverse mode, we should swap start and end points - if (reverse) { - Slider.this.listener.onSliderHit(id, score, - path.points.get(path.points.size() - 1), - path.points.get(0), endsCombo, color, GameObjectListener.SLIDER_END); - } else { - Slider.this.listener.onSliderHit(id, score, path.points.get(0), - path.points.get(path.points.size() - 1), endsCombo, color, GameObjectListener.SLIDER_END); - } - if(!startHit){ - firstHitAccuracy = (int) (GameHelper.getDifficultyHelper().hitWindowFor50(GameHelper.getDifficulty()) * 1000 + 13); - } - listener.onSliderEnd(id, firstHitAccuracy, tickSet); - // Remove slider from scene - SyncTaskManager.getInstance().run(new Runnable() { - - - public void run() { - removeFromScene(); - } - }); - } - - private float getPercentPositionOnTrack(final float[] verts, - final float percent, final int i) { - if (i <= 3) { - return verts[i]; - } - if (percent >= 1) { - return verts[i]; - } - if (percent <= 0) { - return verts[i % 4]; - } - float t = percent * (i / 4); - int index = (int) (t); - t -= index; - index = index * 4 + i % 4; - return verts[index] + (verts[index + 4] - verts[index]) * t; - } - - private boolean isHit() { - float radius = Utils.sqr(Utils.toRes(64) * scale); - for (int i = 0; i < listener.getCursorsCount(); i++) { - if (listener.isMousePressed(this, i) - && Utils.squaredDistance(path.points.get(0), listener.getMousePos(i)) <= radius) { - return true; - } else if (GameHelper.isAutopilotMod() && listener.isMousePressed(this, i)) { - return true; - } else if (GameHelper.isRelaxMod() && passedTime >= 0 && - Utils.squaredDistance(path.points.get(0), listener.getMousePos(i)) <= radius) { - return true; - } - } - return false; - } - - - @Override - public void update(final float dt) { - - if (scene == null) { - return; - } - passedTime += dt; - - if (startHit == false) // If we didn't get start hit(click) - { - // If it's too late, mark this hit missing - if (passedTime > GameHelper.getDifficultyHelper().hitWindowFor50(GameHelper.getDifficulty())) { - startHit = true; - listener.onSliderHit(id, -1, null, path.points.get(0), false, color, GameObjectListener.SLIDER_START); - firstHitAccuracy = (int) (passedTime * 1000); - } else if (autoPlay && passedTime >= 0) { - startHit = true; - Utils.playHitSound(listener, soundId[0], sampleSet[0], addition[0]); - ticksGot++; - listener.onSliderHit(id, 30, null, path.points.get(0), false, color, GameObjectListener.SLIDER_START); - } else if (replayData != null && - Math.abs(replayData.accuracy / 1000f) <= GameHelper.getDifficultyHelper().hitWindowFor50(GameHelper.getDifficulty()) && - passedTime + dt / 2 > replayData.accuracy / 1000f) { - startHit = true; - Utils.playHitSound(listener, soundId[0], sampleSet[0], addition[0]); - ticksGot++; - listener.onSliderHit(id, 30, null, path.points.get(0), false, color, GameObjectListener.SLIDER_START); - } else { - if (isHit() && -passedTime < GameHelper.getDifficultyHelper().hitWindowFor50(GameHelper.getDifficulty())) // if - // we - // clicked - { - listener.registerAccuracy(passedTime); - startHit = true; - Utils.playHitSound(listener, soundId[0], sampleSet[0], addition[0]); - ticksGot++; - firstHitAccuracy = (int) (passedTime * 1000); - listener.onSliderHit(id, 30, null, path.points.get(0), - false, color, GameObjectListener.SLIDER_START); - } - } - } - - if (GameHelper.isKiai()) { - final float kiaiModifier = Math - .max(0, - 1 - GameHelper.getGlobalTime() - / GameHelper.getKiaiTickLength()) * 0.50f; - - final float r = Math.min(1, color.r() + (1 - color.r()) - * kiaiModifier); - final float g = Math.min(1, color.g() + (1 - color.g()) - * kiaiModifier); - final float b = Math.min(1, color.b() + (1 - color.b()) - * kiaiModifier); - kiai = true; - startCircle.setColor(r, g, b); - endCircle.setColor(r, g, b); - if (group != null) { - group.setColor(r, g, b); - } - if (trackPoly != null) { - trackPoly.setColor(r, g, b); - } - if (body != null) { - body.setColor(r, g, b); - } - for (final Sprite sp : trackBoundaries) { - sp.setColor(r, g, b); - } - } else if (kiai == true) { - startCircle.setColor(color.r(), color.g(), color.b()); - endCircle.setColor(color.r(), color.g(), color.b()); - if (group != null) { - group.setColor(color.r(), color.g(), color.b()); - } - if (trackPoly != null) { - trackPoly.setColor(color.r(), color.g(), color.b()); - } - kiai = false; - for (final Sprite sp : trackBoundaries) { - sp.setColor(color.r(), color.g(), color.b()); - } - } - - if (passedTime < 0) // we at approach time - { - float percentage = 1 + passedTime / preTime; - // calculating size of approach circle - approachCircle.setScale(scale - * (1 + 2f * (1 - percentage))); - if (startHit == true) { - approachCircle.setAlpha(0); - } - if (percentage <= 0.5f) { - // Following core doing a very cute show animation ^_^" - percentage = Math.min(1, percentage * 2); - if (startHit == false) { - approachCircle.setAlpha(percentage); - } - - - startCircle.setAlpha(percentage); - startOverlay.setAlpha(percentage); - endCircle.setAlpha(percentage); - endOverlay.setAlpha(percentage); - for (int i = 0; i < ticks.size(); i++) { - if (percentage > (float) (i + 1) / ticks.size()) { - ticks.get(i).setAlpha(1); - } - } - if (repeatCount > 1) { - endArrow.setAlpha(percentage); - } - - if (Config.isComplexAnimations()) { - //final float offset = startCircle.getWidth() / 2; - if (Config.isUseSuperSlider()) { - - float l = superPath.getMeasurer().maxLength() * percentage; - - abstractSliderBody.setEndLength(l); - abstractSliderBody.onUpdate(); - - } else { - tmpPoint = getPercentPosition(percentage, null); -// if (Config.isLowpolySliders()) { - for (int i = 0; i < path.boundIndexes.size(); i++) { - final float ppos = path.boundIndexes.get(i) - / (float) path.points.size(); - PointF tpoint = tmpPoint; - if (percentage >= ppos) { - tpoint = path.points.get(path.boundIndexes - .get(i)); - } - Utils.putSpriteAnchorCenter(tpoint, trackBoundaries.get(i)); - /*trackBoundaries.get(i).setPosition( - tpoint.x - offset, tpoint.y - offset);*/ - if (trackBorders.isEmpty() == false) { - Utils.putSpriteAnchorCenter(tpoint, trackBorders.get(i)); - /*trackBorders.get(i).setPosition( - trackBoundaries.get(i));*/ - } - } -// } else { -// for (int i = 0; i < trackSprites.size(); i++) { -// tmpPoint = getPercentPosition(percentage * i -// / path.points.size(), null); -// trackSprites.get(i).setPosition( -// tmpPoint.x - offset, tmpPoint.y - offset); -// if (trackBorders.isEmpty() == false) { -// trackBorders.get(i).setPosition( -// trackSprites.get(i)); -// } -// } -// } - //endOverlay.setPosition(endCircle); - //endArrow.setPosition(endCircle); - if (trackPolyVerts != null) { - final float verts[] = trackPoly.getVertices(); - for (int i = 0; i < verts.length; i++) { - verts[i] = getPercentPositionOnTrack( - trackPolyVerts, percentage, i);// trackPolyVerts[i - // % 2] + - // (trackPolyVerts[i] - // - - // trackPolyVerts[i - // % 2]) * - // percentage; - } - trackPoly.updateShape(); - } - if (borderPolyVerts != null) { - final float verts[] = borderPoly.getVertices(); - for (int i = 0; i < verts.length; i++) { - verts[i] = getPercentPositionOnTrack( - borderPolyVerts, percentage, i); - // verts[i] = borderPolyVerts[i % 2] + - // (trackPolyVerts[i] - borderPolyVerts[i % 2]) * - // percentage; - } - borderPoly.updateShape(); - } - } - - tmpPoint = getPercentPosition(percentage, null); - - Utils.putSpriteAnchorCenter(tmpPoint, endCircle); - Utils.putSpriteAnchorCenter(tmpPoint, endOverlay); - Utils.putSpriteAnchorCenter(tmpPoint, endArrow); - } - } else if (percentage - dt / preTime <= 0.5f) { - // Setting up positions of slider parts - approachCircle.setAlpha(1); - startCircle.setAlpha(1); - startOverlay.setAlpha(1); - endCircle.setAlpha(1); - endOverlay.setAlpha(1); - for (final Sprite sp : ticks) { - sp.setAlpha(1); - } - if (repeatCount > 1) { - endArrow.setAlpha(1); - } - if (Config.isComplexAnimations()) { - final float offset = startCircle.getWidth() / 2; - if (Config.isUseSuperSlider()) { - if (!preStageFinish) { - abstractSliderBody.setEndLength(superPath.getMeasurer().maxLength()); - abstractSliderBody.onUpdate(); - preStageFinish = true; - } - - } else { - - for (int i = 0; i < path.boundIndexes.size(); i++) { - tmpPoint = path.points - .get(path.boundIndexes.get(i)); - trackBoundaries.get(i).setPosition( - tmpPoint.x - offset, tmpPoint.y - offset); - if (trackBorders.isEmpty() == false) { - trackBorders.get(i).setPosition( - trackBoundaries.get(i)); - } - } - if (trackPolyVerts != null) { - final float verts[] = trackPoly.getVertices(); - for (int i = 0; i < verts.length; i++) { - verts[i] = trackPolyVerts[i]; - } - trackPoly.updateShape(); - trackPolyVerts = null; - } - if (borderPolyVerts != null) { - final float verts[] = borderPoly.getVertices(); - for (int i = 0; i < verts.length; i++) { - verts[i] = borderPolyVerts[i]; - } - borderPoly.updateShape(); - borderPolyVerts = null; - } - } - - tmpPoint = path.points.get(path.points.size() - 1); - - if (/*Config.isLowpolySliders() - && */trackBoundaries.isEmpty() == false) { - endCircle.setPosition(trackBoundaries - .get(trackBoundaries.size() - 1)); - } else { - Utils.putSpriteAnchorCenter(tmpPoint, endCircle); - } - Utils.putSpriteAnchorCenter(tmpPoint, endOverlay); - Utils.putSpriteAnchorCenter(tmpPoint, endArrow); - } - - } - return; - } else { - if (Config.isUseSuperSlider()) { - startCircle.setAlpha(0); - startOverlay.setAlpha(0); - } - - // Slider body, border, and hint gradually fade in Hidden mod - if (GameHelper.isHidden()) { - hiddenFadeOut(); - } - } - - if (ball == null) // if ball still don't exists - { - number.detach(true); - approachCircle.setAlpha(0); - - ball = SpritePool.getInstance().getAnimSprite("sliderb", - SkinManager.getFrames("sliderb")); - ball.setFps(0.1f * GameHelper.getSpeed() * scale - / timing.getBeatLength()); - ball.setScale(scale); - ball.setFlippedHorizontal(false); - - followcircle = SpritePool.getInstance().getSprite( - "sliderfollowcircle"); - followcircle.setScale(scale); - - scene.attachChild(ball); - scene.attachChild(followcircle); - } - // Ball positiong - final float percentage = passedTime / maxTime; - final PointF ballpos = getPercentPosition(reverse ? 1 - percentage - : percentage, ballAngle); - // Calculating if cursor in follow circle bounds - final float radius = Utils.toRes(128) * scale; - boolean inRadius = false; - for (int i = 0; i < listener.getCursorsCount(); i++) { - if (autoPlay == false - && (listener.isMouseDown(i) == false || Utils - .squaredDistance(listener.getMousePos(i), ballpos) > radius - * radius)) { - } else { - inRadius = true; - break; - } - if (GameHelper.isAutopilotMod() && listener.isMouseDown(i)) - inRadius = true; - } - followcircle.setAlpha(inRadius ? 1 : 0); - listener.onTrackingSliders(inRadius); - - tickTime += dt; - //try fixed big followcircle bug - float fcscale = scale * (1.1f - 0.1f * tickTime * GameHelper.getTickRate() / timing.getBeatLength()); - if (fcscale <= scale * 1.1f && fcscale >= scale * -1.1f){ - followcircle.setScale(fcscale); - } - // Some magic with slider ticks. If it'll crash it's not my fault ^_^" - while (ticks.size() > 0 && percentage < 1 - 0.02f / maxTime - && tickTime * GameHelper.getTickRate() > tickInterval) { - tickTime -= tickInterval / GameHelper.getTickRate(); - if (followcircle.getAlpha() > 0 && replayData == null || - replayData != null && replayData.tickSet.get(tickIndex)) { - Utils.playHitSound(listener, 16); - listener.onSliderHit(id, 10, null, ballpos, false, color, GameObjectListener.SLIDER_TICK); - ticksGot++; - tickSet.set(tickIndex++, true); - } else { - listener.onSliderHit(id, -1, null, ballpos, false, color, GameObjectListener.SLIDER_TICK); - tickSet.set(tickIndex++, false); - } - ticks.get(currentTick).setAlpha(0); - if (reverse && currentTick > 0) { - currentTick--; - } else if (!reverse && currentTick < ticks.size() - 1) { - currentTick++; - } - ticksTotal++; - } - // Setting position of ball and follow circle - followcircle.setPosition(ballpos.x - followcircle.getWidth() / 2, - ballpos.y - followcircle.getHeight() / 2); - ball.setPosition(ballpos.x - ball.getWidth() / 2, - ballpos.y - ball.getHeight() / 2); - ball.setRotation(ballAngle); - - if (GameHelper.isAuto() || GameHelper.isAutopilotMod()) { - listener.updateAutoBasedPos(ballpos.x, ballpos.y); - } - - // If we got 100% time, finishing slider - if (percentage >= 1) { - over(); - } - } - - private void hiddenFadeOut() { - if (isHiddenFadeOutActive) { - return; - } - isHiddenFadeOutActive = true; - final float realDuration = maxTime * repeatCount * GameHelper.getTimeMultiplier(); - if (group != null) { - group.registerEntityModifier(new AlphaModifier(realDuration, - group.getAlpha(), 0)); - } - if (trackPoly != null) { - trackPoly.registerEntityModifier(new AlphaModifier(realDuration, - trackPoly.getAlpha(), 0)); - } - if (borderPoly != null) { - borderPoly.registerEntityModifier(new AlphaModifier(realDuration, - borderPoly.getAlpha(), 0)); - } - if (borderGroup != null) { - borderGroup.registerEntityModifier(new AlphaModifier(realDuration, - borderGroup.getAlpha(), 0)); - } - if (body != null) { - body.registerEntityModifier(new AlphaModifier(realDuration, - body.getAlpha(), 0)); - } - if (border != null) { - border.registerEntityModifier(new AlphaModifier(realDuration, - border.getAlpha(), 0)); - } - for (final Sprite sp : trackSprites) { - sp.registerEntityModifier(new AlphaModifier(realDuration, - sp.getAlpha(), 0)); - } - for (final Sprite sp : trackBorders) { - sp.registerEntityModifier(new AlphaModifier(realDuration, - sp.getAlpha(), 0)); - } - for (final Sprite sp : trackBoundaries) { - sp.registerEntityModifier(new AlphaModifier(realDuration, - sp.getAlpha(), 0)); - } - if (abstractSliderBody != null) { - abstractSliderBody.fadeOut(realDuration); - } - } - - @Override - public void tryHit(final float dt){ - if (startHit == false) // If we didn't get start hit(click) - { - if (isHit() && -passedTime < GameHelper.getDifficultyHelper().hitWindowFor50(GameHelper.getDifficulty())) // if - // we - // clicked - { - listener.registerAccuracy(passedTime); - startHit = true; - Utils.playHitSound(listener, soundId[0], sampleSet[0], addition[0]); - ticksGot++; - firstHitAccuracy = (int) (passedTime * 1000); - listener.onSliderHit(id, 30, null, path.points.get(0), - false, color, GameObjectListener.SLIDER_START); - } - if (passedTime < 0) // we at approach time - { - if (startHit == true) { - approachCircle.setAlpha(0); - } - } - } - } + private final Sprite startCircle, endCircle; + private final Sprite startOverlay, endOverlay; + private final Sprite approachCircle; + private final Sprite startArrow, endArrow; + private final ArrayList trackSprites = new ArrayList(); + private final ArrayList trackBorders = new ArrayList(); + private final ArrayList ticks = new ArrayList(); + private final ArrayList trackBoundaries = new ArrayList(); + private Scene scene; + private GameObjectListener listener; + private TimingPoint timing; + private CircleNumber number; + private SliderPath path; + private float passedTime; + private float preTime; + private float tickTime; + private float maxTime; + private float scale; + private float length; + private int repeatCount; + private boolean reverse; + private int[] soundId = new int[3]; + private int[] sampleSet = new int[3]; + private int[] addition = new int[3]; + + private int soundIdIndex; + private int ticksGot; + private int ticksTotal; + private int currentTick; + private double tickInterval; + + private AnimSprite ball; + private Sprite followcircle; + + private PointF tmpPoint = new PointF(); + private Float ballAngle = new Float(0); + private SpriteGroup group = null; + private SpriteGroup borderGroup = null; + private Polygon trackPoly = null; + private Polygon borderPoly = null; + private float trackPolyVerts[] = null; + private float borderPolyVerts[] = null; + + private boolean kiai; + private boolean isHiddenFadeOutActive = false; + private RGBColor color = new RGBColor(); + private RGBColor circleColor = color; + + //for replay + private int firstHitAccuracy; + private BitSet tickSet = new BitSet(); + private int tickIndex; + + private TrianglePack body = null, border = null; + private LinePath superPath = null; + private float sliderLength; + private boolean preStageFinish = false; + + private SliderBody2D abstractSliderBody = null; + + public Slider() { + startCircle = SpritePool.getInstance().getSprite("sliderstartcircle"); + endCircle = SpritePool.getInstance().getSprite("sliderendcircle"); + startOverlay = SpritePool.getInstance().getSprite("sliderstartcircleoverlay"); + endOverlay = SpritePool.getInstance().getSprite("sliderendcircleoverlay"); + approachCircle = SpritePool.getInstance().getSprite("approachcircle"); + startArrow = SpritePool.getInstance().getSprite("reversearrow"); + endArrow = SpritePool.getInstance().getSprite("reversearrow"); + } + + public void init(final GameObjectListener listener, final Scene scene, + final PointF pos, final float offset, final float time, final float r, final float g, + final float b, final float scale, int num, final int sound, final int repeats, + final float length, final String data, final TimingPoint timing, + final String customSound, final String tempSound, final boolean isFirstNote, final double realTime) { + init(listener,scene,pos,offset,time,r,g,b,scale,num,sound,repeats,length,data,timing,customSound,tempSound,isFirstNote,realTime,null); + } + + public void init(final GameObjectListener listener, final Scene scene, + final PointF pos, final float offset, final float time, final float r, final float g, + final float b, final float scale, int num, final int sound, final int repeats, + final float length, final String data, final TimingPoint timing, + final String customSound, final String tempSound, final boolean isFirstNote, final double realTime, + SliderPath sliderPath) { + this.listener = listener; + this.scene = scene; + this.timing = timing; + this.scale = scale; + this.pos = pos; + this.length = length; + passedTime = -time; + preTime = time; + if (sliderPath != null){ + path = sliderPath; + } else{ + //if (Config.isUseSuperSlider()) { + // path = SupportSliderPath.parseDroidLinePath(pos, data, length); + //} else { + //fixed negative length silder bug + if (length < 0){ + path = GameHelper.calculatePath(Utils.realToTrackCoords(pos), + data.split("[|]"), 0, offset); + } + else { + path = GameHelper.calculatePath(Utils.realToTrackCoords(pos), + data.split("[|]"), length, offset); + } + //} + } + + num += 1; + if (SkinJson.get().isLimitComboTextLength()) { + num %= 10; + } + number = GameObjectPool.getInstance().getNumber(num); + + + TimingControlPoint timingPoint = GameHelper.controlPoints.getTimingPointAt(realTime); + double speedMultiplier = GameHelper.controlPoints.getDifficultyPointAt(realTime).getSpeedMultiplier(); + + double scoringDistance = GameHelper.getSpeed() * speedMultiplier; + double velocity = scoringDistance / timingPoint.getBeatLength(); + double spanDuration = length / velocity; + //fixed negative length silder bug + if(spanDuration <= 0){ + spanDuration = 0; + } + /*System.out.println("vel " + velocity); + System.out.println("span " + spanDuration); + System.out.println("sm " + speedMultiplier); + System.out.println("l " + length); + System.out.println("sd " + scoringDistance); + System.out.println("bpm " + 60 * 1000 / timingPoint.getBeatLength());*/ + + maxTime = (float) (spanDuration / 1000);//length * timing.getBeatLength() / GameHelper.getSpeed(); + ball = null; + followcircle = null; + repeatCount = repeats; + reverse = false; + startHit = false; + ticksGot = 0; + ticksTotal = 1; + tickTime = 0; + currentTick = 0; + tickIndex = 0; + firstHitAccuracy = 0; + tickSet.clear(); + kiai = GameHelper.isKiai(); + preStageFinish = false; + color.set(r, g, b); + if (!SkinJson.get().isSliderFollowComboColor()) { + circleColor = color; + color = new RGBColor(SkinJson.get().getSliderBodyColor()); + } + + if (soundId.length < repeats + 1) { + soundId = new int[repeats + 1]; + sampleSet = new int[repeats + 1]; + addition = new int[repeats + 1]; + } + + Arrays.fill(soundId, sound); + Arrays.fill(sampleSet, 0); + Arrays.fill(addition, 0); + + if (customSound != null) { + final String pars[] = customSound.split("[|]"); + for (int i = 0; i < soundId.length; i++) { + if (i < pars.length) { + soundId[i] = Integer.parseInt(pars[i]); + } + } + } + + if (!Utils.isEmpty(tempSound)) { + final String pars[] = tempSound.split("[|]"); + for (int i = 0; i < pars.length; i++) { + final String[] group = pars[i].split(":"); + if (i < sampleSet.length) { + sampleSet[i] = Integer.parseInt(group[0]); + } + if (i < addition.length) { + addition[i] = Integer.parseInt(group[1]); + } + } + } + soundIdIndex = 1; + + // Calculating position of top/left corner for sprites and hit radius + final TextureRegion tex = startCircle.getTextureRegion(); + /*final PointF startPos = new PointF(pos.x - tex.getWidth() / 2, pos.y + - tex.getHeight() / 2);*/ + + /* Initializing sprites */ + + // Start circle + //startCircle.setPosition(startPos.x, startPos.y); + startCircle.setScale(scale); + startCircle.setColor(r, g, b); + startCircle.setAlpha(0); + Utils.putSpriteAnchorCenter(pos, startCircle); + + //startOverlay.setPosition(startPos.x, startPos.y); + startOverlay.setScale(scale); + startOverlay.setAlpha(0); + Utils.putSpriteAnchorCenter(pos, startOverlay); + + //approachCircle.setPosition(startPos.x, startPos.y); + approachCircle.setColor(r, g, b); + approachCircle.setScale(scale * 2); + approachCircle.setAlpha(0); + Utils.putSpriteAnchorCenter(pos, approachCircle); + if (GameHelper.isHidden()) { + approachCircle.setVisible(Config.isShowFirstApproachCircle() && isFirstNote); + } + + // End circle + final int lastIndex = path.points.size() - 1; + final PointF endPos = path.points.get(lastIndex); + /*new PointF(path.points.get(lastIndex).x + - tex.getWidth() / 2, path.points.get(lastIndex).y + - tex.getHeight() / 2);*/ + + //endCircle.setPosition(endPos.x, endPos.y); + endCircle.setScale(scale); + endCircle.setColor(r, g, b); + endCircle.setAlpha(0); + Utils.putSpriteAnchorCenter(endPos, endCircle); + + + //endOverlay.setPosition(endPos.x, endPos.y); + endOverlay.setScale(scale); + endOverlay.setAlpha(0); + Utils.putSpriteAnchorCenter(endPos, endOverlay); + + scene.attachChild(startOverlay, 0); + // Repeat arrow at start + if (repeatCount > 2) { + //startArrow.setPosition(startPos.x, startPos.y); + startArrow.setAlpha(0); + startArrow.setScale(scale); + startArrow.setRotation(MathUtils.radToDeg(Utils.direction( + path.points.get(0), path.points.get(1)))); + Utils.putSpriteAnchorCenter(pos, startArrow); + scene.attachChild(startArrow, 0); + } + if (GameHelper.isHidden()) { + number.init(scene, pos, scale, + new SequenceEntityModifier(new FadeInModifier(time / 4 * GameHelper.getTimeMultiplier()), + new FadeOutModifier(time / 4 * GameHelper.getTimeMultiplier()))); + } else { + number.init(scene, pos, scale, new FadeInModifier( + time / 2 * GameHelper.getTimeMultiplier())); + } + scene.attachChild(startCircle, 0); + scene.attachChild(approachCircle); + scene.attachChild(endOverlay, 0); + // Repeat arrow at end + if (repeatCount > 1) { + //endArrow.setPosition(endPos.x, endPos.y); + endArrow.setAlpha(0); + endArrow.setScale(scale); + endArrow.setRotation(MathUtils.radToDeg(Utils.direction( + path.points.get(lastIndex), path.points.get(lastIndex - 1)))); + Utils.putSpriteAnchorCenter(endPos, endArrow); + scene.attachChild(endArrow, 0); + } + scene.attachChild(endCircle, 0); + + // Ticks + // Try to fix incorrect slider tick count bug + tickInterval = timing.getBeatLength() * speedMultiplier; + int tickCount = (int) (maxTime * GameHelper.getTickRate() / tickInterval); + if(Double.isNaN(tickInterval) || tickInterval < GameHelper.getSliderTickLength() / 1000){ + tickCount = 0; + } + if ((maxTime * GameHelper.getTickRate() / tickInterval) + - (int) (maxTime * GameHelper.getTickRate() / tickInterval) < 0.001f){ + tickCount--; + } + ticks.clear(); + for (int i = 1; i <= tickCount; i++) { + final Sprite tick = SpritePool.getInstance().getCenteredSprite( + "sliderscorepoint", + getPercentPosition((float)(i * tickInterval + / (maxTime * GameHelper.getTickRate())), null)); + tick.setScale(scale); + tick.setAlpha(0); + ticks.add(tick); + scene.attachChild(tick, 0); + } + + // Slider track + if (Config.isUseSuperSlider()) { + superPath = new LinePath(); + for (PointF p : path.points) { + superPath.add(new Vec2(p.x, p.y)); + } + superPath.measure(); + superPath.bufferLength(sliderLength = path.length.get(path.length.size() - 1)); + superPath = superPath.fitToLinePath(); + superPath.measure(); + + abstractSliderBody = new SliderBody2D(superPath); + abstractSliderBody.setBodyWidth( + Utils.toRes(SkinJson.get().getSliderBodyWidth() - SkinJson.get().getSliderBorderWidth()) + * scale); + abstractSliderBody.setBorderWidth(Utils.toRes(SkinJson.get().getSliderBodyWidth()) * scale); + abstractSliderBody.setSliderBodyBaseAlpha(SkinJson.get().getSliderBodyBaseAlpha()); + + if (SkinJson.get().isSliderHintEnable()) { + if (length > SkinJson.get().getSliderHintShowMinLength()) { + abstractSliderBody.setEnableHint(true); + abstractSliderBody.setHintAlpha(SkinJson.get().getSliderHintAlpha()); + abstractSliderBody.setHintWidth(Utils.toRes(SkinJson.get().getSliderHintWidth())); + RGBColor hintColor = SkinJson.get().getSliderHintColor(); + if (hintColor != null) { + abstractSliderBody.setHintColor(hintColor.r(), hintColor.g(), hintColor.b()); + } else { + abstractSliderBody.setHintColor(color.r(), color.g(), color.b()); + } + } + } + + abstractSliderBody.applyToScene(scene, Config.isComplexAnimations()); + abstractSliderBody.setBodyColor(color.r(), color.g(), color.b()); + RGBColor scolor = GameHelper.getSliderColor(); + abstractSliderBody.setBorderColor(scolor.r(), scolor.g(), scolor.b()); + + } else { + initLowPolyTrack(); + } +// if (Config.isLowpolySliders()) { +// initLowPolyTrack(); +// } else { +// initTrack(); +// } + } + + private void initTrack() { + final TextureRegion tex = startCircle.getTextureRegion(); + final PointF startPos = new PointF(path.points.get(0).x + - tex.getWidth() / 2, path.points.get(0).y - tex.getHeight() + / 2); + trackSprites.clear(); + group = new SpriteGroup(ResourceManager.getInstance() + .getTexture("::track").getTexture(), path.points.size()); + group.setColor(color.r(), color.g(), color.b()); + for (int i = 0; i < path.points.size(); i++) { + final PointF p = path.points.get(i); + final Sprite sprite = SpritePool.getInstance().getSprite("::track"); + if (Config.isComplexAnimations() == false) { + sprite.setPosition(p.x - sprite.getWidth() / 2, + p.y - sprite.getHeight() / 2); + } else { + sprite.setPosition(startPos.x, startPos.y); + } + sprite.setScale(scale); + sprite.setColor(color.r(), color.g(), color.b()); + sprite.setAlpha(1); + if (i < path.points.size() - 1) { + sprite.setRotation(MathUtils.radToDeg(Utils.direction(p, + path.points.get(i + 1)))); + } else if (i > 0) { + sprite.setRotation(MathUtils.radToDeg(Utils.direction( + path.points.get(i - 1), p))); + } + trackSprites.add(sprite); + group.attachChild(sprite); + // scene.attachChild(sprite, 0); + } + scene.attachChild(group, 0); + + // Slider track border + if (Config.isSliderBorders()) { + trackBorders.clear(); + borderGroup = new SpriteGroup(ResourceManager.getInstance() + .getTexture("::trackborder").getTexture(), + path.points.size()); + for (final PointF p : path.points) { + final Sprite sprite = SpritePool.getInstance().getSprite( + "::trackborder"); + if (Config.isComplexAnimations() == false) { + sprite.setPosition(p.x - sprite.getWidth() / 2, p.y + - sprite.getHeight() / 2); + } else { + sprite.setPosition(startPos.x, startPos.y); + } + sprite.setScale(scale); + sprite.setAlpha(1); + trackBorders.add(sprite); + borderGroup.attachChild(sprite); + } + final RGBColor scolor = GameHelper.getSliderColor(); + borderGroup.setColor(scolor.r(), scolor.g(), scolor.b()); + scene.attachChild(borderGroup, 0); + } + } + + private void initLowPolyTrack() { + final TextureRegion tex = startCircle.getTextureRegion(); + final PointF startPos = new PointF(path.points.get(0).x + - tex.getWidth() / 2, path.points.get(0).y - tex.getHeight() + / 2); + trackPolyVerts = createPolygon(Utils.toRes(54) * scale); + float verts[]; + if (Config.isComplexAnimations()) { + verts = new float[trackPolyVerts.length]; + for (int i = 0; i < verts.length; i++) { + verts[i] = trackPolyVerts[(i % 2)]; + } + } else { + verts = trackPolyVerts; + trackPolyVerts = null; + } + trackPoly = new Polygon(0, 0, verts); + trackPoly.setColor(color.r(), color.g(), color.b()); +// trackPoly.setAlpha(0.5f); + scene.attachChild(trackPoly, 0); + + trackBoundaries.clear(); + for (final Integer i : path.boundIndexes) { + final Sprite sprite = SpritePool.getInstance() + .getSprite("::track2"); + if (Config.isComplexAnimations() == false) { + sprite.setPosition( + path.points.get(i).x - sprite.getWidth() / 2, + path.points.get(i).y - sprite.getHeight() / 2); + } else { + sprite.setPosition(startPos.x, startPos.y); + } + sprite.setScale(scale); + sprite.setColor(color.r(), color.g(), color.b()); + sprite.setAlpha(0.7f); + scene.attachChild(sprite, 0); + trackBoundaries.add(sprite); + } + + if (Config.isSliderBorders()) { + final RGBColor scolor = GameHelper.getSliderColor(); + + borderPolyVerts = createPolygon(Utils.toRes(57) + * scale); + if (Config.isComplexAnimations()) { + verts = new float[borderPolyVerts.length]; + for (int i = 0; i < verts.length; i++) { + verts[i] = borderPolyVerts[(i % 2)]; + } + } else { + verts = borderPolyVerts; + borderPolyVerts = null; + } + borderPoly = new Polygon(0, 0, verts); + borderPoly.setColor(scolor.r(), scolor.g(), scolor.b()); +// borderPoly.setAlpha(0.1f); + scene.attachChild(borderPoly, 0); + +// trackBorders.clear(); +// for (final Integer i : path.boundIndexes) { +// final Sprite sprite = SpritePool.getInstance().getSprite( +// "::trackborder"); +// if (Config.isComplexAnimations() == false) { +// sprite.setPosition(path.points.get(i).x - sprite.getWidth() +// / 2, path.points.get(i).y - sprite.getHeight() / 2); +// } else { +// sprite.setPosition(startPos.x, startPos.y); +// } +// sprite.setScale(scale); +// sprite.setColor(scolor.r(), scolor.g(), scolor.b()); +// sprite.setAlpha(0.1f); +// scene.attachChild(sprite, 0); +// trackBorders.add(sprite); +// } + } + } + + private float[] createPolygon(final float size) { + int vi = 0; + + final LinkedList points = new LinkedList(); + for (int i = 0; i < path.points.size(); i++) { + points.add(getPointPos(i, -1, size)); + points.add(getPointPos(i, 1, size)); + } + + final ArrayList addPoints = new ArrayList(); + final ListIterator iterator = points.listIterator(); + final float sqrDist = Utils + .sqr(((scale * Constants.HIGH_SLIDER_STEP)) - 1); + for (int i = 0; i < points.size(); i++) { + if (i + 2 >= points.size()) { + break; + } + if (iterator.hasNext() == false) { + break; + } + final PointF p1 = iterator.next(); + if (iterator.hasNext() == false) { + break; + } + iterator.next(); + if (iterator.hasNext() == false) { + break; + } + final PointF p2 = iterator.next(); + iterator.previous(); + iterator.previous(); + + if (addPoints.isEmpty() == false) { + for (int j = 0; j < addPoints.size(); j++) { + iterator.add(addPoints.get(j)); + iterator.add(Utils.inter(p1, p2, (j + 1) + / (float) (addPoints.size() + 1))); + } + addPoints.clear(); + } + + int numPoints = (int) (Utils.squaredDistance(p1, p2) / sqrDist); + if (numPoints < 1) { + continue; + } + numPoints = (int) Math.sqrt(numPoints); + + for (int j = 0; j < numPoints; j++) { + final float t = (j + 1) / (float) (numPoints + 1); + final PointF p = Utils.inter(p1, p2, t); + final int idx = i / 2; + final float dx = path.points.get(idx).x * (1 - t) + + path.points.get(idx + 1).x * t; + final float dy = path.points.get(idx).y * (1 - t) + + path.points.get(idx + 1).y * t; + p.x -= dx; + p.y -= dy; + float len = Utils.length(p); + len = size / len; + if (Math.abs(len - 1) < 0.025f) { + continue; + } + p.x *= len; + p.y *= len; + p.x += dx; + p.y += dy; + + addPoints.add(p); + } + } + + final float verts[] = new float[points.size() * 2]; + for (final PointF p : points) { + verts[vi++] = p.x; + verts[vi++] = p.y; + } + return verts; + } + + private PointF getPercentPosition(final float percentage, final Float angle) { + if (percentage >= 1) { + tmpPoint.set(path.points.get(path.points.size() - 1).x, + path.points.get(path.points.size() - 1).y); + return tmpPoint; + } else if (percentage <= 0) { + if (angle != null) { + ballAngle = MathUtils.radToDeg(Utils.direction( + path.points.get(1), path.points.get(0))); + } + tmpPoint.set(path.points.get(0).x, path.points.get(0).y); + return tmpPoint; + } + + if (path.length.size() == 1) { + final PointF p = tmpPoint; + p.x = path.points.get(0).x * percentage + path.points.get(1).x + * (1 - percentage); + p.y = path.points.get(0).y * percentage + path.points.get(1).y + * (1 - percentage); + return p; + } + int left = 0, right = path.length.size(); + int index = right / 2; + final float realLength = percentage + * path.length.get(path.length.size() - 1); + while (left < right) { + if (index < path.length.size() - 1 + && path.length.get(index + 1) < realLength) { + left = index; + } else if (path.length.get(index) >= realLength) { + right = index; + } else { + break; + } + index = (right + left) / 2; + } + + float addlength = realLength - path.length.get(index); + addlength /= path.length.get(index) - path.length.get(index + 1); + final PointF p = tmpPoint; + p.x = path.points.get(index).x * addlength + + path.points.get(index + 1).x * (1 - addlength); + p.y = path.points.get(index).y * addlength + + path.points.get(index + 1).y * (1 - addlength); + if (angle != null) { + // Well, i should just add flag "save angle" instead of passing + // PointF, but... screw it + ballAngle = MathUtils.radToDeg(Utils.direction( + path.points.get(index), path.points.get(index + 1))); + } + return p; + } + + private PointF getPointPos(final int i, final int sign, final float size) { + int j = i; + if (j + 1 >= path.points.size()) { + j = path.points.size() - 2; + } + float nx = -path.points.get(j + 1).y + path.points.get(j).y; + float ny = path.points.get(j + 1).x - path.points.get(j).x; + if (sign < 0) { + nx *= -1; + ny *= -1; + } + final PointF p = new PointF(); + p.x = path.points.get(i).x; + p.y = path.points.get(i).y; + final float nlen = (float) Math.sqrt(nx * nx + ny * ny); + if (nlen > 0) { + nx /= nlen; + ny /= nlen; + nx *= size; + ny *= size; + p.x += nx; + p.y += ny; + } + return p; + } + + private void removeFromScene() { + if (scene == null) { + return; + } + // Detach all objects + if (group != null) { + group.detachSelf(); + } + if (trackPoly != null) { + trackPoly.detachSelf(); + } + if (borderPoly != null) { + borderPoly.detachSelf(); + } + if (borderGroup != null) { + borderGroup.detachSelf(); + } + if (body != null) { + body.detachSelf(); + } + if (border != null) { + border.detachSelf(); + } + if (abstractSliderBody != null) { + abstractSliderBody.removeFromScene(scene); + } + startCircle.detachSelf(); + endCircle.detachSelf(); + startOverlay.detachSelf(); + endOverlay.detachSelf(); + approachCircle.detachSelf(); + startArrow.detachSelf(); + endArrow.detachSelf(); + ball.detachSelf(); + followcircle.detachSelf(); + SpritePool.getInstance().putAnimSprite("sliderb", ball); + SpritePool.getInstance().putSprite("sliderfollowcircle", followcircle); + for (final Sprite sp : trackSprites) { + sp.detachSelf(); + SpritePool.getInstance().putSprite("::track", sp); + } + for (final Sprite sp : trackBoundaries) { + sp.detachSelf(); + SpritePool.getInstance().putSprite("::track2", sp); + } + trackBoundaries.clear(); + for (final Sprite sp : trackBorders) { + sp.detachSelf(); + SpritePool.getInstance().putSprite("::trackborder", sp); + } + for (final Sprite sp : ticks) { + sp.detachSelf(); + SpritePool.getInstance().putSprite("sliderscorepoint", sp); + } + listener.removeObject(this); + // Put this and number into pool + GameHelper.putPath(path); + GameObjectPool.getInstance().putSlider(this); + GameObjectPool.getInstance().putNumber(number); + scene = null; + isHiddenFadeOutActive = false; + } + + private void over() { + //int type = repeatCount > 0 ? GameObjectListener.SLIDER_REPEAT : GameObjectListener.SLIDER_END; + repeatCount--; + // If alpha > 0 means cursor in slider ball bounds + if (followcircle.getAlpha() > 0 && replayData == null || + replayData != null && replayData.tickSet.get(tickIndex)) { + if (soundIdIndex < soundId.length) + Utils.playHitSound(listener, soundId[soundIdIndex], + sampleSet[soundIdIndex], addition[soundIdIndex]); + ticksGot++; + tickSet.set(tickIndex++, true); + if (repeatCount > 0) { + listener.onSliderHit(id, 30, null, + path.points.get(reverse ? 0 : path.points.size() - 1), + false, color, GameObjectListener.SLIDER_REPEAT); + } + } else { + tickSet.set(tickIndex++, false); + if (repeatCount > 0) { + listener.onSliderHit(id, -1, null, + path.points.get(reverse ? 0 : path.points.size() - 1), + false, color, GameObjectListener.SLIDER_REPEAT); + } + } + soundIdIndex++; + ticksTotal++; + // If slider has more repeats + if (repeatCount > 0) { + reverse = !reverse; + passedTime -= maxTime; + tickTime = passedTime; + ball.setFlippedHorizontal(reverse); + // Restore ticks + for (final Sprite sp : ticks) { + sp.setAlpha(1); + } + currentTick = reverse ? ticks.size() - 1 : 0; + // Setting visibility of repeat arrows + if (reverse && repeatCount <= 2) { + endArrow.setAlpha(0); + } + + if (reverse && repeatCount > 1) { + startArrow.setAlpha(1); + } + + if (!reverse && repeatCount <= 2) { + startArrow.setAlpha(0); + } + //if (repeatCount > 1) { + ((GameScene) listener).onSliderReverse( + path.points.get(!reverse ? 0 : path.points.size() - 1), + reverse ? endArrow.getRotation() : startArrow.getRotation(), + color); + //} + // and go on... + if (passedTime >= maxTime){ + over(); + } + return; + } + // Calculating score + int score = 0; + if (ticksGot > 0) { + score = 50; + } + if (ticksGot >= ticksTotal / 2) { + score = 100; + } + if (ticksGot >= ticksTotal) { + score = 300; + } + // If slider was in reverse mode, we should swap start and end points + if (reverse) { + Slider.this.listener.onSliderHit(id, score, + path.points.get(path.points.size() - 1), + path.points.get(0), endsCombo, color, GameObjectListener.SLIDER_END); + } else { + Slider.this.listener.onSliderHit(id, score, path.points.get(0), + path.points.get(path.points.size() - 1), endsCombo, color, GameObjectListener.SLIDER_END); + } + if(!startHit){ + firstHitAccuracy = (int) (GameHelper.getDifficultyHelper().hitWindowFor50(GameHelper.getDifficulty()) * 1000 + 13); + } + listener.onSliderEnd(id, firstHitAccuracy, tickSet); + // Remove slider from scene + SyncTaskManager.getInstance().run(new Runnable() { + + + public void run() { + removeFromScene(); + } + }); + } + + private float getPercentPositionOnTrack(final float[] verts, + final float percent, final int i) { + if (i <= 3) { + return verts[i]; + } + if (percent >= 1) { + return verts[i]; + } + if (percent <= 0) { + return verts[i % 4]; + } + float t = percent * (i / 4); + int index = (int) (t); + t -= index; + index = index * 4 + i % 4; + return verts[index] + (verts[index + 4] - verts[index]) * t; + } + + private boolean isHit() { + float radius = Utils.sqr(Utils.toRes(64) * scale); + for (int i = 0; i < listener.getCursorsCount(); i++) { + if (listener.isMousePressed(this, i) + && Utils.squaredDistance(path.points.get(0), listener.getMousePos(i)) <= radius) { + return true; + } else if (GameHelper.isAutopilotMod() && listener.isMousePressed(this, i)) { + return true; + } else if (GameHelper.isRelaxMod() && passedTime >= 0 && + Utils.squaredDistance(path.points.get(0), listener.getMousePos(i)) <= radius) { + return true; + } + } + return false; + } + + + @Override + public void update(final float dt) { + + if (scene == null) { + return; + } + passedTime += dt; + + if (startHit == false) // If we didn't get start hit(click) + { + // If it's too late, mark this hit missing + if (passedTime > GameHelper.getDifficultyHelper().hitWindowFor50(GameHelper.getDifficulty())) { + startHit = true; + listener.onSliderHit(id, -1, null, path.points.get(0), false, color, GameObjectListener.SLIDER_START); + firstHitAccuracy = (int) (passedTime * 1000); + } else if (autoPlay && passedTime >= 0) { + startHit = true; + Utils.playHitSound(listener, soundId[0], sampleSet[0], addition[0]); + ticksGot++; + listener.onSliderHit(id, 30, null, path.points.get(0), false, color, GameObjectListener.SLIDER_START); + } else if (replayData != null && + Math.abs(replayData.accuracy / 1000f) <= GameHelper.getDifficultyHelper().hitWindowFor50(GameHelper.getDifficulty()) && + passedTime + dt / 2 > replayData.accuracy / 1000f) { + startHit = true; + Utils.playHitSound(listener, soundId[0], sampleSet[0], addition[0]); + ticksGot++; + listener.onSliderHit(id, 30, null, path.points.get(0), false, color, GameObjectListener.SLIDER_START); + } else { + if (isHit() && -passedTime < GameHelper.getDifficultyHelper().hitWindowFor50(GameHelper.getDifficulty())) // if + // we + // clicked + { + listener.registerAccuracy(passedTime); + startHit = true; + Utils.playHitSound(listener, soundId[0], sampleSet[0], addition[0]); + ticksGot++; + firstHitAccuracy = (int) (passedTime * 1000); + listener.onSliderHit(id, 30, null, path.points.get(0), + false, color, GameObjectListener.SLIDER_START); + } + } + } + + if (GameHelper.isKiai()) { + final float kiaiModifier = Math + .max(0, + 1 - GameHelper.getGlobalTime() + / GameHelper.getKiaiTickLength()) * 0.50f; + + final float r = Math.min(1, color.r() + (1 - color.r()) + * kiaiModifier); + final float g = Math.min(1, color.g() + (1 - color.g()) + * kiaiModifier); + final float b = Math.min(1, color.b() + (1 - color.b()) + * kiaiModifier); + kiai = true; + startCircle.setColor(r, g, b); + endCircle.setColor(r, g, b); + if (group != null) { + group.setColor(r, g, b); + } + if (trackPoly != null) { + trackPoly.setColor(r, g, b); + } + if (body != null) { + body.setColor(r, g, b); + } + for (final Sprite sp : trackBoundaries) { + sp.setColor(r, g, b); + } + } else if (kiai == true) { + startCircle.setColor(color.r(), color.g(), color.b()); + endCircle.setColor(color.r(), color.g(), color.b()); + if (group != null) { + group.setColor(color.r(), color.g(), color.b()); + } + if (trackPoly != null) { + trackPoly.setColor(color.r(), color.g(), color.b()); + } + kiai = false; + for (final Sprite sp : trackBoundaries) { + sp.setColor(color.r(), color.g(), color.b()); + } + } + + if (passedTime < 0) // we at approach time + { + float percentage = 1 + passedTime / preTime; + // calculating size of approach circle + approachCircle.setScale(scale + * (1 + 2f * (1 - percentage))); + if (startHit == true) { + approachCircle.setAlpha(0); + } + if (percentage <= 0.5f) { + // Following core doing a very cute show animation ^_^" + percentage = Math.min(1, percentage * 2); + if (startHit == false) { + approachCircle.setAlpha(percentage); + } + + + startCircle.setAlpha(percentage); + startOverlay.setAlpha(percentage); + endCircle.setAlpha(percentage); + endOverlay.setAlpha(percentage); + for (int i = 0; i < ticks.size(); i++) { + if (percentage > (float) (i + 1) / ticks.size()) { + ticks.get(i).setAlpha(1); + } + } + if (repeatCount > 1) { + endArrow.setAlpha(percentage); + } + + if (Config.isComplexAnimations()) { + //final float offset = startCircle.getWidth() / 2; + if (Config.isUseSuperSlider()) { + + float l = superPath.getMeasurer().maxLength() * percentage; + + abstractSliderBody.setEndLength(l); + abstractSliderBody.onUpdate(); + + } else { + tmpPoint = getPercentPosition(percentage, null); +// if (Config.isLowpolySliders()) { + for (int i = 0; i < path.boundIndexes.size(); i++) { + final float ppos = path.boundIndexes.get(i) + / (float) path.points.size(); + PointF tpoint = tmpPoint; + if (percentage >= ppos) { + tpoint = path.points.get(path.boundIndexes + .get(i)); + } + Utils.putSpriteAnchorCenter(tpoint, trackBoundaries.get(i)); + /*trackBoundaries.get(i).setPosition( + tpoint.x - offset, tpoint.y - offset);*/ + if (trackBorders.isEmpty() == false) { + Utils.putSpriteAnchorCenter(tpoint, trackBorders.get(i)); + /*trackBorders.get(i).setPosition( + trackBoundaries.get(i));*/ + } + } +// } else { +// for (int i = 0; i < trackSprites.size(); i++) { +// tmpPoint = getPercentPosition(percentage * i +// / path.points.size(), null); +// trackSprites.get(i).setPosition( +// tmpPoint.x - offset, tmpPoint.y - offset); +// if (trackBorders.isEmpty() == false) { +// trackBorders.get(i).setPosition( +// trackSprites.get(i)); +// } +// } +// } + //endOverlay.setPosition(endCircle); + //endArrow.setPosition(endCircle); + if (trackPolyVerts != null) { + final float verts[] = trackPoly.getVertices(); + for (int i = 0; i < verts.length; i++) { + verts[i] = getPercentPositionOnTrack( + trackPolyVerts, percentage, i);// trackPolyVerts[i + // % 2] + + // (trackPolyVerts[i] + // - + // trackPolyVerts[i + // % 2]) * + // percentage; + } + trackPoly.updateShape(); + } + if (borderPolyVerts != null) { + final float verts[] = borderPoly.getVertices(); + for (int i = 0; i < verts.length; i++) { + verts[i] = getPercentPositionOnTrack( + borderPolyVerts, percentage, i); + // verts[i] = borderPolyVerts[i % 2] + + // (trackPolyVerts[i] - borderPolyVerts[i % 2]) * + // percentage; + } + borderPoly.updateShape(); + } + } + + tmpPoint = getPercentPosition(percentage, null); + + Utils.putSpriteAnchorCenter(tmpPoint, endCircle); + Utils.putSpriteAnchorCenter(tmpPoint, endOverlay); + Utils.putSpriteAnchorCenter(tmpPoint, endArrow); + } + } else if (percentage - dt / preTime <= 0.5f) { + // Setting up positions of slider parts + approachCircle.setAlpha(1); + startCircle.setAlpha(1); + startOverlay.setAlpha(1); + endCircle.setAlpha(1); + endOverlay.setAlpha(1); + for (final Sprite sp : ticks) { + sp.setAlpha(1); + } + if (repeatCount > 1) { + endArrow.setAlpha(1); + } + if (Config.isComplexAnimations()) { + final float offset = startCircle.getWidth() / 2; + if (Config.isUseSuperSlider()) { + if (!preStageFinish) { + abstractSliderBody.setEndLength(superPath.getMeasurer().maxLength()); + abstractSliderBody.onUpdate(); + preStageFinish = true; + } + + } else { + + for (int i = 0; i < path.boundIndexes.size(); i++) { + tmpPoint = path.points + .get(path.boundIndexes.get(i)); + trackBoundaries.get(i).setPosition( + tmpPoint.x - offset, tmpPoint.y - offset); + if (trackBorders.isEmpty() == false) { + trackBorders.get(i).setPosition( + trackBoundaries.get(i)); + } + } + if (trackPolyVerts != null) { + final float verts[] = trackPoly.getVertices(); + for (int i = 0; i < verts.length; i++) { + verts[i] = trackPolyVerts[i]; + } + trackPoly.updateShape(); + trackPolyVerts = null; + } + if (borderPolyVerts != null) { + final float verts[] = borderPoly.getVertices(); + for (int i = 0; i < verts.length; i++) { + verts[i] = borderPolyVerts[i]; + } + borderPoly.updateShape(); + borderPolyVerts = null; + } + } + + tmpPoint = path.points.get(path.points.size() - 1); + + if (/*Config.isLowpolySliders() + && */trackBoundaries.isEmpty() == false) { + endCircle.setPosition(trackBoundaries + .get(trackBoundaries.size() - 1)); + } else { + Utils.putSpriteAnchorCenter(tmpPoint, endCircle); + } + Utils.putSpriteAnchorCenter(tmpPoint, endOverlay); + Utils.putSpriteAnchorCenter(tmpPoint, endArrow); + } + + } + return; + } else { + if (Config.isUseSuperSlider()) { + startCircle.setAlpha(0); + startOverlay.setAlpha(0); + } + + // Slider body, border, and hint gradually fade in Hidden mod + if (GameHelper.isHidden()) { + hiddenFadeOut(); + } + } + + if (ball == null) // if ball still don't exists + { + number.detach(true); + approachCircle.setAlpha(0); + + ball = SpritePool.getInstance().getAnimSprite("sliderb", + SkinManager.getFrames("sliderb")); + ball.setFps(0.1f * GameHelper.getSpeed() * scale + / timing.getBeatLength()); + ball.setScale(scale); + ball.setFlippedHorizontal(false); + + followcircle = SpritePool.getInstance().getSprite( + "sliderfollowcircle"); + followcircle.setScale(scale); + + scene.attachChild(ball); + scene.attachChild(followcircle); + } + // Ball positiong + final float percentage = passedTime / maxTime; + final PointF ballpos = getPercentPosition(reverse ? 1 - percentage + : percentage, ballAngle); + // Calculating if cursor in follow circle bounds + final float radius = Utils.toRes(128) * scale; + boolean inRadius = false; + for (int i = 0; i < listener.getCursorsCount(); i++) { + if (autoPlay == false + && (listener.isMouseDown(i) == false || Utils + .squaredDistance(listener.getMousePos(i), ballpos) > radius + * radius)) { + } else { + inRadius = true; + break; + } + if (GameHelper.isAutopilotMod() && listener.isMouseDown(i)) + inRadius = true; + } + followcircle.setAlpha(inRadius ? 1 : 0); + listener.onTrackingSliders(inRadius); + + tickTime += dt; + //try fixed big followcircle bug + float fcscale = scale * (1.1f - 0.1f * tickTime * GameHelper.getTickRate() / timing.getBeatLength()); + if (fcscale <= scale * 1.1f && fcscale >= scale * -1.1f){ + followcircle.setScale(fcscale); + } + // Some magic with slider ticks. If it'll crash it's not my fault ^_^" + while (ticks.size() > 0 && percentage < 1 - 0.02f / maxTime + && tickTime * GameHelper.getTickRate() > tickInterval) { + tickTime -= tickInterval / GameHelper.getTickRate(); + if (followcircle.getAlpha() > 0 && replayData == null || + replayData != null && replayData.tickSet.get(tickIndex)) { + Utils.playHitSound(listener, 16); + listener.onSliderHit(id, 10, null, ballpos, false, color, GameObjectListener.SLIDER_TICK); + ticksGot++; + tickSet.set(tickIndex++, true); + } else { + listener.onSliderHit(id, -1, null, ballpos, false, color, GameObjectListener.SLIDER_TICK); + tickSet.set(tickIndex++, false); + } + ticks.get(currentTick).setAlpha(0); + if (reverse && currentTick > 0) { + currentTick--; + } else if (!reverse && currentTick < ticks.size() - 1) { + currentTick++; + } + ticksTotal++; + } + // Setting position of ball and follow circle + followcircle.setPosition(ballpos.x - followcircle.getWidth() / 2, + ballpos.y - followcircle.getHeight() / 2); + ball.setPosition(ballpos.x - ball.getWidth() / 2, + ballpos.y - ball.getHeight() / 2); + ball.setRotation(ballAngle); + + if (GameHelper.isAuto() || GameHelper.isAutopilotMod()) { + listener.updateAutoBasedPos(ballpos.x, ballpos.y); + } + + // If we got 100% time, finishing slider + if (percentage >= 1) { + over(); + } + } + + private void hiddenFadeOut() { + if (isHiddenFadeOutActive) { + return; + } + isHiddenFadeOutActive = true; + final float realDuration = maxTime * repeatCount * GameHelper.getTimeMultiplier(); + if (group != null) { + group.registerEntityModifier(new AlphaModifier(realDuration, + group.getAlpha(), 0)); + } + if (trackPoly != null) { + trackPoly.registerEntityModifier(new AlphaModifier(realDuration, + trackPoly.getAlpha(), 0)); + } + if (borderPoly != null) { + borderPoly.registerEntityModifier(new AlphaModifier(realDuration, + borderPoly.getAlpha(), 0)); + } + if (borderGroup != null) { + borderGroup.registerEntityModifier(new AlphaModifier(realDuration, + borderGroup.getAlpha(), 0)); + } + if (body != null) { + body.registerEntityModifier(new AlphaModifier(realDuration, + body.getAlpha(), 0)); + } + if (border != null) { + border.registerEntityModifier(new AlphaModifier(realDuration, + border.getAlpha(), 0)); + } + for (final Sprite sp : trackSprites) { + sp.registerEntityModifier(new AlphaModifier(realDuration, + sp.getAlpha(), 0)); + } + for (final Sprite sp : trackBorders) { + sp.registerEntityModifier(new AlphaModifier(realDuration, + sp.getAlpha(), 0)); + } + for (final Sprite sp : trackBoundaries) { + sp.registerEntityModifier(new AlphaModifier(realDuration, + sp.getAlpha(), 0)); + } + if (abstractSliderBody != null) { + abstractSliderBody.fadeOut(realDuration); + } + } + + @Override + public void tryHit(final float dt){ + if (startHit == false) // If we didn't get start hit(click) + { + if (isHit() && -passedTime < GameHelper.getDifficultyHelper().hitWindowFor50(GameHelper.getDifficulty())) // if + // we + // clicked + { + listener.registerAccuracy(passedTime); + startHit = true; + Utils.playHitSound(listener, soundId[0], sampleSet[0], addition[0]); + ticksGot++; + firstHitAccuracy = (int) (passedTime * 1000); + listener.onSliderHit(id, 30, null, path.points.get(0), + false, color, GameObjectListener.SLIDER_START); + } + if (passedTime < 0) // we at approach time + { + if (startHit == true) { + approachCircle.setAlpha(0); + } + } + } + } } diff --git a/src/ru/nsu/ccfit/zuev/osu/game/SongProgressBar.java b/src/ru/nsu/ccfit/zuev/osu/game/SongProgressBar.java index 934a894e..9f7ccdc8 100644 --- a/src/ru/nsu/ccfit/zuev/osu/game/SongProgressBar.java +++ b/src/ru/nsu/ccfit/zuev/osu/game/SongProgressBar.java @@ -9,63 +9,63 @@ import ru.nsu.ccfit.zuev.osu.Utils; public class SongProgressBar extends GameObject { - private final Rectangle progressRect; - private final Rectangle bgRect; - private float time; - private float startTime; - private float passedTime; + private final Rectangle progressRect; + private final Rectangle bgRect; + private float time; + private float startTime; + private float passedTime; - public SongProgressBar(final GameObjectListener listener, - final Scene scene, final float time, final float startTime, final PointF pos) { - this(listener, scene, time, startTime, pos, Utils.toRes(300), Utils.toRes(7)); - } + public SongProgressBar(final GameObjectListener listener, + final Scene scene, final float time, final float startTime, final PointF pos) { + this(listener, scene, time, startTime, pos, Utils.toRes(300), Utils.toRes(7)); + } - public SongProgressBar(final GameObjectListener listener, - final Scene scene, final float time, final float startTime, final PointF pos, float width, float height) { - this.time = time; - this.startTime = startTime; - if (listener != null) - listener.addPassiveObject(this); + public SongProgressBar(final GameObjectListener listener, + final Scene scene, final float time, final float startTime, final PointF pos, float width, float height) { + this.time = time; + this.startTime = startTime; + if (listener != null) + listener.addPassiveObject(this); - bgRect = new Rectangle(pos.x, pos.y, width, height); - bgRect.setColor(0, 0, 0, 0.3f); - scene.attachChild(bgRect); + bgRect = new Rectangle(pos.x, pos.y, width, height); + bgRect.setColor(0, 0, 0, 0.3f); + scene.attachChild(bgRect); - progressRect = new Rectangle(bgRect.getX(), bgRect.getY(), 0, - bgRect.getHeight()); - progressRect.setColor(153f / 255f, 204f / 255f, 51f / 255f); - scene.attachChild(progressRect); - } + progressRect = new Rectangle(bgRect.getX(), bgRect.getY(), 0, + bgRect.getHeight()); + progressRect.setColor(153f / 255f, 204f / 255f, 51f / 255f); + scene.attachChild(progressRect); + } - @Override - public void update(final float dt) { - if (passedTime >= startTime) { - passedTime = Math.min(time, passedTime + dt); - progressRect.setWidth(bgRect.getWidth() * (passedTime - startTime) - / (time - startTime)); - } else { - passedTime = Math.min(startTime, passedTime + dt); - progressRect.setWidth(bgRect.getWidth() * passedTime / startTime); - if (passedTime >= startTime) { - progressRect.setColor(1, 1, 150f / 255f); - } - } - } + @Override + public void update(final float dt) { + if (passedTime >= startTime) { + passedTime = Math.min(time, passedTime + dt); + progressRect.setWidth(bgRect.getWidth() * (passedTime - startTime) + / (time - startTime)); + } else { + passedTime = Math.min(startTime, passedTime + dt); + progressRect.setWidth(bgRect.getWidth() * passedTime / startTime); + if (passedTime >= startTime) { + progressRect.setColor(1, 1, 150f / 255f); + } + } + } - public void setTime(float time) { - this.time = time; - } + public void setTime(float time) { + this.time = time; + } - public void setStartTime(float startTime) { - this.startTime = startTime; - } + public void setStartTime(float startTime) { + this.startTime = startTime; + } - public void setPassedTime(float passedTime) { - this.passedTime = passedTime; - } + public void setPassedTime(float passedTime) { + this.passedTime = passedTime; + } - public void setProgressRectColor(RGBAColor color) { - this.progressRect.setColor(color.r(), color.g(), color.b(), color.a()); - } + public void setProgressRectColor(RGBAColor color) { + this.progressRect.setColor(color.r(), color.g(), color.b(), color.a()); + } } diff --git a/src/ru/nsu/ccfit/zuev/osu/game/Spinner.java b/src/ru/nsu/ccfit/zuev/osu/game/Spinner.java index 0ce02982..f3286451 100644 --- a/src/ru/nsu/ccfit/zuev/osu/game/Spinner.java +++ b/src/ru/nsu/ccfit/zuev/osu/game/Spinner.java @@ -28,312 +28,312 @@ import ru.nsu.ccfit.zuev.osu.scoring.StatisticV2; public class Spinner extends GameObject { - private final Sprite background; - public final PointF center; - private final Sprite circle; - private final Sprite approachCircle; - private final Sprite metre; - private final Sprite spinText; - private final TextureRegion mregion; - private Sprite clearText = null; - private PointF oldMouse; - private GameObjectListener listener; - private Scene scene; - private int fullrotations = 0; - private float rotations = 0; - private float needRotations; - private boolean clear = false; - private int soundId; - private int sampleSet; - private int addition; - private ScoreNumber bonusScore = null; - private int score = 1; - private float metreY; - private StatisticV2 stat; - private float totalTime; - private boolean did = false; + private final Sprite background; + public final PointF center; + private final Sprite circle; + private final Sprite approachCircle; + private final Sprite metre; + private final Sprite spinText; + private final TextureRegion mregion; + private Sprite clearText = null; + private PointF oldMouse; + private GameObjectListener listener; + private Scene scene; + private int fullrotations = 0; + private float rotations = 0; + private float needRotations; + private boolean clear = false; + private int soundId; + private int sampleSet; + private int addition; + private ScoreNumber bonusScore = null; + private int score = 1; + private float metreY; + private StatisticV2 stat; + private float totalTime; + private boolean did = false; - public Spinner() { - ResourceManager.getInstance().checkSpinnerTextures(); - this.pos = new PointF(Constants.MAP_WIDTH / 2,Constants.MAP_HEIGHT / 2); - center = Utils.trackToRealCoords(pos); - background = SpritePool.getInstance().getCenteredSprite( - "spinner-background", center); - final float scaleX = Config.getRES_WIDTH() / background.getWidth(); - background.setScale(scaleX); + public Spinner() { + ResourceManager.getInstance().checkSpinnerTextures(); + this.pos = new PointF(Constants.MAP_WIDTH / 2,Constants.MAP_HEIGHT / 2); + center = Utils.trackToRealCoords(pos); + background = SpritePool.getInstance().getCenteredSprite( + "spinner-background", center); + final float scaleX = Config.getRES_WIDTH() / background.getWidth(); + background.setScale(scaleX); - circle = SpritePool.getInstance().getCenteredSprite("spinner-circle", - center); - mregion = ResourceManager.getInstance().getTexture("spinner-metre") - .deepCopy(); - metre = new Sprite(center.x - Config.getRES_WIDTH() / 2, - Config.getRES_HEIGHT(), mregion); - metre.setWidth(Config.getRES_WIDTH()); - metre.setHeight(background.getHeightScaled()); - approachCircle = SpritePool.getInstance().getCenteredSprite( - "spinner-approachcircle", center); - spinText = new CentredSprite(center.x, center.y * 1.5f, ResourceManager - .getInstance().getTexture("spinner-spin")); - } + circle = SpritePool.getInstance().getCenteredSprite("spinner-circle", + center); + mregion = ResourceManager.getInstance().getTexture("spinner-metre") + .deepCopy(); + metre = new Sprite(center.x - Config.getRES_WIDTH() / 2, + Config.getRES_HEIGHT(), mregion); + metre.setWidth(Config.getRES_WIDTH()); + metre.setHeight(background.getHeightScaled()); + approachCircle = SpritePool.getInstance().getCenteredSprite( + "spinner-approachcircle", center); + spinText = new CentredSprite(center.x, center.y * 1.5f, ResourceManager + .getInstance().getTexture("spinner-spin")); + } - public void init(final GameObjectListener listener, final Scene scene, - final float pretime, final float time, final float rps, - final int sound, final String tempSound, final StatisticV2 stat) { - clearText = null; - fullrotations = 0; - rotations = 0; - this.scene = scene; - needRotations = rps * time; - if(time < 0.05f) needRotations = 0.1f; - this.listener = listener; - this.soundId = sound; - this.sampleSet = 0; - this.addition = 0; - this.stat = stat; - this.totalTime = time; - startHit = true; - clear = false; - if(totalTime <= 0f) clear = true; - bonusScore = null; - score = 1; - ResourceManager.getInstance().checkSpinnerTextures(); + public void init(final GameObjectListener listener, final Scene scene, + final float pretime, final float time, final float rps, + final int sound, final String tempSound, final StatisticV2 stat) { + clearText = null; + fullrotations = 0; + rotations = 0; + this.scene = scene; + needRotations = rps * time; + if(time < 0.05f) needRotations = 0.1f; + this.listener = listener; + this.soundId = sound; + this.sampleSet = 0; + this.addition = 0; + this.stat = stat; + this.totalTime = time; + startHit = true; + clear = false; + if(totalTime <= 0f) clear = true; + bonusScore = null; + score = 1; + ResourceManager.getInstance().checkSpinnerTextures(); - if (!Utils.isEmpty(tempSound)) { - final String[] group = tempSound.split(":"); - this.sampleSet = Integer.parseInt(group[0]); - this.addition = Integer.parseInt(group[1]); - } + if (!Utils.isEmpty(tempSound)) { + final String[] group = tempSound.split(":"); + this.sampleSet = Integer.parseInt(group[0]); + this.addition = Integer.parseInt(group[1]); + } - final IEntityModifier appearMoifier = new SequenceEntityModifier( - new DelayModifier(pretime * 0.75f), new FadeInModifier( - pretime * 0.25f)); + final IEntityModifier appearMoifier = new SequenceEntityModifier( + new DelayModifier(pretime * 0.75f), new FadeInModifier( + pretime * 0.25f)); - background.setAlpha(0); - background.registerEntityModifier(appearMoifier.deepCopy()); + background.setAlpha(0); + background.registerEntityModifier(appearMoifier.deepCopy()); - circle.setAlpha(0); - circle.registerEntityModifier(appearMoifier.deepCopy()); + circle.setAlpha(0); + circle.registerEntityModifier(appearMoifier.deepCopy()); - metreY = (Config.getRES_HEIGHT() - background.getHeightScaled()) / 2; - metre.setAlpha(0); - metre.registerEntityModifier(appearMoifier.deepCopy()); - mregion.setTexturePosition(0, (int) metre.getHeightScaled()); + metreY = (Config.getRES_HEIGHT() - background.getHeightScaled()) / 2; + metre.setAlpha(0); + metre.registerEntityModifier(appearMoifier.deepCopy()); + mregion.setTexturePosition(0, (int) metre.getHeightScaled()); - approachCircle.setAlpha(0); - if (GameHelper.isHidden()) { - approachCircle.setVisible(false); - } - approachCircle.registerEntityModifier(new SequenceEntityModifier( - new IEntityModifierListener() { + approachCircle.setAlpha(0); + if (GameHelper.isHidden()) { + approachCircle.setVisible(false); + } + approachCircle.registerEntityModifier(new SequenceEntityModifier( + new IEntityModifierListener() { - public void onModifierStarted( - final IModifier pModifier, - final IEntity pItem) { - // TODO Auto-generated method stub + public void onModifierStarted( + final IModifier pModifier, + final IEntity pItem) { + // TODO Auto-generated method stub - } + } - public void onModifierFinished( - final IModifier pModifier, - final IEntity pItem) { - SyncTaskManager.getInstance().run(new Runnable() { + public void onModifierFinished( + final IModifier pModifier, + final IEntity pItem) { + SyncTaskManager.getInstance().run(new Runnable() { - public void run() { - removeFromScene(); - } - }); - } - }, - new SequenceEntityModifier( - new DelayModifier(pretime), - new ParallelEntityModifier( - new AlphaModifier(time, 0.75f, 1), - new ScaleModifier(time, 2.0f, 0) - ) - ) - )); + public void run() { + removeFromScene(); + } + }); + } + }, + new SequenceEntityModifier( + new DelayModifier(pretime), + new ParallelEntityModifier( + new AlphaModifier(time, 0.75f, 1), + new ScaleModifier(time, 2.0f, 0) + ) + ) + )); - spinText.setAlpha(0); - spinText.registerEntityModifier(new SequenceEntityModifier( - new DelayModifier(pretime * 0.75f), new FadeInModifier( - pretime * 0.25f), new DelayModifier(pretime / 2), - new FadeOutModifier(pretime * 0.25f))); + spinText.setAlpha(0); + spinText.registerEntityModifier(new SequenceEntityModifier( + new DelayModifier(pretime * 0.75f), new FadeInModifier( + pretime * 0.25f), new DelayModifier(pretime / 2), + new FadeOutModifier(pretime * 0.25f))); - scene.attachChild(spinText, 0); - scene.attachChild(approachCircle, 0); - scene.attachChild(circle, 0); - scene.attachChild(metre, 0); - scene.attachChild(background, 0); + scene.attachChild(spinText, 0); + scene.attachChild(approachCircle, 0); + scene.attachChild(circle, 0); + scene.attachChild(metre, 0); + scene.attachChild(background, 0); - oldMouse = null; + oldMouse = null; - } + } - void removeFromScene() { - if (clearText != null) { - scene.detachChild(clearText); - SpritePool.getInstance().putSprite("spinner-clear", clearText); - } - scene.detachChild(spinText); - scene.detachChild(background); - approachCircle.detachSelf(); - scene.detachChild(circle); - scene.detachChild(metre); - // GameObjectPool.getInstance().putSpinner(this); + void removeFromScene() { + if (clearText != null) { + scene.detachChild(clearText); + SpritePool.getInstance().putSprite("spinner-clear", clearText); + } + scene.detachChild(spinText); + scene.detachChild(background); + approachCircle.detachSelf(); + scene.detachChild(circle); + scene.detachChild(metre); + // GameObjectPool.getInstance().putSpinner(this); - if (bonusScore != null) { - bonusScore.detachFromScene(scene); - } - listener.removeObject(Spinner.this); - int score = 0; - if (replayData != null) { - //int bonusRot = (int) (replayData.accuracy / 4 - needRotations + 1); - //while (bonusRot < 0) { - // bonusRot++; - // listener.onSpinnerHit(id, 1000, false, 0); - //} + if (bonusScore != null) { + bonusScore.detachFromScene(scene); + } + listener.removeObject(Spinner.this); + int score = 0; + if (replayData != null) { + //int bonusRot = (int) (replayData.accuracy / 4 - needRotations + 1); + //while (bonusRot < 0) { + // bonusRot++; + // listener.onSpinnerHit(id, 1000, false, 0); + //} - //if (rotations count < the rotations in replay), let rotations count = the rotations in replay - while (fullrotations + this.score < replayData.accuracy / 4 + 1){ - fullrotations++; - listener.onSpinnerHit(id, 1000, false, 0); - } - if (fullrotations >= needRotations) - clear = true; - } - float percentfill = (Math.abs(rotations) + fullrotations) - / needRotations; - if(needRotations <= 0.1f){ - clear = true; - percentfill = 1; - } - if (percentfill > 0.9f) { - score = 50; - } - if (percentfill > 0.95f) { - score = 100; - } - if (clear) { - score = 300; - } - if (replayData != null) { - switch (replayData.accuracy % 4) { - case 0: - score = 0; - break; - case 1: - score = 50; - break; - case 2: - score = 100; - break; - case 3: - score = 300; - break; - } - } - listener.onSpinnerHit(id, score, endsCombo, this.score + fullrotations - 1); - if (score > 0) { - Utils.playHitSound(listener, soundId); - } - } + //if (rotations count < the rotations in replay), let rotations count = the rotations in replay + while (fullrotations + this.score < replayData.accuracy / 4 + 1){ + fullrotations++; + listener.onSpinnerHit(id, 1000, false, 0); + } + if (fullrotations >= needRotations) + clear = true; + } + float percentfill = (Math.abs(rotations) + fullrotations) + / needRotations; + if(needRotations <= 0.1f){ + clear = true; + percentfill = 1; + } + if (percentfill > 0.9f) { + score = 50; + } + if (percentfill > 0.95f) { + score = 100; + } + if (clear) { + score = 300; + } + if (replayData != null) { + switch (replayData.accuracy % 4) { + case 0: + score = 0; + break; + case 1: + score = 50; + break; + case 2: + score = 100; + break; + case 3: + score = 300; + break; + } + } + listener.onSpinnerHit(id, score, endsCombo, this.score + fullrotations - 1); + if (score > 0) { + Utils.playHitSound(listener, soundId); + } + } - @Override - public void update(final float dt) { - if (circle.getAlpha() == 0) { - return; - } - boolean mdown = false; - int firstIndex = -1; - for (int i = 0; i < listener.getCursorsCount(); i++) { - if (listener.isMouseDown(i)) { - firstIndex = i; - mdown = true; - break; - } - } - if (mdown == false && !autoPlay) { - return; - } + @Override + public void update(final float dt) { + if (circle.getAlpha() == 0) { + return; + } + boolean mdown = false; + int firstIndex = -1; + for (int i = 0; i < listener.getCursorsCount(); i++) { + if (listener.isMouseDown(i)) { + firstIndex = i; + mdown = true; + break; + } + } + if (mdown == false && !autoPlay) { + return; + } - final PointF mouse = autoPlay ? center : listener - .getMousePos(firstIndex); - final PointF v = new PointF(mouse.x - center.x, mouse.y - center.y); - for (int i = 0; i < listener.getCursorsCount(); i++) { - if (oldMouse == null || listener.isMousePressed(this, i)) { - oldMouse = v; - return; - } - } - circle.setRotation(MathUtils.radToDeg(Utils.direction(v))); - final PointF v1 = Utils.normalize(v); - final PointF v2 = Utils.normalize(oldMouse); - float dfill = v1.x * v2.y - v1.y * v2.x; - if (autoPlay) { - dfill = 5 * 4 * dt; - circle.setRotation((rotations + dfill / 4f) * 360); - //auto时,FL光圈绕中心旋转 - if (GameHelper.isAuto() || GameHelper.isAutopilotMod()) { - float angle = (rotations + dfill / 4f) * 360; - float pX = center.x + 50 * (float)Math.sin(angle); - float pY = center.y + 50 * (float)Math.cos(angle); - listener.updateAutoBasedPos(pX, pY); - } - } - rotations += dfill / 4f; - float percentfill = (Math.abs(rotations) + fullrotations) - / needRotations; + final PointF mouse = autoPlay ? center : listener + .getMousePos(firstIndex); + final PointF v = new PointF(mouse.x - center.x, mouse.y - center.y); + for (int i = 0; i < listener.getCursorsCount(); i++) { + if (oldMouse == null || listener.isMousePressed(this, i)) { + oldMouse = v; + return; + } + } + circle.setRotation(MathUtils.radToDeg(Utils.direction(v))); + final PointF v1 = Utils.normalize(v); + final PointF v2 = Utils.normalize(oldMouse); + float dfill = v1.x * v2.y - v1.y * v2.x; + if (autoPlay) { + dfill = 5 * 4 * dt; + circle.setRotation((rotations + dfill / 4f) * 360); + //auto时,FL光圈绕中心旋转 + if (GameHelper.isAuto() || GameHelper.isAutopilotMod()) { + float angle = (rotations + dfill / 4f) * 360; + float pX = center.x + 50 * (float)Math.sin(angle); + float pY = center.y + 50 * (float)Math.cos(angle); + listener.updateAutoBasedPos(pX, pY); + } + } + rotations += dfill / 4f; + float percentfill = (Math.abs(rotations) + fullrotations) + / needRotations; - if (percentfill > 1 || clear) { - percentfill = 1; - if (clear == false) { - clearText = SpritePool.getInstance().getCenteredSprite( - "spinner-clear", new PointF(center.x, center.y * 0.5f)); - clearText.registerEntityModifier(new ParallelEntityModifier( - new FadeInModifier(0.25f), new ScaleModifier(0.25f, - 1.5f, 1))); - scene.attachChild(clearText); - clear = true; - } else if (Math.abs(rotations) > 1) { - if (bonusScore != null) { - bonusScore.detachFromScene(scene); - } - rotations -= 1 * Math.signum(rotations); - bonusScore = new ScoreNumber(center.x, center.y + 100, - String.valueOf(score * 1000), 1.1f, true); - listener.onSpinnerHit(id, 1000, false, 0); - score++; - bonusScore.attachToScene(scene); - ResourceManager.getInstance().getSound("spinnerbonus").play(); - float rate = 0.375f; - if (GameHelper.getDrain() > 0) { - rate = 1 + (GameHelper.getDrain() / 4f); - } - stat.changeHp(rate * 0.01f * totalTime / needRotations); - } - } else if (Math.abs(rotations) > 1) { - rotations -= 1 * Math.signum(rotations); - if (replayData == null || replayData.accuracy / 4 > fullrotations) { - fullrotations++; - stat.registerSpinnerHit(); - float rate = 0.375f; - if (GameHelper.getDrain() > 0) { - rate = 1 + (GameHelper.getDrain() / 2f); - } - stat.changeHp(rate * 0.01f * totalTime / needRotations); - } - } - metre.setPosition(metre.getX(), - metreY + metre.getHeight() * (1 - Math.abs(percentfill))); - mregion.setTexturePosition(0, - (int) (metre.getBaseHeight() * (1 - Math.abs(percentfill)))); - oldMouse = v; - } - - @Override - public void tryHit(final float dt){ - return; - } + if (percentfill > 1 || clear) { + percentfill = 1; + if (clear == false) { + clearText = SpritePool.getInstance().getCenteredSprite( + "spinner-clear", new PointF(center.x, center.y * 0.5f)); + clearText.registerEntityModifier(new ParallelEntityModifier( + new FadeInModifier(0.25f), new ScaleModifier(0.25f, + 1.5f, 1))); + scene.attachChild(clearText); + clear = true; + } else if (Math.abs(rotations) > 1) { + if (bonusScore != null) { + bonusScore.detachFromScene(scene); + } + rotations -= 1 * Math.signum(rotations); + bonusScore = new ScoreNumber(center.x, center.y + 100, + String.valueOf(score * 1000), 1.1f, true); + listener.onSpinnerHit(id, 1000, false, 0); + score++; + bonusScore.attachToScene(scene); + ResourceManager.getInstance().getSound("spinnerbonus").play(); + float rate = 0.375f; + if (GameHelper.getDrain() > 0) { + rate = 1 + (GameHelper.getDrain() / 4f); + } + stat.changeHp(rate * 0.01f * totalTime / needRotations); + } + } else if (Math.abs(rotations) > 1) { + rotations -= 1 * Math.signum(rotations); + if (replayData == null || replayData.accuracy / 4 > fullrotations) { + fullrotations++; + stat.registerSpinnerHit(); + float rate = 0.375f; + if (GameHelper.getDrain() > 0) { + rate = 1 + (GameHelper.getDrain() / 2f); + } + stat.changeHp(rate * 0.01f * totalTime / needRotations); + } + } + metre.setPosition(metre.getX(), + metreY + metre.getHeight() * (1 - Math.abs(percentfill))); + mregion.setTexturePosition(0, + (int) (metre.getBaseHeight() * (1 - Math.abs(percentfill)))); + oldMouse = v; + } + + @Override + public void tryHit(final float dt){ + return; + } } diff --git a/src/ru/nsu/ccfit/zuev/osu/game/SpritePool.java b/src/ru/nsu/ccfit/zuev/osu/game/SpritePool.java index 5e047578..fd29b85e 100644 --- a/src/ru/nsu/ccfit/zuev/osu/game/SpritePool.java +++ b/src/ru/nsu/ccfit/zuev/osu/game/SpritePool.java @@ -13,127 +13,127 @@ import ru.nsu.ccfit.zuev.osu.helper.CentredSprite; public class SpritePool { - private static SpritePool instance = new SpritePool(); - private static int CAPACITY = 250; - private final Map> sprites = new HashMap>(); - private final Map> animsprites = new HashMap>(); - int count = 0; - private int spritesCreated = 0; - private SpritePool() { - } - - public static SpritePool getInstance() { - return instance; - } - - public int getSpritesCreated() { - return spritesCreated; - } - - synchronized public void putSprite(final String name, final Sprite sprite) { - if (count > CAPACITY) { - return; - } - if (sprite.hasParent()) { - return; - } - - sprite.setAlpha(1); - sprite.setColor(1, 1, 1); - sprite.setScale(1); - sprite.clearEntityModifiers(); - sprite.clearUpdateHandlers(); - count++; - if (sprites.containsKey(name)) { - sprites.get(name).add(sprite); - } else { - final LinkedList list = new LinkedList(); - list.add(sprite); - sprites.put(name, list); - } - } - - synchronized public Sprite getSprite(final String name) { - if (sprites.containsKey(name)) { - final LinkedList list = sprites.get(name); - while (list.isEmpty() == false && list.peek().hasParent() == true) { - list.poll(); - } - if (list.isEmpty() == false) { - count--; - return list.poll(); - } - } - - spritesCreated++; - return new Sprite(0, 0, ResourceManager.getInstance().getTexture(name)); - } - - synchronized public Sprite getCenteredSprite(final String name, - final PointF pos) { - if (sprites.containsKey(name)) { - final LinkedList list = sprites.get(name); - while (list.isEmpty() == false && list.peek().hasParent() == true) { - list.poll(); - } - if (list.isEmpty() == false) { - count--; - final Sprite sp = list.poll(); - sp.setPosition(pos.x - sp.getWidth() / 2, - pos.y - sp.getHeight() / 2); - return sp; - } - } - - spritesCreated++; - return new CentredSprite(pos.x, pos.y, ResourceManager.getInstance() - .getTexture(name)); - } - - synchronized public AnimSprite getAnimSprite(final String name, int count) { - if (animsprites.containsKey(name)) { - final LinkedList list = animsprites.get(name); - while (list.isEmpty() == false && list.peek().hasParent() == true) { - list.poll(); - } - if (list.isEmpty() == false) { - count--; - return list.poll(); - } - } - - spritesCreated++; - return new AnimSprite(0, 0, name, count, count); - } - - synchronized public void putAnimSprite(final String name, - final AnimSprite sprite) { - if (count > CAPACITY) { - return; - } - if (sprite.hasParent()) { - return; - } - - sprite.setAlpha(1); - sprite.setColor(1, 1, 1); - sprite.setScale(1); - sprite.clearEntityModifiers(); - sprite.clearUpdateHandlers(); - count++; - if (animsprites.containsKey(name)) { - animsprites.get(name).add(sprite); - } else { - final LinkedList list = new LinkedList(); - list.add(sprite); - animsprites.put(name, list); - } - } - - public void purge() { - count = 0; - spritesCreated = 0; - sprites.clear(); - animsprites.clear(); - } + private static SpritePool instance = new SpritePool(); + private static int CAPACITY = 250; + private final Map> sprites = new HashMap>(); + private final Map> animsprites = new HashMap>(); + int count = 0; + private int spritesCreated = 0; + private SpritePool() { + } + + public static SpritePool getInstance() { + return instance; + } + + public int getSpritesCreated() { + return spritesCreated; + } + + synchronized public void putSprite(final String name, final Sprite sprite) { + if (count > CAPACITY) { + return; + } + if (sprite.hasParent()) { + return; + } + + sprite.setAlpha(1); + sprite.setColor(1, 1, 1); + sprite.setScale(1); + sprite.clearEntityModifiers(); + sprite.clearUpdateHandlers(); + count++; + if (sprites.containsKey(name)) { + sprites.get(name).add(sprite); + } else { + final LinkedList list = new LinkedList(); + list.add(sprite); + sprites.put(name, list); + } + } + + synchronized public Sprite getSprite(final String name) { + if (sprites.containsKey(name)) { + final LinkedList list = sprites.get(name); + while (list.isEmpty() == false && list.peek().hasParent() == true) { + list.poll(); + } + if (list.isEmpty() == false) { + count--; + return list.poll(); + } + } + + spritesCreated++; + return new Sprite(0, 0, ResourceManager.getInstance().getTexture(name)); + } + + synchronized public Sprite getCenteredSprite(final String name, + final PointF pos) { + if (sprites.containsKey(name)) { + final LinkedList list = sprites.get(name); + while (list.isEmpty() == false && list.peek().hasParent() == true) { + list.poll(); + } + if (list.isEmpty() == false) { + count--; + final Sprite sp = list.poll(); + sp.setPosition(pos.x - sp.getWidth() / 2, + pos.y - sp.getHeight() / 2); + return sp; + } + } + + spritesCreated++; + return new CentredSprite(pos.x, pos.y, ResourceManager.getInstance() + .getTexture(name)); + } + + synchronized public AnimSprite getAnimSprite(final String name, int count) { + if (animsprites.containsKey(name)) { + final LinkedList list = animsprites.get(name); + while (list.isEmpty() == false && list.peek().hasParent() == true) { + list.poll(); + } + if (list.isEmpty() == false) { + count--; + return list.poll(); + } + } + + spritesCreated++; + return new AnimSprite(0, 0, name, count, count); + } + + synchronized public void putAnimSprite(final String name, + final AnimSprite sprite) { + if (count > CAPACITY) { + return; + } + if (sprite.hasParent()) { + return; + } + + sprite.setAlpha(1); + sprite.setColor(1, 1, 1); + sprite.setScale(1); + sprite.clearEntityModifiers(); + sprite.clearUpdateHandlers(); + count++; + if (animsprites.containsKey(name)) { + animsprites.get(name).add(sprite); + } else { + final LinkedList list = new LinkedList(); + list.add(sprite); + animsprites.put(name, list); + } + } + + public void purge() { + count = 0; + spritesCreated = 0; + sprites.clear(); + animsprites.clear(); + } } diff --git a/src/ru/nsu/ccfit/zuev/osu/game/TimingPoint.java b/src/ru/nsu/ccfit/zuev/osu/game/TimingPoint.java index 379ebc28..deb9d083 100644 --- a/src/ru/nsu/ccfit/zuev/osu/game/TimingPoint.java +++ b/src/ru/nsu/ccfit/zuev/osu/game/TimingPoint.java @@ -3,111 +3,111 @@ import ru.nsu.ccfit.zuev.osu.Constants; public class TimingPoint { - private static String defaultSound = "normal"; - float time; - float beatLength; - int signature = 4; - String hitSound; - int customSound = 0; - float volume; - boolean inherited = false; - boolean kiai; - private float speed; - - public TimingPoint(final String[] data, final TimingPoint prevData) { - time = Float.parseFloat(data[0]) / 1000.0f; - beatLength = Float.parseFloat(data[1]); - if (beatLength < 0 && prevData != null) { - inherited = true; - speed = -100.0f / beatLength; - beatLength = -prevData.getBeatLength() * (beatLength / 100.0f); - } else { - beatLength /= 1000.0f; - speed = 1.0f; - } - //beatLength = FMath.clamp(beatLength, 0.006f, 60); - //speed = FMath.clamp(speed, 0.1f, 10); - - if (data.length > 2) { - if ("4".equals(data[2])) { - signature = 4; - } - if ("3".equals(data[2])) { - signature = 3; - } - } - - if (data.length > 3) { - if (data[3].equals("1")) { - hitSound = Constants.SAMPLE_PREFIX[1]; - } else if (data[3].equals("3")) { - hitSound = Constants.SAMPLE_PREFIX[3]; - } else { - hitSound = Constants.SAMPLE_PREFIX[2]; - } - } else { - hitSound = getDefaultSound(); - } - if (data.length > 4) { - customSound = Integer.parseInt(data[4]); - } - if (data.length > 5) { - volume = Integer.parseInt(data[5]) / 100f; - } else { - volume = 1; - } - if (data.length > 7) { - kiai = (data[7].equals("0") == false); - } else { - kiai = false; - } - } - - public static String getDefaultSound() { - return defaultSound; - } - - public static void setDefaultSound(final String defaultSound) { - TimingPoint.defaultSound = defaultSound; - } - - public boolean wasInderited() { - return inherited; - } - - public String getHitSound() { - return hitSound; - } - - public int getCustomSound() { - return customSound; - } - - public float getVolume() { - return volume; - } - - public float getBeatLength() { - return beatLength; - } - - public int getSignature() { - return signature; - } - - public float getTime() { - return time; - } - - public boolean isKiai() { - return kiai; - } - - public float getSpeed() { - return speed; - } - - public float getBpm() { - return 600.0f / beatLength; - } + private static String defaultSound = "normal"; + float time; + float beatLength; + int signature = 4; + String hitSound; + int customSound = 0; + float volume; + boolean inherited = false; + boolean kiai; + private float speed; + + public TimingPoint(final String[] data, final TimingPoint prevData) { + time = Float.parseFloat(data[0]) / 1000.0f; + beatLength = Float.parseFloat(data[1]); + if (beatLength < 0 && prevData != null) { + inherited = true; + speed = -100.0f / beatLength; + beatLength = -prevData.getBeatLength() * (beatLength / 100.0f); + } else { + beatLength /= 1000.0f; + speed = 1.0f; + } + //beatLength = FMath.clamp(beatLength, 0.006f, 60); + //speed = FMath.clamp(speed, 0.1f, 10); + + if (data.length > 2) { + if ("4".equals(data[2])) { + signature = 4; + } + if ("3".equals(data[2])) { + signature = 3; + } + } + + if (data.length > 3) { + if (data[3].equals("1")) { + hitSound = Constants.SAMPLE_PREFIX[1]; + } else if (data[3].equals("3")) { + hitSound = Constants.SAMPLE_PREFIX[3]; + } else { + hitSound = Constants.SAMPLE_PREFIX[2]; + } + } else { + hitSound = getDefaultSound(); + } + if (data.length > 4) { + customSound = Integer.parseInt(data[4]); + } + if (data.length > 5) { + volume = Integer.parseInt(data[5]) / 100f; + } else { + volume = 1; + } + if (data.length > 7) { + kiai = (data[7].equals("0") == false); + } else { + kiai = false; + } + } + + public static String getDefaultSound() { + return defaultSound; + } + + public static void setDefaultSound(final String defaultSound) { + TimingPoint.defaultSound = defaultSound; + } + + public boolean wasInderited() { + return inherited; + } + + public String getHitSound() { + return hitSound; + } + + public int getCustomSound() { + return customSound; + } + + public float getVolume() { + return volume; + } + + public float getBeatLength() { + return beatLength; + } + + public int getSignature() { + return signature; + } + + public float getTime() { + return time; + } + + public boolean isKiai() { + return kiai; + } + + public float getSpeed() { + return speed; + } + + public float getBpm() { + return 600.0f / beatLength; + } } diff --git a/src/ru/nsu/ccfit/zuev/osu/game/cursor/flashlight/FlashLightDimLayerSprite.java b/src/ru/nsu/ccfit/zuev/osu/game/cursor/flashlight/FlashLightDimLayerSprite.java index c4e1b0c7..1fec9c43 100644 --- a/src/ru/nsu/ccfit/zuev/osu/game/cursor/flashlight/FlashLightDimLayerSprite.java +++ b/src/ru/nsu/ccfit/zuev/osu/game/cursor/flashlight/FlashLightDimLayerSprite.java @@ -7,16 +7,16 @@ public class FlashLightDimLayerSprite extends FlashlightAreaSizedSprite { - public final float BASE_SLIDER_DIM_ALPHA = 0.8f; + public final float BASE_SLIDER_DIM_ALPHA = 0.8f; - public FlashLightDimLayerSprite() { - super(TextureHelper.create1xRegion(Color.BLACK)); - this.setScale(MainFlashLightSprite.TEXTURE_WIDTH, MainFlashLightSprite.TEXTURE_HEIGHT); - this.setAlpha(0); - } + public FlashLightDimLayerSprite() { + super(TextureHelper.create1xRegion(Color.BLACK)); + this.setScale(MainFlashLightSprite.TEXTURE_WIDTH, MainFlashLightSprite.TEXTURE_HEIGHT); + this.setAlpha(0); + } - public void onTrackingSliders(boolean isTrackingSliders) { - float newAlpha = isTrackingSliders? BASE_SLIDER_DIM_ALPHA : 0; - this.registerEntityModifier(new AlphaModifier(0.05f, this.getAlpha(), newAlpha)); - } + public void onTrackingSliders(boolean isTrackingSliders) { + float newAlpha = isTrackingSliders? BASE_SLIDER_DIM_ALPHA : 0; + this.registerEntityModifier(new AlphaModifier(0.05f, this.getAlpha(), newAlpha)); + } } diff --git a/src/ru/nsu/ccfit/zuev/osu/game/cursor/flashlight/FlashLightEntity.java b/src/ru/nsu/ccfit/zuev/osu/game/cursor/flashlight/FlashLightEntity.java index a620d591..3ffcdf33 100644 --- a/src/ru/nsu/ccfit/zuev/osu/game/cursor/flashlight/FlashLightEntity.java +++ b/src/ru/nsu/ccfit/zuev/osu/game/cursor/flashlight/FlashLightEntity.java @@ -12,52 +12,52 @@ public class FlashLightEntity extends Entity { - private final MainFlashLightSprite mainSprite; - private final FlashLightDimLayerSprite dimLayer; - private boolean isTrackingSliders = false; + private final MainFlashLightSprite mainSprite; + private final FlashLightDimLayerSprite dimLayer; + private boolean isTrackingSliders = false; - private IEntityModifier currentModifier = null; - private float nextPX; - private float nextPY; + private IEntityModifier currentModifier = null; + private float nextPX; + private float nextPY; - public static final float defaultMoveDelayMS = 120f; - public static final float defaultMoveDelayS = 0.12f; + public static final float defaultMoveDelayMS = 120f; + public static final float defaultMoveDelayS = 0.12f; - public FlashLightEntity() { - super(Config.getRES_WIDTH() / 2f, Config.getRES_HEIGHT() / 2f); + public FlashLightEntity() { + super(Config.getRES_WIDTH() / 2f, Config.getRES_HEIGHT() / 2f); - mainSprite = new MainFlashLightSprite(); - dimLayer = new FlashLightDimLayerSprite(); + mainSprite = new MainFlashLightSprite(); + dimLayer = new FlashLightDimLayerSprite(); - attachChild(mainSprite); - attachChild(dimLayer); - } + attachChild(mainSprite); + attachChild(dimLayer); + } - public void onBreak(boolean isBreak) { - mainSprite.updateBreak(isBreak); - } + public void onBreak(boolean isBreak) { + mainSprite.updateBreak(isBreak); + } - public void onMouseMove(float pX, float pY) { - float flFollowDelay = ModMenu.getInstance().getFLfollowDelay(); + public void onMouseMove(float pX, float pY) { + float flFollowDelay = ModMenu.getInstance().getFLfollowDelay(); - if (nextPX != 0 && nextPY != 0 && currentModifier != null && this.getX() != nextPX && this.getY() != nextPY) { - this.unregisterEntityModifier(currentModifier); - } + if (nextPX != 0 && nextPY != 0 && currentModifier != null && this.getX() != nextPX && this.getY() != nextPY) { + this.unregisterEntityModifier(currentModifier); + } - nextPX = FMath.clamp(pX, 0, Config.getRES_WIDTH()); - nextPY = FMath.clamp(pY, 0, Config.getRES_HEIGHT()); - currentModifier = new MoveModifier(flFollowDelay, this.getX(), nextPX, this.getY(), nextPY, EaseExponentialOut.getInstance()); + nextPX = FMath.clamp(pX, 0, Config.getRES_WIDTH()); + nextPY = FMath.clamp(pY, 0, Config.getRES_HEIGHT()); + currentModifier = new MoveModifier(flFollowDelay, this.getX(), nextPX, this.getY(), nextPY, EaseExponentialOut.getInstance()); - this.registerEntityModifier(currentModifier); - } + this.registerEntityModifier(currentModifier); + } - public void onTrackingSliders(boolean isTrackingSliders) { - this.isTrackingSliders = isTrackingSliders; - } + public void onTrackingSliders(boolean isTrackingSliders) { + this.isTrackingSliders = isTrackingSliders; + } - public void onUpdate(int combo) { - dimLayer.onTrackingSliders(isTrackingSliders); - mainSprite.onUpdate(combo); - } + public void onUpdate(int combo) { + dimLayer.onTrackingSliders(isTrackingSliders); + mainSprite.onUpdate(combo); + } } diff --git a/src/ru/nsu/ccfit/zuev/osu/game/cursor/flashlight/FlashlightAreaSizedSprite.java b/src/ru/nsu/ccfit/zuev/osu/game/cursor/flashlight/FlashlightAreaSizedSprite.java index 07c88416..5177274c 100644 --- a/src/ru/nsu/ccfit/zuev/osu/game/cursor/flashlight/FlashlightAreaSizedSprite.java +++ b/src/ru/nsu/ccfit/zuev/osu/game/cursor/flashlight/FlashlightAreaSizedSprite.java @@ -4,10 +4,10 @@ import org.anddev.andengine.opengl.texture.region.TextureRegion; public class FlashlightAreaSizedSprite extends Sprite { - public static final float BASE_SIZE = 6f; + public static final float BASE_SIZE = 6f; - public FlashlightAreaSizedSprite(TextureRegion pTextureRegion) { - super(-MainFlashLightSprite.TEXTURE_WIDTH / 2f, -MainFlashLightSprite.TEXTURE_HEIGHT / 2f, pTextureRegion); - this.setScale(BASE_SIZE); - } + public FlashlightAreaSizedSprite(TextureRegion pTextureRegion) { + super(-MainFlashLightSprite.TEXTURE_WIDTH / 2f, -MainFlashLightSprite.TEXTURE_HEIGHT / 2f, pTextureRegion); + this.setScale(BASE_SIZE); + } } diff --git a/src/ru/nsu/ccfit/zuev/osu/game/cursor/flashlight/MainFlashLightSprite.java b/src/ru/nsu/ccfit/zuev/osu/game/cursor/flashlight/MainFlashLightSprite.java index 8b656eec..92b47849 100644 --- a/src/ru/nsu/ccfit/zuev/osu/game/cursor/flashlight/MainFlashLightSprite.java +++ b/src/ru/nsu/ccfit/zuev/osu/game/cursor/flashlight/MainFlashLightSprite.java @@ -7,39 +7,39 @@ public class MainFlashLightSprite extends FlashlightAreaSizedSprite { - private static final TextureRegion DEFAULT_TEXTURE = ResourceManager.getInstance().getTexture("flashlight_cursor"); - public static final int TEXTURE_WIDTH = DEFAULT_TEXTURE.getWidth(); - public static final int TEXTURE_HEIGHT = DEFAULT_TEXTURE.getHeight(); - public final float AREA_CHANGE_FADE_DURATION = 0.8f; - public float currentSize = BASE_SIZE; - - - public MainFlashLightSprite() { - super(DEFAULT_TEXTURE); - } - - private void changeArea(float fromScale, float toScale) { - this.registerEntityModifier(new ScaleModifier(AREA_CHANGE_FADE_DURATION, fromScale, toScale)); - } - - public void onUpdate(int combo) { - this.handleAreaShrinking(combo); - } - - public void handleAreaShrinking(int combo) { - // Area stops shrinking at 200 combo - if (combo <= 200 && combo % 100 == 0) { - // For every 100 combo, the size is decreased by 10% - final float newSize = (1 - 0.1f * combo / 100f) * BASE_SIZE; - this.changeArea(currentSize, newSize); - currentSize = newSize; - } - } - - public void updateBreak(boolean isBreak) { - float fromScale = isBreak? currentSize : 1.5f * BASE_SIZE; - float toScale = isBreak? 1.5f * BASE_SIZE : currentSize; - - this.changeArea(fromScale, toScale); - } + private static final TextureRegion DEFAULT_TEXTURE = ResourceManager.getInstance().getTexture("flashlight_cursor"); + public static final int TEXTURE_WIDTH = DEFAULT_TEXTURE.getWidth(); + public static final int TEXTURE_HEIGHT = DEFAULT_TEXTURE.getHeight(); + public final float AREA_CHANGE_FADE_DURATION = 0.8f; + public float currentSize = BASE_SIZE; + + + public MainFlashLightSprite() { + super(DEFAULT_TEXTURE); + } + + private void changeArea(float fromScale, float toScale) { + this.registerEntityModifier(new ScaleModifier(AREA_CHANGE_FADE_DURATION, fromScale, toScale)); + } + + public void onUpdate(int combo) { + this.handleAreaShrinking(combo); + } + + public void handleAreaShrinking(int combo) { + // Area stops shrinking at 200 combo + if (combo <= 200 && combo % 100 == 0) { + // For every 100 combo, the size is decreased by 10% + final float newSize = (1 - 0.1f * combo / 100f) * BASE_SIZE; + this.changeArea(currentSize, newSize); + currentSize = newSize; + } + } + + public void updateBreak(boolean isBreak) { + float fromScale = isBreak? currentSize : 1.5f * BASE_SIZE; + float toScale = isBreak? 1.5f * BASE_SIZE : currentSize; + + this.changeArea(fromScale, toScale); + } } diff --git a/src/ru/nsu/ccfit/zuev/osu/game/cursor/main/AutoCursor.java b/src/ru/nsu/ccfit/zuev/osu/game/cursor/main/AutoCursor.java index 3b40a2ad..3c7e12d1 100644 --- a/src/ru/nsu/ccfit/zuev/osu/game/cursor/main/AutoCursor.java +++ b/src/ru/nsu/ccfit/zuev/osu/game/cursor/main/AutoCursor.java @@ -11,88 +11,88 @@ import ru.nsu.ccfit.zuev.osu.game.Spinner; public class AutoCursor extends CursorEntity implements ISliderListener { - private MoveModifier currentModifier; - /** - * The ID of the object that the cursor is currently active on. - */ - private int currentObjectId = -1; + private MoveModifier currentModifier; + /** + * The ID of the object that the cursor is currently active on. + */ + private int currentObjectId = -1; - /** - * The Easing function to be used on the cursor. - */ - private final IEaseFunction easeFunction = EaseLinear.getInstance(); + /** + * The Easing function to be used on the cursor. + */ + private final IEaseFunction easeFunction = EaseLinear.getInstance(); - public AutoCursor() { - super(); - this.setPosition(Config.getRES_WIDTH() / 2f, Config.getRES_HEIGHT() / 2f); - this.setShowing(true); - } + public AutoCursor() { + super(); + this.setPosition(Config.getRES_WIDTH() / 2f, Config.getRES_HEIGHT() / 2f); + this.setShowing(true); + } - private void doEasingAutoMove(float pX, float pY, float durationS) { - unregisterEntityModifier(currentModifier); - currentModifier = new MoveModifier(durationS, getX(), pX, getY(), pY, easeFunction); - registerEntityModifier(currentModifier); - } + private void doEasingAutoMove(float pX, float pY, float durationS) { + unregisterEntityModifier(currentModifier); + currentModifier = new MoveModifier(durationS, getX(), pX, getY(), pY, easeFunction); + registerEntityModifier(currentModifier); + } - private void doAutoMove(float pX, float pY, float durationS, GameObjectListener listener) { - if (durationS <= 0) { - setPosition(pX, pY, listener); - click(); - } else { - doEasingAutoMove(pX, pY, durationS); - } - listener.onUpdatedAutoCursor(pX, pY); - } + private void doAutoMove(float pX, float pY, float durationS, GameObjectListener listener) { + if (durationS <= 0) { + setPosition(pX, pY, listener); + click(); + } else { + doEasingAutoMove(pX, pY, durationS); + } + listener.onUpdatedAutoCursor(pX, pY); + } - /** - * Directly moves the cursor's position to the specified position. - * - * @param pX The X coordinate of the new cursor position. - * @param pY The Y coordinate of the new cursor position. - * @param listener The listener that listens to when this cursor is moved. - */ - public void setPosition(float pX, float pY, GameObjectListener listener) { - setPosition(pX, pY); - listener.onUpdatedAutoCursor(pX, pY); - } + /** + * Directly moves the cursor's position to the specified position. + * + * @param pX The X coordinate of the new cursor position. + * @param pY The Y coordinate of the new cursor position. + * @param listener The listener that listens to when this cursor is moved. + */ + public void setPosition(float pX, float pY, GameObjectListener listener) { + setPosition(pX, pY); + listener.onUpdatedAutoCursor(pX, pY); + } - /** - * Moves the cursor to the specified object. - * - * @param object The object to move the cursor to. - * @param secPassed The amount of seconds that have passed since the game has started. - * @param listener The listener that listens to when this cursor is moved. - */ - public void moveToObject(GameObject object, float secPassed, GameObjectListener listener) { - if (object == null || currentObjectId == object.getId()) { - return; - } + /** + * Moves the cursor to the specified object. + * + * @param object The object to move the cursor to. + * @param secPassed The amount of seconds that have passed since the game has started. + * @param listener The listener that listens to when this cursor is moved. + */ + public void moveToObject(GameObject object, float secPassed, GameObjectListener listener) { + if (object == null || currentObjectId == object.getId()) { + return; + } - float movePositionX = object.getPos().x; - float movePositionY = object.getPos().y; + float movePositionX = object.getPos().x; + float movePositionY = object.getPos().y; - if (object instanceof Spinner) { - movePositionX = ((Spinner) object).center.x + 50 * (float) Math.sin(0); - movePositionY = ((Spinner) object).center.y + 50 * (float) Math.cos(0); - } + if (object instanceof Spinner) { + movePositionX = ((Spinner) object).center.x + 50 * (float) Math.sin(0); + movePositionY = ((Spinner) object).center.y + 50 * (float) Math.cos(0); + } - currentObjectId = object.getId(); - float moveDelay = object.getHitTime() - secPassed; - doAutoMove(movePositionX, movePositionY, moveDelay, listener); - } + currentObjectId = object.getId(); + float moveDelay = object.getHitTime() - secPassed; + doAutoMove(movePositionX, movePositionY, moveDelay, listener); + } - @Override - public void onSliderStart() { - cursorSprite.onSliderStart(); - } + @Override + public void onSliderStart() { + cursorSprite.onSliderStart(); + } - @Override - public void onSliderTracking() { - cursorSprite.onSliderTracking(); - } + @Override + public void onSliderTracking() { + cursorSprite.onSliderTracking(); + } - @Override - public void onSliderEnd() { - cursorSprite.onSliderEnd(); - } + @Override + public void onSliderEnd() { + cursorSprite.onSliderEnd(); + } } diff --git a/src/ru/nsu/ccfit/zuev/osu/game/cursor/main/Cursor.java b/src/ru/nsu/ccfit/zuev/osu/game/cursor/main/Cursor.java index 3e984726..44137102 100644 --- a/src/ru/nsu/ccfit/zuev/osu/game/cursor/main/Cursor.java +++ b/src/ru/nsu/ccfit/zuev/osu/game/cursor/main/Cursor.java @@ -3,9 +3,9 @@ import android.graphics.PointF; public class Cursor { - public PointF mousePos = new PointF(0, 0); - public boolean mouseDown = false; - public boolean mouseOldDown = false; - public boolean mousePressed = false; - public double mouseDownOffsetMS = 0; + public PointF mousePos = new PointF(0, 0); + public boolean mouseDown = false; + public boolean mouseOldDown = false; + public boolean mousePressed = false; + public double mouseDownOffsetMS = 0; } diff --git a/src/ru/nsu/ccfit/zuev/osu/game/cursor/main/CursorEntity.java b/src/ru/nsu/ccfit/zuev/osu/game/cursor/main/CursorEntity.java index 6a06074b..10ddc2a4 100644 --- a/src/ru/nsu/ccfit/zuev/osu/game/cursor/main/CursorEntity.java +++ b/src/ru/nsu/ccfit/zuev/osu/game/cursor/main/CursorEntity.java @@ -11,103 +11,103 @@ import ru.nsu.ccfit.zuev.osu.game.cursor.trail.CursorTrail; public class CursorEntity extends Entity { - protected final CursorSprite cursorSprite; - private ParticleSystem particles = null; - private PointParticleEmitter emitter = null; - private boolean isShowing = false; - private float particleOffsetX, particleOffsetY; + protected final CursorSprite cursorSprite; + private ParticleSystem particles = null; + private PointParticleEmitter emitter = null; + private boolean isShowing = false; + private float particleOffsetX, particleOffsetY; - public CursorEntity() { - TextureRegion cursorTex = ResourceManager.getInstance().getTexture("cursor"); - cursorSprite = new CursorSprite(-cursorTex.getWidth() / 2f, -cursorTex.getWidth() / 2f, cursorTex); + public CursorEntity() { + TextureRegion cursorTex = ResourceManager.getInstance().getTexture("cursor"); + cursorSprite = new CursorSprite(-cursorTex.getWidth() / 2f, -cursorTex.getWidth() / 2f, cursorTex); - if (Config.isUseParticles()) { - TextureRegion trailTex = ResourceManager.getInstance().getTexture("cursortrail"); + if (Config.isUseParticles()) { + TextureRegion trailTex = ResourceManager.getInstance().getTexture("cursortrail"); - particleOffsetX = -trailTex.getWidth() / 2f; - particleOffsetY = -trailTex.getHeight() / 2f; + particleOffsetX = -trailTex.getWidth() / 2f; + particleOffsetY = -trailTex.getHeight() / 2f; - emitter = new PointParticleEmitter(particleOffsetX, particleOffsetY); - particles = new CursorTrail( - emitter, 30, 2, 4, cursorSprite.baseSize, trailTex - ); - } + emitter = new PointParticleEmitter(particleOffsetX, particleOffsetY); + particles = new CursorTrail( + emitter, 30, 2, 4, cursorSprite.baseSize, trailTex + ); + } - attachChild(cursorSprite); - } + attachChild(cursorSprite); + } - public void setShowing(boolean showing) { - this.isShowing = showing; - if (particles != null) - particles.setParticlesSpawnEnabled(showing); - } + public void setShowing(boolean showing) { + this.isShowing = showing; + if (particles != null) + particles.setParticlesSpawnEnabled(showing); + } - public void click() { - cursorSprite.handleClick(); - } + public void click() { + cursorSprite.handleClick(); + } - public void update(float pSecondsElapsed) { - // this.handleLongerTrail(); - cursorSprite.update(pSecondsElapsed, isShowing); - super.onManagedUpdate(pSecondsElapsed); - } + public void update(float pSecondsElapsed) { + // this.handleLongerTrail(); + cursorSprite.update(pSecondsElapsed, isShowing); + super.onManagedUpdate(pSecondsElapsed); + } - private void handleLongerTrail() { - //TODO:finish Longer Tail - /* - if (isShowing && Config.isUseLongTrail()) { - if (oldPoint != null){ - float px = cursorSprite.getX() - oldPoint.x; - float py = cursorSprite.getY() - oldPoint.y; - float ds = (float)Math.sqrt(px * px + py * py); - float length = (float)Math.sqrt(particleOffsetX * particleOffsetX + particleOffsetY * particleOffsetY); - int count = (int)(ds / length); - for (int i = 1; i < count - 1; i++){ - final Particle particle = new Particle(oldPoint.x + px * i / count + particleOffsetX, - oldPoint.y + py * i / count + particleOffsetY, ResourceManager.getInstance().getTexture("cursortrail")); - new ExpireModifier(0.25f).onInitializeParticle(particle); - new AlphaModifier(1.0f, 0.0f, 0f, 0.25f).onInitializeParticle(particle); - particle.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); - new ScaleInitializer(csize).onInitializeParticle(particle); - if (tails == null){ - tails = new ArrayList<>(); - } - tails.add(particle); - GlobalManager.getInstance().getGameScene().getScene().attachChild(particle); - } - } - oldPoint = new PointF(cursorSprite.getX(), cursorSprite.getY()); - if (tails != null){ - for (Particle p : tails){ - new ExpireModifier(0.25f).onUpdateParticle(p); - new AlphaModifier(1.0f, 0.0f, 0f, 0.25f).onUpdateParticle(p); - if (p.getAlpha() == 0f){ - p.setDead(true); - } - } - for (int i = tails.size() - 1; i >= 0; i--){ - Particle p = tails.get(i); - if (p.isDead()) { - GlobalManager.getInstance().getGameScene().getScene().detachChild(p); - tails.remove(p); - } - } - } - }*/ - } + private void handleLongerTrail() { + //TODO:finish Longer Tail + /* + if (isShowing && Config.isUseLongTrail()) { + if (oldPoint != null){ + float px = cursorSprite.getX() - oldPoint.x; + float py = cursorSprite.getY() - oldPoint.y; + float ds = (float)Math.sqrt(px * px + py * py); + float length = (float)Math.sqrt(particleOffsetX * particleOffsetX + particleOffsetY * particleOffsetY); + int count = (int)(ds / length); + for (int i = 1; i < count - 1; i++){ + final Particle particle = new Particle(oldPoint.x + px * i / count + particleOffsetX, + oldPoint.y + py * i / count + particleOffsetY, ResourceManager.getInstance().getTexture("cursortrail")); + new ExpireModifier(0.25f).onInitializeParticle(particle); + new AlphaModifier(1.0f, 0.0f, 0f, 0.25f).onInitializeParticle(particle); + particle.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); + new ScaleInitializer(csize).onInitializeParticle(particle); + if (tails == null){ + tails = new ArrayList<>(); + } + tails.add(particle); + GlobalManager.getInstance().getGameScene().getScene().attachChild(particle); + } + } + oldPoint = new PointF(cursorSprite.getX(), cursorSprite.getY()); + if (tails != null){ + for (Particle p : tails){ + new ExpireModifier(0.25f).onUpdateParticle(p); + new AlphaModifier(1.0f, 0.0f, 0f, 0.25f).onUpdateParticle(p); + if (p.getAlpha() == 0f){ + p.setDead(true); + } + } + for (int i = tails.size() - 1; i >= 0; i--){ + Particle p = tails.get(i); + if (p.isDead()) { + GlobalManager.getInstance().getGameScene().getScene().detachChild(p); + tails.remove(p); + } + } + } + }*/ + } - public void attachToScene(Scene fgScene) { - if (particles != null) { - fgScene.attachChild(particles); - } - fgScene.attachChild(this); - } + public void attachToScene(Scene fgScene) { + if (particles != null) { + fgScene.attachChild(particles); + } + fgScene.attachChild(this); + } - @Override - public void setPosition(float pX, float pY) { - if (emitter != null) - emitter.setCenter(pX + particleOffsetX, pY + particleOffsetY); + @Override + public void setPosition(float pX, float pY) { + if (emitter != null) + emitter.setCenter(pX + particleOffsetX, pY + particleOffsetY); - super.setPosition(pX, pY); - } + super.setPosition(pX, pY); + } } diff --git a/src/ru/nsu/ccfit/zuev/osu/game/cursor/main/CursorSprite.java b/src/ru/nsu/ccfit/zuev/osu/game/cursor/main/CursorSprite.java index 643b056e..42ad1f1c 100644 --- a/src/ru/nsu/ccfit/zuev/osu/game/cursor/main/CursorSprite.java +++ b/src/ru/nsu/ccfit/zuev/osu/game/cursor/main/CursorSprite.java @@ -10,55 +10,55 @@ import ru.nsu.ccfit.zuev.osu.game.ISliderListener; public class CursorSprite extends Sprite implements ISliderListener { - public final float baseSize = 2f * Config.getCursorSize(); - private final float clickAnimationTime = 0.5f / 2f; - private ParallelEntityModifier previousClickModifier; + public final float baseSize = 2f * Config.getCursorSize(); + private final float clickAnimationTime = 0.5f / 2f; + private ParallelEntityModifier previousClickModifier; - public CursorSprite(float pX, float pY, TextureRegion pTextureRegion) { - super(pX, pY, pTextureRegion); - setScale(baseSize); - } + public CursorSprite(float pX, float pY, TextureRegion pTextureRegion) { + super(pX, pY, pTextureRegion); + setScale(baseSize); + } - public ScaleModifier clickInModifier() { - return new ScaleModifier(clickAnimationTime, getScaleX(), baseSize * 1.25f); - } + public ScaleModifier clickInModifier() { + return new ScaleModifier(clickAnimationTime, getScaleX(), baseSize * 1.25f); + } - public ScaleModifier clickOutModifier() { - return new ScaleModifier(clickAnimationTime, getScaleX(), baseSize); - } + public ScaleModifier clickOutModifier() { + return new ScaleModifier(clickAnimationTime, getScaleX(), baseSize); + } - public void handleClick() { - if (previousClickModifier != null) { - unregisterEntityModifier(previousClickModifier); - setScale(baseSize); - } - registerEntityModifier( - previousClickModifier = new ParallelEntityModifier( - new SequenceEntityModifier(clickInModifier(), clickOutModifier()) - ) - ); - } + public void handleClick() { + if (previousClickModifier != null) { + unregisterEntityModifier(previousClickModifier); + setScale(baseSize); + } + registerEntityModifier( + previousClickModifier = new ParallelEntityModifier( + new SequenceEntityModifier(clickInModifier(), clickOutModifier()) + ) + ); + } - public void update(float pSecondsElapsed, boolean isShowing) { - setVisible(isShowing); + public void update(float pSecondsElapsed, boolean isShowing) { + setVisible(isShowing); - if (getScaleX() > 2f) { - setScale(Math.max(baseSize, this.getScaleX() - (baseSize * 0.75f) * pSecondsElapsed)); - } - } + if (getScaleX() > 2f) { + setScale(Math.max(baseSize, this.getScaleX() - (baseSize * 0.75f) * pSecondsElapsed)); + } + } - @Override - public void onSliderStart() { + @Override + public void onSliderStart() { - } + } - @Override - public void onSliderTracking() { - registerEntityModifier(clickInModifier()); - } + @Override + public void onSliderTracking() { + registerEntityModifier(clickInModifier()); + } - @Override - public void onSliderEnd() { - registerEntityModifier(clickOutModifier()); - } + @Override + public void onSliderEnd() { + registerEntityModifier(clickOutModifier()); + } } diff --git a/src/ru/nsu/ccfit/zuev/osu/game/cursor/trail/CursorTrail.java b/src/ru/nsu/ccfit/zuev/osu/game/cursor/trail/CursorTrail.java index 10445481..a725e3ea 100644 --- a/src/ru/nsu/ccfit/zuev/osu/game/cursor/trail/CursorTrail.java +++ b/src/ru/nsu/ccfit/zuev/osu/game/cursor/trail/CursorTrail.java @@ -13,33 +13,33 @@ import ru.nsu.ccfit.zuev.osu.game.cursor.main.CursorSprite; public class CursorTrail extends ParticleSystem { - public CursorTrail( - PointParticleEmitter emitter, - int trailAmount, - int longTrailRateMultiplier, int longTrailMaxMultiplier, - float trailSize, - TextureRegion pTextureRegion - ) { - super( - emitter, - Config.isUseLongTrail()? trailAmount * longTrailRateMultiplier : trailAmount, - Config.isUseLongTrail()? trailAmount * longTrailRateMultiplier : trailAmount, - Config.isUseLongTrail()? trailAmount * longTrailMaxMultiplier : trailAmount, - pTextureRegion - ); + public CursorTrail( + PointParticleEmitter emitter, + int trailAmount, + int longTrailRateMultiplier, int longTrailMaxMultiplier, + float trailSize, + TextureRegion pTextureRegion + ) { + super( + emitter, + Config.isUseLongTrail()? trailAmount * longTrailRateMultiplier : trailAmount, + Config.isUseLongTrail()? trailAmount * longTrailRateMultiplier : trailAmount, + Config.isUseLongTrail()? trailAmount * longTrailMaxMultiplier : trailAmount, + pTextureRegion + ); - fadeOut(); - setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); - addParticleInitializer(new ScaleInitializer(trailSize)); - setParticlesSpawnEnabled(false); - } + fadeOut(); + setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); + addParticleInitializer(new ScaleInitializer(trailSize)); + setParticlesSpawnEnabled(false); + } - private void fadeOut() { - float defaultLifeTime = 0.25f; - float longLifeTime = defaultLifeTime * 2; - float lifeTime = Config.isUseLongTrail()? longLifeTime : defaultLifeTime; + private void fadeOut() { + float defaultLifeTime = 0.25f; + float longLifeTime = defaultLifeTime * 2; + float lifeTime = Config.isUseLongTrail()? longLifeTime : defaultLifeTime; - addParticleModifier(new ExpireModifier(lifeTime)); - addParticleModifier(new AlphaModifier(1.0f, 0.0f, 0f, lifeTime)); - } + addParticleModifier(new ExpireModifier(lifeTime)); + addParticleModifier(new AlphaModifier(1.0f, 0.0f, 0f, lifeTime)); + } } diff --git a/src/ru/nsu/ccfit/zuev/osu/game/mods/GameMod.java b/src/ru/nsu/ccfit/zuev/osu/game/mods/GameMod.java index 6d729c67..7c8ada39 100644 --- a/src/ru/nsu/ccfit/zuev/osu/game/mods/GameMod.java +++ b/src/ru/nsu/ccfit/zuev/osu/game/mods/GameMod.java @@ -1,40 +1,40 @@ package ru.nsu.ccfit.zuev.osu.game.mods; public enum GameMod { - /* - * Temporarily unranked mods (until adjusted): - * sd, pf, sc, re, fl - */ - MOD_NOFAIL("nf", 0.5f), - MOD_AUTO("auto", 0, true), - MOD_EASY("es", 0.5f), - MOD_HARDROCK("hr", 1.06f), - MOD_HIDDEN("hd", 1.06f), - MOD_RELAX("relax", 0.001f, true), - MOD_AUTOPILOT("ap", 0.001f, true), - MOD_DOUBLETIME("dt", 1.12f), - MOD_NIGHTCORE("nc", 1.12f), - MOD_HALFTIME("ht", 0.3f), - MOD_SUDDENDEATH("sd", 1, true), - MOD_PERFECT("pf", 1, true), - MOD_FLASHLIGHT("fl", 1.12f, true), - MOD_PRECISE("pr", 1.06f), - MOD_SMALLCIRCLE("sc", 1.06f, true), - MOD_REALLYEASY("re", 0.5f, true), - MOD_SCOREV2("v2", 1, true), - MOD_SPEEDUP("su", 1.06f, true); + /* + * Temporarily unranked mods (until adjusted): + * sd, pf, sc, re, fl + */ + MOD_NOFAIL("nf", 0.5f), + MOD_AUTO("auto", 0, true), + MOD_EASY("es", 0.5f), + MOD_HARDROCK("hr", 1.06f), + MOD_HIDDEN("hd", 1.06f), + MOD_RELAX("relax", 0.001f, true), + MOD_AUTOPILOT("ap", 0.001f, true), + MOD_DOUBLETIME("dt", 1.12f), + MOD_NIGHTCORE("nc", 1.12f), + MOD_HALFTIME("ht", 0.3f), + MOD_SUDDENDEATH("sd", 1, true), + MOD_PERFECT("pf", 1, true), + MOD_FLASHLIGHT("fl", 1.12f, true), + MOD_PRECISE("pr", 1.06f), + MOD_SMALLCIRCLE("sc", 1.06f, true), + MOD_REALLYEASY("re", 0.5f, true), + MOD_SCOREV2("v2", 1, true), + MOD_SPEEDUP("su", 1.06f, true); - public final String shortName; - public final float scoreMultiplier; - public final boolean unranked; + public final String shortName; + public final float scoreMultiplier; + public final boolean unranked; - GameMod(String shortName, float scoreMultiplier) { - this(shortName, scoreMultiplier, false); - } + GameMod(String shortName, float scoreMultiplier) { + this(shortName, scoreMultiplier, false); + } - GameMod(String shortName, float scoreMultiplier, boolean unranked) { - this.shortName = shortName; - this.scoreMultiplier = scoreMultiplier; - this.unranked = unranked; - } + GameMod(String shortName, float scoreMultiplier, boolean unranked) { + this.shortName = shortName; + this.scoreMultiplier = scoreMultiplier; + this.unranked = unranked; + } } diff --git a/src/ru/nsu/ccfit/zuev/osu/game/mods/IModSwitcher.java b/src/ru/nsu/ccfit/zuev/osu/game/mods/IModSwitcher.java index a4877e2d..76daa645 100644 --- a/src/ru/nsu/ccfit/zuev/osu/game/mods/IModSwitcher.java +++ b/src/ru/nsu/ccfit/zuev/osu/game/mods/IModSwitcher.java @@ -1,5 +1,5 @@ package ru.nsu.ccfit.zuev.osu.game.mods; public interface IModSwitcher { - public boolean switchMod(final GameMod mod); + public boolean switchMod(final GameMod mod); } diff --git a/src/ru/nsu/ccfit/zuev/osu/game/mods/ModButton.java b/src/ru/nsu/ccfit/zuev/osu/game/mods/ModButton.java index 5375f47a..267d61b3 100644 --- a/src/ru/nsu/ccfit/zuev/osu/game/mods/ModButton.java +++ b/src/ru/nsu/ccfit/zuev/osu/game/mods/ModButton.java @@ -7,47 +7,47 @@ import ru.nsu.ccfit.zuev.osu.Utils; public class ModButton extends Sprite { - private static final float initalScale = 1.4f; - private static final float selectedScale = 1.8f; - private static final float initalRotate = 0f; - private static final float selectedRotate = 5f; - - private GameMod mod; - private IModSwitcher switcher = null; - - public ModButton(float pX, float pY, String texture, GameMod mod) { - super(Utils.toRes(pX), Utils.toRes(pY), ResourceManager.getInstance().getTexture(texture)); - this.mod = mod; - setScale(initalScale); - } - - public void setSwitcher(IModSwitcher switcher) { - this.switcher = switcher; - } - - public void setModEnabled(boolean enabled) { - if (enabled) { - setScale(selectedScale); - setRotation(selectedRotate); - setColor(1, 1, 1); - } else { - setScale(initalScale); - setRotation(initalRotate); - setColor(0.7f, 0.7f, 0.7f); - } - } - - - @Override - public boolean onAreaTouched(TouchEvent pSceneTouchEvent, - float pTouchAreaLocalX, float pTouchAreaLocalY) { - if (pSceneTouchEvent.isActionDown() && switcher != null) { - setModEnabled(switcher.switchMod(mod)); - return true; - } - - return false; - } + private static final float initalScale = 1.4f; + private static final float selectedScale = 1.8f; + private static final float initalRotate = 0f; + private static final float selectedRotate = 5f; + + private GameMod mod; + private IModSwitcher switcher = null; + + public ModButton(float pX, float pY, String texture, GameMod mod) { + super(Utils.toRes(pX), Utils.toRes(pY), ResourceManager.getInstance().getTexture(texture)); + this.mod = mod; + setScale(initalScale); + } + + public void setSwitcher(IModSwitcher switcher) { + this.switcher = switcher; + } + + public void setModEnabled(boolean enabled) { + if (enabled) { + setScale(selectedScale); + setRotation(selectedRotate); + setColor(1, 1, 1); + } else { + setScale(initalScale); + setRotation(initalRotate); + setColor(0.7f, 0.7f, 0.7f); + } + } + + + @Override + public boolean onAreaTouched(TouchEvent pSceneTouchEvent, + float pTouchAreaLocalX, float pTouchAreaLocalY) { + if (pSceneTouchEvent.isActionDown() && switcher != null) { + setModEnabled(switcher.switchMod(mod)); + return true; + } + + return false; + } } diff --git a/src/ru/nsu/ccfit/zuev/osu/helper/AnimSprite.java b/src/ru/nsu/ccfit/zuev/osu/helper/AnimSprite.java index 16f4c908..6cf1da8f 100644 --- a/src/ru/nsu/ccfit/zuev/osu/helper/AnimSprite.java +++ b/src/ru/nsu/ccfit/zuev/osu/helper/AnimSprite.java @@ -10,161 +10,161 @@ public class AnimSprite extends Sprite { - public enum LoopType { - STOP, // stop at last frame - LOOP, // loop from start - DISAPPEAR, // disappear after last frame - FROZE // do not automatically update frame - } - - private final int count; - private final TextureRegion[] regions; - private int frame; - private float animTime; - private float fps; - private LoopType loopType = LoopType.LOOP; - - public AnimSprite(final float px, final float py, final String texname, - int count, final float fps) { - super(px, py, ResourceManager.getInstance().getTexture(texname + "0")); - if (count == 0) { - count = 1; - } - this.count = count; - this.fps = fps; - this.frame = 0; - this.animTime = 0; - regions = new TextureRegion[count]; - for (int i = 0; i < count; i++) { - regions[i] = ResourceManager.getInstance().getTexture(texname + i); - } - if (fps == 0) { - loopType = LoopType.FROZE; - } - } - - public AnimSprite(final float px, final float py, final float fps, - final String... textures) { - super(px, py, ResourceManager.getInstance().getTextureIfLoaded(textures[0])); - this.count = textures.length; - this.fps = fps; - this.frame = 0; - this.animTime = 0; - regions = new TextureRegion[count]; - for (int i = 0; i < count; i++) { - regions[i] = ResourceManager.getInstance().getTextureIfLoaded(textures[i]); - } - if (fps == 0) { - loopType = LoopType.FROZE; - } - } - - public void setLoopType(LoopType loopType) { - this.loopType = loopType; - } - - public LoopType getLoopType() { - return loopType; - } - - - /** - * Automatically update frame. - * If loopType is {@link LoopType#FROZE} or fps is 0, this will do nothing - */ - private void updateFrame() { - if (loopType == LoopType.FROZE || fps == 0) { - return; - } - int frameByTime = (int) (this.animTime * fps); - switch (loopType) { - case LOOP: - frame = frameByTime % count; - break; - case STOP: - frame = Math.min(frameByTime, count - 1); - break; - case DISAPPEAR: - frame = Math.min(frameByTime, count); - break; - default: - break; - } - } - - /** - * It's not recommended to call this method if you are not initialing this sprite - */ - public void setFps(final float fps) { - frame = 0; - this.fps = fps; - } - - - /** - * Force set animation to target frame. - * @param frame target frame - */ - public void setFrame(int frame) { - if (this.loopType == LoopType.FROZE || fps == 0) { - this.frame = frame; - } else { - this.animTime = (frame + 0.0001f) / fps; - updateFrame(); - } - } - - public void setAnimTime(float animTime) { - this.animTime = animTime; - updateFrame(); - } - - @Override - protected void onManagedUpdate(final float pSecondsElapsed) { - this.animTime += pSecondsElapsed; - updateFrame(); - super.onManagedUpdate(pSecondsElapsed); - } - - - @Override - protected void doDraw(final GL10 pGL, final Camera pCamera) { - if (regions.length == 0 || frame < 0 || frame >= regions.length) { - return; - } - regions[frame].onApply(pGL); - onInitDraw(pGL); - onApplyVertices(pGL); - drawVertices(pGL, pCamera); - } - - - @Override - public void setFlippedHorizontal(final boolean pFlippedHorizontal) { - for (final TextureRegion reg : regions) { - reg.setFlippedHorizontal(pFlippedHorizontal); - } - } - - public float getFrameWidth() { - if (frame < regions.length && frame >= 0) { - return regions[frame].getWidth(); - } else if (regions.length > 0) { - return regions[0].getWidth(); - } else { - return 40; - } - } - - public void setTextureRegion(final int index, final TextureRegion region) { - regions[index] = region; - } - - public TextureRegion getTextureRegionAt(final int index) { - return regions[index]; - } - - public int getTextureRegionCount() { - return regions.length; - } + public enum LoopType { + STOP, // stop at last frame + LOOP, // loop from start + DISAPPEAR, // disappear after last frame + FROZE // do not automatically update frame + } + + private final int count; + private final TextureRegion[] regions; + private int frame; + private float animTime; + private float fps; + private LoopType loopType = LoopType.LOOP; + + public AnimSprite(final float px, final float py, final String texname, + int count, final float fps) { + super(px, py, ResourceManager.getInstance().getTexture(texname + "0")); + if (count == 0) { + count = 1; + } + this.count = count; + this.fps = fps; + this.frame = 0; + this.animTime = 0; + regions = new TextureRegion[count]; + for (int i = 0; i < count; i++) { + regions[i] = ResourceManager.getInstance().getTexture(texname + i); + } + if (fps == 0) { + loopType = LoopType.FROZE; + } + } + + public AnimSprite(final float px, final float py, final float fps, + final String... textures) { + super(px, py, ResourceManager.getInstance().getTextureIfLoaded(textures[0])); + this.count = textures.length; + this.fps = fps; + this.frame = 0; + this.animTime = 0; + regions = new TextureRegion[count]; + for (int i = 0; i < count; i++) { + regions[i] = ResourceManager.getInstance().getTextureIfLoaded(textures[i]); + } + if (fps == 0) { + loopType = LoopType.FROZE; + } + } + + public void setLoopType(LoopType loopType) { + this.loopType = loopType; + } + + public LoopType getLoopType() { + return loopType; + } + + + /** + * Automatically update frame. + * If loopType is {@link LoopType#FROZE} or fps is 0, this will do nothing + */ + private void updateFrame() { + if (loopType == LoopType.FROZE || fps == 0) { + return; + } + int frameByTime = (int) (this.animTime * fps); + switch (loopType) { + case LOOP: + frame = frameByTime % count; + break; + case STOP: + frame = Math.min(frameByTime, count - 1); + break; + case DISAPPEAR: + frame = Math.min(frameByTime, count); + break; + default: + break; + } + } + + /** + * It's not recommended to call this method if you are not initialing this sprite + */ + public void setFps(final float fps) { + frame = 0; + this.fps = fps; + } + + + /** + * Force set animation to target frame. + * @param frame target frame + */ + public void setFrame(int frame) { + if (this.loopType == LoopType.FROZE || fps == 0) { + this.frame = frame; + } else { + this.animTime = (frame + 0.0001f) / fps; + updateFrame(); + } + } + + public void setAnimTime(float animTime) { + this.animTime = animTime; + updateFrame(); + } + + @Override + protected void onManagedUpdate(final float pSecondsElapsed) { + this.animTime += pSecondsElapsed; + updateFrame(); + super.onManagedUpdate(pSecondsElapsed); + } + + + @Override + protected void doDraw(final GL10 pGL, final Camera pCamera) { + if (regions.length == 0 || frame < 0 || frame >= regions.length) { + return; + } + regions[frame].onApply(pGL); + onInitDraw(pGL); + onApplyVertices(pGL); + drawVertices(pGL, pCamera); + } + + + @Override + public void setFlippedHorizontal(final boolean pFlippedHorizontal) { + for (final TextureRegion reg : regions) { + reg.setFlippedHorizontal(pFlippedHorizontal); + } + } + + public float getFrameWidth() { + if (frame < regions.length && frame >= 0) { + return regions[frame].getWidth(); + } else if (regions.length > 0) { + return regions[0].getWidth(); + } else { + return 40; + } + } + + public void setTextureRegion(final int index, final TextureRegion region) { + regions[index] = region; + } + + public TextureRegion getTextureRegionAt(final int index) { + return regions[index]; + } + + public int getTextureRegionCount() { + return regions.length; + } } diff --git a/src/ru/nsu/ccfit/zuev/osu/helper/CentredSprite.java b/src/ru/nsu/ccfit/zuev/osu/helper/CentredSprite.java index 0aa7b43d..89a43c49 100644 --- a/src/ru/nsu/ccfit/zuev/osu/helper/CentredSprite.java +++ b/src/ru/nsu/ccfit/zuev/osu/helper/CentredSprite.java @@ -5,10 +5,10 @@ public class CentredSprite extends Sprite { - public CentredSprite(final float pX, final float pY, - final TextureRegion pTextureRegion) { - super(pX - pTextureRegion.getWidth() / 2, pY - - pTextureRegion.getHeight() / 2, pTextureRegion); - } + public CentredSprite(final float pX, final float pY, + final TextureRegion pTextureRegion) { + super(pX - pTextureRegion.getWidth() / 2, pY + - pTextureRegion.getHeight() / 2, pTextureRegion); + } } diff --git a/src/ru/nsu/ccfit/zuev/osu/helper/DifficultyHelper.java b/src/ru/nsu/ccfit/zuev/osu/helper/DifficultyHelper.java index 10a023b6..5fe2358e 100644 --- a/src/ru/nsu/ccfit/zuev/osu/helper/DifficultyHelper.java +++ b/src/ru/nsu/ccfit/zuev/osu/helper/DifficultyHelper.java @@ -2,45 +2,45 @@ public abstract class DifficultyHelper { - public static final DifficultyHelper StdDifficulty = new DifficultyHelper() { + public static final DifficultyHelper StdDifficulty = new DifficultyHelper() { - @Override - public float hitWindowFor300(float od) { - return (75 + 25 * (5 - od) / 5) / 1000; - } + @Override + public float hitWindowFor300(float od) { + return (75 + 25 * (5 - od) / 5) / 1000; + } - @Override - public float hitWindowFor100(float od) { - return (150 + 50 * (5 - od) / 5) / 1000; - } + @Override + public float hitWindowFor100(float od) { + return (150 + 50 * (5 - od) / 5) / 1000; + } - @Override - public float hitWindowFor50(float od) { - return (250 + 50 * (5 - od) / 5) / 1000f; - } - }; + @Override + public float hitWindowFor50(float od) { + return (250 + 50 * (5 - od) / 5) / 1000f; + } + }; - public static DifficultyHelper HighDifficulty = new DifficultyHelper() { + public static DifficultyHelper HighDifficulty = new DifficultyHelper() { - @Override - public float hitWindowFor300(float od) { - return (55 + 30 * (5 - od) / 5) / 1000f; - } + @Override + public float hitWindowFor300(float od) { + return (55 + 30 * (5 - od) / 5) / 1000f; + } - @Override - public float hitWindowFor100(float od) { - return (120 + 40 * (5 - od) / 5) / 1000f; - } + @Override + public float hitWindowFor100(float od) { + return (120 + 40 * (5 - od) / 5) / 1000f; + } - @Override - public float hitWindowFor50(float od) { - return (180 + 50 * (5 - od) / 5) / 1000f; - } - }; + @Override + public float hitWindowFor50(float od) { + return (180 + 50 * (5 - od) / 5) / 1000f; + } + }; - public abstract float hitWindowFor300(float od); + public abstract float hitWindowFor300(float od); - public abstract float hitWindowFor100(float od); + public abstract float hitWindowFor100(float od); - public abstract float hitWindowFor50(float od); + public abstract float hitWindowFor50(float od); } diff --git a/src/ru/nsu/ccfit/zuev/osu/helper/DifficultyReCalculator.java b/src/ru/nsu/ccfit/zuev/osu/helper/DifficultyReCalculator.java index 34046a6a..e6a779c2 100644 --- a/src/ru/nsu/ccfit/zuev/osu/helper/DifficultyReCalculator.java +++ b/src/ru/nsu/ccfit/zuev/osu/helper/DifficultyReCalculator.java @@ -27,586 +27,586 @@ import test.tpdifficulty.tp.AiModtpDifficulty; public class DifficultyReCalculator { - private OSUParser parser; - private final ArrayList timingPoints = new ArrayList<>(); - private final ArrayList hitObjects = new ArrayList<>(); - private TimingPoint currentTimingPoint = null; - private double total, aim, speed, acc; - private AiModtpDifficulty tpDifficulty; - private int single, fast_single, stream, jump, switch_fingering, multi; - private int stream_longest; - private float real_time; - //copy from OSUParser.java - public boolean init(final TrackInfo track) { - parser = new OSUParser(track.getFilename()); - final BeatmapData data; - if (parser.openFile()) { - data = parser.readData(); - } else { - Debug.e("startGame: cannot open file"); - ToastLogger.showText( - StringTable.format(R.string.message_error_open, - track.getFilename()), true); - return false; - } - - if (GlobalManager.getInstance().getSongMenu().getSelectedTrack() != track) { - return false; - } - - if (!loadTimingPoints(data)) { - return false; - } - float sliderSpeed = parser.tryParseFloat(data.getData("Difficulty", "SliderMultiplier"), 1.0f); - return loadHitObjects(data, sliderSpeed); - } - - private boolean loadTimingPoints(final BeatmapData data) { - // Load timing points - timingPoints.clear(); - - // Get the first uninherited timing point - for (final String tempString : data.getData("TimingPoints")) { - String[] rawData = tempString.split("[,]"); - // Handle malformed timing point - if (rawData.length < 2) { - return false; - } - float bpm = parser.tryParseFloat(rawData[1], Float.NaN); - if (Float.isNaN(bpm)) { - return false; - } - - // Uninherited: bpm > 0 - if (bpm > 0) { - float offset = parser.tryParseFloat(rawData[0], Float.NaN); - if (Float.isNaN(offset)) { - return false; - } - currentTimingPoint = new TimingPoint(bpm, offset, 1f); - break; - } - } - - if (currentTimingPoint == null) { - return false; - } - - for (final String tempString : data.getData("TimingPoints")) { - String[] rawData = tempString.split("[,]"); - // Handle malformed timing point - if (rawData.length < 2) { - return false; - } - float offset = parser.tryParseFloat(rawData[0], Float.NaN); - float bpm = parser.tryParseFloat(rawData[1], Float.NaN); - if (Float.isNaN(offset) || Float.isNaN(bpm)) { - return false; - } - float speed = 1.0f; - boolean inherited = bpm < 0; - - if (inherited) { - speed = -100.0f / bpm; - bpm = currentTimingPoint.getBpm(); - } else { - bpm = 60000.0f / bpm; - } - TimingPoint timing = new TimingPoint(bpm, offset, speed); - if (!inherited) { - currentTimingPoint = timing; - } - timingPoints.add(timing); - } - - return timingPoints.size() > 0; - } - - private boolean loadHitObjects(final BeatmapData data, float sliderSpeed) { - final ArrayList hitObjects = data.getData("HitObjects"); - if (hitObjects.size() <= 0) { - return false; - } - - this.hitObjects.clear(); - int tpIndex = 0; - currentTimingPoint = timingPoints.get(tpIndex); - - for (final String tempString : hitObjects) { - String[] hitObjectData = tempString.split("[,]"); - String[] rawData; - - // Ignoring v10 features - int dataSize = hitObjectData.length; - while (dataSize > 0 && hitObjectData[dataSize - 1].matches("([0-9][:][0-9][|]?)+")) { - dataSize--; - } - if (dataSize < hitObjectData.length) { - rawData = new String[dataSize]; - for (int i = 0; i < rawData.length; i++) { - rawData[i] = hitObjectData[i]; - } - } else { - rawData = hitObjectData; - } - - // Handle malformed hitobject - if (rawData.length < 4) { - return false; - } - - int time = parser.tryParseInt(rawData[2], -1); - if (time <= -1) { - return false; - } - while (tpIndex < timingPoints.size() - 1 && timingPoints.get(tpIndex + 1).getOffset() <= time) { - tpIndex++; - } - currentTimingPoint = timingPoints.get(tpIndex); - HitObjectType hitObjectType = HitObjectType.valueOf(parser.tryParseInt(rawData[3], -1) % 16); - PointF pos = new PointF( - parser.tryParseFloat(rawData[0], Float.NaN), - parser.tryParseFloat(rawData[1], Float.NaN) - ); - if (Float.isNaN(pos.x) || Float.isNaN(pos.y)) { - return false; - } - HitObject object = null; - if (hitObjectType == null) { - System.out.println(tempString); - return false; - } - - if (hitObjectType == HitObjectType.Normal || hitObjectType == HitObjectType.NormalNewCombo) { - // HitCircle - object = new HitCircle(time, pos, currentTimingPoint); - } else if (hitObjectType == HitObjectType.Spinner) { - // Spinner - int endTime = parser.tryParseInt(rawData[5], -1); - if (endTime <= -1) { - return false; - } - object = new Spinner(time, endTime, pos, currentTimingPoint); - } else if (hitObjectType == HitObjectType.Slider || hitObjectType == HitObjectType.SliderNewCombo) { - // Slider - // Handle malformed slider - boolean isValidSlider = rawData.length >= 8; - if (!isValidSlider) { - return false; - } - - String[] curvePointsData = rawData[5].split("[|]"); - SliderType sliderType = SliderType.parse(curvePointsData[0].charAt(0)); - ArrayList curvePoints = new ArrayList<>(); - for (int i = 1; i < curvePointsData.length; i++) { - String[] curvePointData = curvePointsData[i].split("[:]"); - PointF curvePointPosition = new PointF( - parser.tryParseFloat(curvePointData[0], Float.NaN), - parser.tryParseFloat(curvePointData[1], Float.NaN) - ); - if (Float.isNaN(curvePointPosition.x) || Float.isNaN(curvePointPosition.y)) { - isValidSlider = false; - break; - } - curvePoints.add(curvePointPosition); - } - if (!isValidSlider) { - return false; - } - - int repeat = parser.tryParseInt(rawData[6], -1); - float rawLength = parser.tryParseFloat(rawData[7], Float.NaN); - if (repeat <= -1 || Float.isNaN(rawLength)) { - return false; - } - - int endTime = time + (int) (rawLength * (600 / timingPoints.get(0).getBpm()) / sliderSpeed) * repeat; - object = new Slider(time, endTime, pos, currentTimingPoint, sliderType, repeat, curvePoints, rawLength); - } - this.hitObjects.add(object); - } - - return this.hitObjects.size() > 0; - } - - public float recalculateStar(final TrackInfo track, float cs){ - return recalculateStar(track, cs, 1.0f); - } - - public float recalculateStar(final TrackInfo track, float cs, float speed) { - if (!init(track)) { - return 0f; - } - if (GlobalManager.getInstance().getSongMenu().getSelectedTrack() != track){ - return 0f; - } - try { - tpDifficulty = new AiModtpDifficulty(); - tpDifficulty.CalculateAll(hitObjects, cs, speed); - double star = tpDifficulty.getStarRating(); - if (!timingPoints.isEmpty()){ - timingPoints.clear(); - } - if (!hitObjects.isEmpty()){ - hitObjects.clear(); - } - if (GlobalManager.getInstance().getSongMenu().getSelectedTrack() != track){ - return 0f; - } - return GameHelper.Round(star, 2); - } catch (Exception e) { - return 0f; - } - } - - //must use recalculateStar() before this - public void calculatePP(final StatisticV2 stat, final TrackInfo track) { - pp(tpDifficulty, track, stat, stat.getAccuracy()); - } - - //must use recalculateStar() before this - public void calculateMaxPP(final StatisticV2 stat, final TrackInfo track) { - pp(tpDifficulty, track, stat, 1f); - } - - //copy from koohii.java - private double pp_base(double stars) - { - return Math.pow(5.0 * Math.max(1.0, stars / 0.0675) - 4.0, 3.0) - / 100000.0; - } - - //copy from koohii.java - private void pp(AiModtpDifficulty tpDifficulty, TrackInfo track, - StatisticV2 stat, - float accuracy) { - /* global values --------------------------------------- */ - EnumSet mods = stat.getMod(); - int max_combo = stat.getMaxCombo(); - int combo = track.getMaxCombo(); - int ncircles = track.getHitCircleCount(); - int nobjects = track.getTotalHitObjectCount(); - int nmiss = stat.getMisses(); - float base_ar = getAR(stat, track); - float base_od = getOD(stat, track); - if (accuracy == 1f) { - combo = max_combo; - nmiss = 0; - } - double nobjects_over_2k = nobjects / 2000.0; - - double length_bonus = 0.95 + 0.4 * - Math.min(1.0, nobjects_over_2k); - - if (nobjects > 2000) { - length_bonus += Math.log10(nobjects_over_2k) * 0.5; - } - - double combo_break = Math.min(1.0, Math.pow((double) combo / max_combo, 0.8)); - - /* ar bonus -------------------------------------------- */ - double ar_bonus = 0.0; - - if (base_ar > 10.33) { - ar_bonus += 0.4 * (base_ar - 10.33); - } - - else if (base_ar < 8.0) { - ar_bonus += 0.1 * (8.0 - base_ar); - } - - ar_bonus = 1 + Math.min(ar_bonus, ar_bonus * nobjects / 1000); - - /* aim pp ---------------------------------------------- */ - aim = pp_base(tpDifficulty.getAimStars()); - aim *= length_bonus; - aim *= combo_break; - aim *= ar_bonus; - - // aim miss penalty - if (nmiss > 0){ - aim *= 0.97 * Math.pow(1 - Math.pow((double) nmiss / nobjects, 0.775), nmiss); - } - - double hd_bonus = 1.0; - if (mods.contains(GameMod.MOD_HIDDEN)) { - hd_bonus *= 1.0 + 0.04 * (12.0 - base_ar); - } - aim *= hd_bonus; - - if (mods.contains(GameMod.MOD_FLASHLIGHT)) { - double fl_bonus = 1.0 + 0.35 * Math.min(1.0, nobjects / 200.0); - if (nobjects > 200) { - fl_bonus += 0.3 * Math.min(1.0, (nobjects - 200) / 300.0); - } - if (nobjects > 500) { - fl_bonus += (nobjects - 500) / 1200.0; - } - aim *= fl_bonus; - } - - double acc_bonus = 0.5 + accuracy / 2.0; - double od_squared = base_od * base_od; - double od_bonus = 0.98 + od_squared / 2500.0; - - aim *= acc_bonus; - aim *= od_bonus; - if (mods.contains(GameMod.MOD_AUTOPILOT)) { - aim *= 0; - } - /* speed pp -------------------------------------------- */ - speed = pp_base(tpDifficulty.getSpeedStars()); - speed *= length_bonus; - speed *= combo_break; - if (base_ar > 10.33) { - speed *= ar_bonus; - } - speed *= hd_bonus; - - // speed miss penalty - if (nmiss > 0){ - speed *= 0.97 * Math.pow(1 - Math.pow((double) nmiss / nobjects, 0.775), Math.pow(nmiss, 0.875)); - } - - // scale the speed value with accuracy and OD - speed *= (0.95 + Math.pow(base_od, 2) / 750) * Math.pow(accuracy, (14.5 - Math.max(base_od, 8)) / 2); - // scale the speed value with # of 50s to punish doubletapping - if (accuracy != 1f) { - speed *= Math.pow(0.98, Math.max(0, stat.getHit50() - nobjects / 500)); - } - if (mods.contains(GameMod.MOD_RELAX)) { - speed *= 0; - } - /* acc pp ---------------------------------------------- */ - acc = Math.pow(1.52163, base_od) * - Math.pow(accuracy, 24.0) * 2.83; - - acc *= Math.min(1.15, Math.pow(ncircles / 1000.0, 0.3)); - - if (mods.contains(GameMod.MOD_HIDDEN)) { - acc *= 1.08; - } - - if (mods.contains(GameMod.MOD_FLASHLIGHT)) { - acc *= 1.02; - } - - if (mods.contains(GameMod.MOD_RELAX)) { - acc *= 0.1; - } - /* total pp -------------------------------------------- */ - double final_multiplier = 1.12; - - if (mods.contains(GameMod.MOD_NOFAIL)){ - final_multiplier *= Math.max(0.9, 1.0 - 0.02 * nmiss); - } - - //if ((mods & MODS_SO) != 0) { - // final_multiplier *= 0.95; - //} - - total = Math.pow( - Math.pow(aim, 1.1) + Math.pow(speed, 1.1) + - Math.pow(acc, 1.1), - 1.0 / 1.1 - ) * final_multiplier; - } - - public double getTotalPP() { - return total; - } - - public double getAimPP() { - return aim; - } - - public double getSpdPP() { - return speed; - } - - public double getAccPP() { - return acc; - } - - private float getAR(final StatisticV2 stat, final TrackInfo track) { - // no need to calculate force AR value - if (stat.isEnableForceAR()) { - return stat.getForceAR(); - } - float ar = track.getApproachRate(); - EnumSet mod = stat.getMod(); - if (mod.contains(GameMod.MOD_EASY)) { - ar *= 0.5f; - } - if (mod.contains(GameMod.MOD_HARDROCK)) { - ar = Math.min(ar * 1.4f, 10); - } - float speed = stat.getSpeed(); - if (mod.contains(GameMod.MOD_REALLYEASY)) { - if (mod.contains(GameMod.MOD_EASY)){ - ar *= 2f; - ar -= 0.5f; - } - ar -= 0.5f; - ar -= speed - 1.0f; - } - ar = GameHelper.Round(GameHelper.ms2ar(GameHelper.ar2ms(Math.min(13.f, ar)) / speed), 2); - return ar; - } - - private float getOD(final StatisticV2 stat, final TrackInfo track) { - float od = track.getOverallDifficulty(); - EnumSet mod = stat.getMod(); - if (mod.contains(GameMod.MOD_EASY)) { - od *= 0.5f; - } - if (mod.contains(GameMod.MOD_HARDROCK)) { - od *= 1.4f; - } - float speed = stat.getSpeed(); - if (mod.contains(GameMod.MOD_REALLYEASY)) { - od *= 0.5f; - } - od = Math.min(10.f, od); - od = GameHelper.Round(GameHelper.ms2od(GameHelper.od2ms(od) / speed), 2); - return od; - } - - public float getCS(EnumSet mod, final TrackInfo track) { - float cs = track.getCircleSize(); - if (mod.contains(GameMod.MOD_EASY)) { - cs -= 1f; - } - if (mod.contains(GameMod.MOD_HARDROCK)) { - cs += 1f; - } - if (mod.contains(GameMod.MOD_REALLYEASY)) { - cs -= 1f; - } - if (mod.contains(GameMod.MOD_SMALLCIRCLE)) { - cs += 4f; - } - return cs; - } - - public float getCS(final StatisticV2 stat, final TrackInfo track) { - return getCS(stat.getMod(), track); - } - - public float getCS(final TrackInfo track) { - return getCS(ModMenu.getInstance().getMod(), track); - } - - //must use reCalculateStar() before this - //This method calculate the note count of stream/jump/etc in a diff - //public boolean calculateMapInfo(final TrackInfo track, float speedMultiplier) { - //计算谱面信息 - /* - 120bpm: 125ms(dt1), 140bpm: 107ms(dt3), 80bpm: 187.5(dt4), 180bpm: 83.33ms(dt2) - 单点:低于120bpm,间距小于180 - 高速单点:高于120bpm且间距大于90、低于180bpm且间距大于90、小于180 - 连打:高于120bpm且间距小于90,高于180bpm且间距大于90、小于180 - 跳:间距大于180 - */ - /* - if (!init(track)) { - return false; - } - if (GlobalManager.getInstance().getSongMenu().getSelectedTrack() != track){ - return false; - } - final int ds1 = 90, ds2 = 180; - final int dt1 = 125, dt2 = 83, dt3 = 107, dt4 = 188; - single = fast_single = stream = jump = switch_fingering = multi = 0; - stream_longest = 0; - int combo = 0; - int last_delta_time = 0; - HitObject prev = null; - boolean first = true; - int firstObjectTime = 0; - for (HitObject object : hitObjects){ - if (object.getType() == HitObjectType.Spinner){ - continue; - } - if (prev != null){ - int delta_time = object.getStartTime() - prev.getStartTime(); - int distance = (int)Math.sqrt(Math.pow(object.getPos().x - prev.getPos().x, 2) + Math.pow(object.getPos().y - prev.getPos().y, 2)); - if ((delta_time >= dt1 && distance <= ds2) || (delta_time >= dt4 * 4)){ - single++; - } - else if(delta_time >= dt2 && distance >= ds1 && distance <= ds2){ - fast_single++; - } - else if((delta_time <= dt1 && distance <= ds1) || (delta_time <= dt2 && distance <= ds2)){ - stream++; - } - else if(distance >= ds2){ - jump++; - } - else{ - single++; - } - //多押 - if (first && delta_time == 0){ - first = false; - multi += 2; - } - else if (delta_time == 0){ - multi++; - } - else if (delta_time != 0){ - first = true; - } - //切指 - if (delta_time < last_delta_time * 1.2f && delta_time > last_delta_time * 0.8f){ - } - else if ((delta_time < dt3 || last_delta_time < dt3) && last_delta_time != 0 && delta_time < dt4 && last_delta_time < dt4){ - switch_fingering += 2; - } - //最长连打 - if (delta_time > dt3 || last_delta_time > dt3){ - if (combo != 0 && stream_longest < combo + 2){ - stream_longest = combo + 2; - } - combo = 0; - } - else{ - combo++; - } - last_delta_time = delta_time; - } - else { - firstObjectTime = object.getStartTime(); - } - prev = object; - } - //实际游玩时间 - real_time = (hitObjects.get(hitObjects.size() - 1).getEndTime() - firstObjectTime) / 1000f; - return true; - } - */ - public int getSingleCount(){ - return single; - } - public int getFastSingleCount(){ - return fast_single; - } - public int getStreamCount(){ - return stream; - } - public int getJumpCount(){ - return jump; - } - public int getSwitchFingeringCount(){ - return switch_fingering; - } - public int getMultiCount(){ - return multi; - } - public int getLongestStreamCount(){ - return stream_longest; - } - public float getRealTime(){ - return real_time; - } -} \ No newline at end of file + private OSUParser parser; + private final ArrayList timingPoints = new ArrayList<>(); + private final ArrayList hitObjects = new ArrayList<>(); + private TimingPoint currentTimingPoint = null; + private double total, aim, speed, acc; + private AiModtpDifficulty tpDifficulty; + private int single, fast_single, stream, jump, switch_fingering, multi; + private int stream_longest; + private float real_time; + //copy from OSUParser.java + public boolean init(final TrackInfo track) { + parser = new OSUParser(track.getFilename()); + final BeatmapData data; + if (parser.openFile()) { + data = parser.readData(); + } else { + Debug.e("startGame: cannot open file"); + ToastLogger.showText( + StringTable.format(R.string.message_error_open, + track.getFilename()), true); + return false; + } + + if (GlobalManager.getInstance().getSongMenu().getSelectedTrack() != track) { + return false; + } + + if (!loadTimingPoints(data)) { + return false; + } + float sliderSpeed = parser.tryParseFloat(data.getData("Difficulty", "SliderMultiplier"), 1.0f); + return loadHitObjects(data, sliderSpeed); + } + + private boolean loadTimingPoints(final BeatmapData data) { + // Load timing points + timingPoints.clear(); + + // Get the first uninherited timing point + for (final String tempString : data.getData("TimingPoints")) { + String[] rawData = tempString.split("[,]"); + // Handle malformed timing point + if (rawData.length < 2) { + return false; + } + float bpm = parser.tryParseFloat(rawData[1], Float.NaN); + if (Float.isNaN(bpm)) { + return false; + } + + // Uninherited: bpm > 0 + if (bpm > 0) { + float offset = parser.tryParseFloat(rawData[0], Float.NaN); + if (Float.isNaN(offset)) { + return false; + } + currentTimingPoint = new TimingPoint(bpm, offset, 1f); + break; + } + } + + if (currentTimingPoint == null) { + return false; + } + + for (final String tempString : data.getData("TimingPoints")) { + String[] rawData = tempString.split("[,]"); + // Handle malformed timing point + if (rawData.length < 2) { + return false; + } + float offset = parser.tryParseFloat(rawData[0], Float.NaN); + float bpm = parser.tryParseFloat(rawData[1], Float.NaN); + if (Float.isNaN(offset) || Float.isNaN(bpm)) { + return false; + } + float speed = 1.0f; + boolean inherited = bpm < 0; + + if (inherited) { + speed = -100.0f / bpm; + bpm = currentTimingPoint.getBpm(); + } else { + bpm = 60000.0f / bpm; + } + TimingPoint timing = new TimingPoint(bpm, offset, speed); + if (!inherited) { + currentTimingPoint = timing; + } + timingPoints.add(timing); + } + + return timingPoints.size() > 0; + } + + private boolean loadHitObjects(final BeatmapData data, float sliderSpeed) { + final ArrayList hitObjects = data.getData("HitObjects"); + if (hitObjects.size() <= 0) { + return false; + } + + this.hitObjects.clear(); + int tpIndex = 0; + currentTimingPoint = timingPoints.get(tpIndex); + + for (final String tempString : hitObjects) { + String[] hitObjectData = tempString.split("[,]"); + String[] rawData; + + // Ignoring v10 features + int dataSize = hitObjectData.length; + while (dataSize > 0 && hitObjectData[dataSize - 1].matches("([0-9][:][0-9][|]?)+")) { + dataSize--; + } + if (dataSize < hitObjectData.length) { + rawData = new String[dataSize]; + for (int i = 0; i < rawData.length; i++) { + rawData[i] = hitObjectData[i]; + } + } else { + rawData = hitObjectData; + } + + // Handle malformed hitobject + if (rawData.length < 4) { + return false; + } + + int time = parser.tryParseInt(rawData[2], -1); + if (time <= -1) { + return false; + } + while (tpIndex < timingPoints.size() - 1 && timingPoints.get(tpIndex + 1).getOffset() <= time) { + tpIndex++; + } + currentTimingPoint = timingPoints.get(tpIndex); + HitObjectType hitObjectType = HitObjectType.valueOf(parser.tryParseInt(rawData[3], -1) % 16); + PointF pos = new PointF( + parser.tryParseFloat(rawData[0], Float.NaN), + parser.tryParseFloat(rawData[1], Float.NaN) + ); + if (Float.isNaN(pos.x) || Float.isNaN(pos.y)) { + return false; + } + HitObject object = null; + if (hitObjectType == null) { + System.out.println(tempString); + return false; + } + + if (hitObjectType == HitObjectType.Normal || hitObjectType == HitObjectType.NormalNewCombo) { + // HitCircle + object = new HitCircle(time, pos, currentTimingPoint); + } else if (hitObjectType == HitObjectType.Spinner) { + // Spinner + int endTime = parser.tryParseInt(rawData[5], -1); + if (endTime <= -1) { + return false; + } + object = new Spinner(time, endTime, pos, currentTimingPoint); + } else if (hitObjectType == HitObjectType.Slider || hitObjectType == HitObjectType.SliderNewCombo) { + // Slider + // Handle malformed slider + boolean isValidSlider = rawData.length >= 8; + if (!isValidSlider) { + return false; + } + + String[] curvePointsData = rawData[5].split("[|]"); + SliderType sliderType = SliderType.parse(curvePointsData[0].charAt(0)); + ArrayList curvePoints = new ArrayList<>(); + for (int i = 1; i < curvePointsData.length; i++) { + String[] curvePointData = curvePointsData[i].split("[:]"); + PointF curvePointPosition = new PointF( + parser.tryParseFloat(curvePointData[0], Float.NaN), + parser.tryParseFloat(curvePointData[1], Float.NaN) + ); + if (Float.isNaN(curvePointPosition.x) || Float.isNaN(curvePointPosition.y)) { + isValidSlider = false; + break; + } + curvePoints.add(curvePointPosition); + } + if (!isValidSlider) { + return false; + } + + int repeat = parser.tryParseInt(rawData[6], -1); + float rawLength = parser.tryParseFloat(rawData[7], Float.NaN); + if (repeat <= -1 || Float.isNaN(rawLength)) { + return false; + } + + int endTime = time + (int) (rawLength * (600 / timingPoints.get(0).getBpm()) / sliderSpeed) * repeat; + object = new Slider(time, endTime, pos, currentTimingPoint, sliderType, repeat, curvePoints, rawLength); + } + this.hitObjects.add(object); + } + + return this.hitObjects.size() > 0; + } + + public float recalculateStar(final TrackInfo track, float cs){ + return recalculateStar(track, cs, 1.0f); + } + + public float recalculateStar(final TrackInfo track, float cs, float speed) { + if (!init(track)) { + return 0f; + } + if (GlobalManager.getInstance().getSongMenu().getSelectedTrack() != track){ + return 0f; + } + try { + tpDifficulty = new AiModtpDifficulty(); + tpDifficulty.CalculateAll(hitObjects, cs, speed); + double star = tpDifficulty.getStarRating(); + if (!timingPoints.isEmpty()){ + timingPoints.clear(); + } + if (!hitObjects.isEmpty()){ + hitObjects.clear(); + } + if (GlobalManager.getInstance().getSongMenu().getSelectedTrack() != track){ + return 0f; + } + return GameHelper.Round(star, 2); + } catch (Exception e) { + return 0f; + } + } + + //must use recalculateStar() before this + public void calculatePP(final StatisticV2 stat, final TrackInfo track) { + pp(tpDifficulty, track, stat, stat.getAccuracy()); + } + + //must use recalculateStar() before this + public void calculateMaxPP(final StatisticV2 stat, final TrackInfo track) { + pp(tpDifficulty, track, stat, 1f); + } + + //copy from koohii.java + private double pp_base(double stars) + { + return Math.pow(5.0 * Math.max(1.0, stars / 0.0675) - 4.0, 3.0) + / 100000.0; + } + + //copy from koohii.java + private void pp(AiModtpDifficulty tpDifficulty, TrackInfo track, + StatisticV2 stat, + float accuracy) { + /* global values --------------------------------------- */ + EnumSet mods = stat.getMod(); + int max_combo = stat.getMaxCombo(); + int combo = track.getMaxCombo(); + int ncircles = track.getHitCircleCount(); + int nobjects = track.getTotalHitObjectCount(); + int nmiss = stat.getMisses(); + float base_ar = getAR(stat, track); + float base_od = getOD(stat, track); + if (accuracy == 1f) { + combo = max_combo; + nmiss = 0; + } + double nobjects_over_2k = nobjects / 2000.0; + + double length_bonus = 0.95 + 0.4 * + Math.min(1.0, nobjects_over_2k); + + if (nobjects > 2000) { + length_bonus += Math.log10(nobjects_over_2k) * 0.5; + } + + double combo_break = Math.min(1.0, Math.pow((double) combo / max_combo, 0.8)); + + /* ar bonus -------------------------------------------- */ + double ar_bonus = 0.0; + + if (base_ar > 10.33) { + ar_bonus += 0.4 * (base_ar - 10.33); + } + + else if (base_ar < 8.0) { + ar_bonus += 0.1 * (8.0 - base_ar); + } + + ar_bonus = 1 + Math.min(ar_bonus, ar_bonus * nobjects / 1000); + + /* aim pp ---------------------------------------------- */ + aim = pp_base(tpDifficulty.getAimStars()); + aim *= length_bonus; + aim *= combo_break; + aim *= ar_bonus; + + // aim miss penalty + if (nmiss > 0){ + aim *= 0.97 * Math.pow(1 - Math.pow((double) nmiss / nobjects, 0.775), nmiss); + } + + double hd_bonus = 1.0; + if (mods.contains(GameMod.MOD_HIDDEN)) { + hd_bonus *= 1.0 + 0.04 * (12.0 - base_ar); + } + aim *= hd_bonus; + + if (mods.contains(GameMod.MOD_FLASHLIGHT)) { + double fl_bonus = 1.0 + 0.35 * Math.min(1.0, nobjects / 200.0); + if (nobjects > 200) { + fl_bonus += 0.3 * Math.min(1.0, (nobjects - 200) / 300.0); + } + if (nobjects > 500) { + fl_bonus += (nobjects - 500) / 1200.0; + } + aim *= fl_bonus; + } + + double acc_bonus = 0.5 + accuracy / 2.0; + double od_squared = base_od * base_od; + double od_bonus = 0.98 + od_squared / 2500.0; + + aim *= acc_bonus; + aim *= od_bonus; + if (mods.contains(GameMod.MOD_AUTOPILOT)) { + aim *= 0; + } + /* speed pp -------------------------------------------- */ + speed = pp_base(tpDifficulty.getSpeedStars()); + speed *= length_bonus; + speed *= combo_break; + if (base_ar > 10.33) { + speed *= ar_bonus; + } + speed *= hd_bonus; + + // speed miss penalty + if (nmiss > 0){ + speed *= 0.97 * Math.pow(1 - Math.pow((double) nmiss / nobjects, 0.775), Math.pow(nmiss, 0.875)); + } + + // scale the speed value with accuracy and OD + speed *= (0.95 + Math.pow(base_od, 2) / 750) * Math.pow(accuracy, (14.5 - Math.max(base_od, 8)) / 2); + // scale the speed value with # of 50s to punish doubletapping + if (accuracy != 1f) { + speed *= Math.pow(0.98, Math.max(0, stat.getHit50() - nobjects / 500)); + } + if (mods.contains(GameMod.MOD_RELAX)) { + speed *= 0; + } + /* acc pp ---------------------------------------------- */ + acc = Math.pow(1.52163, base_od) * + Math.pow(accuracy, 24.0) * 2.83; + + acc *= Math.min(1.15, Math.pow(ncircles / 1000.0, 0.3)); + + if (mods.contains(GameMod.MOD_HIDDEN)) { + acc *= 1.08; + } + + if (mods.contains(GameMod.MOD_FLASHLIGHT)) { + acc *= 1.02; + } + + if (mods.contains(GameMod.MOD_RELAX)) { + acc *= 0.1; + } + /* total pp -------------------------------------------- */ + double final_multiplier = 1.12; + + if (mods.contains(GameMod.MOD_NOFAIL)){ + final_multiplier *= Math.max(0.9, 1.0 - 0.02 * nmiss); + } + + //if ((mods & MODS_SO) != 0) { + // final_multiplier *= 0.95; + //} + + total = Math.pow( + Math.pow(aim, 1.1) + Math.pow(speed, 1.1) + + Math.pow(acc, 1.1), + 1.0 / 1.1 + ) * final_multiplier; + } + + public double getTotalPP() { + return total; + } + + public double getAimPP() { + return aim; + } + + public double getSpdPP() { + return speed; + } + + public double getAccPP() { + return acc; + } + + private float getAR(final StatisticV2 stat, final TrackInfo track) { + // no need to calculate force AR value + if (stat.isEnableForceAR()) { + return stat.getForceAR(); + } + float ar = track.getApproachRate(); + EnumSet mod = stat.getMod(); + if (mod.contains(GameMod.MOD_EASY)) { + ar *= 0.5f; + } + if (mod.contains(GameMod.MOD_HARDROCK)) { + ar = Math.min(ar * 1.4f, 10); + } + float speed = stat.getSpeed(); + if (mod.contains(GameMod.MOD_REALLYEASY)) { + if (mod.contains(GameMod.MOD_EASY)){ + ar *= 2f; + ar -= 0.5f; + } + ar -= 0.5f; + ar -= speed - 1.0f; + } + ar = GameHelper.Round(GameHelper.ms2ar(GameHelper.ar2ms(Math.min(13.f, ar)) / speed), 2); + return ar; + } + + private float getOD(final StatisticV2 stat, final TrackInfo track) { + float od = track.getOverallDifficulty(); + EnumSet mod = stat.getMod(); + if (mod.contains(GameMod.MOD_EASY)) { + od *= 0.5f; + } + if (mod.contains(GameMod.MOD_HARDROCK)) { + od *= 1.4f; + } + float speed = stat.getSpeed(); + if (mod.contains(GameMod.MOD_REALLYEASY)) { + od *= 0.5f; + } + od = Math.min(10.f, od); + od = GameHelper.Round(GameHelper.ms2od(GameHelper.od2ms(od) / speed), 2); + return od; + } + + public float getCS(EnumSet mod, final TrackInfo track) { + float cs = track.getCircleSize(); + if (mod.contains(GameMod.MOD_EASY)) { + cs -= 1f; + } + if (mod.contains(GameMod.MOD_HARDROCK)) { + cs += 1f; + } + if (mod.contains(GameMod.MOD_REALLYEASY)) { + cs -= 1f; + } + if (mod.contains(GameMod.MOD_SMALLCIRCLE)) { + cs += 4f; + } + return cs; + } + + public float getCS(final StatisticV2 stat, final TrackInfo track) { + return getCS(stat.getMod(), track); + } + + public float getCS(final TrackInfo track) { + return getCS(ModMenu.getInstance().getMod(), track); + } + + //must use reCalculateStar() before this + //This method calculate the note count of stream/jump/etc in a diff + //public boolean calculateMapInfo(final TrackInfo track, float speedMultiplier) { + //计算谱面信息 + /* + 120bpm: 125ms(dt1), 140bpm: 107ms(dt3), 80bpm: 187.5(dt4), 180bpm: 83.33ms(dt2) + 单点:低于120bpm,间距小于180 + 高速单点:高于120bpm且间距大于90、低于180bpm且间距大于90、小于180 + 连打:高于120bpm且间距小于90,高于180bpm且间距大于90、小于180 + 跳:间距大于180 + */ + /* + if (!init(track)) { + return false; + } + if (GlobalManager.getInstance().getSongMenu().getSelectedTrack() != track){ + return false; + } + final int ds1 = 90, ds2 = 180; + final int dt1 = 125, dt2 = 83, dt3 = 107, dt4 = 188; + single = fast_single = stream = jump = switch_fingering = multi = 0; + stream_longest = 0; + int combo = 0; + int last_delta_time = 0; + HitObject prev = null; + boolean first = true; + int firstObjectTime = 0; + for (HitObject object : hitObjects){ + if (object.getType() == HitObjectType.Spinner){ + continue; + } + if (prev != null){ + int delta_time = object.getStartTime() - prev.getStartTime(); + int distance = (int)Math.sqrt(Math.pow(object.getPos().x - prev.getPos().x, 2) + Math.pow(object.getPos().y - prev.getPos().y, 2)); + if ((delta_time >= dt1 && distance <= ds2) || (delta_time >= dt4 * 4)){ + single++; + } + else if(delta_time >= dt2 && distance >= ds1 && distance <= ds2){ + fast_single++; + } + else if((delta_time <= dt1 && distance <= ds1) || (delta_time <= dt2 && distance <= ds2)){ + stream++; + } + else if(distance >= ds2){ + jump++; + } + else{ + single++; + } + //多押 + if (first && delta_time == 0){ + first = false; + multi += 2; + } + else if (delta_time == 0){ + multi++; + } + else if (delta_time != 0){ + first = true; + } + //切指 + if (delta_time < last_delta_time * 1.2f && delta_time > last_delta_time * 0.8f){ + } + else if ((delta_time < dt3 || last_delta_time < dt3) && last_delta_time != 0 && delta_time < dt4 && last_delta_time < dt4){ + switch_fingering += 2; + } + //最长连打 + if (delta_time > dt3 || last_delta_time > dt3){ + if (combo != 0 && stream_longest < combo + 2){ + stream_longest = combo + 2; + } + combo = 0; + } + else{ + combo++; + } + last_delta_time = delta_time; + } + else { + firstObjectTime = object.getStartTime(); + } + prev = object; + } + //实际游玩时间 + real_time = (hitObjects.get(hitObjects.size() - 1).getEndTime() - firstObjectTime) / 1000f; + return true; + } + */ + public int getSingleCount(){ + return single; + } + public int getFastSingleCount(){ + return fast_single; + } + public int getStreamCount(){ + return stream; + } + public int getJumpCount(){ + return jump; + } + public int getSwitchFingeringCount(){ + return switch_fingering; + } + public int getMultiCount(){ + return multi; + } + public int getLongestStreamCount(){ + return stream_longest; + } + public float getRealTime(){ + return real_time; + } +} diff --git a/src/ru/nsu/ccfit/zuev/osu/helper/FileUtils.java b/src/ru/nsu/ccfit/zuev/osu/helper/FileUtils.java index 9befd6f1..d9488e7c 100644 --- a/src/ru/nsu/ccfit/zuev/osu/helper/FileUtils.java +++ b/src/ru/nsu/ccfit/zuev/osu/helper/FileUtils.java @@ -1,206 +1,206 @@ -package ru.nsu.ccfit.zuev.osu.helper; - -import android.os.Build; -import android.os.Environment; - -import java.io.BufferedInputStream; -import java.io.FileInputStream; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; - -// TODO: Implement zhanghai/AndroidRetroFile -import java.nio.file.DirectoryStream; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; - -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; - -import java.util.Arrays; -import java.util.LinkedList; - -import net.lingala.zip4j.ZipFile; -import net.lingala.zip4j.exception.ZipException; - -import okio.BufferedSink; -import okio.Okio; -import okio.Source; - -import org.anddev.andengine.util.Debug; - -import ru.nsu.ccfit.zuev.osu.Config; -import ru.nsu.ccfit.zuev.osu.LibraryManager; -import ru.nsu.ccfit.zuev.osu.ToastLogger; -import ru.nsu.ccfit.zuev.osuplus.R; - -public class FileUtils { - - private FileUtils() {} - - public static void copy(File from, File to) throws FileNotFoundException, IOException { - try (Source source = Okio.source(from); - BufferedSink bufferedSink = Okio.buffer(Okio.sink(to))) { - bufferedSink.writeAll(source); - } - } - - public static void move(File from, File to) throws FileNotFoundException, IOException { - copy(from, to); - from.delete(); - } - - public static boolean extractZip(final String sourcePath, final String targetPath) { - final File file = new File(sourcePath); - - // Check if we can use SD card for storage - if (!canUseSD()) { - return false; - } - - ToastLogger.addToLog("Importing " + sourcePath); - - final String folderName = file.getName().substring(0, file.getName().length() - 4); - - final File folderFile = new File(targetPath + "/" + folderName); - if(!folderFile.exists()) { - folderFile.mkdirs(); - } - - try { - ZipFile zip = new ZipFile(file); - if(!zip.isValidZipFile()) { - ToastLogger.showText( - StringTable.format(R.string.message_error, "Invalid file"), - false); - Debug.e("FileUtils.extractZip: " + file.getName() + " is invalid"); - file.renameTo(new File(file.getParentFile(), file.getName() + ".badzip")); - LibraryManager.getInstance().deleteDir(folderFile); - return false; - } - - zip.extractAll(folderFile.getAbsolutePath()); - if((Config.isDELETE_OSZ() && file.getName().toLowerCase().endsWith(".osz")) - || file.getName().toLowerCase().endsWith(".osk")) { - file.delete(); - } - } catch (final ZipException e) { - Debug.e("FileUtils.extractZip: " + e.getMessage(), e); - return false; - } - - return true; - } - - public static String getFileChecksum(String algorithm, File file) { - StringBuilder sb = new StringBuilder(); - - try { - MessageDigest digest = MessageDigest.getInstance(algorithm); - BufferedInputStream in = new BufferedInputStream( - new FileInputStream(file)); - byte[] byteArray = new byte[1024]; - int bytesCount = 0; - - while((bytesCount = in.read(byteArray)) != -1) { - digest.update(byteArray, 0, bytesCount); - } - in.close(); - - byte[] bytes = digest.digest(); - for(int i = 0; i < bytes.length; i++) { - sb.append(Integer.toString((bytes[i] & 0xff) + 0x100, 16).substring(1)); - } - }catch(IOException e) { - Debug.e("getFileChecksum " + e.getMessage(), e); - }catch(NoSuchAlgorithmException e) { - Debug.e(e.getMessage(), e); - } - return sb.toString(); - } - - public static boolean canUseSD() { - if (Environment.getExternalStorageState().equals( - Environment.MEDIA_MOUNTED)) { - return true; - } else { - if (Environment.getExternalStorageState().equals( - Environment.MEDIA_MOUNTED_READ_ONLY)) { - ToastLogger.showText( - StringTable.get(R.string.message_error_sdcardread), - false); - } else { - ToastLogger.showText( - StringTable.get(R.string.message_error_sdcard), false); - } - } - - return false; - } - - public static String getMD5Checksum(File file) { - return getFileChecksum("MD5", file); - } - - public static String getSHA256Checksum(File file) { - return getFileChecksum("SHA-256", file); - } - - public static File[] listFiles(File directory) { - return listFiles(directory, file -> true); - } - - public static File[] listFiles(File directory, String endsWith) { - return listFiles(directory, file -> - file.getName().toLowerCase().endsWith(endsWith)); - } - - public static File[] listFiles(File directory, String[] endsWithExtensions) { - if(Build.VERSION.SDK_INT < Build.VERSION_CODES.N) { - return listFiles(directory, file -> { - for(String extension : endsWithExtensions) { - if(file.getName().toLowerCase().endsWith(extension)) { - return true; - } - } - return false; - }); - }else if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { - return listFiles(directory, file -> { - String filename = file.getName().toLowerCase(); - return Arrays.stream(endsWithExtensions).anyMatch(filename::endsWith); - }); - } - return null; - } - - public static File[] listFiles(File directory, FileUtilsFilter filter) { - File[] filelist = null; - if(Build.VERSION.SDK_INT < Build.VERSION_CODES.O) { - filelist = directory.listFiles(pathname -> filter.accept(pathname)); - }else if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { - LinkedList cachedFiles = new LinkedList(); - DirectoryStream.Filter directoryFilter = new DirectoryStream.Filter() { - @Override - public boolean accept(Path entry) { - return filter.accept(entry.toFile()); - } - }; - try(DirectoryStream stream = Files.newDirectoryStream(Paths.get(directory.getAbsolutePath()), directoryFilter)) { - for(Path path : stream) { - cachedFiles.add(path.toFile()); - } - }catch(Exception err) { - Debug.e("FileUtils.listFiles: " + err.getMessage(), err); - } - filelist = cachedFiles.toArray(new File[cachedFiles.size()]); - } - return filelist; - } - - public interface FileUtilsFilter { - boolean accept(File file); - } - -} \ No newline at end of file +package ru.nsu.ccfit.zuev.osu.helper; + +import android.os.Build; +import android.os.Environment; + +import java.io.BufferedInputStream; +import java.io.FileInputStream; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; + +// TODO: Implement zhanghai/AndroidRetroFile +import java.nio.file.DirectoryStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; + +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; + +import java.util.Arrays; +import java.util.LinkedList; + +import net.lingala.zip4j.ZipFile; +import net.lingala.zip4j.exception.ZipException; + +import okio.BufferedSink; +import okio.Okio; +import okio.Source; + +import org.anddev.andengine.util.Debug; + +import ru.nsu.ccfit.zuev.osu.Config; +import ru.nsu.ccfit.zuev.osu.LibraryManager; +import ru.nsu.ccfit.zuev.osu.ToastLogger; +import ru.nsu.ccfit.zuev.osuplus.R; + +public class FileUtils { + + private FileUtils() {} + + public static void copy(File from, File to) throws FileNotFoundException, IOException { + try (Source source = Okio.source(from); + BufferedSink bufferedSink = Okio.buffer(Okio.sink(to))) { + bufferedSink.writeAll(source); + } + } + + public static void move(File from, File to) throws FileNotFoundException, IOException { + copy(from, to); + from.delete(); + } + + public static boolean extractZip(final String sourcePath, final String targetPath) { + final File file = new File(sourcePath); + + // Check if we can use SD card for storage + if (!canUseSD()) { + return false; + } + + ToastLogger.addToLog("Importing " + sourcePath); + + final String folderName = file.getName().substring(0, file.getName().length() - 4); + + final File folderFile = new File(targetPath + "/" + folderName); + if(!folderFile.exists()) { + folderFile.mkdirs(); + } + + try { + ZipFile zip = new ZipFile(file); + if(!zip.isValidZipFile()) { + ToastLogger.showText( + StringTable.format(R.string.message_error, "Invalid file"), + false); + Debug.e("FileUtils.extractZip: " + file.getName() + " is invalid"); + file.renameTo(new File(file.getParentFile(), file.getName() + ".badzip")); + LibraryManager.getInstance().deleteDir(folderFile); + return false; + } + + zip.extractAll(folderFile.getAbsolutePath()); + if((Config.isDELETE_OSZ() && file.getName().toLowerCase().endsWith(".osz")) + || file.getName().toLowerCase().endsWith(".osk")) { + file.delete(); + } + } catch (final ZipException e) { + Debug.e("FileUtils.extractZip: " + e.getMessage(), e); + return false; + } + + return true; + } + + public static String getFileChecksum(String algorithm, File file) { + StringBuilder sb = new StringBuilder(); + + try { + MessageDigest digest = MessageDigest.getInstance(algorithm); + BufferedInputStream in = new BufferedInputStream( + new FileInputStream(file)); + byte[] byteArray = new byte[1024]; + int bytesCount = 0; + + while((bytesCount = in.read(byteArray)) != -1) { + digest.update(byteArray, 0, bytesCount); + } + in.close(); + + byte[] bytes = digest.digest(); + for(int i = 0; i < bytes.length; i++) { + sb.append(Integer.toString((bytes[i] & 0xff) + 0x100, 16).substring(1)); + } + }catch(IOException e) { + Debug.e("getFileChecksum " + e.getMessage(), e); + }catch(NoSuchAlgorithmException e) { + Debug.e(e.getMessage(), e); + } + return sb.toString(); + } + + public static boolean canUseSD() { + if (Environment.getExternalStorageState().equals( + Environment.MEDIA_MOUNTED)) { + return true; + } else { + if (Environment.getExternalStorageState().equals( + Environment.MEDIA_MOUNTED_READ_ONLY)) { + ToastLogger.showText( + StringTable.get(R.string.message_error_sdcardread), + false); + } else { + ToastLogger.showText( + StringTable.get(R.string.message_error_sdcard), false); + } + } + + return false; + } + + public static String getMD5Checksum(File file) { + return getFileChecksum("MD5", file); + } + + public static String getSHA256Checksum(File file) { + return getFileChecksum("SHA-256", file); + } + + public static File[] listFiles(File directory) { + return listFiles(directory, file -> true); + } + + public static File[] listFiles(File directory, String endsWith) { + return listFiles(directory, file -> + file.getName().toLowerCase().endsWith(endsWith)); + } + + public static File[] listFiles(File directory, String[] endsWithExtensions) { + if(Build.VERSION.SDK_INT < Build.VERSION_CODES.N) { + return listFiles(directory, file -> { + for(String extension : endsWithExtensions) { + if(file.getName().toLowerCase().endsWith(extension)) { + return true; + } + } + return false; + }); + }else if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { + return listFiles(directory, file -> { + String filename = file.getName().toLowerCase(); + return Arrays.stream(endsWithExtensions).anyMatch(filename::endsWith); + }); + } + return null; + } + + public static File[] listFiles(File directory, FileUtilsFilter filter) { + File[] filelist = null; + if(Build.VERSION.SDK_INT < Build.VERSION_CODES.O) { + filelist = directory.listFiles(pathname -> filter.accept(pathname)); + }else if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { + LinkedList cachedFiles = new LinkedList(); + DirectoryStream.Filter directoryFilter = new DirectoryStream.Filter() { + @Override + public boolean accept(Path entry) { + return filter.accept(entry.toFile()); + } + }; + try(DirectoryStream stream = Files.newDirectoryStream(Paths.get(directory.getAbsolutePath()), directoryFilter)) { + for(Path path : stream) { + cachedFiles.add(path.toFile()); + } + }catch(Exception err) { + Debug.e("FileUtils.listFiles: " + err.getMessage(), err); + } + filelist = cachedFiles.toArray(new File[cachedFiles.size()]); + } + return filelist; + } + + public interface FileUtilsFilter { + boolean accept(File file); + } + +} diff --git a/src/ru/nsu/ccfit/zuev/osu/helper/InputManager.java b/src/ru/nsu/ccfit/zuev/osu/helper/InputManager.java index 1e1d5f82..ab626669 100644 --- a/src/ru/nsu/ccfit/zuev/osu/helper/InputManager.java +++ b/src/ru/nsu/ccfit/zuev/osu/helper/InputManager.java @@ -4,81 +4,81 @@ import android.view.inputmethod.InputMethodManager; public class InputManager { - private static Context context; - private static InputManager instance = new InputManager(); - private boolean inputStarted = false; - private boolean changed = true; - private StringBuilder builder; - private int maxlength; - private InputManager() { - } + private static Context context; + private static InputManager instance = new InputManager(); + private boolean inputStarted = false; + private boolean changed = true; + private StringBuilder builder; + private int maxlength; + private InputManager() { + } - public static void setContext(final Context context) { - InputManager.context = context; - } + public static void setContext(final Context context) { + InputManager.context = context; + } - public static InputManager getInstance() { - return instance; - } + public static InputManager getInstance() { + return instance; + } - public void startInput(final String start, final int maxlength) { - this.maxlength = maxlength; - builder = new StringBuilder(start); - changed = true; - inputStarted = true; - toggleKeyboard(); - } + public void startInput(final String start, final int maxlength) { + this.maxlength = maxlength; + builder = new StringBuilder(start); + changed = true; + inputStarted = true; + toggleKeyboard(); + } - public void toggleKeyboard() { - final InputMethodManager mgr = (InputMethodManager) context - .getSystemService(Context.INPUT_METHOD_SERVICE); - mgr.toggleSoftInput(0, 0); - } + public void toggleKeyboard() { + final InputMethodManager mgr = (InputMethodManager) context + .getSystemService(Context.INPUT_METHOD_SERVICE); + mgr.toggleSoftInput(0, 0); + } - public void append(final char c) { - if (!inputStarted) { - return; - } - if (builder.length() >= maxlength) { - return; - } - changed = true; - builder.append(c); - } + public void append(final char c) { + if (!inputStarted) { + return; + } + if (builder.length() >= maxlength) { + return; + } + changed = true; + builder.append(c); + } - public void pop() { - if (!inputStarted || builder.length() == 0) { - return; - } - changed = true; - builder.deleteCharAt(builder.length() - 1); - } + public void pop() { + if (!inputStarted || builder.length() == 0) { + return; + } + changed = true; + builder.deleteCharAt(builder.length() - 1); + } - public String getText() { - if (!inputStarted) { - return ""; - } - changed = false; - return builder.toString(); - } + public String getText() { + if (!inputStarted) { + return ""; + } + changed = false; + return builder.toString(); + } - public void setText(final String text) { - builder = new StringBuilder(text); - changed = true; - } + public void setText(final String text) { + builder = new StringBuilder(text); + changed = true; + } - public boolean isChanged() { - return changed; - } + public boolean isChanged() { + return changed; + } - public boolean isStarted() { - return inputStarted; - } + public boolean isStarted() { + return inputStarted; + } - public String finish() { - inputStarted = false; - final String str = builder.toString(); - builder = null; - return str; - } + public String finish() { + inputStarted = false; + final String str = builder.toString(); + builder = null; + return str; + } } diff --git a/src/ru/nsu/ccfit/zuev/osu/helper/MD5Calcuator.java b/src/ru/nsu/ccfit/zuev/osu/helper/MD5Calcuator.java index 90583086..b7f75546 100644 --- a/src/ru/nsu/ccfit/zuev/osu/helper/MD5Calcuator.java +++ b/src/ru/nsu/ccfit/zuev/osu/helper/MD5Calcuator.java @@ -8,46 +8,46 @@ import java.security.MessageDigest; public class MD5Calcuator { - public static String getFileMD5(final File file) { - String md5 = ""; - try { - FileInputStream in = new FileInputStream(file); - MessageDigest digester = MessageDigest.getInstance("MD5"); - byte[] bytes = new byte[8192]; - int byteCount; - while ((byteCount = in.read(bytes)) > 0) { - digester.update(bytes, 0, byteCount); - } - - final BigInteger hash = new BigInteger(1, digester.digest()); - md5 = hash.toString(16); - while (md5.length() < 32) { - md5 = "0" + md5; - } - - in.close(); - } catch (Exception e) { - Debug.e("MD5Calculator: " + e.getMessage()); - } - - return md5; - } - - public static String getStringMD5(final String str) { - String md5 = ""; - try { - MessageDigest digester = MessageDigest.getInstance("MD5"); - digester.update(str.getBytes()); - - final BigInteger hash = new BigInteger(1, digester.digest()); - md5 = hash.toString(16); - while (md5.length() < 32) { - md5 = "0" + md5; - } - } catch (Exception e) { - Debug.e("MD5Calculator: " + e.getMessage()); - } - - return md5; - } + public static String getFileMD5(final File file) { + String md5 = ""; + try { + FileInputStream in = new FileInputStream(file); + MessageDigest digester = MessageDigest.getInstance("MD5"); + byte[] bytes = new byte[8192]; + int byteCount; + while ((byteCount = in.read(bytes)) > 0) { + digester.update(bytes, 0, byteCount); + } + + final BigInteger hash = new BigInteger(1, digester.digest()); + md5 = hash.toString(16); + while (md5.length() < 32) { + md5 = "0" + md5; + } + + in.close(); + } catch (Exception e) { + Debug.e("MD5Calculator: " + e.getMessage()); + } + + return md5; + } + + public static String getStringMD5(final String str) { + String md5 = ""; + try { + MessageDigest digester = MessageDigest.getInstance("MD5"); + digester.update(str.getBytes()); + + final BigInteger hash = new BigInteger(1, digester.digest()); + md5 = hash.toString(16); + while (md5.length() < 32) { + md5 = "0" + md5; + } + } catch (Exception e) { + Debug.e("MD5Calculator: " + e.getMessage()); + } + + return md5; + } } diff --git a/src/ru/nsu/ccfit/zuev/osu/helper/ModifierFactory.java b/src/ru/nsu/ccfit/zuev/osu/helper/ModifierFactory.java index 7620f469..edfb2553 100644 --- a/src/ru/nsu/ccfit/zuev/osu/helper/ModifierFactory.java +++ b/src/ru/nsu/ccfit/zuev/osu/helper/ModifierFactory.java @@ -8,57 +8,57 @@ import ru.nsu.ccfit.zuev.osu.helper.UniversalModifier.ValueType; public class ModifierFactory { - private static ModifierFactory instance = new ModifierFactory(); - private final Queue pool = new LinkedList(); + private static ModifierFactory instance = new ModifierFactory(); + private final Queue pool = new LinkedList(); - private ModifierFactory() { - } + private ModifierFactory() { + } - public static IEntityModifier newFadeInModifier(final float duration) { - return instance.newModifier(duration, 0, 1, ValueType.ALPHA); - } + public static IEntityModifier newFadeInModifier(final float duration) { + return instance.newModifier(duration, 0, 1, ValueType.ALPHA); + } - public static IEntityModifier newFadeOutModifier(final float duration) { - return instance.newModifier(duration, 1, 0, ValueType.ALPHA); - } + public static IEntityModifier newFadeOutModifier(final float duration) { + return instance.newModifier(duration, 1, 0, ValueType.ALPHA); + } - public static IEntityModifier newAlphaModifier(final float duration, - final float from, final float to) { - return instance.newModifier(duration, from, to, ValueType.ALPHA); - } + public static IEntityModifier newAlphaModifier(final float duration, + final float from, final float to) { + return instance.newModifier(duration, from, to, ValueType.ALPHA); + } - public static IEntityModifier newScaleModifier(final float duration, - final float from, final float to) { - return instance.newModifier(duration, from, to, ValueType.SCALE); - } + public static IEntityModifier newScaleModifier(final float duration, + final float from, final float to) { + return instance.newModifier(duration, from, to, ValueType.SCALE); + } - public static IEntityModifier newDelayModifier(final float duration) { - return instance.newModifier(duration, 0, 0, ValueType.NONE); - } + public static IEntityModifier newDelayModifier(final float duration) { + return instance.newModifier(duration, 0, 0, ValueType.NONE); + } - public static void putModifier(final UniversalModifier mod) { - instance.pool.add(mod); - } + public static void putModifier(final UniversalModifier mod) { + instance.pool.add(mod); + } - public static void clear() { - instance.pool.clear(); - } + public static void clear() { + instance.pool.clear(); + } - private UniversalModifier newModifier(final float duration, - final float from, final float to, final ValueType type) { - if (pool.isEmpty() == false) { - UniversalModifier mod = null; + private UniversalModifier newModifier(final float duration, + final float from, final float to, final ValueType type) { + if (pool.isEmpty() == false) { + UniversalModifier mod = null; - synchronized (pool) { - if (pool.isEmpty() == false) { - mod = pool.poll(); - } - } - if (mod != null) { - mod.init(duration, from, to, type); - return mod; - } - } - return new UniversalModifier(duration, from, to, type); - } + synchronized (pool) { + if (pool.isEmpty() == false) { + mod = pool.poll(); + } + } + if (mod != null) { + mod.init(duration, from, to, type); + return mod; + } + } + return new UniversalModifier(duration, from, to, type); + } } diff --git a/src/ru/nsu/ccfit/zuev/osu/helper/QualityAssetBitmapSource.java b/src/ru/nsu/ccfit/zuev/osu/helper/QualityAssetBitmapSource.java index edc7b99a..9f76825c 100644 --- a/src/ru/nsu/ccfit/zuev/osu/helper/QualityAssetBitmapSource.java +++ b/src/ru/nsu/ccfit/zuev/osu/helper/QualityAssetBitmapSource.java @@ -14,121 +14,121 @@ import java.io.InputStream; public class QualityAssetBitmapSource extends BaseTextureAtlasSource implements - IBitmapTextureAtlasSource { - - private final int mWidth; - private final int mHeight; - - private final String mAssetPath; - private final Context mContext; - - private Bitmap bitmap = null; - - // =========================================================== - // Constructors - // =========================================================== - - public QualityAssetBitmapSource(final Context pContext, - final String pAssetPath) { - this(pContext, pAssetPath, 0, 0); - } - - public QualityAssetBitmapSource(final Context pContext, - final String pAssetPath, final int pTexturePositionX, - final int pTexturePositionY) { - super(pTexturePositionX, pTexturePositionY); - this.mContext = pContext; - this.mAssetPath = pAssetPath; - - final BitmapFactory.Options decodeOptions = new BitmapFactory.Options(); - decodeOptions.inJustDecodeBounds = true; - decodeOptions.inSampleSize = ru.nsu.ccfit.zuev.osu.Config - .getTextureQuality(); - - InputStream in = null; - try { - in = pContext.getAssets().open(pAssetPath); - BitmapFactory.decodeStream(in, null, decodeOptions); - } catch (final IOException e) { - // Debug.e("Failed loading Bitmap in AssetBitmapTextureAtlasSource. AssetPath: " + pAssetPath, e); - } finally { - StreamUtils.close(in); - } - - this.mWidth = decodeOptions.outWidth; - this.mHeight = decodeOptions.outHeight; - } - - QualityAssetBitmapSource(final Context pContext, final String pAssetPath, - final int pTexturePositionX, final int pTexturePositionY, - final int pWidth, final int pHeight) { - super(pTexturePositionX, pTexturePositionY); - this.mContext = pContext; - this.mAssetPath = pAssetPath; - this.mWidth = pWidth; - this.mHeight = pHeight; - } - - - public QualityAssetBitmapSource deepCopy() { - return new QualityAssetBitmapSource(this.mContext, this.mAssetPath, - this.mTexturePositionX, this.mTexturePositionY, this.mWidth, - this.mHeight); - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - - public int getWidth() { - return this.mWidth; - } - - - public int getHeight() { - return this.mHeight; - } - - public boolean preload() { - bitmap = onLoadBitmap(Bitmap.Config.ARGB_8888); - return bitmap != null; - } - - - public Bitmap onLoadBitmap(final Config pBitmapConfig) { - if (bitmap != null) { - final Bitmap bmp = bitmap; - bitmap = null; - return bmp; - } - InputStream in = null; - try { - final BitmapFactory.Options decodeOptions = new BitmapFactory.Options(); - decodeOptions.inPreferredConfig = pBitmapConfig; - decodeOptions.inSampleSize = ru.nsu.ccfit.zuev.osu.Config - .getTextureQuality(); - - in = this.mContext.getAssets().open(this.mAssetPath); - return BitmapFactory.decodeStream(in, null, decodeOptions); - } catch (final IOException e) { - Debug.e("Failed loading Bitmap in " - + this.getClass().getSimpleName() + ". AssetPath: " - + this.mAssetPath, e); - return null; - } finally { - StreamUtils.close(in); - } - } - - - @Override - public String toString() { - return this.getClass().getSimpleName() + "(" + this.mAssetPath + ")"; - } + IBitmapTextureAtlasSource { + + private final int mWidth; + private final int mHeight; + + private final String mAssetPath; + private final Context mContext; + + private Bitmap bitmap = null; + + // =========================================================== + // Constructors + // =========================================================== + + public QualityAssetBitmapSource(final Context pContext, + final String pAssetPath) { + this(pContext, pAssetPath, 0, 0); + } + + public QualityAssetBitmapSource(final Context pContext, + final String pAssetPath, final int pTexturePositionX, + final int pTexturePositionY) { + super(pTexturePositionX, pTexturePositionY); + this.mContext = pContext; + this.mAssetPath = pAssetPath; + + final BitmapFactory.Options decodeOptions = new BitmapFactory.Options(); + decodeOptions.inJustDecodeBounds = true; + decodeOptions.inSampleSize = ru.nsu.ccfit.zuev.osu.Config + .getTextureQuality(); + + InputStream in = null; + try { + in = pContext.getAssets().open(pAssetPath); + BitmapFactory.decodeStream(in, null, decodeOptions); + } catch (final IOException e) { + // Debug.e("Failed loading Bitmap in AssetBitmapTextureAtlasSource. AssetPath: " + pAssetPath, e); + } finally { + StreamUtils.close(in); + } + + this.mWidth = decodeOptions.outWidth; + this.mHeight = decodeOptions.outHeight; + } + + QualityAssetBitmapSource(final Context pContext, final String pAssetPath, + final int pTexturePositionX, final int pTexturePositionY, + final int pWidth, final int pHeight) { + super(pTexturePositionX, pTexturePositionY); + this.mContext = pContext; + this.mAssetPath = pAssetPath; + this.mWidth = pWidth; + this.mHeight = pHeight; + } + + + public QualityAssetBitmapSource deepCopy() { + return new QualityAssetBitmapSource(this.mContext, this.mAssetPath, + this.mTexturePositionX, this.mTexturePositionY, this.mWidth, + this.mHeight); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + + public int getWidth() { + return this.mWidth; + } + + + public int getHeight() { + return this.mHeight; + } + + public boolean preload() { + bitmap = onLoadBitmap(Bitmap.Config.ARGB_8888); + return bitmap != null; + } + + + public Bitmap onLoadBitmap(final Config pBitmapConfig) { + if (bitmap != null) { + final Bitmap bmp = bitmap; + bitmap = null; + return bmp; + } + InputStream in = null; + try { + final BitmapFactory.Options decodeOptions = new BitmapFactory.Options(); + decodeOptions.inPreferredConfig = pBitmapConfig; + decodeOptions.inSampleSize = ru.nsu.ccfit.zuev.osu.Config + .getTextureQuality(); + + in = this.mContext.getAssets().open(this.mAssetPath); + return BitmapFactory.decodeStream(in, null, decodeOptions); + } catch (final IOException e) { + Debug.e("Failed loading Bitmap in " + + this.getClass().getSimpleName() + ". AssetPath: " + + this.mAssetPath, e); + return null; + } finally { + StreamUtils.close(in); + } + } + + + @Override + public String toString() { + return this.getClass().getSimpleName() + "(" + this.mAssetPath + ")"; + } } diff --git a/src/ru/nsu/ccfit/zuev/osu/helper/QualityFileBitmapSource.java b/src/ru/nsu/ccfit/zuev/osu/helper/QualityFileBitmapSource.java index 3cc19f3d..85bb5e8a 100644 --- a/src/ru/nsu/ccfit/zuev/osu/helper/QualityFileBitmapSource.java +++ b/src/ru/nsu/ccfit/zuev/osu/helper/QualityFileBitmapSource.java @@ -15,139 +15,139 @@ import java.io.InputStream; public class QualityFileBitmapSource extends BaseTextureAtlasSource implements - IBitmapTextureAtlasSource { + IBitmapTextureAtlasSource { - private int mWidth; - private int mHeight; - private Bitmap bitmap = null; + private int mWidth; + private int mHeight; + private Bitmap bitmap = null; - private InputFactory fileBitmapInput; - - private int inSampleSize = ru.nsu.ccfit.zuev.osu.Config.getTextureQuality(); + private InputFactory fileBitmapInput; + + private int inSampleSize = ru.nsu.ccfit.zuev.osu.Config.getTextureQuality(); - public QualityFileBitmapSource(final File pFile) { - this(pFile, 0, 0); - } - - public QualityFileBitmapSource(final InputFactory pFile) { - this(pFile, 0, 0); - } - - public QualityFileBitmapSource(final InputFactory pFile, int inSampleSize) { - this(pFile, 0, 0); - this.inSampleSize = inSampleSize; - } - - public QualityFileBitmapSource(final File pFile, - final int pTexturePositionX, final int pTexturePositionY) { - this(() -> new FileInputStream(pFile), pTexturePositionX, pTexturePositionY); - } - - public QualityFileBitmapSource(final InputFactory pFile, - final int pTexturePositionX, final int pTexturePositionY) { - super(pTexturePositionX, pTexturePositionY); - - fileBitmapInput = pFile; - - final BitmapFactory.Options decodeOptions = new BitmapFactory.Options(); - decodeOptions.inJustDecodeBounds = true; - decodeOptions.inSampleSize = inSampleSize; - - InputStream in = null; - try { - in = openInputStream(); - BitmapFactory.decodeStream(in, null, decodeOptions); - - this.mWidth = decodeOptions.outWidth; - this.mHeight = decodeOptions.outHeight; - } catch (final IOException e) { - Debug.e("Failed loading Bitmap in FileBitmapTextureAtlasSource. File: " - + pFile, e); - this.mWidth = 0; - this.mHeight = 0; - } finally { - StreamUtils.close(in); - } - - } - - QualityFileBitmapSource(final InputFactory pFile, final int pTexturePositionX, - final int pTexturePositionY, final int pWidth, final int pHeight) { - super(pTexturePositionX, pTexturePositionY); - fileBitmapInput = pFile; - this.mWidth = pWidth; - this.mHeight = pHeight; - } - - public InputStream openInputStream() throws IOException { - return fileBitmapInput.openInput(); - } - - - public QualityFileBitmapSource deepCopy() { - QualityFileBitmapSource source = new QualityFileBitmapSource(this.fileBitmapInput, this.mTexturePositionX, - this.mTexturePositionY, this.mWidth, this.mHeight); - source.inSampleSize = inSampleSize; - return source; - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - - public int getWidth() { - return this.mWidth; - } - - - public int getHeight() { - return this.mHeight; - } - - public boolean preload() { - bitmap = onLoadBitmap(Bitmap.Config.ARGB_8888); - return bitmap != null; - } - - - public Bitmap onLoadBitmap(final Config pBitmapConfig) { - if (bitmap != null) { - final Bitmap bmp = bitmap; - bitmap = null; - return bmp; - } - final BitmapFactory.Options decodeOptions = new BitmapFactory.Options(); - decodeOptions.inPreferredConfig = Config.ARGB_8888;//pBitmapConfig; - decodeOptions.inSampleSize = inSampleSize; - - InputStream in = null; - try { - in = openInputStream(); - return BitmapFactory.decodeStream(in, null, decodeOptions); - } catch (final IOException e) { - Debug.e("Failed loading Bitmap in " - + this.getClass().getSimpleName() + ". File: " + this.fileBitmapInput, - e); - return null; - } finally { - StreamUtils.close(in); - } - } - - - @Override - public String toString() { - return this.getClass().getSimpleName() + "(" + this.fileBitmapInput + ")"; - } - - - public interface InputFactory { - InputStream openInput() throws IOException; - } + public QualityFileBitmapSource(final File pFile) { + this(pFile, 0, 0); + } + + public QualityFileBitmapSource(final InputFactory pFile) { + this(pFile, 0, 0); + } + + public QualityFileBitmapSource(final InputFactory pFile, int inSampleSize) { + this(pFile, 0, 0); + this.inSampleSize = inSampleSize; + } + + public QualityFileBitmapSource(final File pFile, + final int pTexturePositionX, final int pTexturePositionY) { + this(() -> new FileInputStream(pFile), pTexturePositionX, pTexturePositionY); + } + + public QualityFileBitmapSource(final InputFactory pFile, + final int pTexturePositionX, final int pTexturePositionY) { + super(pTexturePositionX, pTexturePositionY); + + fileBitmapInput = pFile; + + final BitmapFactory.Options decodeOptions = new BitmapFactory.Options(); + decodeOptions.inJustDecodeBounds = true; + decodeOptions.inSampleSize = inSampleSize; + + InputStream in = null; + try { + in = openInputStream(); + BitmapFactory.decodeStream(in, null, decodeOptions); + + this.mWidth = decodeOptions.outWidth; + this.mHeight = decodeOptions.outHeight; + } catch (final IOException e) { + Debug.e("Failed loading Bitmap in FileBitmapTextureAtlasSource. File: " + + pFile, e); + this.mWidth = 0; + this.mHeight = 0; + } finally { + StreamUtils.close(in); + } + + } + + QualityFileBitmapSource(final InputFactory pFile, final int pTexturePositionX, + final int pTexturePositionY, final int pWidth, final int pHeight) { + super(pTexturePositionX, pTexturePositionY); + fileBitmapInput = pFile; + this.mWidth = pWidth; + this.mHeight = pHeight; + } + + public InputStream openInputStream() throws IOException { + return fileBitmapInput.openInput(); + } + + + public QualityFileBitmapSource deepCopy() { + QualityFileBitmapSource source = new QualityFileBitmapSource(this.fileBitmapInput, this.mTexturePositionX, + this.mTexturePositionY, this.mWidth, this.mHeight); + source.inSampleSize = inSampleSize; + return source; + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + + public int getWidth() { + return this.mWidth; + } + + + public int getHeight() { + return this.mHeight; + } + + public boolean preload() { + bitmap = onLoadBitmap(Bitmap.Config.ARGB_8888); + return bitmap != null; + } + + + public Bitmap onLoadBitmap(final Config pBitmapConfig) { + if (bitmap != null) { + final Bitmap bmp = bitmap; + bitmap = null; + return bmp; + } + final BitmapFactory.Options decodeOptions = new BitmapFactory.Options(); + decodeOptions.inPreferredConfig = Config.ARGB_8888;//pBitmapConfig; + decodeOptions.inSampleSize = inSampleSize; + + InputStream in = null; + try { + in = openInputStream(); + return BitmapFactory.decodeStream(in, null, decodeOptions); + } catch (final IOException e) { + Debug.e("Failed loading Bitmap in " + + this.getClass().getSimpleName() + ". File: " + this.fileBitmapInput, + e); + return null; + } finally { + StreamUtils.close(in); + } + } + + + @Override + public String toString() { + return this.getClass().getSimpleName() + "(" + this.fileBitmapInput + ")"; + } + + + public interface InputFactory { + InputStream openInput() throws IOException; + } } diff --git a/src/ru/nsu/ccfit/zuev/osu/helper/ScaledBitmapSource.java b/src/ru/nsu/ccfit/zuev/osu/helper/ScaledBitmapSource.java index 2bcaa04f..6e6c59e7 100644 --- a/src/ru/nsu/ccfit/zuev/osu/helper/ScaledBitmapSource.java +++ b/src/ru/nsu/ccfit/zuev/osu/helper/ScaledBitmapSource.java @@ -15,122 +15,122 @@ import java.io.InputStream; public class ScaledBitmapSource extends BaseTextureAtlasSource implements - IBitmapTextureAtlasSource { - - private final File mFile; - private int mWidth; - private int mHeight; - private Bitmap bitmap = null; - - // =========================================================== - // Constructors - // =========================================================== - - public ScaledBitmapSource(final File pFile) { - this(pFile, 0, 0); - } - - public ScaledBitmapSource(final File pFile, final int pTexturePositionX, - final int pTexturePositionY) { - super(pTexturePositionX, pTexturePositionY); - this.mFile = pFile; - - final BitmapFactory.Options decodeOptions = new BitmapFactory.Options(); - decodeOptions.inJustDecodeBounds = true; - decodeOptions.inSampleSize = ru.nsu.ccfit.zuev.osu.Config - .getBackgroundQuality(); - - InputStream in = null; - try { - in = new FileInputStream(pFile); - BitmapFactory.decodeStream(in, null, decodeOptions); - this.mWidth = decodeOptions.outWidth; - this.mHeight = decodeOptions.outHeight; - - } catch (final IOException e) { - Debug.e("Failed loading Bitmap in FileBitmapTextureAtlasSource. File: " - + pFile, e); - this.mWidth = 0; - this.mHeight = 0; - } finally { - StreamUtils.close(in); - } - } - - ScaledBitmapSource(final File pFile, final int pTexturePositionX, - final int pTexturePositionY, final int pWidth, final int pHeight) { - super(pTexturePositionX, pTexturePositionY); - this.mFile = pFile; - this.mWidth = pWidth; - this.mHeight = pHeight; - } - - - @Override - public ScaledBitmapSource clone() { - return new ScaledBitmapSource(this.mFile, this.mTexturePositionX, - this.mTexturePositionY, this.mWidth, this.mHeight); - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - - public int getWidth() { - return this.mWidth; - } - - - public int getHeight() { - return this.mHeight; - } - - public boolean preload() { - bitmap = onLoadBitmap(Bitmap.Config.ARGB_8888); - return bitmap != null; - } - - - public Bitmap onLoadBitmap(final Config pBitmapConfig) { - if (bitmap != null) { - final Bitmap bmp = bitmap; - bitmap = null; - return bmp; - } - final BitmapFactory.Options decodeOptions = new BitmapFactory.Options(); - decodeOptions.inPreferredConfig = pBitmapConfig; - decodeOptions.inSampleSize = ru.nsu.ccfit.zuev.osu.Config - .getBackgroundQuality(); - - InputStream in = null; - try { - in = new FileInputStream(this.mFile); - return BitmapFactory.decodeStream(in, null, decodeOptions); - } catch (final IOException e) { - Debug.e("Failed loading Bitmap in " - + this.getClass().getSimpleName() + ". File: " + this.mFile, - e); - return null; - } finally { - StreamUtils.close(in); - } - } - - - @Override - public String toString() { - return this.getClass().getSimpleName() + "(" + this.mFile + ")"; - } - - - public ScaledBitmapSource deepCopy() { - return new ScaledBitmapSource(mFile, mTexturePositionX, - mTexturePositionY); - } + IBitmapTextureAtlasSource { + + private final File mFile; + private int mWidth; + private int mHeight; + private Bitmap bitmap = null; + + // =========================================================== + // Constructors + // =========================================================== + + public ScaledBitmapSource(final File pFile) { + this(pFile, 0, 0); + } + + public ScaledBitmapSource(final File pFile, final int pTexturePositionX, + final int pTexturePositionY) { + super(pTexturePositionX, pTexturePositionY); + this.mFile = pFile; + + final BitmapFactory.Options decodeOptions = new BitmapFactory.Options(); + decodeOptions.inJustDecodeBounds = true; + decodeOptions.inSampleSize = ru.nsu.ccfit.zuev.osu.Config + .getBackgroundQuality(); + + InputStream in = null; + try { + in = new FileInputStream(pFile); + BitmapFactory.decodeStream(in, null, decodeOptions); + this.mWidth = decodeOptions.outWidth; + this.mHeight = decodeOptions.outHeight; + + } catch (final IOException e) { + Debug.e("Failed loading Bitmap in FileBitmapTextureAtlasSource. File: " + + pFile, e); + this.mWidth = 0; + this.mHeight = 0; + } finally { + StreamUtils.close(in); + } + } + + ScaledBitmapSource(final File pFile, final int pTexturePositionX, + final int pTexturePositionY, final int pWidth, final int pHeight) { + super(pTexturePositionX, pTexturePositionY); + this.mFile = pFile; + this.mWidth = pWidth; + this.mHeight = pHeight; + } + + + @Override + public ScaledBitmapSource clone() { + return new ScaledBitmapSource(this.mFile, this.mTexturePositionX, + this.mTexturePositionY, this.mWidth, this.mHeight); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + + public int getWidth() { + return this.mWidth; + } + + + public int getHeight() { + return this.mHeight; + } + + public boolean preload() { + bitmap = onLoadBitmap(Bitmap.Config.ARGB_8888); + return bitmap != null; + } + + + public Bitmap onLoadBitmap(final Config pBitmapConfig) { + if (bitmap != null) { + final Bitmap bmp = bitmap; + bitmap = null; + return bmp; + } + final BitmapFactory.Options decodeOptions = new BitmapFactory.Options(); + decodeOptions.inPreferredConfig = pBitmapConfig; + decodeOptions.inSampleSize = ru.nsu.ccfit.zuev.osu.Config + .getBackgroundQuality(); + + InputStream in = null; + try { + in = new FileInputStream(this.mFile); + return BitmapFactory.decodeStream(in, null, decodeOptions); + } catch (final IOException e) { + Debug.e("Failed loading Bitmap in " + + this.getClass().getSimpleName() + ". File: " + this.mFile, + e); + return null; + } finally { + StreamUtils.close(in); + } + } + + + @Override + public String toString() { + return this.getClass().getSimpleName() + "(" + this.mFile + ")"; + } + + + public ScaledBitmapSource deepCopy() { + return new ScaledBitmapSource(mFile, mTexturePositionX, + mTexturePositionY); + } } diff --git a/src/ru/nsu/ccfit/zuev/osu/helper/StringTable.java b/src/ru/nsu/ccfit/zuev/osu/helper/StringTable.java index 6117bdd9..ff14697a 100644 --- a/src/ru/nsu/ccfit/zuev/osu/helper/StringTable.java +++ b/src/ru/nsu/ccfit/zuev/osu/helper/StringTable.java @@ -4,23 +4,23 @@ import androidx.annotation.StringRes; public class StringTable { - static Context context; + static Context context; - public static void setContext(final Context context) { - StringTable.context = context; - } + public static void setContext(final Context context) { + StringTable.context = context; + } - public static String get(@StringRes final int resid) { - String str; - try { - str = context.getString(resid); - } catch (final NullPointerException e) { - str = ""; - } - return str; - } + public static String get(@StringRes final int resid) { + String str; + try { + str = context.getString(resid); + } catch (final NullPointerException e) { + str = ""; + } + return str; + } - public static String format(final int resid, final Object... objects) { - return String.format(get(resid), objects); - } + public static String format(final int resid, final Object... objects) { + return String.format(get(resid), objects); + } } diff --git a/src/ru/nsu/ccfit/zuev/osu/helper/TextButton.java b/src/ru/nsu/ccfit/zuev/osu/helper/TextButton.java index d3625ff4..526f7db6 100644 --- a/src/ru/nsu/ccfit/zuev/osu/helper/TextButton.java +++ b/src/ru/nsu/ccfit/zuev/osu/helper/TextButton.java @@ -11,47 +11,47 @@ */ public class TextButton extends Sprite { - private final Text buttonText; - - public TextButton(Font font, String text) { - this(font, text, 1.0f); - } - - public TextButton(Font font, String text, float scale) { - super(0, 0, ResourceManager.getInstance().getTexture( - "button")); - buttonText = new Text(0, 0, font, text); - buttonText.setScale(scale); - setColor(201 / 255f, 31 / 255f, 55 / 255f); - this.setWidth(buttonText.getWidthScaled() + 80); - this.setHeight(buttonText.getHeightScaled() + 20); - - float textX = (this.getWidth() - buttonText.getWidth()) / 2; - float textY = (this.getHeight() - buttonText.getHeight()) / 2; - buttonText.setPosition(textX, textY); - setAlpha(0.7f); - attachChild(buttonText); - } - - @Override - public void setWidth(float pWidth) { - this.mWidth = pWidth; - float textX = (this.getWidth() - buttonText.getWidth()) / 2; - float textY = (this.getHeight() - buttonText.getHeight()) / 2; - buttonText.setPosition(textX, textY); - this.updateVertexBuffer(); - } - - @Override - public void setHeight(float pHeight) { - this.mHeight = pHeight; - float textX = (this.getWidth() - buttonText.getWidth()) / 2; - float textY = (this.getHeight() - buttonText.getHeight()) / 2; - buttonText.setPosition(textX, textY); - this.updateVertexBuffer(); - } - - public void setTextColor(float pRed, float pGreen, float pBlue) { - buttonText.setColor(pRed, pGreen, pBlue); - } + private final Text buttonText; + + public TextButton(Font font, String text) { + this(font, text, 1.0f); + } + + public TextButton(Font font, String text, float scale) { + super(0, 0, ResourceManager.getInstance().getTexture( + "button")); + buttonText = new Text(0, 0, font, text); + buttonText.setScale(scale); + setColor(201 / 255f, 31 / 255f, 55 / 255f); + this.setWidth(buttonText.getWidthScaled() + 80); + this.setHeight(buttonText.getHeightScaled() + 20); + + float textX = (this.getWidth() - buttonText.getWidth()) / 2; + float textY = (this.getHeight() - buttonText.getHeight()) / 2; + buttonText.setPosition(textX, textY); + setAlpha(0.7f); + attachChild(buttonText); + } + + @Override + public void setWidth(float pWidth) { + this.mWidth = pWidth; + float textX = (this.getWidth() - buttonText.getWidth()) / 2; + float textY = (this.getHeight() - buttonText.getHeight()) / 2; + buttonText.setPosition(textX, textY); + this.updateVertexBuffer(); + } + + @Override + public void setHeight(float pHeight) { + this.mHeight = pHeight; + float textX = (this.getWidth() - buttonText.getWidth()) / 2; + float textY = (this.getHeight() - buttonText.getHeight()) / 2; + buttonText.setPosition(textX, textY); + this.updateVertexBuffer(); + } + + public void setTextColor(float pRed, float pGreen, float pBlue) { + buttonText.setColor(pRed, pGreen, pBlue); + } } diff --git a/src/ru/nsu/ccfit/zuev/osu/helper/UniversalModifier.java b/src/ru/nsu/ccfit/zuev/osu/helper/UniversalModifier.java index a39baf00..809e9a72 100644 --- a/src/ru/nsu/ccfit/zuev/osu/helper/UniversalModifier.java +++ b/src/ru/nsu/ccfit/zuev/osu/helper/UniversalModifier.java @@ -4,74 +4,74 @@ import org.anddev.andengine.entity.modifier.SingleValueSpanEntityModifier; public class UniversalModifier extends SingleValueSpanEntityModifier { - ValueType type; + ValueType type; - ; + ; - public UniversalModifier(final float duration, final float from, - final float to, final ValueType type) { - super(duration, from, to); - this.type = type; - } + public UniversalModifier(final float duration, final float from, + final float to, final ValueType type) { + super(duration, from, to); + this.type = type; + } - public UniversalModifier(final UniversalModifier modifier) { - super(modifier); - this.type = modifier.type; - } + public UniversalModifier(final UniversalModifier modifier) { + super(modifier); + this.type = modifier.type; + } - @Override - protected void onSetInitialValue(final IEntity pItem, final float pValue) { - switch (type) { - case ALPHA: - pItem.setAlpha(pValue); - break; - case SCALE: - pItem.setScale(pValue); - break; - default: - break; - } - } + @Override + protected void onSetInitialValue(final IEntity pItem, final float pValue) { + switch (type) { + case ALPHA: + pItem.setAlpha(pValue); + break; + case SCALE: + pItem.setScale(pValue); + break; + default: + break; + } + } - @Override - protected void onSetValue(final IEntity pItem, final float pPercentageDone, - final float pValue) { - switch (type) { - case ALPHA: - pItem.setAlpha(pValue); - break; - case SCALE: - pItem.setScale(pValue); - break; - default: - break; - } - } + @Override + protected void onSetValue(final IEntity pItem, final float pPercentageDone, + final float pValue) { + switch (type) { + case ALPHA: + pItem.setAlpha(pValue); + break; + case SCALE: + pItem.setScale(pValue); + break; + default: + break; + } + } - @Override - public UniversalModifier deepCopy() { - return new UniversalModifier(this); - } + @Override + public UniversalModifier deepCopy() { + return new UniversalModifier(this); + } - public void init(final float duration, final float from, final float to, - final ValueType type) { - reset(); - mDuration = duration; - mFromValue = from; - mValueSpan = to - from; - this.type = type; - } + public void init(final float duration, final float from, final float to, + final ValueType type) { + reset(); + mDuration = duration; + mFromValue = from; + mValueSpan = to - from; + this.type = type; + } - @Override - protected void onModifierFinished(final IEntity pItem) { - super.onModifierFinished(pItem); - this.mModifierListeners.clear(); - ModifierFactory.putModifier(this); - } + @Override + protected void onModifierFinished(final IEntity pItem) { + super.onModifierFinished(pItem); + this.mModifierListeners.clear(); + ModifierFactory.putModifier(this); + } - public enum ValueType { - NONE, ALPHA, SCALE - } + public enum ValueType { + NONE, ALPHA, SCALE + } } diff --git a/src/ru/nsu/ccfit/zuev/osu/helper/sql/DBOpenHelper.java b/src/ru/nsu/ccfit/zuev/osu/helper/sql/DBOpenHelper.java index 523885cd..a08a545d 100644 --- a/src/ru/nsu/ccfit/zuev/osu/helper/sql/DBOpenHelper.java +++ b/src/ru/nsu/ccfit/zuev/osu/helper/sql/DBOpenHelper.java @@ -5,64 +5,64 @@ import android.database.sqlite.SQLiteOpenHelper; public class DBOpenHelper extends SQLiteOpenHelper { - public static final String SCORES_TABLENAME = "scores"; - public static final String MAPS_TABLENAME = "ddlmaps"; - private static final String DBNAME = "osudroid_test"; - private static final int DBVERSION = 6; - private static DBOpenHelper helper = null; + public static final String SCORES_TABLENAME = "scores"; + public static final String MAPS_TABLENAME = "ddlmaps"; + private static final String DBNAME = "osudroid_test"; + private static final int DBVERSION = 6; + private static DBOpenHelper helper = null; - private DBOpenHelper(Context context) { - super(new DatabaseContext(context), DBNAME, null, DBVERSION); - } + private DBOpenHelper(Context context) { + super(new DatabaseContext(context), DBNAME, null, DBVERSION); + } - public static DBOpenHelper getOrCreate(Context context) { - if (helper == null) { - helper = new DBOpenHelper(context); - } - return helper; - } + public static DBOpenHelper getOrCreate(Context context) { + if (helper == null) { + helper = new DBOpenHelper(context); + } + return helper; + } - @Override - public void onCreate(SQLiteDatabase db) { - db.execSQL("CREATE TABLE IF NOT EXISTS " + SCORES_TABLENAME + " (" - + "id INTEGER PRIMARY KEY," - + "filename TEXT," - + "playername TEXT," - + "replayfile TEXT," - + "mode TEXT," - + "score INTEGER," - + "combo INTEGER," - + "mark TEXT," - + "h300k INTEGER," - + "h300 INTEGER," - + "h100k INTEGER," - + "h100 INTEGER," - + "h50 INTEGER," - + "misses INTEGER," - + "accuracy FLOAT," - + "time TIMESTAMP," - + "perfect INTEGER);"); + @Override + public void onCreate(SQLiteDatabase db) { + db.execSQL("CREATE TABLE IF NOT EXISTS " + SCORES_TABLENAME + " (" + + "id INTEGER PRIMARY KEY," + + "filename TEXT," + + "playername TEXT," + + "replayfile TEXT," + + "mode TEXT," + + "score INTEGER," + + "combo INTEGER," + + "mark TEXT," + + "h300k INTEGER," + + "h300 INTEGER," + + "h100k INTEGER," + + "h100 INTEGER," + + "h50 INTEGER," + + "misses INTEGER," + + "accuracy FLOAT," + + "time TIMESTAMP," + + "perfect INTEGER);"); - db.execSQL("CREATE TABLE IF NOT EXISTS " + MAPS_TABLENAME + " (" - + "id INTEGER PRIMARY KEY," - + "size INTEGER," - + "inserttime INTEGER," - + "link TEXT);"); + db.execSQL("CREATE TABLE IF NOT EXISTS " + MAPS_TABLENAME + " (" + + "id INTEGER PRIMARY KEY," + + "size INTEGER," + + "inserttime INTEGER," + + "link TEXT);"); - } + } - @Override - public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { - //db.execSQL("DROP TABLE IF EXISTS " + TABLENAME); - if (oldVersion <= 5 && newVersion == 6) { - if (oldVersion != 5) { - String sql = "alter table [" + SCORES_TABLENAME + "] add [time] TIMESTAMP"; - db.execSQL(sql); - } - String sql = "alter table [" + SCORES_TABLENAME + "] add [perfect] INTEGER"; - db.execSQL(sql); - } - } + @Override + public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { + //db.execSQL("DROP TABLE IF EXISTS " + TABLENAME); + if (oldVersion <= 5 && newVersion == 6) { + if (oldVersion != 5) { + String sql = "alter table [" + SCORES_TABLENAME + "] add [time] TIMESTAMP"; + db.execSQL(sql); + } + String sql = "alter table [" + SCORES_TABLENAME + "] add [perfect] INTEGER"; + db.execSQL(sql); + } + } } diff --git a/src/ru/nsu/ccfit/zuev/osu/helper/sql/DatabaseContext.java b/src/ru/nsu/ccfit/zuev/osu/helper/sql/DatabaseContext.java index 3c23c668..67fdde47 100644 --- a/src/ru/nsu/ccfit/zuev/osu/helper/sql/DatabaseContext.java +++ b/src/ru/nsu/ccfit/zuev/osu/helper/sql/DatabaseContext.java @@ -18,68 +18,68 @@ */ public class DatabaseContext extends ContextWrapper { - private static final String DEBUG_CONTEXT = "DatabaseContext"; - private Context context; + private static final String DEBUG_CONTEXT = "DatabaseContext"; + private Context context; - public DatabaseContext(Context base) { - super(base); - context = base; - } + public DatabaseContext(Context base) { + super(base); + context = base; + } - @Override - public File getDatabasePath(String name) { - String dbfile = Config.getCorePath() + "databases/" + name; - if (!dbfile.endsWith(".db")) { - dbfile += ".db"; - } + @Override + public File getDatabasePath(String name) { + String dbfile = Config.getCorePath() + "databases/" + name; + if (!dbfile.endsWith(".db")) { + dbfile += ".db"; + } - File result = new File(dbfile); + File result = new File(dbfile); - if (!result.getParentFile().exists()) { - result.getParentFile().mkdirs(); - } - Debug.i("getDatabasePath(" + name + ") = " + result.getAbsolutePath()); - final File olddb = context.getDatabasePath(name); - if (result.exists() == false && olddb.exists() == true) { - try { - FileUtils.copyFile(olddb, result); - } catch (IOException e) { - Debug.e(e); - } - } - final String olddbfile = Config.getCorePath() + File.separator + "databases" + File.separator + name; - final File olddb2 = new File(olddbfile); - if (result.exists() == false && olddb2.exists() == true) { - try { - FileUtils.copyFile(olddb2, result); - } catch (IOException e) { - Debug.e(e); - } - } - final String olddbfile2 = Config.getCorePath() + File.separator + "databases" + File.separator + "osudroid.db"; - final File olddb3 = new File(olddbfile2); - if (result.exists() == false && olddb3.exists() == true) { - try { - FileUtils.copyFile(olddb3, result); - } catch (IOException e) { - Debug.e(e); - } - } - return result; - } + if (!result.getParentFile().exists()) { + result.getParentFile().mkdirs(); + } + Debug.i("getDatabasePath(" + name + ") = " + result.getAbsolutePath()); + final File olddb = context.getDatabasePath(name); + if (result.exists() == false && olddb.exists() == true) { + try { + FileUtils.copyFile(olddb, result); + } catch (IOException e) { + Debug.e(e); + } + } + final String olddbfile = Config.getCorePath() + File.separator + "databases" + File.separator + name; + final File olddb2 = new File(olddbfile); + if (result.exists() == false && olddb2.exists() == true) { + try { + FileUtils.copyFile(olddb2, result); + } catch (IOException e) { + Debug.e(e); + } + } + final String olddbfile2 = Config.getCorePath() + File.separator + "databases" + File.separator + "osudroid.db"; + final File olddb3 = new File(olddbfile2); + if (result.exists() == false && olddb3.exists() == true) { + try { + FileUtils.copyFile(olddb3, result); + } catch (IOException e) { + Debug.e(e); + } + } + return result; + } - /* this version is called for android devices >= api-11. thank to @damccull for fixing this. */ - @Override - public SQLiteDatabase openOrCreateDatabase(String name, int mode, SQLiteDatabase.CursorFactory factory, DatabaseErrorHandler errorHandler) { - return openOrCreateDatabase(name, mode, factory); - } + /* this version is called for android devices >= api-11. thank to @damccull for fixing this. */ + @Override + public SQLiteDatabase openOrCreateDatabase(String name, int mode, SQLiteDatabase.CursorFactory factory, DatabaseErrorHandler errorHandler) { + return openOrCreateDatabase(name, mode, factory); + } - /* this version is called for android devices < api-11 */ - @Override - public SQLiteDatabase openOrCreateDatabase(String name, int mode, SQLiteDatabase.CursorFactory factory) { - SQLiteDatabase result = SQLiteDatabase.openOrCreateDatabase(getDatabasePath(name), null); - // SQLiteDatabase result = super.openOrCreateDatabase(name, mode, factory); - Debug.i("openOrCreateDatabase(" + name + ") = " + result.getPath()); - return result; - } -} \ No newline at end of file + /* this version is called for android devices < api-11 */ + @Override + public SQLiteDatabase openOrCreateDatabase(String name, int mode, SQLiteDatabase.CursorFactory factory) { + SQLiteDatabase result = SQLiteDatabase.openOrCreateDatabase(getDatabasePath(name), null); + // SQLiteDatabase result = super.openOrCreateDatabase(name, mode, factory); + Debug.i("openOrCreateDatabase(" + name + ") = " + result.getPath()); + return result; + } +} diff --git a/src/ru/nsu/ccfit/zuev/osu/menu/FilterMenu.java b/src/ru/nsu/ccfit/zuev/osu/menu/FilterMenu.java index 066fb7da..2c3c3b89 100644 --- a/src/ru/nsu/ccfit/zuev/osu/menu/FilterMenu.java +++ b/src/ru/nsu/ccfit/zuev/osu/menu/FilterMenu.java @@ -27,378 +27,378 @@ import ru.nsu.ccfit.zuev.osuplus.R; public class FilterMenu implements IUpdateHandler, IFilterMenu { - private Context configContext = null; - private static IFilterMenu instance; - private Scene scene = null; - private ChangeableText filterText; - private String filter = ""; - private ChangeableText sortText; - private SongMenu menu; - private SortOrder order = SortOrder.Title; - private boolean favoritesOnly = false; - private String favoriteFolder = null; - - private FilterMenu() { - } - - public static IFilterMenu getInstance() { - if (instance == null) { - instance = new FilterMenuFragment(); - } - return instance; - } - - @Override - public String getFavoriteFolder() { - return favoriteFolder; - } - - public void loadConfig(final Context context) { - final SharedPreferences prefs = PreferenceManager - .getDefaultSharedPreferences(context); - - final int sortOrder = prefs.getInt("sortorder", 0); - switch (sortOrder) { - case 1: - order = SortOrder.Artist; - break; - case 2: - order = SortOrder.Creator; - break; - case 3: - order = SortOrder.Date; - break; - case 4: - order = SortOrder.Bpm; - break; - case 5: - order = SortOrder.Stars; - break; - case 6: - order = SortOrder.Length; - break; - default: - order = SortOrder.Title; - break; - } - configContext = context; - setSortText(); - } - - public void saveConfig() { - if (configContext == null) { - return; - } - - final SharedPreferences prefs = PreferenceManager - .getDefaultSharedPreferences(configContext); - final SharedPreferences.Editor editor = prefs.edit(); - - switch (order) { - case Artist: - editor.putInt("sortorder", 1); - break; - case Creator: - editor.putInt("sortorder", 2); - break; - case Date: - editor.putInt("sortorder", 3); - break; - case Bpm: - editor.putInt("sortorder", 4); - break; - case Stars: - editor.putInt("sortorder", 5); - break; - case Length: - editor.putInt("sortorder", 6); - break; - default: - editor.putInt("sortorder", 0); - break; - } - - editor.apply(); - } - - public void setSongMenu(final SongMenu menu) { - this.menu = menu; - } - - public void reload() { - init(); - } - - public void init() { - scene = new Scene(); - scene.setBackgroundEnabled(false); - final Rectangle bg = new Rectangle(0, 0, Config.getRES_WIDTH(), - Config.getRES_HEIGHT()); - bg.setColor(0, 0, 0, 0.7f); - scene.attachChild(bg); - - final Text caption = new Text(0, Utils.toRes(60), ResourceManager - .getInstance().getFont("CaptionFont"), - StringTable.get(R.string.menu_search_title)); - caption.setPosition(Config.getRES_WIDTH() / 2f - caption.getWidth() / 2, - caption.getY()); - scene.attachChild(caption); - - final Font font = ResourceManager.getInstance().getFont("font"); - - final Text capt1 = new Text(Utils.toRes(100), Utils.toRes(160), font, - StringTable.get(R.string.menu_search_filter)); - capt1.setPosition(Config.getRES_WIDTH() / 4f - capt1.getWidth(), capt1.getY()); - scene.attachChild(capt1); - - final Rectangle filterBorder = new Rectangle(capt1.getX(), - Utils.toRes(195), Utils.toRes(330), capt1.getHeight() - + Utils.toRes(30)); - scene.attachChild(filterBorder); - filterBorder.setColor(1, 150f / 255, 0); - filterBorder.setVisible(false); - final Rectangle filterBg = new Rectangle(filterBorder.getX() + 5, - Utils.toRes(200), Utils.toRes(320), capt1.getHeight() - + Utils.toRes(20)) { - - @Override - public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, - final float pTouchAreaLocalX, final float pTouchAreaLocalY) { - if (pSceneTouchEvent.isActionDown()) { - filterBorder.setVisible(true); - InputManager.getInstance().startInput( - FilterMenu.getInstance().getFilter(), 20); - return true; - } - return false; - } - }; - scene.registerTouchArea(filterBg); - scene.attachChild(filterBg); - - filterText = new ChangeableText(capt1.getX(), Utils.toRes(210), font, - filter, 21); - filterText.setColor(0, 0, 0); - scene.attachChild(filterText); - - final Text capt2 = new Text(Utils.toRes(700), Utils.toRes(160), font, - StringTable.get(R.string.menu_search_sort)); - capt2.setPosition(Config.getRES_WIDTH() * 2f / 3 - capt2.getWidth(), capt2.getY()); - scene.attachChild(capt2); - - final Rectangle sortBg = new Rectangle(capt2.getX(), Utils.toRes(200), - Utils.toRes(200), capt2.getHeight() + Utils.toRes(20)) { - - @Override - public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, - final float pTouchAreaLocalX, final float pTouchAreaLocalY) { - if (pSceneTouchEvent.isActionDown()) { - SortOrder newOrder; - switch (order) { - case Title: - newOrder = SortOrder.Artist; - break; - case Artist: - newOrder = SortOrder.Creator; - break; - case Creator: - newOrder = SortOrder.Date; - break; - case Date: - newOrder = SortOrder.Bpm; - break; - case Bpm: - newOrder = SortOrder.Stars; - break; - case Stars: - newOrder = SortOrder.Length; - break; - default: - newOrder = SortOrder.Title; - break; - } - order = newOrder; - setSortText(); - saveConfig(); - return true; - } - return false; - } - }; - scene.registerTouchArea(sortBg); - scene.attachChild(sortBg); - sortText = new ChangeableText(capt2.getX() + 5, - Utils.toRes(210), font, - StringTable.get(R.string.menu_search_sort_title), 10); - sortText.setColor(0, 0, 0); - setSortText(); - sortText.detachSelf(); - scene.attachChild(sortText); - - final TextButton back = new TextButton(ResourceManager - .getInstance().getFont("CaptionFont"), - StringTable.get(R.string.menu_mod_back)) { - - @Override - public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, - final float pTouchAreaLocalX, final float pTouchAreaLocalY) { - if (pSceneTouchEvent.isActionUp()) { - hideMenu(); - return true; - } - return false; - } - }; - back.setWidth(Utils.toRes(400)); - back.setScale(1.2f); - back.setPosition(Config.getRES_WIDTH() / 2f - back.getWidth() / 2, Config.getRES_HEIGHT() * 3f / 4 - back.getHeight() / 2); - back.setColor(66 / 255f, 76 / 255f, 80 / 255f); - scene.attachChild(back); - scene.registerTouchArea(back); - - final ChangeableText favs = new ChangeableText(capt1.getX(), - Utils.toRes(300), ResourceManager.getInstance().getFont( - "CaptionFont"), - StringTable.get(R.string.menu_search_favsdisabled)) { - - @Override - public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, - final float pTouchAreaLocalX, final float pTouchAreaLocalY) { - if (pSceneTouchEvent.isActionUp()) { - if (favoritesOnly) { - setText(StringTable - .get(R.string.menu_search_favsdisabled)); - setColor(1, 1, 1); - } else { - setText(StringTable - .get(R.string.menu_search_favsenabled)); - setColor(0, 1, 0); - } - favoritesOnly = !favoritesOnly; - return true; - } - return false; - } - }; - if (favoritesOnly) { - favs.setText(StringTable.get(R.string.menu_search_favsenabled)); - favs.setColor(0, 1, 0); - } - favs.setPosition(capt1.getX(), - favs.getY()); - scene.attachChild(favs); - scene.registerTouchArea(favs); - - - final ChangeableText folder = new ChangeableText(favs.getX(), - favs.getY() + favs.getHeight() + Utils.toRes(20), ResourceManager.getInstance().getFont( - "CaptionFont"), - StringTable.get(R.string.favorite_folder) + " " + (favoriteFolder == null ? StringTable.get(R.string.favorite_default) : favoriteFolder), 40) { - @Override - public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, - final float pTouchAreaLocalX, final float pTouchAreaLocalY) { - if (pSceneTouchEvent.isActionUp()) { - //显示选择收藏夹的dialog - GlobalManager.getInstance().getMainActivity().runOnUiThread(() -> { - FavoriteManagerFragment dialog = new FavoriteManagerFragment(); - dialog.showToSelectFloder(folder1 -> { - favoriteFolder = folder1; - this.setText(StringTable.get(R.string.favorite_folder) + " " + (favoriteFolder == null ? StringTable.get(R.string.favorite_default) : favoriteFolder)); - }); - }); - return true; - } - return false; - } - }; - - folder.setPosition(favs.getX(), - favs.getY() + favs.getHeight() + Utils.toRes(20)); - scene.attachChild(folder); - scene.registerTouchArea(folder); - - scene.registerUpdateHandler(this); - scene.setTouchAreaBindingEnabled(true); - } - - public void hideMenu() { - if (menu != null) { - menu.getScene().clearChildScene(); - menu.loadFilter(this); - scene = null; - } - } - - @Override - public void showMenu(SongMenu parent) { - reload(); - setSongMenu(parent); - parent.scene.setChildScene( - scene, false, - true, true); - } - - private void setSortText() { - if (sortText == null) { - return; - } - String s; - switch (order) { - case Title: - s = StringTable.get(R.string.menu_search_sort_title); - break; - case Artist: - s = StringTable.get(R.string.menu_search_sort_artist); - break; - case Date: - s = StringTable.get(R.string.menu_search_sort_date); - break; - case Bpm: - s = StringTable.get(R.string.menu_search_sort_bpm); - break; - case Stars: - s = StringTable.get(R.string.menu_search_sort_stars); - break; - case Length: - s = StringTable.get(R.string.menu_search_sort_length); - break; - default: - s = StringTable.get(R.string.menu_search_sort_creator); - break; - } - sortText.setText(s); - } - - public Scene getScene() { - if (scene == null) { - init(); - } - return scene; - } - - public void onUpdate(final float pSecondsElapsed) { - if (InputManager.getInstance().isChanged()) { - filter = InputManager.getInstance().getText(); - filterText.setText(filter); - } - } - - - public void reset() { - // TODO Auto-generated method stub - - } - - public SortOrder getOrder() { - return order; - } - - public String getFilter() { - return filter; - } - - public boolean isFavoritesOnly() { - return favoritesOnly; - } + private Context configContext = null; + private static IFilterMenu instance; + private Scene scene = null; + private ChangeableText filterText; + private String filter = ""; + private ChangeableText sortText; + private SongMenu menu; + private SortOrder order = SortOrder.Title; + private boolean favoritesOnly = false; + private String favoriteFolder = null; + + private FilterMenu() { + } + + public static IFilterMenu getInstance() { + if (instance == null) { + instance = new FilterMenuFragment(); + } + return instance; + } + + @Override + public String getFavoriteFolder() { + return favoriteFolder; + } + + public void loadConfig(final Context context) { + final SharedPreferences prefs = PreferenceManager + .getDefaultSharedPreferences(context); + + final int sortOrder = prefs.getInt("sortorder", 0); + switch (sortOrder) { + case 1: + order = SortOrder.Artist; + break; + case 2: + order = SortOrder.Creator; + break; + case 3: + order = SortOrder.Date; + break; + case 4: + order = SortOrder.Bpm; + break; + case 5: + order = SortOrder.Stars; + break; + case 6: + order = SortOrder.Length; + break; + default: + order = SortOrder.Title; + break; + } + configContext = context; + setSortText(); + } + + public void saveConfig() { + if (configContext == null) { + return; + } + + final SharedPreferences prefs = PreferenceManager + .getDefaultSharedPreferences(configContext); + final SharedPreferences.Editor editor = prefs.edit(); + + switch (order) { + case Artist: + editor.putInt("sortorder", 1); + break; + case Creator: + editor.putInt("sortorder", 2); + break; + case Date: + editor.putInt("sortorder", 3); + break; + case Bpm: + editor.putInt("sortorder", 4); + break; + case Stars: + editor.putInt("sortorder", 5); + break; + case Length: + editor.putInt("sortorder", 6); + break; + default: + editor.putInt("sortorder", 0); + break; + } + + editor.apply(); + } + + public void setSongMenu(final SongMenu menu) { + this.menu = menu; + } + + public void reload() { + init(); + } + + public void init() { + scene = new Scene(); + scene.setBackgroundEnabled(false); + final Rectangle bg = new Rectangle(0, 0, Config.getRES_WIDTH(), + Config.getRES_HEIGHT()); + bg.setColor(0, 0, 0, 0.7f); + scene.attachChild(bg); + + final Text caption = new Text(0, Utils.toRes(60), ResourceManager + .getInstance().getFont("CaptionFont"), + StringTable.get(R.string.menu_search_title)); + caption.setPosition(Config.getRES_WIDTH() / 2f - caption.getWidth() / 2, + caption.getY()); + scene.attachChild(caption); + + final Font font = ResourceManager.getInstance().getFont("font"); + + final Text capt1 = new Text(Utils.toRes(100), Utils.toRes(160), font, + StringTable.get(R.string.menu_search_filter)); + capt1.setPosition(Config.getRES_WIDTH() / 4f - capt1.getWidth(), capt1.getY()); + scene.attachChild(capt1); + + final Rectangle filterBorder = new Rectangle(capt1.getX(), + Utils.toRes(195), Utils.toRes(330), capt1.getHeight() + + Utils.toRes(30)); + scene.attachChild(filterBorder); + filterBorder.setColor(1, 150f / 255, 0); + filterBorder.setVisible(false); + final Rectangle filterBg = new Rectangle(filterBorder.getX() + 5, + Utils.toRes(200), Utils.toRes(320), capt1.getHeight() + + Utils.toRes(20)) { + + @Override + public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, + final float pTouchAreaLocalX, final float pTouchAreaLocalY) { + if (pSceneTouchEvent.isActionDown()) { + filterBorder.setVisible(true); + InputManager.getInstance().startInput( + FilterMenu.getInstance().getFilter(), 20); + return true; + } + return false; + } + }; + scene.registerTouchArea(filterBg); + scene.attachChild(filterBg); + + filterText = new ChangeableText(capt1.getX(), Utils.toRes(210), font, + filter, 21); + filterText.setColor(0, 0, 0); + scene.attachChild(filterText); + + final Text capt2 = new Text(Utils.toRes(700), Utils.toRes(160), font, + StringTable.get(R.string.menu_search_sort)); + capt2.setPosition(Config.getRES_WIDTH() * 2f / 3 - capt2.getWidth(), capt2.getY()); + scene.attachChild(capt2); + + final Rectangle sortBg = new Rectangle(capt2.getX(), Utils.toRes(200), + Utils.toRes(200), capt2.getHeight() + Utils.toRes(20)) { + + @Override + public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, + final float pTouchAreaLocalX, final float pTouchAreaLocalY) { + if (pSceneTouchEvent.isActionDown()) { + SortOrder newOrder; + switch (order) { + case Title: + newOrder = SortOrder.Artist; + break; + case Artist: + newOrder = SortOrder.Creator; + break; + case Creator: + newOrder = SortOrder.Date; + break; + case Date: + newOrder = SortOrder.Bpm; + break; + case Bpm: + newOrder = SortOrder.Stars; + break; + case Stars: + newOrder = SortOrder.Length; + break; + default: + newOrder = SortOrder.Title; + break; + } + order = newOrder; + setSortText(); + saveConfig(); + return true; + } + return false; + } + }; + scene.registerTouchArea(sortBg); + scene.attachChild(sortBg); + sortText = new ChangeableText(capt2.getX() + 5, + Utils.toRes(210), font, + StringTable.get(R.string.menu_search_sort_title), 10); + sortText.setColor(0, 0, 0); + setSortText(); + sortText.detachSelf(); + scene.attachChild(sortText); + + final TextButton back = new TextButton(ResourceManager + .getInstance().getFont("CaptionFont"), + StringTable.get(R.string.menu_mod_back)) { + + @Override + public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, + final float pTouchAreaLocalX, final float pTouchAreaLocalY) { + if (pSceneTouchEvent.isActionUp()) { + hideMenu(); + return true; + } + return false; + } + }; + back.setWidth(Utils.toRes(400)); + back.setScale(1.2f); + back.setPosition(Config.getRES_WIDTH() / 2f - back.getWidth() / 2, Config.getRES_HEIGHT() * 3f / 4 - back.getHeight() / 2); + back.setColor(66 / 255f, 76 / 255f, 80 / 255f); + scene.attachChild(back); + scene.registerTouchArea(back); + + final ChangeableText favs = new ChangeableText(capt1.getX(), + Utils.toRes(300), ResourceManager.getInstance().getFont( + "CaptionFont"), + StringTable.get(R.string.menu_search_favsdisabled)) { + + @Override + public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, + final float pTouchAreaLocalX, final float pTouchAreaLocalY) { + if (pSceneTouchEvent.isActionUp()) { + if (favoritesOnly) { + setText(StringTable + .get(R.string.menu_search_favsdisabled)); + setColor(1, 1, 1); + } else { + setText(StringTable + .get(R.string.menu_search_favsenabled)); + setColor(0, 1, 0); + } + favoritesOnly = !favoritesOnly; + return true; + } + return false; + } + }; + if (favoritesOnly) { + favs.setText(StringTable.get(R.string.menu_search_favsenabled)); + favs.setColor(0, 1, 0); + } + favs.setPosition(capt1.getX(), + favs.getY()); + scene.attachChild(favs); + scene.registerTouchArea(favs); + + + final ChangeableText folder = new ChangeableText(favs.getX(), + favs.getY() + favs.getHeight() + Utils.toRes(20), ResourceManager.getInstance().getFont( + "CaptionFont"), + StringTable.get(R.string.favorite_folder) + " " + (favoriteFolder == null ? StringTable.get(R.string.favorite_default) : favoriteFolder), 40) { + @Override + public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, + final float pTouchAreaLocalX, final float pTouchAreaLocalY) { + if (pSceneTouchEvent.isActionUp()) { + //显示选择收藏夹的dialog + GlobalManager.getInstance().getMainActivity().runOnUiThread(() -> { + FavoriteManagerFragment dialog = new FavoriteManagerFragment(); + dialog.showToSelectFloder(folder1 -> { + favoriteFolder = folder1; + this.setText(StringTable.get(R.string.favorite_folder) + " " + (favoriteFolder == null ? StringTable.get(R.string.favorite_default) : favoriteFolder)); + }); + }); + return true; + } + return false; + } + }; + + folder.setPosition(favs.getX(), + favs.getY() + favs.getHeight() + Utils.toRes(20)); + scene.attachChild(folder); + scene.registerTouchArea(folder); + + scene.registerUpdateHandler(this); + scene.setTouchAreaBindingEnabled(true); + } + + public void hideMenu() { + if (menu != null) { + menu.getScene().clearChildScene(); + menu.loadFilter(this); + scene = null; + } + } + + @Override + public void showMenu(SongMenu parent) { + reload(); + setSongMenu(parent); + parent.scene.setChildScene( + scene, false, + true, true); + } + + private void setSortText() { + if (sortText == null) { + return; + } + String s; + switch (order) { + case Title: + s = StringTable.get(R.string.menu_search_sort_title); + break; + case Artist: + s = StringTable.get(R.string.menu_search_sort_artist); + break; + case Date: + s = StringTable.get(R.string.menu_search_sort_date); + break; + case Bpm: + s = StringTable.get(R.string.menu_search_sort_bpm); + break; + case Stars: + s = StringTable.get(R.string.menu_search_sort_stars); + break; + case Length: + s = StringTable.get(R.string.menu_search_sort_length); + break; + default: + s = StringTable.get(R.string.menu_search_sort_creator); + break; + } + sortText.setText(s); + } + + public Scene getScene() { + if (scene == null) { + init(); + } + return scene; + } + + public void onUpdate(final float pSecondsElapsed) { + if (InputManager.getInstance().isChanged()) { + filter = InputManager.getInstance().getText(); + filterText.setText(filter); + } + } + + + public void reset() { + // TODO Auto-generated method stub + + } + + public SortOrder getOrder() { + return order; + } + + public String getFilter() { + return filter; + } + + public boolean isFavoritesOnly() { + return favoritesOnly; + } } diff --git a/src/ru/nsu/ccfit/zuev/osu/menu/IFilterMenu.java b/src/ru/nsu/ccfit/zuev/osu/menu/IFilterMenu.java index cb842295..a78704e7 100644 --- a/src/ru/nsu/ccfit/zuev/osu/menu/IFilterMenu.java +++ b/src/ru/nsu/ccfit/zuev/osu/menu/IFilterMenu.java @@ -6,19 +6,19 @@ public interface IFilterMenu { - String getFilter(); + String getFilter(); - SongMenu.SortOrder getOrder(); + SongMenu.SortOrder getOrder(); - boolean isFavoritesOnly(); + boolean isFavoritesOnly(); - String getFavoriteFolder(); + String getFavoriteFolder(); - void loadConfig(Context context); + void loadConfig(Context context); - Scene getScene(); + Scene getScene(); - void hideMenu(); + void hideMenu(); - void showMenu(SongMenu parent); + void showMenu(SongMenu parent); } diff --git a/src/ru/nsu/ccfit/zuev/osu/menu/IPropsMenu.java b/src/ru/nsu/ccfit/zuev/osu/menu/IPropsMenu.java index ed588334..ebf3187c 100644 --- a/src/ru/nsu/ccfit/zuev/osu/menu/IPropsMenu.java +++ b/src/ru/nsu/ccfit/zuev/osu/menu/IPropsMenu.java @@ -2,5 +2,5 @@ public interface IPropsMenu { - void show(SongMenu menu, MenuItem item); + void show(SongMenu menu, MenuItem item); } diff --git a/src/ru/nsu/ccfit/zuev/osu/menu/IScrollBarListener.java b/src/ru/nsu/ccfit/zuev/osu/menu/IScrollBarListener.java index 5faac29d..9e1705d1 100644 --- a/src/ru/nsu/ccfit/zuev/osu/menu/IScrollBarListener.java +++ b/src/ru/nsu/ccfit/zuev/osu/menu/IScrollBarListener.java @@ -1,5 +1,5 @@ package ru.nsu.ccfit.zuev.osu.menu; public interface IScrollBarListener { - void onScroll(float where); + void onScroll(float where); } diff --git a/src/ru/nsu/ccfit/zuev/osu/menu/LoadingScreen.java b/src/ru/nsu/ccfit/zuev/osu/menu/LoadingScreen.java index 7f2a754e..6f2aa46b 100644 --- a/src/ru/nsu/ccfit/zuev/osu/menu/LoadingScreen.java +++ b/src/ru/nsu/ccfit/zuev/osu/menu/LoadingScreen.java @@ -22,79 +22,79 @@ import ru.nsu.ccfit.zuev.osu.helper.CentredSprite; public class LoadingScreen implements IUpdateHandler { - private final LoadingScene scene; - private final ChangeableText logText; - private float percentage; - - public LoadingScreen() { - ArrayList toastLoggerLog = ToastLogger.getLog(); - - if (toastLoggerLog != null) { - toastLoggerLog.clear(); - } - - scene = new LoadingScene(); - scene.registerEntityModifier(new FadeOutModifier(0.4f)); - - final TextureRegion tex = ResourceManager.getInstance().getTexture("menu-background"); - if (tex != null) { - float height = tex.getHeight(); - height *= Config.getRES_WIDTH() - / (float) tex.getWidth(); - final Sprite menuBg = new Sprite( - 0, - (Config.getRES_HEIGHT() - height) / 2, - Config.getRES_WIDTH(), - height, tex); - scene.setBackground(new SpriteBackground(menuBg)); - } else { - scene.setBackground(new ColorBackground(70 / 255f, 129 / 255f, - 252 / 255f)); - } - - final TextureRegion loadingTexture = ResourceManager.getInstance() - .getTexture("loading-title"); - final Sprite loadingTitle = new Sprite(0, 0, - Config.getRES_WIDTH(), loadingTexture.getHeight(), loadingTexture); - scene.attachChild(loadingTitle); - - logText = new ChangeableText(0, 0, ResourceManager.getInstance() - .getFont("logFont"), "", 5); - scene.attachChild(logText); - ToastLogger.setPercentage(-1); - percentage = -1; - - final TextureRegion ltexture = ResourceManager.getInstance() - .getTexture("loading"); - final Sprite circle = new CentredSprite(Config.getRES_WIDTH() / 2f, - Config.getRES_HEIGHT() / 2f, ltexture); - circle.registerEntityModifier(new LoopEntityModifier( - new RotationByModifier(2.0f, 360))); - scene.attachChild(circle); - - scene.registerUpdateHandler(this); - } - - public Scene getScene() { - return scene; - } - - - @SuppressLint("DefaultLocale") - public void onUpdate(final float pSecondsElapsed) { - if (ToastLogger.getPercentage() != percentage) { - percentage = ToastLogger.getPercentage(); - logText.setText(String.format("%d%%", (int) percentage)); - logText.setPosition(Config.getRES_WIDTH() / 2f - logText.getWidth() - / 2, Config.getRES_HEIGHT() - Utils.toRes(100)); - } - } - - - public void reset() { - // TODO Auto-generated method stub - } - - - public static class LoadingScene extends Scene { } + private final LoadingScene scene; + private final ChangeableText logText; + private float percentage; + + public LoadingScreen() { + ArrayList toastLoggerLog = ToastLogger.getLog(); + + if (toastLoggerLog != null) { + toastLoggerLog.clear(); + } + + scene = new LoadingScene(); + scene.registerEntityModifier(new FadeOutModifier(0.4f)); + + final TextureRegion tex = ResourceManager.getInstance().getTexture("menu-background"); + if (tex != null) { + float height = tex.getHeight(); + height *= Config.getRES_WIDTH() + / (float) tex.getWidth(); + final Sprite menuBg = new Sprite( + 0, + (Config.getRES_HEIGHT() - height) / 2, + Config.getRES_WIDTH(), + height, tex); + scene.setBackground(new SpriteBackground(menuBg)); + } else { + scene.setBackground(new ColorBackground(70 / 255f, 129 / 255f, + 252 / 255f)); + } + + final TextureRegion loadingTexture = ResourceManager.getInstance() + .getTexture("loading-title"); + final Sprite loadingTitle = new Sprite(0, 0, + Config.getRES_WIDTH(), loadingTexture.getHeight(), loadingTexture); + scene.attachChild(loadingTitle); + + logText = new ChangeableText(0, 0, ResourceManager.getInstance() + .getFont("logFont"), "", 5); + scene.attachChild(logText); + ToastLogger.setPercentage(-1); + percentage = -1; + + final TextureRegion ltexture = ResourceManager.getInstance() + .getTexture("loading"); + final Sprite circle = new CentredSprite(Config.getRES_WIDTH() / 2f, + Config.getRES_HEIGHT() / 2f, ltexture); + circle.registerEntityModifier(new LoopEntityModifier( + new RotationByModifier(2.0f, 360))); + scene.attachChild(circle); + + scene.registerUpdateHandler(this); + } + + public Scene getScene() { + return scene; + } + + + @SuppressLint("DefaultLocale") + public void onUpdate(final float pSecondsElapsed) { + if (ToastLogger.getPercentage() != percentage) { + percentage = ToastLogger.getPercentage(); + logText.setText(String.format("%d%%", (int) percentage)); + logText.setPosition(Config.getRES_WIDTH() / 2f - logText.getWidth() + / 2, Config.getRES_HEIGHT() - Utils.toRes(100)); + } + } + + + public void reset() { + // TODO Auto-generated method stub + } + + + public static class LoadingScene extends Scene { } } diff --git a/src/ru/nsu/ccfit/zuev/osu/menu/MenuItem.java b/src/ru/nsu/ccfit/zuev/osu/menu/MenuItem.java index 981bb0cb..6f453ef9 100644 --- a/src/ru/nsu/ccfit/zuev/osu/menu/MenuItem.java +++ b/src/ru/nsu/ccfit/zuev/osu/menu/MenuItem.java @@ -22,439 +22,439 @@ import ru.nsu.ccfit.zuev.osuplus.R; public class MenuItem { - private final MenuItemTrack[] trackSprites; - private final BeatmapInfo beatmap; - private final String trackDir; - private final int bgHeight; - private final String titleStr; - private final String creatorStr; - public float percentAppeared = 0; - MenuItemBackground background; - Scene scene; - boolean selected = false; - WeakReference listener; - private MenuItemTrack selTrack = null; - private boolean visible = true; - private boolean favorite; - private boolean deleted = false; - private Entity layer = null; - private int trackId = -1; - - public MenuItem(final MenuItemListener listener, final BeatmapInfo info) { - this.listener = new WeakReference<>(listener); - beatmap = info; - trackDir = ScoreLibrary.getTrackDir(beatmap.getPath()); - bgHeight = ResourceManager.getInstance() - .getTexture("menu-button-background").getHeight() - - Utils.toRes(25); -// titleStr = (beatmap.getArtistUnicode() == null ? beatmap.getArtist() : beatmap.getArtistUnicode()) + " - " -// + (beatmap.getTitleUnicode() == null ? beatmap.getTitle() : beatmap.getTitleUnicode()); - titleStr = beatmap.getArtist() + " - " + beatmap.getTitle(); - creatorStr = StringTable.format(R.string.menu_creator, - beatmap.getCreator()); - trackSprites = new MenuItemTrack[info.getCount()]; - - final BeatmapProperties props = PropertiesLibrary.getInstance() - .getProperties(info.getPath()); - favorite = props != null && props.isFavorite(); - - } - - public MenuItem(final MenuItemListener listener, final BeatmapInfo info, int id) { - this.listener = new WeakReference<>(listener); - beatmap = info; - trackDir = ScoreLibrary.getTrackDir(beatmap.getPath()); - bgHeight = ResourceManager.getInstance() - .getTexture("menu-button-background").getHeight() - - Utils.toRes(25); -// titleStr = (beatmap.getArtistUnicode() == null ? beatmap.getArtist() : beatmap.getArtistUnicode()) + " - " -// + (beatmap.getTitleUnicode() == null ? beatmap.getTitle() : beatmap.getTitleUnicode()); - titleStr = beatmap.getArtist() + " - " + beatmap.getTitle(); - creatorStr = StringTable.format(R.string.menu_creator, beatmap.getCreator()); - trackSprites = new MenuItemTrack[1]; - trackId = id; - final BeatmapProperties props = PropertiesLibrary.getInstance().getProperties(info.getPath()); - favorite = props != null && props.isFavorite(); - - } - - public BeatmapInfo getBeatmap() { - return beatmap; - } - - public void updateMarks() { - for (final MenuItemTrack tr : trackSprites) { - if (tr != null) { - tr.updateMark(); - } - } - } - - public void attachToScene(final Scene scene, final Entity layer) { - this.scene = scene; - this.layer = layer; - // initBackground(); - } - - public float getHeight() { - if (!visible) { - return 0; - } - if (selected) { - return bgHeight + percentAppeared * (bgHeight) - * (trackSprites.length - 1); - } - return bgHeight - Utils.toRes(5); - } - - public float getInitialHeight() { - if (!visible) { - return 0; - } - return bgHeight - Utils.toRes(5); - } - - public float getTotalHeight() { - return (bgHeight) * (trackSprites.length); - } - - public void setPos(final float x, final float y) { - if (background != null) { - background.setPosition(x, y); - if (y > Config.getRES_HEIGHT() || y < -background.getHeight()) { - freeBackground(); - } - } - if (!selected) { - if (visible && background == null - && y < Config.getRES_HEIGHT() && y > -bgHeight) { - initBackground(); - background.setPosition(x, y); - } - return; - } - float oy = 0; - for (final Sprite s : trackSprites) { - if (s == null) { - continue; - } - final float cy = y + oy + Config.getRES_HEIGHT() / 2f - + s.getHeight() / 2; - final float ox = x - + Utils.toRes(170 * (float) Math.abs(Math.cos(cy * Math.PI - / (Config.getRES_HEIGHT() * 2)))); - s.setPosition(ox - Utils.toRes(100), y + oy); - oy += (s.getHeight() - Utils.toRes(25)) * percentAppeared; - } - } - - public void select(boolean reloadMusic, boolean reloadBG) { - if (!listener.get().isSelectAllowed() || scene == null) { - return; - } - - freeBackground(); - selected = true; - listener.get().select(this); - initTracks(); - percentAppeared = 0; - final String musicFileName = beatmap.getMusic(); - if (reloadMusic) { - listener.get().playMusic(musicFileName, beatmap.getPreviewTime()); - } - - selectTrack(trackSprites[0], reloadBG); - trackSprites[0].setSelectedColor(); - } - - public void deselect() { - if (scene == null ) { - return; - } - - if (deleted) { - return; - } - initBackground(); - selected = false; - percentAppeared = 0; - deselectTrack(); - freeTracks(); - } - - public void deselectTrack() { - if (scene == null) { - return; - } - if (selTrack != null) { - selTrack.setDeselectColor(); - } - selTrack = null; - } - - public void applyFilter(final String filter, final boolean favs, Set limit) { - if ((favs && !isFavorite()) - || (limit != null && !limit.contains(trackDir))) { - //System.out.println(trackDir); - if (selected) { - deselect(); - } - freeBackground(); - visible = false; - return; - } - final StringBuilder builder = new StringBuilder(); - builder.append(beatmap.getTitle()); - builder.append(' '); - builder.append(beatmap.getArtist()); - builder.append(' '); - builder.append(beatmap.getCreator()); - builder.append(' '); - builder.append(beatmap.getTags()); - builder.append(' '); - builder.append(beatmap.getSource()); - builder.append(' '); - builder.append(beatmap.getTracks().get(0).getBeatmapSetID()); - for (TrackInfo track : beatmap.getTracks()) { - builder.append(' '); - builder.append(track.getMode()); - } - boolean canVisible = true; - final String lowerText = builder.toString().toLowerCase(); - final String[] lowerFilterTexts = filter.toLowerCase().split("[ ]"); - for (String filterText : lowerFilterTexts) { - Pattern pattern = Pattern.compile("(ar|od|cs|hp|star)(=|<|>|<=|>=)(\\d+)"); - Matcher matcher = pattern.matcher(filterText); - if (matcher.find()) { - String key = matcher.group(1); - String opt = matcher.group(2); - String value = matcher.group(3); - boolean vis = false; - if(trackId < 0){ - for (TrackInfo track : beatmap.getTracks()) { - if (key != null) { - vis |= visibleTrack(track, key, opt, value); - } - } - } - else{ - if (key != null) { - vis = visibleTrack(beatmap.getTrack(trackId), key, opt, value); - } - } - canVisible &= vis; - } else { - if (!lowerText.contains(filterText)) { - canVisible = false; - break; - } - } - } - - if (filter.equals("")) { - canVisible = true; - } - - if (canVisible) { - if (!visible) { - visible = true; - // initBackground(); - selected = false; - percentAppeared = 0; - } - return; - } - - if (selected) { - deselect(); - } - freeBackground(); - visible = false; - } - - private boolean visibleTrack(TrackInfo track, String key, String opt, String value) { - switch (key) { - case "ar": - return calOpt(track.getApproachRate(), Float.parseFloat(value), opt); - case "od": - return calOpt(track.getOverallDifficulty(), Float.parseFloat(value), opt); - case "cs": - return calOpt(track.getCircleSize(), Float.parseFloat(value), opt); - case "hp": - return calOpt(track.getHpDrain(), Float.parseFloat(value), opt); - case "star": - return calOpt(track.getDifficulty(), Float.parseFloat(value), opt); - default: - return false; - } - } - - private boolean calOpt(float val1, float val2, String opt) { - switch (opt) { - case "=": - return val1 == val2; - case "<": - return val1 < val2; - case ">": - return val1 > val2; - case "<=": - return val1 <= val2; - case ">=": - return val1 >= val2; - default: - return false; - } - } - - public void delete() { - - if (selected) { - deselect(); - } - freeBackground(); - visible = false; - deleted = true; - LibraryManager.getInstance().deleteMap(beatmap); - } - - public boolean isVisible() { - return visible && (!deleted); - } - - public void stopScroll(final float y) { - listener.get().stopScroll(y); - } - - public void selectTrack(final MenuItemTrack track, boolean reloadBG) { - selTrack = track; - listener.get().selectTrack(track.getTrack(), reloadBG); - } - - public boolean isTrackSelected(final MenuItemTrack track) { - return selTrack == track; - } - - private void freeBackground() { - // scene.unregisterTouchArea(background); - if (background == null) { - return; - } - background.setVisible(false); - SongMenuPool.getInstance().putBackground(background); - background = null; - - } - - private synchronized void initBackground() { - if (background == null) { - background = SongMenuPool.getInstance().newBackground(); - } - background.setItem(this); - background.setTitle(titleStr); - background.setAuthor(creatorStr); - background.setVisible(true); - if (!background.hasParent()) { - layer.attachChild(background); - scene.registerTouchArea(background); - } - } - - private void freeTracks() { - - for (int i = 0; i < trackSprites.length; i++) { - trackSprites[i].setVisible(false); - scene.unregisterTouchArea(trackSprites[i]); - trackSprites[i].setVisible(false); - SongMenuPool.getInstance().putTrack(trackSprites[i]); - trackSprites[i] = null; - } - - } - - private void initTracks() { - if (trackId == -1){ - for (int i = 0; i < trackSprites.length; i++) { - trackSprites[i] = SongMenuPool.getInstance().newTrack(); - trackSprites[i].setItem(this); - trackSprites[i].setTrack(beatmap.getTrack(i), beatmap); - beatmap.getTrack(i).setBeatmap(beatmap); - if (!trackSprites[i].hasParent()) { - layer.attachChild(trackSprites[i]); - } - scene.registerTouchArea(trackSprites[i]); - trackSprites[i].setVisible(true); - } - } - else{ - trackSprites[0] = SongMenuPool.getInstance().newTrack(); - trackSprites[0].setItem(this); - trackSprites[0].setTrack(beatmap.getTrack(trackId), beatmap); - beatmap.getTrack(trackId).setBeatmap(beatmap); - if (!trackSprites[0].hasParent()) { - layer.attachChild(trackSprites[0]); - } - scene.registerTouchArea(trackSprites[0]); - trackSprites[0].setVisible(true); - } - } - - public boolean isFavorite() { - return favorite; - } - - public void setFavorite(final boolean favorite) { - this.favorite = favorite; - } - - public void showPropertiesMenu() { - listener.get().showPropertiesMenu(this); - } - - public void update(final float dt) { - if (deleted) { - return; - } - for (final MenuItemTrack tr : trackSprites) { - if (tr != null) { - tr.update(dt); - } - } - } - - public TrackInfo getFirstTrack(){ - return beatmap.getTrack(Math.max(trackId, 0)); - } - - public void removeFromScene() { - if (scene == null) { - return; - } - if (selected) { - deselect(); - } - freeBackground(); - visible = false; - scene = null; - } - - public int tryGetCorrespondingTrackId(String oldTrackFileName){ - if (trackId <= -1){ - int i = 0; - for (TrackInfo track : beatmap.getTracks()){ - if (track == null) continue; - if (track.getFilename().equals(oldTrackFileName)){ - return i; - } - i++; - } - } - else if (beatmap.getTrack(trackId).getFilename().equals(oldTrackFileName)){ - return trackId; - } - return -1; - } - - public MenuItemTrack getTrackSpritesById(int index){ - return trackSprites[index]; - } + private final MenuItemTrack[] trackSprites; + private final BeatmapInfo beatmap; + private final String trackDir; + private final int bgHeight; + private final String titleStr; + private final String creatorStr; + public float percentAppeared = 0; + MenuItemBackground background; + Scene scene; + boolean selected = false; + WeakReference listener; + private MenuItemTrack selTrack = null; + private boolean visible = true; + private boolean favorite; + private boolean deleted = false; + private Entity layer = null; + private int trackId = -1; + + public MenuItem(final MenuItemListener listener, final BeatmapInfo info) { + this.listener = new WeakReference<>(listener); + beatmap = info; + trackDir = ScoreLibrary.getTrackDir(beatmap.getPath()); + bgHeight = ResourceManager.getInstance() + .getTexture("menu-button-background").getHeight() + - Utils.toRes(25); +// titleStr = (beatmap.getArtistUnicode() == null ? beatmap.getArtist() : beatmap.getArtistUnicode()) + " - " +// + (beatmap.getTitleUnicode() == null ? beatmap.getTitle() : beatmap.getTitleUnicode()); + titleStr = beatmap.getArtist() + " - " + beatmap.getTitle(); + creatorStr = StringTable.format(R.string.menu_creator, + beatmap.getCreator()); + trackSprites = new MenuItemTrack[info.getCount()]; + + final BeatmapProperties props = PropertiesLibrary.getInstance() + .getProperties(info.getPath()); + favorite = props != null && props.isFavorite(); + + } + + public MenuItem(final MenuItemListener listener, final BeatmapInfo info, int id) { + this.listener = new WeakReference<>(listener); + beatmap = info; + trackDir = ScoreLibrary.getTrackDir(beatmap.getPath()); + bgHeight = ResourceManager.getInstance() + .getTexture("menu-button-background").getHeight() + - Utils.toRes(25); +// titleStr = (beatmap.getArtistUnicode() == null ? beatmap.getArtist() : beatmap.getArtistUnicode()) + " - " +// + (beatmap.getTitleUnicode() == null ? beatmap.getTitle() : beatmap.getTitleUnicode()); + titleStr = beatmap.getArtist() + " - " + beatmap.getTitle(); + creatorStr = StringTable.format(R.string.menu_creator, beatmap.getCreator()); + trackSprites = new MenuItemTrack[1]; + trackId = id; + final BeatmapProperties props = PropertiesLibrary.getInstance().getProperties(info.getPath()); + favorite = props != null && props.isFavorite(); + + } + + public BeatmapInfo getBeatmap() { + return beatmap; + } + + public void updateMarks() { + for (final MenuItemTrack tr : trackSprites) { + if (tr != null) { + tr.updateMark(); + } + } + } + + public void attachToScene(final Scene scene, final Entity layer) { + this.scene = scene; + this.layer = layer; + // initBackground(); + } + + public float getHeight() { + if (!visible) { + return 0; + } + if (selected) { + return bgHeight + percentAppeared * (bgHeight) + * (trackSprites.length - 1); + } + return bgHeight - Utils.toRes(5); + } + + public float getInitialHeight() { + if (!visible) { + return 0; + } + return bgHeight - Utils.toRes(5); + } + + public float getTotalHeight() { + return (bgHeight) * (trackSprites.length); + } + + public void setPos(final float x, final float y) { + if (background != null) { + background.setPosition(x, y); + if (y > Config.getRES_HEIGHT() || y < -background.getHeight()) { + freeBackground(); + } + } + if (!selected) { + if (visible && background == null + && y < Config.getRES_HEIGHT() && y > -bgHeight) { + initBackground(); + background.setPosition(x, y); + } + return; + } + float oy = 0; + for (final Sprite s : trackSprites) { + if (s == null) { + continue; + } + final float cy = y + oy + Config.getRES_HEIGHT() / 2f + + s.getHeight() / 2; + final float ox = x + + Utils.toRes(170 * (float) Math.abs(Math.cos(cy * Math.PI + / (Config.getRES_HEIGHT() * 2)))); + s.setPosition(ox - Utils.toRes(100), y + oy); + oy += (s.getHeight() - Utils.toRes(25)) * percentAppeared; + } + } + + public void select(boolean reloadMusic, boolean reloadBG) { + if (!listener.get().isSelectAllowed() || scene == null) { + return; + } + + freeBackground(); + selected = true; + listener.get().select(this); + initTracks(); + percentAppeared = 0; + final String musicFileName = beatmap.getMusic(); + if (reloadMusic) { + listener.get().playMusic(musicFileName, beatmap.getPreviewTime()); + } + + selectTrack(trackSprites[0], reloadBG); + trackSprites[0].setSelectedColor(); + } + + public void deselect() { + if (scene == null ) { + return; + } + + if (deleted) { + return; + } + initBackground(); + selected = false; + percentAppeared = 0; + deselectTrack(); + freeTracks(); + } + + public void deselectTrack() { + if (scene == null) { + return; + } + if (selTrack != null) { + selTrack.setDeselectColor(); + } + selTrack = null; + } + + public void applyFilter(final String filter, final boolean favs, Set limit) { + if ((favs && !isFavorite()) + || (limit != null && !limit.contains(trackDir))) { + //System.out.println(trackDir); + if (selected) { + deselect(); + } + freeBackground(); + visible = false; + return; + } + final StringBuilder builder = new StringBuilder(); + builder.append(beatmap.getTitle()); + builder.append(' '); + builder.append(beatmap.getArtist()); + builder.append(' '); + builder.append(beatmap.getCreator()); + builder.append(' '); + builder.append(beatmap.getTags()); + builder.append(' '); + builder.append(beatmap.getSource()); + builder.append(' '); + builder.append(beatmap.getTracks().get(0).getBeatmapSetID()); + for (TrackInfo track : beatmap.getTracks()) { + builder.append(' '); + builder.append(track.getMode()); + } + boolean canVisible = true; + final String lowerText = builder.toString().toLowerCase(); + final String[] lowerFilterTexts = filter.toLowerCase().split("[ ]"); + for (String filterText : lowerFilterTexts) { + Pattern pattern = Pattern.compile("(ar|od|cs|hp|star)(=|<|>|<=|>=)(\\d+)"); + Matcher matcher = pattern.matcher(filterText); + if (matcher.find()) { + String key = matcher.group(1); + String opt = matcher.group(2); + String value = matcher.group(3); + boolean vis = false; + if(trackId < 0){ + for (TrackInfo track : beatmap.getTracks()) { + if (key != null) { + vis |= visibleTrack(track, key, opt, value); + } + } + } + else{ + if (key != null) { + vis = visibleTrack(beatmap.getTrack(trackId), key, opt, value); + } + } + canVisible &= vis; + } else { + if (!lowerText.contains(filterText)) { + canVisible = false; + break; + } + } + } + + if (filter.equals("")) { + canVisible = true; + } + + if (canVisible) { + if (!visible) { + visible = true; + // initBackground(); + selected = false; + percentAppeared = 0; + } + return; + } + + if (selected) { + deselect(); + } + freeBackground(); + visible = false; + } + + private boolean visibleTrack(TrackInfo track, String key, String opt, String value) { + switch (key) { + case "ar": + return calOpt(track.getApproachRate(), Float.parseFloat(value), opt); + case "od": + return calOpt(track.getOverallDifficulty(), Float.parseFloat(value), opt); + case "cs": + return calOpt(track.getCircleSize(), Float.parseFloat(value), opt); + case "hp": + return calOpt(track.getHpDrain(), Float.parseFloat(value), opt); + case "star": + return calOpt(track.getDifficulty(), Float.parseFloat(value), opt); + default: + return false; + } + } + + private boolean calOpt(float val1, float val2, String opt) { + switch (opt) { + case "=": + return val1 == val2; + case "<": + return val1 < val2; + case ">": + return val1 > val2; + case "<=": + return val1 <= val2; + case ">=": + return val1 >= val2; + default: + return false; + } + } + + public void delete() { + + if (selected) { + deselect(); + } + freeBackground(); + visible = false; + deleted = true; + LibraryManager.getInstance().deleteMap(beatmap); + } + + public boolean isVisible() { + return visible && (!deleted); + } + + public void stopScroll(final float y) { + listener.get().stopScroll(y); + } + + public void selectTrack(final MenuItemTrack track, boolean reloadBG) { + selTrack = track; + listener.get().selectTrack(track.getTrack(), reloadBG); + } + + public boolean isTrackSelected(final MenuItemTrack track) { + return selTrack == track; + } + + private void freeBackground() { + // scene.unregisterTouchArea(background); + if (background == null) { + return; + } + background.setVisible(false); + SongMenuPool.getInstance().putBackground(background); + background = null; + + } + + private synchronized void initBackground() { + if (background == null) { + background = SongMenuPool.getInstance().newBackground(); + } + background.setItem(this); + background.setTitle(titleStr); + background.setAuthor(creatorStr); + background.setVisible(true); + if (!background.hasParent()) { + layer.attachChild(background); + scene.registerTouchArea(background); + } + } + + private void freeTracks() { + + for (int i = 0; i < trackSprites.length; i++) { + trackSprites[i].setVisible(false); + scene.unregisterTouchArea(trackSprites[i]); + trackSprites[i].setVisible(false); + SongMenuPool.getInstance().putTrack(trackSprites[i]); + trackSprites[i] = null; + } + + } + + private void initTracks() { + if (trackId == -1){ + for (int i = 0; i < trackSprites.length; i++) { + trackSprites[i] = SongMenuPool.getInstance().newTrack(); + trackSprites[i].setItem(this); + trackSprites[i].setTrack(beatmap.getTrack(i), beatmap); + beatmap.getTrack(i).setBeatmap(beatmap); + if (!trackSprites[i].hasParent()) { + layer.attachChild(trackSprites[i]); + } + scene.registerTouchArea(trackSprites[i]); + trackSprites[i].setVisible(true); + } + } + else{ + trackSprites[0] = SongMenuPool.getInstance().newTrack(); + trackSprites[0].setItem(this); + trackSprites[0].setTrack(beatmap.getTrack(trackId), beatmap); + beatmap.getTrack(trackId).setBeatmap(beatmap); + if (!trackSprites[0].hasParent()) { + layer.attachChild(trackSprites[0]); + } + scene.registerTouchArea(trackSprites[0]); + trackSprites[0].setVisible(true); + } + } + + public boolean isFavorite() { + return favorite; + } + + public void setFavorite(final boolean favorite) { + this.favorite = favorite; + } + + public void showPropertiesMenu() { + listener.get().showPropertiesMenu(this); + } + + public void update(final float dt) { + if (deleted) { + return; + } + for (final MenuItemTrack tr : trackSprites) { + if (tr != null) { + tr.update(dt); + } + } + } + + public TrackInfo getFirstTrack(){ + return beatmap.getTrack(Math.max(trackId, 0)); + } + + public void removeFromScene() { + if (scene == null) { + return; + } + if (selected) { + deselect(); + } + freeBackground(); + visible = false; + scene = null; + } + + public int tryGetCorrespondingTrackId(String oldTrackFileName){ + if (trackId <= -1){ + int i = 0; + for (TrackInfo track : beatmap.getTracks()){ + if (track == null) continue; + if (track.getFilename().equals(oldTrackFileName)){ + return i; + } + i++; + } + } + else if (beatmap.getTrack(trackId).getFilename().equals(oldTrackFileName)){ + return trackId; + } + return -1; + } + + public MenuItemTrack getTrackSpritesById(int index){ + return trackSprites[index]; + } } diff --git a/src/ru/nsu/ccfit/zuev/osu/menu/MenuItemBackground.java b/src/ru/nsu/ccfit/zuev/osu/menu/MenuItemBackground.java index dddc0881..c227e575 100644 --- a/src/ru/nsu/ccfit/zuev/osu/menu/MenuItemBackground.java +++ b/src/ru/nsu/ccfit/zuev/osu/menu/MenuItemBackground.java @@ -12,80 +12,80 @@ public class MenuItemBackground extends Sprite { - private static final RGBColor DEFAULT_COLOR = new RGBColor(240 / 255f, 150 / 255f, 0 / 255f); - private static final RGBColor ON_TOUCH_COLOR = new RGBColor(1, 1, 1); - private final ChangeableText title, author; - private final RGBColor defColor = SkinJson.get().getColor("MenuItemDefaultColor", DEFAULT_COLOR); - private final RGBColor onTouchColor = SkinJson.get().getColor("MenuItemOnTouchColor", ON_TOUCH_COLOR); - private boolean moved = false; - private float dx = 0, dy = 0; - private MenuItem item; + private static final RGBColor DEFAULT_COLOR = new RGBColor(240 / 255f, 150 / 255f, 0 / 255f); + private static final RGBColor ON_TOUCH_COLOR = new RGBColor(1, 1, 1); + private final ChangeableText title, author; + private final RGBColor defColor = SkinJson.get().getColor("MenuItemDefaultColor", DEFAULT_COLOR); + private final RGBColor onTouchColor = SkinJson.get().getColor("MenuItemOnTouchColor", ON_TOUCH_COLOR); + private boolean moved = false; + private float dx = 0, dy = 0; + private MenuItem item; - public MenuItemBackground() { - super(0, 0, ResourceManager.getInstance().getTexture( - "menu-button-background")); + public MenuItemBackground() { + super(0, 0, ResourceManager.getInstance().getTexture( + "menu-button-background")); - setAlpha(0.8f); - title = new ChangeableText(Utils.toRes(32), Utils.toRes(25), - ResourceManager.getInstance().getFont("font"), "", 255); - author = new ChangeableText(0, 0, ResourceManager.getInstance() - .getFont("font"), "", 100); - author.setPosition(Utils.toRes(150), Utils.toRes(60)); + setAlpha(0.8f); + title = new ChangeableText(Utils.toRes(32), Utils.toRes(25), + ResourceManager.getInstance().getFont("font"), "", 255); + author = new ChangeableText(0, 0, ResourceManager.getInstance() + .getFont("font"), "", 100); + author.setPosition(Utils.toRes(150), Utils.toRes(60)); - defColor.apply(this); - attachChild(title); - attachChild(author); - } + defColor.apply(this); + attachChild(title); + attachChild(author); + } - @Override - public void reset() { - defColor.apply(this); - } + @Override + public void reset() { + defColor.apply(this); + } - public void setItem(final MenuItem it) { - item = it; - } + public void setItem(final MenuItem it) { + item = it; + } - public void setTitle(final String newTitle) { - title.setText(newTitle); - } + public void setTitle(final String newTitle) { + title.setText(newTitle); + } - public void setAuthor(final String newAuthor) { - author.setText(newAuthor); - } + public void setAuthor(final String newAuthor) { + author.setText(newAuthor); + } - @Override - public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, - final float pTouchAreaLocalX, final float pTouchAreaLocalY) { - if (!isVisible()) { - return false; - } - if (pSceneTouchEvent.isActionDown()) { - moved = false; - onTouchColor.apply(this); - if (item != null) { - item.stopScroll(getY() + pTouchAreaLocalY); - } - dx = pTouchAreaLocalX; - dy = pTouchAreaLocalY; - return true; - } else if (pSceneTouchEvent.isActionUp() && !moved) { - ResourceManager.getInstance().getSound("menuclick").play(); - defColor.apply(this); - if (item != null) { - item.select(true, true); - } - return true; - } else if (pSceneTouchEvent.isActionOutside() - || pSceneTouchEvent.isActionMove() - && (MathUtils.distance(dx, dy, pTouchAreaLocalX, - pTouchAreaLocalY) > 50)) { - defColor.apply(this); - moved = true; - return false; - } - return false; - } + @Override + public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, + final float pTouchAreaLocalX, final float pTouchAreaLocalY) { + if (!isVisible()) { + return false; + } + if (pSceneTouchEvent.isActionDown()) { + moved = false; + onTouchColor.apply(this); + if (item != null) { + item.stopScroll(getY() + pTouchAreaLocalY); + } + dx = pTouchAreaLocalX; + dy = pTouchAreaLocalY; + return true; + } else if (pSceneTouchEvent.isActionUp() && !moved) { + ResourceManager.getInstance().getSound("menuclick").play(); + defColor.apply(this); + if (item != null) { + item.select(true, true); + } + return true; + } else if (pSceneTouchEvent.isActionOutside() + || pSceneTouchEvent.isActionMove() + && (MathUtils.distance(dx, dy, pTouchAreaLocalX, + pTouchAreaLocalY) > 50)) { + defColor.apply(this); + moved = true; + return false; + } + return false; + } } diff --git a/src/ru/nsu/ccfit/zuev/osu/menu/MenuItemListener.java b/src/ru/nsu/ccfit/zuev/osu/menu/MenuItemListener.java index 03831ce6..3b07fe79 100644 --- a/src/ru/nsu/ccfit/zuev/osu/menu/MenuItemListener.java +++ b/src/ru/nsu/ccfit/zuev/osu/menu/MenuItemListener.java @@ -3,19 +3,19 @@ import ru.nsu.ccfit.zuev.osu.TrackInfo; public interface MenuItemListener { - void select(MenuItem item); + void select(MenuItem item); - void selectTrack(TrackInfo track, boolean reloadBG); + void selectTrack(TrackInfo track, boolean reloadBG); - void stopScroll(float y); + void stopScroll(float y); - void setY(float y); + void setY(float y); - void openScore(int id, boolean showOnline, final String playerName); + void openScore(int id, boolean showOnline, final String playerName); - void playMusic(final String filename, final int previewTime); + void playMusic(final String filename, final int previewTime); - boolean isSelectAllowed(); + boolean isSelectAllowed(); - void showPropertiesMenu(MenuItem item); + void showPropertiesMenu(MenuItem item); } diff --git a/src/ru/nsu/ccfit/zuev/osu/menu/MenuItemTrack.java b/src/ru/nsu/ccfit/zuev/osu/menu/MenuItemTrack.java index 219341ad..5869405a 100644 --- a/src/ru/nsu/ccfit/zuev/osu/menu/MenuItemTrack.java +++ b/src/ru/nsu/ccfit/zuev/osu/menu/MenuItemTrack.java @@ -19,172 +19,172 @@ public class MenuItemTrack extends Sprite { - private static final RGBColor DEFAULT_COLOR = new RGBColor(25 / 255f, 25 / 255f, 240 / 255f); - private static final RGBColor SELECTED_COLOR = new RGBColor(1, 1, 1); - - private static final RGBColor DEFAULT_TEXT_COLOR = new RGBColor(1, 1, 1); - private static final RGBColor SELECTED_TEXT_COLOR = new RGBColor(0, 0, 0); - private final ChangeableText trackTitle, trackLeftText; - private final Sprite[] stars; - private final Sprite halfStar; - private boolean moved = false; - private float dx = 0, dy = 0; - private WeakReference item; - private TrackInfo track; - private String currentMark = null; - private Sprite mark; - private float downTime = -1; - - public MenuItemTrack() { - super(0, 0, ResourceManager.getInstance().getTexture( - "menu-button-background")); - - trackTitle = new ChangeableText(Utils.toRes(32), Utils.toRes(22), - ResourceManager.getInstance().getFont("font"), "", 200); - trackLeftText = new ChangeableText(Utils.toRes(350), Utils.toRes(22), - ResourceManager.getInstance().getFont("font"), "", 30); - SkinJson.get().getColor("MenuItemVersionsDefaultColor", DEFAULT_COLOR).apply(this); - SkinJson.get().getColor("MenuItemDefaultTextColor", DEFAULT_TEXT_COLOR).applyAll(trackTitle, trackLeftText); - setAlpha(0.8f); - attachChild(trackTitle); -// attachChild(trackLeftText); - - stars = new Sprite[10]; - for (int i = 0; i < 10; i++) { - stars[i] = new Sprite(Utils.toRes(60 + 52 * i), Utils.toRes(50), - ResourceManager.getInstance().getTexture("star")); - attachChild(stars[i]); - } - final TextureRegion starTex = ResourceManager.getInstance() - .getTexture("star").deepCopy(); -// starTex.setWidth((starTex.getWidth() / 2)); - halfStar = new Sprite(0, 0, starTex); - attachChild(halfStar); - } - - public void setItem(final MenuItem it) { - item = new WeakReference<>(it); - } - - public void setTrack(final TrackInfo track, final BeatmapInfo info) { - this.track = track; - trackTitle.setText(track.getMode() + " (" + track.getCreator() + ")"); - trackLeftText.setText("\n" + info.getTitle()); - - for (final Sprite s : stars) { - s.setVisible(false); - } - halfStar.setVisible(false); - - final float diff = Math.min(track.getDifficulty(), 10); - int fInt = (int) (diff); - BigDecimal b1 = new BigDecimal(Float.toString(diff)); - BigDecimal b2 = new BigDecimal(Integer.toString(fInt)); - float fPoint = b1.subtract(b2).floatValue(); - - for (int j = 0; j < fInt; j++) { - if (j < stars.length) { - stars[j].setVisible(true); - } - } - - if (fPoint > 0 && fInt != 10) { - halfStar.setVisible(true); - halfStar.setPosition(Utils.toRes(60 + 52 * fInt), - Utils.toRes(50)); - halfStar.setScale(fPoint); - } - updateMark(); - } - - public void updateMark() { - if (track == null) { - return; - } - final String newmark = ScoreLibrary.getInstance().getBestMark( - track.getFilename()); - if (currentMark != null && currentMark.equals(newmark)) { - return; - } - - if (mark != null) { - mark.detachSelf(); - } - if (newmark != null) { - mark = new Sprite(Utils.toRes(25), Utils.toRes(55), ResourceManager - .getInstance().getTexture("ranking-" + newmark + "-small")); - attachChild(mark); - } else { - mark = null; - } - currentMark = newmark; - } - - public TrackInfo getTrack() { - return track; - } - - public void setDeselectColor() { - SkinJson.get().getColor("MenuItemVersionsDefaultColor", DEFAULT_COLOR).apply(this); - SkinJson.get().getColor("MenuItemDefaultTextColor", DEFAULT_TEXT_COLOR).applyAll(trackTitle, trackLeftText); - } - - public void setSelectedColor() { - SkinJson.get().getColor("MenuItemVersionsSelectedColor", SELECTED_COLOR).apply(this); - SkinJson.get().getColor("MenuItemSelectedTextColor", SELECTED_TEXT_COLOR).applyAll(trackTitle, trackLeftText); - } - - @Override - public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, - final float pTouchAreaLocalX, final float pTouchAreaLocalY) { - if (pSceneTouchEvent.isActionDown()) { - downTime = 0; - moved = false; - setSelectedColor(); - dx = pTouchAreaLocalX; - dy = pTouchAreaLocalY; - if (item != null) { - item.get().stopScroll(getY() + pTouchAreaLocalY); - } - return true; - } else if (pSceneTouchEvent.isActionUp() && !moved) { - downTime = -1; - if (item == null) { - return true; - } - if (!item.get().isTrackSelected(this)) { - ResourceManager.getInstance().getSound("menuclick").play(); - item.get().deselectTrack(); - } - item.get().selectTrack(this, false); - - return true; - } else if (pSceneTouchEvent.isActionOutside() - || pSceneTouchEvent.isActionMove() - && (MathUtils.distance(dx, dy, pTouchAreaLocalX, - pTouchAreaLocalY) > 50)) { - downTime = -1; - setDeselectColor(); - moved = true; - return false; - } else { - return !pSceneTouchEvent.isActionUp(); - } - } - - void update(final float dt) { - if (downTime >= 0) { - downTime += dt; - } - if (downTime > 0.5) { - setSelectedColor(); - moved = true; - if (item != null) { - item.get().showPropertiesMenu(); - } - downTime = -1; - } - } + private static final RGBColor DEFAULT_COLOR = new RGBColor(25 / 255f, 25 / 255f, 240 / 255f); + private static final RGBColor SELECTED_COLOR = new RGBColor(1, 1, 1); + + private static final RGBColor DEFAULT_TEXT_COLOR = new RGBColor(1, 1, 1); + private static final RGBColor SELECTED_TEXT_COLOR = new RGBColor(0, 0, 0); + private final ChangeableText trackTitle, trackLeftText; + private final Sprite[] stars; + private final Sprite halfStar; + private boolean moved = false; + private float dx = 0, dy = 0; + private WeakReference item; + private TrackInfo track; + private String currentMark = null; + private Sprite mark; + private float downTime = -1; + + public MenuItemTrack() { + super(0, 0, ResourceManager.getInstance().getTexture( + "menu-button-background")); + + trackTitle = new ChangeableText(Utils.toRes(32), Utils.toRes(22), + ResourceManager.getInstance().getFont("font"), "", 200); + trackLeftText = new ChangeableText(Utils.toRes(350), Utils.toRes(22), + ResourceManager.getInstance().getFont("font"), "", 30); + SkinJson.get().getColor("MenuItemVersionsDefaultColor", DEFAULT_COLOR).apply(this); + SkinJson.get().getColor("MenuItemDefaultTextColor", DEFAULT_TEXT_COLOR).applyAll(trackTitle, trackLeftText); + setAlpha(0.8f); + attachChild(trackTitle); +// attachChild(trackLeftText); + + stars = new Sprite[10]; + for (int i = 0; i < 10; i++) { + stars[i] = new Sprite(Utils.toRes(60 + 52 * i), Utils.toRes(50), + ResourceManager.getInstance().getTexture("star")); + attachChild(stars[i]); + } + final TextureRegion starTex = ResourceManager.getInstance() + .getTexture("star").deepCopy(); +// starTex.setWidth((starTex.getWidth() / 2)); + halfStar = new Sprite(0, 0, starTex); + attachChild(halfStar); + } + + public void setItem(final MenuItem it) { + item = new WeakReference<>(it); + } + + public void setTrack(final TrackInfo track, final BeatmapInfo info) { + this.track = track; + trackTitle.setText(track.getMode() + " (" + track.getCreator() + ")"); + trackLeftText.setText("\n" + info.getTitle()); + + for (final Sprite s : stars) { + s.setVisible(false); + } + halfStar.setVisible(false); + + final float diff = Math.min(track.getDifficulty(), 10); + int fInt = (int) (diff); + BigDecimal b1 = new BigDecimal(Float.toString(diff)); + BigDecimal b2 = new BigDecimal(Integer.toString(fInt)); + float fPoint = b1.subtract(b2).floatValue(); + + for (int j = 0; j < fInt; j++) { + if (j < stars.length) { + stars[j].setVisible(true); + } + } + + if (fPoint > 0 && fInt != 10) { + halfStar.setVisible(true); + halfStar.setPosition(Utils.toRes(60 + 52 * fInt), + Utils.toRes(50)); + halfStar.setScale(fPoint); + } + updateMark(); + } + + public void updateMark() { + if (track == null) { + return; + } + final String newmark = ScoreLibrary.getInstance().getBestMark( + track.getFilename()); + if (currentMark != null && currentMark.equals(newmark)) { + return; + } + + if (mark != null) { + mark.detachSelf(); + } + if (newmark != null) { + mark = new Sprite(Utils.toRes(25), Utils.toRes(55), ResourceManager + .getInstance().getTexture("ranking-" + newmark + "-small")); + attachChild(mark); + } else { + mark = null; + } + currentMark = newmark; + } + + public TrackInfo getTrack() { + return track; + } + + public void setDeselectColor() { + SkinJson.get().getColor("MenuItemVersionsDefaultColor", DEFAULT_COLOR).apply(this); + SkinJson.get().getColor("MenuItemDefaultTextColor", DEFAULT_TEXT_COLOR).applyAll(trackTitle, trackLeftText); + } + + public void setSelectedColor() { + SkinJson.get().getColor("MenuItemVersionsSelectedColor", SELECTED_COLOR).apply(this); + SkinJson.get().getColor("MenuItemSelectedTextColor", SELECTED_TEXT_COLOR).applyAll(trackTitle, trackLeftText); + } + + @Override + public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, + final float pTouchAreaLocalX, final float pTouchAreaLocalY) { + if (pSceneTouchEvent.isActionDown()) { + downTime = 0; + moved = false; + setSelectedColor(); + dx = pTouchAreaLocalX; + dy = pTouchAreaLocalY; + if (item != null) { + item.get().stopScroll(getY() + pTouchAreaLocalY); + } + return true; + } else if (pSceneTouchEvent.isActionUp() && !moved) { + downTime = -1; + if (item == null) { + return true; + } + if (!item.get().isTrackSelected(this)) { + ResourceManager.getInstance().getSound("menuclick").play(); + item.get().deselectTrack(); + } + item.get().selectTrack(this, false); + + return true; + } else if (pSceneTouchEvent.isActionOutside() + || pSceneTouchEvent.isActionMove() + && (MathUtils.distance(dx, dy, pTouchAreaLocalX, + pTouchAreaLocalY) > 50)) { + downTime = -1; + setDeselectColor(); + moved = true; + return false; + } else { + return !pSceneTouchEvent.isActionUp(); + } + } + + void update(final float dt) { + if (downTime >= 0) { + downTime += dt; + } + if (downTime > 0.5) { + setSelectedColor(); + moved = true; + if (item != null) { + item.get().showPropertiesMenu(); + } + downTime = -1; + } + } } diff --git a/src/ru/nsu/ccfit/zuev/osu/menu/ModMenu.java b/src/ru/nsu/ccfit/zuev/osu/menu/ModMenu.java index 2123fde4..1d038455 100644 --- a/src/ru/nsu/ccfit/zuev/osu/menu/ModMenu.java +++ b/src/ru/nsu/ccfit/zuev/osu/menu/ModMenu.java @@ -27,327 +27,327 @@ import ru.nsu.ccfit.zuev.osuplus.R; public class ModMenu implements IModSwitcher { - private static final ModMenu instance = new ModMenu(); - private Scene scene = null; - private SongMenu menu; - private EnumSet mod; - private ChangeableText multiplierText; - private TrackInfo selectedTrack; - private final Map modButtons = new TreeMap<>(); - private float changeSpeed = 1.0f; - private float forceAR = 9.0f; - private boolean enableForceAR = false; - private boolean enableNCWhenSpeedChange = false; - private boolean modsRemoved = false; - private float FLfollowDelay = 0.12f; - - private ModMenu() { - mod = EnumSet.noneOf(GameMod.class); - } - - public float getFLfollowDelay() { - return FLfollowDelay; - } - - public void setFLfollowDelay(float newfLfollowDelay) { - FLfollowDelay = newfLfollowDelay; - } - - public static ModMenu getInstance() { - return instance; - } - - public void setSongMenu(final SongMenu menu) { - this.menu = menu; - } - - public void reload() { - mod = EnumSet.noneOf(GameMod.class); - init(); - } - - public void show(SongMenu songMenu, TrackInfo selectedTrack) { - setSongMenu(songMenu); - setSelectedTrack(selectedTrack); - songMenu.scene.setChildScene(getScene(), - false, true, true); - InGameSettingMenu.getInstance().show(); - } - - public void hide() { - if (menu != null) { - menu.getScene().clearChildScene(); - menu = null; - } - InGameSettingMenu.getInstance().dismiss(); - } - - public void hideByFrag() { - if (menu != null) { - menu.getScene().clearChildScene(); - menu = null; - } - } - - private void addButton(int x, int y, String texture, GameMod mod) { - ModButton mButton; - - mButton = new ModButton(x, y, texture, mod); - mButton.setModEnabled(this.mod.contains(mod)); - mButton.setSwitcher(this); - scene.attachChild(mButton); - scene.registerTouchArea(mButton); - modButtons.put(mod, mButton); - } - - public void init() { - - modButtons.clear(); - scene = new Scene(); - scene.setBackgroundEnabled(false); - final Rectangle bg = new Rectangle(0, 0, Config.getRES_WIDTH(), - Config.getRES_HEIGHT()); - bg.setColor(0, 0, 0, 0.7f); - scene.attachChild(bg); - - multiplierText = new ChangeableText(0, Utils.toRes(50), - ResourceManager.getInstance().getFont("CaptionFont"), - StringTable.format(R.string.menu_mod_multiplier, 1f)); - multiplierText.setScale(1.2f); - scene.attachChild(multiplierText); - - changeMultiplierText(); - - final int offset = 100; - final int offsetGrowth = 130; - final TextureRegion button = ResourceManager.getInstance().getTexture("selection-mod-easy"); - - //line 1 - addButton(offset, Config.getRES_HEIGHT() / 2 - button.getHeight() * 3, "selection-mod-easy", GameMod.MOD_EASY); - addButton(offset + offsetGrowth, Config.getRES_HEIGHT() / 2 - button.getHeight() * 3, "selection-mod-nofail", GameMod.MOD_NOFAIL); - addButton(offset + offsetGrowth * 2, Config.getRES_HEIGHT() / 2 - button.getHeight() * 3, "selection-mod-halftime", GameMod.MOD_HALFTIME); - addButton(offset + offsetGrowth * 3, Config.getRES_HEIGHT() / 2 - button.getHeight() * 3, "selection-mod-reallyeasy", GameMod.MOD_REALLYEASY); - - //line 2 - addButton(offset, Config.getRES_HEIGHT() / 2 - button.getHeight() / 2, "selection-mod-hardrock", GameMod.MOD_HARDROCK); - addButton(offset + offsetGrowth, Config.getRES_HEIGHT() / 2 - button.getHeight() / 2, "selection-mod-doubletime", GameMod.MOD_DOUBLETIME); - addButton(offset + offsetGrowth * 2, Config.getRES_HEIGHT() / 2 - button.getHeight() / 2, "selection-mod-nightcore", GameMod.MOD_NIGHTCORE); - addButton(offset + offsetGrowth * 3, Config.getRES_HEIGHT() / 2 - button.getHeight() / 2, "selection-mod-hidden", GameMod.MOD_HIDDEN); - addButton(offset + offsetGrowth * 4, Config.getRES_HEIGHT() / 2 - button.getHeight() / 2, "selection-mod-flashlight", GameMod.MOD_FLASHLIGHT); - addButton(offset + offsetGrowth * 5, Config.getRES_HEIGHT() / 2 - button.getHeight() / 2, "selection-mod-suddendeath", GameMod.MOD_SUDDENDEATH); - addButton(offset + offsetGrowth * 6, Config.getRES_HEIGHT() / 2 - button.getHeight() / 2, "selection-mod-perfect", GameMod.MOD_PERFECT); - //addButton(offset + offsetGrowth * 6, Config.getRES_HEIGHT() / 2 - button.getHeight() / 2, "selection-mod-speedup", GameMod.MOD_SPEEDUP); - //line 3 - addButton(offset, Config.getRES_HEIGHT() / 2 + button.getHeight() * 2, "selection-mod-relax", GameMod.MOD_RELAX); - addButton(offset + offsetGrowth, Config.getRES_HEIGHT() / 2 + button.getHeight() * 2, "selection-mod-relax2", GameMod.MOD_AUTOPILOT); - addButton(offset + offsetGrowth * 2, Config.getRES_HEIGHT() / 2 + button.getHeight() * 2, "selection-mod-autoplay", GameMod.MOD_AUTO); - addButton(offset + offsetGrowth * 3, Config.getRES_HEIGHT() / 2 + button.getHeight() * 2, "selection-mod-scorev2", GameMod.MOD_SCOREV2); - addButton(offset + offsetGrowth * 4, Config.getRES_HEIGHT() / 2 + button.getHeight() * 2, "selection-mod-precise", GameMod.MOD_PRECISE); - addButton(offset + offsetGrowth * 5, Config.getRES_HEIGHT() / 2 + button.getHeight() * 2, "selection-mod-smallcircle", GameMod.MOD_SMALLCIRCLE); - - - final TextButton resetText = new TextButton(ResourceManager - .getInstance().getFont("CaptionFont"), - StringTable.get(R.string.menu_mod_reset)) { - - @Override - public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, - final float pTouchAreaLocalX, final float pTouchAreaLocalY) { - if (pSceneTouchEvent.isActionUp()) { - mod.clear(); - changeMultiplierText(); - for (ModButton btn : modButtons.values()) { - btn.setModEnabled(false); - } - return true; - } - return false; - } - }; - scene.attachChild(resetText); - scene.registerTouchArea(resetText); - resetText.setScale(1.2f); - - final TextButton back = new TextButton(ResourceManager - .getInstance().getFont("CaptionFont"), - StringTable.get(R.string.menu_mod_back)) { - - @Override - public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, - final float pTouchAreaLocalX, final float pTouchAreaLocalY) { - if (pSceneTouchEvent.isActionUp()) { - (new Thread() { - public void run() { - if (GlobalManager.getInstance().getSongMenu().getSelectedTrack() != null){ - DifficultyReCalculator rec = new DifficultyReCalculator(); - float newstar = rec.recalculateStar( - GlobalManager.getInstance().getSongMenu().getSelectedTrack(), - rec.getCS(GlobalManager.getInstance().getSongMenu().getSelectedTrack()), - getSpeed()); - if (newstar != 0f) { - GlobalManager.getInstance().getSongMenu().setStarsDisplay(newstar); - } - } - } - }).start(); - hide(); - return true; - } - return false; - } - }; - back.setScale(1.2f); - back.setWidth(resetText.getWidth()); - back.setHeight(resetText.getHeight()); - back.setPosition(Config.getRES_WIDTH() - back.getWidth() - 60, Config.getRES_HEIGHT() - back.getHeight() - 30); - back.setColor(66 / 255f, 76 / 255f, 80 / 255f); - resetText.setPosition(Config.getRES_WIDTH() - resetText.getWidth() - 60, back.getY() - resetText.getHeight() - 20); -// multiplierText.setPosition(back.getX() + (back.getWidth() / 2 - multiplierText.getWidth() / 2), resetText.getY() - multiplierText.getHeight() - 40); - - scene.attachChild(back); - scene.registerTouchArea(back); - - scene.setTouchAreaBindingEnabled(true); - } - - public Scene getScene() { - if (scene == null) { - init(); - } - return scene; - } - - public EnumSet getMod() { - return mod.clone(); - } - - public void setMod(EnumSet mod) { - this.mod = mod.clone(); - } - - private void changeMultiplierText() { - GlobalManager.getInstance().getSongMenu().changeDimensionInfo(selectedTrack); - //calculateAble = true; - float mult = 1; - for (GameMod m : mod) { - mult *= m.scoreMultiplier; - } - if (changeSpeed != 1.0f){ - mult *= StatisticV2.getSpeedChangeScoreMultiplier(getSpeed(), mod); - } - - multiplierText.setText(StringTable.format(R.string.menu_mod_multiplier, - mult)); - multiplierText.setPosition( - Config.getRES_WIDTH() / 2f - multiplierText.getWidth() / 2, - multiplierText.getY()); - if (mult == 1) { - multiplierText.setColor(1, 1, 1); - } else if (mult < 1) { - multiplierText.setColor(1, 150f / 255f, 0); - } else { - multiplierText.setColor(5 / 255f, 240 / 255f, 5 / 255f); - } - } - - public void handleModFlags(GameMod flag, GameMod modToCheck, GameMod[] modsToRemove) { - if (flag.equals(modToCheck)) { - for (GameMod modToRemove: modsToRemove) { - mod.remove(modToRemove); - modsRemoved = true; - } - } - } - - public boolean switchMod(GameMod flag) { - boolean returnValue = true; - - if (mod.contains(flag)) { - mod.remove(flag); - returnValue = false; - } else { - mod.add(flag); - - handleModFlags(flag, GameMod.MOD_HARDROCK, new GameMod[]{GameMod.MOD_EASY}); - handleModFlags(flag, GameMod.MOD_EASY, new GameMod[]{GameMod.MOD_HARDROCK}); - handleModFlags(flag, GameMod.MOD_AUTOPILOT, new GameMod[]{GameMod.MOD_RELAX, GameMod.MOD_PERFECT, GameMod.MOD_SUDDENDEATH, GameMod.MOD_AUTO, GameMod.MOD_NOFAIL}); - handleModFlags(flag, GameMod.MOD_AUTO, new GameMod[]{GameMod.MOD_RELAX, GameMod.MOD_AUTOPILOT, GameMod.MOD_PERFECT, GameMod.MOD_SUDDENDEATH}); - handleModFlags(flag, GameMod.MOD_RELAX, new GameMod[]{GameMod.MOD_AUTO, GameMod.MOD_PERFECT, GameMod.MOD_SUDDENDEATH, GameMod.MOD_NOFAIL, GameMod.MOD_AUTOPILOT}); - handleModFlags(flag, GameMod.MOD_DOUBLETIME, new GameMod[]{GameMod.MOD_NIGHTCORE, GameMod.MOD_HALFTIME}); - handleModFlags(flag, GameMod.MOD_NIGHTCORE, new GameMod[]{GameMod.MOD_DOUBLETIME, GameMod.MOD_HALFTIME}); - handleModFlags(flag, GameMod.MOD_HALFTIME, new GameMod[]{GameMod.MOD_DOUBLETIME, GameMod.MOD_NIGHTCORE}); - handleModFlags(flag, GameMod.MOD_SUDDENDEATH, new GameMod[]{GameMod.MOD_NOFAIL, GameMod.MOD_PERFECT, GameMod.MOD_AUTOPILOT, GameMod.MOD_RELAX, GameMod.MOD_AUTO}); - handleModFlags(flag, GameMod.MOD_PERFECT, new GameMod[]{GameMod.MOD_NOFAIL, GameMod.MOD_SUDDENDEATH, GameMod.MOD_AUTOPILOT, GameMod.MOD_RELAX, GameMod.MOD_AUTO}); - handleModFlags(flag, GameMod.MOD_NOFAIL, new GameMod[]{GameMod.MOD_PERFECT, GameMod.MOD_SUDDENDEATH, GameMod.MOD_AUTOPILOT, GameMod.MOD_RELAX}); - - if (modsRemoved) { - for (GameMod gameMod : modButtons.keySet()) { - modButtons.get(gameMod).setModEnabled(mod.contains(gameMod)); - } - } - } - - changeMultiplierText(); - - return returnValue; - } - - public void setSelectedTrack(TrackInfo selectedTrack) { - this.selectedTrack = selectedTrack; - if (selectedTrack != null) { - changeMultiplierText(); - } - } - - public float getSpeed(){ - float speed = changeSpeed; - if (mod.contains(GameMod.MOD_DOUBLETIME) || mod.contains(GameMod.MOD_NIGHTCORE)){ - speed *= 1.5f; - } else if (mod.contains(GameMod.MOD_HALFTIME)){ - speed *= 0.75f; - } - - return speed; - } - - public boolean isChangeSpeed() { - return changeSpeed != 1.0; - } - - public float getChangeSpeed(){ - return changeSpeed; - } - - public void setChangeSpeed(float speed){ - changeSpeed = speed; - } - - public float getForceAR(){ - return forceAR; - } - - public void setForceAR(float ar){ - forceAR = ar; - } - - public boolean isEnableForceAR(){ - return enableForceAR; - } - - public void setEnableForceAR(boolean t){ - enableForceAR = t; - } - - public boolean isEnableNCWhenSpeedChange(){ - return enableNCWhenSpeedChange; - } - - public void setEnableNCWhenSpeedChange(boolean t){ - enableNCWhenSpeedChange = t; - } - - public void updateMultiplierText(){ - changeMultiplierText(); - } + private static final ModMenu instance = new ModMenu(); + private Scene scene = null; + private SongMenu menu; + private EnumSet mod; + private ChangeableText multiplierText; + private TrackInfo selectedTrack; + private final Map modButtons = new TreeMap<>(); + private float changeSpeed = 1.0f; + private float forceAR = 9.0f; + private boolean enableForceAR = false; + private boolean enableNCWhenSpeedChange = false; + private boolean modsRemoved = false; + private float FLfollowDelay = 0.12f; + + private ModMenu() { + mod = EnumSet.noneOf(GameMod.class); + } + + public float getFLfollowDelay() { + return FLfollowDelay; + } + + public void setFLfollowDelay(float newfLfollowDelay) { + FLfollowDelay = newfLfollowDelay; + } + + public static ModMenu getInstance() { + return instance; + } + + public void setSongMenu(final SongMenu menu) { + this.menu = menu; + } + + public void reload() { + mod = EnumSet.noneOf(GameMod.class); + init(); + } + + public void show(SongMenu songMenu, TrackInfo selectedTrack) { + setSongMenu(songMenu); + setSelectedTrack(selectedTrack); + songMenu.scene.setChildScene(getScene(), + false, true, true); + InGameSettingMenu.getInstance().show(); + } + + public void hide() { + if (menu != null) { + menu.getScene().clearChildScene(); + menu = null; + } + InGameSettingMenu.getInstance().dismiss(); + } + + public void hideByFrag() { + if (menu != null) { + menu.getScene().clearChildScene(); + menu = null; + } + } + + private void addButton(int x, int y, String texture, GameMod mod) { + ModButton mButton; + + mButton = new ModButton(x, y, texture, mod); + mButton.setModEnabled(this.mod.contains(mod)); + mButton.setSwitcher(this); + scene.attachChild(mButton); + scene.registerTouchArea(mButton); + modButtons.put(mod, mButton); + } + + public void init() { + + modButtons.clear(); + scene = new Scene(); + scene.setBackgroundEnabled(false); + final Rectangle bg = new Rectangle(0, 0, Config.getRES_WIDTH(), + Config.getRES_HEIGHT()); + bg.setColor(0, 0, 0, 0.7f); + scene.attachChild(bg); + + multiplierText = new ChangeableText(0, Utils.toRes(50), + ResourceManager.getInstance().getFont("CaptionFont"), + StringTable.format(R.string.menu_mod_multiplier, 1f)); + multiplierText.setScale(1.2f); + scene.attachChild(multiplierText); + + changeMultiplierText(); + + final int offset = 100; + final int offsetGrowth = 130; + final TextureRegion button = ResourceManager.getInstance().getTexture("selection-mod-easy"); + + //line 1 + addButton(offset, Config.getRES_HEIGHT() / 2 - button.getHeight() * 3, "selection-mod-easy", GameMod.MOD_EASY); + addButton(offset + offsetGrowth, Config.getRES_HEIGHT() / 2 - button.getHeight() * 3, "selection-mod-nofail", GameMod.MOD_NOFAIL); + addButton(offset + offsetGrowth * 2, Config.getRES_HEIGHT() / 2 - button.getHeight() * 3, "selection-mod-halftime", GameMod.MOD_HALFTIME); + addButton(offset + offsetGrowth * 3, Config.getRES_HEIGHT() / 2 - button.getHeight() * 3, "selection-mod-reallyeasy", GameMod.MOD_REALLYEASY); + + //line 2 + addButton(offset, Config.getRES_HEIGHT() / 2 - button.getHeight() / 2, "selection-mod-hardrock", GameMod.MOD_HARDROCK); + addButton(offset + offsetGrowth, Config.getRES_HEIGHT() / 2 - button.getHeight() / 2, "selection-mod-doubletime", GameMod.MOD_DOUBLETIME); + addButton(offset + offsetGrowth * 2, Config.getRES_HEIGHT() / 2 - button.getHeight() / 2, "selection-mod-nightcore", GameMod.MOD_NIGHTCORE); + addButton(offset + offsetGrowth * 3, Config.getRES_HEIGHT() / 2 - button.getHeight() / 2, "selection-mod-hidden", GameMod.MOD_HIDDEN); + addButton(offset + offsetGrowth * 4, Config.getRES_HEIGHT() / 2 - button.getHeight() / 2, "selection-mod-flashlight", GameMod.MOD_FLASHLIGHT); + addButton(offset + offsetGrowth * 5, Config.getRES_HEIGHT() / 2 - button.getHeight() / 2, "selection-mod-suddendeath", GameMod.MOD_SUDDENDEATH); + addButton(offset + offsetGrowth * 6, Config.getRES_HEIGHT() / 2 - button.getHeight() / 2, "selection-mod-perfect", GameMod.MOD_PERFECT); + //addButton(offset + offsetGrowth * 6, Config.getRES_HEIGHT() / 2 - button.getHeight() / 2, "selection-mod-speedup", GameMod.MOD_SPEEDUP); + //line 3 + addButton(offset, Config.getRES_HEIGHT() / 2 + button.getHeight() * 2, "selection-mod-relax", GameMod.MOD_RELAX); + addButton(offset + offsetGrowth, Config.getRES_HEIGHT() / 2 + button.getHeight() * 2, "selection-mod-relax2", GameMod.MOD_AUTOPILOT); + addButton(offset + offsetGrowth * 2, Config.getRES_HEIGHT() / 2 + button.getHeight() * 2, "selection-mod-autoplay", GameMod.MOD_AUTO); + addButton(offset + offsetGrowth * 3, Config.getRES_HEIGHT() / 2 + button.getHeight() * 2, "selection-mod-scorev2", GameMod.MOD_SCOREV2); + addButton(offset + offsetGrowth * 4, Config.getRES_HEIGHT() / 2 + button.getHeight() * 2, "selection-mod-precise", GameMod.MOD_PRECISE); + addButton(offset + offsetGrowth * 5, Config.getRES_HEIGHT() / 2 + button.getHeight() * 2, "selection-mod-smallcircle", GameMod.MOD_SMALLCIRCLE); + + + final TextButton resetText = new TextButton(ResourceManager + .getInstance().getFont("CaptionFont"), + StringTable.get(R.string.menu_mod_reset)) { + + @Override + public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, + final float pTouchAreaLocalX, final float pTouchAreaLocalY) { + if (pSceneTouchEvent.isActionUp()) { + mod.clear(); + changeMultiplierText(); + for (ModButton btn : modButtons.values()) { + btn.setModEnabled(false); + } + return true; + } + return false; + } + }; + scene.attachChild(resetText); + scene.registerTouchArea(resetText); + resetText.setScale(1.2f); + + final TextButton back = new TextButton(ResourceManager + .getInstance().getFont("CaptionFont"), + StringTable.get(R.string.menu_mod_back)) { + + @Override + public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, + final float pTouchAreaLocalX, final float pTouchAreaLocalY) { + if (pSceneTouchEvent.isActionUp()) { + (new Thread() { + public void run() { + if (GlobalManager.getInstance().getSongMenu().getSelectedTrack() != null){ + DifficultyReCalculator rec = new DifficultyReCalculator(); + float newstar = rec.recalculateStar( + GlobalManager.getInstance().getSongMenu().getSelectedTrack(), + rec.getCS(GlobalManager.getInstance().getSongMenu().getSelectedTrack()), + getSpeed()); + if (newstar != 0f) { + GlobalManager.getInstance().getSongMenu().setStarsDisplay(newstar); + } + } + } + }).start(); + hide(); + return true; + } + return false; + } + }; + back.setScale(1.2f); + back.setWidth(resetText.getWidth()); + back.setHeight(resetText.getHeight()); + back.setPosition(Config.getRES_WIDTH() - back.getWidth() - 60, Config.getRES_HEIGHT() - back.getHeight() - 30); + back.setColor(66 / 255f, 76 / 255f, 80 / 255f); + resetText.setPosition(Config.getRES_WIDTH() - resetText.getWidth() - 60, back.getY() - resetText.getHeight() - 20); +// multiplierText.setPosition(back.getX() + (back.getWidth() / 2 - multiplierText.getWidth() / 2), resetText.getY() - multiplierText.getHeight() - 40); + + scene.attachChild(back); + scene.registerTouchArea(back); + + scene.setTouchAreaBindingEnabled(true); + } + + public Scene getScene() { + if (scene == null) { + init(); + } + return scene; + } + + public EnumSet getMod() { + return mod.clone(); + } + + public void setMod(EnumSet mod) { + this.mod = mod.clone(); + } + + private void changeMultiplierText() { + GlobalManager.getInstance().getSongMenu().changeDimensionInfo(selectedTrack); + //calculateAble = true; + float mult = 1; + for (GameMod m : mod) { + mult *= m.scoreMultiplier; + } + if (changeSpeed != 1.0f){ + mult *= StatisticV2.getSpeedChangeScoreMultiplier(getSpeed(), mod); + } + + multiplierText.setText(StringTable.format(R.string.menu_mod_multiplier, + mult)); + multiplierText.setPosition( + Config.getRES_WIDTH() / 2f - multiplierText.getWidth() / 2, + multiplierText.getY()); + if (mult == 1) { + multiplierText.setColor(1, 1, 1); + } else if (mult < 1) { + multiplierText.setColor(1, 150f / 255f, 0); + } else { + multiplierText.setColor(5 / 255f, 240 / 255f, 5 / 255f); + } + } + + public void handleModFlags(GameMod flag, GameMod modToCheck, GameMod[] modsToRemove) { + if (flag.equals(modToCheck)) { + for (GameMod modToRemove: modsToRemove) { + mod.remove(modToRemove); + modsRemoved = true; + } + } + } + + public boolean switchMod(GameMod flag) { + boolean returnValue = true; + + if (mod.contains(flag)) { + mod.remove(flag); + returnValue = false; + } else { + mod.add(flag); + + handleModFlags(flag, GameMod.MOD_HARDROCK, new GameMod[]{GameMod.MOD_EASY}); + handleModFlags(flag, GameMod.MOD_EASY, new GameMod[]{GameMod.MOD_HARDROCK}); + handleModFlags(flag, GameMod.MOD_AUTOPILOT, new GameMod[]{GameMod.MOD_RELAX, GameMod.MOD_PERFECT, GameMod.MOD_SUDDENDEATH, GameMod.MOD_AUTO, GameMod.MOD_NOFAIL}); + handleModFlags(flag, GameMod.MOD_AUTO, new GameMod[]{GameMod.MOD_RELAX, GameMod.MOD_AUTOPILOT, GameMod.MOD_PERFECT, GameMod.MOD_SUDDENDEATH}); + handleModFlags(flag, GameMod.MOD_RELAX, new GameMod[]{GameMod.MOD_AUTO, GameMod.MOD_PERFECT, GameMod.MOD_SUDDENDEATH, GameMod.MOD_NOFAIL, GameMod.MOD_AUTOPILOT}); + handleModFlags(flag, GameMod.MOD_DOUBLETIME, new GameMod[]{GameMod.MOD_NIGHTCORE, GameMod.MOD_HALFTIME}); + handleModFlags(flag, GameMod.MOD_NIGHTCORE, new GameMod[]{GameMod.MOD_DOUBLETIME, GameMod.MOD_HALFTIME}); + handleModFlags(flag, GameMod.MOD_HALFTIME, new GameMod[]{GameMod.MOD_DOUBLETIME, GameMod.MOD_NIGHTCORE}); + handleModFlags(flag, GameMod.MOD_SUDDENDEATH, new GameMod[]{GameMod.MOD_NOFAIL, GameMod.MOD_PERFECT, GameMod.MOD_AUTOPILOT, GameMod.MOD_RELAX, GameMod.MOD_AUTO}); + handleModFlags(flag, GameMod.MOD_PERFECT, new GameMod[]{GameMod.MOD_NOFAIL, GameMod.MOD_SUDDENDEATH, GameMod.MOD_AUTOPILOT, GameMod.MOD_RELAX, GameMod.MOD_AUTO}); + handleModFlags(flag, GameMod.MOD_NOFAIL, new GameMod[]{GameMod.MOD_PERFECT, GameMod.MOD_SUDDENDEATH, GameMod.MOD_AUTOPILOT, GameMod.MOD_RELAX}); + + if (modsRemoved) { + for (GameMod gameMod : modButtons.keySet()) { + modButtons.get(gameMod).setModEnabled(mod.contains(gameMod)); + } + } + } + + changeMultiplierText(); + + return returnValue; + } + + public void setSelectedTrack(TrackInfo selectedTrack) { + this.selectedTrack = selectedTrack; + if (selectedTrack != null) { + changeMultiplierText(); + } + } + + public float getSpeed(){ + float speed = changeSpeed; + if (mod.contains(GameMod.MOD_DOUBLETIME) || mod.contains(GameMod.MOD_NIGHTCORE)){ + speed *= 1.5f; + } else if (mod.contains(GameMod.MOD_HALFTIME)){ + speed *= 0.75f; + } + + return speed; + } + + public boolean isChangeSpeed() { + return changeSpeed != 1.0; + } + + public float getChangeSpeed(){ + return changeSpeed; + } + + public void setChangeSpeed(float speed){ + changeSpeed = speed; + } + + public float getForceAR(){ + return forceAR; + } + + public void setForceAR(float ar){ + forceAR = ar; + } + + public boolean isEnableForceAR(){ + return enableForceAR; + } + + public void setEnableForceAR(boolean t){ + enableForceAR = t; + } + + public boolean isEnableNCWhenSpeedChange(){ + return enableNCWhenSpeedChange; + } + + public void setEnableNCWhenSpeedChange(boolean t){ + enableNCWhenSpeedChange = t; + } + + public void updateMultiplierText(){ + changeMultiplierText(); + } } diff --git a/src/ru/nsu/ccfit/zuev/osu/menu/PauseMenu.java b/src/ru/nsu/ccfit/zuev/osu/menu/PauseMenu.java index b6f5808d..45098a7c 100644 --- a/src/ru/nsu/ccfit/zuev/osu/menu/PauseMenu.java +++ b/src/ru/nsu/ccfit/zuev/osu/menu/PauseMenu.java @@ -25,119 +25,119 @@ import ru.nsu.ccfit.zuev.osuplus.R; public class PauseMenu implements IOnMenuItemClickListener { - static final int ITEM_CONTINUE = 0; - static final int ITEM_RETRY = 1; - static final int ITEM_BACK = 2; - private final MenuScene scene; - private final GameScene game; - private final boolean fail; - private boolean savedFailedReplay; + static final int ITEM_CONTINUE = 0; + static final int ITEM_RETRY = 1; + static final int ITEM_BACK = 2; + private final MenuScene scene; + private final GameScene game; + private final boolean fail; + private boolean savedFailedReplay; - public PauseMenu(final Engine engine, final GameScene game, - final boolean fail) { - this.game = game; - this.fail = fail; - savedFailedReplay = false; - final ChangeableText saveFailedReplay = new ChangeableText(Utils.toRes(4), Utils.toRes(2), - ResourceManager.getInstance().getFont("font"), StringTable.get(R.string.str_save_failed_replay)); - class PauseMenuScene extends MenuScene implements IOnSceneTouchListener{ - PauseMenuScene(final Camera pCamera){ - super(pCamera); - } - public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) { - float pTouchX = FMath.clamp(pSceneTouchEvent.getX(), 0, Config.getRES_WIDTH()); - float pTouchY = FMath.clamp(pSceneTouchEvent.getY(), 0, Config.getRES_HEIGHT()); - if (fail && pSceneTouchEvent.isActionUp() && pTouchX < Config.getRES_WIDTH() / 2 && pTouchY < 50 && savedFailedReplay == false && game.getReplaying() == false){ - //save replay - if (game.saveFailedReplay()){ - saveFailedReplay.setText(StringTable.get(R.string.message_save_replay_successful)); - savedFailedReplay = true; - } - } - return true; - } - } - scene = new PauseMenuScene(engine.getCamera()); + public PauseMenu(final Engine engine, final GameScene game, + final boolean fail) { + this.game = game; + this.fail = fail; + savedFailedReplay = false; + final ChangeableText saveFailedReplay = new ChangeableText(Utils.toRes(4), Utils.toRes(2), + ResourceManager.getInstance().getFont("font"), StringTable.get(R.string.str_save_failed_replay)); + class PauseMenuScene extends MenuScene implements IOnSceneTouchListener{ + PauseMenuScene(final Camera pCamera){ + super(pCamera); + } + public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) { + float pTouchX = FMath.clamp(pSceneTouchEvent.getX(), 0, Config.getRES_WIDTH()); + float pTouchY = FMath.clamp(pSceneTouchEvent.getY(), 0, Config.getRES_HEIGHT()); + if (fail && pSceneTouchEvent.isActionUp() && pTouchX < Config.getRES_WIDTH() / 2 && pTouchY < 50 && savedFailedReplay == false && game.getReplaying() == false){ + //save replay + if (game.saveFailedReplay()){ + saveFailedReplay.setText(StringTable.get(R.string.message_save_replay_successful)); + savedFailedReplay = true; + } + } + return true; + } + } + scene = new PauseMenuScene(engine.getCamera()); - final SpriteMenuItem itemContinue = new SpriteMenuItem(ITEM_CONTINUE, - ResourceManager.getInstance().getTexture("pause-continue")); - scene.addMenuItem(itemContinue); - final SpriteMenuItem itemRetry = new SpriteMenuItem(ITEM_RETRY, - ResourceManager.getInstance().getTexture("pause-retry")); - scene.addMenuItem(itemRetry); - final SpriteMenuItem itemBack = new SpriteMenuItem(ITEM_BACK, - ResourceManager.getInstance().getTexture("pause-back")); - scene.addMenuItem(itemBack); - scene.attachChild(saveFailedReplay); - scene.setBackgroundEnabled(false); - TextureRegion tex; - if (fail) { - itemContinue.setVisible(false); - tex = ResourceManager.getInstance().getTexture("fail-background"); - if (game.getReplaying()){ - saveFailedReplay.setVisible(false); - } - } else { - saveFailedReplay.setVisible(false); - tex = ResourceManager.getInstance().getTexture("pause-overlay"); - } + final SpriteMenuItem itemContinue = new SpriteMenuItem(ITEM_CONTINUE, + ResourceManager.getInstance().getTexture("pause-continue")); + scene.addMenuItem(itemContinue); + final SpriteMenuItem itemRetry = new SpriteMenuItem(ITEM_RETRY, + ResourceManager.getInstance().getTexture("pause-retry")); + scene.addMenuItem(itemRetry); + final SpriteMenuItem itemBack = new SpriteMenuItem(ITEM_BACK, + ResourceManager.getInstance().getTexture("pause-back")); + scene.addMenuItem(itemBack); + scene.attachChild(saveFailedReplay); + scene.setBackgroundEnabled(false); + TextureRegion tex; + if (fail) { + itemContinue.setVisible(false); + tex = ResourceManager.getInstance().getTexture("fail-background"); + if (game.getReplaying()){ + saveFailedReplay.setVisible(false); + } + } else { + saveFailedReplay.setVisible(false); + tex = ResourceManager.getInstance().getTexture("pause-overlay"); + } - if (tex != null) { -// scene.setBackgroundEnabled(true); - float height = tex.getHeight(); - height *= Config.getRES_WIDTH() / (float) (tex.getWidth()); - final Sprite bg = new Sprite(0, - (Config.getRES_HEIGHT() - height) / 2, - Config.getRES_WIDTH(), height, tex); - scene.attachChild(bg, 0); - } + if (tex != null) { +// scene.setBackgroundEnabled(true); + float height = tex.getHeight(); + height *= Config.getRES_WIDTH() / (float) (tex.getWidth()); + final Sprite bg = new Sprite(0, + (Config.getRES_HEIGHT() - height) / 2, + Config.getRES_WIDTH(), height, tex); + scene.attachChild(bg, 0); + } - scene.buildAnimations(); - scene.setOnMenuItemClickListener(this); - } + scene.buildAnimations(); + scene.setOnMenuItemClickListener(this); + } - public MenuScene getScene() { - return scene; - } + public MenuScene getScene() { + return scene; + } - public boolean onMenuItemClicked(final MenuScene pMenuScene, - final IMenuItem pMenuItem, final float pMenuItemLocalX, - final float pMenuItemLocalY) { + public boolean onMenuItemClicked(final MenuScene pMenuScene, + final IMenuItem pMenuItem, final float pMenuItemLocalX, + final float pMenuItemLocalY) { - if (pMenuItem.getAlpha() < 0.75f) { - return false; - } - BassSoundProvider playSnd; - switch (pMenuItem.getID()) { - case ITEM_CONTINUE: - if (fail) { - return false; - } - playSnd = ResourceManager.getInstance().getSound("menuback"); - if (playSnd != null) { - playSnd.play(); - } - game.resume(); - return true; - case ITEM_BACK: - GlobalManager.getInstance().getScoring().setReplayID(-1); - playSnd = ResourceManager.getInstance().getSound("menuback"); - if (playSnd != null) { - playSnd.play(); - } - game.resume(); - game.quit(); - return true; - case ITEM_RETRY: - ResourceManager.getInstance().getSound("failsound").stop(); - playSnd = ResourceManager.getInstance().getSound("menuhit"); - if (playSnd != null) { - playSnd.play(); - } - game.restartGame(); - return true; - } - return false; - } + if (pMenuItem.getAlpha() < 0.75f) { + return false; + } + BassSoundProvider playSnd; + switch (pMenuItem.getID()) { + case ITEM_CONTINUE: + if (fail) { + return false; + } + playSnd = ResourceManager.getInstance().getSound("menuback"); + if (playSnd != null) { + playSnd.play(); + } + game.resume(); + return true; + case ITEM_BACK: + GlobalManager.getInstance().getScoring().setReplayID(-1); + playSnd = ResourceManager.getInstance().getSound("menuback"); + if (playSnd != null) { + playSnd.play(); + } + game.resume(); + game.quit(); + return true; + case ITEM_RETRY: + ResourceManager.getInstance().getSound("failsound").stop(); + playSnd = ResourceManager.getInstance().getSound("menuhit"); + if (playSnd != null) { + playSnd.play(); + } + game.restartGame(); + return true; + } + return false; + } } diff --git a/src/ru/nsu/ccfit/zuev/osu/menu/ScoreBoard.java b/src/ru/nsu/ccfit/zuev/osu/menu/ScoreBoard.java index 68adc7d5..050f824f 100644 --- a/src/ru/nsu/ccfit/zuev/osu/menu/ScoreBoard.java +++ b/src/ru/nsu/ccfit/zuev/osu/menu/ScoreBoard.java @@ -40,660 +40,660 @@ import ru.nsu.ccfit.zuev.osuplus.R; public class ScoreBoard implements ScrollDetector.IScrollDetectorListener { - private final Scene scene; - private final Scene mainScene; - private final MenuItemListener listener; - private final ChangeableText loadingText; - private Sprite[] sprites = null; - private Avatar[] avatars = null; - private float percentShow = -1; - - private final Boolean trackMutex = false; - private long viewNumber = 0; - - private boolean showOnlineScores = false; - private TrackInfo lastTrack = null; - private boolean wasOnline = false; - private boolean isCanceled = false; - private boolean isScroll = false; - - private AsyncTask onlineTask; - private final LinkedList> avatarTasks; - private final Context context; - - private final SurfaceScrollDetector mScrollDetector; - - private float maxY = 100500; - private int pointerId = -1; - private float initalY = -1; - private Float touchY = null; - private float camY = -146; - private float velocityY; - private float secPassed = 0, tapTime; - private float height = 0; - - private float downTime = -1; - private int _scoreID = -1; - private boolean moved = false; - private ScoreBoardItems[] scoreItems = new ScoreBoardItems[0]; - - public ScoreBoard(final Scene scene, final Entity layer, final MenuItemListener listener, final Context context) { - this.scene = new Scene(); - this.mainScene = scene; - this.context = context; - this.scene.setBackgroundEnabled(false); - layer.attachChild(this.scene); - - loadingText = new ChangeableText(Utils.toRes(5), Utils.toRes(230), - ResourceManager.getInstance().getFont("strokeFont"), "", 50); - this.scene.attachChild(loadingText); - - this.listener = listener; - this.mScrollDetector = new SurfaceScrollDetector(this); - avatarTasks = new LinkedList<>(); - } - - public static String ConvertModString(String s) { - String[] strMod = s.split("\\|", 2); - StringBuilder result = new StringBuilder(); - - for (int i = 0; i < strMod[0].length(); i++) { - switch (strMod[0].charAt(i)) { - case 'a': - result.append("Auto,"); - break; - case 'x': - result.append("Relax,"); - break; - case 'p': - result.append("AP,"); - break; - case 'e': - result.append("EZ,"); - break; - case 'n': - result.append("NF,"); - break; - case 'r': - result.append("HR,"); - break; - case 'h': - result.append("HD,"); - break; - case 'i': - result.append("FL,"); - break; - case 'd': - result.append("DT,"); - break; - case 'c': - result.append("NC,"); - break; - case 't': - result.append("HT,"); - break; - case 's': - result.append("PR,"); - break; - case 'l': - result.append("REZ,"); - break; - case 'm': - result.append("SC,"); - break; - case 'u': - result.append("SD,"); - break; - case 'f': - result.append("PF,"); - break; - case 'b': - result.append("SU,"); - break; - case 'v': - result.append("ScoreV2,"); - break; - } - } - - if (strMod.length > 1){ - result.append(ConvertExtraModString(strMod[1])); - } - if (result.length() == 0) { - return "None"; - } - - return result.substring(0, result.length() - 1); - } - - private static String ConvertExtraModString(String s) { - StringBuilder stringBuilder = new StringBuilder(); - for (String str: s.split("\\|")){ - if (str.startsWith("x") && str.length() == 5){ - stringBuilder.append(str.substring(1)).append("x,"); - } else if (str.startsWith("AR")){ - stringBuilder.append(str).append(","); - } - } - return stringBuilder.toString(); - } - - public ScoreBoardItems[] getScoreBoardItems() { - return scoreItems; - } - - private String formatScore(int score) { - StringBuilder scoreBuilder = new StringBuilder(); - scoreBuilder.append(Math.abs(score)); - for (int i = scoreBuilder.length() - 3; i > 0; i -= 3) { - scoreBuilder.insert(i, ' '); - } - return scoreBuilder.toString(); - } - - private void initSprite(int i, String title, String acc, String markStr, final boolean showOnline, final int scoreID, String avaUrl, final String userName) { - final TextureRegion tex = ResourceManager.getInstance().getTexture( - "menu-button-background").deepCopy(); - tex.setHeight(107); - tex.setWidth(724); - camY = -146; - sprites[i] = new Sprite(Utils.toRes(-150), Utils.toRes(40), tex) { - private float dx = 0, dy = 0; - - @Override - public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, - final float pTouchAreaLocalX, - final float pTouchAreaLocalY) { - mScrollDetector.onTouchEvent(pSceneTouchEvent); - mScrollDetector.setEnabled(true); - if (pSceneTouchEvent.isActionDown()) { - moved = false; - setAlpha(0.8f); - listener.stopScroll(getY() + pTouchAreaLocalY); - dx = pTouchAreaLocalX; - dy = pTouchAreaLocalY; - downTime = 0; - _scoreID = scoreID; - return true; - } else if (pSceneTouchEvent.isActionUp() && !moved && !isScroll) { - downTime = -1; - setAlpha(0.5f); - listener.openScore(scoreID, showOnline, userName); - GlobalManager.getInstance().getScoring().setReplayID(scoreID); - return true; - } else if (pSceneTouchEvent.isActionOutside() - || pSceneTouchEvent.isActionMove() - && (MathUtils.distance(dx, dy, pTouchAreaLocalX, - pTouchAreaLocalY) > 50)) { - downTime = -1; - setAlpha(0.5f); - moved = true; - return false; - } else if (pSceneTouchEvent.isActionUp()) { - return false; - } - return false; - } - }; - - sprites[i].setColor(0, 0, 0); - sprites[i].setAlpha(0.5f); - sprites[i].setScale(0.65f); - sprites[i].setWidth(sprites[i].getWidth() * 1.1f); - int pos = 0; - if (showOnlineScores) { - pos = 90; - avatars[i] = new Avatar(userName, avaUrl); - } - final Text text = new Text(Utils.toRes(pos + 160), Utils.toRes(20), - ResourceManager.getInstance().getFont("font"), title); - final Text accText = new Text(Utils.toRes(670), Utils.toRes(12), - ResourceManager.getInstance().getFont("smallFont"), acc); - final Sprite mark = new Sprite(Utils.toRes(pos + 80), Utils.toRes(35), - ResourceManager.getInstance().getTexture( - "ranking-" + markStr + "-small")); - text.setScale(1.2f); - mark.setScale(1.5f); - mark.setPosition(pos + 60 + mark.getWidth() / 2, mark.getY()); - sprites[i].attachChild(text); - sprites[i].attachChild(accText); - sprites[i].attachChild(mark); - scene.attachChild(sprites[i]); - mainScene.registerTouchArea(sprites[i]); - height = sprites[i].getHeight(); - } - - private void initFromOnline(final TrackInfo track) { - final long currentNumber = viewNumber; - loadingText.setText("Loading scores..."); - onlineTask = new AsyncTaskLoader().execute(new OsuAsyncCallback() { - - - public void run() { - File trackFile = new File(track.getFilename()); - String hash = FileUtils.getMD5Checksum(trackFile); - ArrayList scores; - - try { - scores = OnlineManager.getInstance().getTop(trackFile, hash); - } catch (OnlineManager.OnlineManagerException e) { - Debug.e("Cannot load scores " + e.getMessage()); - synchronized (trackMutex) { - if (currentNumber == viewNumber) - loadingText.setText(OnlineManager.getInstance().getFailMessage()); - } - return; - } - - synchronized (trackMutex) { - if (currentNumber != viewNumber) - return; - - loadingText.setText(OnlineManager.getInstance().getFailMessage()); - sprites = new Sprite[scores.size() + 1]; - avatars = new Avatar[scores.size() + 1]; - long lastTotalScore = 0; - List scoreBoardItems = new ArrayList<>(); - for (int i = scores.size() - 1; i >= 0; i--) { - Debug.i(scores.get(i)); - String[] data = scores.get(i).split("\\s+"); - if (data.length < 8 || data.length == 10) - continue; - final int scoreID = Integer.parseInt(data[0]); - - String totalScore = formatScore(Integer.parseInt(data[2])); - long currTotalScore = Long.parseLong(data[2]); - String titleStr = "#" - + (i + 1) - + " " - + data[1] - + "\n" - + StringTable.format(R.string.menu_score, - totalScore, Integer.parseInt(data[3])); - long diffTotalScore = currTotalScore - lastTotalScore; - String accStr = ConvertModString(data[5]) + "\n" - + String.format(Locale.ENGLISH, "%.2f", GameHelper.Round(Integer.parseInt(data[6]) / 1000f, 2)) + "%" + "\n" - + (lastTotalScore == 0 ? "-" : ((diffTotalScore != 0 ? "+" : "") + diffTotalScore)); - lastTotalScore = currTotalScore; - initSprite(i, titleStr, accStr, data[4], true, scoreID, data[7], data[1]); - ScoreBoardItems item = new ScoreBoardItems(); - item.set(data[1], Integer.parseInt(data[3]), Integer.parseInt(data[2]), scoreID); - scoreBoardItems.add(item); - } - scoreItems = new ScoreBoardItems[scoreBoardItems.size()]; - for (int i = 0; i < scoreItems.length; i++) { - scoreItems[i] = scoreBoardItems.get(scoreBoardItems.size() - 1 - i); - } - if (scores.size() > 0) { - String[] data = scores.get(scores.size() - 1).split("\\s+"); - if (data.length == 10) { - final int scoreID = Integer.parseInt(data[0]); - String totalScore = formatScore(Integer.parseInt(data[2])); - String titleStr = "#" - + data[7] - + " of " - + data[8] - + "\n" - + StringTable.format(R.string.menu_score, - totalScore, Integer.parseInt(data[3])); - String accStr = ConvertModString(data[5]) + "\n" - + String.format(Locale.ENGLISH, "%.2f", GameHelper.Round(Integer.parseInt(data[6]) / 1000f, 2)) + "%" + "\n" - + "-"; - initSprite(scores.size(), titleStr, accStr, data[4], true, scoreID, data[9], data[1]); - } else { - sprites[scores.size()] = null; - } - } - - percentShow = 0; - } - } - - - public void onComplete() { - isCanceled = false; - if (Utils.isWifi(context) || Config.getLoadAvatar()) - loadAvatar(); - } - - }); - } - - public void init(final TrackInfo track) { - if (lastTrack == track && showOnlineScores == wasOnline && wasOnline) { - return; - } - - scoreItems = new ScoreBoardItems[0]; - lastTrack = track; - wasOnline = showOnlineScores; - - synchronized (trackMutex) { - viewNumber++; - } - - clear(); - if (track == null) { - return; - } - loadingText.setText(""); - if (OnlineManager.getInstance().isStayOnline() && showOnlineScores) { - initFromOnline(track); - return; - } - - String[] columns = {"id", "playername", "score", "combo", "mark", "accuracy", "mode"}; - Cursor scoresSet = ScoreLibrary.getInstance().getMapScores(columns, track.getFilename()); - if (scoresSet == null || scoresSet.getCount() == 0) { - if (scoresSet != null) { - scoresSet.close(); - } - - return; - } - percentShow = 0; - scoresSet.moveToFirst(); - sprites = new Sprite[scoresSet.getCount()]; - long lastTotalScore = 0; - scoreItems = new ScoreBoardItems[scoresSet.getCount()]; - for (int i = scoresSet.getCount() - 1; i >= 0; i--) { - scoresSet.moveToPosition(i); - final int scoreID = scoresSet.getInt(0); - - String totalScore = formatScore(scoresSet.getInt(scoresSet.getColumnIndexOrThrow("score"))); - long currTotalScore = scoresSet.getLong(scoresSet.getColumnIndexOrThrow("score")); - String titleStr = "#" - + (i + 1) - + " " - + scoresSet.getString(scoresSet.getColumnIndexOrThrow("playername")) - + "\n" - + StringTable.format(R.string.menu_score, - totalScore, scoresSet.getInt(scoresSet.getColumnIndexOrThrow("combo"))); - long diffTotalScore = currTotalScore - lastTotalScore; - @SuppressLint("DefaultLocale") String accStr = ConvertModString(scoresSet.getString(scoresSet.getColumnIndexOrThrow("mode"))) + "\n" - + String.format("%.2f", GameHelper.Round( scoresSet.getFloat(scoresSet.getColumnIndexOrThrow("accuracy")) * 100, 2)) + "%" + "\n" - + (lastTotalScore == 0 ? "-" : ((diffTotalScore != 0 ? "+" : "") + diffTotalScore)); - lastTotalScore = currTotalScore; - initSprite(i, titleStr, accStr, scoresSet.getString(scoresSet.getColumnIndexOrThrow("mark")), - false, scoreID, null, null); - scoreItems[i] = new ScoreBoardItems(); - scoreItems[i].set(scoresSet.getString(scoresSet.getColumnIndexOrThrow("playername")), - scoresSet.getInt(scoresSet.getColumnIndexOrThrow("combo")), - scoresSet.getInt(scoresSet.getColumnIndexOrThrow("score")), - scoreID); - } - scoresSet.close(); - } - - public void clear() { - if (sprites == null) { - return; - } - final Sprite[] sprs = sprites; - sprites = null; - SyncTaskManager.getInstance().run(() -> { - for (final Sprite sp : sprs) { - if (sp == null) continue; - mainScene.unregisterTouchArea(sp); - sp.detachSelf(); - } - }); - - } - - public void update(final float pSecondsElapsed) { - secPassed += pSecondsElapsed; - if (sprites == null || sprites.length <= 0) { - return; - } - if (percentShow == -1) { - float oy = -camY; - for (final Sprite item : sprites) { - if (item == null) - break; - item.setPosition(item.getX(), oy); - oy += (item.getHeight() - Utils.toRes(32)) - * 0.8f; - } - oy += camY; - camY += velocityY * pSecondsElapsed; - maxY = oy - (Config.getRES_HEIGHT() - 110 - (height - Utils.toRes(32)) - * 0.8f); - if (camY <= -146 && velocityY < 0 || camY >= maxY && velocityY > 0) { - camY -= velocityY * pSecondsElapsed; - velocityY = 0; - isScroll = false; - } - if (Math.abs(velocityY) > Utils.toRes(500) * pSecondsElapsed) { - velocityY -= Utils.toRes(10) * pSecondsElapsed - * Math.signum(velocityY); - } else { - velocityY = 0; - isScroll = false; - } - } else { - percentShow += pSecondsElapsed * 4; - if (percentShow > 1) { - percentShow = 1; - } - for (int i = 0; i < sprites.length; i++) { - if (sprites[i] != null) { -// if (i == 5 && showOnlineScores == true) { -// sprites[i].setPosition( -// Utils.toRes(-160), -// Utils.toRes(194) + percentShow * 5 -// * (sprites[5].getHeight() - Utils.toRes(32)) -// * 0.95f) ; -// continue; -// } - sprites[i].setPosition( - Utils.toRes(-160), - Utils.toRes(146) + percentShow * i - * (sprites[i].getHeight() - Utils.toRes(32)) - * 0.8f); - } - } - if (percentShow == 1) { - percentShow = -1; - } - } - if (downTime >= 0) { - downTime += pSecondsElapsed; - } - if (downTime > 0.5) { - moved = true; - if (_scoreID != -1 && !showOnlineScores) { - GlobalManager.getInstance().getSongMenu().showDeleteScoreMenu(_scoreID); - } - downTime = -1; - } - } - - public boolean isShowOnlineScores() { - return showOnlineScores; - } - - public void setShowOnlineScores(boolean showOnlineScores) { - synchronized (trackMutex) { - this.showOnlineScores = showOnlineScores; - } - } - - public void loadAvatar() { - - try { - if (avatars == null) { - return; - } - for (int i = 0; i < avatars.length; i++) { - if (isCanceled) { - isCanceled = false; - break; - } - if (sprites[i] == null) { - continue; - } - final int finalI = i; - AsyncTask avatarTask = new AsyncTaskLoader().execute(new OsuAsyncCallback() { - - private final TextureRegion[] avatarTexRegion = new TextureRegion[avatars.length]; - - public void run() { - - Avatar ava = avatars[finalI]; - boolean bool = OnlineManager.getInstance().loadAvatarToTextureManager(ava.getAvaUrl(), "ava@" + ava.getUserName()); - if (bool) { - avatarTexRegion[finalI] = ResourceManager.getInstance().getTextureIfLoaded("ava@" + ava.getUserName()); - } else { - avatarTexRegion[finalI] = ResourceManager.getInstance().getTexture("emptyavatar"); - } - } - - public void onComplete() { - try { - if (avatarTexRegion[finalI] != null && showOnlineScores) { - final Sprite avatar = new Sprite(55, 12, Utils.toRes(90), Utils.toRes(90), avatarTexRegion[finalI]); - sprites[finalI].attachChild(avatar); - } - } catch (Exception ignored) {} - - isCanceled = false; - } - }); - - avatarTasks.add(avatarTask); - } - isCanceled = false; - } catch (Exception ex) { -// Debug.e(ex.toString()); - isCanceled = false; - } - } - - public void cancleLoadOnlineScores() { - if (onlineTask != null && onlineTask.getStatus() != AsyncTask.Status.FINISHED) { - onlineTask.cancel(true); - } - } - - public void cancleLoadAvatar() { - if (avatarTasks != null) { - for (AsyncTask avatarTask : avatarTasks) { - if (avatarTask.getStatus() != AsyncTask.Status.FINISHED) { - isCanceled = true; - avatarTask.cancel(true); - /* if (OnlineManager.get != null) { - OnlineManager.get.abort(); - } */ - } - } - } - } - - @Override - public void onScroll(ScrollDetector scrollDetector, TouchEvent touchEvent, float distanceX, float distanceY) { - switch (touchEvent.getAction()) { - case (TouchEvent.ACTION_DOWN): - velocityY = 0; - touchY = touchEvent.getY(); - pointerId = touchEvent.getPointerID(); - tapTime = secPassed; - initalY = touchY; - isScroll = true; - break; - case (TouchEvent.ACTION_MOVE): - if (pointerId != -1 && pointerId != touchEvent.getPointerID()) { - break; - } - isScroll = true; - if (initalY == -1) { - velocityY = 0; - touchY = touchEvent.getY(); - initalY = touchY; - tapTime = secPassed; - pointerId = touchEvent.getPointerID(); - } - final float dy = touchEvent.getY() - touchY; - - camY -= dy; - touchY = touchEvent.getY(); - if (camY <= -146) { - camY = -146; - velocityY = 0; - } else if (camY >= maxY) { - camY = maxY; - velocityY = 0; - } - - // velocityY = -3f * dy; - break; - default: { - if (pointerId != -1 && pointerId != touchEvent.getPointerID()) { - break; - } - touchY = null; - if (secPassed - tapTime < 0.001f || initalY == -1) { - velocityY = 0; - isScroll = false; - } else { - velocityY = (initalY - touchEvent.getY()) - / (secPassed - tapTime); - isScroll = true; - } - pointerId = -1; - initalY = -1; - - } - break; - } - } - - public Scene getScene() { - return scene; - } - - public static class ScoreBoardItems { - public String userName; - public int playScore; - public int scoreId; - private int maxCombo; - - public void set(String name, int com, int scr, int id) { - userName = name; - maxCombo = com; - playScore = scr; - scoreId = id; - } - - public String get() { - return userName + "\n" + NumberFormat.getNumberInstance(Locale.US).format(playScore) + "\n" + NumberFormat.getNumberInstance(Locale.US).format(maxCombo) + "x"; - } - } - - static class Avatar { - private String userName; - private String avaUrl; - - public Avatar(String userName, String avaUrl) { - this.userName = userName; - this.avaUrl = "https://secure.gravatar.com/avatar/" + avaUrl + ".jpg?s=100"; - } - - public String getUserName() { - return userName; - } - - public void setUserName(String userName) { - this.userName = userName; - } - - public String getAvaUrl() { - return avaUrl; - } - - public void setAvaUrl(String avaUrl) { - this.avaUrl = avaUrl; - } - } + private final Scene scene; + private final Scene mainScene; + private final MenuItemListener listener; + private final ChangeableText loadingText; + private Sprite[] sprites = null; + private Avatar[] avatars = null; + private float percentShow = -1; + + private final Boolean trackMutex = false; + private long viewNumber = 0; + + private boolean showOnlineScores = false; + private TrackInfo lastTrack = null; + private boolean wasOnline = false; + private boolean isCanceled = false; + private boolean isScroll = false; + + private AsyncTask onlineTask; + private final LinkedList> avatarTasks; + private final Context context; + + private final SurfaceScrollDetector mScrollDetector; + + private float maxY = 100500; + private int pointerId = -1; + private float initalY = -1; + private Float touchY = null; + private float camY = -146; + private float velocityY; + private float secPassed = 0, tapTime; + private float height = 0; + + private float downTime = -1; + private int _scoreID = -1; + private boolean moved = false; + private ScoreBoardItems[] scoreItems = new ScoreBoardItems[0]; + + public ScoreBoard(final Scene scene, final Entity layer, final MenuItemListener listener, final Context context) { + this.scene = new Scene(); + this.mainScene = scene; + this.context = context; + this.scene.setBackgroundEnabled(false); + layer.attachChild(this.scene); + + loadingText = new ChangeableText(Utils.toRes(5), Utils.toRes(230), + ResourceManager.getInstance().getFont("strokeFont"), "", 50); + this.scene.attachChild(loadingText); + + this.listener = listener; + this.mScrollDetector = new SurfaceScrollDetector(this); + avatarTasks = new LinkedList<>(); + } + + public static String ConvertModString(String s) { + String[] strMod = s.split("\\|", 2); + StringBuilder result = new StringBuilder(); + + for (int i = 0; i < strMod[0].length(); i++) { + switch (strMod[0].charAt(i)) { + case 'a': + result.append("Auto,"); + break; + case 'x': + result.append("Relax,"); + break; + case 'p': + result.append("AP,"); + break; + case 'e': + result.append("EZ,"); + break; + case 'n': + result.append("NF,"); + break; + case 'r': + result.append("HR,"); + break; + case 'h': + result.append("HD,"); + break; + case 'i': + result.append("FL,"); + break; + case 'd': + result.append("DT,"); + break; + case 'c': + result.append("NC,"); + break; + case 't': + result.append("HT,"); + break; + case 's': + result.append("PR,"); + break; + case 'l': + result.append("REZ,"); + break; + case 'm': + result.append("SC,"); + break; + case 'u': + result.append("SD,"); + break; + case 'f': + result.append("PF,"); + break; + case 'b': + result.append("SU,"); + break; + case 'v': + result.append("ScoreV2,"); + break; + } + } + + if (strMod.length > 1){ + result.append(ConvertExtraModString(strMod[1])); + } + if (result.length() == 0) { + return "None"; + } + + return result.substring(0, result.length() - 1); + } + + private static String ConvertExtraModString(String s) { + StringBuilder stringBuilder = new StringBuilder(); + for (String str: s.split("\\|")){ + if (str.startsWith("x") && str.length() == 5){ + stringBuilder.append(str.substring(1)).append("x,"); + } else if (str.startsWith("AR")){ + stringBuilder.append(str).append(","); + } + } + return stringBuilder.toString(); + } + + public ScoreBoardItems[] getScoreBoardItems() { + return scoreItems; + } + + private String formatScore(int score) { + StringBuilder scoreBuilder = new StringBuilder(); + scoreBuilder.append(Math.abs(score)); + for (int i = scoreBuilder.length() - 3; i > 0; i -= 3) { + scoreBuilder.insert(i, ' '); + } + return scoreBuilder.toString(); + } + + private void initSprite(int i, String title, String acc, String markStr, final boolean showOnline, final int scoreID, String avaUrl, final String userName) { + final TextureRegion tex = ResourceManager.getInstance().getTexture( + "menu-button-background").deepCopy(); + tex.setHeight(107); + tex.setWidth(724); + camY = -146; + sprites[i] = new Sprite(Utils.toRes(-150), Utils.toRes(40), tex) { + private float dx = 0, dy = 0; + + @Override + public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, + final float pTouchAreaLocalX, + final float pTouchAreaLocalY) { + mScrollDetector.onTouchEvent(pSceneTouchEvent); + mScrollDetector.setEnabled(true); + if (pSceneTouchEvent.isActionDown()) { + moved = false; + setAlpha(0.8f); + listener.stopScroll(getY() + pTouchAreaLocalY); + dx = pTouchAreaLocalX; + dy = pTouchAreaLocalY; + downTime = 0; + _scoreID = scoreID; + return true; + } else if (pSceneTouchEvent.isActionUp() && !moved && !isScroll) { + downTime = -1; + setAlpha(0.5f); + listener.openScore(scoreID, showOnline, userName); + GlobalManager.getInstance().getScoring().setReplayID(scoreID); + return true; + } else if (pSceneTouchEvent.isActionOutside() + || pSceneTouchEvent.isActionMove() + && (MathUtils.distance(dx, dy, pTouchAreaLocalX, + pTouchAreaLocalY) > 50)) { + downTime = -1; + setAlpha(0.5f); + moved = true; + return false; + } else if (pSceneTouchEvent.isActionUp()) { + return false; + } + return false; + } + }; + + sprites[i].setColor(0, 0, 0); + sprites[i].setAlpha(0.5f); + sprites[i].setScale(0.65f); + sprites[i].setWidth(sprites[i].getWidth() * 1.1f); + int pos = 0; + if (showOnlineScores) { + pos = 90; + avatars[i] = new Avatar(userName, avaUrl); + } + final Text text = new Text(Utils.toRes(pos + 160), Utils.toRes(20), + ResourceManager.getInstance().getFont("font"), title); + final Text accText = new Text(Utils.toRes(670), Utils.toRes(12), + ResourceManager.getInstance().getFont("smallFont"), acc); + final Sprite mark = new Sprite(Utils.toRes(pos + 80), Utils.toRes(35), + ResourceManager.getInstance().getTexture( + "ranking-" + markStr + "-small")); + text.setScale(1.2f); + mark.setScale(1.5f); + mark.setPosition(pos + 60 + mark.getWidth() / 2, mark.getY()); + sprites[i].attachChild(text); + sprites[i].attachChild(accText); + sprites[i].attachChild(mark); + scene.attachChild(sprites[i]); + mainScene.registerTouchArea(sprites[i]); + height = sprites[i].getHeight(); + } + + private void initFromOnline(final TrackInfo track) { + final long currentNumber = viewNumber; + loadingText.setText("Loading scores..."); + onlineTask = new AsyncTaskLoader().execute(new OsuAsyncCallback() { + + + public void run() { + File trackFile = new File(track.getFilename()); + String hash = FileUtils.getMD5Checksum(trackFile); + ArrayList scores; + + try { + scores = OnlineManager.getInstance().getTop(trackFile, hash); + } catch (OnlineManager.OnlineManagerException e) { + Debug.e("Cannot load scores " + e.getMessage()); + synchronized (trackMutex) { + if (currentNumber == viewNumber) + loadingText.setText(OnlineManager.getInstance().getFailMessage()); + } + return; + } + + synchronized (trackMutex) { + if (currentNumber != viewNumber) + return; + + loadingText.setText(OnlineManager.getInstance().getFailMessage()); + sprites = new Sprite[scores.size() + 1]; + avatars = new Avatar[scores.size() + 1]; + long lastTotalScore = 0; + List scoreBoardItems = new ArrayList<>(); + for (int i = scores.size() - 1; i >= 0; i--) { + Debug.i(scores.get(i)); + String[] data = scores.get(i).split("\\s+"); + if (data.length < 8 || data.length == 10) + continue; + final int scoreID = Integer.parseInt(data[0]); + + String totalScore = formatScore(Integer.parseInt(data[2])); + long currTotalScore = Long.parseLong(data[2]); + String titleStr = "#" + + (i + 1) + + " " + + data[1] + + "\n" + + StringTable.format(R.string.menu_score, + totalScore, Integer.parseInt(data[3])); + long diffTotalScore = currTotalScore - lastTotalScore; + String accStr = ConvertModString(data[5]) + "\n" + + String.format(Locale.ENGLISH, "%.2f", GameHelper.Round(Integer.parseInt(data[6]) / 1000f, 2)) + "%" + "\n" + + (lastTotalScore == 0 ? "-" : ((diffTotalScore != 0 ? "+" : "") + diffTotalScore)); + lastTotalScore = currTotalScore; + initSprite(i, titleStr, accStr, data[4], true, scoreID, data[7], data[1]); + ScoreBoardItems item = new ScoreBoardItems(); + item.set(data[1], Integer.parseInt(data[3]), Integer.parseInt(data[2]), scoreID); + scoreBoardItems.add(item); + } + scoreItems = new ScoreBoardItems[scoreBoardItems.size()]; + for (int i = 0; i < scoreItems.length; i++) { + scoreItems[i] = scoreBoardItems.get(scoreBoardItems.size() - 1 - i); + } + if (scores.size() > 0) { + String[] data = scores.get(scores.size() - 1).split("\\s+"); + if (data.length == 10) { + final int scoreID = Integer.parseInt(data[0]); + String totalScore = formatScore(Integer.parseInt(data[2])); + String titleStr = "#" + + data[7] + + " of " + + data[8] + + "\n" + + StringTable.format(R.string.menu_score, + totalScore, Integer.parseInt(data[3])); + String accStr = ConvertModString(data[5]) + "\n" + + String.format(Locale.ENGLISH, "%.2f", GameHelper.Round(Integer.parseInt(data[6]) / 1000f, 2)) + "%" + "\n" + + "-"; + initSprite(scores.size(), titleStr, accStr, data[4], true, scoreID, data[9], data[1]); + } else { + sprites[scores.size()] = null; + } + } + + percentShow = 0; + } + } + + + public void onComplete() { + isCanceled = false; + if (Utils.isWifi(context) || Config.getLoadAvatar()) + loadAvatar(); + } + + }); + } + + public void init(final TrackInfo track) { + if (lastTrack == track && showOnlineScores == wasOnline && wasOnline) { + return; + } + + scoreItems = new ScoreBoardItems[0]; + lastTrack = track; + wasOnline = showOnlineScores; + + synchronized (trackMutex) { + viewNumber++; + } + + clear(); + if (track == null) { + return; + } + loadingText.setText(""); + if (OnlineManager.getInstance().isStayOnline() && showOnlineScores) { + initFromOnline(track); + return; + } + + String[] columns = {"id", "playername", "score", "combo", "mark", "accuracy", "mode"}; + Cursor scoresSet = ScoreLibrary.getInstance().getMapScores(columns, track.getFilename()); + if (scoresSet == null || scoresSet.getCount() == 0) { + if (scoresSet != null) { + scoresSet.close(); + } + + return; + } + percentShow = 0; + scoresSet.moveToFirst(); + sprites = new Sprite[scoresSet.getCount()]; + long lastTotalScore = 0; + scoreItems = new ScoreBoardItems[scoresSet.getCount()]; + for (int i = scoresSet.getCount() - 1; i >= 0; i--) { + scoresSet.moveToPosition(i); + final int scoreID = scoresSet.getInt(0); + + String totalScore = formatScore(scoresSet.getInt(scoresSet.getColumnIndexOrThrow("score"))); + long currTotalScore = scoresSet.getLong(scoresSet.getColumnIndexOrThrow("score")); + String titleStr = "#" + + (i + 1) + + " " + + scoresSet.getString(scoresSet.getColumnIndexOrThrow("playername")) + + "\n" + + StringTable.format(R.string.menu_score, + totalScore, scoresSet.getInt(scoresSet.getColumnIndexOrThrow("combo"))); + long diffTotalScore = currTotalScore - lastTotalScore; + @SuppressLint("DefaultLocale") String accStr = ConvertModString(scoresSet.getString(scoresSet.getColumnIndexOrThrow("mode"))) + "\n" + + String.format("%.2f", GameHelper.Round( scoresSet.getFloat(scoresSet.getColumnIndexOrThrow("accuracy")) * 100, 2)) + "%" + "\n" + + (lastTotalScore == 0 ? "-" : ((diffTotalScore != 0 ? "+" : "") + diffTotalScore)); + lastTotalScore = currTotalScore; + initSprite(i, titleStr, accStr, scoresSet.getString(scoresSet.getColumnIndexOrThrow("mark")), + false, scoreID, null, null); + scoreItems[i] = new ScoreBoardItems(); + scoreItems[i].set(scoresSet.getString(scoresSet.getColumnIndexOrThrow("playername")), + scoresSet.getInt(scoresSet.getColumnIndexOrThrow("combo")), + scoresSet.getInt(scoresSet.getColumnIndexOrThrow("score")), + scoreID); + } + scoresSet.close(); + } + + public void clear() { + if (sprites == null) { + return; + } + final Sprite[] sprs = sprites; + sprites = null; + SyncTaskManager.getInstance().run(() -> { + for (final Sprite sp : sprs) { + if (sp == null) continue; + mainScene.unregisterTouchArea(sp); + sp.detachSelf(); + } + }); + + } + + public void update(final float pSecondsElapsed) { + secPassed += pSecondsElapsed; + if (sprites == null || sprites.length <= 0) { + return; + } + if (percentShow == -1) { + float oy = -camY; + for (final Sprite item : sprites) { + if (item == null) + break; + item.setPosition(item.getX(), oy); + oy += (item.getHeight() - Utils.toRes(32)) + * 0.8f; + } + oy += camY; + camY += velocityY * pSecondsElapsed; + maxY = oy - (Config.getRES_HEIGHT() - 110 - (height - Utils.toRes(32)) + * 0.8f); + if (camY <= -146 && velocityY < 0 || camY >= maxY && velocityY > 0) { + camY -= velocityY * pSecondsElapsed; + velocityY = 0; + isScroll = false; + } + if (Math.abs(velocityY) > Utils.toRes(500) * pSecondsElapsed) { + velocityY -= Utils.toRes(10) * pSecondsElapsed + * Math.signum(velocityY); + } else { + velocityY = 0; + isScroll = false; + } + } else { + percentShow += pSecondsElapsed * 4; + if (percentShow > 1) { + percentShow = 1; + } + for (int i = 0; i < sprites.length; i++) { + if (sprites[i] != null) { +// if (i == 5 && showOnlineScores == true) { +// sprites[i].setPosition( +// Utils.toRes(-160), +// Utils.toRes(194) + percentShow * 5 +// * (sprites[5].getHeight() - Utils.toRes(32)) +// * 0.95f) ; +// continue; +// } + sprites[i].setPosition( + Utils.toRes(-160), + Utils.toRes(146) + percentShow * i + * (sprites[i].getHeight() - Utils.toRes(32)) + * 0.8f); + } + } + if (percentShow == 1) { + percentShow = -1; + } + } + if (downTime >= 0) { + downTime += pSecondsElapsed; + } + if (downTime > 0.5) { + moved = true; + if (_scoreID != -1 && !showOnlineScores) { + GlobalManager.getInstance().getSongMenu().showDeleteScoreMenu(_scoreID); + } + downTime = -1; + } + } + + public boolean isShowOnlineScores() { + return showOnlineScores; + } + + public void setShowOnlineScores(boolean showOnlineScores) { + synchronized (trackMutex) { + this.showOnlineScores = showOnlineScores; + } + } + + public void loadAvatar() { + + try { + if (avatars == null) { + return; + } + for (int i = 0; i < avatars.length; i++) { + if (isCanceled) { + isCanceled = false; + break; + } + if (sprites[i] == null) { + continue; + } + final int finalI = i; + AsyncTask avatarTask = new AsyncTaskLoader().execute(new OsuAsyncCallback() { + + private final TextureRegion[] avatarTexRegion = new TextureRegion[avatars.length]; + + public void run() { + + Avatar ava = avatars[finalI]; + boolean bool = OnlineManager.getInstance().loadAvatarToTextureManager(ava.getAvaUrl(), "ava@" + ava.getUserName()); + if (bool) { + avatarTexRegion[finalI] = ResourceManager.getInstance().getTextureIfLoaded("ava@" + ava.getUserName()); + } else { + avatarTexRegion[finalI] = ResourceManager.getInstance().getTexture("emptyavatar"); + } + } + + public void onComplete() { + try { + if (avatarTexRegion[finalI] != null && showOnlineScores) { + final Sprite avatar = new Sprite(55, 12, Utils.toRes(90), Utils.toRes(90), avatarTexRegion[finalI]); + sprites[finalI].attachChild(avatar); + } + } catch (Exception ignored) {} + + isCanceled = false; + } + }); + + avatarTasks.add(avatarTask); + } + isCanceled = false; + } catch (Exception ex) { +// Debug.e(ex.toString()); + isCanceled = false; + } + } + + public void cancleLoadOnlineScores() { + if (onlineTask != null && onlineTask.getStatus() != AsyncTask.Status.FINISHED) { + onlineTask.cancel(true); + } + } + + public void cancleLoadAvatar() { + if (avatarTasks != null) { + for (AsyncTask avatarTask : avatarTasks) { + if (avatarTask.getStatus() != AsyncTask.Status.FINISHED) { + isCanceled = true; + avatarTask.cancel(true); + /* if (OnlineManager.get != null) { + OnlineManager.get.abort(); + } */ + } + } + } + } + + @Override + public void onScroll(ScrollDetector scrollDetector, TouchEvent touchEvent, float distanceX, float distanceY) { + switch (touchEvent.getAction()) { + case (TouchEvent.ACTION_DOWN): + velocityY = 0; + touchY = touchEvent.getY(); + pointerId = touchEvent.getPointerID(); + tapTime = secPassed; + initalY = touchY; + isScroll = true; + break; + case (TouchEvent.ACTION_MOVE): + if (pointerId != -1 && pointerId != touchEvent.getPointerID()) { + break; + } + isScroll = true; + if (initalY == -1) { + velocityY = 0; + touchY = touchEvent.getY(); + initalY = touchY; + tapTime = secPassed; + pointerId = touchEvent.getPointerID(); + } + final float dy = touchEvent.getY() - touchY; + + camY -= dy; + touchY = touchEvent.getY(); + if (camY <= -146) { + camY = -146; + velocityY = 0; + } else if (camY >= maxY) { + camY = maxY; + velocityY = 0; + } + + // velocityY = -3f * dy; + break; + default: { + if (pointerId != -1 && pointerId != touchEvent.getPointerID()) { + break; + } + touchY = null; + if (secPassed - tapTime < 0.001f || initalY == -1) { + velocityY = 0; + isScroll = false; + } else { + velocityY = (initalY - touchEvent.getY()) + / (secPassed - tapTime); + isScroll = true; + } + pointerId = -1; + initalY = -1; + + } + break; + } + } + + public Scene getScene() { + return scene; + } + + public static class ScoreBoardItems { + public String userName; + public int playScore; + public int scoreId; + private int maxCombo; + + public void set(String name, int com, int scr, int id) { + userName = name; + maxCombo = com; + playScore = scr; + scoreId = id; + } + + public String get() { + return userName + "\n" + NumberFormat.getNumberInstance(Locale.US).format(playScore) + "\n" + NumberFormat.getNumberInstance(Locale.US).format(maxCombo) + "x"; + } + } + + static class Avatar { + private String userName; + private String avaUrl; + + public Avatar(String userName, String avaUrl) { + this.userName = userName; + this.avaUrl = "https://secure.gravatar.com/avatar/" + avaUrl + ".jpg?s=100"; + } + + public String getUserName() { + return userName; + } + + public void setUserName(String userName) { + this.userName = userName; + } + + public String getAvaUrl() { + return avaUrl; + } + + public void setAvaUrl(String avaUrl) { + this.avaUrl = avaUrl; + } + } } diff --git a/src/ru/nsu/ccfit/zuev/osu/menu/ScrollBar.java b/src/ru/nsu/ccfit/zuev/osu/menu/ScrollBar.java index 44d692ce..27494d66 100644 --- a/src/ru/nsu/ccfit/zuev/osu/menu/ScrollBar.java +++ b/src/ru/nsu/ccfit/zuev/osu/menu/ScrollBar.java @@ -8,39 +8,39 @@ import ru.nsu.ccfit.zuev.osu.Utils; public class ScrollBar { - private final Rectangle barRectangle; - private boolean visible; - - public ScrollBar(final Scene scene) { - visible = false; - - barRectangle = new Rectangle(Config.getRES_WIDTH() - Utils.toRes(20), - 0, Utils.toRes(20), Utils.toRes(50)); - barRectangle.setAlpha(0.8f); - barRectangle.setColor(1, 1, 1); - - scene.attachChild(barRectangle); - barRectangle.setVisible(false); - } - - public void setPosition(final float vy, final float maxy) { - if (!visible) { - return; - } - - barRectangle - .setPosition(barRectangle.getX(), - (Config.getRES_HEIGHT() - barRectangle.getHeight()) - * vy / maxy); - } - - public void setVisible(final boolean vis) { - barRectangle.setVisible(vis); - if (vis && !visible) { - final IEntity parent = barRectangle.getParent(); - parent.detachChild(barRectangle); - parent.attachChild(barRectangle); - } - visible = vis; - } + private final Rectangle barRectangle; + private boolean visible; + + public ScrollBar(final Scene scene) { + visible = false; + + barRectangle = new Rectangle(Config.getRES_WIDTH() - Utils.toRes(20), + 0, Utils.toRes(20), Utils.toRes(50)); + barRectangle.setAlpha(0.8f); + barRectangle.setColor(1, 1, 1); + + scene.attachChild(barRectangle); + barRectangle.setVisible(false); + } + + public void setPosition(final float vy, final float maxy) { + if (!visible) { + return; + } + + barRectangle + .setPosition(barRectangle.getX(), + (Config.getRES_HEIGHT() - barRectangle.getHeight()) + * vy / maxy); + } + + public void setVisible(final boolean vis) { + barRectangle.setVisible(vis); + if (vis && !visible) { + final IEntity parent = barRectangle.getParent(); + parent.detachChild(barRectangle); + parent.attachChild(barRectangle); + } + visible = vis; + } } diff --git a/src/ru/nsu/ccfit/zuev/osu/menu/SettingsMenu.java b/src/ru/nsu/ccfit/zuev/osu/menu/SettingsMenu.java index 4a083d3e..b90e2c94 100644 --- a/src/ru/nsu/ccfit/zuev/osu/menu/SettingsMenu.java +++ b/src/ru/nsu/ccfit/zuev/osu/menu/SettingsMenu.java @@ -52,241 +52,241 @@ public class SettingsMenu extends SettingsFragment { - private PreferenceScreen mParentScreen, parentScreen; - private boolean isOnNestedScreen = false; - private Activity mActivity; - - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - mActivity = GlobalManager.getInstance().getMainActivity(); - } - - @Override - public void onCreatePreferences(Bundle savedInstanceState, String rootKey) { - setPreferencesFromResource(R.xml.options, rootKey); - - SkinPathPreference skinPath = (SkinPathPreference) findPreference("skinPath"); - skinPath.reloadSkinList(); - skinPath.setOnPreferenceChangeListener((preference, newValue) -> { - if(GlobalManager.getInstance().getSkinNow() != newValue.toString()) { - // SpritePool.getInstance().purge(); - GlobalManager.getInstance().setSkinNow(Config.getSkinPath()); - SkinManager.getInstance().clearSkin(); - ResourceManager.getInstance().loadSkin(newValue.toString()); - GlobalManager.getInstance().getEngine().getTextureManager().reloadTextures(); - mActivity.startActivity(new Intent(mActivity, MainActivity.class)); - Snackbar.make(mActivity.findViewById(android.R.id.content), - StringTable.get(R.string.message_loaded_skin), 1500).show(); - } - return true; - }); - - // screens - mParentScreen = parentScreen = getPreferenceScreen(); - - ((PreferenceScreen) findPreference("onlineOption")).setOnPreferenceClickListener(preference -> { - setPreferenceScreen((PreferenceScreen) preference); - return true; - }); - - ((PreferenceScreen) findPreference("general")).setOnPreferenceClickListener(preference -> { - setPreferenceScreen((PreferenceScreen) preference); - return true; - }); - - ((PreferenceScreen) findPreference("color")).setOnPreferenceClickListener(preference -> { - parentScreen = (PreferenceScreen) findPreference("general"); - setPreferenceScreen((PreferenceScreen) preference); - return true; - }); - - ((PreferenceScreen) findPreference("sound")).setOnPreferenceClickListener(preference -> { - setPreferenceScreen((PreferenceScreen) preference); - return true; - }); - - ((PreferenceScreen) findPreference("beatmaps")).setOnPreferenceClickListener(preference -> { - setPreferenceScreen((PreferenceScreen) preference); - return true; - }); - - ((PreferenceScreen) findPreference("advancedopts")).setOnPreferenceClickListener(preference -> { - setPreferenceScreen((PreferenceScreen) preference); - return true; - }); - // screens END - - final EditTextPreference onlinePassword = (EditTextPreference) findPreference("onlinePassword"); - onlinePassword.setOnBindEditTextListener(editText -> { - editText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD); - }); - - final EditTextPreference skinToppref = (EditTextPreference) findPreference("skinTopPath"); - skinToppref.setOnPreferenceChangeListener((preference, newValue) -> { - if (newValue.toString().trim().length() == 0) { - skinToppref.setText(Config.getCorePath() + "Skin/"); - Config.loadConfig(mActivity); - skinPath.reloadSkinList(); - return false; - } - - File file = new File(newValue.toString()); - if (!file.exists()) { - if (!file.mkdirs()) { - ToastLogger.showText(StringTable.get(R.string.message_error_dir_not_found), true); - return false; - } - } - - skinToppref.setText(newValue.toString()); - Config.loadConfig(mActivity); - skinPath.reloadSkinList(); - return false; - }); - - final Preference pref = findPreference("clear"); - pref.setOnPreferenceClickListener(preference -> { - LibraryManager.getInstance().clearCache(); - return true; - }); - final Preference clearProps = findPreference("clear_properties"); - clearProps.setOnPreferenceClickListener(preference -> { - PropertiesLibrary.getInstance() - .clear(mActivity); - return true; - }); - final Preference register = findPreference("registerAcc"); - register.setOnPreferenceClickListener(preference -> { - OnlineInitializer initializer = new OnlineInitializer(getActivity()); - initializer.createInitDialog(); - return true; - }); - - final Preference update = findPreference("update"); - update.setOnPreferenceClickListener(preference -> { - Updater.getInstance().checkForUpdates(); - return true; - }); - } - - public void onNavigateToScreen(PreferenceScreen preferenceScreen) { - if(preferenceScreen.getKey() != null) { - if(!isOnNestedScreen) { - isOnNestedScreen = true; - animateBackButton(R.drawable.back_black); - } - setTitle(preferenceScreen.getTitle().toString()); - for(int v : new int[]{android.R.id.list_container, R.id.title}) { - animateView(v, R.anim.slide_in_right); - } - } - } - - private void animateBackButton(@DrawableRes int newDrawable) { - Animation animation = AnimationUtils.loadAnimation(mActivity, R.anim.rotate_360); - animation.setAnimationListener(new Animation.AnimationListener() { - public void onAnimationEnd(Animation animation) { - ImageButton backButton = (ImageButton) findViewById(R.id.back_button); - backButton.setImageDrawable(mActivity.getResources().getDrawable(newDrawable)); - } - public void onAnimationRepeat(Animation animation) {} - public void onAnimationStart(Animation animation) {} - }); - ((ImageButton) findViewById(R.id.back_button)).startAnimation(animation); - } - - private void animateView(@IdRes int viewId, @AnimRes int anim) { - findViewById(viewId).startAnimation(AnimationUtils.loadAnimation(mActivity, anim)); - } - - private void setTitle(String title) { - ((TextView) findViewById(R.id.title)).setText(title); - } - - @Override - public void callDismissOnBackPress() { - navigateBack(); - } - - // only supports 1 child with an optional grandchild - private void navigateBack() { - for(int v : new int[]{android.R.id.list_container, R.id.title}) { - animateView(v, R.anim.slide_in_left); - } - - if(parentScreen.getKey() != null) { - setPreferenceScreen(parentScreen); - setTitle(parentScreen.getTitle().toString()); - parentScreen = mParentScreen; - return; - } - - if(isOnNestedScreen) { - isOnNestedScreen = false; - animateBackButton(R.drawable.close_black); - setPreferenceScreen(mParentScreen); - setTitle(StringTable.get(R.string.menu_settings_title)); - }else { - dismiss(); - } - } - - @Override - protected void onLoadView() { - ((ImageButton) findViewById(R.id.back_button)).setOnClickListener(v -> { - navigateBack(); - }); - } - - protected void playOnLoadAnim() { - View body = findViewById(R.id.body); - body.setAlpha(0); - body.setTranslationX(400); - body.animate().cancel(); - body.animate() - .translationX(0) - .alpha(1) - .setInterpolator(EasingHelper.asInterpolator(Easing.InOutQuad)) - .setDuration(150) - .start(); - playBackgroundHideInAnim(150); - } - - protected void playOnDismissAnim(Runnable action) { - View body = findViewById(R.id.body); - body.animate().cancel(); - body.animate() - .translationXBy(400) - .alpha(0) - .setDuration(200) - .setInterpolator(EasingHelper.asInterpolator(Easing.InOutQuad)) - .setListener(new BaseAnimationListener() { - @Override - public void onAnimationEnd(Animator animation) { - if (action != null) { - action.run(); - } - } - }) - .start(); - playBackgroundHideOutAnim(200); - } - - @Override - public void show() { - super.show(); - } - - @Override - public void dismiss() { - playOnDismissAnim(() -> { - Config.loadConfig(mActivity); - GlobalManager.getInstance().getMainScene().reloadOnlinePanel(); - GlobalManager.getInstance().getMainScene().loadTimeingPoints(false); - GlobalManager.getInstance().getSongService().setVolume(Config.getBgmVolume()); - GlobalManager.getInstance().getSongService().setGaming(false); - SettingsMenu.super.dismiss(); - }); - } - -} \ No newline at end of file + private PreferenceScreen mParentScreen, parentScreen; + private boolean isOnNestedScreen = false; + private Activity mActivity; + + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + mActivity = GlobalManager.getInstance().getMainActivity(); + } + + @Override + public void onCreatePreferences(Bundle savedInstanceState, String rootKey) { + setPreferencesFromResource(R.xml.options, rootKey); + + SkinPathPreference skinPath = (SkinPathPreference) findPreference("skinPath"); + skinPath.reloadSkinList(); + skinPath.setOnPreferenceChangeListener((preference, newValue) -> { + if(GlobalManager.getInstance().getSkinNow() != newValue.toString()) { + // SpritePool.getInstance().purge(); + GlobalManager.getInstance().setSkinNow(Config.getSkinPath()); + SkinManager.getInstance().clearSkin(); + ResourceManager.getInstance().loadSkin(newValue.toString()); + GlobalManager.getInstance().getEngine().getTextureManager().reloadTextures(); + mActivity.startActivity(new Intent(mActivity, MainActivity.class)); + Snackbar.make(mActivity.findViewById(android.R.id.content), + StringTable.get(R.string.message_loaded_skin), 1500).show(); + } + return true; + }); + + // screens + mParentScreen = parentScreen = getPreferenceScreen(); + + ((PreferenceScreen) findPreference("onlineOption")).setOnPreferenceClickListener(preference -> { + setPreferenceScreen((PreferenceScreen) preference); + return true; + }); + + ((PreferenceScreen) findPreference("general")).setOnPreferenceClickListener(preference -> { + setPreferenceScreen((PreferenceScreen) preference); + return true; + }); + + ((PreferenceScreen) findPreference("color")).setOnPreferenceClickListener(preference -> { + parentScreen = (PreferenceScreen) findPreference("general"); + setPreferenceScreen((PreferenceScreen) preference); + return true; + }); + + ((PreferenceScreen) findPreference("sound")).setOnPreferenceClickListener(preference -> { + setPreferenceScreen((PreferenceScreen) preference); + return true; + }); + + ((PreferenceScreen) findPreference("beatmaps")).setOnPreferenceClickListener(preference -> { + setPreferenceScreen((PreferenceScreen) preference); + return true; + }); + + ((PreferenceScreen) findPreference("advancedopts")).setOnPreferenceClickListener(preference -> { + setPreferenceScreen((PreferenceScreen) preference); + return true; + }); + // screens END + + final EditTextPreference onlinePassword = (EditTextPreference) findPreference("onlinePassword"); + onlinePassword.setOnBindEditTextListener(editText -> { + editText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD); + }); + + final EditTextPreference skinToppref = (EditTextPreference) findPreference("skinTopPath"); + skinToppref.setOnPreferenceChangeListener((preference, newValue) -> { + if (newValue.toString().trim().length() == 0) { + skinToppref.setText(Config.getCorePath() + "Skin/"); + Config.loadConfig(mActivity); + skinPath.reloadSkinList(); + return false; + } + + File file = new File(newValue.toString()); + if (!file.exists()) { + if (!file.mkdirs()) { + ToastLogger.showText(StringTable.get(R.string.message_error_dir_not_found), true); + return false; + } + } + + skinToppref.setText(newValue.toString()); + Config.loadConfig(mActivity); + skinPath.reloadSkinList(); + return false; + }); + + final Preference pref = findPreference("clear"); + pref.setOnPreferenceClickListener(preference -> { + LibraryManager.getInstance().clearCache(); + return true; + }); + final Preference clearProps = findPreference("clear_properties"); + clearProps.setOnPreferenceClickListener(preference -> { + PropertiesLibrary.getInstance() + .clear(mActivity); + return true; + }); + final Preference register = findPreference("registerAcc"); + register.setOnPreferenceClickListener(preference -> { + OnlineInitializer initializer = new OnlineInitializer(getActivity()); + initializer.createInitDialog(); + return true; + }); + + final Preference update = findPreference("update"); + update.setOnPreferenceClickListener(preference -> { + Updater.getInstance().checkForUpdates(); + return true; + }); + } + + public void onNavigateToScreen(PreferenceScreen preferenceScreen) { + if(preferenceScreen.getKey() != null) { + if(!isOnNestedScreen) { + isOnNestedScreen = true; + animateBackButton(R.drawable.back_black); + } + setTitle(preferenceScreen.getTitle().toString()); + for(int v : new int[]{android.R.id.list_container, R.id.title}) { + animateView(v, R.anim.slide_in_right); + } + } + } + + private void animateBackButton(@DrawableRes int newDrawable) { + Animation animation = AnimationUtils.loadAnimation(mActivity, R.anim.rotate_360); + animation.setAnimationListener(new Animation.AnimationListener() { + public void onAnimationEnd(Animation animation) { + ImageButton backButton = (ImageButton) findViewById(R.id.back_button); + backButton.setImageDrawable(mActivity.getResources().getDrawable(newDrawable)); + } + public void onAnimationRepeat(Animation animation) {} + public void onAnimationStart(Animation animation) {} + }); + ((ImageButton) findViewById(R.id.back_button)).startAnimation(animation); + } + + private void animateView(@IdRes int viewId, @AnimRes int anim) { + findViewById(viewId).startAnimation(AnimationUtils.loadAnimation(mActivity, anim)); + } + + private void setTitle(String title) { + ((TextView) findViewById(R.id.title)).setText(title); + } + + @Override + public void callDismissOnBackPress() { + navigateBack(); + } + + // only supports 1 child with an optional grandchild + private void navigateBack() { + for(int v : new int[]{android.R.id.list_container, R.id.title}) { + animateView(v, R.anim.slide_in_left); + } + + if(parentScreen.getKey() != null) { + setPreferenceScreen(parentScreen); + setTitle(parentScreen.getTitle().toString()); + parentScreen = mParentScreen; + return; + } + + if(isOnNestedScreen) { + isOnNestedScreen = false; + animateBackButton(R.drawable.close_black); + setPreferenceScreen(mParentScreen); + setTitle(StringTable.get(R.string.menu_settings_title)); + }else { + dismiss(); + } + } + + @Override + protected void onLoadView() { + ((ImageButton) findViewById(R.id.back_button)).setOnClickListener(v -> { + navigateBack(); + }); + } + + protected void playOnLoadAnim() { + View body = findViewById(R.id.body); + body.setAlpha(0); + body.setTranslationX(400); + body.animate().cancel(); + body.animate() + .translationX(0) + .alpha(1) + .setInterpolator(EasingHelper.asInterpolator(Easing.InOutQuad)) + .setDuration(150) + .start(); + playBackgroundHideInAnim(150); + } + + protected void playOnDismissAnim(Runnable action) { + View body = findViewById(R.id.body); + body.animate().cancel(); + body.animate() + .translationXBy(400) + .alpha(0) + .setDuration(200) + .setInterpolator(EasingHelper.asInterpolator(Easing.InOutQuad)) + .setListener(new BaseAnimationListener() { + @Override + public void onAnimationEnd(Animator animation) { + if (action != null) { + action.run(); + } + } + }) + .start(); + playBackgroundHideOutAnim(200); + } + + @Override + public void show() { + super.show(); + } + + @Override + public void dismiss() { + playOnDismissAnim(() -> { + Config.loadConfig(mActivity); + GlobalManager.getInstance().getMainScene().reloadOnlinePanel(); + GlobalManager.getInstance().getMainScene().loadTimeingPoints(false); + GlobalManager.getInstance().getSongService().setVolume(Config.getBgmVolume()); + GlobalManager.getInstance().getSongService().setGaming(false); + SettingsMenu.super.dismiss(); + }); + } + +} diff --git a/src/ru/nsu/ccfit/zuev/osu/menu/SongMenu.java b/src/ru/nsu/ccfit/zuev/osu/menu/SongMenu.java index 1eadc2d2..2c8c1cde 100644 --- a/src/ru/nsu/ccfit/zuev/osu/menu/SongMenu.java +++ b/src/ru/nsu/ccfit/zuev/osu/menu/SongMenu.java @@ -66,1339 +66,1339 @@ import ru.nsu.ccfit.zuev.osuplus.R; public class SongMenu implements IUpdateHandler, MenuItemListener, - IScrollBarListener { - private final static Boolean musicMutex = true; - private final Boolean backgroundMutex = true; - public Scene scene; - public Entity frontLayer = new Entity(); - SortOrder sortOrder = SortOrder.Title; - private Engine engine; - private GameScene game; - private ScoringScene scoreScene; - private float camY = 0; - private float velocityY; - private Activity context; - private Entity backLayer = new Entity(); - private ArrayList items = new ArrayList<>(); - private MenuItem selectedItem = null; - private TrackInfo selectedTrack; - private Sprite bg = null; - private Boolean bgLoaded = false; - private String bgName = ""; - private ScoreBoard board; - private Float touchY = null; - private String filterText = ""; - private boolean favsOnly = false; - private Set limitC; - private float secondsSinceLastSelect = 0; - private float maxY = 100500; - private int pointerId = -1; - private float initalY = -1; - private float secPassed = 0, tapTime; - private Sprite backButton = null; - private ScrollBar scrollbar; - private ChangeableText trackInfo, mapper, beatmapInfo, beatmapInfo2, dimensionInfo; - private boolean isSelectComplete = true; - private AnimSprite scoringSwitcher = null; - private AsyncTask boardTask; - private GroupType groupType = GroupType.MapSet; - - public SongMenu() { - } - - public static void stopMusicStatic() { - synchronized (musicMutex) { - if (GlobalManager.getInstance().getSongService() != null) { - GlobalManager.getInstance().getSongService().stop(); - } - } - } - - public void setScoringScene(final ScoringScene ss) { - scoreScene = ss; - } - - public ScoreBoard.ScoreBoardItems[] getBoard() { - return board.getScoreBoardItems(); - } - - public boolean isBoardOnline() { - return board.isShowOnlineScores(); - } - - public ArrayList getMenuItems() { - return items; - } - - public void init(final Activity context, final Engine engine, - final GameScene pGame) { - this.engine = engine; - game = pGame; - this.context = context; - } - - public void loadFilter(IFilterMenu filterMenu) { - setFilter(filterMenu.getFilter(), filterMenu.getOrder(), filterMenu.isFavoritesOnly(), - filterMenu.getFavoriteFolder() == null ? null : FavoriteLibrary.get().getMaps(filterMenu.getFavoriteFolder())); - } - - public void reload() { - frontLayer = new Entity(); - backLayer = new Entity(); - scene.unregisterUpdateHandler(this); - scene.setTouchAreaBindingEnabled(false); - load(); - GlobalManager.getInstance().getGameScene().setOldScene(scene); - } - - public synchronized void load() { - scene = new Scene(); - camY = 0; - velocityY = 0; - selectedItem = null; - items = new ArrayList<>(); - selectedTrack = null; - bgLoaded = true; - SongMenuPool.getInstance().init(); - FilterMenu.getInstance().loadConfig(context); - ModMenu.getInstance().reload(); - bindDataBaseChangedListener(); - - scene.attachChild(backLayer); - scene.attachChild(frontLayer); - - final TextureRegion tex = ResourceManager.getInstance().getTexture("menu-background"); - float height = tex.getHeight(); - height *= Config.getRES_WIDTH() / (float) tex.getWidth(); - final Sprite bg = new Sprite(0, (Config.getRES_HEIGHT() - height) / 2, - Config.getRES_WIDTH(), height, tex); - scene.setBackground(new SpriteBackground(bg)); - - final Rectangle bgDimRect = new Rectangle(0, 0, Config.getRES_WIDTH(), Config.getRES_HEIGHT()); - bgDimRect.setColor(0, 0, 0, 0.2f); - backLayer.attachChild(bgDimRect); - - board = new ScoreBoard(scene, backLayer, this, context); - - float oy = 10; - for (final BeatmapInfo i : LibraryManager.getInstance().getLibrary()) { - final MenuItem item = new MenuItem(this, i); - items.add(item); - item.attachToScene(scene, backLayer); - oy += item.getHeight(); - } - sortOrder = SortOrder.Title; - sort(); - - if (items.size() == 0) { - final Text text = new Text(0, 0, ResourceManager.getInstance() - .getFont("CaptionFont"), "There are no songs in library", - HorizontalAlign.CENTER); - text.setPosition(Config.getRES_WIDTH() / 2f - text.getWidth() / 2, - Config.getRES_HEIGHT() / 2f - text.getHeight() / 2); - text.setScale(1.5f); - text.setColor(0, 0, 0); - scene.attachChild(text); - return; - } - - scene.setOnSceneTouchListener((pScene, evt) -> { - if (evt.getX() < Config.getRES_WIDTH() / 5f * 2) { - return false; - } - switch (evt.getAction()) { - case (TouchEvent.ACTION_DOWN): - velocityY = 0; - touchY = evt.getY(); - pointerId = evt.getPointerID(); - tapTime = secPassed; - initalY = touchY; - break; - case (TouchEvent.ACTION_MOVE): - if (pointerId != -1 && pointerId != evt.getPointerID()) { - break; - } - if (initalY == -1) { - velocityY = 0; - touchY = evt.getY(); - initalY = touchY; - tapTime = secPassed; - pointerId = evt.getPointerID(); - } - final float dy = evt.getY() - touchY; - - camY -= dy; - touchY = evt.getY(); - if (camY <= -Config.getRES_HEIGHT() / 2f) { - camY = -Config.getRES_HEIGHT() / 2f; - velocityY = 0; - } else if (camY >= maxY) { - camY = maxY; - velocityY = 0; - } - - // velocityY = -3f * dy; - break; - default: { - if (pointerId != -1 && pointerId != evt.getPointerID()) { - break; - } - touchY = null; - if (secPassed - tapTime < 0.001f || initalY == -1) { - velocityY = 0; - } else { - velocityY = (initalY - evt.getY()) - / (secPassed - tapTime); - } - pointerId = -1; - initalY = -1; - - } - break; - } - return true; - }); - - scene.registerUpdateHandler(this); - scene.setTouchAreaBindingEnabled(true); - - scrollbar = new ScrollBar(scene); - - /*final Rectangle bgTopRect = new Rectangle(0, 0, Config.getRES_WIDTH(), Utils.toRes(170)); - bgTopRect.setColor(0, 0, 0, 0.8f);*/ - final TextureRegion songSelectTopTexture = ResourceManager.getInstance().getTexture("songselect-top"); - final Sprite songSelectTop = new Sprite(0, 0, songSelectTopTexture); - songSelectTop.setSize(songSelectTopTexture.getWidth() * songSelectTopTexture.getHeight() / 184f, 184); - songSelectTop.setPosition(-1640, songSelectTop.getY()); - songSelectTop.setAlpha(0.6f); - frontLayer.attachChild(songSelectTop); - - /*final Rectangle bgbottomRect = new Rectangle(0, 0, Config.getRES_WIDTH(), Utils.toRes(110)); - bgbottomRect.setPosition(0, Config.getRES_HEIGHT() - bgbottomRect.getHeight()); - bgbottomRect.setColor(0, 0, 0, 0.8f); - frontLayer.attachChild(bgbottomRect);*/ - - trackInfo = new ChangeableText(Utils.toRes(70), Utils.toRes(2), - ResourceManager.getInstance().getFont("font"), "title", 1024); - frontLayer.attachChild(trackInfo); - - mapper = new ChangeableText(Utils.toRes(70), trackInfo.getY() + trackInfo.getHeight() + Utils.toRes(2), - ResourceManager.getInstance().getFont("middleFont"), "mapper", 1024); - frontLayer.attachChild(mapper); - - beatmapInfo = new ChangeableText(Utils.toRes(4), mapper.getY() + mapper.getHeight() + Utils.toRes(2), - ResourceManager.getInstance().getFont("middleFont"), "beatmapInfo", 1024); - frontLayer.attachChild(beatmapInfo); - - beatmapInfo2 = new ChangeableText(Utils.toRes(4), beatmapInfo.getY() + beatmapInfo.getHeight() + Utils.toRes(2), - ResourceManager.getInstance().getFont("middleFont"), "beatmapInfo2", 1024); - frontLayer.attachChild(beatmapInfo2); - - dimensionInfo = new ChangeableText(Utils.toRes(4), beatmapInfo2.getY() + beatmapInfo2.getHeight() + Utils.toRes(2), - ResourceManager.getInstance().getFont("smallFont"), "dimensionInfo", 1024); - frontLayer.attachChild(dimensionInfo); - - SkinJson.Layout layoutBackButton = SkinJson.get().getLayout("BackButton"); - SkinJson.Layout layoutMods = SkinJson.get().getLayout("ModsButton"); - SkinJson.Layout layoutOptions = SkinJson.get().getLayout("OptionsButton"); - SkinJson.Layout layoutRandom = SkinJson.get().getLayout("RandomButton"); - - if (ResourceManager.getInstance().isTextureLoaded("menu-back-0")) { - List loadedBackTextures = new ArrayList<>(); - for (int i = 0; i < 60; i++) { - if (ResourceManager.getInstance().isTextureLoaded("menu-back-" + i)) - loadedBackTextures.add("menu-back-" + i); - } - backButton = new AnimSprite(0, 0, loadedBackTextures.size(), loadedBackTextures.toArray(new String[0])) { - boolean moved = false; - float dx = 0, dy = 0; - boolean scaleWhenHold = true; - - { - if (layoutBackButton != null) { - scaleWhenHold = layoutBackButton.property.optBoolean("scaleWhenHold", true); - } - } - - @Override - public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, - final float pTouchAreaLocalX, final float pTouchAreaLocalY) { - if (pSceneTouchEvent.isActionDown()) { - if (scaleWhenHold) backButton.setScale(1.25f); - moved = false; - dx = pTouchAreaLocalX; - dy = pTouchAreaLocalY; - BassSoundProvider playSnd = ResourceManager.getInstance().getSound("menuback"); - if (playSnd != null) { - playSnd.play(); - } - return true; - } - if (pSceneTouchEvent.isActionUp()) { - // back - if (selectedTrack == null) { - return true; - } - if (!moved) { - backButton.setScale(1f); - back(); - } - return true; - } - if (pSceneTouchEvent.isActionOutside() - || pSceneTouchEvent.isActionMove() - && (MathUtils.distance(dx, dy, pTouchAreaLocalX, - pTouchAreaLocalY) > 50)) { - backButton.setScale(1f); - moved = true; - } - return false; - } - }; - } else { - backButton = new Sprite(0, 0, ResourceManager.getInstance().getTexture("menu-back")) { - boolean moved = false; - float dx = 0, dy = 0; - boolean scaleWhenHold = true; - - { - if (layoutBackButton != null) { - scaleWhenHold = layoutBackButton.property.optBoolean("scaleWhenHold", true); - } - } - - @Override - public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, - final float pTouchAreaLocalX, final float pTouchAreaLocalY) { - if (pSceneTouchEvent.isActionDown()) { - if (scaleWhenHold) backButton.setScale(1.25f); - moved = false; - dx = pTouchAreaLocalX; - dy = pTouchAreaLocalY; - BassSoundProvider playSnd = ResourceManager.getInstance().getSound("menuback"); - if (playSnd != null) { - playSnd.play(); - } - return true; - } - if (pSceneTouchEvent.isActionUp()) { - // back - if (selectedTrack == null) { - return true; - } - if (!moved) { - backButton.setScale(1f); - back(); - } - return true; - } - if (pSceneTouchEvent.isActionOutside() - || pSceneTouchEvent.isActionMove() - && (MathUtils.distance(dx, dy, pTouchAreaLocalX, - pTouchAreaLocalY) > 50)) { - backButton.setScale(1f); - moved = true; - } - return false; - } - }; - } - - final AnimSprite modSelection = new AnimSprite(0, 0, 0, - "selection-mods", "selection-mods-over") { - boolean moved = false; - private float dx = 0, dy = 0; - - - @Override - public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, - final float pTouchAreaLocalX, final float pTouchAreaLocalY) { - if (pSceneTouchEvent.isActionDown()) { - setFrame(1); - moved = false; - dx = pTouchAreaLocalX; - dy = pTouchAreaLocalY; - return true; - } - if (pSceneTouchEvent.isActionUp()) { - setFrame(0); - if (!moved) { - velocityY = 0; - ModMenu.getInstance().show(SongMenu.this, selectedTrack); - } - return true; - } - if (pSceneTouchEvent.isActionOutside() - || pSceneTouchEvent.isActionMove() - && (MathUtils.distance(dx, dy, pTouchAreaLocalX, - pTouchAreaLocalY) > 50)) { - moved = true; - setFrame(0); - } - return false; - } - }; - - final AnimSprite optionSelection = new AnimSprite(0, 0, 0, - "selection-options", "selection-options-over") { - boolean moved = false; - private float dx = 0, dy = 0; - - - @Override - public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, - final float pTouchAreaLocalX, final float pTouchAreaLocalY) { - if (pSceneTouchEvent.isActionDown()) { - setFrame(1); - moved = false; - dx = pTouchAreaLocalX; - dy = pTouchAreaLocalY; - return true; - } - if (pSceneTouchEvent.isActionUp()) { - - setFrame(0); - if (!moved) { - velocityY = 0; - - FilterMenu.getInstance().showMenu(SongMenu.this); - } - return true; - } - if (pSceneTouchEvent.isActionOutside() - || pSceneTouchEvent.isActionMove() - && (MathUtils.distance(dx, dy, pTouchAreaLocalX, - pTouchAreaLocalY) > 50)) { - moved = true; - setFrame(0); - } - return false; - } - }; - - final AnimSprite randomMap = new AnimSprite(0, 0, 0, - "selection-random", "selection-random-over") { - boolean moved = false; - private float dx = 0, dy = 0; - - - @Override - public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, - final float pTouchAreaLocalX, final float pTouchAreaLocalY) { - if (pSceneTouchEvent.isActionDown()) { - setFrame(1); - moved = false; - dx = pTouchAreaLocalX; - dy = pTouchAreaLocalY; - return true; - } - if (pSceneTouchEvent.isActionUp()) { - setFrame(0); - if (!isSelectComplete) { - return true; - } - if (!moved) { - velocityY = 0; - if (items.size() <= 1) { - return true; - } - int rnd = MathUtils.random(0, items.size() - 1); - int index = 0; - while (rnd > 0) { - rnd--; - int oldIndex = index; - do { - index = (index + 1) % items.size(); - if (index == oldIndex) - return true; - } while (!items.get(index).isVisible()); - } - if (!items.get(index).isVisible()) { - return true; - } - if (selectedItem == items.get(index)) { - return true; - } - ResourceManager.getInstance().getSound("menuclick") - .play(); - items.get(index).select(true, true); - } - return true; - } - if (pSceneTouchEvent.isActionOutside() - || pSceneTouchEvent.isActionMove() - && (MathUtils.distance(dx, dy, pTouchAreaLocalX, - pTouchAreaLocalY) > 50)) { - moved = true; - setFrame(0); - } - return false; - } - }; - - - modSelection.setScale(1.5f); - optionSelection.setScale(1.5f); - randomMap.setScale(1.5f); - if (SkinJson.get().isUseNewLayout()) { - if (layoutBackButton != null) { - layoutBackButton.baseApply(backButton); - } - if (layoutMods != null) { - layoutMods.baseApply(modSelection); - } - if (layoutOptions != null) { - layoutOptions.baseApply(optionSelection); - } - if (layoutRandom != null) { - layoutRandom.baseApply(randomMap); - } - backButton.setPosition(0, Config.getRES_HEIGHT() - backButton.getHeightScaled()); - modSelection.setPosition(backButton.getX() + backButton.getWidth(), - Config.getRES_HEIGHT() - modSelection.getHeightScaled()); - optionSelection.setPosition( - modSelection.getX() + modSelection.getWidthScaled(), - Config.getRES_HEIGHT() - optionSelection.getHeightScaled()); - randomMap.setPosition( - optionSelection.getX() + optionSelection.getWidthScaled(), - Config.getRES_HEIGHT() - randomMap.getHeightScaled()); - } else { - backButton.setPosition(0, Config.getRES_HEIGHT() - backButton.getHeight()); - modSelection.setPosition(backButton.getX() + backButton.getWidth(), - Config.getRES_HEIGHT() - Utils.toRes(90)); - optionSelection.setPosition( - modSelection.getX() + modSelection.getWidthScaled(), - Config.getRES_HEIGHT() - Utils.toRes(90)); - randomMap.setPosition( - optionSelection.getX() + optionSelection.getWidthScaled(), - Config.getRES_HEIGHT() - Utils.toRes(90)); - } - - - frontLayer.attachChild(backButton); - scene.registerTouchArea(backButton); - frontLayer.attachChild(modSelection); - scene.registerTouchArea(modSelection); - frontLayer.attachChild(optionSelection); - scene.registerTouchArea(optionSelection); - frontLayer.attachChild(randomMap); - scene.registerTouchArea(randomMap); - - if (OnlineScoring.getInstance().createSecondPanel() != null) { - OnlinePanel panel = OnlineScoring.getInstance().getSecondPanel(); - panel.detachSelf(); - panel.setPosition(randomMap.getX() + randomMap.getWidthScaled() - 18, Config.getRES_HEIGHT() - Utils.toRes(110)); - OnlineScoring.getInstance().loadAvatar(false); - frontLayer.attachChild(panel); - - - scoringSwitcher = new AnimSprite(Utils.toRes(5), Utils.toRes(10), 0, "ranking_enabled", "ranking_disabled") { - @Override - public boolean onAreaTouched(TouchEvent pSceneTouchEvent, - float pTouchAreaLocalX, float pTouchAreaLocalY) { - if (!pSceneTouchEvent.isActionDown()) return false; - board.cancleLoadAvatar(); - toggleScoringSwitcher(); - return true; - } - }; - scoringSwitcher.setFrame(1); - scoringSwitcher.setPosition(10, 10); - scene.registerTouchArea(scoringSwitcher); - frontLayer.attachChild(scoringSwitcher); - } - } - - public void toggleScoringSwitcher() { - if (board.isShowOnlineScores()) { - board.setShowOnlineScores(false); - board.init(selectedTrack); - scoringSwitcher.setFrame(1); - updateInfo(selectedTrack); - } else if (OnlineManager.getInstance().isStayOnline()) { - board.setShowOnlineScores(true); - board.init(selectedTrack); - setRank(); - } - } - - public void setRank() { - if (!board.isShowOnlineScores()) { - if (scoringSwitcher != null) { - scoringSwitcher.setFrame(1); - } - updateInfo(selectedTrack); - return; - } - scoringSwitcher.setFrame(0); - } - - public Scene getScene() { - return scene; - } - - public void setFilter(final String filter, final SortOrder order, - final boolean favsOnly, Set limit) { - String oldTrackFileName = ""; - if (selectedTrack != null) { - oldTrackFileName = selectedTrack.getFilename(); - } - if (!order.equals(sortOrder)) { - sortOrder = order; - tryReloadMenuItems(sortOrder); - sort(); - reSelectItem(oldTrackFileName); - } - if (filter == null || filterText.equals(filter)) { - if (favsOnly == this.favsOnly && limitC == limit) { - return; - } - } - limitC = limit; - filterText = filter; - camY = 0; - velocityY = 0; - final String lowerFilter = filter.toLowerCase(); - for (final MenuItem item : items) { - item.applyFilter(lowerFilter, favsOnly, limit); - } - if (favsOnly != this.favsOnly) { - this.favsOnly = favsOnly; - } else { - reSelectItem(oldTrackFileName); - } - if (selectedItem != null && !selectedItem.isVisible()) { - selectedItem = null; - selectedTrack = null; - } - System.gc(); - } - - public void sort() { - if (!sortOrder.equals(FilterMenu.getInstance().getOrder())) { - sortOrder = FilterMenu.getInstance().getOrder(); - } - Collections.sort(items, (i1, i2) -> { - String s1; - String s2; - switch (sortOrder) { - case Artist: - s1 = i1.getBeatmap().getArtist(); - s2 = i2.getBeatmap().getArtist(); - break; - case Creator: - s1 = i1.getBeatmap().getCreator(); - s2 = i2.getBeatmap().getCreator(); - break; - case Date: - final Long int1 = i1.getBeatmap().getDate(); - final Long int2 = i2.getBeatmap().getDate(); - return int2.compareTo(int1); - case Bpm: - final float bpm1 = i1.getFirstTrack().getBpmMax(); - final float bpm2 = i2.getFirstTrack().getBpmMax(); - return Float.compare(bpm2, bpm1); - case Stars: - final float float1 = i1.getFirstTrack().getDifficulty(); - final float float2 = i2.getFirstTrack().getDifficulty(); - return Float.compare(float2, float1); - case Length: - final Long length1 = i1.getFirstTrack().getMusicLength(); - final Long length2 = i2.getFirstTrack().getMusicLength(); - return length2.compareTo(length1); - default: - s1 = i1.getBeatmap().getTitle(); - s2 = i2.getBeatmap().getTitle(); - } - - return s1.compareToIgnoreCase(s2); - }); - } - - public void onUpdate(final float pSecondsElapsed) { - secPassed += pSecondsElapsed; - increaseVolume(); - increaseBackgroundLuminance(pSecondsElapsed); - - secondsSinceLastSelect += pSecondsElapsed; - float oy = -camY; - for (final MenuItem item : items) { - final float cy = oy + Config.getRES_HEIGHT() / 2f + item.getHeight() - / 2; - float ox = Config.getRES_WIDTH() / 1.85f + 200 * (float) Math.abs(Math.cos(cy * Math.PI - / (Config.getRES_HEIGHT() * 2))); - ox = Utils.toRes(ox); - item.setPos(ox, oy); - oy += item.getHeight(); - } - oy += camY; - camY += velocityY * pSecondsElapsed; - maxY = oy - Config.getRES_HEIGHT() / 2f; - if (camY <= -Config.getRES_HEIGHT() / 2f && velocityY < 0 - || camY >= maxY && velocityY > 0) { - camY -= velocityY * pSecondsElapsed; - velocityY = 0; - } - if (Math.abs(velocityY) > Utils.toRes(1000) * pSecondsElapsed) { - velocityY -= Utils.toRes(1000) * pSecondsElapsed - * Math.signum(velocityY); - } else { - velocityY = 0; - } - - expandSelectedItem(pSecondsElapsed); - - board.update(pSecondsElapsed); - updateScrollbar(camY + Config.getRES_HEIGHT() / 2f, oy); - } - - public void increaseVolume() { - if (GlobalManager.getInstance().getSongService() != null) { - synchronized (musicMutex) { - if (GlobalManager.getInstance().getSongService() != null && GlobalManager.getInstance().getSongService().getStatus() == Status.PLAYING && GlobalManager.getInstance().getSongService().getVolume() < Config.getBgmVolume()) { - float vol = Math.min(1, GlobalManager.getInstance().getSongService().getVolume() + 0.01f); - GlobalManager.getInstance().getSongService().setVolume(vol); - } - } - } - } - - public void increaseBackgroundLuminance(final float pSecondsElapsed) { - if (bg != null) { - synchronized (backgroundMutex) { - if (bg != null && bg.getRed() < 1) { - final float col = Math.min(1, bg.getRed() + pSecondsElapsed); - bg.setColor(col, col, col); - } - } - } - } - - public void expandSelectedItem(float pSecondsElapsed) { - if (selectedItem != null) { - if (selectedItem.percentAppeared < 1) { - selectedItem.percentAppeared += 2 * pSecondsElapsed; - } else { - selectedItem.percentAppeared = 1; - } - selectedItem.update(pSecondsElapsed); - } - } - - public void updateScrollbar(final float vy, final float maxy) { - scrollbar.setPosition(vy, maxy); - scrollbar.setVisible(Math.abs(velocityY) > Utils.toRes(500)); - } - - public void reset() { - } - - public void select(final MenuItem item) { - secondsSinceLastSelect = 0; - if (selectedItem != null) { - selectedItem.deselect(); - } - - selectedItem = item; - velocityY = 0; - selectedTrack = null; - float height = 0; - for (int i = 0; i < items.size(); i++) { - if (items.get(i) == selectedItem) { - break; - } - height += items.get(i).getInitialHeight(); - } - camY = height - Config.getRES_HEIGHT() / 2f; - camY += item.getTotalHeight() / 2; - } - - @SuppressLint("SimpleDateFormat") - public void changeDimensionInfo(TrackInfo track) { - if (track == null) { - return; - } - float ar = track.getApproachRate(); - float od = track.getOverallDifficulty(); - float cs = track.getCircleSize(); - float hp = track.getHpDrain(); - float bpm_max = track.getBpmMax(); - float bpm_min = track.getBpmMin(); - long length = track.getMusicLength(); - EnumSet mod = ModMenu.getInstance().getMod(); - - dimensionInfo.setColor(1, 1, 1); - beatmapInfo.setColor(1, 1, 1); - - if (mod.contains(GameMod.MOD_EASY)) { - ar *= 0.5f; - od *= 0.5f; - cs -= 1f; - hp *= 0.5f; - dimensionInfo.setColor(46 / 255f, 139 / 255f, 87 / 255f); - } - if (mod.contains(GameMod.MOD_HARDROCK)) { - ar *= 1.4f; - if (ar > 10) { - ar = 10; - } - od *= 1.4f; - cs += 1f; - hp *= 1.4f; - dimensionInfo.setColor(205 / 255f, 85 / 255f, 85 / 255f); - } - if (ModMenu.getInstance().getChangeSpeed() != 1) { - float speed = ModMenu.getInstance().getSpeed(); - bpm_max *= speed; - bpm_min *= speed; - length /= speed; - if (speed > 1) { - beatmapInfo.setColor(205 / 255f, 85 / 255f, 85 / 255f); - dimensionInfo.setColor(205 / 255f, 85 / 255f, 85 / 255f); - } else if (speed < 1) { - beatmapInfo.setColor(46 / 255f, 139 / 255f, 87 / 255f); - dimensionInfo.setColor(46 / 255f, 139 / 255f, 87 / 255f); - } - } else { - if (mod.contains(GameMod.MOD_DOUBLETIME)) { - bpm_max *= 1.5f; - bpm_min *= 1.5f; - length *= 2 / 3f; - beatmapInfo.setColor(205 / 255f, 85 / 255f, 85 / 255f); - dimensionInfo.setColor(205 / 255f, 85 / 255f, 85 / 255f); - } - if (mod.contains(GameMod.MOD_NIGHTCORE)) { - bpm_max *= 1.5f; - bpm_min *= 1.5f; - length *= 2 / 3f; - beatmapInfo.setColor(205 / 255f, 85 / 255f, 85 / 255f); - dimensionInfo.setColor(205 / 255f, 85 / 255f, 85 / 255f); - } - if (mod.contains(GameMod.MOD_HALFTIME)) { - bpm_max *= 0.75f; - bpm_min *= 0.75f; - length *= 4 / 3f; - beatmapInfo.setColor(46 / 255f, 139 / 255f, 87 / 255f); - dimensionInfo.setColor(46 / 255f, 139 / 255f, 87 / 255f); - } - } - if (mod.contains(GameMod.MOD_REALLYEASY)) { - if (mod.contains(GameMod.MOD_EASY)) { - ar *= 2f; - ar -= 0.5f; - } - ar -= 0.5f; - if (ModMenu.getInstance().getChangeSpeed() != 1) { - ar -= ModMenu.getInstance().getSpeed() - 1.0f; - } else if (mod.contains(GameMod.MOD_DOUBLETIME) || mod.contains(GameMod.MOD_NIGHTCORE)) { - ar -= 0.5f; - } - od *= 0.5f; - cs -= 1f; - hp *= 0.5f; - dimensionInfo.setColor(46 / 255f, 139 / 255f, 87 / 255f); - } - if (mod.contains(GameMod.MOD_SMALLCIRCLE)) { - cs += 4f; - dimensionInfo.setColor(205 / 255f, 85 / 255f, 85 / 255f); - } - // - @SuppressLint("SimpleDateFormat") SimpleDateFormat sdf = new SimpleDateFormat("mm:ss"); - sdf.setTimeZone(TimeZone.getTimeZone("GMT+0")); - String binfoStr = String.format(StringTable.get(R.string.binfoStr1), sdf.format(length), - (bpm_min == bpm_max ? GameHelper.Round(bpm_min, 1) : GameHelper.Round(bpm_min, 1) + "-" + GameHelper.Round(bpm_max, 1)), - track.getMaxCombo()); - if (length > 3600 * 1000) { - sdf = new SimpleDateFormat("HH:mm:ss"); - sdf.setTimeZone(TimeZone.getTimeZone("GMT+0")); - binfoStr = String.format(StringTable.get(R.string.binfoStr1), sdf.format(length), - (bpm_min == bpm_max ? GameHelper.Round(bpm_min, 1) : GameHelper.Round(bpm_min, 1) + "-" + GameHelper.Round(bpm_max, 1)), - track.getMaxCombo()); - } - beatmapInfo.setText(binfoStr); - - final StringBuilder dimensionStringBuilder = new StringBuilder(); - ar = Math.min(13.f, ar); - od = Math.min(10.f, od); - cs = Math.min(15.f, cs); - hp = Math.min(10.f, hp); - if (ModMenu.getInstance().getChangeSpeed() != 1) { - float speed = ModMenu.getInstance().getSpeed(); - ar = GameHelper.Round(GameHelper.ms2ar(GameHelper.ar2ms(ar) / speed), 2); - od = GameHelper.Round(GameHelper.ms2od(GameHelper.od2ms(od) / speed), 2); - } else if (mod.contains(GameMod.MOD_DOUBLETIME) || mod.contains(GameMod.MOD_NIGHTCORE)) { - ar = GameHelper.Round(GameHelper.ms2ar(GameHelper.ar2ms(ar) * 2 / 3), 2); - od = GameHelper.Round(GameHelper.ms2od(GameHelper.od2ms(od) * 2 / 3), 2); - } else if (mod.contains(GameMod.MOD_HALFTIME)) { - ar = GameHelper.Round(GameHelper.ms2ar(GameHelper.ar2ms(ar) * 4 / 3), 2); - od = GameHelper.Round(GameHelper.ms2od(GameHelper.od2ms(od) * 4 / 3), 2); - } - if (ModMenu.getInstance().isEnableForceAR()) { - float oriAr = ar; - ar = ModMenu.getInstance().getForceAR(); - if (ar > oriAr) { - dimensionInfo.setColor(205 / 255f, 85 / 255f, 85 / 255f); - } else if (ar < oriAr) { - dimensionInfo.setColor(46 / 255f, 139 / 255f, 87 / 255f); - } - } - dimensionStringBuilder.append("AR: ").append(GameHelper.Round(ar, 2)).append(" ") - .append("OD: ").append(GameHelper.Round(od, 2)).append(" ") - .append("CS: ").append(GameHelper.Round(cs, 2)).append(" ") - .append("HP: ").append(GameHelper.Round(hp, 2)).append(" ") - .append("Stars: ").append(GameHelper.Round(track.getDifficulty(), 2)); - - dimensionInfo.setText(dimensionStringBuilder.toString()); - } - - public void updateInfo(TrackInfo track) { - if (track == null) { - return; - } - - String tinfoStr = (track.getBeatmap().getArtistUnicode() == null || Config.isForceRomanized() ? track.getBeatmap().getArtist() : track.getBeatmap().getArtistUnicode()) + " - " + - (track.getBeatmap().getTitleUnicode() == null || Config.isForceRomanized() ? track.getBeatmap().getTitle() : track.getBeatmap().getTitleUnicode()) + " [" + track.getMode() + "]"; - String mapperStr = "Beatmap by " + track.getCreator(); - String binfoStr2 = String.format(StringTable.get(R.string.binfoStr2), - track.getHitCircleCount(), track.getSliderCount(), track.getSpinnerCount(), track.getBeatmapSetID()); - trackInfo.setText(tinfoStr); - mapper.setText(mapperStr); - beatmapInfo2.setText(binfoStr2); - changeDimensionInfo(track); - (new Thread() { - public void run() { - DifficultyReCalculator diffReCalculator = new DifficultyReCalculator(); - float newstar = diffReCalculator.recalculateStar( - selectedTrack, - diffReCalculator.getCS(selectedTrack), - ModMenu.getInstance().getSpeed() - ); - - if (newstar != 0f) { - setStarsDisplay(newstar); - } - } - }).start(); - } - - public void selectTrack(final TrackInfo track, boolean reloadBG) { -// BassAudioProvider provider = BassAudioPlayer.getProvider(); -// if (provider != null && provider.getStatus() != Status.STOPPED) { -// provider.stop(); -// } - new Thread() { - @Override - public void run() { - if (board.isShowOnlineScores()) setRank(); - } - }.start(); - - if (selectedTrack == track) { - synchronized (bgLoaded) { - if (!bgLoaded) { - return; - } - } - - ResourceManager.getInstance().getSound("menuhit").play(); - stopMusic(); - game.startGame(track, null); - unload(); - return; - } - isSelectComplete = false; - selectedTrack = track; - EdExtensionHelper.onSelectTrack(selectedTrack); - GlobalManager.getInstance().setSelectedTrack(track); - updateInfo(track); - board.cancleLoadAvatar(); - if (boardTask != null && boardTask.getStatus() != AsyncTask.Status.FINISHED) { - boardTask.cancel(true); - board.cancleLoadOnlineScores(); - } - boardTask = new AsyncTaskLoader().execute(new OsuAsyncCallback() { - @Override - public void run() { - board.init(track); - } - - @Override - public void onComplete() { - // Do something cleanup - } - }); - - final int quality = Config.getBackgroundQuality(); - synchronized (backgroundMutex) { - - if (!reloadBG && bgName.equals(track.getBackground())) { - isSelectComplete = true; - return; - } - bgName = track.getBackground(); - bg = null; - bgLoaded = false; - scene.setBackground(new ColorBackground(0, 0, 0)); - if (quality == 0) { - Config.setBackgroundQuality(4); - } - } - new AsyncTaskLoader().execute(new OsuAsyncCallback() { - - - public void run() { - // Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); - synchronized (backgroundMutex) { - final TextureRegion tex = Config.isSafeBeatmapBg() ? - ResourceManager.getInstance().getTexture("menu-background") : - ResourceManager.getInstance().loadBackground(bgName); - if (tex != null) { - float height = tex.getHeight(); - height *= Config.getRES_WIDTH() - / (float) tex.getWidth(); - bg = new Sprite(0, - (Config.getRES_HEIGHT() - height) / 2, Config - .getRES_WIDTH(), height, tex); - bg.setColor(0, 0, 0); - } - - // run() - SyncTaskManager.getInstance().run(() -> { - synchronized (backgroundMutex) { - if (bg == null) { - final TextureRegion tex1 = ResourceManager - .getInstance().getTexture("menu-background"); - float height = tex1.getHeight(); - height *= Config.getRES_WIDTH() - / (float) tex1.getWidth(); - bg = new Sprite( - 0, - (Config.getRES_HEIGHT() - height) / 2, - Config.getRES_WIDTH(), height, tex1); - bgName = ""; - } - scene.setBackground(new SpriteBackground(bg)); - Config.setBackgroundQuality(quality); - synchronized (bgLoaded) { - bgLoaded = true; - } - } - });// SyncTask.run - - } - } - - - public void onComplete() { - isSelectComplete = true; - }// onComplete - }); - } - - public void stopScroll(final float y) { - velocityY = 0; - touchY = y; - initalY = -1; - } - - public void updateScore() { - board.init(selectedTrack); - if (selectedItem != null) { - selectedItem.updateMarks(); - } - } - - public void openScore(final int id, boolean showOnline, final String playerName) { - if (showOnline) { - engine.setScene(new LoadingScreen().getScene()); - ToastLogger.showTextId(R.string.online_loadrecord, false); - new AsyncTaskLoader().execute(new OsuAsyncCallback() { - - - public void run() { - try { - String scorePack = OnlineManager.getInstance().getScorePack(id); - String[] params = scorePack.split("\\s+"); - if (params.length < 11) return; - - StatisticV2 stat = new StatisticV2(params); - stat.setPlayerName(playerName); - scoreScene.load(stat, null, null, OnlineManager.getReplayURL(id), null, selectedTrack); - engine.setScene(scoreScene.getScene()); - - } catch (OnlineManagerException e) { - Debug.e("Cannot load play info: " + e.getMessage(), e); - engine.setScene(scene); - } - - } - - public void onComplete() { - // TODO Auto-generated method stub - } - }); - return; - } - - - StatisticV2 stat = ScoreLibrary.getInstance().getScore(id); - scoreScene.load(stat, null, null, stat.getReplayName(), null, selectedTrack); - engine.setScene(scoreScene.getScene()); - } - - - public void onScroll(final float where) { - velocityY = 0; - camY = where - Config.getRES_HEIGHT() / 2f; - } - - public void unload() { - } - - public void back() { - unbindDataBaseChangedListener(); - GlobalManager.getInstance().getMainScene().show(); - } - - public void bindDataBaseChangedListener() { - OdrDatabase.get().setOnDatabaseChangedListener(this::reloadScoreBroad); - } - - public void unbindDataBaseChangedListener() { - OdrDatabase.get().setOnDatabaseChangedListener(null); - } - - public void setY(final float y) { - velocityY = 0; - camY = y; - } - - public void stopMusic() { - synchronized (musicMutex) { - if (GlobalManager.getInstance().getSongService() != null) { - GlobalManager.getInstance().getSongService().stop(); - } - } - } - - public void playMusic(final String filename, final int previewTime) { - if (!Config.isPlayMusicPreview()) { - return; - } - new AsyncTaskLoader().execute(new OsuAsyncCallback() { - - - public void run() { - Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); - synchronized (musicMutex) { - if (GlobalManager.getInstance().getSongService() != null) { - GlobalManager.getInstance().getSongService().stop(); - } - - try { -// GlobalManager.getInstance().getSongService().preLoadWithLoop(filename); - GlobalManager.getInstance().getSongService().preLoad(filename); - GlobalManager.getInstance().getSongService().play(); - GlobalManager.getInstance().getSongService().setVolume(0); - if (previewTime >= 0) { - GlobalManager.getInstance().getSongService().seekTo(previewTime); - } else { - GlobalManager.getInstance().getSongService().seekTo(GlobalManager.getInstance().getSongService().getLength() / 2); - } - } catch (final Exception e) { - Debug.e("LoadingMusic: " + e.getMessage(), e); - } - - } - } - - - public void onComplete() { - // TODO Auto-generated method stub - - } - }); - } - - public boolean isSelectAllowed() { - if (!bgLoaded) { - return false; - } - return secondsSinceLastSelect > 0.5f; - } - - public void showPropertiesMenu(MenuItem item) { - if (item == null) { - if (selectedItem == null) { - return; - } - item = selectedItem; - } - (new PropsMenuFragment()).show(SongMenu.this, item); - } - - public void showDeleteScoreMenu(int scoreId) { - (new ScoreMenuFragment()).show(scoreId); - //ScorePropsMenu.getInstance().setSongMenu(SongMenu.this); - //ScorePropsMenu.getInstance().setScoreId(scoreId); - //scene.setChildScene(ScorePropsMenu.getInstance().getScene(), false, true, true); - } - - public void reloadScoreBroad() { - board.cancleLoadAvatar(); - if (boardTask != null && boardTask.getStatus() != AsyncTask.Status.FINISHED) { - boardTask.cancel(true); - board.cancleLoadOnlineScores(); - } - boardTask = new AsyncTaskLoader().execute(new OsuAsyncCallback() { - @Override - public void run() { - board.init(selectedTrack); - } - - @Override - public void onComplete() { - // Do something cleanup - } - }); - } - - public Entity getFrontLayer() { - return frontLayer; - } - - public Entity getBackLayer() { - return backLayer; - } - - public void select() { - if (GlobalManager.getInstance().getMainScene().getBeatmapInfo() != null) { - BeatmapInfo beatmapInfo = GlobalManager.getInstance().getMainScene().getBeatmapInfo(); - for (int i = 0; i < items.size(); i++) { - if (items.get(i).getBeatmap().getArtist().equals(beatmapInfo.getArtist()) && - items.get(i).getBeatmap().getTitle().equals(beatmapInfo.getTitle()) && - items.get(i).getBeatmap().getCreator().equals(beatmapInfo.getCreator())) { - secondsSinceLastSelect = 2; - items.get(i).select(false, true); - break; - } - } - } - } - - public TrackInfo getSelectedTrack() { - return selectedTrack; - } - - public boolean checkBG(String filePath) { - if (filePath == null) return false; - if (filePath.trim().equals("")) return false; - - BitmapFactory.Options bgOption = new BitmapFactory.Options(); - bgOption.inJustDecodeBounds = true; - int w = BitmapFactory.decodeFile(filePath).getWidth(); - int h = BitmapFactory.decodeFile(filePath).getHeight(); - bgOption.inJustDecodeBounds = false; - bgOption = null; - return (w * h) > 0; - } - - private void tryReloadMenuItems(SortOrder order) { - switch (order) { - case Title: - case Artist: - case Creator: - case Date: - case Bpm: - reloadMenuItems(GroupType.MapSet); - break; - case Stars: - case Length: - reloadMenuItems(GroupType.SingleDiff); - break; - } - } - - private void reloadMenuItems(GroupType type) { - if (!groupType.equals(type)) { - groupType = type; - float oy = 10; - for (MenuItem item : items) { - item.removeFromScene(); - } - items.clear(); - switch (type) { - case MapSet: - for (final BeatmapInfo i : LibraryManager.getInstance().getLibrary()) { - final MenuItem item = new MenuItem(this, i); - items.add(item); - item.attachToScene(scene, backLayer); - oy += item.getHeight(); - } - break; - case SingleDiff: - for (final BeatmapInfo i : LibraryManager.getInstance().getLibrary()) { - for (int j = 0; j < i.getCount(); j++) { - final MenuItem item = new MenuItem(this, i, j); - items.add(item); - item.attachToScene(scene, backLayer); - oy += item.getHeight(); - } - } - break; - } - final String lowerFilter = FilterMenu.getInstance().getFilter().toLowerCase(); - final boolean favsOnly = FilterMenu.getInstance().isFavoritesOnly(); - final Set limit = FilterMenu.getInstance().getFavoriteFolder() == null ? null : FavoriteLibrary.get().getMaps(FilterMenu.getInstance().getFavoriteFolder()); - for (final MenuItem item : items) { - item.applyFilter(lowerFilter, favsOnly, limit); - } - System.gc(); - } - } - - public void setStarsDisplay(float star) { - String str = dimensionInfo.getText(); - String[] strs = str.split("Stars: "); - if (strs.length == 2) { - dimensionInfo.setText(strs[0] + "Stars: " + star); - } - } - - private void reSelectItem(String oldTrackFileName) { - if (!oldTrackFileName.equals("")) { - if (selectedTrack.getFilename().equals(oldTrackFileName) && items.size() > 1 && selectedItem != null && selectedItem.isVisible()) { - velocityY = 0; - float height = 0; - for (int i = 0; i < items.size(); i++) { - if (items.get(i) == selectedItem) { - break; - } - height += items.get(i).getInitialHeight(); - } - camY = height - Config.getRES_HEIGHT() / 2f; - camY += items.get(0).getTotalHeight() / 2; - return; - } - for (final MenuItem item : items) { - if (item == null || !item.isVisible()) continue; - int trackid = item.tryGetCorrespondingTrackId(oldTrackFileName); - if (trackid >= 0) { - item.select(true, true); - if (trackid != 0) { - item.selectTrack(item.getTrackSpritesById(trackid), false); - } - break; - } - } - } - } - - public enum SortOrder { - Title, Artist, Creator, Date, Bpm, Stars, Length - } - - public enum GroupType { - MapSet, SingleDiff - } + IScrollBarListener { + private final static Boolean musicMutex = true; + private final Boolean backgroundMutex = true; + public Scene scene; + public Entity frontLayer = new Entity(); + SortOrder sortOrder = SortOrder.Title; + private Engine engine; + private GameScene game; + private ScoringScene scoreScene; + private float camY = 0; + private float velocityY; + private Activity context; + private Entity backLayer = new Entity(); + private ArrayList items = new ArrayList<>(); + private MenuItem selectedItem = null; + private TrackInfo selectedTrack; + private Sprite bg = null; + private Boolean bgLoaded = false; + private String bgName = ""; + private ScoreBoard board; + private Float touchY = null; + private String filterText = ""; + private boolean favsOnly = false; + private Set limitC; + private float secondsSinceLastSelect = 0; + private float maxY = 100500; + private int pointerId = -1; + private float initalY = -1; + private float secPassed = 0, tapTime; + private Sprite backButton = null; + private ScrollBar scrollbar; + private ChangeableText trackInfo, mapper, beatmapInfo, beatmapInfo2, dimensionInfo; + private boolean isSelectComplete = true; + private AnimSprite scoringSwitcher = null; + private AsyncTask boardTask; + private GroupType groupType = GroupType.MapSet; + + public SongMenu() { + } + + public static void stopMusicStatic() { + synchronized (musicMutex) { + if (GlobalManager.getInstance().getSongService() != null) { + GlobalManager.getInstance().getSongService().stop(); + } + } + } + + public void setScoringScene(final ScoringScene ss) { + scoreScene = ss; + } + + public ScoreBoard.ScoreBoardItems[] getBoard() { + return board.getScoreBoardItems(); + } + + public boolean isBoardOnline() { + return board.isShowOnlineScores(); + } + + public ArrayList getMenuItems() { + return items; + } + + public void init(final Activity context, final Engine engine, + final GameScene pGame) { + this.engine = engine; + game = pGame; + this.context = context; + } + + public void loadFilter(IFilterMenu filterMenu) { + setFilter(filterMenu.getFilter(), filterMenu.getOrder(), filterMenu.isFavoritesOnly(), + filterMenu.getFavoriteFolder() == null ? null : FavoriteLibrary.get().getMaps(filterMenu.getFavoriteFolder())); + } + + public void reload() { + frontLayer = new Entity(); + backLayer = new Entity(); + scene.unregisterUpdateHandler(this); + scene.setTouchAreaBindingEnabled(false); + load(); + GlobalManager.getInstance().getGameScene().setOldScene(scene); + } + + public synchronized void load() { + scene = new Scene(); + camY = 0; + velocityY = 0; + selectedItem = null; + items = new ArrayList<>(); + selectedTrack = null; + bgLoaded = true; + SongMenuPool.getInstance().init(); + FilterMenu.getInstance().loadConfig(context); + ModMenu.getInstance().reload(); + bindDataBaseChangedListener(); + + scene.attachChild(backLayer); + scene.attachChild(frontLayer); + + final TextureRegion tex = ResourceManager.getInstance().getTexture("menu-background"); + float height = tex.getHeight(); + height *= Config.getRES_WIDTH() / (float) tex.getWidth(); + final Sprite bg = new Sprite(0, (Config.getRES_HEIGHT() - height) / 2, + Config.getRES_WIDTH(), height, tex); + scene.setBackground(new SpriteBackground(bg)); + + final Rectangle bgDimRect = new Rectangle(0, 0, Config.getRES_WIDTH(), Config.getRES_HEIGHT()); + bgDimRect.setColor(0, 0, 0, 0.2f); + backLayer.attachChild(bgDimRect); + + board = new ScoreBoard(scene, backLayer, this, context); + + float oy = 10; + for (final BeatmapInfo i : LibraryManager.getInstance().getLibrary()) { + final MenuItem item = new MenuItem(this, i); + items.add(item); + item.attachToScene(scene, backLayer); + oy += item.getHeight(); + } + sortOrder = SortOrder.Title; + sort(); + + if (items.size() == 0) { + final Text text = new Text(0, 0, ResourceManager.getInstance() + .getFont("CaptionFont"), "There are no songs in library", + HorizontalAlign.CENTER); + text.setPosition(Config.getRES_WIDTH() / 2f - text.getWidth() / 2, + Config.getRES_HEIGHT() / 2f - text.getHeight() / 2); + text.setScale(1.5f); + text.setColor(0, 0, 0); + scene.attachChild(text); + return; + } + + scene.setOnSceneTouchListener((pScene, evt) -> { + if (evt.getX() < Config.getRES_WIDTH() / 5f * 2) { + return false; + } + switch (evt.getAction()) { + case (TouchEvent.ACTION_DOWN): + velocityY = 0; + touchY = evt.getY(); + pointerId = evt.getPointerID(); + tapTime = secPassed; + initalY = touchY; + break; + case (TouchEvent.ACTION_MOVE): + if (pointerId != -1 && pointerId != evt.getPointerID()) { + break; + } + if (initalY == -1) { + velocityY = 0; + touchY = evt.getY(); + initalY = touchY; + tapTime = secPassed; + pointerId = evt.getPointerID(); + } + final float dy = evt.getY() - touchY; + + camY -= dy; + touchY = evt.getY(); + if (camY <= -Config.getRES_HEIGHT() / 2f) { + camY = -Config.getRES_HEIGHT() / 2f; + velocityY = 0; + } else if (camY >= maxY) { + camY = maxY; + velocityY = 0; + } + + // velocityY = -3f * dy; + break; + default: { + if (pointerId != -1 && pointerId != evt.getPointerID()) { + break; + } + touchY = null; + if (secPassed - tapTime < 0.001f || initalY == -1) { + velocityY = 0; + } else { + velocityY = (initalY - evt.getY()) + / (secPassed - tapTime); + } + pointerId = -1; + initalY = -1; + + } + break; + } + return true; + }); + + scene.registerUpdateHandler(this); + scene.setTouchAreaBindingEnabled(true); + + scrollbar = new ScrollBar(scene); + + /*final Rectangle bgTopRect = new Rectangle(0, 0, Config.getRES_WIDTH(), Utils.toRes(170)); + bgTopRect.setColor(0, 0, 0, 0.8f);*/ + final TextureRegion songSelectTopTexture = ResourceManager.getInstance().getTexture("songselect-top"); + final Sprite songSelectTop = new Sprite(0, 0, songSelectTopTexture); + songSelectTop.setSize(songSelectTopTexture.getWidth() * songSelectTopTexture.getHeight() / 184f, 184); + songSelectTop.setPosition(-1640, songSelectTop.getY()); + songSelectTop.setAlpha(0.6f); + frontLayer.attachChild(songSelectTop); + + /*final Rectangle bgbottomRect = new Rectangle(0, 0, Config.getRES_WIDTH(), Utils.toRes(110)); + bgbottomRect.setPosition(0, Config.getRES_HEIGHT() - bgbottomRect.getHeight()); + bgbottomRect.setColor(0, 0, 0, 0.8f); + frontLayer.attachChild(bgbottomRect);*/ + + trackInfo = new ChangeableText(Utils.toRes(70), Utils.toRes(2), + ResourceManager.getInstance().getFont("font"), "title", 1024); + frontLayer.attachChild(trackInfo); + + mapper = new ChangeableText(Utils.toRes(70), trackInfo.getY() + trackInfo.getHeight() + Utils.toRes(2), + ResourceManager.getInstance().getFont("middleFont"), "mapper", 1024); + frontLayer.attachChild(mapper); + + beatmapInfo = new ChangeableText(Utils.toRes(4), mapper.getY() + mapper.getHeight() + Utils.toRes(2), + ResourceManager.getInstance().getFont("middleFont"), "beatmapInfo", 1024); + frontLayer.attachChild(beatmapInfo); + + beatmapInfo2 = new ChangeableText(Utils.toRes(4), beatmapInfo.getY() + beatmapInfo.getHeight() + Utils.toRes(2), + ResourceManager.getInstance().getFont("middleFont"), "beatmapInfo2", 1024); + frontLayer.attachChild(beatmapInfo2); + + dimensionInfo = new ChangeableText(Utils.toRes(4), beatmapInfo2.getY() + beatmapInfo2.getHeight() + Utils.toRes(2), + ResourceManager.getInstance().getFont("smallFont"), "dimensionInfo", 1024); + frontLayer.attachChild(dimensionInfo); + + SkinJson.Layout layoutBackButton = SkinJson.get().getLayout("BackButton"); + SkinJson.Layout layoutMods = SkinJson.get().getLayout("ModsButton"); + SkinJson.Layout layoutOptions = SkinJson.get().getLayout("OptionsButton"); + SkinJson.Layout layoutRandom = SkinJson.get().getLayout("RandomButton"); + + if (ResourceManager.getInstance().isTextureLoaded("menu-back-0")) { + List loadedBackTextures = new ArrayList<>(); + for (int i = 0; i < 60; i++) { + if (ResourceManager.getInstance().isTextureLoaded("menu-back-" + i)) + loadedBackTextures.add("menu-back-" + i); + } + backButton = new AnimSprite(0, 0, loadedBackTextures.size(), loadedBackTextures.toArray(new String[0])) { + boolean moved = false; + float dx = 0, dy = 0; + boolean scaleWhenHold = true; + + { + if (layoutBackButton != null) { + scaleWhenHold = layoutBackButton.property.optBoolean("scaleWhenHold", true); + } + } + + @Override + public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, + final float pTouchAreaLocalX, final float pTouchAreaLocalY) { + if (pSceneTouchEvent.isActionDown()) { + if (scaleWhenHold) backButton.setScale(1.25f); + moved = false; + dx = pTouchAreaLocalX; + dy = pTouchAreaLocalY; + BassSoundProvider playSnd = ResourceManager.getInstance().getSound("menuback"); + if (playSnd != null) { + playSnd.play(); + } + return true; + } + if (pSceneTouchEvent.isActionUp()) { + // back + if (selectedTrack == null) { + return true; + } + if (!moved) { + backButton.setScale(1f); + back(); + } + return true; + } + if (pSceneTouchEvent.isActionOutside() + || pSceneTouchEvent.isActionMove() + && (MathUtils.distance(dx, dy, pTouchAreaLocalX, + pTouchAreaLocalY) > 50)) { + backButton.setScale(1f); + moved = true; + } + return false; + } + }; + } else { + backButton = new Sprite(0, 0, ResourceManager.getInstance().getTexture("menu-back")) { + boolean moved = false; + float dx = 0, dy = 0; + boolean scaleWhenHold = true; + + { + if (layoutBackButton != null) { + scaleWhenHold = layoutBackButton.property.optBoolean("scaleWhenHold", true); + } + } + + @Override + public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, + final float pTouchAreaLocalX, final float pTouchAreaLocalY) { + if (pSceneTouchEvent.isActionDown()) { + if (scaleWhenHold) backButton.setScale(1.25f); + moved = false; + dx = pTouchAreaLocalX; + dy = pTouchAreaLocalY; + BassSoundProvider playSnd = ResourceManager.getInstance().getSound("menuback"); + if (playSnd != null) { + playSnd.play(); + } + return true; + } + if (pSceneTouchEvent.isActionUp()) { + // back + if (selectedTrack == null) { + return true; + } + if (!moved) { + backButton.setScale(1f); + back(); + } + return true; + } + if (pSceneTouchEvent.isActionOutside() + || pSceneTouchEvent.isActionMove() + && (MathUtils.distance(dx, dy, pTouchAreaLocalX, + pTouchAreaLocalY) > 50)) { + backButton.setScale(1f); + moved = true; + } + return false; + } + }; + } + + final AnimSprite modSelection = new AnimSprite(0, 0, 0, + "selection-mods", "selection-mods-over") { + boolean moved = false; + private float dx = 0, dy = 0; + + + @Override + public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, + final float pTouchAreaLocalX, final float pTouchAreaLocalY) { + if (pSceneTouchEvent.isActionDown()) { + setFrame(1); + moved = false; + dx = pTouchAreaLocalX; + dy = pTouchAreaLocalY; + return true; + } + if (pSceneTouchEvent.isActionUp()) { + setFrame(0); + if (!moved) { + velocityY = 0; + ModMenu.getInstance().show(SongMenu.this, selectedTrack); + } + return true; + } + if (pSceneTouchEvent.isActionOutside() + || pSceneTouchEvent.isActionMove() + && (MathUtils.distance(dx, dy, pTouchAreaLocalX, + pTouchAreaLocalY) > 50)) { + moved = true; + setFrame(0); + } + return false; + } + }; + + final AnimSprite optionSelection = new AnimSprite(0, 0, 0, + "selection-options", "selection-options-over") { + boolean moved = false; + private float dx = 0, dy = 0; + + + @Override + public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, + final float pTouchAreaLocalX, final float pTouchAreaLocalY) { + if (pSceneTouchEvent.isActionDown()) { + setFrame(1); + moved = false; + dx = pTouchAreaLocalX; + dy = pTouchAreaLocalY; + return true; + } + if (pSceneTouchEvent.isActionUp()) { + + setFrame(0); + if (!moved) { + velocityY = 0; + + FilterMenu.getInstance().showMenu(SongMenu.this); + } + return true; + } + if (pSceneTouchEvent.isActionOutside() + || pSceneTouchEvent.isActionMove() + && (MathUtils.distance(dx, dy, pTouchAreaLocalX, + pTouchAreaLocalY) > 50)) { + moved = true; + setFrame(0); + } + return false; + } + }; + + final AnimSprite randomMap = new AnimSprite(0, 0, 0, + "selection-random", "selection-random-over") { + boolean moved = false; + private float dx = 0, dy = 0; + + + @Override + public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, + final float pTouchAreaLocalX, final float pTouchAreaLocalY) { + if (pSceneTouchEvent.isActionDown()) { + setFrame(1); + moved = false; + dx = pTouchAreaLocalX; + dy = pTouchAreaLocalY; + return true; + } + if (pSceneTouchEvent.isActionUp()) { + setFrame(0); + if (!isSelectComplete) { + return true; + } + if (!moved) { + velocityY = 0; + if (items.size() <= 1) { + return true; + } + int rnd = MathUtils.random(0, items.size() - 1); + int index = 0; + while (rnd > 0) { + rnd--; + int oldIndex = index; + do { + index = (index + 1) % items.size(); + if (index == oldIndex) + return true; + } while (!items.get(index).isVisible()); + } + if (!items.get(index).isVisible()) { + return true; + } + if (selectedItem == items.get(index)) { + return true; + } + ResourceManager.getInstance().getSound("menuclick") + .play(); + items.get(index).select(true, true); + } + return true; + } + if (pSceneTouchEvent.isActionOutside() + || pSceneTouchEvent.isActionMove() + && (MathUtils.distance(dx, dy, pTouchAreaLocalX, + pTouchAreaLocalY) > 50)) { + moved = true; + setFrame(0); + } + return false; + } + }; + + + modSelection.setScale(1.5f); + optionSelection.setScale(1.5f); + randomMap.setScale(1.5f); + if (SkinJson.get().isUseNewLayout()) { + if (layoutBackButton != null) { + layoutBackButton.baseApply(backButton); + } + if (layoutMods != null) { + layoutMods.baseApply(modSelection); + } + if (layoutOptions != null) { + layoutOptions.baseApply(optionSelection); + } + if (layoutRandom != null) { + layoutRandom.baseApply(randomMap); + } + backButton.setPosition(0, Config.getRES_HEIGHT() - backButton.getHeightScaled()); + modSelection.setPosition(backButton.getX() + backButton.getWidth(), + Config.getRES_HEIGHT() - modSelection.getHeightScaled()); + optionSelection.setPosition( + modSelection.getX() + modSelection.getWidthScaled(), + Config.getRES_HEIGHT() - optionSelection.getHeightScaled()); + randomMap.setPosition( + optionSelection.getX() + optionSelection.getWidthScaled(), + Config.getRES_HEIGHT() - randomMap.getHeightScaled()); + } else { + backButton.setPosition(0, Config.getRES_HEIGHT() - backButton.getHeight()); + modSelection.setPosition(backButton.getX() + backButton.getWidth(), + Config.getRES_HEIGHT() - Utils.toRes(90)); + optionSelection.setPosition( + modSelection.getX() + modSelection.getWidthScaled(), + Config.getRES_HEIGHT() - Utils.toRes(90)); + randomMap.setPosition( + optionSelection.getX() + optionSelection.getWidthScaled(), + Config.getRES_HEIGHT() - Utils.toRes(90)); + } + + + frontLayer.attachChild(backButton); + scene.registerTouchArea(backButton); + frontLayer.attachChild(modSelection); + scene.registerTouchArea(modSelection); + frontLayer.attachChild(optionSelection); + scene.registerTouchArea(optionSelection); + frontLayer.attachChild(randomMap); + scene.registerTouchArea(randomMap); + + if (OnlineScoring.getInstance().createSecondPanel() != null) { + OnlinePanel panel = OnlineScoring.getInstance().getSecondPanel(); + panel.detachSelf(); + panel.setPosition(randomMap.getX() + randomMap.getWidthScaled() - 18, Config.getRES_HEIGHT() - Utils.toRes(110)); + OnlineScoring.getInstance().loadAvatar(false); + frontLayer.attachChild(panel); + + + scoringSwitcher = new AnimSprite(Utils.toRes(5), Utils.toRes(10), 0, "ranking_enabled", "ranking_disabled") { + @Override + public boolean onAreaTouched(TouchEvent pSceneTouchEvent, + float pTouchAreaLocalX, float pTouchAreaLocalY) { + if (!pSceneTouchEvent.isActionDown()) return false; + board.cancleLoadAvatar(); + toggleScoringSwitcher(); + return true; + } + }; + scoringSwitcher.setFrame(1); + scoringSwitcher.setPosition(10, 10); + scene.registerTouchArea(scoringSwitcher); + frontLayer.attachChild(scoringSwitcher); + } + } + + public void toggleScoringSwitcher() { + if (board.isShowOnlineScores()) { + board.setShowOnlineScores(false); + board.init(selectedTrack); + scoringSwitcher.setFrame(1); + updateInfo(selectedTrack); + } else if (OnlineManager.getInstance().isStayOnline()) { + board.setShowOnlineScores(true); + board.init(selectedTrack); + setRank(); + } + } + + public void setRank() { + if (!board.isShowOnlineScores()) { + if (scoringSwitcher != null) { + scoringSwitcher.setFrame(1); + } + updateInfo(selectedTrack); + return; + } + scoringSwitcher.setFrame(0); + } + + public Scene getScene() { + return scene; + } + + public void setFilter(final String filter, final SortOrder order, + final boolean favsOnly, Set limit) { + String oldTrackFileName = ""; + if (selectedTrack != null) { + oldTrackFileName = selectedTrack.getFilename(); + } + if (!order.equals(sortOrder)) { + sortOrder = order; + tryReloadMenuItems(sortOrder); + sort(); + reSelectItem(oldTrackFileName); + } + if (filter == null || filterText.equals(filter)) { + if (favsOnly == this.favsOnly && limitC == limit) { + return; + } + } + limitC = limit; + filterText = filter; + camY = 0; + velocityY = 0; + final String lowerFilter = filter.toLowerCase(); + for (final MenuItem item : items) { + item.applyFilter(lowerFilter, favsOnly, limit); + } + if (favsOnly != this.favsOnly) { + this.favsOnly = favsOnly; + } else { + reSelectItem(oldTrackFileName); + } + if (selectedItem != null && !selectedItem.isVisible()) { + selectedItem = null; + selectedTrack = null; + } + System.gc(); + } + + public void sort() { + if (!sortOrder.equals(FilterMenu.getInstance().getOrder())) { + sortOrder = FilterMenu.getInstance().getOrder(); + } + Collections.sort(items, (i1, i2) -> { + String s1; + String s2; + switch (sortOrder) { + case Artist: + s1 = i1.getBeatmap().getArtist(); + s2 = i2.getBeatmap().getArtist(); + break; + case Creator: + s1 = i1.getBeatmap().getCreator(); + s2 = i2.getBeatmap().getCreator(); + break; + case Date: + final Long int1 = i1.getBeatmap().getDate(); + final Long int2 = i2.getBeatmap().getDate(); + return int2.compareTo(int1); + case Bpm: + final float bpm1 = i1.getFirstTrack().getBpmMax(); + final float bpm2 = i2.getFirstTrack().getBpmMax(); + return Float.compare(bpm2, bpm1); + case Stars: + final float float1 = i1.getFirstTrack().getDifficulty(); + final float float2 = i2.getFirstTrack().getDifficulty(); + return Float.compare(float2, float1); + case Length: + final Long length1 = i1.getFirstTrack().getMusicLength(); + final Long length2 = i2.getFirstTrack().getMusicLength(); + return length2.compareTo(length1); + default: + s1 = i1.getBeatmap().getTitle(); + s2 = i2.getBeatmap().getTitle(); + } + + return s1.compareToIgnoreCase(s2); + }); + } + + public void onUpdate(final float pSecondsElapsed) { + secPassed += pSecondsElapsed; + increaseVolume(); + increaseBackgroundLuminance(pSecondsElapsed); + + secondsSinceLastSelect += pSecondsElapsed; + float oy = -camY; + for (final MenuItem item : items) { + final float cy = oy + Config.getRES_HEIGHT() / 2f + item.getHeight() + / 2; + float ox = Config.getRES_WIDTH() / 1.85f + 200 * (float) Math.abs(Math.cos(cy * Math.PI + / (Config.getRES_HEIGHT() * 2))); + ox = Utils.toRes(ox); + item.setPos(ox, oy); + oy += item.getHeight(); + } + oy += camY; + camY += velocityY * pSecondsElapsed; + maxY = oy - Config.getRES_HEIGHT() / 2f; + if (camY <= -Config.getRES_HEIGHT() / 2f && velocityY < 0 + || camY >= maxY && velocityY > 0) { + camY -= velocityY * pSecondsElapsed; + velocityY = 0; + } + if (Math.abs(velocityY) > Utils.toRes(1000) * pSecondsElapsed) { + velocityY -= Utils.toRes(1000) * pSecondsElapsed + * Math.signum(velocityY); + } else { + velocityY = 0; + } + + expandSelectedItem(pSecondsElapsed); + + board.update(pSecondsElapsed); + updateScrollbar(camY + Config.getRES_HEIGHT() / 2f, oy); + } + + public void increaseVolume() { + if (GlobalManager.getInstance().getSongService() != null) { + synchronized (musicMutex) { + if (GlobalManager.getInstance().getSongService() != null && GlobalManager.getInstance().getSongService().getStatus() == Status.PLAYING && GlobalManager.getInstance().getSongService().getVolume() < Config.getBgmVolume()) { + float vol = Math.min(1, GlobalManager.getInstance().getSongService().getVolume() + 0.01f); + GlobalManager.getInstance().getSongService().setVolume(vol); + } + } + } + } + + public void increaseBackgroundLuminance(final float pSecondsElapsed) { + if (bg != null) { + synchronized (backgroundMutex) { + if (bg != null && bg.getRed() < 1) { + final float col = Math.min(1, bg.getRed() + pSecondsElapsed); + bg.setColor(col, col, col); + } + } + } + } + + public void expandSelectedItem(float pSecondsElapsed) { + if (selectedItem != null) { + if (selectedItem.percentAppeared < 1) { + selectedItem.percentAppeared += 2 * pSecondsElapsed; + } else { + selectedItem.percentAppeared = 1; + } + selectedItem.update(pSecondsElapsed); + } + } + + public void updateScrollbar(final float vy, final float maxy) { + scrollbar.setPosition(vy, maxy); + scrollbar.setVisible(Math.abs(velocityY) > Utils.toRes(500)); + } + + public void reset() { + } + + public void select(final MenuItem item) { + secondsSinceLastSelect = 0; + if (selectedItem != null) { + selectedItem.deselect(); + } + + selectedItem = item; + velocityY = 0; + selectedTrack = null; + float height = 0; + for (int i = 0; i < items.size(); i++) { + if (items.get(i) == selectedItem) { + break; + } + height += items.get(i).getInitialHeight(); + } + camY = height - Config.getRES_HEIGHT() / 2f; + camY += item.getTotalHeight() / 2; + } + + @SuppressLint("SimpleDateFormat") + public void changeDimensionInfo(TrackInfo track) { + if (track == null) { + return; + } + float ar = track.getApproachRate(); + float od = track.getOverallDifficulty(); + float cs = track.getCircleSize(); + float hp = track.getHpDrain(); + float bpm_max = track.getBpmMax(); + float bpm_min = track.getBpmMin(); + long length = track.getMusicLength(); + EnumSet mod = ModMenu.getInstance().getMod(); + + dimensionInfo.setColor(1, 1, 1); + beatmapInfo.setColor(1, 1, 1); + + if (mod.contains(GameMod.MOD_EASY)) { + ar *= 0.5f; + od *= 0.5f; + cs -= 1f; + hp *= 0.5f; + dimensionInfo.setColor(46 / 255f, 139 / 255f, 87 / 255f); + } + if (mod.contains(GameMod.MOD_HARDROCK)) { + ar *= 1.4f; + if (ar > 10) { + ar = 10; + } + od *= 1.4f; + cs += 1f; + hp *= 1.4f; + dimensionInfo.setColor(205 / 255f, 85 / 255f, 85 / 255f); + } + if (ModMenu.getInstance().getChangeSpeed() != 1) { + float speed = ModMenu.getInstance().getSpeed(); + bpm_max *= speed; + bpm_min *= speed; + length /= speed; + if (speed > 1) { + beatmapInfo.setColor(205 / 255f, 85 / 255f, 85 / 255f); + dimensionInfo.setColor(205 / 255f, 85 / 255f, 85 / 255f); + } else if (speed < 1) { + beatmapInfo.setColor(46 / 255f, 139 / 255f, 87 / 255f); + dimensionInfo.setColor(46 / 255f, 139 / 255f, 87 / 255f); + } + } else { + if (mod.contains(GameMod.MOD_DOUBLETIME)) { + bpm_max *= 1.5f; + bpm_min *= 1.5f; + length *= 2 / 3f; + beatmapInfo.setColor(205 / 255f, 85 / 255f, 85 / 255f); + dimensionInfo.setColor(205 / 255f, 85 / 255f, 85 / 255f); + } + if (mod.contains(GameMod.MOD_NIGHTCORE)) { + bpm_max *= 1.5f; + bpm_min *= 1.5f; + length *= 2 / 3f; + beatmapInfo.setColor(205 / 255f, 85 / 255f, 85 / 255f); + dimensionInfo.setColor(205 / 255f, 85 / 255f, 85 / 255f); + } + if (mod.contains(GameMod.MOD_HALFTIME)) { + bpm_max *= 0.75f; + bpm_min *= 0.75f; + length *= 4 / 3f; + beatmapInfo.setColor(46 / 255f, 139 / 255f, 87 / 255f); + dimensionInfo.setColor(46 / 255f, 139 / 255f, 87 / 255f); + } + } + if (mod.contains(GameMod.MOD_REALLYEASY)) { + if (mod.contains(GameMod.MOD_EASY)) { + ar *= 2f; + ar -= 0.5f; + } + ar -= 0.5f; + if (ModMenu.getInstance().getChangeSpeed() != 1) { + ar -= ModMenu.getInstance().getSpeed() - 1.0f; + } else if (mod.contains(GameMod.MOD_DOUBLETIME) || mod.contains(GameMod.MOD_NIGHTCORE)) { + ar -= 0.5f; + } + od *= 0.5f; + cs -= 1f; + hp *= 0.5f; + dimensionInfo.setColor(46 / 255f, 139 / 255f, 87 / 255f); + } + if (mod.contains(GameMod.MOD_SMALLCIRCLE)) { + cs += 4f; + dimensionInfo.setColor(205 / 255f, 85 / 255f, 85 / 255f); + } + // + @SuppressLint("SimpleDateFormat") SimpleDateFormat sdf = new SimpleDateFormat("mm:ss"); + sdf.setTimeZone(TimeZone.getTimeZone("GMT+0")); + String binfoStr = String.format(StringTable.get(R.string.binfoStr1), sdf.format(length), + (bpm_min == bpm_max ? GameHelper.Round(bpm_min, 1) : GameHelper.Round(bpm_min, 1) + "-" + GameHelper.Round(bpm_max, 1)), + track.getMaxCombo()); + if (length > 3600 * 1000) { + sdf = new SimpleDateFormat("HH:mm:ss"); + sdf.setTimeZone(TimeZone.getTimeZone("GMT+0")); + binfoStr = String.format(StringTable.get(R.string.binfoStr1), sdf.format(length), + (bpm_min == bpm_max ? GameHelper.Round(bpm_min, 1) : GameHelper.Round(bpm_min, 1) + "-" + GameHelper.Round(bpm_max, 1)), + track.getMaxCombo()); + } + beatmapInfo.setText(binfoStr); + + final StringBuilder dimensionStringBuilder = new StringBuilder(); + ar = Math.min(13.f, ar); + od = Math.min(10.f, od); + cs = Math.min(15.f, cs); + hp = Math.min(10.f, hp); + if (ModMenu.getInstance().getChangeSpeed() != 1) { + float speed = ModMenu.getInstance().getSpeed(); + ar = GameHelper.Round(GameHelper.ms2ar(GameHelper.ar2ms(ar) / speed), 2); + od = GameHelper.Round(GameHelper.ms2od(GameHelper.od2ms(od) / speed), 2); + } else if (mod.contains(GameMod.MOD_DOUBLETIME) || mod.contains(GameMod.MOD_NIGHTCORE)) { + ar = GameHelper.Round(GameHelper.ms2ar(GameHelper.ar2ms(ar) * 2 / 3), 2); + od = GameHelper.Round(GameHelper.ms2od(GameHelper.od2ms(od) * 2 / 3), 2); + } else if (mod.contains(GameMod.MOD_HALFTIME)) { + ar = GameHelper.Round(GameHelper.ms2ar(GameHelper.ar2ms(ar) * 4 / 3), 2); + od = GameHelper.Round(GameHelper.ms2od(GameHelper.od2ms(od) * 4 / 3), 2); + } + if (ModMenu.getInstance().isEnableForceAR()) { + float oriAr = ar; + ar = ModMenu.getInstance().getForceAR(); + if (ar > oriAr) { + dimensionInfo.setColor(205 / 255f, 85 / 255f, 85 / 255f); + } else if (ar < oriAr) { + dimensionInfo.setColor(46 / 255f, 139 / 255f, 87 / 255f); + } + } + dimensionStringBuilder.append("AR: ").append(GameHelper.Round(ar, 2)).append(" ") + .append("OD: ").append(GameHelper.Round(od, 2)).append(" ") + .append("CS: ").append(GameHelper.Round(cs, 2)).append(" ") + .append("HP: ").append(GameHelper.Round(hp, 2)).append(" ") + .append("Stars: ").append(GameHelper.Round(track.getDifficulty(), 2)); + + dimensionInfo.setText(dimensionStringBuilder.toString()); + } + + public void updateInfo(TrackInfo track) { + if (track == null) { + return; + } + + String tinfoStr = (track.getBeatmap().getArtistUnicode() == null || Config.isForceRomanized() ? track.getBeatmap().getArtist() : track.getBeatmap().getArtistUnicode()) + " - " + + (track.getBeatmap().getTitleUnicode() == null || Config.isForceRomanized() ? track.getBeatmap().getTitle() : track.getBeatmap().getTitleUnicode()) + " [" + track.getMode() + "]"; + String mapperStr = "Beatmap by " + track.getCreator(); + String binfoStr2 = String.format(StringTable.get(R.string.binfoStr2), + track.getHitCircleCount(), track.getSliderCount(), track.getSpinnerCount(), track.getBeatmapSetID()); + trackInfo.setText(tinfoStr); + mapper.setText(mapperStr); + beatmapInfo2.setText(binfoStr2); + changeDimensionInfo(track); + (new Thread() { + public void run() { + DifficultyReCalculator diffReCalculator = new DifficultyReCalculator(); + float newstar = diffReCalculator.recalculateStar( + selectedTrack, + diffReCalculator.getCS(selectedTrack), + ModMenu.getInstance().getSpeed() + ); + + if (newstar != 0f) { + setStarsDisplay(newstar); + } + } + }).start(); + } + + public void selectTrack(final TrackInfo track, boolean reloadBG) { +// BassAudioProvider provider = BassAudioPlayer.getProvider(); +// if (provider != null && provider.getStatus() != Status.STOPPED) { +// provider.stop(); +// } + new Thread() { + @Override + public void run() { + if (board.isShowOnlineScores()) setRank(); + } + }.start(); + + if (selectedTrack == track) { + synchronized (bgLoaded) { + if (!bgLoaded) { + return; + } + } + + ResourceManager.getInstance().getSound("menuhit").play(); + stopMusic(); + game.startGame(track, null); + unload(); + return; + } + isSelectComplete = false; + selectedTrack = track; + EdExtensionHelper.onSelectTrack(selectedTrack); + GlobalManager.getInstance().setSelectedTrack(track); + updateInfo(track); + board.cancleLoadAvatar(); + if (boardTask != null && boardTask.getStatus() != AsyncTask.Status.FINISHED) { + boardTask.cancel(true); + board.cancleLoadOnlineScores(); + } + boardTask = new AsyncTaskLoader().execute(new OsuAsyncCallback() { + @Override + public void run() { + board.init(track); + } + + @Override + public void onComplete() { + // Do something cleanup + } + }); + + final int quality = Config.getBackgroundQuality(); + synchronized (backgroundMutex) { + + if (!reloadBG && bgName.equals(track.getBackground())) { + isSelectComplete = true; + return; + } + bgName = track.getBackground(); + bg = null; + bgLoaded = false; + scene.setBackground(new ColorBackground(0, 0, 0)); + if (quality == 0) { + Config.setBackgroundQuality(4); + } + } + new AsyncTaskLoader().execute(new OsuAsyncCallback() { + + + public void run() { + // Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); + synchronized (backgroundMutex) { + final TextureRegion tex = Config.isSafeBeatmapBg() ? + ResourceManager.getInstance().getTexture("menu-background") : + ResourceManager.getInstance().loadBackground(bgName); + if (tex != null) { + float height = tex.getHeight(); + height *= Config.getRES_WIDTH() + / (float) tex.getWidth(); + bg = new Sprite(0, + (Config.getRES_HEIGHT() - height) / 2, Config + .getRES_WIDTH(), height, tex); + bg.setColor(0, 0, 0); + } + + // run() + SyncTaskManager.getInstance().run(() -> { + synchronized (backgroundMutex) { + if (bg == null) { + final TextureRegion tex1 = ResourceManager + .getInstance().getTexture("menu-background"); + float height = tex1.getHeight(); + height *= Config.getRES_WIDTH() + / (float) tex1.getWidth(); + bg = new Sprite( + 0, + (Config.getRES_HEIGHT() - height) / 2, + Config.getRES_WIDTH(), height, tex1); + bgName = ""; + } + scene.setBackground(new SpriteBackground(bg)); + Config.setBackgroundQuality(quality); + synchronized (bgLoaded) { + bgLoaded = true; + } + } + });// SyncTask.run + + } + } + + + public void onComplete() { + isSelectComplete = true; + }// onComplete + }); + } + + public void stopScroll(final float y) { + velocityY = 0; + touchY = y; + initalY = -1; + } + + public void updateScore() { + board.init(selectedTrack); + if (selectedItem != null) { + selectedItem.updateMarks(); + } + } + + public void openScore(final int id, boolean showOnline, final String playerName) { + if (showOnline) { + engine.setScene(new LoadingScreen().getScene()); + ToastLogger.showTextId(R.string.online_loadrecord, false); + new AsyncTaskLoader().execute(new OsuAsyncCallback() { + + + public void run() { + try { + String scorePack = OnlineManager.getInstance().getScorePack(id); + String[] params = scorePack.split("\\s+"); + if (params.length < 11) return; + + StatisticV2 stat = new StatisticV2(params); + stat.setPlayerName(playerName); + scoreScene.load(stat, null, null, OnlineManager.getReplayURL(id), null, selectedTrack); + engine.setScene(scoreScene.getScene()); + + } catch (OnlineManagerException e) { + Debug.e("Cannot load play info: " + e.getMessage(), e); + engine.setScene(scene); + } + + } + + public void onComplete() { + // TODO Auto-generated method stub + } + }); + return; + } + + + StatisticV2 stat = ScoreLibrary.getInstance().getScore(id); + scoreScene.load(stat, null, null, stat.getReplayName(), null, selectedTrack); + engine.setScene(scoreScene.getScene()); + } + + + public void onScroll(final float where) { + velocityY = 0; + camY = where - Config.getRES_HEIGHT() / 2f; + } + + public void unload() { + } + + public void back() { + unbindDataBaseChangedListener(); + GlobalManager.getInstance().getMainScene().show(); + } + + public void bindDataBaseChangedListener() { + OdrDatabase.get().setOnDatabaseChangedListener(this::reloadScoreBroad); + } + + public void unbindDataBaseChangedListener() { + OdrDatabase.get().setOnDatabaseChangedListener(null); + } + + public void setY(final float y) { + velocityY = 0; + camY = y; + } + + public void stopMusic() { + synchronized (musicMutex) { + if (GlobalManager.getInstance().getSongService() != null) { + GlobalManager.getInstance().getSongService().stop(); + } + } + } + + public void playMusic(final String filename, final int previewTime) { + if (!Config.isPlayMusicPreview()) { + return; + } + new AsyncTaskLoader().execute(new OsuAsyncCallback() { + + + public void run() { + Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); + synchronized (musicMutex) { + if (GlobalManager.getInstance().getSongService() != null) { + GlobalManager.getInstance().getSongService().stop(); + } + + try { +// GlobalManager.getInstance().getSongService().preLoadWithLoop(filename); + GlobalManager.getInstance().getSongService().preLoad(filename); + GlobalManager.getInstance().getSongService().play(); + GlobalManager.getInstance().getSongService().setVolume(0); + if (previewTime >= 0) { + GlobalManager.getInstance().getSongService().seekTo(previewTime); + } else { + GlobalManager.getInstance().getSongService().seekTo(GlobalManager.getInstance().getSongService().getLength() / 2); + } + } catch (final Exception e) { + Debug.e("LoadingMusic: " + e.getMessage(), e); + } + + } + } + + + public void onComplete() { + // TODO Auto-generated method stub + + } + }); + } + + public boolean isSelectAllowed() { + if (!bgLoaded) { + return false; + } + return secondsSinceLastSelect > 0.5f; + } + + public void showPropertiesMenu(MenuItem item) { + if (item == null) { + if (selectedItem == null) { + return; + } + item = selectedItem; + } + (new PropsMenuFragment()).show(SongMenu.this, item); + } + + public void showDeleteScoreMenu(int scoreId) { + (new ScoreMenuFragment()).show(scoreId); + //ScorePropsMenu.getInstance().setSongMenu(SongMenu.this); + //ScorePropsMenu.getInstance().setScoreId(scoreId); + //scene.setChildScene(ScorePropsMenu.getInstance().getScene(), false, true, true); + } + + public void reloadScoreBroad() { + board.cancleLoadAvatar(); + if (boardTask != null && boardTask.getStatus() != AsyncTask.Status.FINISHED) { + boardTask.cancel(true); + board.cancleLoadOnlineScores(); + } + boardTask = new AsyncTaskLoader().execute(new OsuAsyncCallback() { + @Override + public void run() { + board.init(selectedTrack); + } + + @Override + public void onComplete() { + // Do something cleanup + } + }); + } + + public Entity getFrontLayer() { + return frontLayer; + } + + public Entity getBackLayer() { + return backLayer; + } + + public void select() { + if (GlobalManager.getInstance().getMainScene().getBeatmapInfo() != null) { + BeatmapInfo beatmapInfo = GlobalManager.getInstance().getMainScene().getBeatmapInfo(); + for (int i = 0; i < items.size(); i++) { + if (items.get(i).getBeatmap().getArtist().equals(beatmapInfo.getArtist()) && + items.get(i).getBeatmap().getTitle().equals(beatmapInfo.getTitle()) && + items.get(i).getBeatmap().getCreator().equals(beatmapInfo.getCreator())) { + secondsSinceLastSelect = 2; + items.get(i).select(false, true); + break; + } + } + } + } + + public TrackInfo getSelectedTrack() { + return selectedTrack; + } + + public boolean checkBG(String filePath) { + if (filePath == null) return false; + if (filePath.trim().equals("")) return false; + + BitmapFactory.Options bgOption = new BitmapFactory.Options(); + bgOption.inJustDecodeBounds = true; + int w = BitmapFactory.decodeFile(filePath).getWidth(); + int h = BitmapFactory.decodeFile(filePath).getHeight(); + bgOption.inJustDecodeBounds = false; + bgOption = null; + return (w * h) > 0; + } + + private void tryReloadMenuItems(SortOrder order) { + switch (order) { + case Title: + case Artist: + case Creator: + case Date: + case Bpm: + reloadMenuItems(GroupType.MapSet); + break; + case Stars: + case Length: + reloadMenuItems(GroupType.SingleDiff); + break; + } + } + + private void reloadMenuItems(GroupType type) { + if (!groupType.equals(type)) { + groupType = type; + float oy = 10; + for (MenuItem item : items) { + item.removeFromScene(); + } + items.clear(); + switch (type) { + case MapSet: + for (final BeatmapInfo i : LibraryManager.getInstance().getLibrary()) { + final MenuItem item = new MenuItem(this, i); + items.add(item); + item.attachToScene(scene, backLayer); + oy += item.getHeight(); + } + break; + case SingleDiff: + for (final BeatmapInfo i : LibraryManager.getInstance().getLibrary()) { + for (int j = 0; j < i.getCount(); j++) { + final MenuItem item = new MenuItem(this, i, j); + items.add(item); + item.attachToScene(scene, backLayer); + oy += item.getHeight(); + } + } + break; + } + final String lowerFilter = FilterMenu.getInstance().getFilter().toLowerCase(); + final boolean favsOnly = FilterMenu.getInstance().isFavoritesOnly(); + final Set limit = FilterMenu.getInstance().getFavoriteFolder() == null ? null : FavoriteLibrary.get().getMaps(FilterMenu.getInstance().getFavoriteFolder()); + for (final MenuItem item : items) { + item.applyFilter(lowerFilter, favsOnly, limit); + } + System.gc(); + } + } + + public void setStarsDisplay(float star) { + String str = dimensionInfo.getText(); + String[] strs = str.split("Stars: "); + if (strs.length == 2) { + dimensionInfo.setText(strs[0] + "Stars: " + star); + } + } + + private void reSelectItem(String oldTrackFileName) { + if (!oldTrackFileName.equals("")) { + if (selectedTrack.getFilename().equals(oldTrackFileName) && items.size() > 1 && selectedItem != null && selectedItem.isVisible()) { + velocityY = 0; + float height = 0; + for (int i = 0; i < items.size(); i++) { + if (items.get(i) == selectedItem) { + break; + } + height += items.get(i).getInitialHeight(); + } + camY = height - Config.getRES_HEIGHT() / 2f; + camY += items.get(0).getTotalHeight() / 2; + return; + } + for (final MenuItem item : items) { + if (item == null || !item.isVisible()) continue; + int trackid = item.tryGetCorrespondingTrackId(oldTrackFileName); + if (trackid >= 0) { + item.select(true, true); + if (trackid != 0) { + item.selectTrack(item.getTrackSpritesById(trackid), false); + } + break; + } + } + } + } + + public enum SortOrder { + Title, Artist, Creator, Date, Bpm, Stars, Length + } + + public enum GroupType { + MapSet, SingleDiff + } } diff --git a/src/ru/nsu/ccfit/zuev/osu/menu/SongMenuPool.java b/src/ru/nsu/ccfit/zuev/osu/menu/SongMenuPool.java index a94c412c..f5d487e3 100644 --- a/src/ru/nsu/ccfit/zuev/osu/menu/SongMenuPool.java +++ b/src/ru/nsu/ccfit/zuev/osu/menu/SongMenuPool.java @@ -6,54 +6,54 @@ import java.util.Queue; public class SongMenuPool { - private static final SongMenuPool instance = new SongMenuPool(); - private final Queue backgrounds = new LinkedList<>(); - private final Queue tracks = new LinkedList<>(); - private int count = 0; - private SongMenuPool() { - } - - public static SongMenuPool getInstance() { - return instance; - } - - public void init() { - count = 0; - tracks.clear(); - backgrounds.clear(); - for (int i = 0; i < 15; i++) { - backgrounds.add(new MenuItemBackground()); - } - for (int i = 0; i < 5; i++) { - tracks.add(new MenuItemTrack()); - } - count = 20; - } - - public MenuItemBackground newBackground() { - if (!backgrounds.isEmpty()) { - return backgrounds.poll(); - } - count++; - Debug.i("Count = " + count); - return new MenuItemBackground(); - } - - public void putBackground(final MenuItemBackground background) { - backgrounds.add(background); - } - - public MenuItemTrack newTrack() { - if (!tracks.isEmpty()) { - return tracks.poll(); - } - count++; - Debug.i("Count = " + count); - return new MenuItemTrack(); - } - - public void putTrack(final MenuItemTrack track) { - tracks.add(track); - } + private static final SongMenuPool instance = new SongMenuPool(); + private final Queue backgrounds = new LinkedList<>(); + private final Queue tracks = new LinkedList<>(); + private int count = 0; + private SongMenuPool() { + } + + public static SongMenuPool getInstance() { + return instance; + } + + public void init() { + count = 0; + tracks.clear(); + backgrounds.clear(); + for (int i = 0; i < 15; i++) { + backgrounds.add(new MenuItemBackground()); + } + for (int i = 0; i < 5; i++) { + tracks.add(new MenuItemTrack()); + } + count = 20; + } + + public MenuItemBackground newBackground() { + if (!backgrounds.isEmpty()) { + return backgrounds.poll(); + } + count++; + Debug.i("Count = " + count); + return new MenuItemBackground(); + } + + public void putBackground(final MenuItemBackground background) { + backgrounds.add(background); + } + + public MenuItemTrack newTrack() { + if (!tracks.isEmpty()) { + return tracks.poll(); + } + count++; + Debug.i("Count = " + count); + return new MenuItemTrack(); + } + + public void putTrack(final MenuItemTrack track) { + tracks.add(track); + } } diff --git a/src/ru/nsu/ccfit/zuev/osu/menu/SplashScene.java b/src/ru/nsu/ccfit/zuev/osu/menu/SplashScene.java index 63cfdbff..a2ce41fd 100644 --- a/src/ru/nsu/ccfit/zuev/osu/menu/SplashScene.java +++ b/src/ru/nsu/ccfit/zuev/osu/menu/SplashScene.java @@ -22,89 +22,89 @@ * Created by Fuuko on 2015/4/25. */ public class SplashScene implements IUpdateHandler { - private final Scene scene; - //private Sprite logo2; - private final Rectangle progressRect; - private final Rectangle bgRect; - private final ChangeableText infoText; - private final ChangeableText progressText; + private final Scene scene; + //private Sprite logo2; + private final Rectangle progressRect; + private final Rectangle bgRect; + private final ChangeableText infoText; + private final ChangeableText progressText; - public SplashScene() { - scene = new Scene(); - scene.registerEntityModifier(new FadeOutModifier(0.5f)); - final TextureRegion logotex = ResourceManager.getInstance().getTexture("logo"); - Sprite logo = new Sprite(0, 0, logotex); - logo.setWidth(500); - logo.setHeight(500); - logo.setPosition((Config.getRES_WIDTH() - logotex.getWidth()) / 2f, (Config.getRES_HEIGHT() - logotex.getHeight()) / 2f - 40); - logo.setRotationCenter(250, 250); - scene.attachChild(logo); + public SplashScene() { + scene = new Scene(); + scene.registerEntityModifier(new FadeOutModifier(0.5f)); + final TextureRegion logotex = ResourceManager.getInstance().getTexture("logo"); + Sprite logo = new Sprite(0, 0, logotex); + logo.setWidth(500); + logo.setHeight(500); + logo.setPosition((Config.getRES_WIDTH() - logotex.getWidth()) / 2f, (Config.getRES_HEIGHT() - logotex.getHeight()) / 2f - 40); + logo.setRotationCenter(250, 250); + scene.attachChild(logo); - // final TextureRegion welcometex = ResourceManager.getInstance().getTexture("welcome"); - // logo2 = new Sprite(0, 0, welcometex); - // logo2.setWidth(375); - // logo2.setHeight(78); - // logo2.setPosition((Config.getRES_WIDTH() - welcometex.getWidth()) / 2, (Config.getRES_HEIGHT() - welcometex.getHeight()) / 2 - 40); - // logo2.setRotationCenter(0, 0); - // logo2.set((((Dimmer scene))) - // scene.attachChild(logo2); + // final TextureRegion welcometex = ResourceManager.getInstance().getTexture("welcome"); + // logo2 = new Sprite(0, 0, welcometex); + // logo2.setWidth(375); + // logo2.setHeight(78); + // logo2.setPosition((Config.getRES_WIDTH() - welcometex.getWidth()) / 2, (Config.getRES_HEIGHT() - welcometex.getHeight()) / 2 - 40); + // logo2.setRotationCenter(0, 0); + // logo2.set((((Dimmer scene))) + // scene.attachChild(logo2); - final TextureRegion bgtex = ResourceManager.getInstance().getTexture("loading-background"); - if (bgtex != null) { - float height = bgtex.getHeight(); - height *= Config.getRES_WIDTH() - / (float) bgtex.getWidth(); - final Sprite menuBg = new Sprite( - 0, - (Config.getRES_HEIGHT() - height) / 2, - Config.getRES_WIDTH(), - height, bgtex); - scene.setBackground(new SpriteBackground(menuBg)); - } else { - scene.setBackground(new ColorBackground(70 / 255f, 129 / 255f, - 252 / 255f)); - } - logo.registerEntityModifier(new LoopEntityModifier( - new RotationByModifier(4.0f, 360))); + final TextureRegion bgtex = ResourceManager.getInstance().getTexture("loading-background"); + if (bgtex != null) { + float height = bgtex.getHeight(); + height *= Config.getRES_WIDTH() + / (float) bgtex.getWidth(); + final Sprite menuBg = new Sprite( + 0, + (Config.getRES_HEIGHT() - height) / 2, + Config.getRES_WIDTH(), + height, bgtex); + scene.setBackground(new SpriteBackground(menuBg)); + } else { + scene.setBackground(new ColorBackground(70 / 255f, 129 / 255f, + 252 / 255f)); + } + logo.registerEntityModifier(new LoopEntityModifier( + new RotationByModifier(4.0f, 360))); - bgRect = new Rectangle(0, 0, Utils.toRes(800), Utils.toRes(50)); - bgRect.setPosition((Config.getRES_WIDTH() - bgRect.getWidth()) / 2, Config.getRES_HEIGHT() - 90); - bgRect.setColor(0, 0, 0, 0.4f); - scene.attachChild(bgRect); + bgRect = new Rectangle(0, 0, Utils.toRes(800), Utils.toRes(50)); + bgRect.setPosition((Config.getRES_WIDTH() - bgRect.getWidth()) / 2, Config.getRES_HEIGHT() - 90); + bgRect.setColor(0, 0, 0, 0.4f); + scene.attachChild(bgRect); - progressRect = new Rectangle(bgRect.getX(), bgRect.getY(), 0, - bgRect.getHeight()); - progressRect.setColor(0, 0.8f, 0); - scene.attachChild(progressRect); + progressRect = new Rectangle(bgRect.getX(), bgRect.getY(), 0, + bgRect.getHeight()); + progressRect.setColor(0, 0.8f, 0); + scene.attachChild(progressRect); - progressText = new ChangeableText(0, 0, ResourceManager.getInstance().getFont("font"), "0 %", HorizontalAlign.CENTER, 10); - progressText.setPosition((Config.getRES_WIDTH() - progressText.getWidth()) / 2, bgRect.getY()); - scene.attachChild(progressText); + progressText = new ChangeableText(0, 0, ResourceManager.getInstance().getFont("font"), "0 %", HorizontalAlign.CENTER, 10); + progressText.setPosition((Config.getRES_WIDTH() - progressText.getWidth()) / 2, bgRect.getY()); + scene.attachChild(progressText); - infoText = new ChangeableText(0, 0, ResourceManager.getInstance().getFont("strokeFont"), "", HorizontalAlign.CENTER, 1024); - infoText.setPosition((Config.getRES_WIDTH() - infoText.getWidth()) / 2, bgRect.getY() - infoText.getHeight() - 10); - scene.attachChild(infoText); + infoText = new ChangeableText(0, 0, ResourceManager.getInstance().getFont("strokeFont"), "", HorizontalAlign.CENTER, 1024); + infoText.setPosition((Config.getRES_WIDTH() - infoText.getWidth()) / 2, bgRect.getY() - infoText.getHeight() - 10); + scene.attachChild(infoText); - scene.registerUpdateHandler(this); - } + scene.registerUpdateHandler(this); + } - public Scene getScene() { - return scene; - } + public Scene getScene() { + return scene; + } - @Override - public void onUpdate(final float pSecondsElapsed) { - progressRect.setWidth(bgRect.getWidth() * (GlobalManager.getInstance().getLoadingProgress() / 100f)); - progressText.setText(GlobalManager.getInstance().getLoadingProgress() + " %"); - progressText.setPosition((Config.getRES_WIDTH() - progressText.getWidth()) / 2, bgRect.getY() + (bgRect.getHeight() - progressText.getHeight()) / 2); - if (GlobalManager.getInstance().getInfo() != null) { - infoText.setText(GlobalManager.getInstance().getInfo()); - infoText.setPosition((Config.getRES_WIDTH() - infoText.getWidth()) / 2, bgRect.getY() - infoText.getHeight() - 10); - } - } + @Override + public void onUpdate(final float pSecondsElapsed) { + progressRect.setWidth(bgRect.getWidth() * (GlobalManager.getInstance().getLoadingProgress() / 100f)); + progressText.setText(GlobalManager.getInstance().getLoadingProgress() + " %"); + progressText.setPosition((Config.getRES_WIDTH() - progressText.getWidth()) / 2, bgRect.getY() + (bgRect.getHeight() - progressText.getHeight()) / 2); + if (GlobalManager.getInstance().getInfo() != null) { + infoText.setText(GlobalManager.getInstance().getInfo()); + infoText.setPosition((Config.getRES_WIDTH() - infoText.getWidth()) / 2, bgRect.getY() - infoText.getHeight() - 10); + } + } - @Override - public void reset() { + @Override + public void reset() { - } + } } diff --git a/src/ru/nsu/ccfit/zuev/osu/model/vo/GithubReleaseVO.java b/src/ru/nsu/ccfit/zuev/osu/model/vo/GithubReleaseVO.java index e8f9a335..b9eb73d8 100644 --- a/src/ru/nsu/ccfit/zuev/osu/model/vo/GithubReleaseVO.java +++ b/src/ru/nsu/ccfit/zuev/osu/model/vo/GithubReleaseVO.java @@ -1,74 +1,74 @@ -package ru.nsu.ccfit.zuev.osu.model.vo; - -import java.util.List; - -public class GithubReleaseVO { - - private String html_url; - private List assets; - private String body; - - public void setHtml_url(String html_url){ - this.html_url = html_url; - } - - public String getHtml_url(){ - return this.html_url; - } - - public void setAssets(List assets){ - this.assets = assets; - } - - public List getAssets(){ - return this.assets; - } - - public void setBody(String body){ - this.body = body; - } - - public String getBody(){ - return this.body; - } - - public class Asset { - private String name; - private String content_type; - private int size; - private String browser_download_url; - - public void setName(String name){ - this.name = name; - } - - public String getName(){ - return this.name; - } - - public void setContent_type(String content_type){ - this.content_type = content_type; - } - - public String getContent_type(){ - return this.content_type; - } - - public void setSize(int size){ - this.size = size; - } - - public int getSize(){ - return this.size; - } - - public void setBrowser_download_url(String browser_download_url){ - this.browser_download_url = browser_download_url; - } - - public String getBrowser_download_url(){ - return this.browser_download_url; - } - } - -} \ No newline at end of file +package ru.nsu.ccfit.zuev.osu.model.vo; + +import java.util.List; + +public class GithubReleaseVO { + + private String html_url; + private List assets; + private String body; + + public void setHtml_url(String html_url){ + this.html_url = html_url; + } + + public String getHtml_url(){ + return this.html_url; + } + + public void setAssets(List assets){ + this.assets = assets; + } + + public List getAssets(){ + return this.assets; + } + + public void setBody(String body){ + this.body = body; + } + + public String getBody(){ + return this.body; + } + + public class Asset { + private String name; + private String content_type; + private int size; + private String browser_download_url; + + public void setName(String name){ + this.name = name; + } + + public String getName(){ + return this.name; + } + + public void setContent_type(String content_type){ + this.content_type = content_type; + } + + public String getContent_type(){ + return this.content_type; + } + + public void setSize(int size){ + this.size = size; + } + + public int getSize(){ + return this.size; + } + + public void setBrowser_download_url(String browser_download_url){ + this.browser_download_url = browser_download_url; + } + + public String getBrowser_download_url(){ + return this.browser_download_url; + } + } + +} diff --git a/src/ru/nsu/ccfit/zuev/osu/model/vo/UserVO.java b/src/ru/nsu/ccfit/zuev/osu/model/vo/UserVO.java index c56a5a12..c29ea0e3 100644 --- a/src/ru/nsu/ccfit/zuev/osu/model/vo/UserVO.java +++ b/src/ru/nsu/ccfit/zuev/osu/model/vo/UserVO.java @@ -5,13 +5,13 @@ */ public class UserVO { - private Long uid; + private Long uid; - public Long getUid() { - return uid; - } + public Long getUid() { + return uid; + } - public void setUid(Long uid) { - this.uid = uid; - } + public void setUid(Long uid) { + this.uid = uid; + } } diff --git a/src/ru/nsu/ccfit/zuev/osu/model/vo/VersionCodeVO.java b/src/ru/nsu/ccfit/zuev/osu/model/vo/VersionCodeVO.java index 84e7e137..292bc51e 100644 --- a/src/ru/nsu/ccfit/zuev/osu/model/vo/VersionCodeVO.java +++ b/src/ru/nsu/ccfit/zuev/osu/model/vo/VersionCodeVO.java @@ -1,15 +1,15 @@ -package ru.nsu.ccfit.zuev.osu.model.vo; - -public class VersionCodeVO { - - private long version_code; - - public void setValue(long version_code){ - this.version_code = version_code; - } - - public long getValue(){ - return this.version_code; - } - -} \ No newline at end of file +package ru.nsu.ccfit.zuev.osu.model.vo; + +public class VersionCodeVO { + + private long version_code; + + public void setValue(long version_code){ + this.version_code = version_code; + } + + public long getValue(){ + return this.version_code; + } + +} diff --git a/src/ru/nsu/ccfit/zuev/osu/online/OnlineFileOperator.java b/src/ru/nsu/ccfit/zuev/osu/online/OnlineFileOperator.java index 67332364..8320487e 100644 --- a/src/ru/nsu/ccfit/zuev/osu/online/OnlineFileOperator.java +++ b/src/ru/nsu/ccfit/zuev/osu/online/OnlineFileOperator.java @@ -19,68 +19,68 @@ public class OnlineFileOperator { - public static void sendFile(String urlstr, String filename, String replayID) { - try { - File file = new File(filename); - if (!file.exists()) { - Debug.i(filename + " does not exist."); - return; - } + public static void sendFile(String urlstr, String filename, String replayID) { + try { + File file = new File(filename); + if (!file.exists()) { + Debug.i(filename + " does not exist."); + return; + } - String checksum = FileUtils.getSHA256Checksum(file); - StringBuilder sb = new StringBuilder(); - sb.append(URLEncoder.encode(checksum, "UTF-8")); - sb.append("_"); - sb.append(URLEncoder.encode(replayID, "UTF-8")); - String signature = SecurityUtils.signRequest(sb.toString()); + String checksum = FileUtils.getSHA256Checksum(file); + StringBuilder sb = new StringBuilder(); + sb.append(URLEncoder.encode(checksum, "UTF-8")); + sb.append("_"); + sb.append(URLEncoder.encode(replayID, "UTF-8")); + String signature = SecurityUtils.signRequest(sb.toString()); - MediaType mime = MediaType.parse("application/octet-stream"); - RequestBody fileBody = RequestBody.create(mime, file); - RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM) - .addFormDataPart("uploadedfile", file.getName(), fileBody) - .addFormDataPart("hash", checksum) - .addFormDataPart("replayID", replayID) - .addFormDataPart("sign", signature) - .build(); - Request request = new Request.Builder().url(urlstr) - .post(requestBody).build(); - Response response = OnlineManager.client.newCall(request).execute(); - String responseMsg = response.body().string(); + MediaType mime = MediaType.parse("application/octet-stream"); + RequestBody fileBody = RequestBody.create(mime, file); + RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM) + .addFormDataPart("uploadedfile", file.getName(), fileBody) + .addFormDataPart("hash", checksum) + .addFormDataPart("replayID", replayID) + .addFormDataPart("sign", signature) + .build(); + Request request = new Request.Builder().url(urlstr) + .post(requestBody).build(); + Response response = OnlineManager.client.newCall(request).execute(); + String responseMsg = response.body().string(); - Debug.i("sendFile signatureResponse " + responseMsg); - } catch (final IOException e) { - Debug.e("sendFile IOException " + e.getMessage(), e); - } catch (final Exception e) { - Debug.e("sendFile Exception " + e.getMessage(), e); - } - } + Debug.i("sendFile signatureResponse " + responseMsg); + } catch (final IOException e) { + Debug.e("sendFile IOException " + e.getMessage(), e); + } catch (final Exception e) { + Debug.e("sendFile Exception " + e.getMessage(), e); + } + } - public static boolean downloadFile(String urlstr, String filename) { - Debug.i("Starting download " + urlstr); - File file = new File(filename); - try { - if(file.exists()) { - Debug.i(file.getName() + " already exists"); - return true; - } - // Cheching for errors - Debug.i("Connected to " + urlstr); + public static boolean downloadFile(String urlstr, String filename) { + Debug.i("Starting download " + urlstr); + File file = new File(filename); + try { + if(file.exists()) { + Debug.i(file.getName() + " already exists"); + return true; + } + // Cheching for errors + Debug.i("Connected to " + urlstr); - Request request = new Request.Builder() - .url(urlstr) - .build(); - Response response = OnlineManager.client.newCall(request).execute(); - BufferedSink sink = Okio.buffer(Okio.sink(file)); - sink.writeAll(response.body().source()); - response.close(); - sink.close(); - return true; - } catch (final IOException e) { - Debug.e("downloadFile IOException " + e.getMessage(), e); - return false; - } catch (final Exception e) { - Debug.e("downloadFile Exception " + e.getMessage(), e); - return false; - } - } + Request request = new Request.Builder() + .url(urlstr) + .build(); + Response response = OnlineManager.client.newCall(request).execute(); + BufferedSink sink = Okio.buffer(Okio.sink(file)); + sink.writeAll(response.body().source()); + response.close(); + sink.close(); + return true; + } catch (final IOException e) { + Debug.e("downloadFile IOException " + e.getMessage(), e); + return false; + } catch (final Exception e) { + Debug.e("downloadFile Exception " + e.getMessage(), e); + return false; + } + } } diff --git a/src/ru/nsu/ccfit/zuev/osu/online/OnlineInitializer.java b/src/ru/nsu/ccfit/zuev/osu/online/OnlineInitializer.java index 8e75cf53..cdb3a6a8 100644 --- a/src/ru/nsu/ccfit/zuev/osu/online/OnlineInitializer.java +++ b/src/ru/nsu/ccfit/zuev/osu/online/OnlineInitializer.java @@ -21,109 +21,109 @@ import ru.nsu.ccfit.zuev.osuplus.R; public class OnlineInitializer implements View.OnClickListener { - private Activity activity; - private Dialog registerDialog; - - public OnlineInitializer(Activity context) { - this.activity = context; - } - - public void createInitDialog() { - registerDialog = new Dialog(activity); - registerDialog.setContentView(R.layout.register_dialog); - registerDialog.setTitle(StringTable.get(R.string.online_registration)); - - Button btn = (Button) registerDialog.findViewById(R.id.register_btn); - if (btn != null) btn.setOnClickListener(this); - btn = (Button) registerDialog.findViewById(R.id.cancel_btn); - if (btn != null) btn.setOnClickListener(new View.OnClickListener() { - public void onClick(View v) { - registerDialog.dismiss(); - } - }); - - registerDialog.show(); - } - - - public void onClick(View v) { - final String username = ((EditText) registerDialog.findViewById(R.id.username_edit)) - .getText().toString(); - final String password = ((EditText) registerDialog.findViewById(R.id.password_edit)) - .getText().toString(); - final String confirm_password = ((EditText) registerDialog.findViewById(R.id.confirm_password_edit)) - .getText().toString(); - final String email = ((EditText) registerDialog.findViewById(R.id.email_edit)) - .getText().toString(); - - final TextView errorText = (TextView) registerDialog.findViewById(R.id.register_error_text); - errorText.setText(""); - - if (username.matches("^\\w{3,16}$") == false) { - ToastLogger.showTextId(R.string.online_invlogin, true); - return; - } - if (password.length() < 4 || password.length() > 32) { - ToastLogger.showTextId(R.string.online_invpassword, true); - return; - } - if (password.equals(confirm_password) == false) { - ToastLogger.showTextId(R.string.online_invconfirm, true); - return; - } - if (email.matches("^[\\w.-_]+@[\\w.-_]+$") == false) { - ToastLogger.showTextId(R.string.online_invemail, true); - return; - } - - final ProgressDialog pdialog = ProgressDialog.show(activity, - StringTable.get(R.string.online_registration), - StringTable.get(R.string.online_registration_process)); - - new AsyncTaskLoader().execute(new OsuAsyncCallback() { - private boolean success = false; - private String resultMessage = ""; - - public void run() { - - try { - success = OnlineManager.getInstance().register(username, password, email, - Config.getOnlineDeviceID()); - } catch (OnlineManagerException e) { - resultMessage = e.getMessage(); - ToastLogger.showText(resultMessage, true); - return; - } - - //Error check - resultMessage = OnlineManager.getInstance().getFailMessage(); - } - - public void onComplete() { - activity.runOnUiThread(new Runnable() { - public void run() { - pdialog.dismiss(); - if (success) - registerDialog.dismiss(); - errorText.setText(resultMessage); - } - }); - final SharedPreferences prefs = PreferenceManager - .getDefaultSharedPreferences(activity); - - //Save changes - Editor editor = prefs.edit(); - if (prefs.getBoolean("onlineSet", false) == false || success) { - editor.putBoolean("stayOnline", success); - editor.putString("onlineUsername", username); - editor.putString("onlinePassword", password); - } - editor.putBoolean("onlineSet", true); - editor.commit(); - if (success) { - ToastLogger.showTextId(R.string.online_regcomplete, true); - } - } - }); - } + private Activity activity; + private Dialog registerDialog; + + public OnlineInitializer(Activity context) { + this.activity = context; + } + + public void createInitDialog() { + registerDialog = new Dialog(activity); + registerDialog.setContentView(R.layout.register_dialog); + registerDialog.setTitle(StringTable.get(R.string.online_registration)); + + Button btn = (Button) registerDialog.findViewById(R.id.register_btn); + if (btn != null) btn.setOnClickListener(this); + btn = (Button) registerDialog.findViewById(R.id.cancel_btn); + if (btn != null) btn.setOnClickListener(new View.OnClickListener() { + public void onClick(View v) { + registerDialog.dismiss(); + } + }); + + registerDialog.show(); + } + + + public void onClick(View v) { + final String username = ((EditText) registerDialog.findViewById(R.id.username_edit)) + .getText().toString(); + final String password = ((EditText) registerDialog.findViewById(R.id.password_edit)) + .getText().toString(); + final String confirm_password = ((EditText) registerDialog.findViewById(R.id.confirm_password_edit)) + .getText().toString(); + final String email = ((EditText) registerDialog.findViewById(R.id.email_edit)) + .getText().toString(); + + final TextView errorText = (TextView) registerDialog.findViewById(R.id.register_error_text); + errorText.setText(""); + + if (username.matches("^\\w{3,16}$") == false) { + ToastLogger.showTextId(R.string.online_invlogin, true); + return; + } + if (password.length() < 4 || password.length() > 32) { + ToastLogger.showTextId(R.string.online_invpassword, true); + return; + } + if (password.equals(confirm_password) == false) { + ToastLogger.showTextId(R.string.online_invconfirm, true); + return; + } + if (email.matches("^[\\w.-_]+@[\\w.-_]+$") == false) { + ToastLogger.showTextId(R.string.online_invemail, true); + return; + } + + final ProgressDialog pdialog = ProgressDialog.show(activity, + StringTable.get(R.string.online_registration), + StringTable.get(R.string.online_registration_process)); + + new AsyncTaskLoader().execute(new OsuAsyncCallback() { + private boolean success = false; + private String resultMessage = ""; + + public void run() { + + try { + success = OnlineManager.getInstance().register(username, password, email, + Config.getOnlineDeviceID()); + } catch (OnlineManagerException e) { + resultMessage = e.getMessage(); + ToastLogger.showText(resultMessage, true); + return; + } + + //Error check + resultMessage = OnlineManager.getInstance().getFailMessage(); + } + + public void onComplete() { + activity.runOnUiThread(new Runnable() { + public void run() { + pdialog.dismiss(); + if (success) + registerDialog.dismiss(); + errorText.setText(resultMessage); + } + }); + final SharedPreferences prefs = PreferenceManager + .getDefaultSharedPreferences(activity); + + //Save changes + Editor editor = prefs.edit(); + if (prefs.getBoolean("onlineSet", false) == false || success) { + editor.putBoolean("stayOnline", success); + editor.putString("onlineUsername", username); + editor.putString("onlinePassword", password); + } + editor.putBoolean("onlineSet", true); + editor.commit(); + if (success) { + ToastLogger.showTextId(R.string.online_regcomplete, true); + } + } + }); + } } diff --git a/src/ru/nsu/ccfit/zuev/osu/online/OnlineManager.java b/src/ru/nsu/ccfit/zuev/osu/online/OnlineManager.java index 9629b06c..f5cc6654 100644 --- a/src/ru/nsu/ccfit/zuev/osu/online/OnlineManager.java +++ b/src/ru/nsu/ccfit/zuev/osu/online/OnlineManager.java @@ -26,408 +26,408 @@ import ru.nsu.ccfit.zuev.osu.online.PostBuilder.RequestException; public class OnlineManager { - public static final String hostname = "osudroid.moe"; - public static final String endpoint = "https://" + hostname + "/api/"; - private static final String onlineVersion = "29"; - - public static final OkHttpClient client = new OkHttpClient(); - - private static OnlineManager instance = null; - private Context context; - private String failMessage = ""; - - private boolean stayOnline = true; - private String ssid = ""; - private String userId = ""; - private String playID = ""; - - private String username = ""; - private String password = ""; - private String deviceID = ""; - private long rank = 0; - private long score = 0; - private float accuracy = 0; - private String avatarURL = ""; - private int mapRank; - private int replayID = 0; - - public static OnlineManager getInstance() { - if (instance == null) { - instance = new OnlineManager(); - } - return instance; - } - - public static String getReplayURL(int playID) { - return endpoint + "upload/" + playID + ".odr"; - } - - public void Init(Context context) { - this.stayOnline = Config.isStayOnline(); - this.username = Config.getOnlineUsername(); - this.password = Config.getOnlinePassword(); - this.deviceID = Config.getOnlineDeviceID(); - this.context = context; - } - - private ArrayList sendRequest(PostBuilder post, String url) throws OnlineManagerException { - ArrayList response; - try { - response = post.requestWithAttempts(url, 3); - } catch (RequestException e) { - Debug.e(e.getMessage(), e); - failMessage = "Cannot connect to server"; - throw new OnlineManagerException("Cannot connect to server", e); - } - failMessage = ""; - - //TODO debug code - /*Debug.i("Received " + response.size() + " lines"); - for(String str: response) - { - Debug.i(str); - }*/ - - if (response.size() == 0 || response.get(0).length() == 0) { - failMessage = "Got empty response"; - Debug.i("Received empty response!"); - return null; - } - - if (!response.get(0).equals("SUCCESS")) { - Debug.i("sendRequest response code: " + response.get(0)); - if (response.size() >= 2) { - failMessage = response.get(1); - } else - failMessage = "Unknown server error"; - Debug.i("Received fail: " + failMessage); - return null; - } - - - return response; - } - - public boolean logIn() throws OnlineManagerException { - return logIn(username, password); - } - - public boolean logIn(String username) throws OnlineManagerException { - return logIn(username, password); - } - - public synchronized boolean logIn(String username, String password) throws OnlineManagerException { - this.username = username; - this.password = password; - - PostBuilder post = new PostBuilder(); - post.addParam("username", username); - post.addParam("password", MD5Calcuator.getStringMD5(password + "taikotaiko")); - post.addParam("version", onlineVersion); - - ArrayList response = sendRequest(post, endpoint + "login.php"); - - if (response == null) { - return false; - } - if (response.size() < 2) { - failMessage = "Invalid server response"; - return false; - } - - String[] params = response.get(1).split("\\s+"); - if (params.length < 6) { - failMessage = "Invalid server response"; - return false; - } - userId = params[0]; - ssid = params[1]; - rank = Integer.parseInt(params[2]); - score = Long.parseLong(params[3]); - accuracy = Integer.parseInt(params[4]) / 100000f; - this.username = params[5]; - if (params.length >= 7) { - avatarURL = params[6]; - } else { - avatarURL = ""; - } - - Bundle bParams = new Bundle(); - bParams.putString(FirebaseAnalytics.Param.METHOD, "ingame"); - GlobalManager.getInstance().getMainActivity().getAnalytics().logEvent(FirebaseAnalytics.Event.LOGIN, - bParams); - - return true; - } - - boolean tryToLogIn() throws OnlineManagerException { - if (logIn(username, password) == false) { - stayOnline = false; - return false; - } - return true; - } - - public boolean register(final String username, final String password, final String email, - final String deviceID) throws OnlineManagerException { - PostBuilder post = new PostBuilder(); - post.addParam("username", username); - post.addParam("password", MD5Calcuator.getStringMD5(password + "taikotaiko")); - post.addParam("email", email); - post.addParam("deviceID", deviceID); - - ArrayList response = sendRequest(post, endpoint + "register.php"); - - Bundle params = new Bundle(); - params.putString(FirebaseAnalytics.Param.METHOD, "ingame"); - GlobalManager.getInstance().getMainActivity().getAnalytics().logEvent(FirebaseAnalytics.Event.SIGN_UP, - params); - - return (response != null); - } - - public void startPlay(final TrackInfo track, final String hash) throws OnlineManagerException { - Debug.i("Starting play..."); - playID = null; - final BeatmapInfo beatmap = track.getBeatmap(); - if (beatmap == null) return; - - File trackfile = new File(track.getFilename()); - trackfile.getParentFile().getName(); - String osuID = trackfile.getParentFile().getName(); - Debug.i("osuid = " + osuID); - if (osuID.matches("^[0-9]+ .*")) - osuID = osuID.substring(0, osuID.indexOf(' ')); - else - osuID = null; - - PostBuilder post = new PostBuilder(); - post.addParam("userID", userId); - post.addParam("ssid", ssid); - post.addParam("filename", trackfile.getName()); - post.addParam("hash", hash); - post.addParam("songTitle", beatmap.getTitle()); - post.addParam("songArtist", beatmap.getArtist()); - post.addParam("songCreator", beatmap.getCreator()); - if (osuID != null) - post.addParam("songID", osuID); - - ArrayList response = sendRequest(post, endpoint + "submit.php"); - - if (response == null) { - if (failMessage.equals("Cannot log in") && stayOnline) { - if (tryToLogIn()) { - startPlay(track, hash); - } - } - return; - } - - if (response.size() < 2) { - failMessage = "Invalid server response"; - return; - } - - String[] resp = response.get(1).split("\\s+"); - if (resp.length < 2) { - failMessage = "Invalid server response"; - return; - } - - if (!resp[0].equals("1")) { - return; - } - - playID = resp[1]; - Debug.i("Getting play ID = " + playID); - } - - public boolean sendRecord(String data) throws OnlineManagerException { - if (playID == null || playID.length() == 0) { - failMessage = "I don't have play ID"; - return false; - } - - Debug.i("Sending record..."); - - PostBuilder post = new PostBuilder(); - post.addParam("userID", userId); - post.addParam("playID", playID); - post.addParam("data", data); - - ArrayList response = sendRequest(post, endpoint + "submit.php"); - - if (response == null) { - return false; - } - - if (failMessage.equals("Invalid record data")) - return false; - - if (response.size() < 2) { - failMessage = "Invalid server response"; - return false; - } - - String[] resp = response.get(1).split("\\s+"); - if (resp.length < 4) { - failMessage = "Invalid server response"; - return false; - } - - - rank = Integer.parseInt(resp[0]); - score = Long.parseLong(resp[1]); - accuracy = Integer.parseInt(resp[2]) / 100000f; - mapRank = Integer.parseInt(resp[3]); - - if (resp.length >= 5) { - replayID = Integer.parseInt(resp[4]); - } else - replayID = 0; - - return true; - } - - public ArrayList getTop(final File trackFile, final String hash) throws OnlineManagerException { - PostBuilder post = new PostBuilder(); - post.addParam("filename", trackFile.getName()); - post.addParam("hash", hash); - - ArrayList response = sendRequest(post, endpoint + "getrank.php"); - - if (response == null) { - return new ArrayList(); - } - - response.remove(0); - - return response; - } - - public boolean loadAvatarToTextureManager() { - return loadAvatarToTextureManager(this.avatarURL, "userAvatar"); - } - - public boolean loadAvatarToTextureManager(String avatarURL, String userName) { - if (avatarURL == null || avatarURL.length() == 0) return false; - - String filename = MD5Calcuator.getStringMD5(avatarURL + userName); - Debug.i("Loading avatar from " + avatarURL); - Debug.i("filename = " + filename); - File picfile = new File(Config.getCachePath(), filename); - - if(!picfile.exists()) { - OnlineFileOperator.downloadFile(avatarURL, picfile.getAbsolutePath()); - }else if(picfile.exists() && picfile.length() < 1) { - picfile.delete(); - OnlineFileOperator.downloadFile(avatarURL, picfile.getAbsolutePath()); - } - int imageWidth = 0, imageHeight = 0; - boolean fileAvailable = true; - - try { - BitmapFactory.Options options = new BitmapFactory.Options(); - options.inJustDecodeBounds = true; - imageWidth = BitmapFactory.decodeFile(picfile.getPath()).getWidth(); - imageHeight = BitmapFactory.decodeFile(picfile.getPath()).getHeight(); - options.inJustDecodeBounds = false; - options = null; - } catch (NullPointerException e) { - fileAvailable = false; - } - if (fileAvailable && (imageWidth * imageHeight) > 0) { - //头像已经缓存好在本地 - ResourceManager.getInstance().loadHighQualityFile(userName, picfile); - if (ResourceManager.getInstance().getTextureIfLoaded(userName) != null) { - return true; - } - } - - Debug.i("Success!"); - return false; - } - - public void sendReplay(String filename) { - if (replayID <= 0) return; - Debug.i("Sending replay '" + filename + "' for id = " + replayID); - OnlineFileOperator.sendFile(endpoint + "upload.php", filename, String.valueOf(replayID)); - } - - public String getScorePack(int playid) throws OnlineManagerException { - PostBuilder post = new PostBuilder(); - post.addParam("playID", String.valueOf(playid)); - - ArrayList response = sendRequest(post, endpoint + "gettop.php"); - - if (response == null || response.size() < 2) { - return ""; - } - - return response.get(1); - } - - public String getFailMessage() { - return failMessage; - } - - public long getRank() { - return rank; - } - - public long getScore() { - return score; - } - - public float getAccuracy() { - return accuracy; - } - - public String getAvatarURL() { - return avatarURL; - } - - public String getUsername() { - return username; - } - - public String getUserId() { - return userId; - } - - public String getPassword() { - return password; - } - - public String getDeviceID() { - return deviceID; - } - - public boolean isStayOnline() { - return stayOnline; - } - - public void setStayOnline(boolean stayOnline) { - this.stayOnline = stayOnline; - } - - public boolean isReadyToSend() { - return (playID != null); - } - - public int getMapRank() { - return mapRank; - } - - public static class OnlineManagerException extends Exception { - private static final long serialVersionUID = -5703212596292949401L; - - public OnlineManagerException(final String message, final Throwable cause) { - super(message, cause); - } - - public OnlineManagerException(final String message) { - super(message); - } - } + public static final String hostname = "osudroid.moe"; + public static final String endpoint = "https://" + hostname + "/api/"; + private static final String onlineVersion = "29"; + + public static final OkHttpClient client = new OkHttpClient(); + + private static OnlineManager instance = null; + private Context context; + private String failMessage = ""; + + private boolean stayOnline = true; + private String ssid = ""; + private String userId = ""; + private String playID = ""; + + private String username = ""; + private String password = ""; + private String deviceID = ""; + private long rank = 0; + private long score = 0; + private float accuracy = 0; + private String avatarURL = ""; + private int mapRank; + private int replayID = 0; + + public static OnlineManager getInstance() { + if (instance == null) { + instance = new OnlineManager(); + } + return instance; + } + + public static String getReplayURL(int playID) { + return endpoint + "upload/" + playID + ".odr"; + } + + public void Init(Context context) { + this.stayOnline = Config.isStayOnline(); + this.username = Config.getOnlineUsername(); + this.password = Config.getOnlinePassword(); + this.deviceID = Config.getOnlineDeviceID(); + this.context = context; + } + + private ArrayList sendRequest(PostBuilder post, String url) throws OnlineManagerException { + ArrayList response; + try { + response = post.requestWithAttempts(url, 3); + } catch (RequestException e) { + Debug.e(e.getMessage(), e); + failMessage = "Cannot connect to server"; + throw new OnlineManagerException("Cannot connect to server", e); + } + failMessage = ""; + + //TODO debug code + /*Debug.i("Received " + response.size() + " lines"); + for(String str: response) + { + Debug.i(str); + }*/ + + if (response.size() == 0 || response.get(0).length() == 0) { + failMessage = "Got empty response"; + Debug.i("Received empty response!"); + return null; + } + + if (!response.get(0).equals("SUCCESS")) { + Debug.i("sendRequest response code: " + response.get(0)); + if (response.size() >= 2) { + failMessage = response.get(1); + } else + failMessage = "Unknown server error"; + Debug.i("Received fail: " + failMessage); + return null; + } + + + return response; + } + + public boolean logIn() throws OnlineManagerException { + return logIn(username, password); + } + + public boolean logIn(String username) throws OnlineManagerException { + return logIn(username, password); + } + + public synchronized boolean logIn(String username, String password) throws OnlineManagerException { + this.username = username; + this.password = password; + + PostBuilder post = new PostBuilder(); + post.addParam("username", username); + post.addParam("password", MD5Calcuator.getStringMD5(password + "taikotaiko")); + post.addParam("version", onlineVersion); + + ArrayList response = sendRequest(post, endpoint + "login.php"); + + if (response == null) { + return false; + } + if (response.size() < 2) { + failMessage = "Invalid server response"; + return false; + } + + String[] params = response.get(1).split("\\s+"); + if (params.length < 6) { + failMessage = "Invalid server response"; + return false; + } + userId = params[0]; + ssid = params[1]; + rank = Integer.parseInt(params[2]); + score = Long.parseLong(params[3]); + accuracy = Integer.parseInt(params[4]) / 100000f; + this.username = params[5]; + if (params.length >= 7) { + avatarURL = params[6]; + } else { + avatarURL = ""; + } + + Bundle bParams = new Bundle(); + bParams.putString(FirebaseAnalytics.Param.METHOD, "ingame"); + GlobalManager.getInstance().getMainActivity().getAnalytics().logEvent(FirebaseAnalytics.Event.LOGIN, + bParams); + + return true; + } + + boolean tryToLogIn() throws OnlineManagerException { + if (logIn(username, password) == false) { + stayOnline = false; + return false; + } + return true; + } + + public boolean register(final String username, final String password, final String email, + final String deviceID) throws OnlineManagerException { + PostBuilder post = new PostBuilder(); + post.addParam("username", username); + post.addParam("password", MD5Calcuator.getStringMD5(password + "taikotaiko")); + post.addParam("email", email); + post.addParam("deviceID", deviceID); + + ArrayList response = sendRequest(post, endpoint + "register.php"); + + Bundle params = new Bundle(); + params.putString(FirebaseAnalytics.Param.METHOD, "ingame"); + GlobalManager.getInstance().getMainActivity().getAnalytics().logEvent(FirebaseAnalytics.Event.SIGN_UP, + params); + + return (response != null); + } + + public void startPlay(final TrackInfo track, final String hash) throws OnlineManagerException { + Debug.i("Starting play..."); + playID = null; + final BeatmapInfo beatmap = track.getBeatmap(); + if (beatmap == null) return; + + File trackfile = new File(track.getFilename()); + trackfile.getParentFile().getName(); + String osuID = trackfile.getParentFile().getName(); + Debug.i("osuid = " + osuID); + if (osuID.matches("^[0-9]+ .*")) + osuID = osuID.substring(0, osuID.indexOf(' ')); + else + osuID = null; + + PostBuilder post = new PostBuilder(); + post.addParam("userID", userId); + post.addParam("ssid", ssid); + post.addParam("filename", trackfile.getName()); + post.addParam("hash", hash); + post.addParam("songTitle", beatmap.getTitle()); + post.addParam("songArtist", beatmap.getArtist()); + post.addParam("songCreator", beatmap.getCreator()); + if (osuID != null) + post.addParam("songID", osuID); + + ArrayList response = sendRequest(post, endpoint + "submit.php"); + + if (response == null) { + if (failMessage.equals("Cannot log in") && stayOnline) { + if (tryToLogIn()) { + startPlay(track, hash); + } + } + return; + } + + if (response.size() < 2) { + failMessage = "Invalid server response"; + return; + } + + String[] resp = response.get(1).split("\\s+"); + if (resp.length < 2) { + failMessage = "Invalid server response"; + return; + } + + if (!resp[0].equals("1")) { + return; + } + + playID = resp[1]; + Debug.i("Getting play ID = " + playID); + } + + public boolean sendRecord(String data) throws OnlineManagerException { + if (playID == null || playID.length() == 0) { + failMessage = "I don't have play ID"; + return false; + } + + Debug.i("Sending record..."); + + PostBuilder post = new PostBuilder(); + post.addParam("userID", userId); + post.addParam("playID", playID); + post.addParam("data", data); + + ArrayList response = sendRequest(post, endpoint + "submit.php"); + + if (response == null) { + return false; + } + + if (failMessage.equals("Invalid record data")) + return false; + + if (response.size() < 2) { + failMessage = "Invalid server response"; + return false; + } + + String[] resp = response.get(1).split("\\s+"); + if (resp.length < 4) { + failMessage = "Invalid server response"; + return false; + } + + + rank = Integer.parseInt(resp[0]); + score = Long.parseLong(resp[1]); + accuracy = Integer.parseInt(resp[2]) / 100000f; + mapRank = Integer.parseInt(resp[3]); + + if (resp.length >= 5) { + replayID = Integer.parseInt(resp[4]); + } else + replayID = 0; + + return true; + } + + public ArrayList getTop(final File trackFile, final String hash) throws OnlineManagerException { + PostBuilder post = new PostBuilder(); + post.addParam("filename", trackFile.getName()); + post.addParam("hash", hash); + + ArrayList response = sendRequest(post, endpoint + "getrank.php"); + + if (response == null) { + return new ArrayList(); + } + + response.remove(0); + + return response; + } + + public boolean loadAvatarToTextureManager() { + return loadAvatarToTextureManager(this.avatarURL, "userAvatar"); + } + + public boolean loadAvatarToTextureManager(String avatarURL, String userName) { + if (avatarURL == null || avatarURL.length() == 0) return false; + + String filename = MD5Calcuator.getStringMD5(avatarURL + userName); + Debug.i("Loading avatar from " + avatarURL); + Debug.i("filename = " + filename); + File picfile = new File(Config.getCachePath(), filename); + + if(!picfile.exists()) { + OnlineFileOperator.downloadFile(avatarURL, picfile.getAbsolutePath()); + }else if(picfile.exists() && picfile.length() < 1) { + picfile.delete(); + OnlineFileOperator.downloadFile(avatarURL, picfile.getAbsolutePath()); + } + int imageWidth = 0, imageHeight = 0; + boolean fileAvailable = true; + + try { + BitmapFactory.Options options = new BitmapFactory.Options(); + options.inJustDecodeBounds = true; + imageWidth = BitmapFactory.decodeFile(picfile.getPath()).getWidth(); + imageHeight = BitmapFactory.decodeFile(picfile.getPath()).getHeight(); + options.inJustDecodeBounds = false; + options = null; + } catch (NullPointerException e) { + fileAvailable = false; + } + if (fileAvailable && (imageWidth * imageHeight) > 0) { + //头像已经缓存好在本地 + ResourceManager.getInstance().loadHighQualityFile(userName, picfile); + if (ResourceManager.getInstance().getTextureIfLoaded(userName) != null) { + return true; + } + } + + Debug.i("Success!"); + return false; + } + + public void sendReplay(String filename) { + if (replayID <= 0) return; + Debug.i("Sending replay '" + filename + "' for id = " + replayID); + OnlineFileOperator.sendFile(endpoint + "upload.php", filename, String.valueOf(replayID)); + } + + public String getScorePack(int playid) throws OnlineManagerException { + PostBuilder post = new PostBuilder(); + post.addParam("playID", String.valueOf(playid)); + + ArrayList response = sendRequest(post, endpoint + "gettop.php"); + + if (response == null || response.size() < 2) { + return ""; + } + + return response.get(1); + } + + public String getFailMessage() { + return failMessage; + } + + public long getRank() { + return rank; + } + + public long getScore() { + return score; + } + + public float getAccuracy() { + return accuracy; + } + + public String getAvatarURL() { + return avatarURL; + } + + public String getUsername() { + return username; + } + + public String getUserId() { + return userId; + } + + public String getPassword() { + return password; + } + + public String getDeviceID() { + return deviceID; + } + + public boolean isStayOnline() { + return stayOnline; + } + + public void setStayOnline(boolean stayOnline) { + this.stayOnline = stayOnline; + } + + public boolean isReadyToSend() { + return (playID != null); + } + + public int getMapRank() { + return mapRank; + } + + public static class OnlineManagerException extends Exception { + private static final long serialVersionUID = -5703212596292949401L; + + public OnlineManagerException(final String message, final Throwable cause) { + super(message, cause); + } + + public OnlineManagerException(final String message) { + super(message); + } + } } diff --git a/src/ru/nsu/ccfit/zuev/osu/online/OnlinePanel.java b/src/ru/nsu/ccfit/zuev/osu/online/OnlinePanel.java index b346c31f..475032c9 100644 --- a/src/ru/nsu/ccfit/zuev/osu/online/OnlinePanel.java +++ b/src/ru/nsu/ccfit/zuev/osu/online/OnlinePanel.java @@ -17,147 +17,147 @@ import ru.nsu.ccfit.zuev.osuplus.R; public class OnlinePanel extends Entity { - private Entity onlineLayer = new Entity(); - private Entity messageLayer = new Entity(); - private Entity frontLayer = new Entity(); - - public Rectangle rect; - - private ChangeableText rankText, nameText, scoreText, accText; - private ChangeableText messageText, submessageText; - private Sprite avatar = null; - - public OnlinePanel() { - rect = new Rectangle(0, 0, Utils.toRes(410), Utils.toRes(110)) { - boolean moved = false; - float dx = 0, dy = 0; - - @Override - public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final float pTouchAreaLocalX, final float pTouchAreaLocalY) { - if (pSceneTouchEvent.isActionDown()) { - this.setColor(0.3f, 0.3f, 0.3f, 0.9f); - moved = false; - dx = pTouchAreaLocalX; - dy = pTouchAreaLocalY; - return true; - } - if (pSceneTouchEvent.isActionUp()) { - this.setColor(0.2f, 0.2f, 0.2f, 0.5f); - if (!moved) { - if(OnlineManager.getInstance().isStayOnline()) { - new ConfirmDialogFragment() - .setMessage(R.string.dialog_visit_profile_page) - .showForResult(isAccepted -> { - GlobalManager.getInstance().getMainActivity().runOnUiThread(() -> { - new WebViewFragment().setURL( - WebViewFragment.PROFILE_URL + OnlineManager.getInstance().getUserId()) - .show(); - }); - }); - } - } - return true; - } - if (pSceneTouchEvent.isActionOutside() - || pSceneTouchEvent.isActionMove() - && (MathUtils.distance(dx, dy, pTouchAreaLocalX, - pTouchAreaLocalY) > 50)) { - moved = true; - this.setColor(0.2f, 0.2f, 0.2f, 0.5f); - } - return false; - } - }; - rect.setColor(0.2f, 0.2f, 0.2f, 0.5f); - attachChild(rect); - - Rectangle avatarFooter = new Rectangle(0, 0, Utils.toRes(110), Utils.toRes(110)); - avatarFooter.setColor(0.2f, 0.2f, 0.2f, 0.8f); - attachChild(avatarFooter); - - /*Rectangle rightFooter = new Rectangle(Utils.toRes(410), 0, Utils.toRes(614), Utils.toRes(110)); - rightFooter.setColor(0.3f, 0.3f, 0.3f, 0.35f); - attachChild(rightFooter);*/ - - rankText = new ChangeableText(0, 0, - ResourceManager.getInstance().getFont("CaptionFont"), "#1", - HorizontalAlign.RIGHT, 12); - rankText.setColor(0.6f, 0.6f, 0.6f, 0.9f); - rankText.setScaleCenterX(0); - rankText.setScale(1.7f); - rankText.setPosition(Utils.toRes(390 + 10) - rankText.getWidthScaled(), Utils.toRes(55)); - onlineLayer.attachChild(rankText); - - nameText = new ChangeableText(Utils.toRes(120), Utils.toRes(5), - ResourceManager.getInstance().getFont("CaptionFont"), "Guest", 16); - onlineLayer.attachChild(nameText); - scoreText = new ChangeableText(Utils.toRes(120), Utils.toRes(50), - ResourceManager.getInstance().getFont("smallFont"), "Score: 0", - HorizontalAlign.LEFT, 22); - scoreText.setColor(0.85f, 0.85f, 0.9f); - onlineLayer.attachChild(scoreText); - - accText = new ChangeableText(Utils.toRes(120), Utils.toRes(75), - ResourceManager.getInstance().getFont("smallFont"), "Accuracy: 0.00%", - HorizontalAlign.LEFT, 17); - accText.setColor(0.85f, 0.85f, 0.9f); - onlineLayer.attachChild(accText); - - messageText = new ChangeableText(Utils.toRes(110), Utils.toRes(5), - ResourceManager.getInstance().getFont("CaptionFont"), "Logging in...", 16); - messageLayer.attachChild(messageText); - - submessageText = new ChangeableText(Utils.toRes(110), Utils.toRes(60), - ResourceManager.getInstance().getFont("smallFont"), "Connecting to server...", 40); - messageLayer.attachChild(submessageText); - - attachChild(messageLayer); - attachChild(frontLayer); - - } - - void setMessage(final String message, final String submessage) { - messageText.setText(message); - submessageText.setText(submessage); - - messageLayer.detachSelf(); - onlineLayer.detachSelf(); - attachChild(messageLayer); - } - - void setInfo() { - nameText.setText(OnlineManager.getInstance().getUsername()); - StringBuilder scoreBuilder = new StringBuilder("Score: "); - scoreBuilder.append(OnlineManager.getInstance().getScore()); - for (int i = scoreBuilder.length() - 3; i > 7; i -= 3) { - scoreBuilder.insert(i, ' '); - } - - scoreText.setText(scoreBuilder.toString()); - - accText.setText(String.format("Accuracy: %.2f%%", - OnlineManager.getInstance().getAccuracy() * 100f)); - rankText.setScale(1); - rankText.setText(String.format("#%d", OnlineManager.getInstance().getRank())); - rankText.setPosition(Utils.toRes(390 + 10) - rankText.getWidth() * 1.7f, Utils.toRes(55)); - rankText.setScaleCenterX(0); - rankText.setScale(1.7f); - - messageLayer.detachSelf(); - onlineLayer.detachSelf(); - attachChild(onlineLayer); - } - - void setAvatar(final String texname) { - if (avatar != null) - avatar.detachSelf(); - avatar = null; - if (texname == null) return; - TextureRegion tex = ResourceManager.getInstance().getTextureIfLoaded(texname); - if (tex == null) return; - - Debug.i("Avatar is set!"); - avatar = new Sprite(0, 0, Utils.toRes(110), Utils.toRes(110), tex); - frontLayer.attachChild(avatar); - } -} \ No newline at end of file + private Entity onlineLayer = new Entity(); + private Entity messageLayer = new Entity(); + private Entity frontLayer = new Entity(); + + public Rectangle rect; + + private ChangeableText rankText, nameText, scoreText, accText; + private ChangeableText messageText, submessageText; + private Sprite avatar = null; + + public OnlinePanel() { + rect = new Rectangle(0, 0, Utils.toRes(410), Utils.toRes(110)) { + boolean moved = false; + float dx = 0, dy = 0; + + @Override + public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final float pTouchAreaLocalX, final float pTouchAreaLocalY) { + if (pSceneTouchEvent.isActionDown()) { + this.setColor(0.3f, 0.3f, 0.3f, 0.9f); + moved = false; + dx = pTouchAreaLocalX; + dy = pTouchAreaLocalY; + return true; + } + if (pSceneTouchEvent.isActionUp()) { + this.setColor(0.2f, 0.2f, 0.2f, 0.5f); + if (!moved) { + if(OnlineManager.getInstance().isStayOnline()) { + new ConfirmDialogFragment() + .setMessage(R.string.dialog_visit_profile_page) + .showForResult(isAccepted -> { + GlobalManager.getInstance().getMainActivity().runOnUiThread(() -> { + new WebViewFragment().setURL( + WebViewFragment.PROFILE_URL + OnlineManager.getInstance().getUserId()) + .show(); + }); + }); + } + } + return true; + } + if (pSceneTouchEvent.isActionOutside() + || pSceneTouchEvent.isActionMove() + && (MathUtils.distance(dx, dy, pTouchAreaLocalX, + pTouchAreaLocalY) > 50)) { + moved = true; + this.setColor(0.2f, 0.2f, 0.2f, 0.5f); + } + return false; + } + }; + rect.setColor(0.2f, 0.2f, 0.2f, 0.5f); + attachChild(rect); + + Rectangle avatarFooter = new Rectangle(0, 0, Utils.toRes(110), Utils.toRes(110)); + avatarFooter.setColor(0.2f, 0.2f, 0.2f, 0.8f); + attachChild(avatarFooter); + + /*Rectangle rightFooter = new Rectangle(Utils.toRes(410), 0, Utils.toRes(614), Utils.toRes(110)); + rightFooter.setColor(0.3f, 0.3f, 0.3f, 0.35f); + attachChild(rightFooter);*/ + + rankText = new ChangeableText(0, 0, + ResourceManager.getInstance().getFont("CaptionFont"), "#1", + HorizontalAlign.RIGHT, 12); + rankText.setColor(0.6f, 0.6f, 0.6f, 0.9f); + rankText.setScaleCenterX(0); + rankText.setScale(1.7f); + rankText.setPosition(Utils.toRes(390 + 10) - rankText.getWidthScaled(), Utils.toRes(55)); + onlineLayer.attachChild(rankText); + + nameText = new ChangeableText(Utils.toRes(120), Utils.toRes(5), + ResourceManager.getInstance().getFont("CaptionFont"), "Guest", 16); + onlineLayer.attachChild(nameText); + scoreText = new ChangeableText(Utils.toRes(120), Utils.toRes(50), + ResourceManager.getInstance().getFont("smallFont"), "Score: 0", + HorizontalAlign.LEFT, 22); + scoreText.setColor(0.85f, 0.85f, 0.9f); + onlineLayer.attachChild(scoreText); + + accText = new ChangeableText(Utils.toRes(120), Utils.toRes(75), + ResourceManager.getInstance().getFont("smallFont"), "Accuracy: 0.00%", + HorizontalAlign.LEFT, 17); + accText.setColor(0.85f, 0.85f, 0.9f); + onlineLayer.attachChild(accText); + + messageText = new ChangeableText(Utils.toRes(110), Utils.toRes(5), + ResourceManager.getInstance().getFont("CaptionFont"), "Logging in...", 16); + messageLayer.attachChild(messageText); + + submessageText = new ChangeableText(Utils.toRes(110), Utils.toRes(60), + ResourceManager.getInstance().getFont("smallFont"), "Connecting to server...", 40); + messageLayer.attachChild(submessageText); + + attachChild(messageLayer); + attachChild(frontLayer); + + } + + void setMessage(final String message, final String submessage) { + messageText.setText(message); + submessageText.setText(submessage); + + messageLayer.detachSelf(); + onlineLayer.detachSelf(); + attachChild(messageLayer); + } + + void setInfo() { + nameText.setText(OnlineManager.getInstance().getUsername()); + StringBuilder scoreBuilder = new StringBuilder("Score: "); + scoreBuilder.append(OnlineManager.getInstance().getScore()); + for (int i = scoreBuilder.length() - 3; i > 7; i -= 3) { + scoreBuilder.insert(i, ' '); + } + + scoreText.setText(scoreBuilder.toString()); + + accText.setText(String.format("Accuracy: %.2f%%", + OnlineManager.getInstance().getAccuracy() * 100f)); + rankText.setScale(1); + rankText.setText(String.format("#%d", OnlineManager.getInstance().getRank())); + rankText.setPosition(Utils.toRes(390 + 10) - rankText.getWidth() * 1.7f, Utils.toRes(55)); + rankText.setScaleCenterX(0); + rankText.setScale(1.7f); + + messageLayer.detachSelf(); + onlineLayer.detachSelf(); + attachChild(onlineLayer); + } + + void setAvatar(final String texname) { + if (avatar != null) + avatar.detachSelf(); + avatar = null; + if (texname == null) return; + TextureRegion tex = ResourceManager.getInstance().getTextureIfLoaded(texname); + if (tex == null) return; + + Debug.i("Avatar is set!"); + avatar = new Sprite(0, 0, Utils.toRes(110), Utils.toRes(110), tex); + frontLayer.attachChild(avatar); + } +} diff --git a/src/ru/nsu/ccfit/zuev/osu/online/OnlineScoring.java b/src/ru/nsu/ccfit/zuev/osu/online/OnlineScoring.java index 8d72e27a..4751cc2b 100644 --- a/src/ru/nsu/ccfit/zuev/osu/online/OnlineScoring.java +++ b/src/ru/nsu/ccfit/zuev/osu/online/OnlineScoring.java @@ -15,245 +15,245 @@ import ru.nsu.ccfit.zuev.osu.scoring.StatisticV2; public class OnlineScoring { - private static final int attemptCount = 5; - private static OnlineScoring instance = null; - private Boolean onlineMutex = new Boolean(false); - private OnlinePanel panel = null; - private OnlinePanel secondPanel = null; - private boolean avatarLoaded = false; - - public static OnlineScoring getInstance() { - if (instance == null) - instance = new OnlineScoring(); - return instance; - } - - public void createPanel() { - panel = new OnlinePanel(); - } - - public OnlinePanel getPanel() { - return panel; - } - - public OnlinePanel createSecondPanel() { - if (OnlineManager.getInstance().isStayOnline() == false) - return null; - secondPanel = new OnlinePanel(); - secondPanel.setInfo(); - secondPanel.setAvatar(avatarLoaded ? "userAvatar" : null); - return secondPanel; - } - - public OnlinePanel getSecondPanel() { - return secondPanel; - } - - public void setPanelMessage(String message, String submessage) { - panel.setMessage(message, submessage); - if (secondPanel != null) - secondPanel.setMessage(message, submessage); - } - - public void updatePanels() { - panel.setInfo(); - if (secondPanel != null) - secondPanel.setInfo(); - } - - public void updatePanelAvatars() { - String texname = avatarLoaded ? "userAvatar" : null; - panel.setAvatar(texname); - if (secondPanel != null) - secondPanel.setAvatar(texname); - } - - public void login() { - if (OnlineManager.getInstance().isStayOnline() == false) - return; - avatarLoaded = false; - new AsyncTaskLoader().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, new OsuAsyncCallback() { - - - public void run() { - synchronized (onlineMutex) { - boolean success = false; - - //Trying to send request - for (int i = 0; i < 3; i++) { - setPanelMessage("Logging in...", ""); - - try { - success = OnlineManager.getInstance().logIn(); - } catch (OnlineManagerException e) { - Debug.e("Login error: " + e.getMessage()); - setPanelMessage("Login failed", "Retrying in 5 sec"); - try { - Thread.sleep(3000); - } catch (InterruptedException e1) { - break; - } - continue; - } - break; - } - if (success) { - updatePanels(); - OnlineManager.getInstance().setStayOnline(true); - loadAvatar(true); - } else { - setPanelMessage("Cannot log in", OnlineManager.getInstance().getFailMessage()); - OnlineManager.getInstance().setStayOnline(false); - } - } - } - - - public void onComplete() { - // TODO Auto-generated method stub - - } - }); - } - - public void startPlay(final TrackInfo track, final String hash) { - if (OnlineManager.getInstance().isStayOnline() == false) - return; - new AsyncTaskLoader().execute(new OsuAsyncCallback() { - - - public void run() { - synchronized (onlineMutex) { - - for (int i = 0; i < attemptCount; i++) { - try { - OnlineManager.getInstance().startPlay(track, hash); - } catch (OnlineManagerException e) { - Debug.e("Login error: " + e.getMessage()); - continue; - } - break; - } - - if (OnlineManager.getInstance().getFailMessage().length() > 0) { - ToastLogger.showText(OnlineManager.getInstance().getFailMessage(), true); - } - } - } - - - public void onComplete() { - // TODO Auto-generated method stub - - } - }); - } - - public void sendRecord(final StatisticV2 record, final SendingPanel panel, final String replay) { - if (OnlineManager.getInstance().isStayOnline() == false) - return; - if (OnlineManager.getInstance().isReadyToSend() == false) - return; - - Debug.i("Sending score"); - - final String recordData = record.compile(); - - new AsyncTaskLoader().execute(new OsuAsyncCallback() { - - - public void run() { - boolean success = false; - synchronized (onlineMutex) { - for (int i = 0; i < attemptCount; i++) { - if (!record.isScoreValid()) { - Debug.e("Detected illegal actions."); - break; - } - - try { - success = OnlineManager.getInstance().sendRecord(recordData); - } catch (OnlineManagerException e) { - Debug.e("Login error: " + e.getMessage()); - success = false; - } - - if (OnlineManager.getInstance().getFailMessage().length() > 0) { - ToastLogger.showText(OnlineManager.getInstance().getFailMessage(), true); - if (OnlineManager.getInstance().getFailMessage().equals("Invalid record data")) - i = attemptCount; - } else if (success) { - updatePanels(); - OnlineManager mgr = OnlineManager.getInstance(); - panel.show(mgr.getMapRank(), mgr.getScore(), mgr.getRank(), mgr.getAccuracy()); - OnlineManager.getInstance().sendReplay(replay); - break; - } - - - try { - Thread.sleep(5000); - } catch (InterruptedException e) { - } - } - - if (!success) { - panel.setFail(); - } - - } - } - - - public void onComplete() { - // TODO Auto-generated method stub - - } - }); - } - - public ArrayList getTop(final File trackFile, final String hash) { - synchronized (onlineMutex) { - try { - return OnlineManager.getInstance().getTop(trackFile, hash); - } catch (OnlineManagerException e) { - Debug.e("Cannot load scores " + e.getMessage()); - return new ArrayList(); - } - } - } - - public void loadAvatar(final boolean both) { - if (!OnlineManager.getInstance().isStayOnline()) return; - final String avatarUrl = OnlineManager.getInstance().getAvatarURL(); - if (avatarUrl == null || avatarUrl.length() == 0) - return; - - new AsyncTaskLoader().execute(new OsuAsyncCallback() { - - - public void run() { - synchronized (onlineMutex) { - if (OnlineManager.getInstance().loadAvatarToTextureManager()) { - avatarLoaded = true; - } else - avatarLoaded = false; - if (both) - updatePanelAvatars(); - else if (secondPanel != null) - secondPanel.setAvatar(avatarLoaded ? "userAvatar" : null); - } - } - - - public void onComplete() { - // TODO Auto-generated method stub - - } - }); - } - - public boolean isAvatarLoaded() { - return avatarLoaded; - } + private static final int attemptCount = 5; + private static OnlineScoring instance = null; + private Boolean onlineMutex = new Boolean(false); + private OnlinePanel panel = null; + private OnlinePanel secondPanel = null; + private boolean avatarLoaded = false; + + public static OnlineScoring getInstance() { + if (instance == null) + instance = new OnlineScoring(); + return instance; + } + + public void createPanel() { + panel = new OnlinePanel(); + } + + public OnlinePanel getPanel() { + return panel; + } + + public OnlinePanel createSecondPanel() { + if (OnlineManager.getInstance().isStayOnline() == false) + return null; + secondPanel = new OnlinePanel(); + secondPanel.setInfo(); + secondPanel.setAvatar(avatarLoaded ? "userAvatar" : null); + return secondPanel; + } + + public OnlinePanel getSecondPanel() { + return secondPanel; + } + + public void setPanelMessage(String message, String submessage) { + panel.setMessage(message, submessage); + if (secondPanel != null) + secondPanel.setMessage(message, submessage); + } + + public void updatePanels() { + panel.setInfo(); + if (secondPanel != null) + secondPanel.setInfo(); + } + + public void updatePanelAvatars() { + String texname = avatarLoaded ? "userAvatar" : null; + panel.setAvatar(texname); + if (secondPanel != null) + secondPanel.setAvatar(texname); + } + + public void login() { + if (OnlineManager.getInstance().isStayOnline() == false) + return; + avatarLoaded = false; + new AsyncTaskLoader().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, new OsuAsyncCallback() { + + + public void run() { + synchronized (onlineMutex) { + boolean success = false; + + //Trying to send request + for (int i = 0; i < 3; i++) { + setPanelMessage("Logging in...", ""); + + try { + success = OnlineManager.getInstance().logIn(); + } catch (OnlineManagerException e) { + Debug.e("Login error: " + e.getMessage()); + setPanelMessage("Login failed", "Retrying in 5 sec"); + try { + Thread.sleep(3000); + } catch (InterruptedException e1) { + break; + } + continue; + } + break; + } + if (success) { + updatePanels(); + OnlineManager.getInstance().setStayOnline(true); + loadAvatar(true); + } else { + setPanelMessage("Cannot log in", OnlineManager.getInstance().getFailMessage()); + OnlineManager.getInstance().setStayOnline(false); + } + } + } + + + public void onComplete() { + // TODO Auto-generated method stub + + } + }); + } + + public void startPlay(final TrackInfo track, final String hash) { + if (OnlineManager.getInstance().isStayOnline() == false) + return; + new AsyncTaskLoader().execute(new OsuAsyncCallback() { + + + public void run() { + synchronized (onlineMutex) { + + for (int i = 0; i < attemptCount; i++) { + try { + OnlineManager.getInstance().startPlay(track, hash); + } catch (OnlineManagerException e) { + Debug.e("Login error: " + e.getMessage()); + continue; + } + break; + } + + if (OnlineManager.getInstance().getFailMessage().length() > 0) { + ToastLogger.showText(OnlineManager.getInstance().getFailMessage(), true); + } + } + } + + + public void onComplete() { + // TODO Auto-generated method stub + + } + }); + } + + public void sendRecord(final StatisticV2 record, final SendingPanel panel, final String replay) { + if (OnlineManager.getInstance().isStayOnline() == false) + return; + if (OnlineManager.getInstance().isReadyToSend() == false) + return; + + Debug.i("Sending score"); + + final String recordData = record.compile(); + + new AsyncTaskLoader().execute(new OsuAsyncCallback() { + + + public void run() { + boolean success = false; + synchronized (onlineMutex) { + for (int i = 0; i < attemptCount; i++) { + if (!record.isScoreValid()) { + Debug.e("Detected illegal actions."); + break; + } + + try { + success = OnlineManager.getInstance().sendRecord(recordData); + } catch (OnlineManagerException e) { + Debug.e("Login error: " + e.getMessage()); + success = false; + } + + if (OnlineManager.getInstance().getFailMessage().length() > 0) { + ToastLogger.showText(OnlineManager.getInstance().getFailMessage(), true); + if (OnlineManager.getInstance().getFailMessage().equals("Invalid record data")) + i = attemptCount; + } else if (success) { + updatePanels(); + OnlineManager mgr = OnlineManager.getInstance(); + panel.show(mgr.getMapRank(), mgr.getScore(), mgr.getRank(), mgr.getAccuracy()); + OnlineManager.getInstance().sendReplay(replay); + break; + } + + + try { + Thread.sleep(5000); + } catch (InterruptedException e) { + } + } + + if (!success) { + panel.setFail(); + } + + } + } + + + public void onComplete() { + // TODO Auto-generated method stub + + } + }); + } + + public ArrayList getTop(final File trackFile, final String hash) { + synchronized (onlineMutex) { + try { + return OnlineManager.getInstance().getTop(trackFile, hash); + } catch (OnlineManagerException e) { + Debug.e("Cannot load scores " + e.getMessage()); + return new ArrayList(); + } + } + } + + public void loadAvatar(final boolean both) { + if (!OnlineManager.getInstance().isStayOnline()) return; + final String avatarUrl = OnlineManager.getInstance().getAvatarURL(); + if (avatarUrl == null || avatarUrl.length() == 0) + return; + + new AsyncTaskLoader().execute(new OsuAsyncCallback() { + + + public void run() { + synchronized (onlineMutex) { + if (OnlineManager.getInstance().loadAvatarToTextureManager()) { + avatarLoaded = true; + } else + avatarLoaded = false; + if (both) + updatePanelAvatars(); + else if (secondPanel != null) + secondPanel.setAvatar(avatarLoaded ? "userAvatar" : null); + } + } + + + public void onComplete() { + // TODO Auto-generated method stub + + } + }); + } + + public boolean isAvatarLoaded() { + return avatarLoaded; + } } diff --git a/src/ru/nsu/ccfit/zuev/osu/online/PostBuilder.java b/src/ru/nsu/ccfit/zuev/osu/online/PostBuilder.java index 648a3059..aaaefff0 100644 --- a/src/ru/nsu/ccfit/zuev/osu/online/PostBuilder.java +++ b/src/ru/nsu/ccfit/zuev/osu/online/PostBuilder.java @@ -19,96 +19,96 @@ import ru.nsu.ccfit.zuev.osuplus.BuildConfig; public class PostBuilder { - private FormBody.Builder formBodyBuilder = new FormBody.Builder(); - private StringBuilder values = new StringBuilder(); - - public void addParam(final String key, final String value) { - try { - if (values.length() > 0) { - values.append("_"); - } - formBodyBuilder.add(key, value); - values.append(URLEncoder.encode(value, "UTF-8")); - } catch (UnsupportedEncodingException e) { - return; - } - - } - - public ArrayList requestWithAttempts(final String scriptUrl, int attempts) throws RequestException { - ArrayList response = null; - String signature = SecurityUtils.signRequest(values.toString()); - - if (signature != null) { - addParam("sign", signature); - } - for (int i = 0; i < attempts; i++) { - try { - response = request(scriptUrl); - } catch (RequestException e) { - if (e.getCause() instanceof UnknownHostException) { - Debug.e("Cannot resolve server name"); - break; - } - Debug.e("Received error, continuing... ", e); - response = null; - } - - if (response == null || response.isEmpty() || response.get(0).length() == 0 - || !(response.get(0).equals("FAIL") || response.get(0).equals("SUCCESS"))) { - try { - Thread.sleep(3000); - } catch (InterruptedException e) { - } - continue; - } - break; - } - - if (response == null) response = new ArrayList(); - - if (response.isEmpty()) { - response.add(""); - } - return response; - } - - private ArrayList request(final String scriptUrl) throws RequestException { - String data = values.toString(); - ArrayList response = new ArrayList(); - - try { - Request request = new Request.Builder() - .url(scriptUrl) - .post(formBodyBuilder.build()) - .build(); - Response resp = OnlineManager.client.newCall(request).execute(); - - Debug.i("request url=" + scriptUrl); - Debug.i("request --------Content---------"); - String line = null; - BufferedReader reader = new BufferedReader(new StringReader(resp.body().string())); - while((line = reader.readLine()) != null) { - Debug.i(String.format("request [%d]: %s", response.size(), line)); - response.add(line); - } - Debug.i("request url=" + scriptUrl); - Debug.i("request -----End of content-----"); - } catch(Exception e) { - Debug.e(e.getMessage(), e); - } - - if (response.isEmpty()) { - response.add(""); - } - return response; - } - - public static class RequestException extends Exception { - private static final long serialVersionUID = 671773899432746143L; - - public RequestException(final Throwable cause) { - super(cause); - } - } + private FormBody.Builder formBodyBuilder = new FormBody.Builder(); + private StringBuilder values = new StringBuilder(); + + public void addParam(final String key, final String value) { + try { + if (values.length() > 0) { + values.append("_"); + } + formBodyBuilder.add(key, value); + values.append(URLEncoder.encode(value, "UTF-8")); + } catch (UnsupportedEncodingException e) { + return; + } + + } + + public ArrayList requestWithAttempts(final String scriptUrl, int attempts) throws RequestException { + ArrayList response = null; + String signature = SecurityUtils.signRequest(values.toString()); + + if (signature != null) { + addParam("sign", signature); + } + for (int i = 0; i < attempts; i++) { + try { + response = request(scriptUrl); + } catch (RequestException e) { + if (e.getCause() instanceof UnknownHostException) { + Debug.e("Cannot resolve server name"); + break; + } + Debug.e("Received error, continuing... ", e); + response = null; + } + + if (response == null || response.isEmpty() || response.get(0).length() == 0 + || !(response.get(0).equals("FAIL") || response.get(0).equals("SUCCESS"))) { + try { + Thread.sleep(3000); + } catch (InterruptedException e) { + } + continue; + } + break; + } + + if (response == null) response = new ArrayList(); + + if (response.isEmpty()) { + response.add(""); + } + return response; + } + + private ArrayList request(final String scriptUrl) throws RequestException { + String data = values.toString(); + ArrayList response = new ArrayList(); + + try { + Request request = new Request.Builder() + .url(scriptUrl) + .post(formBodyBuilder.build()) + .build(); + Response resp = OnlineManager.client.newCall(request).execute(); + + Debug.i("request url=" + scriptUrl); + Debug.i("request --------Content---------"); + String line = null; + BufferedReader reader = new BufferedReader(new StringReader(resp.body().string())); + while((line = reader.readLine()) != null) { + Debug.i(String.format("request [%d]: %s", response.size(), line)); + response.add(line); + } + Debug.i("request url=" + scriptUrl); + Debug.i("request -----End of content-----"); + } catch(Exception e) { + Debug.e(e.getMessage(), e); + } + + if (response.isEmpty()) { + response.add(""); + } + return response; + } + + public static class RequestException extends Exception { + private static final long serialVersionUID = 671773899432746143L; + + public RequestException(final Throwable cause) { + super(cause); + } + } } diff --git a/src/ru/nsu/ccfit/zuev/osu/online/SendingPanel.java b/src/ru/nsu/ccfit/zuev/osu/online/SendingPanel.java index c4dc02d6..f8a8dbd4 100644 --- a/src/ru/nsu/ccfit/zuev/osu/online/SendingPanel.java +++ b/src/ru/nsu/ccfit/zuev/osu/online/SendingPanel.java @@ -15,164 +15,164 @@ import ru.nsu.ccfit.zuev.osu.Utils; public class SendingPanel extends Rectangle { - private ChangeableText mapText, rankText, accText, scoreText; - private ChangeableText buttonText; - private Rectangle mapRect, rankRect, accRect, scoreRect; - private Sprite button; - - private long rank, score; - private float accuracy; - private boolean canBeDismissed = false; - - public SendingPanel(long rank, long score, float accuracy) { - super(0, Utils.toRes(-300), Utils.toRes(800), Utils.toRes(300)); - TextureRegion btnTex = ResourceManager.getInstance(). - getTexture("ranking_button"); - - this.rank = rank; - this.score = score; - this.accuracy = accuracy; - setColor(0, 0, 0, 0.7f); - - button = new Sprite(Utils.toRes(272), Utils.toRes(300), btnTex) { - - - @Override - public boolean onAreaTouched(TouchEvent pSceneTouchEvent, - float pTouchAreaLocalX, float pTouchAreaLocalY) { - if (canBeDismissed) { - SendingPanel.this.registerEntityModifier(new MoveYModifier(0.5f, 0, - Utils.toRes(-350))); - canBeDismissed = false; - return true; - } - return false; - } - }; - attachChild(button); - - buttonText = new ChangeableText(Utils.toRes(340), Utils.toRes(305), - ResourceManager.getInstance().getFont("font"), - "Sending...", HorizontalAlign.CENTER, 10); - attachChild(buttonText); - - Text topScoreText = new Text(0, 0, - ResourceManager.getInstance().getFont("CaptionFonrt"), "Overall Ranking"); - topScoreText.setPosition(Utils.toRes(400) - topScoreText.getWidth() / 2, Utils.toRes(60)); - attachChild(topScoreText); - - Text tableCaption = new Text(Utils.toRes(60), Utils.toRes(120), - ResourceManager.getInstance().getFont("font"), - "Map rank Overall Accuracy Ranked score"); - attachChild(tableCaption); - - mapRect = new Rectangle(Utils.toRes(50), Utils.toRes(160), - Utils.toRes(140), Utils.toRes(80)); - mapRect.setColor(1, 1, 0, 0.8f); - attachChild(mapRect); - - rankRect = new Rectangle(Utils.toRes(195), Utils.toRes(160), - Utils.toRes(150), Utils.toRes(80)); - attachChild(rankRect); - - accRect = new Rectangle(Utils.toRes(350), Utils.toRes(160), - Utils.toRes(150), Utils.toRes(80)); - attachChild(accRect); - - scoreRect = new Rectangle(Utils.toRes(505), Utils.toRes(160), - Utils.toRes(250), Utils.toRes(80)); - attachChild(scoreRect); - - Font font = ResourceManager.getInstance().getFont("font"); - mapText = new ChangeableText(0, 0, font, "#9999999", HorizontalAlign.CENTER, 8); - placeText(mapRect, mapText); - attachChild(mapText); - - rankText = new ChangeableText(0, 0, font, "#9999999\n(+100)", HorizontalAlign.CENTER, 19); - placeText(rankRect, rankText); - attachChild(rankText); - - accText = new ChangeableText(0, 0, font, "100.00%\n(+21.90%)", HorizontalAlign.CENTER, 16); - placeText(accRect, accText); - attachChild(accText); - - scoreText = new ChangeableText(0, 0, font, "99 123 456 789\n(+99 999 999)", HorizontalAlign.CENTER, 100); - placeText(scoreRect, scoreText); - attachChild(scoreText); - } - - private void placeText(Rectangle rect, ChangeableText text) { - text.setPosition(rect.getX() + rect.getWidth() / 2 - text.getWidth() / 2, - rect.getY() + rect.getHeight() / 2 - text.getHeight() / 2); - } - - private void setRectColor(Rectangle rect, float difference) { - if (difference > 0) - rect.setColor(0, 1, 0, 0.5f); - else if (difference < 0) - rect.setColor(1, 0, 0, 0.5f); - else - rect.setColor(0.4f, 0.4f, 0.4f, 0.8f); - } - - private String formatScore(long score) { - StringBuilder scoreBuilder = new StringBuilder(); - scoreBuilder.append(Math.abs(score)); - for (int i = scoreBuilder.length() - 3; i > 0; i -= 3) { - scoreBuilder.insert(i, ' '); - } - if (score < 0) { - scoreBuilder.insert(0, '-'); - } - return scoreBuilder.toString(); - } - - public void show(long mapRank, long newScore, long newRank, float newAcc) { - canBeDismissed = true; - mapText.setText(String.format("#%d", mapRank)); - placeText(mapRect, mapText); - if (newScore > score) - mapRect.setColor(1, 1, 0, 0.8f); - else - setRectColor(mapRect, 0); - - if (newRank == rank) - rankText.setText(String.format("#%d", rank)); - else if (newRank < rank) - rankText.setText(String.format("#%d\n(+%d)", newRank, rank - newRank)); - else - rankText.setText(String.format("#%d\n(%d)", newRank, rank - newRank)); - placeText(rankRect, rankText); - setRectColor(rankRect, rank - newRank); - - if (Math.abs(newAcc - accuracy) < 0.0001f) - accText.setText(String.format("%.2f%%", accuracy * 100f)); - else if (newAcc < accuracy) - accText.setText(String.format("%.2f%%\n(%.2f%%)", newAcc * 100f, (newAcc - accuracy) * 100f)); - else - accText.setText(String.format("%.2f%%\n(+%.2f%%)", newAcc * 100f, (newAcc - accuracy) * 100f)); - placeText(accRect, accText); - setRectColor(accRect, newAcc - accuracy); - - if (newScore == score) - scoreText.setText(String.format("%s", formatScore(score))); - else if (newScore < score) - scoreText.setText(String.format("%s\n(%s)", formatScore(newScore), formatScore(newScore - score))); - else - scoreText.setText(String.format("%s\n(+%s)", formatScore(newScore), formatScore(newScore - score))); - placeText(scoreRect, scoreText); - setRectColor(scoreRect, newScore - score); - - buttonText.setText(" Dismiss"); - - registerEntityModifier(new MoveYModifier(0.5f, Utils.toRes(-300), 0)); - } - - void setFail() { - buttonText.setText(" Failed"); - } - - public ITouchArea getDismissTouchArea() { - return button; - } + private ChangeableText mapText, rankText, accText, scoreText; + private ChangeableText buttonText; + private Rectangle mapRect, rankRect, accRect, scoreRect; + private Sprite button; + + private long rank, score; + private float accuracy; + private boolean canBeDismissed = false; + + public SendingPanel(long rank, long score, float accuracy) { + super(0, Utils.toRes(-300), Utils.toRes(800), Utils.toRes(300)); + TextureRegion btnTex = ResourceManager.getInstance(). + getTexture("ranking_button"); + + this.rank = rank; + this.score = score; + this.accuracy = accuracy; + setColor(0, 0, 0, 0.7f); + + button = new Sprite(Utils.toRes(272), Utils.toRes(300), btnTex) { + + + @Override + public boolean onAreaTouched(TouchEvent pSceneTouchEvent, + float pTouchAreaLocalX, float pTouchAreaLocalY) { + if (canBeDismissed) { + SendingPanel.this.registerEntityModifier(new MoveYModifier(0.5f, 0, + Utils.toRes(-350))); + canBeDismissed = false; + return true; + } + return false; + } + }; + attachChild(button); + + buttonText = new ChangeableText(Utils.toRes(340), Utils.toRes(305), + ResourceManager.getInstance().getFont("font"), + "Sending...", HorizontalAlign.CENTER, 10); + attachChild(buttonText); + + Text topScoreText = new Text(0, 0, + ResourceManager.getInstance().getFont("CaptionFonrt"), "Overall Ranking"); + topScoreText.setPosition(Utils.toRes(400) - topScoreText.getWidth() / 2, Utils.toRes(60)); + attachChild(topScoreText); + + Text tableCaption = new Text(Utils.toRes(60), Utils.toRes(120), + ResourceManager.getInstance().getFont("font"), + "Map rank Overall Accuracy Ranked score"); + attachChild(tableCaption); + + mapRect = new Rectangle(Utils.toRes(50), Utils.toRes(160), + Utils.toRes(140), Utils.toRes(80)); + mapRect.setColor(1, 1, 0, 0.8f); + attachChild(mapRect); + + rankRect = new Rectangle(Utils.toRes(195), Utils.toRes(160), + Utils.toRes(150), Utils.toRes(80)); + attachChild(rankRect); + + accRect = new Rectangle(Utils.toRes(350), Utils.toRes(160), + Utils.toRes(150), Utils.toRes(80)); + attachChild(accRect); + + scoreRect = new Rectangle(Utils.toRes(505), Utils.toRes(160), + Utils.toRes(250), Utils.toRes(80)); + attachChild(scoreRect); + + Font font = ResourceManager.getInstance().getFont("font"); + mapText = new ChangeableText(0, 0, font, "#9999999", HorizontalAlign.CENTER, 8); + placeText(mapRect, mapText); + attachChild(mapText); + + rankText = new ChangeableText(0, 0, font, "#9999999\n(+100)", HorizontalAlign.CENTER, 19); + placeText(rankRect, rankText); + attachChild(rankText); + + accText = new ChangeableText(0, 0, font, "100.00%\n(+21.90%)", HorizontalAlign.CENTER, 16); + placeText(accRect, accText); + attachChild(accText); + + scoreText = new ChangeableText(0, 0, font, "99 123 456 789\n(+99 999 999)", HorizontalAlign.CENTER, 100); + placeText(scoreRect, scoreText); + attachChild(scoreText); + } + + private void placeText(Rectangle rect, ChangeableText text) { + text.setPosition(rect.getX() + rect.getWidth() / 2 - text.getWidth() / 2, + rect.getY() + rect.getHeight() / 2 - text.getHeight() / 2); + } + + private void setRectColor(Rectangle rect, float difference) { + if (difference > 0) + rect.setColor(0, 1, 0, 0.5f); + else if (difference < 0) + rect.setColor(1, 0, 0, 0.5f); + else + rect.setColor(0.4f, 0.4f, 0.4f, 0.8f); + } + + private String formatScore(long score) { + StringBuilder scoreBuilder = new StringBuilder(); + scoreBuilder.append(Math.abs(score)); + for (int i = scoreBuilder.length() - 3; i > 0; i -= 3) { + scoreBuilder.insert(i, ' '); + } + if (score < 0) { + scoreBuilder.insert(0, '-'); + } + return scoreBuilder.toString(); + } + + public void show(long mapRank, long newScore, long newRank, float newAcc) { + canBeDismissed = true; + mapText.setText(String.format("#%d", mapRank)); + placeText(mapRect, mapText); + if (newScore > score) + mapRect.setColor(1, 1, 0, 0.8f); + else + setRectColor(mapRect, 0); + + if (newRank == rank) + rankText.setText(String.format("#%d", rank)); + else if (newRank < rank) + rankText.setText(String.format("#%d\n(+%d)", newRank, rank - newRank)); + else + rankText.setText(String.format("#%d\n(%d)", newRank, rank - newRank)); + placeText(rankRect, rankText); + setRectColor(rankRect, rank - newRank); + + if (Math.abs(newAcc - accuracy) < 0.0001f) + accText.setText(String.format("%.2f%%", accuracy * 100f)); + else if (newAcc < accuracy) + accText.setText(String.format("%.2f%%\n(%.2f%%)", newAcc * 100f, (newAcc - accuracy) * 100f)); + else + accText.setText(String.format("%.2f%%\n(+%.2f%%)", newAcc * 100f, (newAcc - accuracy) * 100f)); + placeText(accRect, accText); + setRectColor(accRect, newAcc - accuracy); + + if (newScore == score) + scoreText.setText(String.format("%s", formatScore(score))); + else if (newScore < score) + scoreText.setText(String.format("%s\n(%s)", formatScore(newScore), formatScore(newScore - score))); + else + scoreText.setText(String.format("%s\n(+%s)", formatScore(newScore), formatScore(newScore - score))); + placeText(scoreRect, scoreText); + setRectColor(scoreRect, newScore - score); + + buttonText.setText(" Dismiss"); + + registerEntityModifier(new MoveYModifier(0.5f, Utils.toRes(-300), 0)); + } + + void setFail() { + buttonText.setText(" Failed"); + } + + public ITouchArea getDismissTouchArea() { + return button; + } } diff --git a/src/ru/nsu/ccfit/zuev/osu/polygon/Polygon.java b/src/ru/nsu/ccfit/zuev/osu/polygon/Polygon.java index 70b2465d..409589bd 100644 --- a/src/ru/nsu/ccfit/zuev/osu/polygon/Polygon.java +++ b/src/ru/nsu/ccfit/zuev/osu/polygon/Polygon.java @@ -11,137 +11,137 @@ public class Polygon extends Shape { - // =========================================================== - // Fields - // =========================================================== + // =========================================================== + // Fields + // =========================================================== - private final float[] mVertices; + private final float[] mVertices; - private final PolygonVertexBuffer mPolygonVertexBuffer; + private final PolygonVertexBuffer mPolygonVertexBuffer; - // =========================================================== - // Constructors - // =========================================================== + // =========================================================== + // Constructors + // =========================================================== - public Polygon(final float pX, final float pY, final float[] pVertices) { - this(pX, pY, pVertices, new PolygonVertexBuffer(pVertices.length, - GL11.GL_STATIC_DRAW, true)); - } + public Polygon(final float pX, final float pY, final float[] pVertices) { + this(pX, pY, pVertices, new PolygonVertexBuffer(pVertices.length, + GL11.GL_STATIC_DRAW, true)); + } - public Polygon(final float pX, final float pY, final float[] pVertices, - final PolygonVertexBuffer pPolygonVertexBuffer) { - super(pX, pY); + public Polygon(final float pX, final float pY, final float[] pVertices, + final PolygonVertexBuffer pPolygonVertexBuffer) { + super(pX, pY); - this.mVertices = pVertices; + this.mVertices = pVertices; - this.mPolygonVertexBuffer = pPolygonVertexBuffer; - this.updateVertexBuffer(); - } + this.mPolygonVertexBuffer = pPolygonVertexBuffer; + this.updateVertexBuffer(); + } - // =========================================================== - // Getter & Setter - // =========================================================== + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - @Override - protected void onInitDraw(final GL10 pGL) { - super.onInitDraw(pGL); - GLHelper.disableTextures(pGL); - GLHelper.disableTexCoordArray(pGL); - } + @Override + protected void onInitDraw(final GL10 pGL) { + super.onInitDraw(pGL); + GLHelper.disableTextures(pGL); + GLHelper.disableTexCoordArray(pGL); + } - @Override - protected VertexBuffer getVertexBuffer() { - return this.mPolygonVertexBuffer; - } + @Override + protected VertexBuffer getVertexBuffer() { + return this.mPolygonVertexBuffer; + } - @Override - protected void onUpdateVertexBuffer() { - this.mPolygonVertexBuffer.update(mVertices); - } + @Override + protected void onUpdateVertexBuffer() { + this.mPolygonVertexBuffer.update(mVertices); + } - public void updateShape() { - onUpdateVertexBuffer(); - } + public void updateShape() { + onUpdateVertexBuffer(); + } - public float[] getVertices() { - return mVertices; - } + public float[] getVertices() { + return mVertices; + } - @Override - protected void drawVertices(final GL10 pGL, final Camera pCamera) { - pGL.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, mVertices.length / 2); - } + @Override + protected void drawVertices(final GL10 pGL, final Camera pCamera) { + pGL.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, mVertices.length / 2); + } - @Override - protected boolean isCulled(final Camera pCamera) { - // TODO Auto-generated method stub - return false; - } + @Override + protected boolean isCulled(final Camera pCamera) { + // TODO Auto-generated method stub + return false; + } - public boolean collidesWith(final IShape pOtherShape) { - // TODO Auto-generated method stub - return false; - } + public boolean collidesWith(final IShape pOtherShape) { + // TODO Auto-generated method stub + return false; + } - public float getBaseHeight() { - // TODO Auto-generated method stub - return 0; - } + public float getBaseHeight() { + // TODO Auto-generated method stub + return 0; + } - public float getBaseWidth() { - // TODO Auto-generated method stub - return 0; - } + public float getBaseWidth() { + // TODO Auto-generated method stub + return 0; + } - public float getHeight() { - // TODO Auto-generated method stub - return 0; - } + public float getHeight() { + // TODO Auto-generated method stub + return 0; + } - @Override - public float[] getSceneCenterCoordinates() { - // TODO Auto-generated method stub - return null; - } + @Override + public float[] getSceneCenterCoordinates() { + // TODO Auto-generated method stub + return null; + } - public float getWidth() { - // TODO Auto-generated method stub - return 0; - } + public float getWidth() { + // TODO Auto-generated method stub + return 0; + } - @Deprecated - public boolean contains(final float pX, final float pY) { - return false; - } + @Deprecated + public boolean contains(final float pX, final float pY) { + return false; + } - @Override - @Deprecated - public float[] convertLocalToSceneCoordinates(final float pX, final float pY) { - return null; - } + @Override + @Deprecated + public float[] convertLocalToSceneCoordinates(final float pX, final float pY) { + return null; + } - @Override - @Deprecated - public float[] convertSceneToLocalCoordinates(final float pX, final float pY) { - return null; - } + @Override + @Deprecated + public float[] convertSceneToLocalCoordinates(final float pX, final float pY) { + return null; + } } diff --git a/src/ru/nsu/ccfit/zuev/osu/polygon/PolygonVertexBuffer.java b/src/ru/nsu/ccfit/zuev/osu/polygon/PolygonVertexBuffer.java index 19ad536e..5d267bd6 100644 --- a/src/ru/nsu/ccfit/zuev/osu/polygon/PolygonVertexBuffer.java +++ b/src/ru/nsu/ccfit/zuev/osu/polygon/PolygonVertexBuffer.java @@ -4,21 +4,21 @@ import org.anddev.andengine.opengl.vertex.VertexBuffer; public class PolygonVertexBuffer extends VertexBuffer { - final static int BYTES_PER_FLOAT = Float.SIZE / 8; + final static int BYTES_PER_FLOAT = Float.SIZE / 8; - public PolygonVertexBuffer(final int pVerticesCount, final int pDrawType, - final boolean managed) { - super(2 * pVerticesCount * BYTES_PER_FLOAT, pDrawType, managed); - } + public PolygonVertexBuffer(final int pVerticesCount, final int pDrawType, + final boolean managed) { + super(2 * pVerticesCount * BYTES_PER_FLOAT, pDrawType, managed); + } - public synchronized void update(final float[] pVertices) { - final FastFloatBuffer buffer = this.getFloatBuffer(); - buffer.position(0); + public synchronized void update(final float[] pVertices) { + final FastFloatBuffer buffer = this.getFloatBuffer(); + buffer.position(0); - buffer.put(pVertices); + buffer.put(pVertices); - buffer.position(0); + buffer.position(0); - // super.update(); - } + // super.update(); + } } diff --git a/src/ru/nsu/ccfit/zuev/osu/polygon/Spline.java b/src/ru/nsu/ccfit/zuev/osu/polygon/Spline.java index 16a51566..9c08c49d 100644 --- a/src/ru/nsu/ccfit/zuev/osu/polygon/Spline.java +++ b/src/ru/nsu/ccfit/zuev/osu/polygon/Spline.java @@ -8,393 +8,393 @@ * Created by Fuuko on 2015/4/7. */ public class Spline { - private static final float TWO_PI = (float) (Math.PI * 2); - private static Spline instance = null; - private static int DetailLevel = 50; - private CurveTypes m_curve_type; - private ArrayList m_ctrl_pts; - private ArrayList m_path; - private ArrayList m_points; - private ArrayList m_ctrl_pts_copy = null; - private ArrayList m_path_copy = null; - private ArrayList m_points_copy = null; - private ArrayList m_lengths = null; - public Spline() { - m_ctrl_pts = new ArrayList(); - m_curve_type = CurveTypes.Linear; - m_path = new ArrayList(); - m_points = new ArrayList(); - } - public Spline(ArrayList theControlPoints, CurveTypes theCurveType) { - m_ctrl_pts = new ArrayList(theControlPoints); - m_curve_type = theCurveType; - m_path = new ArrayList(); - m_points = new ArrayList(); - - sliderthing(m_curve_type, m_ctrl_pts, m_path, m_points); - } - - public static Spline getInstance() { - if (instance == null) { - instance = new Spline(); - } - return instance; - } - - private static float DistToOrigin(PointF point) { - return (float) Math.sqrt(point.x * point.x + point.y * point.y); - } - - private static float Rho(Line line) { - return DistToOrigin(Subtract(line.p2, line.p1)); - } - - /** - * /// Copied from peppy's slider fragment code. (substituting XNA Vector2s for System.Drawing.PointFs) - */ - private static ArrayList CreateBezier(ArrayList input) { - float DetailLevel2 = (float) DetailLevel; - PointF[] working = new PointF[input.size()]; - ArrayList output = new ArrayList(); - - PointF lll; - - for (int iteration = 0; iteration <= DetailLevel; iteration++) { - // Reset the control points for the next sample - for (int i = 0; i < input.size(); i++) - working[i] = new PointF(input.get(i).x, input.get(i).y); - - // I love how you unrolled the recursion from the Bezier formula, peppy ^o^ - for (int level = 0; level < input.size() - 1; level++) - for (int i = 0; i < input.size() - level - 1; i++) { - lll = Lerp(working[i], working[i + 1], (float) iteration / DetailLevel2); - working[i] = lll; // fix premature overwriting of out variable before done with it - } - - output.add(working[0]); - } - - return output; - } - - /// - /// Linear interpolates between 2 points. Support method from Xna.Vector2 not implemented within PointF. - /// - /// Start point - /// End point - /// Weight, starting at Point1 = 0 and going to Point2 = 1. - /// Result - private static PointF Lerp(PointF pt1, PointF pt2, float weight) { - // HURR DERP!! - //result = pt1 + PtToSize(MultiplyPt(pt2 - PtToSize(pt1), weight)); - if ((weight > 1) || (weight < 0)) throw new ArrayIndexOutOfBoundsException("weight"); - //result = new PointF(pt1.x + (pt2.x - pt1.x) * weight, pt1.y + (pt2.y - pt1.y) * weight); - return Lerp(pt1.x, pt2.x, pt1.y, pt2.y, weight); - } - - private static PointF Lerp(float x1, float x2, float y1, float y2, float weight) { - if ((weight > 1) || (weight < 0)) throw new ArrayIndexOutOfBoundsException("weight"); - return new PointF(x1 + (x2 - x1) * weight, y1 + (y2 - y1) * weight); - } - - private static PointF CatmullRom(PointF value1, PointF value2, PointF value3, PointF value4, float amount) { - PointF vector = new PointF(); - float num = amount * amount; - float num2 = amount * num; - vector.x = 0.5f * ((((2f * value2.x) + ((-value1.x + value3.x) * amount)) + (((((2f * value1.x) - (5f * value2.x)) + (4f * value3.x)) - value4.x) * num)) + ((((-value1.x + (3f * value2.x)) - (3f * value3.x)) + value4.x) * num2)); - vector.y = 0.5f * ((((2f * value2.y) + ((-value1.y + value3.y) * amount)) + (((((2f * value1.y) - (5f * value2.y)) + (4f * value3.y)) - value4.y) * num)) + ((((-value1.y + (3f * value2.y)) - (3f * value3.y)) + value4.y) * num2)); - return vector; - } - - private static PointF MultiplyPt(PointF value, float scalar) { - return new PointF(value.x * scalar, value.y * scalar); - } - - private static PointF CircleCenterPoint(PointF point1, PointF point2, PointF point3) { - PointF center = new PointF(); - double a = Math.pow(point1.x, 2) + Math.pow(point1.y, 2); - double b = Math.pow(point2.x, 2) + Math.pow(point2.y, 2); - double c = Math.pow(point3.x, 2) + Math.pow(point3.y, 2); - double g = (point3.y - point2.y) * point1.x + (point1.y - point3.y) * point2.x + (point2.y - point1.y) * point3.x; - center.x = (float) (((b - c) * point1.y + (c - a) * point2.y + (a - b) * point3.y) / (2 * g)); - center.y = (float) (((c - b) * point1.x + (a - c) * point2.x + (b - a) * point3.x) / (2 * g)); - return center; - } - - private static float TwoPointSide(PointF point1, PointF point2) { - return (float) Math.sqrt(Math.pow(point1.x - point2.x, 2) + Math.pow(point1.y - point2.y, 2)); - } - - private static float CircleRadius(PointF point1, PointF point2, PointF point3) { - float a = TwoPointSide(point1, point2); - float b = TwoPointSide(point2, point3); - float c = TwoPointSide(point1, point3); - return (float) ((a * b * c) / Math.sqrt((a + b + c) * (a + b - c) * (a - b + c) * (-a + b + c))); - } - - private static PointF CircularArc(float startAng, float endAng, PointF circleCenter, float radius, float t) { - PointF vector = new PointF(); - float ang = lerp(startAng, endAng, t); - vector.x = (float) (Math.cos(ang) * radius + circleCenter.x); - vector.y = (float) (Math.sin(ang) * radius + circleCenter.y); - return vector; - } - - private static boolean isIn(float a, float b, float c) { - return (b > a && b < c) || (b < a && b > c); - } - - /* - private Point GetLineCoords(ArrayList points, int length) - { - // Find the last segment before length: - ArrayList lengths2; - ArrayList lengths1 = GetLineLengths(points, out lengths2); - int index = lengths2.FindLastIndex(delegate(double d) { return d > length; }); - } - - private ArrayList GetLineLengths(ArrayList points, out ArrayList accumu) - { - ArrayList result = new ArrayList(); - accumu = new ArrayList(); - double accu_value = 0D; - for (int x = 1; x < points.Count; x++) - { - result.Add(DistToOrigin(points[x] - points[x - 1])); - accumu.Add(accu_value += DistToOrigin(points[x] - points[x - 1])); - } - return result; - } - - private static Point GetBezierCoords(ArrayList points, int length) - { - } - */ - - private static float lerp(float a, float b, float t) { - return a * (1 - t) + b * t; - } - - public static PointF Add(PointF pt1, PointF sz2) { - return new PointF(pt1.x + sz2.x, pt1.y + sz2.y); - } - - public static PointF Subtract(PointF pt1, PointF sz2) { - return new PointF(pt1.x - sz2.x, pt1.y - sz2.y); - } - - public static CurveTypes getCurveType(char c) { - switch (c) { - case 'L': - return CurveTypes.Linear; - case 'C': - return CurveTypes.Catmull; - case 'P': - return CurveTypes.PerfectCurve; - case 'B': - return CurveTypes.Bezier; - default: - return CurveTypes.Bezier; - } - } - - public ArrayList getControlPoints() { - if (m_ctrl_pts_copy == null) m_ctrl_pts_copy = new ArrayList(m_ctrl_pts); - return m_ctrl_pts_copy; - } - - public void setControlPoints(ArrayList theControlPoints) { - m_ctrl_pts.clear(); - m_ctrl_pts.addAll(theControlPoints); - } - - public CurveTypes getType() { - return m_curve_type; - } - - public void setType(CurveTypes type) { - m_curve_type = type; - } - - public ArrayList getPath() { - if (m_path_copy == null) m_path_copy = new ArrayList(m_path); - return m_path_copy; - } - - public ArrayList getPoints() { - if (m_points_copy == null) m_points_copy = new ArrayList(m_points); - return m_points_copy; - } - - public ArrayList getLengths() { - if (m_lengths == null) { - m_lengths = new ArrayList(m_path.size() + 1); - float length_so_far = 0; - for (int x = 0; x < m_path.size(); x++) { - m_lengths.add(length_so_far); - length_so_far += Rho(m_path.get(x)); - } - m_lengths.add(length_so_far); - } - return m_lengths; - } - - private void ValidateRange(int which, String paramName, Boolean allow_end) { - if ((which >= m_ctrl_pts.size() + (allow_end ? 0 : -1)) || (which < 0)) - throw new ArrayIndexOutOfBoundsException(paramName); - } - - public void Refresh() { - m_path.clear(); - m_points.clear(); - - sliderthing(m_curve_type, m_ctrl_pts, m_path, m_points); - - m_ctrl_pts_copy = null; - m_path_copy = null; - m_points_copy = null; - m_lengths = null; - } - - public void AdjustPt(int which, PointF where) { - ValidateRange(which, "which", true); - - m_ctrl_pts.add(which, new PointF(where.x, where.y)); // copy - - Refresh(); - } - - public void AddPt(int after) { - ValidateRange(after, "after", false); - - PointF target, pt1, pt2; - pt1 = m_ctrl_pts.get(after); - pt2 = m_ctrl_pts.get(after + 1); - target = Lerp(pt1, pt2, 0.5f); - - target = new PointF((float) Math.round((double) target.x), (float) Math.round((double) target.y)); - - m_ctrl_pts.add(after + 1, target); - Refresh(); - } - - public void DelPt(int where) { - ValidateRange(where, "where", true); - - m_ctrl_pts.remove(where); - Refresh(); - } - - private void sliderthing(CurveTypes CurveType, ArrayList sliderCurvePoints, ArrayList path, ArrayList points) { - switch (CurveType) { - case Catmull: - for (int j = 0; j < sliderCurvePoints.size() - 1; j++) { - PointF v1 = (j - 1 >= 0 ? sliderCurvePoints.get(j - 1) : sliderCurvePoints.get(j)); - PointF v2 = sliderCurvePoints.get(j); - PointF v3 = (j + 1 < sliderCurvePoints.size() - ? sliderCurvePoints.get(j + 1) - : Add(v2, Subtract(v2, v1))); - PointF v4 = (j + 2 < sliderCurvePoints.size() - ? sliderCurvePoints.get(j + 2) - : Add(v3, Subtract(v3, v2))); - - for (int k = 0; k < DetailLevel; k++) { -// path.add( -// new Line(CatmullRom(v1, v2, v3, v4, (float) k / DetailLevel), -// CatmullRom(v1, v2, v3, v4, -// (float) (k + 1) / DetailLevel))); - points.add(CatmullRom(v1, v2, v3, v4, (float) k / DetailLevel)); - } - } - break; - - case Bezier: - int lastIndex = 0; - for (int i = 0; i < sliderCurvePoints.size(); i++) - if ((i > 0 && sliderCurvePoints.get(i) == sliderCurvePoints.get(i - 1)) || i == sliderCurvePoints.size() - 1) { - ArrayList thisLength = new ArrayList(sliderCurvePoints.subList(lastIndex, i - lastIndex + ((i == sliderCurvePoints.size() - 1) ? 1 : 0))); // + 1); // i145 - - ArrayList points1 = CreateBezier(thisLength); - points.addAll(points1); -// for (int j = 1; j < points1.size(); j++) { -// path.add(new Line(points1.get(j - 1), points1.get(j))); -// } - lastIndex = i; - } - break; - - case Linear: - for (int i = 1; i < sliderCurvePoints.size(); i++) { - Line l = new Line(sliderCurvePoints.get(i - 1), sliderCurvePoints.get(i)); - int segments = (int) (Rho(l) / 10); -// if (segments == 0) segments = 1; /********FIX for current osu! bug!********/ - if (segments <= 3) segments = 5; /********FIX for current osu! bug!********/ - // Debug.i("segments=" + segments); - for (int j = 0; j < segments; j++) { -// path.add( -// new Line(Add(l.p1, MultiplyPt(Subtract(l.p2, l.p1), ((float) j / segments))), -// Add(l.p1, MultiplyPt(Subtract(l.p2, l.p1), ((float) (j + 1) / segments))))); - points.add(Add(l.p1, MultiplyPt(Subtract(l.p2, l.p1), ((float) j / segments)))); - } - } - break; - - case PerfectCurve: - if (sliderCurvePoints.size() < 3 || - (sliderCurvePoints.size() == 3 && ((sliderCurvePoints.get(0).x - sliderCurvePoints.get(2).x) * (sliderCurvePoints.get(1).y - sliderCurvePoints.get(2).y) - == (sliderCurvePoints.get(1).x - sliderCurvePoints.get(2).x) * (sliderCurvePoints.get(0).y - sliderCurvePoints.get(2).y)))) { - sliderthing(CurveTypes.Linear, m_ctrl_pts, m_path, m_points); - break; - } - PointF point1 = sliderCurvePoints.get(0); - PointF point2 = sliderCurvePoints.get(1); - PointF point3 = sliderCurvePoints.get(2); - PointF circleCenter = CircleCenterPoint(point1, point2, point3); - float radius = CircleRadius(point1, point2, point3); - float startAng = (float) Math.atan2(point1.y - circleCenter.y, point1.x - circleCenter.x); - float midAng = (float) Math.atan2(point2.y - circleCenter.y, point2.x - circleCenter.x); - float endAng = (float) Math.atan2(point3.y - circleCenter.y, point3.x - circleCenter.x); - if (!isIn(startAng, midAng, endAng)) { - if (Math.abs(startAng + TWO_PI - endAng) < TWO_PI && isIn(startAng + (TWO_PI), midAng, endAng)) - startAng += TWO_PI; - else if (Math.abs(startAng - (endAng + TWO_PI)) < TWO_PI && isIn(startAng, midAng, endAng + (TWO_PI))) - endAng += TWO_PI; - else if (Math.abs(startAng - TWO_PI - endAng) < TWO_PI && isIn(startAng - (TWO_PI), midAng, endAng)) - startAng -= TWO_PI; - else if (Math.abs(startAng - (endAng - TWO_PI)) < TWO_PI && isIn(startAng, midAng, endAng - (TWO_PI))) - endAng -= TWO_PI; - } - if (Math.abs(startAng - midAng) < 0.1 && Math.abs(midAng - endAng) < 0.1) { - sliderthing(CurveTypes.Bezier, m_ctrl_pts, m_path, m_points); - break; - } -// points.add(point1); - for (int k = 0; k < DetailLevel; k++) { -// path.add(new Line(CircularArc(startAng, endAng, circleCenter, radius, (float) k / DetailLevel), -// CircularArc(startAng, endAng, circleCenter, radius, (float) (k + 1) / DetailLevel))); - points.add(CircularArc(startAng, endAng, circleCenter, radius, (float) k / DetailLevel)); - } -// points.add(point3); - break; - } - } - - public enum CurveTypes { - Linear, - Bezier, - Catmull, - PerfectCurve - } - - /// - /// Probably another XNA class? Guessing its structure based on usage - /// - public class Line { - public PointF p1, p2; - - public Line(PointF Start, PointF End) { - p1 = Start; - p2 = End; - } - } + private static final float TWO_PI = (float) (Math.PI * 2); + private static Spline instance = null; + private static int DetailLevel = 50; + private CurveTypes m_curve_type; + private ArrayList m_ctrl_pts; + private ArrayList m_path; + private ArrayList m_points; + private ArrayList m_ctrl_pts_copy = null; + private ArrayList m_path_copy = null; + private ArrayList m_points_copy = null; + private ArrayList m_lengths = null; + public Spline() { + m_ctrl_pts = new ArrayList(); + m_curve_type = CurveTypes.Linear; + m_path = new ArrayList(); + m_points = new ArrayList(); + } + public Spline(ArrayList theControlPoints, CurveTypes theCurveType) { + m_ctrl_pts = new ArrayList(theControlPoints); + m_curve_type = theCurveType; + m_path = new ArrayList(); + m_points = new ArrayList(); + + sliderthing(m_curve_type, m_ctrl_pts, m_path, m_points); + } + + public static Spline getInstance() { + if (instance == null) { + instance = new Spline(); + } + return instance; + } + + private static float DistToOrigin(PointF point) { + return (float) Math.sqrt(point.x * point.x + point.y * point.y); + } + + private static float Rho(Line line) { + return DistToOrigin(Subtract(line.p2, line.p1)); + } + + /** + * /// Copied from peppy's slider fragment code. (substituting XNA Vector2s for System.Drawing.PointFs) + */ + private static ArrayList CreateBezier(ArrayList input) { + float DetailLevel2 = (float) DetailLevel; + PointF[] working = new PointF[input.size()]; + ArrayList output = new ArrayList(); + + PointF lll; + + for (int iteration = 0; iteration <= DetailLevel; iteration++) { + // Reset the control points for the next sample + for (int i = 0; i < input.size(); i++) + working[i] = new PointF(input.get(i).x, input.get(i).y); + + // I love how you unrolled the recursion from the Bezier formula, peppy ^o^ + for (int level = 0; level < input.size() - 1; level++) + for (int i = 0; i < input.size() - level - 1; i++) { + lll = Lerp(working[i], working[i + 1], (float) iteration / DetailLevel2); + working[i] = lll; // fix premature overwriting of out variable before done with it + } + + output.add(working[0]); + } + + return output; + } + + /// + /// Linear interpolates between 2 points. Support method from Xna.Vector2 not implemented within PointF. + /// + /// Start point + /// End point + /// Weight, starting at Point1 = 0 and going to Point2 = 1. + /// Result + private static PointF Lerp(PointF pt1, PointF pt2, float weight) { + // HURR DERP!! + //result = pt1 + PtToSize(MultiplyPt(pt2 - PtToSize(pt1), weight)); + if ((weight > 1) || (weight < 0)) throw new ArrayIndexOutOfBoundsException("weight"); + //result = new PointF(pt1.x + (pt2.x - pt1.x) * weight, pt1.y + (pt2.y - pt1.y) * weight); + return Lerp(pt1.x, pt2.x, pt1.y, pt2.y, weight); + } + + private static PointF Lerp(float x1, float x2, float y1, float y2, float weight) { + if ((weight > 1) || (weight < 0)) throw new ArrayIndexOutOfBoundsException("weight"); + return new PointF(x1 + (x2 - x1) * weight, y1 + (y2 - y1) * weight); + } + + private static PointF CatmullRom(PointF value1, PointF value2, PointF value3, PointF value4, float amount) { + PointF vector = new PointF(); + float num = amount * amount; + float num2 = amount * num; + vector.x = 0.5f * ((((2f * value2.x) + ((-value1.x + value3.x) * amount)) + (((((2f * value1.x) - (5f * value2.x)) + (4f * value3.x)) - value4.x) * num)) + ((((-value1.x + (3f * value2.x)) - (3f * value3.x)) + value4.x) * num2)); + vector.y = 0.5f * ((((2f * value2.y) + ((-value1.y + value3.y) * amount)) + (((((2f * value1.y) - (5f * value2.y)) + (4f * value3.y)) - value4.y) * num)) + ((((-value1.y + (3f * value2.y)) - (3f * value3.y)) + value4.y) * num2)); + return vector; + } + + private static PointF MultiplyPt(PointF value, float scalar) { + return new PointF(value.x * scalar, value.y * scalar); + } + + private static PointF CircleCenterPoint(PointF point1, PointF point2, PointF point3) { + PointF center = new PointF(); + double a = Math.pow(point1.x, 2) + Math.pow(point1.y, 2); + double b = Math.pow(point2.x, 2) + Math.pow(point2.y, 2); + double c = Math.pow(point3.x, 2) + Math.pow(point3.y, 2); + double g = (point3.y - point2.y) * point1.x + (point1.y - point3.y) * point2.x + (point2.y - point1.y) * point3.x; + center.x = (float) (((b - c) * point1.y + (c - a) * point2.y + (a - b) * point3.y) / (2 * g)); + center.y = (float) (((c - b) * point1.x + (a - c) * point2.x + (b - a) * point3.x) / (2 * g)); + return center; + } + + private static float TwoPointSide(PointF point1, PointF point2) { + return (float) Math.sqrt(Math.pow(point1.x - point2.x, 2) + Math.pow(point1.y - point2.y, 2)); + } + + private static float CircleRadius(PointF point1, PointF point2, PointF point3) { + float a = TwoPointSide(point1, point2); + float b = TwoPointSide(point2, point3); + float c = TwoPointSide(point1, point3); + return (float) ((a * b * c) / Math.sqrt((a + b + c) * (a + b - c) * (a - b + c) * (-a + b + c))); + } + + private static PointF CircularArc(float startAng, float endAng, PointF circleCenter, float radius, float t) { + PointF vector = new PointF(); + float ang = lerp(startAng, endAng, t); + vector.x = (float) (Math.cos(ang) * radius + circleCenter.x); + vector.y = (float) (Math.sin(ang) * radius + circleCenter.y); + return vector; + } + + private static boolean isIn(float a, float b, float c) { + return (b > a && b < c) || (b < a && b > c); + } + + /* + private Point GetLineCoords(ArrayList points, int length) + { + // Find the last segment before length: + ArrayList lengths2; + ArrayList lengths1 = GetLineLengths(points, out lengths2); + int index = lengths2.FindLastIndex(delegate(double d) { return d > length; }); + } + + private ArrayList GetLineLengths(ArrayList points, out ArrayList accumu) + { + ArrayList result = new ArrayList(); + accumu = new ArrayList(); + double accu_value = 0D; + for (int x = 1; x < points.Count; x++) + { + result.Add(DistToOrigin(points[x] - points[x - 1])); + accumu.Add(accu_value += DistToOrigin(points[x] - points[x - 1])); + } + return result; + } + + private static Point GetBezierCoords(ArrayList points, int length) + { + } + */ + + private static float lerp(float a, float b, float t) { + return a * (1 - t) + b * t; + } + + public static PointF Add(PointF pt1, PointF sz2) { + return new PointF(pt1.x + sz2.x, pt1.y + sz2.y); + } + + public static PointF Subtract(PointF pt1, PointF sz2) { + return new PointF(pt1.x - sz2.x, pt1.y - sz2.y); + } + + public static CurveTypes getCurveType(char c) { + switch (c) { + case 'L': + return CurveTypes.Linear; + case 'C': + return CurveTypes.Catmull; + case 'P': + return CurveTypes.PerfectCurve; + case 'B': + return CurveTypes.Bezier; + default: + return CurveTypes.Bezier; + } + } + + public ArrayList getControlPoints() { + if (m_ctrl_pts_copy == null) m_ctrl_pts_copy = new ArrayList(m_ctrl_pts); + return m_ctrl_pts_copy; + } + + public void setControlPoints(ArrayList theControlPoints) { + m_ctrl_pts.clear(); + m_ctrl_pts.addAll(theControlPoints); + } + + public CurveTypes getType() { + return m_curve_type; + } + + public void setType(CurveTypes type) { + m_curve_type = type; + } + + public ArrayList getPath() { + if (m_path_copy == null) m_path_copy = new ArrayList(m_path); + return m_path_copy; + } + + public ArrayList getPoints() { + if (m_points_copy == null) m_points_copy = new ArrayList(m_points); + return m_points_copy; + } + + public ArrayList getLengths() { + if (m_lengths == null) { + m_lengths = new ArrayList(m_path.size() + 1); + float length_so_far = 0; + for (int x = 0; x < m_path.size(); x++) { + m_lengths.add(length_so_far); + length_so_far += Rho(m_path.get(x)); + } + m_lengths.add(length_so_far); + } + return m_lengths; + } + + private void ValidateRange(int which, String paramName, Boolean allow_end) { + if ((which >= m_ctrl_pts.size() + (allow_end ? 0 : -1)) || (which < 0)) + throw new ArrayIndexOutOfBoundsException(paramName); + } + + public void Refresh() { + m_path.clear(); + m_points.clear(); + + sliderthing(m_curve_type, m_ctrl_pts, m_path, m_points); + + m_ctrl_pts_copy = null; + m_path_copy = null; + m_points_copy = null; + m_lengths = null; + } + + public void AdjustPt(int which, PointF where) { + ValidateRange(which, "which", true); + + m_ctrl_pts.add(which, new PointF(where.x, where.y)); // copy + + Refresh(); + } + + public void AddPt(int after) { + ValidateRange(after, "after", false); + + PointF target, pt1, pt2; + pt1 = m_ctrl_pts.get(after); + pt2 = m_ctrl_pts.get(after + 1); + target = Lerp(pt1, pt2, 0.5f); + + target = new PointF((float) Math.round((double) target.x), (float) Math.round((double) target.y)); + + m_ctrl_pts.add(after + 1, target); + Refresh(); + } + + public void DelPt(int where) { + ValidateRange(where, "where", true); + + m_ctrl_pts.remove(where); + Refresh(); + } + + private void sliderthing(CurveTypes CurveType, ArrayList sliderCurvePoints, ArrayList path, ArrayList points) { + switch (CurveType) { + case Catmull: + for (int j = 0; j < sliderCurvePoints.size() - 1; j++) { + PointF v1 = (j - 1 >= 0 ? sliderCurvePoints.get(j - 1) : sliderCurvePoints.get(j)); + PointF v2 = sliderCurvePoints.get(j); + PointF v3 = (j + 1 < sliderCurvePoints.size() + ? sliderCurvePoints.get(j + 1) + : Add(v2, Subtract(v2, v1))); + PointF v4 = (j + 2 < sliderCurvePoints.size() + ? sliderCurvePoints.get(j + 2) + : Add(v3, Subtract(v3, v2))); + + for (int k = 0; k < DetailLevel; k++) { +// path.add( +// new Line(CatmullRom(v1, v2, v3, v4, (float) k / DetailLevel), +// CatmullRom(v1, v2, v3, v4, +// (float) (k + 1) / DetailLevel))); + points.add(CatmullRom(v1, v2, v3, v4, (float) k / DetailLevel)); + } + } + break; + + case Bezier: + int lastIndex = 0; + for (int i = 0; i < sliderCurvePoints.size(); i++) + if ((i > 0 && sliderCurvePoints.get(i) == sliderCurvePoints.get(i - 1)) || i == sliderCurvePoints.size() - 1) { + ArrayList thisLength = new ArrayList(sliderCurvePoints.subList(lastIndex, i - lastIndex + ((i == sliderCurvePoints.size() - 1) ? 1 : 0))); // + 1); // i145 + + ArrayList points1 = CreateBezier(thisLength); + points.addAll(points1); +// for (int j = 1; j < points1.size(); j++) { +// path.add(new Line(points1.get(j - 1), points1.get(j))); +// } + lastIndex = i; + } + break; + + case Linear: + for (int i = 1; i < sliderCurvePoints.size(); i++) { + Line l = new Line(sliderCurvePoints.get(i - 1), sliderCurvePoints.get(i)); + int segments = (int) (Rho(l) / 10); +// if (segments == 0) segments = 1; /********FIX for current osu! bug!********/ + if (segments <= 3) segments = 5; /********FIX for current osu! bug!********/ + // Debug.i("segments=" + segments); + for (int j = 0; j < segments; j++) { +// path.add( +// new Line(Add(l.p1, MultiplyPt(Subtract(l.p2, l.p1), ((float) j / segments))), +// Add(l.p1, MultiplyPt(Subtract(l.p2, l.p1), ((float) (j + 1) / segments))))); + points.add(Add(l.p1, MultiplyPt(Subtract(l.p2, l.p1), ((float) j / segments)))); + } + } + break; + + case PerfectCurve: + if (sliderCurvePoints.size() < 3 || + (sliderCurvePoints.size() == 3 && ((sliderCurvePoints.get(0).x - sliderCurvePoints.get(2).x) * (sliderCurvePoints.get(1).y - sliderCurvePoints.get(2).y) + == (sliderCurvePoints.get(1).x - sliderCurvePoints.get(2).x) * (sliderCurvePoints.get(0).y - sliderCurvePoints.get(2).y)))) { + sliderthing(CurveTypes.Linear, m_ctrl_pts, m_path, m_points); + break; + } + PointF point1 = sliderCurvePoints.get(0); + PointF point2 = sliderCurvePoints.get(1); + PointF point3 = sliderCurvePoints.get(2); + PointF circleCenter = CircleCenterPoint(point1, point2, point3); + float radius = CircleRadius(point1, point2, point3); + float startAng = (float) Math.atan2(point1.y - circleCenter.y, point1.x - circleCenter.x); + float midAng = (float) Math.atan2(point2.y - circleCenter.y, point2.x - circleCenter.x); + float endAng = (float) Math.atan2(point3.y - circleCenter.y, point3.x - circleCenter.x); + if (!isIn(startAng, midAng, endAng)) { + if (Math.abs(startAng + TWO_PI - endAng) < TWO_PI && isIn(startAng + (TWO_PI), midAng, endAng)) + startAng += TWO_PI; + else if (Math.abs(startAng - (endAng + TWO_PI)) < TWO_PI && isIn(startAng, midAng, endAng + (TWO_PI))) + endAng += TWO_PI; + else if (Math.abs(startAng - TWO_PI - endAng) < TWO_PI && isIn(startAng - (TWO_PI), midAng, endAng)) + startAng -= TWO_PI; + else if (Math.abs(startAng - (endAng - TWO_PI)) < TWO_PI && isIn(startAng, midAng, endAng - (TWO_PI))) + endAng -= TWO_PI; + } + if (Math.abs(startAng - midAng) < 0.1 && Math.abs(midAng - endAng) < 0.1) { + sliderthing(CurveTypes.Bezier, m_ctrl_pts, m_path, m_points); + break; + } +// points.add(point1); + for (int k = 0; k < DetailLevel; k++) { +// path.add(new Line(CircularArc(startAng, endAng, circleCenter, radius, (float) k / DetailLevel), +// CircularArc(startAng, endAng, circleCenter, radius, (float) (k + 1) / DetailLevel))); + points.add(CircularArc(startAng, endAng, circleCenter, radius, (float) k / DetailLevel)); + } +// points.add(point3); + break; + } + } + + public enum CurveTypes { + Linear, + Bezier, + Catmull, + PerfectCurve + } + + /// + /// Probably another XNA class? Guessing its structure based on usage + /// + public class Line { + public PointF p1, p2; + + public Line(PointF Start, PointF End) { + p1 = Start; + p2 = End; + } + } } diff --git a/src/ru/nsu/ccfit/zuev/osu/scoring/Replay.java b/src/ru/nsu/ccfit/zuev/osu/scoring/Replay.java index a9120736..9135153e 100644 --- a/src/ru/nsu/ccfit/zuev/osu/scoring/Replay.java +++ b/src/ru/nsu/ccfit/zuev/osu/scoring/Replay.java @@ -31,508 +31,508 @@ public class Replay { - public static final byte RESULT_300 = 4; - public static final byte RESULT_100 = 3; - public static final byte RESULT_50 = 2; - public static final byte RESULT_0 = 1; - public static final byte ID_DOWN = 0; - public static final byte ID_UP = 2; - - public static final byte ID_MOVE = 1; - public static EnumSet mod = EnumSet.noneOf(GameMod.class); - public static EnumSet oldMod = EnumSet.noneOf(GameMod.class); - private static int pointsSkipped = 0; - public ArrayList cursorMoves = new ArrayList(); - public int[] cursorIndex; - public int[] lastMoveIndex; - public ReplayObjectData[] objectData = null; - public int replayVersion; - public StatisticV2 stat = null; - private String md5 = ""; - private String mapfile = ""; - private String mapname = ""; - public static float oldChangeSpeed = 1.0f; - public static float oldForceAR = 9.0f; - public static boolean oldEnableForceAR = false; - public static float oldFLFollowDelay = FlashLightEntity.defaultMoveDelayS; - - public Replay() { - cursorMoves.add(new MoveArray(200)); - cursorMoves.add(new MoveArray(50)); - for (int i = 2; i < GameScene.CursorCount; i++) { - cursorMoves.add(new MoveArray(15)); - } - cursorIndex = new int[GameScene.CursorCount]; - lastMoveIndex = new int[GameScene.CursorCount]; - for (int i = 0; i < GameScene.CursorCount; i++) { - cursorIndex[i] = 0; - lastMoveIndex[i] = -1; - } - - pointsSkipped = 0; - } - - public void setMap(String mapname, String file, String md5) { - this.mapname = mapname; - this.md5 = md5; - this.mapfile = file; - } - - public void setObjectCount(int count) { - objectData = new ReplayObjectData[count]; - } - - public void addObjectResult(int id, short accuracy, BitSet ticks) { - if (id < 0 || objectData == null || id >= objectData.length) - return; - - ReplayObjectData data = objectData[id] == null ? new ReplayObjectData() : objectData[id]; - data.accuracy = accuracy; - data.tickSet = ticks; - objectData[id] = data; - } - - public void addObjectScore(int id, byte score) { - if (id < 0 || objectData == null || id >= objectData.length) - return; - - if (objectData[id] == null) - objectData[id] = new ReplayObjectData(); - objectData[id].result = score; - } - - public void addPress(final float time, final PointF pos, final int pid) { - if (pid > GameScene.CursorCount) return; - - int itime = Math.max(0, (int) (time * 1000)); - cursorMoves.get(pid).pushBack(itime, pos.x, pos.y, ID_DOWN); - } - - public void addMove(final float time, final PointF pos, final int pid) { - if (pid > GameScene.CursorCount) return; - - int itime = Math.max(0, (int) (time * 1000)); - cursorMoves.get(pid).pushBack(itime, pos.x, pos.y, ID_MOVE); - } - - public void addUp(final float time, final int pid) { - if (pid > GameScene.CursorCount) return; - - int itime = Math.max(0, (int) (time * 1000)); - cursorMoves.get(pid).pushBack(itime, ID_UP); - } - - public void save(final String filename) { - for (int i = 0; i < cursorMoves.size(); i++) - Debug.i("Replay contains " + cursorMoves.get(i).size + " moves for finger " + i); - Debug.i("Skipped " + pointsSkipped + " points"); - Debug.i("Replay contains " + objectData.length + " objects"); - ObjectOutputStream os; - ZipOutputStream zip; - try { - zip = new ZipOutputStream(new FileOutputStream(new File(filename))); - zip.setMethod(ZipOutputStream.DEFLATED); - zip.setLevel(Deflater.DEFAULT_COMPRESSION); - zip.putNextEntry(new ZipEntry("data")); - os = new ObjectOutputStream(zip); - } catch (final FileNotFoundException e) { - Debug.e("File not found " + filename, e); - return; - } catch (final IOException e) { - Debug.e("IOException: " + e.getMessage(), e); - return; - } - - try { - os.writeObject(new ReplayVersion()); - os.writeObject(mapname); - os.writeObject(mapfile); - os.writeObject(md5); - - if (stat != null) { - os.writeLong(stat.getTime()); - os.writeInt(stat.getHit300k()); - os.writeInt(stat.getHit300()); - os.writeInt(stat.getHit100k()); - os.writeInt(stat.getHit100()); - os.writeInt(stat.getHit50()); - os.writeInt(stat.getMisses()); - os.writeInt(stat.getModifiedTotalScore()); - os.writeInt(stat.getMaxCombo()); - os.writeFloat(stat.getAccuracy()); - os.writeBoolean(stat.isPerfect()); - os.writeObject(stat.getPlayerName()); - os.writeObject(stat.getMod()); - //Add in replay version - os.writeObject(stat.getExtraModString()); - } - - os.writeInt(cursorMoves.size()); - //Storing all moves - for (final MoveArray move : cursorMoves) { - move.writeTo(os); - } - os.writeInt(objectData.length); - for (ReplayObjectData data : objectData) { - if (data == null) data = new ReplayObjectData(); - os.writeShort(data.accuracy); - if (data.tickSet == null || data.tickSet.length() == 0) { - os.writeByte(0); - } else { - byte[] bytes = new byte[(data.tickSet.length() + 7) / 8]; - for (int i = 0; i < data.tickSet.length(); i++) { - if (data.tickSet.get(i)) { - bytes[bytes.length - i / 8 - 1] |= 1 << (i % 8); - } - } - os.writeByte(bytes.length); - os.write(bytes); - } - os.writeByte(data.result); - } - } catch (final IOException e) { - Debug.e("IOException: " + e.getMessage(), e); - return; - } - - try { - os.flush(); - zip.flush(); - zip.closeEntry(); - zip.flush(); - } catch (final IOException e) { - Debug.e("IOException: " + e.getMessage(), e); - } - - } - - public boolean loadInfo(final String filename) { - ObjectInputStream os; - try { - final ZipInputStream zip = new ZipInputStream(new FileInputStream( - new File(filename))); - zip.getNextEntry(); - os = new ObjectInputStream(zip); - // zip.close(); - } catch (final Exception e) { - Debug.e("Cannot load replay: " + e.getMessage(), e); - return false; - } - - Debug.i("Loading replay " + filename); - - cursorMoves.clear(); - int version = 0; - try { - Object firstObject = os.readObject(); - Debug.i("Readed object: " + firstObject.getClass().getName()); - if (firstObject.getClass().equals(ReplayVersion.class)) { - Debug.i("Other replay version"); - version = ((ReplayVersion) firstObject).version; - replayVersion = version; - mapname = (String) os.readObject(); - - } else { - mapname = (String) firstObject; - } - mapfile = (String) os.readObject(); - md5 = (String) os.readObject(); - - Debug.i(mapname); - Debug.i(mapfile); - Debug.i(md5); - - if (version >= 3) { - stat = new StatisticV2(); - stat.setTime(os.readLong()); - stat.setHit300k(os.readInt()); - stat.setHit300(os.readInt()); - stat.setHit100k(os.readInt()); - stat.setHit100(os.readInt()); - stat.setHit50(os.readInt()); - stat.setMisses(os.readInt()); - stat.setForcedScore(os.readInt()); - stat.setMaxCombo(os.readInt()); - stat.setAccuracy(os.readFloat()); - stat.setPerfect(os.readBoolean()); - stat.setPlayerName((String) os.readObject()); - stat.setMod((EnumSet) os.readObject()); - } - - if (version >= 4) { - stat.setExtraModFromString((String) os.readObject()); - } - - } catch (EOFException e) { - Debug.e("O_o eof..."); - Debug.e("Replay.loadInfo: " + e.getMessage(), e); - ToastLogger.showTextId(R.string.replay_corrupted, true); - return false; - - } catch (Exception e) { - ToastLogger.showTextId(R.string.replay_corrupted, true); - Debug.e("Cannot load replay: " + e.getMessage(), e); - return false; - } - - return true; - } - - public boolean load(final String filename) { - ObjectInputStream os; - try { - final ZipInputStream zip = new ZipInputStream(new FileInputStream( - new File(filename))); - zip.getNextEntry(); - os = new ObjectInputStream(zip); - // zip.close(); - } catch (final Exception e) { - Debug.e("Cannot load replay: " + e.getMessage(), e); - return false; - } - - Debug.i("Loading replay " + filename); - - cursorMoves.clear(); - int version = 0; - try { - String mname; - Object firstObject = os.readObject(); - Debug.i("Readed object: " + firstObject.getClass().getName()); - if (firstObject.getClass().equals(ReplayVersion.class)) { - Debug.i("Other replay version"); - version = ((ReplayVersion) firstObject).version; - replayVersion = version; - mname = (String) os.readObject(); - - } else { - mname = (String) firstObject; - } - String mfile = (String) os.readObject(); - String mmd5 = (String) os.readObject(); - - if (mname.equals(mapname) == false && mfile.equals(mapfile) == false) { - Debug.i("Replay doesn't match the map!"); - Debug.i(mapname + " ::: " + mname); - Debug.i(mapfile + " ::: " + mfile); - Debug.i(md5 + " ::: " + mmd5); - ToastLogger.showTextId(R.string.replay_wrongmap, true); - - os.close(); - return false; - } - - if (version >= 3) { - stat = new StatisticV2(); - stat.setTime(os.readLong()); - stat.setHit300k(os.readInt()); - stat.setHit300(os.readInt()); - stat.setHit100k(os.readInt()); - stat.setHit100(os.readInt()); - stat.setHit50(os.readInt()); - stat.setMisses(os.readInt()); - stat.setForcedScore(os.readInt()); - stat.setMaxCombo(os.readInt()); - stat.setAccuracy(os.readFloat()); - stat.setPerfect(os.readBoolean()); - stat.setPlayerName((String) os.readObject()); - stat.setMod((EnumSet) os.readObject()); - } - - if (version >= 4) { - stat.setExtraModFromString((String) os.readObject()); - } - - int msize = os.readInt(); - for (int i = 0; i < msize; i++) { - cursorMoves.add(MoveArray.readFrom(os, this)); - } - - os.readInt(); - for (int i = 0; i < objectData.length; i++) { - ReplayObjectData data = new ReplayObjectData(); - data.accuracy = os.readShort(); - int len = os.readByte(); - if (len > 0) { - data.tickSet = new BitSet(); - byte[] bytes = new byte[len]; - os.read(bytes); - for (int j = 0; j < len * 8; j++) { - data.tickSet.set(j, (bytes[len - j / 8 - 1] & 1 << (j % 8)) != 0); - } - } - if (version >= 1) { - data.result = os.readByte(); - } - objectData[i] = data; - } - } catch (EOFException e) { - Debug.e("Replay.load: " + e.getMessage(), e); - ToastLogger.showTextId(R.string.replay_corrupted, true); - return false; - } - catch (Exception e) { - ToastLogger.showTextId(R.string.replay_corrupted, true); - Debug.e("Cannot load replay: " + e.getMessage(), e); - return false; - } - - for (int i = 0; i < cursorMoves.size(); i++) - Debug.i("Loaded " + cursorMoves.get(i).size + " moves for finger " + i); - Debug.i("Loaded " + objectData.length + " objects"); - return true; - } - - public void countMarks(float difficulty) { - } - - public StatisticV2 getStat() { - return stat; - } - - public void setStat(StatisticV2 stat) { - this.stat = stat; - } - - public String getMd5() { - return md5; - } - - public String getMapfile() { - return mapfile; - } - - public String getMapname() { - return mapname; - } - - public static class ReplayVersion implements Serializable { - private static final long serialVersionUID = 4643121693566795335L; - int version = 5; - // version 4: Add ExtraModString's save and load in save()/load()/loadInfo() - // version 5: changed gamePoints to be a float type - } - - public static class ReplayObjectData { - public short accuracy = 0; - public BitSet tickSet = null; - public byte result = 0; - } - - public static class MoveArray { - public int[] time; - public float[] x; - public float[] y; - public byte[] id; - - public int size; - public int allocated; - - public MoveArray(int startSize) { - allocated = startSize; - size = 0; - time = new int[allocated]; - x = new float[allocated]; - y = new float[allocated]; - id = new byte[allocated]; - } - - public static MoveArray readFrom(ObjectInputStream is, Replay replay) throws IOException { - int size = is.readInt(); - MoveArray array = new MoveArray(size); - - for (int i = 0; i < size; i++) { - array.time[i] = is.readInt(); - array.id[i] = (byte) (array.time[i] & 3); - array.time[i] >>= 2; - if (array.id[i] != ID_UP) { - PointF gamePoint; - - if(replay.replayVersion >= 5) { - gamePoint = new PointF((float) (Math.round(is.readFloat()) / Config.getTextureQuality()), - (float) (Math.round(is.readFloat()) / Config.getTextureQuality())); - }else { - gamePoint = new PointF((float) (is.readShort() / Config.getTextureQuality()), - (float) (is.readShort() / Config.getTextureQuality())); - } - - if (replay.replayVersion == 1) { - PointF realPoint = Utils.trackToRealCoords(Utils.realToTrackCoords(gamePoint, 1024, 600, true)); - array.x[i] = realPoint.x; - array.y[i] = realPoint.y; - } else if (replay.replayVersion > 1) { - PointF realPoint = Utils.trackToRealCoords(gamePoint); - array.x[i] = realPoint.x; - array.y[i] = realPoint.y; - } - } - array.size = size; - } - - return array; - } - - public void reallocate(int newSize) { - if (newSize <= allocated) return; - int[] newTime = new int[newSize]; - float[] newX = new float[newSize]; - float[] newY = new float[newSize]; - byte[] newId = new byte[newSize]; - - System.arraycopy(time, 0, newTime, 0, size); - System.arraycopy(x, 0, newX, 0, size); - System.arraycopy(y, 0, newY, 0, size); - System.arraycopy(id, 0, newId, 0, size); - - time = newTime; - x = newX; - y = newY; - id = newId; - - allocated = newSize; - } - - public boolean checkNewPoint(float px, float py) { - if (size < 2) return false; - float tx = (px + x[size - 2]) * 0.5f; - float ty = (py + y[size - 2]) * 0.5f; - - return (Utils.sqr(x[size - 1] - tx) + Utils.sqr(y[size - 1] - ty)) <= 25; - } - - public void pushBack(int time, float x, float y, byte id) { - int idx = size; - if (id == ID_MOVE && checkNewPoint(x, y)) { - idx = size - 1; - pointsSkipped++; - } else { - if (size + 1 >= allocated) - reallocate((allocated * 3) / 2); - size++; - } - this.time[idx] = time; - this.x[idx] = x; - this.y[idx] = y; - this.id[idx] = id; - } - - public void pushBack(int time, byte id) { - if (size >= allocated) - reallocate((allocated * 3) / 2); - this.time[size] = time; - this.id[size] = id; - size++; - } - - public void writeTo(ObjectOutputStream os) throws IOException { - os.writeInt(size); - for (int i = 0; i < size; i++) { - os.writeInt((time[i] << 2) + id[i]); - if (id[i] != ID_UP) { - os.writeFloat(x[i] * Config.getTextureQuality()); - os.writeFloat(y[i] * Config.getTextureQuality()); - } - } - } - } + public static final byte RESULT_300 = 4; + public static final byte RESULT_100 = 3; + public static final byte RESULT_50 = 2; + public static final byte RESULT_0 = 1; + public static final byte ID_DOWN = 0; + public static final byte ID_UP = 2; + + public static final byte ID_MOVE = 1; + public static EnumSet mod = EnumSet.noneOf(GameMod.class); + public static EnumSet oldMod = EnumSet.noneOf(GameMod.class); + private static int pointsSkipped = 0; + public ArrayList cursorMoves = new ArrayList(); + public int[] cursorIndex; + public int[] lastMoveIndex; + public ReplayObjectData[] objectData = null; + public int replayVersion; + public StatisticV2 stat = null; + private String md5 = ""; + private String mapfile = ""; + private String mapname = ""; + public static float oldChangeSpeed = 1.0f; + public static float oldForceAR = 9.0f; + public static boolean oldEnableForceAR = false; + public static float oldFLFollowDelay = FlashLightEntity.defaultMoveDelayS; + + public Replay() { + cursorMoves.add(new MoveArray(200)); + cursorMoves.add(new MoveArray(50)); + for (int i = 2; i < GameScene.CursorCount; i++) { + cursorMoves.add(new MoveArray(15)); + } + cursorIndex = new int[GameScene.CursorCount]; + lastMoveIndex = new int[GameScene.CursorCount]; + for (int i = 0; i < GameScene.CursorCount; i++) { + cursorIndex[i] = 0; + lastMoveIndex[i] = -1; + } + + pointsSkipped = 0; + } + + public void setMap(String mapname, String file, String md5) { + this.mapname = mapname; + this.md5 = md5; + this.mapfile = file; + } + + public void setObjectCount(int count) { + objectData = new ReplayObjectData[count]; + } + + public void addObjectResult(int id, short accuracy, BitSet ticks) { + if (id < 0 || objectData == null || id >= objectData.length) + return; + + ReplayObjectData data = objectData[id] == null ? new ReplayObjectData() : objectData[id]; + data.accuracy = accuracy; + data.tickSet = ticks; + objectData[id] = data; + } + + public void addObjectScore(int id, byte score) { + if (id < 0 || objectData == null || id >= objectData.length) + return; + + if (objectData[id] == null) + objectData[id] = new ReplayObjectData(); + objectData[id].result = score; + } + + public void addPress(final float time, final PointF pos, final int pid) { + if (pid > GameScene.CursorCount) return; + + int itime = Math.max(0, (int) (time * 1000)); + cursorMoves.get(pid).pushBack(itime, pos.x, pos.y, ID_DOWN); + } + + public void addMove(final float time, final PointF pos, final int pid) { + if (pid > GameScene.CursorCount) return; + + int itime = Math.max(0, (int) (time * 1000)); + cursorMoves.get(pid).pushBack(itime, pos.x, pos.y, ID_MOVE); + } + + public void addUp(final float time, final int pid) { + if (pid > GameScene.CursorCount) return; + + int itime = Math.max(0, (int) (time * 1000)); + cursorMoves.get(pid).pushBack(itime, ID_UP); + } + + public void save(final String filename) { + for (int i = 0; i < cursorMoves.size(); i++) + Debug.i("Replay contains " + cursorMoves.get(i).size + " moves for finger " + i); + Debug.i("Skipped " + pointsSkipped + " points"); + Debug.i("Replay contains " + objectData.length + " objects"); + ObjectOutputStream os; + ZipOutputStream zip; + try { + zip = new ZipOutputStream(new FileOutputStream(new File(filename))); + zip.setMethod(ZipOutputStream.DEFLATED); + zip.setLevel(Deflater.DEFAULT_COMPRESSION); + zip.putNextEntry(new ZipEntry("data")); + os = new ObjectOutputStream(zip); + } catch (final FileNotFoundException e) { + Debug.e("File not found " + filename, e); + return; + } catch (final IOException e) { + Debug.e("IOException: " + e.getMessage(), e); + return; + } + + try { + os.writeObject(new ReplayVersion()); + os.writeObject(mapname); + os.writeObject(mapfile); + os.writeObject(md5); + + if (stat != null) { + os.writeLong(stat.getTime()); + os.writeInt(stat.getHit300k()); + os.writeInt(stat.getHit300()); + os.writeInt(stat.getHit100k()); + os.writeInt(stat.getHit100()); + os.writeInt(stat.getHit50()); + os.writeInt(stat.getMisses()); + os.writeInt(stat.getModifiedTotalScore()); + os.writeInt(stat.getMaxCombo()); + os.writeFloat(stat.getAccuracy()); + os.writeBoolean(stat.isPerfect()); + os.writeObject(stat.getPlayerName()); + os.writeObject(stat.getMod()); + //Add in replay version + os.writeObject(stat.getExtraModString()); + } + + os.writeInt(cursorMoves.size()); + //Storing all moves + for (final MoveArray move : cursorMoves) { + move.writeTo(os); + } + os.writeInt(objectData.length); + for (ReplayObjectData data : objectData) { + if (data == null) data = new ReplayObjectData(); + os.writeShort(data.accuracy); + if (data.tickSet == null || data.tickSet.length() == 0) { + os.writeByte(0); + } else { + byte[] bytes = new byte[(data.tickSet.length() + 7) / 8]; + for (int i = 0; i < data.tickSet.length(); i++) { + if (data.tickSet.get(i)) { + bytes[bytes.length - i / 8 - 1] |= 1 << (i % 8); + } + } + os.writeByte(bytes.length); + os.write(bytes); + } + os.writeByte(data.result); + } + } catch (final IOException e) { + Debug.e("IOException: " + e.getMessage(), e); + return; + } + + try { + os.flush(); + zip.flush(); + zip.closeEntry(); + zip.flush(); + } catch (final IOException e) { + Debug.e("IOException: " + e.getMessage(), e); + } + + } + + public boolean loadInfo(final String filename) { + ObjectInputStream os; + try { + final ZipInputStream zip = new ZipInputStream(new FileInputStream( + new File(filename))); + zip.getNextEntry(); + os = new ObjectInputStream(zip); + // zip.close(); + } catch (final Exception e) { + Debug.e("Cannot load replay: " + e.getMessage(), e); + return false; + } + + Debug.i("Loading replay " + filename); + + cursorMoves.clear(); + int version = 0; + try { + Object firstObject = os.readObject(); + Debug.i("Readed object: " + firstObject.getClass().getName()); + if (firstObject.getClass().equals(ReplayVersion.class)) { + Debug.i("Other replay version"); + version = ((ReplayVersion) firstObject).version; + replayVersion = version; + mapname = (String) os.readObject(); + + } else { + mapname = (String) firstObject; + } + mapfile = (String) os.readObject(); + md5 = (String) os.readObject(); + + Debug.i(mapname); + Debug.i(mapfile); + Debug.i(md5); + + if (version >= 3) { + stat = new StatisticV2(); + stat.setTime(os.readLong()); + stat.setHit300k(os.readInt()); + stat.setHit300(os.readInt()); + stat.setHit100k(os.readInt()); + stat.setHit100(os.readInt()); + stat.setHit50(os.readInt()); + stat.setMisses(os.readInt()); + stat.setForcedScore(os.readInt()); + stat.setMaxCombo(os.readInt()); + stat.setAccuracy(os.readFloat()); + stat.setPerfect(os.readBoolean()); + stat.setPlayerName((String) os.readObject()); + stat.setMod((EnumSet) os.readObject()); + } + + if (version >= 4) { + stat.setExtraModFromString((String) os.readObject()); + } + + } catch (EOFException e) { + Debug.e("O_o eof..."); + Debug.e("Replay.loadInfo: " + e.getMessage(), e); + ToastLogger.showTextId(R.string.replay_corrupted, true); + return false; + + } catch (Exception e) { + ToastLogger.showTextId(R.string.replay_corrupted, true); + Debug.e("Cannot load replay: " + e.getMessage(), e); + return false; + } + + return true; + } + + public boolean load(final String filename) { + ObjectInputStream os; + try { + final ZipInputStream zip = new ZipInputStream(new FileInputStream( + new File(filename))); + zip.getNextEntry(); + os = new ObjectInputStream(zip); + // zip.close(); + } catch (final Exception e) { + Debug.e("Cannot load replay: " + e.getMessage(), e); + return false; + } + + Debug.i("Loading replay " + filename); + + cursorMoves.clear(); + int version = 0; + try { + String mname; + Object firstObject = os.readObject(); + Debug.i("Readed object: " + firstObject.getClass().getName()); + if (firstObject.getClass().equals(ReplayVersion.class)) { + Debug.i("Other replay version"); + version = ((ReplayVersion) firstObject).version; + replayVersion = version; + mname = (String) os.readObject(); + + } else { + mname = (String) firstObject; + } + String mfile = (String) os.readObject(); + String mmd5 = (String) os.readObject(); + + if (mname.equals(mapname) == false && mfile.equals(mapfile) == false) { + Debug.i("Replay doesn't match the map!"); + Debug.i(mapname + " ::: " + mname); + Debug.i(mapfile + " ::: " + mfile); + Debug.i(md5 + " ::: " + mmd5); + ToastLogger.showTextId(R.string.replay_wrongmap, true); + + os.close(); + return false; + } + + if (version >= 3) { + stat = new StatisticV2(); + stat.setTime(os.readLong()); + stat.setHit300k(os.readInt()); + stat.setHit300(os.readInt()); + stat.setHit100k(os.readInt()); + stat.setHit100(os.readInt()); + stat.setHit50(os.readInt()); + stat.setMisses(os.readInt()); + stat.setForcedScore(os.readInt()); + stat.setMaxCombo(os.readInt()); + stat.setAccuracy(os.readFloat()); + stat.setPerfect(os.readBoolean()); + stat.setPlayerName((String) os.readObject()); + stat.setMod((EnumSet) os.readObject()); + } + + if (version >= 4) { + stat.setExtraModFromString((String) os.readObject()); + } + + int msize = os.readInt(); + for (int i = 0; i < msize; i++) { + cursorMoves.add(MoveArray.readFrom(os, this)); + } + + os.readInt(); + for (int i = 0; i < objectData.length; i++) { + ReplayObjectData data = new ReplayObjectData(); + data.accuracy = os.readShort(); + int len = os.readByte(); + if (len > 0) { + data.tickSet = new BitSet(); + byte[] bytes = new byte[len]; + os.read(bytes); + for (int j = 0; j < len * 8; j++) { + data.tickSet.set(j, (bytes[len - j / 8 - 1] & 1 << (j % 8)) != 0); + } + } + if (version >= 1) { + data.result = os.readByte(); + } + objectData[i] = data; + } + } catch (EOFException e) { + Debug.e("Replay.load: " + e.getMessage(), e); + ToastLogger.showTextId(R.string.replay_corrupted, true); + return false; + } + catch (Exception e) { + ToastLogger.showTextId(R.string.replay_corrupted, true); + Debug.e("Cannot load replay: " + e.getMessage(), e); + return false; + } + + for (int i = 0; i < cursorMoves.size(); i++) + Debug.i("Loaded " + cursorMoves.get(i).size + " moves for finger " + i); + Debug.i("Loaded " + objectData.length + " objects"); + return true; + } + + public void countMarks(float difficulty) { + } + + public StatisticV2 getStat() { + return stat; + } + + public void setStat(StatisticV2 stat) { + this.stat = stat; + } + + public String getMd5() { + return md5; + } + + public String getMapfile() { + return mapfile; + } + + public String getMapname() { + return mapname; + } + + public static class ReplayVersion implements Serializable { + private static final long serialVersionUID = 4643121693566795335L; + int version = 5; + // version 4: Add ExtraModString's save and load in save()/load()/loadInfo() + // version 5: changed gamePoints to be a float type + } + + public static class ReplayObjectData { + public short accuracy = 0; + public BitSet tickSet = null; + public byte result = 0; + } + + public static class MoveArray { + public int[] time; + public float[] x; + public float[] y; + public byte[] id; + + public int size; + public int allocated; + + public MoveArray(int startSize) { + allocated = startSize; + size = 0; + time = new int[allocated]; + x = new float[allocated]; + y = new float[allocated]; + id = new byte[allocated]; + } + + public static MoveArray readFrom(ObjectInputStream is, Replay replay) throws IOException { + int size = is.readInt(); + MoveArray array = new MoveArray(size); + + for (int i = 0; i < size; i++) { + array.time[i] = is.readInt(); + array.id[i] = (byte) (array.time[i] & 3); + array.time[i] >>= 2; + if (array.id[i] != ID_UP) { + PointF gamePoint; + + if(replay.replayVersion >= 5) { + gamePoint = new PointF((float) (Math.round(is.readFloat()) / Config.getTextureQuality()), + (float) (Math.round(is.readFloat()) / Config.getTextureQuality())); + }else { + gamePoint = new PointF((float) (is.readShort() / Config.getTextureQuality()), + (float) (is.readShort() / Config.getTextureQuality())); + } + + if (replay.replayVersion == 1) { + PointF realPoint = Utils.trackToRealCoords(Utils.realToTrackCoords(gamePoint, 1024, 600, true)); + array.x[i] = realPoint.x; + array.y[i] = realPoint.y; + } else if (replay.replayVersion > 1) { + PointF realPoint = Utils.trackToRealCoords(gamePoint); + array.x[i] = realPoint.x; + array.y[i] = realPoint.y; + } + } + array.size = size; + } + + return array; + } + + public void reallocate(int newSize) { + if (newSize <= allocated) return; + int[] newTime = new int[newSize]; + float[] newX = new float[newSize]; + float[] newY = new float[newSize]; + byte[] newId = new byte[newSize]; + + System.arraycopy(time, 0, newTime, 0, size); + System.arraycopy(x, 0, newX, 0, size); + System.arraycopy(y, 0, newY, 0, size); + System.arraycopy(id, 0, newId, 0, size); + + time = newTime; + x = newX; + y = newY; + id = newId; + + allocated = newSize; + } + + public boolean checkNewPoint(float px, float py) { + if (size < 2) return false; + float tx = (px + x[size - 2]) * 0.5f; + float ty = (py + y[size - 2]) * 0.5f; + + return (Utils.sqr(x[size - 1] - tx) + Utils.sqr(y[size - 1] - ty)) <= 25; + } + + public void pushBack(int time, float x, float y, byte id) { + int idx = size; + if (id == ID_MOVE && checkNewPoint(x, y)) { + idx = size - 1; + pointsSkipped++; + } else { + if (size + 1 >= allocated) + reallocate((allocated * 3) / 2); + size++; + } + this.time[idx] = time; + this.x[idx] = x; + this.y[idx] = y; + this.id[idx] = id; + } + + public void pushBack(int time, byte id) { + if (size >= allocated) + reallocate((allocated * 3) / 2); + this.time[size] = time; + this.id[size] = id; + size++; + } + + public void writeTo(ObjectOutputStream os) throws IOException { + os.writeInt(size); + for (int i = 0; i < size; i++) { + os.writeInt((time[i] << 2) + id[i]); + if (id[i] != ID_UP) { + os.writeFloat(x[i] * Config.getTextureQuality()); + os.writeFloat(y[i] * Config.getTextureQuality()); + } + } + } + } } diff --git a/src/ru/nsu/ccfit/zuev/osu/scoring/ScoreLibrary.java b/src/ru/nsu/ccfit/zuev/osu/scoring/ScoreLibrary.java index d3c79da7..e2f7cbd1 100644 --- a/src/ru/nsu/ccfit/zuev/osu/scoring/ScoreLibrary.java +++ b/src/ru/nsu/ccfit/zuev/osu/scoring/ScoreLibrary.java @@ -26,275 +26,275 @@ import ru.nsu.ccfit.zuev.osuplus.R; public class ScoreLibrary { - private static final Pattern newPathPattern = Pattern.compile("[^/]*/[^/]*\\z"); - private static ScoreLibrary lib = new ScoreLibrary(); - private SQLiteDatabase db = null; - - private ScoreLibrary() { - } - - public static ScoreLibrary getInstance() { - return lib; - } - - public static String getTrackPath(final String track) { - final Matcher newPathMather = newPathPattern.matcher(track); - if (newPathMather.find()) { - return newPathMather.group(); - } - return track; - } - - public static String getTrackDir(final String track) { - String s = getTrackPath(track); - if (s.endsWith(".osu")) { - return s.substring(0, s.indexOf('/')); - } else { - return s.substring(s.indexOf('/') + 1, s.length()); - } - } - - public SQLiteDatabase getDb() { - return db; - } - - public void load(Context context) { - DBOpenHelper helper = DBOpenHelper.getOrCreate(context); - try { - db = helper.getWritableDatabase(); - } catch (SQLiteCantOpenDatabaseException e) { - ToastLogger.showText( - StringTable.get(R.string.require_storage_permission), - true); - throw new RuntimeException(e); - } - loadOld(context); - } - - @SuppressWarnings("unchecked") - private void loadOld(Context context) { - final File folder = new File(Config.getCorePath() + "/Scores"); - if (folder.exists() == false) { - return; - } - final File f = new File(folder, "scoreboard"); - if (f.exists() == false) { - return; - } - Debug.i("Loading old scores..."); - try { - final ObjectInputStream in = new ObjectInputStream( - new FileInputStream(f)); - - Object obj = in.readObject(); - String versionStr = ""; - if (obj instanceof String) { - versionStr = (String) obj; - if (versionStr.equals("scores1") == false - && versionStr.equals("scores2") == false) { - in.close(); - return; - } - } else { - in.close(); - return; - } - obj = in.readObject(); - Map> scores = null; - if (obj instanceof Map) { - if (versionStr.equals("scores1")) { - final Map> oldStat = (Map>) obj; - scores = new HashMap>(); - for (final String str : oldStat.keySet()) { - final ArrayList newStat = new ArrayList(); - for (final Statistic s : oldStat.get(str)) { - newStat.add(new StatisticV2(s)); - } - final Matcher newPathMather = newPathPattern - .matcher(str); - if (newPathMather.find()) { - scores.put(newPathMather.group(), newStat); - } else { - scores.put(str, newStat); - } - } - } else if (versionStr.equals("scores2")) { - scores = (Map>) obj; - } - } - - if (scores != null) { - for (String track : scores.keySet()) { - for (StatisticV2 stat : scores.get(track)) { - addScore(track, stat, null); - } - } - } - - in.close(); - } catch (final Exception e) { - Debug.e("ScoreLibrary.loadOld: " + e.getMessage()); - return; - } - f.delete(); - } - - public void save() { - - } - - public void sendScoreOnline(final StatisticV2 stat, final String replay, - final SendingPanel panel) { - Debug.i("Preparing for online!"); - if (stat.getModifiedTotalScore() <= 0) return; - OnlineScoring.getInstance().sendRecord(stat, panel, replay); - } - - public void addScore(final String trackPath, final StatisticV2 stat, final String replay) { - if (stat.getModifiedTotalScore() == 0) { - return; - } - final String track = getTrackPath(trackPath); - - if (db == null) return; - ContentValues values = new ContentValues(); - values.put("filename", track); - values.put("playername", stat.getPlayerName()); - values.put("replayfile", replay); - values.put("mode", stat.getModString()); - values.put("score", stat.getModifiedTotalScore()); - values.put("combo", stat.getMaxCombo()); - values.put("mark", stat.getMark()); - values.put("h300k", stat.getHit300k()); - values.put("h300", stat.getHit300()); - values.put("h100k", stat.getHit100k()); - values.put("h100", stat.getHit100()); - values.put("h50", stat.getHit50()); - values.put("misses", stat.getMisses()); - values.put("accuracy", stat.getAccuracy()); - values.put("time", stat.getTime()); - values.put("perfect", stat.isPerfect() ? 1 : 0); - - long result = db.insert(DBOpenHelper.SCORES_TABLENAME, null, values); - Debug.i("Inserting data, result = " + result); - -// String[] columns = {"id", "filename", "score", "replayfile"}; -// Cursor response = -// db.query(DBOpenHelper.SCORES_TABLENAME, columns, "filename = \"" + track + "\"" , -// null, null, null, "score ASC"); - //if scores > 5, we need to remove some -// if (response.getCount() > 5) -// { -// response.moveToFirst(); -// int rowsToDelete = response.getCount() - 5; -// String filter = ""; -// for (int i = 0; i < rowsToDelete; i++) -// { -// filter += response.getString(0); -// if (i < rowsToDelete - 1) -// filter += ","; + private static final Pattern newPathPattern = Pattern.compile("[^/]*/[^/]*\\z"); + private static ScoreLibrary lib = new ScoreLibrary(); + private SQLiteDatabase db = null; + + private ScoreLibrary() { + } + + public static ScoreLibrary getInstance() { + return lib; + } + + public static String getTrackPath(final String track) { + final Matcher newPathMather = newPathPattern.matcher(track); + if (newPathMather.find()) { + return newPathMather.group(); + } + return track; + } + + public static String getTrackDir(final String track) { + String s = getTrackPath(track); + if (s.endsWith(".osu")) { + return s.substring(0, s.indexOf('/')); + } else { + return s.substring(s.indexOf('/') + 1, s.length()); + } + } + + public SQLiteDatabase getDb() { + return db; + } + + public void load(Context context) { + DBOpenHelper helper = DBOpenHelper.getOrCreate(context); + try { + db = helper.getWritableDatabase(); + } catch (SQLiteCantOpenDatabaseException e) { + ToastLogger.showText( + StringTable.get(R.string.require_storage_permission), + true); + throw new RuntimeException(e); + } + loadOld(context); + } + + @SuppressWarnings("unchecked") + private void loadOld(Context context) { + final File folder = new File(Config.getCorePath() + "/Scores"); + if (folder.exists() == false) { + return; + } + final File f = new File(folder, "scoreboard"); + if (f.exists() == false) { + return; + } + Debug.i("Loading old scores..."); + try { + final ObjectInputStream in = new ObjectInputStream( + new FileInputStream(f)); + + Object obj = in.readObject(); + String versionStr = ""; + if (obj instanceof String) { + versionStr = (String) obj; + if (versionStr.equals("scores1") == false + && versionStr.equals("scores2") == false) { + in.close(); + return; + } + } else { + in.close(); + return; + } + obj = in.readObject(); + Map> scores = null; + if (obj instanceof Map) { + if (versionStr.equals("scores1")) { + final Map> oldStat = (Map>) obj; + scores = new HashMap>(); + for (final String str : oldStat.keySet()) { + final ArrayList newStat = new ArrayList(); + for (final Statistic s : oldStat.get(str)) { + newStat.add(new StatisticV2(s)); + } + final Matcher newPathMather = newPathPattern + .matcher(str); + if (newPathMather.find()) { + scores.put(newPathMather.group(), newStat); + } else { + scores.put(str, newStat); + } + } + } else if (versionStr.equals("scores2")) { + scores = (Map>) obj; + } + } + + if (scores != null) { + for (String track : scores.keySet()) { + for (StatisticV2 stat : scores.get(track)) { + addScore(track, stat, null); + } + } + } + + in.close(); + } catch (final Exception e) { + Debug.e("ScoreLibrary.loadOld: " + e.getMessage()); + return; + } + f.delete(); + } + + public void save() { + + } + + public void sendScoreOnline(final StatisticV2 stat, final String replay, + final SendingPanel panel) { + Debug.i("Preparing for online!"); + if (stat.getModifiedTotalScore() <= 0) return; + OnlineScoring.getInstance().sendRecord(stat, panel, replay); + } + + public void addScore(final String trackPath, final StatisticV2 stat, final String replay) { + if (stat.getModifiedTotalScore() == 0) { + return; + } + final String track = getTrackPath(trackPath); + + if (db == null) return; + ContentValues values = new ContentValues(); + values.put("filename", track); + values.put("playername", stat.getPlayerName()); + values.put("replayfile", replay); + values.put("mode", stat.getModString()); + values.put("score", stat.getModifiedTotalScore()); + values.put("combo", stat.getMaxCombo()); + values.put("mark", stat.getMark()); + values.put("h300k", stat.getHit300k()); + values.put("h300", stat.getHit300()); + values.put("h100k", stat.getHit100k()); + values.put("h100", stat.getHit100()); + values.put("h50", stat.getHit50()); + values.put("misses", stat.getMisses()); + values.put("accuracy", stat.getAccuracy()); + values.put("time", stat.getTime()); + values.put("perfect", stat.isPerfect() ? 1 : 0); + + long result = db.insert(DBOpenHelper.SCORES_TABLENAME, null, values); + Debug.i("Inserting data, result = " + result); + +// String[] columns = {"id", "filename", "score", "replayfile"}; +// Cursor response = +// db.query(DBOpenHelper.SCORES_TABLENAME, columns, "filename = \"" + track + "\"" , +// null, null, null, "score ASC"); + //if scores > 5, we need to remove some +// if (response.getCount() > 5) +// { +// response.moveToFirst(); +// int rowsToDelete = response.getCount() - 5; +// String filter = ""; +// for (int i = 0; i < rowsToDelete; i++) +// { +// filter += response.getString(0); +// if (i < rowsToDelete - 1) +// filter += ","; // -// //removing score replay -// try{ -// new File(response.getString(3)).delete(); -// } catch (Exception e){} +// //removing score replay +// try{ +// new File(response.getString(3)).delete(); +// } catch (Exception e){} // -// response.moveToNext(); +// response.moveToNext(); // -// } -// //removing all unnecessary scores -// filter = "id IN (" + filter + ")"; -// result = db.delete(DBOpenHelper.SCORES_TABLENAME, filter, null); -// } - -// response.close(); - } - - public Cursor getMapScores(String[] columns, String filename) { - final String track = getTrackPath(filename); - if (db == null) return null; - return db.query(DBOpenHelper.SCORES_TABLENAME, columns, "filename = ?", - new String[]{track}, null, null, "score DESC"); - } - - public String getBestMark(final String trackPath) { - final String track = getTrackPath(trackPath); - String[] columns = {"mark", "filename", "id", "score"}; - Cursor response = - db.query(DBOpenHelper.SCORES_TABLENAME, columns, "filename = ?", - new String[]{track}, null, null, "score DESC"); - if (response.getCount() == 0) { - response.close(); - return null; - } - response.moveToFirst(); - - String mark = response.getString(0); -// do { -// final String s = response.getString(0); -// if (s.equals("XH")) { -// mark = s; -// } else if (s.equals("X") && mark.equals("XH") == false) { -// mark = s; -// } else if (s.equals("SH") && mark.equals("XH") == false -// && mark.equals("X") == false) { -// mark = s; -// } else if (s.equals("S") && mark.equals("XH") == false -// && mark.equals("X") == false && mark.equals("SH") == false) { -// mark = s; -// } else if (s.equals("A") && mark.equals("XH") == false -// && mark.equals("X") == false && mark.equals("SH") == false -// && mark.equals("S") == false) { -// mark = s; -// } else if (s.equals("B") && mark.equals("XH") == false -// && mark.equals("X") == false && mark.equals("SH") == false -// && mark.equals("S") == false && mark.equals("A") == false) { -// mark = s; -// } else if (s.equals("C") && mark.equals("XH") == false -// && mark.equals("X") == false && mark.equals("SH") == false -// && mark.equals("S") == false && mark.equals("A") == false -// && mark.equals("B") == false) { -// mark = s; -// } -// } while (response.moveToNext()); - - response.close(); - - return mark; - } - - public StatisticV2 getScore(int id) { - Cursor c = db.query(DBOpenHelper.SCORES_TABLENAME, null, "id = " + id, - null, null, null, null); - StatisticV2 stat = new StatisticV2(); - if (c.getCount() == 0) { - c.close(); - return stat; - } - c.moveToFirst(); - - stat.setPlayerName(c.getString(c.getColumnIndexOrThrow("playername"))); - stat.setReplayName(c.getString(c.getColumnIndexOrThrow("replayfile"))); - stat.setModFromString(c.getString(c.getColumnIndexOrThrow("mode"))); - stat.setForcedScore(c.getInt(c.getColumnIndexOrThrow("score"))); - stat.maxCombo = c.getInt(c.getColumnIndexOrThrow("combo")); - stat.setMark(c.getString(c.getColumnIndexOrThrow("mark"))); - stat.hit300k = c.getInt(c.getColumnIndexOrThrow("h300k")); - stat.hit300 = c.getInt(c.getColumnIndexOrThrow("h300")); - stat.hit100k = c.getInt(c.getColumnIndexOrThrow("h100k")); - stat.hit100 = c.getInt(c.getColumnIndexOrThrow("h100")); - stat.hit50 = c.getInt(c.getColumnIndexOrThrow("h50")); - stat.misses = c.getInt(c.getColumnIndexOrThrow("misses")); - stat.accuracy = c.getFloat(c.getColumnIndexOrThrow("accuracy")); - stat.time = c.getLong(c.getColumnIndexOrThrow("time")); - stat.setPerfect(c.getInt(c.getColumnIndexOrThrow("perfect")) != 0); - - c.close(); - - return stat; - } - - public boolean deleteScore(int id) { - return db.delete(DBOpenHelper.SCORES_TABLENAME, "id = " + id, null) != 0; - } +// } +// //removing all unnecessary scores +// filter = "id IN (" + filter + ")"; +// result = db.delete(DBOpenHelper.SCORES_TABLENAME, filter, null); +// } + +// response.close(); + } + + public Cursor getMapScores(String[] columns, String filename) { + final String track = getTrackPath(filename); + if (db == null) return null; + return db.query(DBOpenHelper.SCORES_TABLENAME, columns, "filename = ?", + new String[]{track}, null, null, "score DESC"); + } + + public String getBestMark(final String trackPath) { + final String track = getTrackPath(trackPath); + String[] columns = {"mark", "filename", "id", "score"}; + Cursor response = + db.query(DBOpenHelper.SCORES_TABLENAME, columns, "filename = ?", + new String[]{track}, null, null, "score DESC"); + if (response.getCount() == 0) { + response.close(); + return null; + } + response.moveToFirst(); + + String mark = response.getString(0); +// do { +// final String s = response.getString(0); +// if (s.equals("XH")) { +// mark = s; +// } else if (s.equals("X") && mark.equals("XH") == false) { +// mark = s; +// } else if (s.equals("SH") && mark.equals("XH") == false +// && mark.equals("X") == false) { +// mark = s; +// } else if (s.equals("S") && mark.equals("XH") == false +// && mark.equals("X") == false && mark.equals("SH") == false) { +// mark = s; +// } else if (s.equals("A") && mark.equals("XH") == false +// && mark.equals("X") == false && mark.equals("SH") == false +// && mark.equals("S") == false) { +// mark = s; +// } else if (s.equals("B") && mark.equals("XH") == false +// && mark.equals("X") == false && mark.equals("SH") == false +// && mark.equals("S") == false && mark.equals("A") == false) { +// mark = s; +// } else if (s.equals("C") && mark.equals("XH") == false +// && mark.equals("X") == false && mark.equals("SH") == false +// && mark.equals("S") == false && mark.equals("A") == false +// && mark.equals("B") == false) { +// mark = s; +// } +// } while (response.moveToNext()); + + response.close(); + + return mark; + } + + public StatisticV2 getScore(int id) { + Cursor c = db.query(DBOpenHelper.SCORES_TABLENAME, null, "id = " + id, + null, null, null, null); + StatisticV2 stat = new StatisticV2(); + if (c.getCount() == 0) { + c.close(); + return stat; + } + c.moveToFirst(); + + stat.setPlayerName(c.getString(c.getColumnIndexOrThrow("playername"))); + stat.setReplayName(c.getString(c.getColumnIndexOrThrow("replayfile"))); + stat.setModFromString(c.getString(c.getColumnIndexOrThrow("mode"))); + stat.setForcedScore(c.getInt(c.getColumnIndexOrThrow("score"))); + stat.maxCombo = c.getInt(c.getColumnIndexOrThrow("combo")); + stat.setMark(c.getString(c.getColumnIndexOrThrow("mark"))); + stat.hit300k = c.getInt(c.getColumnIndexOrThrow("h300k")); + stat.hit300 = c.getInt(c.getColumnIndexOrThrow("h300")); + stat.hit100k = c.getInt(c.getColumnIndexOrThrow("h100k")); + stat.hit100 = c.getInt(c.getColumnIndexOrThrow("h100")); + stat.hit50 = c.getInt(c.getColumnIndexOrThrow("h50")); + stat.misses = c.getInt(c.getColumnIndexOrThrow("misses")); + stat.accuracy = c.getFloat(c.getColumnIndexOrThrow("accuracy")); + stat.time = c.getLong(c.getColumnIndexOrThrow("time")); + stat.setPerfect(c.getInt(c.getColumnIndexOrThrow("perfect")) != 0); + + c.close(); + + return stat; + } + + public boolean deleteScore(int id) { + return db.delete(DBOpenHelper.SCORES_TABLENAME, "id = " + id, null) != 0; + } } diff --git a/src/ru/nsu/ccfit/zuev/osu/scoring/ScoreNumber.java b/src/ru/nsu/ccfit/zuev/osu/scoring/ScoreNumber.java index caa7eacb..287f189a 100644 --- a/src/ru/nsu/ccfit/zuev/osu/scoring/ScoreNumber.java +++ b/src/ru/nsu/ccfit/zuev/osu/scoring/ScoreNumber.java @@ -8,67 +8,67 @@ import ru.nsu.ccfit.zuev.osu.ResourceManager; public class ScoreNumber { - private final Sprite[] letters; - private float x, y, height; + private final Sprite[] letters; + private float x, y, height; - public ScoreNumber(final float x, final float y, final String text, - final float scale, final boolean center) { - this.x = x; - this.y = y; - letters = new Sprite[text.length()]; - float width = 0; - for (int i = 0; i < text.length(); i++) { - if (text.charAt(i) <= '9' && text.charAt(i) >= '0') { - letters[i] = new Sprite(x + width * scale, y, ResourceManager - .getInstance().getTexture("score-" + text.charAt(i))); - } else if (text.charAt(i) == '.' || text.charAt(i) == ',') { - letters[i] = new Sprite(x + width * scale, y, ResourceManager - .getInstance().getTexture("score-comma")); - } else if (text.charAt(i) == '%') { - letters[i] = new Sprite(x + width * scale, y, ResourceManager - .getInstance().getTexture("score-percent")); - } else { - letters[i] = new Sprite(x + width * scale, y, ResourceManager - .getInstance().getTexture("score-x")); - } - letters[i].setSize(letters[i].getWidth() * scale, - letters[i].getHeight() * scale); - width += letters[i].getWidth() * scale; - height = letters[i].getHeight() * scale; - } + public ScoreNumber(final float x, final float y, final String text, + final float scale, final boolean center) { + this.x = x; + this.y = y; + letters = new Sprite[text.length()]; + float width = 0; + for (int i = 0; i < text.length(); i++) { + if (text.charAt(i) <= '9' && text.charAt(i) >= '0') { + letters[i] = new Sprite(x + width * scale, y, ResourceManager + .getInstance().getTexture("score-" + text.charAt(i))); + } else if (text.charAt(i) == '.' || text.charAt(i) == ',') { + letters[i] = new Sprite(x + width * scale, y, ResourceManager + .getInstance().getTexture("score-comma")); + } else if (text.charAt(i) == '%') { + letters[i] = new Sprite(x + width * scale, y, ResourceManager + .getInstance().getTexture("score-percent")); + } else { + letters[i] = new Sprite(x + width * scale, y, ResourceManager + .getInstance().getTexture("score-x")); + } + letters[i].setSize(letters[i].getWidth() * scale, + letters[i].getHeight() * scale); + width += letters[i].getWidth() * scale; + height = letters[i].getHeight() * scale; + } - if (center) { - width /= 2 * scale; - for (final Sprite sp : letters) { - sp.setPosition(sp.getX() - width, sp.getY()); - sp.registerEntityModifier(new SequenceEntityModifier( - new ScaleModifier(0.2f, scale, scale * 1.5f), - new ScaleModifier(0.4f, scale * 1.5f, scale))); - } - }// if center - } + if (center) { + width /= 2 * scale; + for (final Sprite sp : letters) { + sp.setPosition(sp.getX() - width, sp.getY()); + sp.registerEntityModifier(new SequenceEntityModifier( + new ScaleModifier(0.2f, scale, scale * 1.5f), + new ScaleModifier(0.4f, scale * 1.5f, scale))); + } + }// if center + } - public void attachToScene(final Scene scene) { - for (final Sprite sp : letters) { - scene.attachChild(sp); - } - } + public void attachToScene(final Scene scene) { + for (final Sprite sp : letters) { + scene.attachChild(sp); + } + } - public void detachFromScene(final Scene scene) { - for (final Sprite sp : letters) { - scene.detachChild(sp); - } - } + public void detachFromScene(final Scene scene) { + for (final Sprite sp : letters) { + scene.detachChild(sp); + } + } - public float getX() { - return x; - } + public float getX() { + return x; + } - public float getY() { - return y; - } + public float getY() { + return y; + } - public float getHeight() { - return height; - } + public float getHeight() { + return height; + } } diff --git a/src/ru/nsu/ccfit/zuev/osu/scoring/ScoringScene.java b/src/ru/nsu/ccfit/zuev/osu/scoring/ScoringScene.java index 4aec9dc5..0da84dd3 100644 --- a/src/ru/nsu/ccfit/zuev/osu/scoring/ScoringScene.java +++ b/src/ru/nsu/ccfit/zuev/osu/scoring/ScoringScene.java @@ -37,518 +37,518 @@ import ru.nsu.ccfit.zuev.osuplus.R; public class ScoringScene { - private final Engine engine; - private final GameScene game; - private final SongMenu menu; - private Scene scene; - private SongService songService; - private StatisticV2 replayStat; - private int replayID = -1; - private TrackInfo track; - - public ScoringScene(final Engine pEngine, final GameScene pGame, - final SongMenu pMenu) { - engine = pEngine; - game = pGame; - menu = pMenu; - } - - public void load(final StatisticV2 stat, final TrackInfo track, - final SongService player, final String replay, final String mapMD5, - final TrackInfo trackToReplay) { - scene = new Scene(); - //music = player; - this.songService = player; - if (replay != null && track == null) { - replayStat = stat; - } - InGameSettingMenu.getInstance().dismiss(); - TextureRegion tex = ResourceManager.getInstance() - .getTextureIfLoaded("::background"); - if (tex == null) { - tex = ResourceManager.getInstance().getTexture("menu-background"); - } - float height = tex.getHeight(); - height *= Config.getRES_WIDTH() / (float) tex.getWidth(); - final Sprite bg = new Sprite(0, (Config.getRES_HEIGHT() - height) / 2, - Config.getRES_WIDTH(), height, tex); - scene.setBackground(new SpriteBackground(bg)); - - final Rectangle bgTopRect = new Rectangle(0, 0, Config.getRES_WIDTH(), Utils.toRes(100)); - bgTopRect.setColor(0, 0, 0, 0.8f); - scene.attachChild(bgTopRect); - - TrackInfo trackInfo = trackToReplay; - if (trackToReplay == null && track != null) { - trackInfo = track; - } - this.track = trackInfo; - final int x = 0, y = 100; - final TextureRegion panelr = ResourceManager.getInstance().getTexture( - "ranking-panel"); - final Sprite panel = new Sprite(x, y, Utils.toRes(panelr.getWidth() * 0.9f), - Utils.toRes(panelr.getHeight() * 0.9f), panelr); - scene.attachChild(panel); - -// final float iconSize = Utils.toRes(64); - - final TextureRegion hit300sr = ResourceManager.getInstance().getTexture("hit300"); - final Sprite hit300s = new Sprite(Utils.toRes(10), Utils.toRes(130), - Utils.toRes(hit300sr.getWidth()), Utils.toRes(hit300sr.getHeight()), hit300sr); - hit300s.setPosition(Utils.toRes(70 - hit300s.getWidth() / 2 + x), Utils.toRes(130 - hit300s.getHeight() / 2 + y)); - scene.attachChild(hit300s); - - final TextureRegion hit100sr = ResourceManager.getInstance().getTexture("hit100"); - final Sprite hit100s = new Sprite(Utils.toRes(10), Utils.toRes(130 + 92), - Utils.toRes(hit100sr.getWidth()), Utils.toRes(hit100sr.getHeight()), hit100sr); - hit100s.setPosition(Utils.toRes(70 - hit100s.getWidth() / 2 + x), Utils.toRes(130 + 92 - hit100s.getHeight() / 2 + y)); - scene.attachChild(hit100s); - - final TextureRegion hit50sr = ResourceManager.getInstance().getTexture("hit50"); - final Sprite hit50s = new Sprite(0, Utils.toRes(120 + 92 * 2), - Utils.toRes(hit50sr.getWidth()), Utils.toRes(hit50sr.getHeight()), hit50sr); - hit50s.setPosition(Utils.toRes(70 - hit50s.getWidth() / 2 + x), Utils.toRes(130 + 92 * 2 - hit50s.getHeight() / 2 + y)); - scene.attachChild(hit50s); - - final TextureRegion hit300ksr = ResourceManager.getInstance().getTexture("hit300g"); - final Sprite hit300ks = new Sprite(Utils.toRes(300), Utils.toRes(100), - Utils.toRes(hit300ksr.getWidth()), Utils.toRes(hit300ksr.getHeight()), hit300ksr); - hit300ks.setPosition(Utils.toRes(340 - hit300ks.getWidth() / 2 + x), Utils.toRes(130 - hit300ks.getHeight() / 2 + y)); - scene.attachChild(hit300ks); - - final TextureRegion hit100ksr = ResourceManager.getInstance().getTexture("hit100k"); - final Sprite hit100ks = new Sprite(Utils.toRes(300), Utils.toRes(120 + 92), - Utils.toRes(hit100ksr.getWidth()), Utils.toRes(hit100ksr.getHeight()), hit100ksr); - hit100ks.setPosition(Utils.toRes(340 - hit100ks.getWidth() / 2 + x), Utils.toRes(130 + 92 - hit100ks.getHeight() / 2 + y)); - scene.attachChild(hit100ks); - - final TextureRegion hit0sr = ResourceManager.getInstance().getTexture("hit0"); - final Sprite hit0s = new Sprite(Utils.toRes(300), Utils.toRes(120 + 92 * 2), - Utils.toRes(hit0sr.getWidth()), Utils.toRes(hit0sr.getHeight()), hit0sr); - hit0s.setPosition(Utils.toRes(340 - hit0s.getWidth() / 2 + x), Utils.toRes(130 + 92 * 2 - hit0s.getHeight() / 2 + y)); - scene.attachChild(hit0s); - - final Sprite rankingText = new Sprite(Utils.toRes(580), 0, - ResourceManager.getInstance().getTexture("ranking-title")); - rankingText.setPosition(Config.getRES_WIDTH() * 5 / 6 - rankingText.getWidth() / 2, 0); - scene.attachChild(rankingText); - - int totalScore = stat.getModifiedTotalScore(); - if (totalScore == 0) { - totalScore = stat.getAutoTotalScore(); - } - String scoreStr = String.valueOf(totalScore); - while (scoreStr.length() < 8) { - scoreStr = '0' + scoreStr; - } - final ScoreNumber scoreNum = new ScoreNumber(Utils.toRes(220 + x), - Utils.toRes(18 + y), scoreStr, 1, false); - scoreNum.attachToScene(scene); - - final ScoreNumber hit300num = new ScoreNumber(Utils.toRes(138 + x), - Utils.toRes(110 + y), stat.getHit300() + "x", 1, - false); - hit300num.attachToScene(scene); - final ScoreNumber hit100num = new ScoreNumber(Utils.toRes(138 + x), - Utils.toRes(110 + 85 + y), stat.getHit100() + "x", - 1, false); - hit100num.attachToScene(scene); - final ScoreNumber hit50num = new ScoreNumber(Utils.toRes(138 + x), - Utils.toRes(110 + 85 * 2 + y), stat.getHit50() + "x", - 1, false); - hit50num.attachToScene(scene); - - final ScoreNumber hit300knum = new ScoreNumber(Utils.toRes(400 + x), - Utils.toRes(110 + y), stat.getHit300k() + "x", 1, - false); - hit300knum.attachToScene(scene); - final ScoreNumber hit100knum = new ScoreNumber(Utils.toRes(400 + x), - Utils.toRes(110 + 85 + y), stat.getHit100k() + "x", - 1, false); - hit100knum.attachToScene(scene); - final ScoreNumber hit0num = new ScoreNumber(Utils.toRes(400 + x), - Utils.toRes(110 + 85 * 2 + y), stat.getMisses() + "x", - 1, false); - hit0num.attachToScene(scene); - - final Sprite maxComboText = new Sprite(Utils.toRes(20 + x), - Utils.toRes(332 + y), ResourceManager.getInstance().getTexture( - "ranking-maxcombo")); - scene.attachChild(maxComboText); - final Sprite accText = new Sprite(Utils.toRes(260 + x), Utils.toRes(332 + y), - ResourceManager.getInstance().getTexture("ranking-accuracy")); - scene.attachChild(accText); - final ScoreNumber maxCombo = new ScoreNumber(Utils.toRes(20 + x), - Utils.toRes(maxComboText.getY() + 38), String.valueOf(stat.getMaxCombo()) + "x", 1, - false); - maxCombo.attachToScene(scene); - final String accStr = String - .format(Locale.ENGLISH, "%2.2f%%", stat.getAccuracy() * 100); - final ScoreNumber accuracy = new ScoreNumber(Utils.toRes(260 + x), - Utils.toRes(accText.getY() + 38), accStr, 1, false); - accuracy.attachToScene(scene); - - final Sprite mark = new Sprite(Utils.toRes(610), 0, ResourceManager - .getInstance().getTexture("ranking-" + stat.getMark())); - if (track != null) { - mark.setAlpha(0); - mark.setScale(1.5f); - mark.registerEntityModifier(new ParallelEntityModifier( - new FadeInModifier(2), new ScaleModifier(2, 2, 1))); - } - mark.setPosition(Config.getRES_WIDTH() * 5 / 6 - mark.getWidth() / 2, 80); - - final Sprite backBtn = new Sprite(Utils.toRes(580), Utils.toRes(490), - ResourceManager.getInstance().getTexture("ranking-back")) { - - - @Override - public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, - final float pTouchAreaLocalX, final float pTouchAreaLocalY) { - if (pSceneTouchEvent.isActionDown()) { - setColor(0.7f, 0.7f, 0.7f); - ResourceManager.getInstance().getSound("menuback").play(); - return true; - } - if (pSceneTouchEvent.isActionUp()) { - ResourceManager.getInstance().getSound("applause").stop(); - GlobalManager.getInstance().getScoring().setReplayID(-1); - menu.updateScore(); -// stopMusic(); - replayMusic(); - engine.setScene(menu.getScene()); - scene = null; - return true; - } - return false; - } - - }; - backBtn.setPosition(Config.getRES_WIDTH() - backBtn.getWidth() - 10, Config.getRES_HEIGHT() - backBtn.getHeight() - 10); - scene.attachChild(backBtn); - - final Sprite retryBtn = new Sprite(Utils.toRes(580), Utils.toRes(400), ResourceManager.getInstance().getTexture("ranking-retry")) { - - @Override - public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, - final float pTouchAreaLocalX, final float pTouchAreaLocalY) { - if (pSceneTouchEvent.isActionDown()) { - setColor(0.7f, 0.7f, 0.7f); - ResourceManager.getInstance().getSound("menuback").play(); - return true; - } - if (pSceneTouchEvent.isActionUp()) { - ResourceManager.getInstance().getSound("applause").stop(); - engine.setScene(menu.getScene()); - game.startGame(null, null); - scene = null; - stopMusic(); - return true; - } - return false; - } - - }; - - final Sprite replayBtn = new Sprite(Utils.toRes(580), Utils.toRes(400), - ResourceManager.getInstance().getTexture("ranking-replay")) { - - ///////////////////////////////////////////////////////////////////////////////// - ///////////////////////////////////////////////////////////////////////////////// - ///////////////////////////////////////////////////////////////////////////////// - ///////////////////////////////////////////////////////////////////////////////// - - @Override - public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, - final float pTouchAreaLocalX, final float pTouchAreaLocalY) { - if (pSceneTouchEvent.isActionDown()) { - setColor(0.7f, 0.7f, 0.7f); - ResourceManager.getInstance().getSound("menuback").play(); - return true; - } - if (pSceneTouchEvent.isActionUp()) { - ResourceManager.getInstance().getSound("applause").stop(); - SongMenu.stopMusicStatic(); - engine.setScene(menu.getScene()); - Replay.oldMod = ModMenu.getInstance().getMod(); - Replay.oldChangeSpeed = ModMenu.getInstance().getChangeSpeed(); - Replay.oldForceAR = ModMenu.getInstance().getForceAR(); - Replay.oldEnableForceAR = ModMenu.getInstance().isEnableForceAR(); - Replay.oldFLFollowDelay = ModMenu.getInstance().getFLfollowDelay(); - - ModMenu.getInstance().setMod(stat.getMod()); - ModMenu.getInstance().setChangeSpeed(stat.getChangeSpeed()); - ModMenu.getInstance().setForceAR(stat.getForceAR()); - ModMenu.getInstance().setEnableForceAR(stat.isEnableForceAR()); - ModMenu.getInstance().setFLfollowDelay(stat.getFLFollowDelay()); -// Replay.mod = stat.getMod(); - game.startGame(trackToReplay, replay); - scene = null; - stopMusic(); - return true; - } - return false; - } - - }; - - if (stat.accuracy == 1 || stat.getMaxCombo() == this.track.getMaxCombo() || stat.isPerfect()) { - final Sprite perfect = new Sprite(0, 0, ResourceManager - .getInstance().getTexture("ranking-perfect")); - perfect.setPosition(0, accuracy.getY() + accuracy.getHeight() + 10); - scene.attachChild(perfect); - } - if (track != null) { - retryBtn.setPosition(Config.getRES_WIDTH() - backBtn.getWidth() - 10, backBtn.getY() - retryBtn.getHeight() - 10); - scene.attachChild(retryBtn); - } else if (replay != null) { - replayBtn.setPosition(Config.getRES_WIDTH() - backBtn.getWidth() - 10, backBtn.getY() - replayBtn.getHeight() - 10); - scene.attachChild(replayBtn); - } - - scene.setTouchAreaBindingEnabled(true); - if (track != null) { - scene.registerTouchArea(retryBtn); - } else if (replay != null) { - scene.registerTouchArea(replayBtn); - } - scene.registerTouchArea(backBtn); - scene.attachChild(mark); - - float modX = mark.getX() - 30; - final float modY = mark.getY() + mark.getHeight() * 2 / 3; - if (stat.getMod().contains(GameMod.MOD_SCOREV2)) { - final Sprite modSprite = new Sprite(modX, modY, ResourceManager - .getInstance().getTexture("selection-mod-scorev2")); - modX -= Utils.toRes(30); - scene.attachChild(modSprite); - } - if (stat.getMod().contains(GameMod.MOD_HARDROCK)) { - final Sprite modSprite = new Sprite(modX, modY, ResourceManager - .getInstance().getTexture("selection-mod-hardrock")); - modX -= Utils.toRes(30); - scene.attachChild(modSprite); - } else if (stat.getMod().contains(GameMod.MOD_EASY)) { - final Sprite modSprite = new Sprite(modX, modY, ResourceManager - .getInstance().getTexture("selection-mod-easy")); - modX -= Utils.toRes(30); - scene.attachChild(modSprite); - } - - if (stat.getMod().contains(GameMod.MOD_HIDDEN)) { - final Sprite modSprite = new Sprite(modX, modY, ResourceManager - .getInstance().getTexture("selection-mod-hidden")); - modX -= Utils.toRes(30); - scene.attachChild(modSprite); - } - - if (stat.getMod().contains(GameMod.MOD_FLASHLIGHT)) { - final Sprite modSprite = new Sprite(modX, modY, ResourceManager - .getInstance().getTexture("selection-mod-flashlight")); - modX -= Utils.toRes(30); - scene.attachChild(modSprite); - } - if (stat.getMod().contains(GameMod.MOD_NOFAIL)) { - final Sprite modSprite = new Sprite(modX, modY, ResourceManager - .getInstance().getTexture("selection-mod-nofail")); - modX -= Utils.toRes(30); - scene.attachChild(modSprite); - } else if (stat.getMod().contains(GameMod.MOD_SUDDENDEATH)) { - final Sprite modSprite = new Sprite(modX, modY, ResourceManager - .getInstance().getTexture("selection-mod-suddendeath")); - modX -= Utils.toRes(30); - scene.attachChild(modSprite); - } else if (stat.getMod().contains(GameMod.MOD_PERFECT)) { - final Sprite modSprite = new Sprite(modX, modY, ResourceManager - .getInstance().getTexture("selection-mod-perfect")); - modX -= Utils.toRes(30); - scene.attachChild(modSprite); - } - if (stat.getMod().contains(GameMod.MOD_AUTO)) { - final Sprite modSprite = new Sprite(modX, modY, ResourceManager - .getInstance().getTexture("selection-mod-autoplay")); - modX -= Utils.toRes(30); - scene.attachChild(modSprite); - } else if (stat.getMod().contains(GameMod.MOD_AUTOPILOT)) { - final Sprite modSprite = new Sprite(modX, modY, ResourceManager - .getInstance().getTexture("selection-mod-relax2")); - modX -= Utils.toRes(30); - scene.attachChild(modSprite); - } else if (stat.getMod().contains(GameMod.MOD_RELAX)) { - final Sprite modSprite = new Sprite(modX, modY, ResourceManager - .getInstance().getTexture("selection-mod-relax")); - modX -= Utils.toRes(30); - scene.attachChild(modSprite); - } - if (stat.getMod().contains(GameMod.MOD_DOUBLETIME)) { - final Sprite modSprite = new Sprite(modX, modY, ResourceManager - .getInstance().getTexture("selection-mod-doubletime")); - modX -= Utils.toRes(30); - scene.attachChild(modSprite); - } else if (stat.getMod().contains(GameMod.MOD_NIGHTCORE)) { - final Sprite modSprite = new Sprite(modX, modY, ResourceManager - .getInstance().getTexture("selection-mod-nightcore")); - modX -= Utils.toRes(30); - scene.attachChild(modSprite); - } else if (stat.getMod().contains(GameMod.MOD_HALFTIME)) { - final Sprite modSprite = new Sprite(modX, modY, ResourceManager - .getInstance().getTexture("selection-mod-halftime")); - modX -= Utils.toRes(30); - scene.attachChild(modSprite); - } - - if (stat.getMod().contains(GameMod.MOD_PRECISE)) { - final Sprite modSprite = new Sprite(modX, modY, ResourceManager - .getInstance().getTexture("selection-mod-precise")); - modX -= Utils.toRes(30); - scene.attachChild(modSprite); - } - //new mods in 1.6.8 - if (stat.getMod().contains(GameMod.MOD_REALLYEASY)) { - final Sprite modSprite = new Sprite(modX, modY, ResourceManager - .getInstance().getTexture("selection-mod-reallyeasy")); - modX -= Utils.toRes(30); - scene.attachChild(modSprite); - } - if (stat.getMod().contains(GameMod.MOD_SMALLCIRCLE)) { - final Sprite modSprite = new Sprite(modX, modY, ResourceManager - .getInstance().getTexture("selection-mod-smallcircle")); - modX -= Utils.toRes(30); - scene.attachChild(modSprite); - } - // - - String infoStr = (trackInfo.getBeatmap().getArtistUnicode() == null || Config.isForceRomanized() ? trackInfo.getBeatmap().getArtist() : trackInfo.getBeatmap().getArtistUnicode()) + " - " + - (trackInfo.getBeatmap().getTitleUnicode() == null || Config.isForceRomanized() ? trackInfo.getBeatmap().getTitle() : trackInfo.getBeatmap().getTitleUnicode()) + " [" + trackInfo.getMode() + "]"; - String mapperStr = "Beatmap by " + trackInfo.getCreator(); - String playerStr = "Played by " + stat.getPlayerName() + " on " + - new java.text.SimpleDateFormat("yyyy/MM/dd HH:mm:ss", Locale.getDefault()).format(new java.util.Date(stat.getTime())); - playerStr += String.format(" %s(%s)", BuildConfig.VERSION_NAME, BuildConfig.BUILD_TYPE); - if (stat.getChangeSpeed() != 1 || - stat.isEnableForceAR() || - stat.getFLFollowDelay() != FlashLightEntity.defaultMoveDelayS && - stat.getMod().contains(GameMod.MOD_FLASHLIGHT)) { - - mapperStr += " ["; - if (stat.getChangeSpeed() != 1){ - mapperStr += String.format(Locale.ENGLISH, "%.2fx,", stat.getChangeSpeed()); - } - if (stat.isEnableForceAR()){ - mapperStr += String.format(Locale.ENGLISH, "AR%.1f,", stat.getForceAR()); - } - if (stat.getFLFollowDelay() != FlashLightEntity.defaultMoveDelayS && stat.getMod().contains(GameMod.MOD_FLASHLIGHT)){ - mapperStr += String.format(Locale.ENGLISH, "FLD%.2f,", stat.getFLFollowDelay()); - } - if (mapperStr.endsWith(",")){ - mapperStr = mapperStr.substring(0, mapperStr.length() - 1); - } - mapperStr += "]"; - } - Debug.i("playedtime " + stat.getTime()); - final Text beatmapInfo = new Text(Utils.toRes(4), Utils.toRes(2), - ResourceManager.getInstance().getFont("font"), infoStr); - final Text mapperInfo = new Text(Utils.toRes(4), beatmapInfo.getY() + beatmapInfo.getHeight() + Utils.toRes(2), - ResourceManager.getInstance().getFont("smallFont"), mapperStr); - final Text playerInfo = new Text(Utils.toRes(4), mapperInfo.getY() + mapperInfo.getHeight() + Utils.toRes(2), - ResourceManager.getInstance().getFont("smallFont"), playerStr); - //calculatePP - if (Config.isDisplayScorePP()){ - StringBuilder ppinfo = new StringBuilder(); - ppinfo.append("["); - DifficultyReCalculator diffRecalculator = new DifficultyReCalculator(); - float newstar = diffRecalculator.recalculateStar( - trackInfo, - diffRecalculator.getCS(stat, trackInfo), - stat.getSpeed() - ); - diffRecalculator.calculatePP(stat, trackInfo); - double pp = diffRecalculator.getTotalPP(); - double aimpp = diffRecalculator.getAimPP(); - double spdpp = diffRecalculator.getSpdPP(); - double accpp = diffRecalculator.getAccPP(); - diffRecalculator.calculateMaxPP(stat, trackInfo); - double max_pp = diffRecalculator.getTotalPP(); - double max_aimpp = diffRecalculator.getAimPP(); - double max_spdpp = diffRecalculator.getSpdPP(); - double max_accpp = diffRecalculator.getAccPP(); - ppinfo.append(String.format(Locale.ENGLISH, "%.2f*, ", newstar)); - ppinfo.append(String.format(Locale.ENGLISH, "%.2f/%.2fpp (", pp, max_pp)); - ppinfo.append(String.format(Locale.ENGLISH, "Aim: %.0f/%.0f, ", aimpp, max_aimpp)); - ppinfo.append(String.format(Locale.ENGLISH, "Speed: %.0f/%.0f, ", spdpp, max_spdpp)); - ppinfo.append(String.format(Locale.ENGLISH, "Accuracy: %.0f/%.0f)", accpp, max_accpp)); - ppinfo.append("]"); - String ppStr = ppinfo.toString(); - final Text ppInfo = new Text(Utils.toRes(4), Config.getRES_HEIGHT() - playerInfo.getHeight() - Utils.toRes(2), - ResourceManager.getInstance().getFont("smallFont"), ppStr); - ppInfo.setPosition(Utils.toRes(4), Config.getRES_HEIGHT() - ppInfo.getHeight() - Utils.toRes(2)); - final Rectangle bgBottomRect = new Rectangle(0, Config.getRES_HEIGHT() - ppInfo.getHeight() - Utils.toRes(4), ppInfo.getWidth() + Utils.toRes(12), ppInfo.getHeight() + Utils.toRes(4)); - bgBottomRect.setColor(0, 0, 0, 0.5f); - scene.attachChild(bgBottomRect); - scene.attachChild(ppInfo); - } - scene.attachChild(beatmapInfo); - scene.attachChild(mapperInfo); - scene.attachChild(playerInfo); - - //save and upload score - if (track != null && mapMD5 != null) { - if (stat.getModifiedTotalScore() > 0 && OnlineManager.getInstance().isStayOnline() && - OnlineManager.getInstance().isReadyToSend()) { - boolean hasUnrankedMod = SmartIterator.wrap(stat.getMod().iterator()) - .applyFilter(m -> m.unranked).hasNext(); - if (hasUnrankedMod - || Config.isRemoveSliderLock() - || ModMenu.getInstance().isChangeSpeed() - || ModMenu.getInstance().isEnableForceAR()) { - return; - } - - SendingPanel sendingPanel = new SendingPanel(OnlineManager.getInstance().getRank(), - OnlineManager.getInstance().getScore(), OnlineManager.getInstance().getAccuracy()); - sendingPanel.setPosition(Config.getRES_WIDTH() / 2 - 400, Utils.toRes(-300)); - scene.registerTouchArea(sendingPanel.getDismissTouchArea()); - scene.attachChild(sendingPanel); - ScoreLibrary.getInstance().sendScoreOnline(stat, replay, sendingPanel); - } - - ResourceManager.getInstance().getSound("applause").play(); - ScoreLibrary.getInstance().addScore(track.getFilename(), stat, replay); - } - - } - - public Scene getScene() { - return scene; - } - - public void stopMusic() { - if (songService != null) { - songService.stop(); - } - } - - public void replayMusic() { - if (songService != null) { - songService.stop(); -// songService.preLoadWithLoop(game.filePath); - songService.preLoad(track.getBeatmap().getMusic()); - songService.play(); - } - } - - public StatisticV2 getReplayStat() { - return replayStat; - } - - public void setReplayStat(StatisticV2 replayStat) { - this.replayStat = replayStat; - } - - public int getReplayID() { - return replayID; - } - - public void setReplayID(int id) { - this.replayID = id; - } + private final Engine engine; + private final GameScene game; + private final SongMenu menu; + private Scene scene; + private SongService songService; + private StatisticV2 replayStat; + private int replayID = -1; + private TrackInfo track; + + public ScoringScene(final Engine pEngine, final GameScene pGame, + final SongMenu pMenu) { + engine = pEngine; + game = pGame; + menu = pMenu; + } + + public void load(final StatisticV2 stat, final TrackInfo track, + final SongService player, final String replay, final String mapMD5, + final TrackInfo trackToReplay) { + scene = new Scene(); + //music = player; + this.songService = player; + if (replay != null && track == null) { + replayStat = stat; + } + InGameSettingMenu.getInstance().dismiss(); + TextureRegion tex = ResourceManager.getInstance() + .getTextureIfLoaded("::background"); + if (tex == null) { + tex = ResourceManager.getInstance().getTexture("menu-background"); + } + float height = tex.getHeight(); + height *= Config.getRES_WIDTH() / (float) tex.getWidth(); + final Sprite bg = new Sprite(0, (Config.getRES_HEIGHT() - height) / 2, + Config.getRES_WIDTH(), height, tex); + scene.setBackground(new SpriteBackground(bg)); + + final Rectangle bgTopRect = new Rectangle(0, 0, Config.getRES_WIDTH(), Utils.toRes(100)); + bgTopRect.setColor(0, 0, 0, 0.8f); + scene.attachChild(bgTopRect); + + TrackInfo trackInfo = trackToReplay; + if (trackToReplay == null && track != null) { + trackInfo = track; + } + this.track = trackInfo; + final int x = 0, y = 100; + final TextureRegion panelr = ResourceManager.getInstance().getTexture( + "ranking-panel"); + final Sprite panel = new Sprite(x, y, Utils.toRes(panelr.getWidth() * 0.9f), + Utils.toRes(panelr.getHeight() * 0.9f), panelr); + scene.attachChild(panel); + +// final float iconSize = Utils.toRes(64); + + final TextureRegion hit300sr = ResourceManager.getInstance().getTexture("hit300"); + final Sprite hit300s = new Sprite(Utils.toRes(10), Utils.toRes(130), + Utils.toRes(hit300sr.getWidth()), Utils.toRes(hit300sr.getHeight()), hit300sr); + hit300s.setPosition(Utils.toRes(70 - hit300s.getWidth() / 2 + x), Utils.toRes(130 - hit300s.getHeight() / 2 + y)); + scene.attachChild(hit300s); + + final TextureRegion hit100sr = ResourceManager.getInstance().getTexture("hit100"); + final Sprite hit100s = new Sprite(Utils.toRes(10), Utils.toRes(130 + 92), + Utils.toRes(hit100sr.getWidth()), Utils.toRes(hit100sr.getHeight()), hit100sr); + hit100s.setPosition(Utils.toRes(70 - hit100s.getWidth() / 2 + x), Utils.toRes(130 + 92 - hit100s.getHeight() / 2 + y)); + scene.attachChild(hit100s); + + final TextureRegion hit50sr = ResourceManager.getInstance().getTexture("hit50"); + final Sprite hit50s = new Sprite(0, Utils.toRes(120 + 92 * 2), + Utils.toRes(hit50sr.getWidth()), Utils.toRes(hit50sr.getHeight()), hit50sr); + hit50s.setPosition(Utils.toRes(70 - hit50s.getWidth() / 2 + x), Utils.toRes(130 + 92 * 2 - hit50s.getHeight() / 2 + y)); + scene.attachChild(hit50s); + + final TextureRegion hit300ksr = ResourceManager.getInstance().getTexture("hit300g"); + final Sprite hit300ks = new Sprite(Utils.toRes(300), Utils.toRes(100), + Utils.toRes(hit300ksr.getWidth()), Utils.toRes(hit300ksr.getHeight()), hit300ksr); + hit300ks.setPosition(Utils.toRes(340 - hit300ks.getWidth() / 2 + x), Utils.toRes(130 - hit300ks.getHeight() / 2 + y)); + scene.attachChild(hit300ks); + + final TextureRegion hit100ksr = ResourceManager.getInstance().getTexture("hit100k"); + final Sprite hit100ks = new Sprite(Utils.toRes(300), Utils.toRes(120 + 92), + Utils.toRes(hit100ksr.getWidth()), Utils.toRes(hit100ksr.getHeight()), hit100ksr); + hit100ks.setPosition(Utils.toRes(340 - hit100ks.getWidth() / 2 + x), Utils.toRes(130 + 92 - hit100ks.getHeight() / 2 + y)); + scene.attachChild(hit100ks); + + final TextureRegion hit0sr = ResourceManager.getInstance().getTexture("hit0"); + final Sprite hit0s = new Sprite(Utils.toRes(300), Utils.toRes(120 + 92 * 2), + Utils.toRes(hit0sr.getWidth()), Utils.toRes(hit0sr.getHeight()), hit0sr); + hit0s.setPosition(Utils.toRes(340 - hit0s.getWidth() / 2 + x), Utils.toRes(130 + 92 * 2 - hit0s.getHeight() / 2 + y)); + scene.attachChild(hit0s); + + final Sprite rankingText = new Sprite(Utils.toRes(580), 0, + ResourceManager.getInstance().getTexture("ranking-title")); + rankingText.setPosition(Config.getRES_WIDTH() * 5 / 6 - rankingText.getWidth() / 2, 0); + scene.attachChild(rankingText); + + int totalScore = stat.getModifiedTotalScore(); + if (totalScore == 0) { + totalScore = stat.getAutoTotalScore(); + } + String scoreStr = String.valueOf(totalScore); + while (scoreStr.length() < 8) { + scoreStr = '0' + scoreStr; + } + final ScoreNumber scoreNum = new ScoreNumber(Utils.toRes(220 + x), + Utils.toRes(18 + y), scoreStr, 1, false); + scoreNum.attachToScene(scene); + + final ScoreNumber hit300num = new ScoreNumber(Utils.toRes(138 + x), + Utils.toRes(110 + y), stat.getHit300() + "x", 1, + false); + hit300num.attachToScene(scene); + final ScoreNumber hit100num = new ScoreNumber(Utils.toRes(138 + x), + Utils.toRes(110 + 85 + y), stat.getHit100() + "x", + 1, false); + hit100num.attachToScene(scene); + final ScoreNumber hit50num = new ScoreNumber(Utils.toRes(138 + x), + Utils.toRes(110 + 85 * 2 + y), stat.getHit50() + "x", + 1, false); + hit50num.attachToScene(scene); + + final ScoreNumber hit300knum = new ScoreNumber(Utils.toRes(400 + x), + Utils.toRes(110 + y), stat.getHit300k() + "x", 1, + false); + hit300knum.attachToScene(scene); + final ScoreNumber hit100knum = new ScoreNumber(Utils.toRes(400 + x), + Utils.toRes(110 + 85 + y), stat.getHit100k() + "x", + 1, false); + hit100knum.attachToScene(scene); + final ScoreNumber hit0num = new ScoreNumber(Utils.toRes(400 + x), + Utils.toRes(110 + 85 * 2 + y), stat.getMisses() + "x", + 1, false); + hit0num.attachToScene(scene); + + final Sprite maxComboText = new Sprite(Utils.toRes(20 + x), + Utils.toRes(332 + y), ResourceManager.getInstance().getTexture( + "ranking-maxcombo")); + scene.attachChild(maxComboText); + final Sprite accText = new Sprite(Utils.toRes(260 + x), Utils.toRes(332 + y), + ResourceManager.getInstance().getTexture("ranking-accuracy")); + scene.attachChild(accText); + final ScoreNumber maxCombo = new ScoreNumber(Utils.toRes(20 + x), + Utils.toRes(maxComboText.getY() + 38), String.valueOf(stat.getMaxCombo()) + "x", 1, + false); + maxCombo.attachToScene(scene); + final String accStr = String + .format(Locale.ENGLISH, "%2.2f%%", stat.getAccuracy() * 100); + final ScoreNumber accuracy = new ScoreNumber(Utils.toRes(260 + x), + Utils.toRes(accText.getY() + 38), accStr, 1, false); + accuracy.attachToScene(scene); + + final Sprite mark = new Sprite(Utils.toRes(610), 0, ResourceManager + .getInstance().getTexture("ranking-" + stat.getMark())); + if (track != null) { + mark.setAlpha(0); + mark.setScale(1.5f); + mark.registerEntityModifier(new ParallelEntityModifier( + new FadeInModifier(2), new ScaleModifier(2, 2, 1))); + } + mark.setPosition(Config.getRES_WIDTH() * 5 / 6 - mark.getWidth() / 2, 80); + + final Sprite backBtn = new Sprite(Utils.toRes(580), Utils.toRes(490), + ResourceManager.getInstance().getTexture("ranking-back")) { + + + @Override + public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, + final float pTouchAreaLocalX, final float pTouchAreaLocalY) { + if (pSceneTouchEvent.isActionDown()) { + setColor(0.7f, 0.7f, 0.7f); + ResourceManager.getInstance().getSound("menuback").play(); + return true; + } + if (pSceneTouchEvent.isActionUp()) { + ResourceManager.getInstance().getSound("applause").stop(); + GlobalManager.getInstance().getScoring().setReplayID(-1); + menu.updateScore(); +// stopMusic(); + replayMusic(); + engine.setScene(menu.getScene()); + scene = null; + return true; + } + return false; + } + + }; + backBtn.setPosition(Config.getRES_WIDTH() - backBtn.getWidth() - 10, Config.getRES_HEIGHT() - backBtn.getHeight() - 10); + scene.attachChild(backBtn); + + final Sprite retryBtn = new Sprite(Utils.toRes(580), Utils.toRes(400), ResourceManager.getInstance().getTexture("ranking-retry")) { + + @Override + public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, + final float pTouchAreaLocalX, final float pTouchAreaLocalY) { + if (pSceneTouchEvent.isActionDown()) { + setColor(0.7f, 0.7f, 0.7f); + ResourceManager.getInstance().getSound("menuback").play(); + return true; + } + if (pSceneTouchEvent.isActionUp()) { + ResourceManager.getInstance().getSound("applause").stop(); + engine.setScene(menu.getScene()); + game.startGame(null, null); + scene = null; + stopMusic(); + return true; + } + return false; + } + + }; + + final Sprite replayBtn = new Sprite(Utils.toRes(580), Utils.toRes(400), + ResourceManager.getInstance().getTexture("ranking-replay")) { + + ///////////////////////////////////////////////////////////////////////////////// + ///////////////////////////////////////////////////////////////////////////////// + ///////////////////////////////////////////////////////////////////////////////// + ///////////////////////////////////////////////////////////////////////////////// + + @Override + public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, + final float pTouchAreaLocalX, final float pTouchAreaLocalY) { + if (pSceneTouchEvent.isActionDown()) { + setColor(0.7f, 0.7f, 0.7f); + ResourceManager.getInstance().getSound("menuback").play(); + return true; + } + if (pSceneTouchEvent.isActionUp()) { + ResourceManager.getInstance().getSound("applause").stop(); + SongMenu.stopMusicStatic(); + engine.setScene(menu.getScene()); + Replay.oldMod = ModMenu.getInstance().getMod(); + Replay.oldChangeSpeed = ModMenu.getInstance().getChangeSpeed(); + Replay.oldForceAR = ModMenu.getInstance().getForceAR(); + Replay.oldEnableForceAR = ModMenu.getInstance().isEnableForceAR(); + Replay.oldFLFollowDelay = ModMenu.getInstance().getFLfollowDelay(); + + ModMenu.getInstance().setMod(stat.getMod()); + ModMenu.getInstance().setChangeSpeed(stat.getChangeSpeed()); + ModMenu.getInstance().setForceAR(stat.getForceAR()); + ModMenu.getInstance().setEnableForceAR(stat.isEnableForceAR()); + ModMenu.getInstance().setFLfollowDelay(stat.getFLFollowDelay()); +// Replay.mod = stat.getMod(); + game.startGame(trackToReplay, replay); + scene = null; + stopMusic(); + return true; + } + return false; + } + + }; + + if (stat.accuracy == 1 || stat.getMaxCombo() == this.track.getMaxCombo() || stat.isPerfect()) { + final Sprite perfect = new Sprite(0, 0, ResourceManager + .getInstance().getTexture("ranking-perfect")); + perfect.setPosition(0, accuracy.getY() + accuracy.getHeight() + 10); + scene.attachChild(perfect); + } + if (track != null) { + retryBtn.setPosition(Config.getRES_WIDTH() - backBtn.getWidth() - 10, backBtn.getY() - retryBtn.getHeight() - 10); + scene.attachChild(retryBtn); + } else if (replay != null) { + replayBtn.setPosition(Config.getRES_WIDTH() - backBtn.getWidth() - 10, backBtn.getY() - replayBtn.getHeight() - 10); + scene.attachChild(replayBtn); + } + + scene.setTouchAreaBindingEnabled(true); + if (track != null) { + scene.registerTouchArea(retryBtn); + } else if (replay != null) { + scene.registerTouchArea(replayBtn); + } + scene.registerTouchArea(backBtn); + scene.attachChild(mark); + + float modX = mark.getX() - 30; + final float modY = mark.getY() + mark.getHeight() * 2 / 3; + if (stat.getMod().contains(GameMod.MOD_SCOREV2)) { + final Sprite modSprite = new Sprite(modX, modY, ResourceManager + .getInstance().getTexture("selection-mod-scorev2")); + modX -= Utils.toRes(30); + scene.attachChild(modSprite); + } + if (stat.getMod().contains(GameMod.MOD_HARDROCK)) { + final Sprite modSprite = new Sprite(modX, modY, ResourceManager + .getInstance().getTexture("selection-mod-hardrock")); + modX -= Utils.toRes(30); + scene.attachChild(modSprite); + } else if (stat.getMod().contains(GameMod.MOD_EASY)) { + final Sprite modSprite = new Sprite(modX, modY, ResourceManager + .getInstance().getTexture("selection-mod-easy")); + modX -= Utils.toRes(30); + scene.attachChild(modSprite); + } + + if (stat.getMod().contains(GameMod.MOD_HIDDEN)) { + final Sprite modSprite = new Sprite(modX, modY, ResourceManager + .getInstance().getTexture("selection-mod-hidden")); + modX -= Utils.toRes(30); + scene.attachChild(modSprite); + } + + if (stat.getMod().contains(GameMod.MOD_FLASHLIGHT)) { + final Sprite modSprite = new Sprite(modX, modY, ResourceManager + .getInstance().getTexture("selection-mod-flashlight")); + modX -= Utils.toRes(30); + scene.attachChild(modSprite); + } + if (stat.getMod().contains(GameMod.MOD_NOFAIL)) { + final Sprite modSprite = new Sprite(modX, modY, ResourceManager + .getInstance().getTexture("selection-mod-nofail")); + modX -= Utils.toRes(30); + scene.attachChild(modSprite); + } else if (stat.getMod().contains(GameMod.MOD_SUDDENDEATH)) { + final Sprite modSprite = new Sprite(modX, modY, ResourceManager + .getInstance().getTexture("selection-mod-suddendeath")); + modX -= Utils.toRes(30); + scene.attachChild(modSprite); + } else if (stat.getMod().contains(GameMod.MOD_PERFECT)) { + final Sprite modSprite = new Sprite(modX, modY, ResourceManager + .getInstance().getTexture("selection-mod-perfect")); + modX -= Utils.toRes(30); + scene.attachChild(modSprite); + } + if (stat.getMod().contains(GameMod.MOD_AUTO)) { + final Sprite modSprite = new Sprite(modX, modY, ResourceManager + .getInstance().getTexture("selection-mod-autoplay")); + modX -= Utils.toRes(30); + scene.attachChild(modSprite); + } else if (stat.getMod().contains(GameMod.MOD_AUTOPILOT)) { + final Sprite modSprite = new Sprite(modX, modY, ResourceManager + .getInstance().getTexture("selection-mod-relax2")); + modX -= Utils.toRes(30); + scene.attachChild(modSprite); + } else if (stat.getMod().contains(GameMod.MOD_RELAX)) { + final Sprite modSprite = new Sprite(modX, modY, ResourceManager + .getInstance().getTexture("selection-mod-relax")); + modX -= Utils.toRes(30); + scene.attachChild(modSprite); + } + if (stat.getMod().contains(GameMod.MOD_DOUBLETIME)) { + final Sprite modSprite = new Sprite(modX, modY, ResourceManager + .getInstance().getTexture("selection-mod-doubletime")); + modX -= Utils.toRes(30); + scene.attachChild(modSprite); + } else if (stat.getMod().contains(GameMod.MOD_NIGHTCORE)) { + final Sprite modSprite = new Sprite(modX, modY, ResourceManager + .getInstance().getTexture("selection-mod-nightcore")); + modX -= Utils.toRes(30); + scene.attachChild(modSprite); + } else if (stat.getMod().contains(GameMod.MOD_HALFTIME)) { + final Sprite modSprite = new Sprite(modX, modY, ResourceManager + .getInstance().getTexture("selection-mod-halftime")); + modX -= Utils.toRes(30); + scene.attachChild(modSprite); + } + + if (stat.getMod().contains(GameMod.MOD_PRECISE)) { + final Sprite modSprite = new Sprite(modX, modY, ResourceManager + .getInstance().getTexture("selection-mod-precise")); + modX -= Utils.toRes(30); + scene.attachChild(modSprite); + } + //new mods in 1.6.8 + if (stat.getMod().contains(GameMod.MOD_REALLYEASY)) { + final Sprite modSprite = new Sprite(modX, modY, ResourceManager + .getInstance().getTexture("selection-mod-reallyeasy")); + modX -= Utils.toRes(30); + scene.attachChild(modSprite); + } + if (stat.getMod().contains(GameMod.MOD_SMALLCIRCLE)) { + final Sprite modSprite = new Sprite(modX, modY, ResourceManager + .getInstance().getTexture("selection-mod-smallcircle")); + modX -= Utils.toRes(30); + scene.attachChild(modSprite); + } + // + + String infoStr = (trackInfo.getBeatmap().getArtistUnicode() == null || Config.isForceRomanized() ? trackInfo.getBeatmap().getArtist() : trackInfo.getBeatmap().getArtistUnicode()) + " - " + + (trackInfo.getBeatmap().getTitleUnicode() == null || Config.isForceRomanized() ? trackInfo.getBeatmap().getTitle() : trackInfo.getBeatmap().getTitleUnicode()) + " [" + trackInfo.getMode() + "]"; + String mapperStr = "Beatmap by " + trackInfo.getCreator(); + String playerStr = "Played by " + stat.getPlayerName() + " on " + + new java.text.SimpleDateFormat("yyyy/MM/dd HH:mm:ss", Locale.getDefault()).format(new java.util.Date(stat.getTime())); + playerStr += String.format(" %s(%s)", BuildConfig.VERSION_NAME, BuildConfig.BUILD_TYPE); + if (stat.getChangeSpeed() != 1 || + stat.isEnableForceAR() || + stat.getFLFollowDelay() != FlashLightEntity.defaultMoveDelayS && + stat.getMod().contains(GameMod.MOD_FLASHLIGHT)) { + + mapperStr += " ["; + if (stat.getChangeSpeed() != 1){ + mapperStr += String.format(Locale.ENGLISH, "%.2fx,", stat.getChangeSpeed()); + } + if (stat.isEnableForceAR()){ + mapperStr += String.format(Locale.ENGLISH, "AR%.1f,", stat.getForceAR()); + } + if (stat.getFLFollowDelay() != FlashLightEntity.defaultMoveDelayS && stat.getMod().contains(GameMod.MOD_FLASHLIGHT)){ + mapperStr += String.format(Locale.ENGLISH, "FLD%.2f,", stat.getFLFollowDelay()); + } + if (mapperStr.endsWith(",")){ + mapperStr = mapperStr.substring(0, mapperStr.length() - 1); + } + mapperStr += "]"; + } + Debug.i("playedtime " + stat.getTime()); + final Text beatmapInfo = new Text(Utils.toRes(4), Utils.toRes(2), + ResourceManager.getInstance().getFont("font"), infoStr); + final Text mapperInfo = new Text(Utils.toRes(4), beatmapInfo.getY() + beatmapInfo.getHeight() + Utils.toRes(2), + ResourceManager.getInstance().getFont("smallFont"), mapperStr); + final Text playerInfo = new Text(Utils.toRes(4), mapperInfo.getY() + mapperInfo.getHeight() + Utils.toRes(2), + ResourceManager.getInstance().getFont("smallFont"), playerStr); + //calculatePP + if (Config.isDisplayScorePP()){ + StringBuilder ppinfo = new StringBuilder(); + ppinfo.append("["); + DifficultyReCalculator diffRecalculator = new DifficultyReCalculator(); + float newstar = diffRecalculator.recalculateStar( + trackInfo, + diffRecalculator.getCS(stat, trackInfo), + stat.getSpeed() + ); + diffRecalculator.calculatePP(stat, trackInfo); + double pp = diffRecalculator.getTotalPP(); + double aimpp = diffRecalculator.getAimPP(); + double spdpp = diffRecalculator.getSpdPP(); + double accpp = diffRecalculator.getAccPP(); + diffRecalculator.calculateMaxPP(stat, trackInfo); + double max_pp = diffRecalculator.getTotalPP(); + double max_aimpp = diffRecalculator.getAimPP(); + double max_spdpp = diffRecalculator.getSpdPP(); + double max_accpp = diffRecalculator.getAccPP(); + ppinfo.append(String.format(Locale.ENGLISH, "%.2f*, ", newstar)); + ppinfo.append(String.format(Locale.ENGLISH, "%.2f/%.2fpp (", pp, max_pp)); + ppinfo.append(String.format(Locale.ENGLISH, "Aim: %.0f/%.0f, ", aimpp, max_aimpp)); + ppinfo.append(String.format(Locale.ENGLISH, "Speed: %.0f/%.0f, ", spdpp, max_spdpp)); + ppinfo.append(String.format(Locale.ENGLISH, "Accuracy: %.0f/%.0f)", accpp, max_accpp)); + ppinfo.append("]"); + String ppStr = ppinfo.toString(); + final Text ppInfo = new Text(Utils.toRes(4), Config.getRES_HEIGHT() - playerInfo.getHeight() - Utils.toRes(2), + ResourceManager.getInstance().getFont("smallFont"), ppStr); + ppInfo.setPosition(Utils.toRes(4), Config.getRES_HEIGHT() - ppInfo.getHeight() - Utils.toRes(2)); + final Rectangle bgBottomRect = new Rectangle(0, Config.getRES_HEIGHT() - ppInfo.getHeight() - Utils.toRes(4), ppInfo.getWidth() + Utils.toRes(12), ppInfo.getHeight() + Utils.toRes(4)); + bgBottomRect.setColor(0, 0, 0, 0.5f); + scene.attachChild(bgBottomRect); + scene.attachChild(ppInfo); + } + scene.attachChild(beatmapInfo); + scene.attachChild(mapperInfo); + scene.attachChild(playerInfo); + + //save and upload score + if (track != null && mapMD5 != null) { + if (stat.getModifiedTotalScore() > 0 && OnlineManager.getInstance().isStayOnline() && + OnlineManager.getInstance().isReadyToSend()) { + boolean hasUnrankedMod = SmartIterator.wrap(stat.getMod().iterator()) + .applyFilter(m -> m.unranked).hasNext(); + if (hasUnrankedMod + || Config.isRemoveSliderLock() + || ModMenu.getInstance().isChangeSpeed() + || ModMenu.getInstance().isEnableForceAR()) { + return; + } + + SendingPanel sendingPanel = new SendingPanel(OnlineManager.getInstance().getRank(), + OnlineManager.getInstance().getScore(), OnlineManager.getInstance().getAccuracy()); + sendingPanel.setPosition(Config.getRES_WIDTH() / 2 - 400, Utils.toRes(-300)); + scene.registerTouchArea(sendingPanel.getDismissTouchArea()); + scene.attachChild(sendingPanel); + ScoreLibrary.getInstance().sendScoreOnline(stat, replay, sendingPanel); + } + + ResourceManager.getInstance().getSound("applause").play(); + ScoreLibrary.getInstance().addScore(track.getFilename(), stat, replay); + } + + } + + public Scene getScene() { + return scene; + } + + public void stopMusic() { + if (songService != null) { + songService.stop(); + } + } + + public void replayMusic() { + if (songService != null) { + songService.stop(); +// songService.preLoadWithLoop(game.filePath); + songService.preLoad(track.getBeatmap().getMusic()); + songService.play(); + } + } + + public StatisticV2 getReplayStat() { + return replayStat; + } + + public void setReplayStat(StatisticV2 replayStat) { + this.replayStat = replayStat; + } + + public int getReplayID() { + return replayID; + } + + public void setReplayID(int id) { + this.replayID = id; + } } diff --git a/src/ru/nsu/ccfit/zuev/osu/scoring/Statistic.java b/src/ru/nsu/ccfit/zuev/osu/scoring/Statistic.java index 7ddca152..4f73194e 100644 --- a/src/ru/nsu/ccfit/zuev/osu/scoring/Statistic.java +++ b/src/ru/nsu/ccfit/zuev/osu/scoring/Statistic.java @@ -7,276 +7,276 @@ import ru.nsu.ccfit.zuev.osu.game.mods.GameMod; public class Statistic implements Serializable { - private static final long serialVersionUID = 8339570462000129479L; + private static final long serialVersionUID = 8339570462000129479L; - int notes = 0; - int hit300 = 0, hit100 = 0, hit50 = 0; - int hit300k = 0, hit100k = 0; - int misses = 0; - int maxCombo = 0; - int currentCombo = 0; - int totalScore; - int possibleScore = 0; - int realScore = 0; - float hp = 1; - float diffModifier = 1; - EnumSet mod = EnumSet.noneOf(GameMod.class); + int notes = 0; + int hit300 = 0, hit100 = 0, hit50 = 0; + int hit300k = 0, hit100k = 0; + int misses = 0; + int maxCombo = 0; + int currentCombo = 0; + int totalScore; + int possibleScore = 0; + int realScore = 0; + float hp = 1; + float diffModifier = 1; + EnumSet mod = EnumSet.noneOf(GameMod.class); - public float getHp() { - return hp; - } + public float getHp() { + return hp; + } - public void changeHp(final float amount) { - hp += amount; - if (hp < 0) { - hp = 0; - } - if (hp > 1) { - hp = 1; - } - } + public void changeHp(final float amount) { + hp += amount; + if (hp < 0) { + hp = 0; + } + if (hp > 1) { + hp = 1; + } + } - public int getTotalScore() { - return totalScore; - } + public int getTotalScore() { + return totalScore; + } - public int getModifiedTotalScore() { - float mult = 1; - if (mod.contains(GameMod.MOD_AUTO)) { - mult *= 0; - } - if (mod.contains(GameMod.MOD_EASY)) { - mult *= 0.5f; - } - if (mod.contains(GameMod.MOD_NOFAIL)) { - mult *= 0.5f; - } - if (mod.contains(GameMod.MOD_HARDROCK)) { - mult *= 1.06f; - } - if (mod.contains(GameMod.MOD_HIDDEN)) { - mult *= 1.06f; - } - if (mod.contains(GameMod.MOD_FLASHLIGHT)) { - mult *= 1.12f; - } - if (mod.contains(GameMod.MOD_DOUBLETIME)) { - mult *= 1.12f; - } - if (mod.contains(GameMod.MOD_NIGHTCORE)) { - mult *= 1.12f; - } - if (mod.contains(GameMod.MOD_HALFTIME)) { - mult *= 0.3f; - } - if (mod.contains(GameMod.MOD_REALLYEASY)) { - mult *= 0.4f; - } - return (int) (totalScore * mult); - } + public int getModifiedTotalScore() { + float mult = 1; + if (mod.contains(GameMod.MOD_AUTO)) { + mult *= 0; + } + if (mod.contains(GameMod.MOD_EASY)) { + mult *= 0.5f; + } + if (mod.contains(GameMod.MOD_NOFAIL)) { + mult *= 0.5f; + } + if (mod.contains(GameMod.MOD_HARDROCK)) { + mult *= 1.06f; + } + if (mod.contains(GameMod.MOD_HIDDEN)) { + mult *= 1.06f; + } + if (mod.contains(GameMod.MOD_FLASHLIGHT)) { + mult *= 1.12f; + } + if (mod.contains(GameMod.MOD_DOUBLETIME)) { + mult *= 1.12f; + } + if (mod.contains(GameMod.MOD_NIGHTCORE)) { + mult *= 1.12f; + } + if (mod.contains(GameMod.MOD_HALFTIME)) { + mult *= 0.3f; + } + if (mod.contains(GameMod.MOD_REALLYEASY)) { + mult *= 0.4f; + } + return (int) (totalScore * mult); + } - public int getAutoTotalScore() { - float mult = 1; - if (mod.contains(GameMod.MOD_EASY)) { - mult *= 0.5f; - } - if (mod.contains(GameMod.MOD_NOFAIL)) { - mult *= 0.5f; - } - if (mod.contains(GameMod.MOD_HARDROCK)) { - mult *= 1.06f; - } - if (mod.contains(GameMod.MOD_HIDDEN)) { - mult *= 1.06f; - } - if (mod.contains(GameMod.MOD_FLASHLIGHT)) { - mult *= 1.12f; - } - if (mod.contains(GameMod.MOD_DOUBLETIME)) { - mult *= 1.12f; - } - if (mod.contains(GameMod.MOD_NIGHTCORE)) { - mult *= 1.12f; - } - if (mod.contains(GameMod.MOD_HALFTIME)) { - mult *= 0.3f; - } - if (mod.contains(GameMod.MOD_REALLYEASY)) { - mult *= 0.4f; - } - return (int) (totalScore * mult); - } + public int getAutoTotalScore() { + float mult = 1; + if (mod.contains(GameMod.MOD_EASY)) { + mult *= 0.5f; + } + if (mod.contains(GameMod.MOD_NOFAIL)) { + mult *= 0.5f; + } + if (mod.contains(GameMod.MOD_HARDROCK)) { + mult *= 1.06f; + } + if (mod.contains(GameMod.MOD_HIDDEN)) { + mult *= 1.06f; + } + if (mod.contains(GameMod.MOD_FLASHLIGHT)) { + mult *= 1.12f; + } + if (mod.contains(GameMod.MOD_DOUBLETIME)) { + mult *= 1.12f; + } + if (mod.contains(GameMod.MOD_NIGHTCORE)) { + mult *= 1.12f; + } + if (mod.contains(GameMod.MOD_HALFTIME)) { + mult *= 0.3f; + } + if (mod.contains(GameMod.MOD_REALLYEASY)) { + mult *= 0.4f; + } + return (int) (totalScore * mult); + } - public void registerSpinnerHit() { - totalScore += 100; - } + public void registerSpinnerHit() { + totalScore += 100; + } - public void registerHit(final int score, final boolean k, final boolean g) { - if (score == 1000) { - totalScore += score; - return; - } - if (score < 50 && score > 0) { - changeHp(0.05f); - totalScore += score; - currentCombo++; - return; - } - if (score == 0 && k == true) { - changeHp(-(5 + GameHelper.getDrain()) / 100f); - if (currentCombo > maxCombo) { - maxCombo = currentCombo; - } - currentCombo = 0; - return; - } + public void registerHit(final int score, final boolean k, final boolean g) { + if (score == 1000) { + totalScore += score; + return; + } + if (score < 50 && score > 0) { + changeHp(0.05f); + totalScore += score; + currentCombo++; + return; + } + if (score == 0 && k == true) { + changeHp(-(5 + GameHelper.getDrain()) / 100f); + if (currentCombo > maxCombo) { + maxCombo = currentCombo; + } + currentCombo = 0; + return; + } - notes++; - possibleScore += 300; + notes++; + possibleScore += 300; - switch (score) { - case 300: - changeHp(k ? 0.10f : 0.05f); - if (g) { - hit300k++; - } - hit300++; - addScore(300); - realScore += 300; - currentCombo++; - break; - case 100: - changeHp(k ? 0.15f : 0.05f); - if (k) { - hit100k++; - } + switch (score) { + case 300: + changeHp(k ? 0.10f : 0.05f); + if (g) { + hit300k++; + } + hit300++; + addScore(300); + realScore += 300; + currentCombo++; + break; + case 100: + changeHp(k ? 0.15f : 0.05f); + if (k) { + hit100k++; + } - hit100++; - addScore(100); - realScore += 100; - currentCombo++; - break; - case 50: - changeHp(0.05f); - hit50++; - addScore(50); - realScore += 50; - currentCombo++; - break; - default: - changeHp(-(5 + GameHelper.getDrain()) / 100f); - misses++; - if (currentCombo > maxCombo) { - maxCombo = currentCombo; - } - currentCombo = 0; - break; - } - } + hit100++; + addScore(100); + realScore += 100; + currentCombo++; + break; + case 50: + changeHp(0.05f); + hit50++; + addScore(50); + realScore += 50; + currentCombo++; + break; + default: + changeHp(-(5 + GameHelper.getDrain()) / 100f); + misses++; + if (currentCombo > maxCombo) { + maxCombo = currentCombo; + } + currentCombo = 0; + break; + } + } - public float getAccuracy() { - if (possibleScore == 0) { - return 0; - } - return realScore / (float) possibleScore; - } + public float getAccuracy() { + if (possibleScore == 0) { + return 0; + } + return realScore / (float) possibleScore; + } - public void addScore(final int amount) { - totalScore += amount + (amount * currentCombo * diffModifier) / 25; - } + public void addScore(final int amount) { + totalScore += amount + (amount * currentCombo * diffModifier) / 25; + } - public String getMark() { - boolean isH = false; - forcycle: - for (final GameMod m : mod) { - switch (m) { - case MOD_HIDDEN: - isH = true; - break forcycle; - default: - break; - } - } + public String getMark() { + boolean isH = false; + forcycle: + for (final GameMod m : mod) { + switch (m) { + case MOD_HIDDEN: + isH = true; + break forcycle; + default: + break; + } + } - if (hit100 == 0 && hit100k == 0 && hit50 == 0 && misses == 0) { - if (isH) { - return "XH"; - } - return "X"; - } - if ((hit300) / (float) notes > 0.9f && misses == 0 - && hit50 / (float) notes < 0.01f) { - if (isH) { - return "SH"; - } - return "S"; - } - if ((hit300) / (float) notes > 0.8f && misses == 0 - || (hit300) / (float) notes > 0.9f) { - return "A"; - } - if ((hit300) / (float) notes > 0.7f && misses == 0 - || (hit300) / (float) notes > 0.8f) { - return "B"; - } - if ((hit300) / (float) notes > 0.6f) { - return "C"; - } - return "D"; - } + if (hit100 == 0 && hit100k == 0 && hit50 == 0 && misses == 0) { + if (isH) { + return "XH"; + } + return "X"; + } + if ((hit300) / (float) notes > 0.9f && misses == 0 + && hit50 / (float) notes < 0.01f) { + if (isH) { + return "SH"; + } + return "S"; + } + if ((hit300) / (float) notes > 0.8f && misses == 0 + || (hit300) / (float) notes > 0.9f) { + return "A"; + } + if ((hit300) / (float) notes > 0.7f && misses == 0 + || (hit300) / (float) notes > 0.8f) { + return "B"; + } + if ((hit300) / (float) notes > 0.6f) { + return "C"; + } + return "D"; + } - public int getMaxCombo() { - if (currentCombo > maxCombo) { - maxCombo = currentCombo; - } - return maxCombo; - } + public int getMaxCombo() { + if (currentCombo > maxCombo) { + maxCombo = currentCombo; + } + return maxCombo; + } - public int getNotes() { - return notes; - } + public int getNotes() { + return notes; + } - public int getHit300() { - return hit300; - } + public int getHit300() { + return hit300; + } - public int getHit100() { - return hit100; - } + public int getHit100() { + return hit100; + } - public int getHit50() { - return hit50; - } + public int getHit50() { + return hit50; + } - public int getHit300k() { - return hit300k; - } + public int getHit300k() { + return hit300k; + } - public int getHit100k() { - return hit100k; - } + public int getHit100k() { + return hit100k; + } - public int getMisses() { - return misses; - } + public int getMisses() { + return misses; + } - public int getCombo() { - return currentCombo; - } + public int getCombo() { + return currentCombo; + } - public EnumSet getMod() { - return mod; - } + public EnumSet getMod() { + return mod; + } - public void setMod(final EnumSet mod) { - this.mod = mod.clone(); - } + public void setMod(final EnumSet mod) { + this.mod = mod.clone(); + } - public float getDiffModifier() { - return diffModifier; - } + public float getDiffModifier() { + return diffModifier; + } - public void setDiffModifier(final float diffModifier) { - this.diffModifier = diffModifier; - } + public void setDiffModifier(final float diffModifier) { + this.diffModifier = diffModifier; + } } diff --git a/src/ru/nsu/ccfit/zuev/osu/scoring/StatisticV2.java b/src/ru/nsu/ccfit/zuev/osu/scoring/StatisticV2.java index c01dbc27..24815568 100644 --- a/src/ru/nsu/ccfit/zuev/osu/scoring/StatisticV2.java +++ b/src/ru/nsu/ccfit/zuev/osu/scoring/StatisticV2.java @@ -14,712 +14,712 @@ import ru.nsu.ccfit.zuev.osu.online.OnlineManager; public class StatisticV2 implements Serializable { - private static final long serialVersionUID = 8339570462000129479L; - int hit300 = 0, hit100 = 0, hit50 = 0; - int hit300k = 0, hit100k = 0; - int misses = 0; - int maxCombo = 0; - float accuracy = -1; - long time = 0; - private Random random; - private int notes = 0; - private boolean perfect = true; - private int currentCombo = 0; - private int scoreHash = 0; - private int totalScore; - private int possibleScore = 0; - private int realScore = 0; - private float hp = 1; - private float diffModifier = 1; - private EnumSet mod = EnumSet.noneOf(GameMod.class); - private String playerName = ""; - private String fileName = ""; - private String replayName = ""; - private int forcedScore = -1; - private String mark = null; - private float changeSpeed = 1.0f; - private float forceAR = 9.0f; - private boolean enableForceAR = false; - private final int MAX_SCORE = 1000000; - private final float ACC_PORTION = 0.3f; - private final float COMBO_PORTION = 0.7f; - private int maxObjectsCount = 0; - private int maxHighestCombo = 0; - private int bonusScore = 0; - private float flFollowDelay = FlashLightEntity.defaultMoveDelayS; - - public StatisticV2() { - random = new Random(); - playerName = null; - if (Config.isStayOnline()) { - playerName = OnlineManager.getInstance().getUsername(); - if (playerName == null || playerName.length() == 0) - playerName = Config.getOnlineUsername(); - } - - if (playerName == null || playerName.length() == 0) - playerName = Config.getLocalUsername(); - } - - public StatisticV2(final Statistic stat) { - notes = stat.notes; - hit300 = stat.hit300; - hit100 = stat.hit100; - hit50 = stat.hit50; - hit300k = stat.hit300k; - hit100k = stat.hit100k; - misses = stat.misses; - maxCombo = stat.maxCombo; - currentCombo = stat.currentCombo; - totalScore = stat.totalScore; - possibleScore = stat.possibleScore; - realScore = stat.realScore; - hp = stat.hp; - diffModifier = stat.diffModifier; - mod = stat.mod.clone(); - setPlayerName(Config.getLocalUsername()); - } - - public StatisticV2(final String[] params) { - playerName = ""; - if (params.length < 6) return; - - setModFromString(params[0]); - setForcedScore(Integer.parseInt(params[1])); - maxCombo = Integer.parseInt(params[2]); - mark = params[3]; - hit300k = Integer.parseInt(params[4]); - hit300 = Integer.parseInt(params[5]); - hit100k = Integer.parseInt(params[6]); - hit100 = Integer.parseInt(params[7]); - hit50 = Integer.parseInt(params[8]); - misses = Integer.parseInt(params[9]); - accuracy = Integer.parseInt(params[10]) / 100000f; - if (params.length >= 12) { - time = Long.parseLong(params[11]); - } - if (params.length >= 13) { - perfect = Integer.parseInt(params[12]) != 0; - } - if (params.length >= 14) { - playerName = params[13]; - } - } - - public float getHp() { - return hp; - } - - public void changeHp(final float amount) { - hp += amount; - if (hp < 0) { - hp = 0; - } - if (hp > 1) { - hp = 1; - } - } - - public int getTotalScore() { - return totalScore; - } - - public int getModifiedTotalScore() { - if (forcedScore > 0) - return forcedScore; - float mult = 1; - for (GameMod m : mod) { - mult *= m.scoreMultiplier; - } - if (changeSpeed != 1.0f){ - mult *= getSpeedChangeScoreMultiplier(); - } - return (int) (totalScore * mult); - } - - public int getAutoTotalScore() { - float mult = 1; - for (GameMod m : mod) { - if (m.unranked) { - continue; - } - mult *= m.scoreMultiplier; - } - if (changeSpeed != 1.0f){ - mult *= getSpeedChangeScoreMultiplier(); - } - return (int) (totalScore * mult); - } - - public void registerSpinnerHit() { - addScore(100, false); - } - - public void registerHit(final int score, final boolean k, final boolean g) { - if (score == 1000) { - addScore(score, false); - return; - } - if (score < 50 && score > 0) { - changeHp(0.05f); - addScore(score, false); - currentCombo++; - return; - } - if (score == 0 && k == true) { - changeHp(-(5 + GameHelper.getDrain()) / 100f); - if (currentCombo > maxCombo) { - maxCombo = currentCombo; - } - currentCombo = 0; - return; - } - - notes++; - possibleScore += 300; - - switch (score) { - case 300: - changeHp(k ? 0.10f : 0.05f); - if (g) { - hit300k++; - } - hit300++; - addScore(300, true); - realScore += 300; - currentCombo++; - break; - case 100: - changeHp(k ? 0.15f : 0.05f); - if (k) { - hit100k++; - } - hit100++; - addScore(100, true); - realScore += 100; - currentCombo++; - break; - case 50: - changeHp(0.05f); - hit50++; - addScore(50, true); - realScore += 50; - currentCombo++; - break; - default: - changeHp(-(5 + GameHelper.getDrain()) / 100f); - misses++; - perfect = false; - if (currentCombo > maxCombo) { - maxCombo = currentCombo; - } - currentCombo = 0; - break; - } - } - - public float getAccuracy() { - if (accuracy >= 0) - return accuracy; - if (possibleScore == 0) { - return 0; - } - return realScore / (float) possibleScore; - } - - public void setAccuracy(float accuracy) { - this.accuracy = accuracy; - } - - private void addScore(final int amount, final boolean combo) { - if (!isScoreValid()) { - scoreHash = random.nextInt(1313) | 3455; - return; - } - //如果使用scorev2 - if (mod.contains(GameMod.MOD_SCOREV2)){ - if (amount == 1000) { - bonusScore += amount; - } - float percentage = (float)(notes) / maxObjectsCount; - //get real maxcb - int maxcb = getMaxCombo(); - if (currentCombo == maxcb)maxcb++; - //get real acc - float acc = 0; - if (possibleScore > 0){ - switch (amount) { - case 300: - acc = (realScore + 300) / (float) possibleScore; - break; - case 100: - acc = (realScore + 100) / (float) possibleScore; - break; - case 50: - acc = (realScore + 50) / (float) possibleScore; - break; - default: - acc = realScore / (float) possibleScore; - break; - } - } - totalScore = (int)(MAX_SCORE * (ACC_PORTION * Math.pow(acc , 10) * percentage - + COMBO_PORTION * maxcb / maxHighestCombo) + bonusScore); - } else{ - //如果分数溢出或分数满了 - if (totalScore + (amount * currentCombo * diffModifier) / 25 + amount < 0 || totalScore == Integer.MAX_VALUE){ - totalScore = Integer.MAX_VALUE; - } - else{ - totalScore += amount; - if (combo) { - totalScore += (amount * currentCombo * diffModifier) / 25; - } - } - } - scoreHash = SecurityUtils.getHigh16Bits(totalScore); - } - - public String getMark() { - if (mark != null) - return mark; - boolean isH = false; - forcycle: - for (final GameMod m : mod) { - switch (m) { - case MOD_HIDDEN: - isH = true; - break forcycle; - case MOD_FLASHLIGHT: - isH = true; - break forcycle; - default: - break; - } - } - - if (hit100 == 0 && hit50 == 0 && misses == 0) { - if (isH) { - return "XH"; - } - return "X"; - } - if ((hit300) / (float) notes > 0.9f && misses == 0 - && hit50 / (float) notes < 0.01f) { - if (isH) { - return "SH"; - } - return "S"; - } - if ((hit300) / (float) notes > 0.8f && misses == 0 - || (hit300) / (float) notes > 0.9f) { - return "A"; - } - if ((hit300) / (float) notes > 0.7f && misses == 0 - || (hit300) / (float) notes > 0.8f) { - return "B"; - } - if ((hit300) / (float) notes > 0.6f) { - return "C"; - } - return "D"; - } - - public void setMark(String mark) { - this.mark = mark; - } - - public int getMaxCombo() { - if (currentCombo > maxCombo) { - maxCombo = currentCombo; - } - return maxCombo; - } - - public void setMaxCombo(int maxCombo) { - this.maxCombo = maxCombo; - } - - public int getNotes() { - return notes; - } - - public int getHit300() { - return hit300; - } - - public void setHit300(int hit300) { - this.hit300 = hit300; - } - - public int getHit100() { - return hit100; - } - - public void setHit100(int hit100) { - this.hit100 = hit100; - } - - public int getHit50() { - return hit50; - } - - public void setHit50(int hit50) { - this.hit50 = hit50; - } - - public int getHit300k() { - return hit300k; - } - - public void setHit300k(int hit300k) { - this.hit300k = hit300k; - } - - public int getHit100k() { - return hit100k; - } - - public void setHit100k(int hit100k) { - this.hit100k = hit100k; - } - - public int getMisses() { - return misses; - } - - public void setMisses(int misses) { - this.misses = misses; - } - - public boolean isPerfect() { - return perfect; - } - - public void setPerfect(boolean perfect) { - this.perfect = perfect; - } - - public int getCombo() { - return currentCombo; - } - - public long getTime() { - return time; - } - - public void setTime(long time) { - this.time = time; - } - - public EnumSet getMod() { - return mod; - } - - public void setMod(final EnumSet mod) { - this.mod = mod.clone(); - } - - public float getDiffModifier() { - return diffModifier; - } - - public void setDiffModifier(final float diffModifier) { - this.diffModifier = diffModifier; - } - - public String getPlayerName() { - return playerName; - } - - public void setPlayerName(final String playerName) { - this.playerName = playerName; - } - - public String getModString() { - String s = ""; - - if (mod.contains(GameMod.MOD_AUTO)) { - s += "a"; - } - if (mod.contains(GameMod.MOD_RELAX)) { - s += "x"; - } - if (mod.contains(GameMod.MOD_AUTOPILOT)) { - s += "p"; - } - if (mod.contains(GameMod.MOD_EASY)) { - s += "e"; - } - if (mod.contains(GameMod.MOD_NOFAIL)) { - s += "n"; - } - if (mod.contains(GameMod.MOD_HARDROCK)) { - s += "r"; - } - if (mod.contains(GameMod.MOD_HIDDEN)) { - s += "h"; - } - if (mod.contains(GameMod.MOD_FLASHLIGHT)) { - s += "i"; - } - if (mod.contains(GameMod.MOD_DOUBLETIME)) { - s += "d"; - } - if (mod.contains(GameMod.MOD_NIGHTCORE)) { - s += "c"; - } - if (mod.contains(GameMod.MOD_HALFTIME)) { - s += "t"; - } - if (mod.contains(GameMod.MOD_PRECISE)) { - s += "s"; - } - if (mod.contains(GameMod.MOD_SMALLCIRCLE)) { - s += "m"; - } - if (mod.contains(GameMod.MOD_REALLYEASY)) { - s += "l"; - } - if (mod.contains(GameMod.MOD_PERFECT)) { - s += "f"; - } - if (mod.contains(GameMod.MOD_SUDDENDEATH)) { - s += "u"; - } - if (mod.contains(GameMod.MOD_SCOREV2)) { - s += "v"; - } - s += "|"; - s += getExtraModString(); - return s; - } - - public void setModFromString(String s) { - String[] strMod = s.split("\\|", 2); - mod = EnumSet.noneOf(GameMod.class); - for (int i = 0; i < strMod[0].length(); i++) { - switch (strMod[0].charAt(i)) { - case 'a': - mod.add(GameMod.MOD_AUTO); - break; - case 'x': - mod.add(GameMod.MOD_RELAX); - break; - case 'p': - mod.add(GameMod.MOD_AUTOPILOT); - break; - case 'e': - mod.add(GameMod.MOD_EASY); - break; - case 'n': - mod.add(GameMod.MOD_NOFAIL); - break; - case 'r': - mod.add(GameMod.MOD_HARDROCK); - break; - case 'h': - mod.add(GameMod.MOD_HIDDEN); - break; - case 'i': - mod.add(GameMod.MOD_FLASHLIGHT); - break; - case 'd': - mod.add(GameMod.MOD_DOUBLETIME); - break; - case 'c': - mod.add(GameMod.MOD_NIGHTCORE); - break; - case 't': - mod.add(GameMod.MOD_HALFTIME); - break; - case 's': - mod.add(GameMod.MOD_PRECISE); - break; - case 'm': - mod.add(GameMod.MOD_SMALLCIRCLE); - break; - case 'l': - mod.add(GameMod.MOD_REALLYEASY); - break; - case 'u': - mod.add(GameMod.MOD_SUDDENDEATH); - break; - case 'f': - mod.add(GameMod.MOD_PERFECT); - break; - case 'v': - mod.add(GameMod.MOD_SCOREV2); - break; - } - } - if (strMod.length > 1) - setExtraModFromString(strMod[1]); - } - - public String getReplayName() { - return replayName; - } - - public void setReplayName(String replayName) { - this.replayName = replayName; - } - - public void setForcedScore(int forcedScore) { - this.forcedScore = forcedScore; - totalScore = forcedScore; - } - - public String getFileName() { - return fileName; - } - - public void setFileName(String fileName) { - this.fileName = fileName; - } - - public final boolean isScoreValid() { - return SecurityUtils.getHigh16Bits(totalScore) == scoreHash; - } - - public String compile() { - StringBuilder builder = new StringBuilder(); - String mstring = getModString(); - if (mstring.length() == 0) - mstring = "-"; - builder.append(mstring); - builder.append(' '); - builder.append(getModifiedTotalScore()); - builder.append(' '); - builder.append(getMaxCombo()); - builder.append(' '); - builder.append(getMark()); - builder.append(' '); - builder.append(getHit300k()); - builder.append(' '); - builder.append(getHit300()); - builder.append(' '); - builder.append(getHit100k()); - builder.append(' '); - builder.append(getHit100()); - builder.append(' '); - builder.append(getHit50()); - builder.append(' '); - builder.append(getMisses()); - builder.append(' '); - builder.append((int) (getAccuracy() * 100000f)); - builder.append(' '); - builder.append(getTime()); - builder.append(' '); - builder.append(isPerfect() ? 1 : 0); - builder.append(' '); - builder.append(getPlayerName()); - return builder.toString(); - } - - public void setMaxObjectsCount(int count){ - maxObjectsCount = count; - } - public void setMaxHighestCombo(int count){ - maxHighestCombo = count; - } - - public float getChangeSpeed(){ - return changeSpeed; - } - - public void setChangeSpeed(float speed){ - changeSpeed = speed; - } - - public float getForceAR(){ - return forceAR; - } - - public void setForceAR(float ar){ - forceAR = ar; - } - - public boolean isEnableForceAR(){ - return enableForceAR; - } - - public void setFLFollowDelay(float delay) { - flFollowDelay = delay; - } - - public float getFLFollowDelay() { - return flFollowDelay; - } - - public void setEnableForceAR(boolean t){ - enableForceAR = t; - } - - public float getSpeed(){ - float speed = changeSpeed; - if (mod.contains(GameMod.MOD_DOUBLETIME) || mod.contains(GameMod.MOD_NIGHTCORE)){ - speed *= 1.5f; - } - if (mod.contains(GameMod.MOD_HALFTIME)){ - speed *= 0.75f; - } - return speed; - } - - public static float getSpeedChangeScoreMultiplier(float speed, EnumSet mod) { - float multi = speed; - if (multi > 1){ - multi = 1.0f + (multi - 1.0f) * 0.24f; - } else if (multi < 1){ - multi = (float) Math.pow(0.3, (1.0 - multi) * 4); - } else if (multi == 1){ - return 1f; - } - if (mod.contains(GameMod.MOD_DOUBLETIME) || mod.contains(GameMod.MOD_NIGHTCORE)){ - multi /= 1.12f; - } - if (mod.contains(GameMod.MOD_HALFTIME)){ - multi /= 0.3f; - } - return multi; - } - - private float getSpeedChangeScoreMultiplier(){ - return getSpeedChangeScoreMultiplier(getSpeed(), mod); - } - - public String getExtraModString() { - StringBuilder builder = new StringBuilder(); - if (changeSpeed != 1){ - builder.append(String.format(Locale.ENGLISH, "x%.2f|", changeSpeed)); - } - if (enableForceAR){ - builder.append(String.format(Locale.ENGLISH, "AR%.1f|", forceAR)); - } - if (flFollowDelay != FlashLightEntity.defaultMoveDelayS) { - builder.append(String.format(Locale.ENGLISH, "FLD%.2f|", flFollowDelay)); - } - if (builder.length() > 0){ - builder.delete(builder.length() - 1, builder.length()); - } - - return builder.toString(); - } - - public void setExtraModFromString(String s) { - for (String str: s.split("\\|")){ - if (str.startsWith("x") && str.length() == 5){ - changeSpeed = Float.parseFloat(str.substring(1)); - continue; - } - if (str.startsWith("AR")){ - enableForceAR = true; - forceAR = Float.parseFloat(str.substring(2)); - } - if (str.startsWith("FLD")) { - flFollowDelay = Float.parseFloat(str.substring(3)); - } - } - } + private static final long serialVersionUID = 8339570462000129479L; + int hit300 = 0, hit100 = 0, hit50 = 0; + int hit300k = 0, hit100k = 0; + int misses = 0; + int maxCombo = 0; + float accuracy = -1; + long time = 0; + private Random random; + private int notes = 0; + private boolean perfect = true; + private int currentCombo = 0; + private int scoreHash = 0; + private int totalScore; + private int possibleScore = 0; + private int realScore = 0; + private float hp = 1; + private float diffModifier = 1; + private EnumSet mod = EnumSet.noneOf(GameMod.class); + private String playerName = ""; + private String fileName = ""; + private String replayName = ""; + private int forcedScore = -1; + private String mark = null; + private float changeSpeed = 1.0f; + private float forceAR = 9.0f; + private boolean enableForceAR = false; + private final int MAX_SCORE = 1000000; + private final float ACC_PORTION = 0.3f; + private final float COMBO_PORTION = 0.7f; + private int maxObjectsCount = 0; + private int maxHighestCombo = 0; + private int bonusScore = 0; + private float flFollowDelay = FlashLightEntity.defaultMoveDelayS; + + public StatisticV2() { + random = new Random(); + playerName = null; + if (Config.isStayOnline()) { + playerName = OnlineManager.getInstance().getUsername(); + if (playerName == null || playerName.length() == 0) + playerName = Config.getOnlineUsername(); + } + + if (playerName == null || playerName.length() == 0) + playerName = Config.getLocalUsername(); + } + + public StatisticV2(final Statistic stat) { + notes = stat.notes; + hit300 = stat.hit300; + hit100 = stat.hit100; + hit50 = stat.hit50; + hit300k = stat.hit300k; + hit100k = stat.hit100k; + misses = stat.misses; + maxCombo = stat.maxCombo; + currentCombo = stat.currentCombo; + totalScore = stat.totalScore; + possibleScore = stat.possibleScore; + realScore = stat.realScore; + hp = stat.hp; + diffModifier = stat.diffModifier; + mod = stat.mod.clone(); + setPlayerName(Config.getLocalUsername()); + } + + public StatisticV2(final String[] params) { + playerName = ""; + if (params.length < 6) return; + + setModFromString(params[0]); + setForcedScore(Integer.parseInt(params[1])); + maxCombo = Integer.parseInt(params[2]); + mark = params[3]; + hit300k = Integer.parseInt(params[4]); + hit300 = Integer.parseInt(params[5]); + hit100k = Integer.parseInt(params[6]); + hit100 = Integer.parseInt(params[7]); + hit50 = Integer.parseInt(params[8]); + misses = Integer.parseInt(params[9]); + accuracy = Integer.parseInt(params[10]) / 100000f; + if (params.length >= 12) { + time = Long.parseLong(params[11]); + } + if (params.length >= 13) { + perfect = Integer.parseInt(params[12]) != 0; + } + if (params.length >= 14) { + playerName = params[13]; + } + } + + public float getHp() { + return hp; + } + + public void changeHp(final float amount) { + hp += amount; + if (hp < 0) { + hp = 0; + } + if (hp > 1) { + hp = 1; + } + } + + public int getTotalScore() { + return totalScore; + } + + public int getModifiedTotalScore() { + if (forcedScore > 0) + return forcedScore; + float mult = 1; + for (GameMod m : mod) { + mult *= m.scoreMultiplier; + } + if (changeSpeed != 1.0f){ + mult *= getSpeedChangeScoreMultiplier(); + } + return (int) (totalScore * mult); + } + + public int getAutoTotalScore() { + float mult = 1; + for (GameMod m : mod) { + if (m.unranked) { + continue; + } + mult *= m.scoreMultiplier; + } + if (changeSpeed != 1.0f){ + mult *= getSpeedChangeScoreMultiplier(); + } + return (int) (totalScore * mult); + } + + public void registerSpinnerHit() { + addScore(100, false); + } + + public void registerHit(final int score, final boolean k, final boolean g) { + if (score == 1000) { + addScore(score, false); + return; + } + if (score < 50 && score > 0) { + changeHp(0.05f); + addScore(score, false); + currentCombo++; + return; + } + if (score == 0 && k == true) { + changeHp(-(5 + GameHelper.getDrain()) / 100f); + if (currentCombo > maxCombo) { + maxCombo = currentCombo; + } + currentCombo = 0; + return; + } + + notes++; + possibleScore += 300; + + switch (score) { + case 300: + changeHp(k ? 0.10f : 0.05f); + if (g) { + hit300k++; + } + hit300++; + addScore(300, true); + realScore += 300; + currentCombo++; + break; + case 100: + changeHp(k ? 0.15f : 0.05f); + if (k) { + hit100k++; + } + hit100++; + addScore(100, true); + realScore += 100; + currentCombo++; + break; + case 50: + changeHp(0.05f); + hit50++; + addScore(50, true); + realScore += 50; + currentCombo++; + break; + default: + changeHp(-(5 + GameHelper.getDrain()) / 100f); + misses++; + perfect = false; + if (currentCombo > maxCombo) { + maxCombo = currentCombo; + } + currentCombo = 0; + break; + } + } + + public float getAccuracy() { + if (accuracy >= 0) + return accuracy; + if (possibleScore == 0) { + return 0; + } + return realScore / (float) possibleScore; + } + + public void setAccuracy(float accuracy) { + this.accuracy = accuracy; + } + + private void addScore(final int amount, final boolean combo) { + if (!isScoreValid()) { + scoreHash = random.nextInt(1313) | 3455; + return; + } + //如果使用scorev2 + if (mod.contains(GameMod.MOD_SCOREV2)){ + if (amount == 1000) { + bonusScore += amount; + } + float percentage = (float)(notes) / maxObjectsCount; + //get real maxcb + int maxcb = getMaxCombo(); + if (currentCombo == maxcb)maxcb++; + //get real acc + float acc = 0; + if (possibleScore > 0){ + switch (amount) { + case 300: + acc = (realScore + 300) / (float) possibleScore; + break; + case 100: + acc = (realScore + 100) / (float) possibleScore; + break; + case 50: + acc = (realScore + 50) / (float) possibleScore; + break; + default: + acc = realScore / (float) possibleScore; + break; + } + } + totalScore = (int)(MAX_SCORE * (ACC_PORTION * Math.pow(acc , 10) * percentage + + COMBO_PORTION * maxcb / maxHighestCombo) + bonusScore); + } else{ + //如果分数溢出或分数满了 + if (totalScore + (amount * currentCombo * diffModifier) / 25 + amount < 0 || totalScore == Integer.MAX_VALUE){ + totalScore = Integer.MAX_VALUE; + } + else{ + totalScore += amount; + if (combo) { + totalScore += (amount * currentCombo * diffModifier) / 25; + } + } + } + scoreHash = SecurityUtils.getHigh16Bits(totalScore); + } + + public String getMark() { + if (mark != null) + return mark; + boolean isH = false; + forcycle: + for (final GameMod m : mod) { + switch (m) { + case MOD_HIDDEN: + isH = true; + break forcycle; + case MOD_FLASHLIGHT: + isH = true; + break forcycle; + default: + break; + } + } + + if (hit100 == 0 && hit50 == 0 && misses == 0) { + if (isH) { + return "XH"; + } + return "X"; + } + if ((hit300) / (float) notes > 0.9f && misses == 0 + && hit50 / (float) notes < 0.01f) { + if (isH) { + return "SH"; + } + return "S"; + } + if ((hit300) / (float) notes > 0.8f && misses == 0 + || (hit300) / (float) notes > 0.9f) { + return "A"; + } + if ((hit300) / (float) notes > 0.7f && misses == 0 + || (hit300) / (float) notes > 0.8f) { + return "B"; + } + if ((hit300) / (float) notes > 0.6f) { + return "C"; + } + return "D"; + } + + public void setMark(String mark) { + this.mark = mark; + } + + public int getMaxCombo() { + if (currentCombo > maxCombo) { + maxCombo = currentCombo; + } + return maxCombo; + } + + public void setMaxCombo(int maxCombo) { + this.maxCombo = maxCombo; + } + + public int getNotes() { + return notes; + } + + public int getHit300() { + return hit300; + } + + public void setHit300(int hit300) { + this.hit300 = hit300; + } + + public int getHit100() { + return hit100; + } + + public void setHit100(int hit100) { + this.hit100 = hit100; + } + + public int getHit50() { + return hit50; + } + + public void setHit50(int hit50) { + this.hit50 = hit50; + } + + public int getHit300k() { + return hit300k; + } + + public void setHit300k(int hit300k) { + this.hit300k = hit300k; + } + + public int getHit100k() { + return hit100k; + } + + public void setHit100k(int hit100k) { + this.hit100k = hit100k; + } + + public int getMisses() { + return misses; + } + + public void setMisses(int misses) { + this.misses = misses; + } + + public boolean isPerfect() { + return perfect; + } + + public void setPerfect(boolean perfect) { + this.perfect = perfect; + } + + public int getCombo() { + return currentCombo; + } + + public long getTime() { + return time; + } + + public void setTime(long time) { + this.time = time; + } + + public EnumSet getMod() { + return mod; + } + + public void setMod(final EnumSet mod) { + this.mod = mod.clone(); + } + + public float getDiffModifier() { + return diffModifier; + } + + public void setDiffModifier(final float diffModifier) { + this.diffModifier = diffModifier; + } + + public String getPlayerName() { + return playerName; + } + + public void setPlayerName(final String playerName) { + this.playerName = playerName; + } + + public String getModString() { + String s = ""; + + if (mod.contains(GameMod.MOD_AUTO)) { + s += "a"; + } + if (mod.contains(GameMod.MOD_RELAX)) { + s += "x"; + } + if (mod.contains(GameMod.MOD_AUTOPILOT)) { + s += "p"; + } + if (mod.contains(GameMod.MOD_EASY)) { + s += "e"; + } + if (mod.contains(GameMod.MOD_NOFAIL)) { + s += "n"; + } + if (mod.contains(GameMod.MOD_HARDROCK)) { + s += "r"; + } + if (mod.contains(GameMod.MOD_HIDDEN)) { + s += "h"; + } + if (mod.contains(GameMod.MOD_FLASHLIGHT)) { + s += "i"; + } + if (mod.contains(GameMod.MOD_DOUBLETIME)) { + s += "d"; + } + if (mod.contains(GameMod.MOD_NIGHTCORE)) { + s += "c"; + } + if (mod.contains(GameMod.MOD_HALFTIME)) { + s += "t"; + } + if (mod.contains(GameMod.MOD_PRECISE)) { + s += "s"; + } + if (mod.contains(GameMod.MOD_SMALLCIRCLE)) { + s += "m"; + } + if (mod.contains(GameMod.MOD_REALLYEASY)) { + s += "l"; + } + if (mod.contains(GameMod.MOD_PERFECT)) { + s += "f"; + } + if (mod.contains(GameMod.MOD_SUDDENDEATH)) { + s += "u"; + } + if (mod.contains(GameMod.MOD_SCOREV2)) { + s += "v"; + } + s += "|"; + s += getExtraModString(); + return s; + } + + public void setModFromString(String s) { + String[] strMod = s.split("\\|", 2); + mod = EnumSet.noneOf(GameMod.class); + for (int i = 0; i < strMod[0].length(); i++) { + switch (strMod[0].charAt(i)) { + case 'a': + mod.add(GameMod.MOD_AUTO); + break; + case 'x': + mod.add(GameMod.MOD_RELAX); + break; + case 'p': + mod.add(GameMod.MOD_AUTOPILOT); + break; + case 'e': + mod.add(GameMod.MOD_EASY); + break; + case 'n': + mod.add(GameMod.MOD_NOFAIL); + break; + case 'r': + mod.add(GameMod.MOD_HARDROCK); + break; + case 'h': + mod.add(GameMod.MOD_HIDDEN); + break; + case 'i': + mod.add(GameMod.MOD_FLASHLIGHT); + break; + case 'd': + mod.add(GameMod.MOD_DOUBLETIME); + break; + case 'c': + mod.add(GameMod.MOD_NIGHTCORE); + break; + case 't': + mod.add(GameMod.MOD_HALFTIME); + break; + case 's': + mod.add(GameMod.MOD_PRECISE); + break; + case 'm': + mod.add(GameMod.MOD_SMALLCIRCLE); + break; + case 'l': + mod.add(GameMod.MOD_REALLYEASY); + break; + case 'u': + mod.add(GameMod.MOD_SUDDENDEATH); + break; + case 'f': + mod.add(GameMod.MOD_PERFECT); + break; + case 'v': + mod.add(GameMod.MOD_SCOREV2); + break; + } + } + if (strMod.length > 1) + setExtraModFromString(strMod[1]); + } + + public String getReplayName() { + return replayName; + } + + public void setReplayName(String replayName) { + this.replayName = replayName; + } + + public void setForcedScore(int forcedScore) { + this.forcedScore = forcedScore; + totalScore = forcedScore; + } + + public String getFileName() { + return fileName; + } + + public void setFileName(String fileName) { + this.fileName = fileName; + } + + public final boolean isScoreValid() { + return SecurityUtils.getHigh16Bits(totalScore) == scoreHash; + } + + public String compile() { + StringBuilder builder = new StringBuilder(); + String mstring = getModString(); + if (mstring.length() == 0) + mstring = "-"; + builder.append(mstring); + builder.append(' '); + builder.append(getModifiedTotalScore()); + builder.append(' '); + builder.append(getMaxCombo()); + builder.append(' '); + builder.append(getMark()); + builder.append(' '); + builder.append(getHit300k()); + builder.append(' '); + builder.append(getHit300()); + builder.append(' '); + builder.append(getHit100k()); + builder.append(' '); + builder.append(getHit100()); + builder.append(' '); + builder.append(getHit50()); + builder.append(' '); + builder.append(getMisses()); + builder.append(' '); + builder.append((int) (getAccuracy() * 100000f)); + builder.append(' '); + builder.append(getTime()); + builder.append(' '); + builder.append(isPerfect() ? 1 : 0); + builder.append(' '); + builder.append(getPlayerName()); + return builder.toString(); + } + + public void setMaxObjectsCount(int count){ + maxObjectsCount = count; + } + public void setMaxHighestCombo(int count){ + maxHighestCombo = count; + } + + public float getChangeSpeed(){ + return changeSpeed; + } + + public void setChangeSpeed(float speed){ + changeSpeed = speed; + } + + public float getForceAR(){ + return forceAR; + } + + public void setForceAR(float ar){ + forceAR = ar; + } + + public boolean isEnableForceAR(){ + return enableForceAR; + } + + public void setFLFollowDelay(float delay) { + flFollowDelay = delay; + } + + public float getFLFollowDelay() { + return flFollowDelay; + } + + public void setEnableForceAR(boolean t){ + enableForceAR = t; + } + + public float getSpeed(){ + float speed = changeSpeed; + if (mod.contains(GameMod.MOD_DOUBLETIME) || mod.contains(GameMod.MOD_NIGHTCORE)){ + speed *= 1.5f; + } + if (mod.contains(GameMod.MOD_HALFTIME)){ + speed *= 0.75f; + } + return speed; + } + + public static float getSpeedChangeScoreMultiplier(float speed, EnumSet mod) { + float multi = speed; + if (multi > 1){ + multi = 1.0f + (multi - 1.0f) * 0.24f; + } else if (multi < 1){ + multi = (float) Math.pow(0.3, (1.0 - multi) * 4); + } else if (multi == 1){ + return 1f; + } + if (mod.contains(GameMod.MOD_DOUBLETIME) || mod.contains(GameMod.MOD_NIGHTCORE)){ + multi /= 1.12f; + } + if (mod.contains(GameMod.MOD_HALFTIME)){ + multi /= 0.3f; + } + return multi; + } + + private float getSpeedChangeScoreMultiplier(){ + return getSpeedChangeScoreMultiplier(getSpeed(), mod); + } + + public String getExtraModString() { + StringBuilder builder = new StringBuilder(); + if (changeSpeed != 1){ + builder.append(String.format(Locale.ENGLISH, "x%.2f|", changeSpeed)); + } + if (enableForceAR){ + builder.append(String.format(Locale.ENGLISH, "AR%.1f|", forceAR)); + } + if (flFollowDelay != FlashLightEntity.defaultMoveDelayS) { + builder.append(String.format(Locale.ENGLISH, "FLD%.2f|", flFollowDelay)); + } + if (builder.length() > 0){ + builder.delete(builder.length() - 1, builder.length()); + } + + return builder.toString(); + } + + public void setExtraModFromString(String s) { + for (String str: s.split("\\|")){ + if (str.startsWith("x") && str.length() == 5){ + changeSpeed = Float.parseFloat(str.substring(1)); + continue; + } + if (str.startsWith("AR")){ + enableForceAR = true; + forceAR = Float.parseFloat(str.substring(2)); + } + if (str.startsWith("FLD")) { + flFollowDelay = Float.parseFloat(str.substring(3)); + } + } + } } diff --git a/src/ru/nsu/ccfit/zuev/osu/storyboard/Command.java b/src/ru/nsu/ccfit/zuev/osu/storyboard/Command.java index 9f3e1708..ab3fd97c 100644 --- a/src/ru/nsu/ccfit/zuev/osu/storyboard/Command.java +++ b/src/ru/nsu/ccfit/zuev/osu/storyboard/Command.java @@ -5,13 +5,13 @@ */ public enum Command { - F, M, MX, MY, S, V, R, C, P, L, T, NONE; + F, M, MX, MY, S, V, R, C, P, L, T, NONE; - public static Command getType(String type) { - try { - return valueOf(type.toUpperCase()); - } catch (Exception e) { - return NONE; - } - } + public static Command getType(String type) { + try { + return valueOf(type.toUpperCase()); + } catch (Exception e) { + return NONE; + } + } } diff --git a/src/ru/nsu/ccfit/zuev/osu/storyboard/HitSound.java b/src/ru/nsu/ccfit/zuev/osu/storyboard/HitSound.java index 8a60469f..9718972b 100644 --- a/src/ru/nsu/ccfit/zuev/osu/storyboard/HitSound.java +++ b/src/ru/nsu/ccfit/zuev/osu/storyboard/HitSound.java @@ -5,6 +5,6 @@ */ public class HitSound { - public int soundType;//Normal 0, Whistle 2, Finish 4, Clap 8 - public long time; + public int soundType;//Normal 0, Whistle 2, Finish 4, Clap 8 + public long time; } diff --git a/src/ru/nsu/ccfit/zuev/osu/storyboard/OsbParser.java b/src/ru/nsu/ccfit/zuev/osu/storyboard/OsbParser.java index c52fe20f..21f0a441 100644 --- a/src/ru/nsu/ccfit/zuev/osu/storyboard/OsbParser.java +++ b/src/ru/nsu/ccfit/zuev/osu/storyboard/OsbParser.java @@ -21,498 +21,498 @@ * Created by dgsrz on 16/9/16. */ public class OsbParser { - public static OsbParser instance = new OsbParser(); - private LinkedList sprites = new LinkedList(); - private ArrayList timingPoints = new ArrayList(); - private ArrayList hitSounds = new ArrayList(); - private HashMap variablesMap = new HashMap(); - private String line; - private String[] info; - private float sliderMultiplier; - private int ZIndex = -900; - - public ArrayList getTimingPoints() { - return timingPoints; - } - - public HashMap getVariablesMap() { - return variablesMap; - } - - public LinkedList getSprites() { - return sprites; - } - - public ArrayList getHitSounds() { - return hitSounds; - } - - public void parse(String path) throws IOException { - File osuFile = new File(path); - loadBeatmap(osuFile); - File[] files = FileUtils.listFiles(osuFile.getParentFile(), ".osb"); - if (files.length > 0) { - BufferedSource source = Okio.buffer(Okio.source(files[0])); - - Pattern pattern; - Matcher matcher; - String line; - while ((line = source.readUtf8Line()) != null) { - pattern = Pattern.compile("\\[(\\w+)]"); - matcher = pattern.matcher(line.trim()); - - if (matcher.find()) { - String title = matcher.group(1); - if (title.equals("Events")) { - parseObjects(source); - } else if (title.equals("Variables")) { - parseVariables(source); - } - } - } - source.close(); - } - Collections.sort(hitSounds, new Comparator() { - @Override - public int compare(HitSound lhs, HitSound rhs) { - return (int) (lhs.time - rhs.time); - } - }); - Collections.sort(sprites, new Comparator() { - @Override - public int compare(OsuSprite lhs, OsuSprite rhs) { - return (int) (lhs.spriteStartTime - rhs.spriteStartTime); - } - }); - } - - private void parseObjects(BufferedSource source) throws IOException { - line = source.readUtf8Line(); - while (line != null) { - if (line.equals("")) { - break; - } - - if (line.startsWith("Sprite")) { - for (String s : variablesMap.keySet()) { - if (line.contains(s)) { - line = line.replace(s, variablesMap.get(s)); - } - } - info = line.split(","); - int layer = 0; - if (info[1].equals("Background")) { - layer = 0; - } else if (info[1].equals("Fail")) { - layer = 1; - } else if (info[1].equals("Pass")) { - layer = 2; - } else if (info[1].equals("Foreground")) { - layer = 3; - } - OsuSprite.Origin origin = OsuSprite.Origin.valueOf(info[2]); - String filePath = info[3]; - filePath = filePath.replaceAll("\"", ""); - float x = Float.parseFloat(info[4]); - float y = Float.parseFloat(info[5]); - ArrayList events = parseEvents(source); - OsuSprite sprite = new OsuSprite(x, y, layer, origin, filePath, events, ZIndex++); - sprite.setDebugLine(line); - sprites.add(sprite); - } else if (line.startsWith("Animation")) { - for (String s : variablesMap.keySet()) { - if (line.contains(s)) { - line = line.replace(s, variablesMap.get(s)); - } - } - info = line.split(","); - int layer = 0; - if (info[1].equals("Background")) { - layer = 0; - } else if (info[1].equals("Fail")) { - layer = 1; - } else if (info[1].equals("Pass")) { - layer = 2; - } else if (info[1].equals("Foreground")) { - layer = 3; - } - OsuSprite.Origin origin = OsuSprite.Origin.valueOf(info[2]); - String filePath = info[3]; - filePath = filePath.replaceAll("\"", ""); - float x = Float.parseFloat(info[4]); - float y = Float.parseFloat(info[5]); - int count = Integer.parseInt(info[6]); - int delay = Integer.parseInt(info[7]); - String loopType = "LoopForever"; - if (info.length == 9) { - loopType = info[8]; - } - ArrayList events = parseEvents(source); - sprites.add(new OsuSprite(x, y, layer, origin, filePath, events, ZIndex++, count, delay, loopType)); - } else { - line = source.readUtf8Line(); - } - - } - } - - private ArrayList parseEvents(BufferedSource source) throws IOException { - ArrayList eventList = new ArrayList(); - line = source.readUtf8Line(); - if (line.startsWith("_")) { - line = line.replaceAll("_", " "); - } - while (line != null && line.startsWith(" ")) { - line = line.trim(); - if (line.length() == 0) break; - for (String s : variablesMap.keySet()) { - if (line.contains(s)) { - line = line.replace(s, variablesMap.get(s)); - } - } - OsuEvent currentOsuEvent = new OsuEvent(); - info = line.split(","); - Command command = Command.valueOf(info[0]); - currentOsuEvent.command = command; - if (command == Command.L) { - currentOsuEvent.startTime = Long.parseLong(info[1]); - currentOsuEvent.loopCount = Integer.parseInt(info[2]); - currentOsuEvent.subEvents = parseSubEvents(source); - if (currentOsuEvent.subEvents.size() > 0) {//real start time - currentOsuEvent.startTime = currentOsuEvent.subEvents.get(0).startTime + currentOsuEvent.startTime; - } - } else if (command == Command.T) { - if (info.length > 2) { - currentOsuEvent.startTime = Long.parseLong(info[2]); - currentOsuEvent.endTime = Long.parseLong(info[3]); - } else { - currentOsuEvent.startTime = 0; - currentOsuEvent.endTime = 999999999; - } - currentOsuEvent.triggerType = info[1]; - int soundType = -1; - if (currentOsuEvent.triggerType.equals("HitSoundWhistle")) { - soundType = 2; - } else if (currentOsuEvent.triggerType.equals("HitSoundFinish")) { - soundType = 4; - } else if (currentOsuEvent.triggerType.equals("HitSoundClap")) { - soundType = 8; - } - currentOsuEvent.subEvents = parseSubEvents(source); - for (HitSound hitSound : hitSounds) {//real start time - if (hitSound.time >= currentOsuEvent.startTime && (hitSound.soundType & soundType) == soundType) { - currentOsuEvent.startTime = hitSound.time; - break; - } - } - } else { - currentOsuEvent.ease = Integer.parseInt(info[1]); - currentOsuEvent.startTime = Long.parseLong(info[2]); - currentOsuEvent.endTime = info[3].equals("") ? currentOsuEvent.startTime + 1 : Long.parseLong(info[3]); - float[] params = null; - switch (command) { - case F: - case MX: - case MY: - case S: - case R: - params = new float[2]; - params[0] = Float.parseFloat(info[4]); - if (info.length == 5) { - params[1] = Float.parseFloat(info[4]); - } else {//TODO more than two params - params[1] = Float.parseFloat(info[5]); - } - break; - - case M: - case V: - params = new float[4]; - params[0] = Float.parseFloat(info[4]); - params[1] = Float.parseFloat(info[5]); - if (info.length == 6) { - params[2] = Float.parseFloat(info[4]); - params[3] = Float.parseFloat(info[5]); - } else { - params[2] = Float.parseFloat(info[6]); - params[3] = Float.parseFloat(info[7]); - } - break; - case C: - params = new float[6]; - params[0] = Float.parseFloat(info[4]); - params[1] = Float.parseFloat(info[5]); - params[2] = Float.parseFloat(info[6]); - if (info.length == 7) { - params[3] = Float.parseFloat(info[4]); - params[4] = Float.parseFloat(info[5]); - params[5] = Float.parseFloat(info[6]); - } else { - params[3] = Float.parseFloat(info[7]); - params[4] = Float.parseFloat(info[8]); - params[5] = Float.parseFloat(info[9]); - } - break; - case P: - currentOsuEvent.P = info[4]; - break; - } - currentOsuEvent.params = params; - line = source.readUtf8Line(); - if (line.startsWith("_")) { - line = line.replaceAll("_", " "); - } - for (String s : variablesMap.keySet()) { - if (line.contains(s)) { - line = line.replace(s, variablesMap.get(s)); - } - } - } - if (currentOsuEvent.triggerType == null || (!currentOsuEvent.triggerType.equals("Passing") && !currentOsuEvent.triggerType.equals("Failing"))) { - eventList.add(currentOsuEvent); - } - } - return eventList; - } - - private ArrayList parseSubEvents(BufferedSource source) throws IOException { - ArrayList subOsuEventList = new ArrayList(); - while ((line = source.readUtf8Line()) != null && (line.startsWith(" ") || line.startsWith("__"))) { - line = line.replaceAll("_", " ").trim(); - for (String s : variablesMap.keySet()) { - if (line.contains(s)) { - line = line.replace(s, variablesMap.get(s)); - } - } - OsuEvent subEvent = new OsuEvent(); - info = line.split(","); - Command subCommand = Command.valueOf(info[0]); - subEvent.command = subCommand; - subEvent.ease = Integer.parseInt(info[1]); - subEvent.startTime = Long.parseLong(info[2]); - subEvent.endTime = info[3].equals("") ? subEvent.startTime + 1 : Long.parseLong(info[3]); - float[] params = null; - switch (subCommand) { - case F: - case MX: - case MY: - case S: - case R: - params = new float[2]; - params[0] = Float.parseFloat(info[4]); - if (info.length == 5) { - params[1] = Float.parseFloat(info[4]); - } else {//TODO more than two params - params[1] = Float.parseFloat(info[5]); - } - break; - - case M: - case V: - params = new float[4]; - params[0] = Float.parseFloat(info[4]); - params[1] = Float.parseFloat(info[5]); - if (info.length == 6) { - params[2] = Float.parseFloat(info[4]); - params[3] = Float.parseFloat(info[5]); - } else { - params[2] = Float.parseFloat(info[6]); - params[3] = Float.parseFloat(info[7]); - } - break; - case C: - params = new float[6]; - params[0] = Float.parseFloat(info[4]); - params[1] = Float.parseFloat(info[5]); - params[2] = Float.parseFloat(info[6]); - if (info.length == 7) { - params[3] = Float.parseFloat(info[4]); - params[4] = Float.parseFloat(info[5]); - params[5] = Float.parseFloat(info[6]); - } else { - params[3] = Float.parseFloat(info[7]); - params[4] = Float.parseFloat(info[8]); - params[5] = Float.parseFloat(info[9]); - } - break; - case P: - subEvent.P = info[4]; - break; - case T: - case L: - parseSubEvents(source); - break; - } - subEvent.params = params; - subOsuEventList.add(subEvent); - } - return subOsuEventList; - } - - - public void loadBeatmap(File file) throws IOException { - BufferedSource source = Okio.buffer(Okio.source(file)); - - String header = source.readUtf8Line().trim(); - Pattern pattern; - Matcher matcher; -// Pattern pattern = Pattern.compile("osu file format v(\\d+)"); -// Matcher matcher = pattern.matcher(header); -// if (!matcher.find()) -// { -// Log.e("BeatmapParsing", "Incompatible beatmap version."); -// } -// mVersion = Integer.parseInt(matcher.group(1)); - - String line; - while ((line = source.readUtf8Line()) != null) { - pattern = Pattern.compile("\\[(\\w+)]"); - matcher = pattern.matcher(line.trim()); - - if (matcher.find()) { - String title = matcher.group(1); - if (title.equals("General")) { - parseGeneral(source); - } else if (title.equals("Difficulty")) { - parseDifficulty(source); - } else if (title.equals("Events")) { - parseEvent(source); - } else if (title.equals("TimingPoints")) { - parseTimingPoints(source); - } else if (title.equals("HitObjects")) { - parseHitObject(source); - } - } - } - source.close(); - } - - private void parseGeneral(BufferedSource source) throws IOException { - String line; - while ((line = source.readUtf8Line()) != null) { - line = line.trim(); - if (line.equals("")) return; - String[] values = line.split(":"); - String key = values[0]; - String value = values[1].trim(); - - if (key.equals("AudioFilename")) { - StoryBoardTestActivity.activity.mAudioFileName = value; - break; - } - } - } - - private void parseEvent(BufferedSource source) throws IOException { - String line; - String info[]; - while ((line = source.readUtf8Line()) != null) { - line = line.trim(); - if (line.equals("")) return; - - if (line.contains(",")) { - info = line.split(","); - Pattern pattern = Pattern.compile("[^\"]+\\.(jpg|png)", Pattern.CASE_INSENSITIVE); - Matcher matcher = pattern.matcher(line); - if (info[0].equals("0") && matcher.find()) { - StoryBoardTestActivity.activity.mBackground = matcher.group(0); - parseObjects(source); - break; - } - } - } - } - - private void parseVariables(BufferedSource source) throws IOException { - String line; - while ((line = source.readUtf8Line()) != null) { - line = line.trim(); - if (line.equals("")) return; - String[] values = line.split("="); - String key = values[0]; - String value = values[1].trim(); - variablesMap.put(key, value); - } - } - - private void parseDifficulty(BufferedSource source) throws IOException { - String line; - while ((line = source.readUtf8Line()) != null) { - line = line.trim(); - if (line.equals("")) return; - String[] values = line.split(":"); - if (values[0].equals("SliderMultiplier")) { - sliderMultiplier = Float.parseFloat(values[1]); - } - } - } - - private void parseTimingPoints(BufferedSource source) throws IOException { - String line; - float lastLengthPerBeat = -100; - while ((line = source.readUtf8Line()) != null) { - line = line.trim(); - if (line.equals("")) return; - String[] values = line.split(","); - TimingPoint timingPoint = new TimingPoint(); - timingPoint.startTime = (long) Float.parseFloat(values[0]); - timingPoint.lengthPerBeat = Float.parseFloat(values[1]); - if (timingPoint.lengthPerBeat < 0) { - timingPoint.lengthPerBeat = lastLengthPerBeat; - } else { - lastLengthPerBeat = timingPoint.lengthPerBeat; - } - timingPoints.add(timingPoint); - } - } - - private void parseHitObject(BufferedSource source) throws IOException { - String line; - while ((line = source.readUtf8Line()) != null) { - line = line.trim(); - if (line.equals("")) return; - String[] values = line.split(","); - int objectType = Integer.parseInt(values[3]); - if ((objectType & 1) == 1) {//circle - HitSound hitSound = new HitSound(); - hitSound.time = Long.parseLong(values[2]); - hitSound.soundType = Integer.parseInt(values[4]); - hitSounds.add(hitSound); - } else if ((objectType & 2) == 2) {//slider - long startTime = Long.parseLong(values[2]); - int count = Integer.parseInt(values[6]) + 1; - float sliderLength = Float.parseFloat(values[7]); - String[] soundTypes = null; - if (values.length > 8) { - soundTypes = values[8].split("\\|"); - } - TimingPoint currentPoint = timingPoints.get(0); - for (TimingPoint timingPoint : timingPoints) { - if (startTime > timingPoint.startTime) { - currentPoint = timingPoint; - break; - } - } - float sliderLengthTime = currentPoint.lengthPerBeat * (sliderMultiplier / sliderLength) / 100; - for (int i = 0; i < count; i++) { - HitSound hitSound = new HitSound(); - if (values.length > 8) { - assert soundTypes != null; - hitSound.soundType = Integer.parseInt(soundTypes[i]); - } else { - hitSound.soundType = Integer.parseInt(values[4]); - } - - hitSound.time = (long) (startTime + sliderLengthTime * i); - if (hitSound.soundType > 0) - hitSounds.add(hitSound); - } - } else if ((objectType & 8) == 8) {//spinner - HitSound hitSound = new HitSound(); - hitSound.time = Long.parseLong(values[5]); - hitSound.soundType = Integer.parseInt(values[4]); - hitSounds.add(hitSound); - } - } - } + public static OsbParser instance = new OsbParser(); + private LinkedList sprites = new LinkedList(); + private ArrayList timingPoints = new ArrayList(); + private ArrayList hitSounds = new ArrayList(); + private HashMap variablesMap = new HashMap(); + private String line; + private String[] info; + private float sliderMultiplier; + private int ZIndex = -900; + + public ArrayList getTimingPoints() { + return timingPoints; + } + + public HashMap getVariablesMap() { + return variablesMap; + } + + public LinkedList getSprites() { + return sprites; + } + + public ArrayList getHitSounds() { + return hitSounds; + } + + public void parse(String path) throws IOException { + File osuFile = new File(path); + loadBeatmap(osuFile); + File[] files = FileUtils.listFiles(osuFile.getParentFile(), ".osb"); + if (files.length > 0) { + BufferedSource source = Okio.buffer(Okio.source(files[0])); + + Pattern pattern; + Matcher matcher; + String line; + while ((line = source.readUtf8Line()) != null) { + pattern = Pattern.compile("\\[(\\w+)]"); + matcher = pattern.matcher(line.trim()); + + if (matcher.find()) { + String title = matcher.group(1); + if (title.equals("Events")) { + parseObjects(source); + } else if (title.equals("Variables")) { + parseVariables(source); + } + } + } + source.close(); + } + Collections.sort(hitSounds, new Comparator() { + @Override + public int compare(HitSound lhs, HitSound rhs) { + return (int) (lhs.time - rhs.time); + } + }); + Collections.sort(sprites, new Comparator() { + @Override + public int compare(OsuSprite lhs, OsuSprite rhs) { + return (int) (lhs.spriteStartTime - rhs.spriteStartTime); + } + }); + } + + private void parseObjects(BufferedSource source) throws IOException { + line = source.readUtf8Line(); + while (line != null) { + if (line.equals("")) { + break; + } + + if (line.startsWith("Sprite")) { + for (String s : variablesMap.keySet()) { + if (line.contains(s)) { + line = line.replace(s, variablesMap.get(s)); + } + } + info = line.split(","); + int layer = 0; + if (info[1].equals("Background")) { + layer = 0; + } else if (info[1].equals("Fail")) { + layer = 1; + } else if (info[1].equals("Pass")) { + layer = 2; + } else if (info[1].equals("Foreground")) { + layer = 3; + } + OsuSprite.Origin origin = OsuSprite.Origin.valueOf(info[2]); + String filePath = info[3]; + filePath = filePath.replaceAll("\"", ""); + float x = Float.parseFloat(info[4]); + float y = Float.parseFloat(info[5]); + ArrayList events = parseEvents(source); + OsuSprite sprite = new OsuSprite(x, y, layer, origin, filePath, events, ZIndex++); + sprite.setDebugLine(line); + sprites.add(sprite); + } else if (line.startsWith("Animation")) { + for (String s : variablesMap.keySet()) { + if (line.contains(s)) { + line = line.replace(s, variablesMap.get(s)); + } + } + info = line.split(","); + int layer = 0; + if (info[1].equals("Background")) { + layer = 0; + } else if (info[1].equals("Fail")) { + layer = 1; + } else if (info[1].equals("Pass")) { + layer = 2; + } else if (info[1].equals("Foreground")) { + layer = 3; + } + OsuSprite.Origin origin = OsuSprite.Origin.valueOf(info[2]); + String filePath = info[3]; + filePath = filePath.replaceAll("\"", ""); + float x = Float.parseFloat(info[4]); + float y = Float.parseFloat(info[5]); + int count = Integer.parseInt(info[6]); + int delay = Integer.parseInt(info[7]); + String loopType = "LoopForever"; + if (info.length == 9) { + loopType = info[8]; + } + ArrayList events = parseEvents(source); + sprites.add(new OsuSprite(x, y, layer, origin, filePath, events, ZIndex++, count, delay, loopType)); + } else { + line = source.readUtf8Line(); + } + + } + } + + private ArrayList parseEvents(BufferedSource source) throws IOException { + ArrayList eventList = new ArrayList(); + line = source.readUtf8Line(); + if (line.startsWith("_")) { + line = line.replaceAll("_", " "); + } + while (line != null && line.startsWith(" ")) { + line = line.trim(); + if (line.length() == 0) break; + for (String s : variablesMap.keySet()) { + if (line.contains(s)) { + line = line.replace(s, variablesMap.get(s)); + } + } + OsuEvent currentOsuEvent = new OsuEvent(); + info = line.split(","); + Command command = Command.valueOf(info[0]); + currentOsuEvent.command = command; + if (command == Command.L) { + currentOsuEvent.startTime = Long.parseLong(info[1]); + currentOsuEvent.loopCount = Integer.parseInt(info[2]); + currentOsuEvent.subEvents = parseSubEvents(source); + if (currentOsuEvent.subEvents.size() > 0) {//real start time + currentOsuEvent.startTime = currentOsuEvent.subEvents.get(0).startTime + currentOsuEvent.startTime; + } + } else if (command == Command.T) { + if (info.length > 2) { + currentOsuEvent.startTime = Long.parseLong(info[2]); + currentOsuEvent.endTime = Long.parseLong(info[3]); + } else { + currentOsuEvent.startTime = 0; + currentOsuEvent.endTime = 999999999; + } + currentOsuEvent.triggerType = info[1]; + int soundType = -1; + if (currentOsuEvent.triggerType.equals("HitSoundWhistle")) { + soundType = 2; + } else if (currentOsuEvent.triggerType.equals("HitSoundFinish")) { + soundType = 4; + } else if (currentOsuEvent.triggerType.equals("HitSoundClap")) { + soundType = 8; + } + currentOsuEvent.subEvents = parseSubEvents(source); + for (HitSound hitSound : hitSounds) {//real start time + if (hitSound.time >= currentOsuEvent.startTime && (hitSound.soundType & soundType) == soundType) { + currentOsuEvent.startTime = hitSound.time; + break; + } + } + } else { + currentOsuEvent.ease = Integer.parseInt(info[1]); + currentOsuEvent.startTime = Long.parseLong(info[2]); + currentOsuEvent.endTime = info[3].equals("") ? currentOsuEvent.startTime + 1 : Long.parseLong(info[3]); + float[] params = null; + switch (command) { + case F: + case MX: + case MY: + case S: + case R: + params = new float[2]; + params[0] = Float.parseFloat(info[4]); + if (info.length == 5) { + params[1] = Float.parseFloat(info[4]); + } else {//TODO more than two params + params[1] = Float.parseFloat(info[5]); + } + break; + + case M: + case V: + params = new float[4]; + params[0] = Float.parseFloat(info[4]); + params[1] = Float.parseFloat(info[5]); + if (info.length == 6) { + params[2] = Float.parseFloat(info[4]); + params[3] = Float.parseFloat(info[5]); + } else { + params[2] = Float.parseFloat(info[6]); + params[3] = Float.parseFloat(info[7]); + } + break; + case C: + params = new float[6]; + params[0] = Float.parseFloat(info[4]); + params[1] = Float.parseFloat(info[5]); + params[2] = Float.parseFloat(info[6]); + if (info.length == 7) { + params[3] = Float.parseFloat(info[4]); + params[4] = Float.parseFloat(info[5]); + params[5] = Float.parseFloat(info[6]); + } else { + params[3] = Float.parseFloat(info[7]); + params[4] = Float.parseFloat(info[8]); + params[5] = Float.parseFloat(info[9]); + } + break; + case P: + currentOsuEvent.P = info[4]; + break; + } + currentOsuEvent.params = params; + line = source.readUtf8Line(); + if (line.startsWith("_")) { + line = line.replaceAll("_", " "); + } + for (String s : variablesMap.keySet()) { + if (line.contains(s)) { + line = line.replace(s, variablesMap.get(s)); + } + } + } + if (currentOsuEvent.triggerType == null || (!currentOsuEvent.triggerType.equals("Passing") && !currentOsuEvent.triggerType.equals("Failing"))) { + eventList.add(currentOsuEvent); + } + } + return eventList; + } + + private ArrayList parseSubEvents(BufferedSource source) throws IOException { + ArrayList subOsuEventList = new ArrayList(); + while ((line = source.readUtf8Line()) != null && (line.startsWith(" ") || line.startsWith("__"))) { + line = line.replaceAll("_", " ").trim(); + for (String s : variablesMap.keySet()) { + if (line.contains(s)) { + line = line.replace(s, variablesMap.get(s)); + } + } + OsuEvent subEvent = new OsuEvent(); + info = line.split(","); + Command subCommand = Command.valueOf(info[0]); + subEvent.command = subCommand; + subEvent.ease = Integer.parseInt(info[1]); + subEvent.startTime = Long.parseLong(info[2]); + subEvent.endTime = info[3].equals("") ? subEvent.startTime + 1 : Long.parseLong(info[3]); + float[] params = null; + switch (subCommand) { + case F: + case MX: + case MY: + case S: + case R: + params = new float[2]; + params[0] = Float.parseFloat(info[4]); + if (info.length == 5) { + params[1] = Float.parseFloat(info[4]); + } else {//TODO more than two params + params[1] = Float.parseFloat(info[5]); + } + break; + + case M: + case V: + params = new float[4]; + params[0] = Float.parseFloat(info[4]); + params[1] = Float.parseFloat(info[5]); + if (info.length == 6) { + params[2] = Float.parseFloat(info[4]); + params[3] = Float.parseFloat(info[5]); + } else { + params[2] = Float.parseFloat(info[6]); + params[3] = Float.parseFloat(info[7]); + } + break; + case C: + params = new float[6]; + params[0] = Float.parseFloat(info[4]); + params[1] = Float.parseFloat(info[5]); + params[2] = Float.parseFloat(info[6]); + if (info.length == 7) { + params[3] = Float.parseFloat(info[4]); + params[4] = Float.parseFloat(info[5]); + params[5] = Float.parseFloat(info[6]); + } else { + params[3] = Float.parseFloat(info[7]); + params[4] = Float.parseFloat(info[8]); + params[5] = Float.parseFloat(info[9]); + } + break; + case P: + subEvent.P = info[4]; + break; + case T: + case L: + parseSubEvents(source); + break; + } + subEvent.params = params; + subOsuEventList.add(subEvent); + } + return subOsuEventList; + } + + + public void loadBeatmap(File file) throws IOException { + BufferedSource source = Okio.buffer(Okio.source(file)); + + String header = source.readUtf8Line().trim(); + Pattern pattern; + Matcher matcher; +// Pattern pattern = Pattern.compile("osu file format v(\\d+)"); +// Matcher matcher = pattern.matcher(header); +// if (!matcher.find()) +// { +// Log.e("BeatmapParsing", "Incompatible beatmap version."); +// } +// mVersion = Integer.parseInt(matcher.group(1)); + + String line; + while ((line = source.readUtf8Line()) != null) { + pattern = Pattern.compile("\\[(\\w+)]"); + matcher = pattern.matcher(line.trim()); + + if (matcher.find()) { + String title = matcher.group(1); + if (title.equals("General")) { + parseGeneral(source); + } else if (title.equals("Difficulty")) { + parseDifficulty(source); + } else if (title.equals("Events")) { + parseEvent(source); + } else if (title.equals("TimingPoints")) { + parseTimingPoints(source); + } else if (title.equals("HitObjects")) { + parseHitObject(source); + } + } + } + source.close(); + } + + private void parseGeneral(BufferedSource source) throws IOException { + String line; + while ((line = source.readUtf8Line()) != null) { + line = line.trim(); + if (line.equals("")) return; + String[] values = line.split(":"); + String key = values[0]; + String value = values[1].trim(); + + if (key.equals("AudioFilename")) { + StoryBoardTestActivity.activity.mAudioFileName = value; + break; + } + } + } + + private void parseEvent(BufferedSource source) throws IOException { + String line; + String info[]; + while ((line = source.readUtf8Line()) != null) { + line = line.trim(); + if (line.equals("")) return; + + if (line.contains(",")) { + info = line.split(","); + Pattern pattern = Pattern.compile("[^\"]+\\.(jpg|png)", Pattern.CASE_INSENSITIVE); + Matcher matcher = pattern.matcher(line); + if (info[0].equals("0") && matcher.find()) { + StoryBoardTestActivity.activity.mBackground = matcher.group(0); + parseObjects(source); + break; + } + } + } + } + + private void parseVariables(BufferedSource source) throws IOException { + String line; + while ((line = source.readUtf8Line()) != null) { + line = line.trim(); + if (line.equals("")) return; + String[] values = line.split("="); + String key = values[0]; + String value = values[1].trim(); + variablesMap.put(key, value); + } + } + + private void parseDifficulty(BufferedSource source) throws IOException { + String line; + while ((line = source.readUtf8Line()) != null) { + line = line.trim(); + if (line.equals("")) return; + String[] values = line.split(":"); + if (values[0].equals("SliderMultiplier")) { + sliderMultiplier = Float.parseFloat(values[1]); + } + } + } + + private void parseTimingPoints(BufferedSource source) throws IOException { + String line; + float lastLengthPerBeat = -100; + while ((line = source.readUtf8Line()) != null) { + line = line.trim(); + if (line.equals("")) return; + String[] values = line.split(","); + TimingPoint timingPoint = new TimingPoint(); + timingPoint.startTime = (long) Float.parseFloat(values[0]); + timingPoint.lengthPerBeat = Float.parseFloat(values[1]); + if (timingPoint.lengthPerBeat < 0) { + timingPoint.lengthPerBeat = lastLengthPerBeat; + } else { + lastLengthPerBeat = timingPoint.lengthPerBeat; + } + timingPoints.add(timingPoint); + } + } + + private void parseHitObject(BufferedSource source) throws IOException { + String line; + while ((line = source.readUtf8Line()) != null) { + line = line.trim(); + if (line.equals("")) return; + String[] values = line.split(","); + int objectType = Integer.parseInt(values[3]); + if ((objectType & 1) == 1) {//circle + HitSound hitSound = new HitSound(); + hitSound.time = Long.parseLong(values[2]); + hitSound.soundType = Integer.parseInt(values[4]); + hitSounds.add(hitSound); + } else if ((objectType & 2) == 2) {//slider + long startTime = Long.parseLong(values[2]); + int count = Integer.parseInt(values[6]) + 1; + float sliderLength = Float.parseFloat(values[7]); + String[] soundTypes = null; + if (values.length > 8) { + soundTypes = values[8].split("\\|"); + } + TimingPoint currentPoint = timingPoints.get(0); + for (TimingPoint timingPoint : timingPoints) { + if (startTime > timingPoint.startTime) { + currentPoint = timingPoint; + break; + } + } + float sliderLengthTime = currentPoint.lengthPerBeat * (sliderMultiplier / sliderLength) / 100; + for (int i = 0; i < count; i++) { + HitSound hitSound = new HitSound(); + if (values.length > 8) { + assert soundTypes != null; + hitSound.soundType = Integer.parseInt(soundTypes[i]); + } else { + hitSound.soundType = Integer.parseInt(values[4]); + } + + hitSound.time = (long) (startTime + sliderLengthTime * i); + if (hitSound.soundType > 0) + hitSounds.add(hitSound); + } + } else if ((objectType & 8) == 8) {//spinner + HitSound hitSound = new HitSound(); + hitSound.time = Long.parseLong(values[5]); + hitSound.soundType = Integer.parseInt(values[4]); + hitSounds.add(hitSound); + } + } + } } diff --git a/src/ru/nsu/ccfit/zuev/osu/storyboard/OsuEvent.java b/src/ru/nsu/ccfit/zuev/osu/storyboard/OsuEvent.java index 977699e7..5f2a1edc 100644 --- a/src/ru/nsu/ccfit/zuev/osu/storyboard/OsuEvent.java +++ b/src/ru/nsu/ccfit/zuev/osu/storyboard/OsuEvent.java @@ -7,16 +7,16 @@ */ public class OsuEvent { - public Command command; - public int ease; - public long startTime; - public long endTime; - public float[] params; - public ArrayList subEvents;//for command L and T - public String triggerType;//for command T - public int loopCount; - public String P; + public Command command; + public int ease; + public long startTime; + public long endTime; + public float[] params; + public ArrayList subEvents;//for command L and T + public String triggerType;//for command T + public int loopCount; + public String P; - public OsuEvent() { - } + public OsuEvent() { + } } diff --git a/src/ru/nsu/ccfit/zuev/osu/storyboard/OsuSprite.java b/src/ru/nsu/ccfit/zuev/osu/storyboard/OsuSprite.java index ccf2bf6a..a39438d5 100644 --- a/src/ru/nsu/ccfit/zuev/osu/storyboard/OsuSprite.java +++ b/src/ru/nsu/ccfit/zuev/osu/storyboard/OsuSprite.java @@ -46,460 +46,460 @@ */ public class OsuSprite { - public static final int LAYER_BACKGROUND = 0; - public static final int LAYER_FAIL = 1; - public static final int LAYER_PASS = 2; - public static final int LAYER_FOREGROUND = 3; - public static float TO_RADIANS = (1 / 180.0f) * (float) Math.PI; - public static float TO_DEGREES = (1 / (float) Math.PI) * 180; - public long spriteStartTime, spriteEndTime; - private String fileName; - private String debugLine; - private int layer, ZIndex; - private Origin origin; - private BaseSprite sprite; - private ArrayList eventList; - private TextureRegion textureRegion; - private StoryBoardTestActivity activity = StoryBoardTestActivity.activity; - private boolean isValid; - private ParallelEntityModifier parallelEntityModifier; - private boolean isAnimation; - private float anchorCenterX = 0f; - private float anchorCenterY = 0f; + public static final int LAYER_BACKGROUND = 0; + public static final int LAYER_FAIL = 1; + public static final int LAYER_PASS = 2; + public static final int LAYER_FOREGROUND = 3; + public static float TO_RADIANS = (1 / 180.0f) * (float) Math.PI; + public static float TO_DEGREES = (1 / (float) Math.PI) * 180; + public long spriteStartTime, spriteEndTime; + private String fileName; + private String debugLine; + private int layer, ZIndex; + private Origin origin; + private BaseSprite sprite; + private ArrayList eventList; + private TextureRegion textureRegion; + private StoryBoardTestActivity activity = StoryBoardTestActivity.activity; + private boolean isValid; + private ParallelEntityModifier parallelEntityModifier; + private boolean isAnimation; + private float anchorCenterX = 0f; + private float anchorCenterY = 0f; - public OsuSprite(float x, float y, int layer, Origin origin, String filePath, ArrayList eventList, int ZIndex) {//normal sprite - this.fileName = filePath.replaceAll("\"", "").replaceAll("\\\\", "/"); - textureRegion = ResourceManager.getInstance().getTexture(new File(StoryBoardTestActivity.FOLDER, fileName).getPath()); - if (null == textureRegion) { - isValid = false; - } else { - isValid = true; - sprite = new Sprite(x, y, textureRegion); - this.layer = layer; - this.origin = origin; - this.eventList = eventList; - if (filePath.equals(activity.mBackground)) { - activity.mBackground = null; - } - if (eventList.size() == 0) { - isValid = false; - return; - } - this.ZIndex = ZIndex; - setUpSprite(); - } - } + public OsuSprite(float x, float y, int layer, Origin origin, String filePath, ArrayList eventList, int ZIndex) {//normal sprite + this.fileName = filePath.replaceAll("\"", "").replaceAll("\\\\", "/"); + textureRegion = ResourceManager.getInstance().getTexture(new File(StoryBoardTestActivity.FOLDER, fileName).getPath()); + if (null == textureRegion) { + isValid = false; + } else { + isValid = true; + sprite = new Sprite(x, y, textureRegion); + this.layer = layer; + this.origin = origin; + this.eventList = eventList; + if (filePath.equals(activity.mBackground)) { + activity.mBackground = null; + } + if (eventList.size() == 0) { + isValid = false; + return; + } + this.ZIndex = ZIndex; + setUpSprite(); + } + } - public OsuSprite(float x, float y, int layer, Origin origin, String filePath, ArrayList eventList, int ZIndex, int count, int delay, String loopType) {//Animation - isAnimation = true; - filePath = filePath.replaceAll("\"", "").replaceAll("\\\\", "/"); - this.fileName = filePath.substring(filePath.lastIndexOf("/") + 1, filePath.lastIndexOf(".")); - String fileExt = filePath.substring(filePath.lastIndexOf(".")); - FileBitmapTextureAtlasSource cSource = new FileBitmapTextureAtlasSource(new File(StoryBoardTestActivity.FOLDER, filePath.substring(0, filePath.lastIndexOf(".")) + "0" + fileExt)); - int tw = 16, th = 16; - int width = cSource.getWidth() * count; - int height = cSource.getHeight(); - while (tw < width) { - tw *= 2; - } - while (th < height) { - th *= 2; - } - BuildableBitmapTextureAtlas mBitmapTextureAtlas = new BuildableBitmapTextureAtlas(tw, th, TextureOptions.BILINEAR); - ArrayList textureRegions = new ArrayList(); - for (int i = 0; i < count; i++) { - File temp = new File(StoryBoardTestActivity.FOLDER, filePath.substring(0, filePath.lastIndexOf(".")) + i + fileExt); - if (temp.exists()) { - FileBitmapTextureAtlasSource cSource2 = new FileBitmapTextureAtlasSource(temp); - TextureRegion iTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromSource(mBitmapTextureAtlas, cSource2); - textureRegions.add(iTextureRegion); - } else { - break; - } - } - if (textureRegions.size() > 0) { - isValid = true; - } else { - isValid = false; - return; - } - try { - mBitmapTextureAtlas.build(new BlackPawnTextureBuilder(0)); - } catch (ITextureBuilder.TextureAtlasSourcePackingException e) { - e.printStackTrace(); - } - ResourceManager.getInstance().getEngine().getTextureManager().loadTexture(mBitmapTextureAtlas); + public OsuSprite(float x, float y, int layer, Origin origin, String filePath, ArrayList eventList, int ZIndex, int count, int delay, String loopType) {//Animation + isAnimation = true; + filePath = filePath.replaceAll("\"", "").replaceAll("\\\\", "/"); + this.fileName = filePath.substring(filePath.lastIndexOf("/") + 1, filePath.lastIndexOf(".")); + String fileExt = filePath.substring(filePath.lastIndexOf(".")); + FileBitmapTextureAtlasSource cSource = new FileBitmapTextureAtlasSource(new File(StoryBoardTestActivity.FOLDER, filePath.substring(0, filePath.lastIndexOf(".")) + "0" + fileExt)); + int tw = 16, th = 16; + int width = cSource.getWidth() * count; + int height = cSource.getHeight(); + while (tw < width) { + tw *= 2; + } + while (th < height) { + th *= 2; + } + BuildableBitmapTextureAtlas mBitmapTextureAtlas = new BuildableBitmapTextureAtlas(tw, th, TextureOptions.BILINEAR); + ArrayList textureRegions = new ArrayList(); + for (int i = 0; i < count; i++) { + File temp = new File(StoryBoardTestActivity.FOLDER, filePath.substring(0, filePath.lastIndexOf(".")) + i + fileExt); + if (temp.exists()) { + FileBitmapTextureAtlasSource cSource2 = new FileBitmapTextureAtlasSource(temp); + TextureRegion iTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromSource(mBitmapTextureAtlas, cSource2); + textureRegions.add(iTextureRegion); + } else { + break; + } + } + if (textureRegions.size() > 0) { + isValid = true; + } else { + isValid = false; + return; + } + try { + mBitmapTextureAtlas.build(new BlackPawnTextureBuilder(0)); + } catch (ITextureBuilder.TextureAtlasSourcePackingException e) { + e.printStackTrace(); + } + ResourceManager.getInstance().getEngine().getTextureManager().loadTexture(mBitmapTextureAtlas); - isValid = true; - TiledTextureRegion tiledTextureRegion = new TiledTextureRegion(mBitmapTextureAtlas, - 0, 0, width, height, count, 1); - AnimatedSprite sprite = new AnimatedSprite(x, y, tiledTextureRegion); - sprite.animate(delay, loopType.equals("LoopForever")); - this.sprite = sprite; - this.layer = layer; - this.origin = origin; - this.eventList = eventList; - if (eventList.size() == 0) { - isValid = false; - return; - } - this.ZIndex = ZIndex; - setUpSprite(); - } + isValid = true; + TiledTextureRegion tiledTextureRegion = new TiledTextureRegion(mBitmapTextureAtlas, + 0, 0, width, height, count, 1); + AnimatedSprite sprite = new AnimatedSprite(x, y, tiledTextureRegion); + sprite.animate(delay, loopType.equals("LoopForever")); + this.sprite = sprite; + this.layer = layer; + this.origin = origin; + this.eventList = eventList; + if (eventList.size() == 0) { + isValid = false; + return; + } + this.ZIndex = ZIndex; + setUpSprite(); + } - private void setUpSprite() { -// spriteStartTime = eventList.get(eventList.size() - 1).startTime; - for (OsuEvent osuEvent : eventList) { - if (osuEvent.startTime + 1 >= osuEvent.endTime && osuEvent.command != Command.F) { - continue; - } - spriteStartTime = osuEvent.startTime; - break; - } + private void setUpSprite() { +// spriteStartTime = eventList.get(eventList.size() - 1).startTime; + for (OsuEvent osuEvent : eventList) { + if (osuEvent.startTime + 1 >= osuEvent.endTime && osuEvent.command != Command.F) { + continue; + } + spriteStartTime = osuEvent.startTime; + break; + } - for (OsuEvent osuEvent : eventList) { - if (osuEvent.startTime + 1 >= osuEvent.endTime && osuEvent.command != Command.F) { - continue; - } - if (spriteStartTime > osuEvent.startTime) { - spriteStartTime = osuEvent.startTime; - } - } - for (OsuEvent firstEvent : eventList) { - if (firstEvent.startTime + 1 == firstEvent.endTime && firstEvent.command != Command.F) { - firstEvent.startTime = spriteStartTime; - break; - } - } - spriteEndTime = eventList.get(eventList.size() - 1).endTime; - sprite.setVisible(false); - sprite.setZIndex(ZIndex); - // TODO: TextureMeta - float x = sprite.getX(); - float y = sprite.getY(); + for (OsuEvent osuEvent : eventList) { + if (osuEvent.startTime + 1 >= osuEvent.endTime && osuEvent.command != Command.F) { + continue; + } + if (spriteStartTime > osuEvent.startTime) { + spriteStartTime = osuEvent.startTime; + } + } + for (OsuEvent firstEvent : eventList) { + if (firstEvent.startTime + 1 == firstEvent.endTime && firstEvent.command != Command.F) { + firstEvent.startTime = spriteStartTime; + break; + } + } + spriteEndTime = eventList.get(eventList.size() - 1).endTime; + sprite.setVisible(false); + sprite.setZIndex(ZIndex); + // TODO: TextureMeta + float x = sprite.getX(); + float y = sprite.getY(); - switch (origin) { - case TopLeft: - // sprite.setAnchorCenter(0f, 1f); - sprite.setScaleCenter(0f, 0f); - sprite.setRotationCenter(0f, 0f); - sprite.setPosition(x, y); - anchorCenterX = 0f; - anchorCenterY = 0f; - break; - case TopCentre: - // sprite.setAnchorCenter(0.5f, 1f); - sprite.setScaleCenter(sprite.getWidth() / 2f, 0); - sprite.setRotationCenter(sprite.getWidth() / 2f, 0); - sprite.setPosition(x - sprite.getWidth() / 2f, y); - anchorCenterX = sprite.getWidth() / 2f; - anchorCenterY = 0f; - break; - case TopRight: - // sprite.setAnchorCenter(1f, 1f); - sprite.setScaleCenter(sprite.getWidth(), 0); - sprite.setRotationCenter(sprite.getWidth(), 0); - sprite.setPosition(x - sprite.getWidth(), y); - anchorCenterX = sprite.getWidth(); - anchorCenterY = 0f; - break; - case CentreLeft: - // sprite.setAnchorCenter(0f, 0.5f); - sprite.setScaleCenter(0f, sprite.getHeight() / 2f); - sprite.setRotationCenter(0f, sprite.getHeight() / 2f); - sprite.setPosition(x, y - sprite.getHeight() / 2f); - anchorCenterX = 0f; - anchorCenterY = sprite.getHeight() / 2f; - break; - case Centre: - // sprite.setAnchorCenter(0.5f, 0.5f); - sprite.setScaleCenter(sprite.getWidth() / 2f, sprite.getHeight() / 2f); - sprite.setRotationCenter(sprite.getWidth() / 2f, sprite.getHeight() / 2f); - sprite.setPosition(x - sprite.getWidth() / 2f, y - sprite.getHeight() / 2f); - anchorCenterX = sprite.getWidth() / 2f; - anchorCenterY = sprite.getHeight() / 2f; - break; - case CentreRight: - // sprite.setAnchorCenter(1f, 0.5f); - sprite.setScaleCenter(sprite.getWidth(), sprite.getHeight() / 2f); - sprite.setRotationCenter(sprite.getWidth(), sprite.getHeight() / 2f); - sprite.setPosition(x - sprite.getWidth(), y - sprite.getHeight() / 2f); - anchorCenterX = sprite.getWidth(); - anchorCenterY = sprite.getHeight() / 2f; - break; - case BottomLeft: - // sprite.setAnchorCenter(0f, 0f); - sprite.setScaleCenter(0f, sprite.getHeight()); - sprite.setRotationCenter(0f, sprite.getHeight()); - sprite.setPosition(x, y - sprite.getHeight()); - anchorCenterX = 0; - anchorCenterY = sprite.getHeight(); - break; - case BottomCentre: - // sprite.setAnchorCenter(0.5f, 0f); - sprite.setScaleCenter(sprite.getWidth() / 2f, sprite.getHeight()); - sprite.setRotationCenter(sprite.getWidth() / 2f, sprite.getHeight()); - sprite.setPosition(x - sprite.getWidth() / 2f, y - sprite.getHeight()); - anchorCenterX = sprite.getWidth() / 2f; - anchorCenterY = sprite.getHeight(); - break; - case BottomRight: - // sprite.setAnchorCenter(1f, 0f); - sprite.setScaleCenter(sprite.getWidth(), sprite.getHeight()); - sprite.setRotationCenter(sprite.getWidth(), sprite.getHeight()); - sprite.setPosition(x - sprite.getWidth(), y - sprite.getHeight()); - anchorCenterX = sprite.getWidth(); - anchorCenterY = sprite.getHeight(); - break; - } - IEntityModifier[] entityModifiers = new IEntityModifier[eventList.size()]; - for (int i = 0; i < eventList.size(); i++) { - OsuEvent osuEvent = eventList.get(i); - if (osuEvent.startTime == spriteStartTime) { -// entityModifiers[i] = new SequenceEntityModifier( -// parseModifier(osuEvent) -// ); - entityModifiers[i] = parseModifier(osuEvent); - } else { - entityModifiers[i] = new SequenceEntityModifier( - new DelayModifier((osuEvent.startTime - spriteStartTime) / 1000f), - parseModifier(osuEvent) - ); - } - } - parallelEntityModifier = new ParallelEntityModifier(entityModifiers); - parallelEntityModifier.addModifierListener(new IModifier.IModifierListener() { + switch (origin) { + case TopLeft: + // sprite.setAnchorCenter(0f, 1f); + sprite.setScaleCenter(0f, 0f); + sprite.setRotationCenter(0f, 0f); + sprite.setPosition(x, y); + anchorCenterX = 0f; + anchorCenterY = 0f; + break; + case TopCentre: + // sprite.setAnchorCenter(0.5f, 1f); + sprite.setScaleCenter(sprite.getWidth() / 2f, 0); + sprite.setRotationCenter(sprite.getWidth() / 2f, 0); + sprite.setPosition(x - sprite.getWidth() / 2f, y); + anchorCenterX = sprite.getWidth() / 2f; + anchorCenterY = 0f; + break; + case TopRight: + // sprite.setAnchorCenter(1f, 1f); + sprite.setScaleCenter(sprite.getWidth(), 0); + sprite.setRotationCenter(sprite.getWidth(), 0); + sprite.setPosition(x - sprite.getWidth(), y); + anchorCenterX = sprite.getWidth(); + anchorCenterY = 0f; + break; + case CentreLeft: + // sprite.setAnchorCenter(0f, 0.5f); + sprite.setScaleCenter(0f, sprite.getHeight() / 2f); + sprite.setRotationCenter(0f, sprite.getHeight() / 2f); + sprite.setPosition(x, y - sprite.getHeight() / 2f); + anchorCenterX = 0f; + anchorCenterY = sprite.getHeight() / 2f; + break; + case Centre: + // sprite.setAnchorCenter(0.5f, 0.5f); + sprite.setScaleCenter(sprite.getWidth() / 2f, sprite.getHeight() / 2f); + sprite.setRotationCenter(sprite.getWidth() / 2f, sprite.getHeight() / 2f); + sprite.setPosition(x - sprite.getWidth() / 2f, y - sprite.getHeight() / 2f); + anchorCenterX = sprite.getWidth() / 2f; + anchorCenterY = sprite.getHeight() / 2f; + break; + case CentreRight: + // sprite.setAnchorCenter(1f, 0.5f); + sprite.setScaleCenter(sprite.getWidth(), sprite.getHeight() / 2f); + sprite.setRotationCenter(sprite.getWidth(), sprite.getHeight() / 2f); + sprite.setPosition(x - sprite.getWidth(), y - sprite.getHeight() / 2f); + anchorCenterX = sprite.getWidth(); + anchorCenterY = sprite.getHeight() / 2f; + break; + case BottomLeft: + // sprite.setAnchorCenter(0f, 0f); + sprite.setScaleCenter(0f, sprite.getHeight()); + sprite.setRotationCenter(0f, sprite.getHeight()); + sprite.setPosition(x, y - sprite.getHeight()); + anchorCenterX = 0; + anchorCenterY = sprite.getHeight(); + break; + case BottomCentre: + // sprite.setAnchorCenter(0.5f, 0f); + sprite.setScaleCenter(sprite.getWidth() / 2f, sprite.getHeight()); + sprite.setRotationCenter(sprite.getWidth() / 2f, sprite.getHeight()); + sprite.setPosition(x - sprite.getWidth() / 2f, y - sprite.getHeight()); + anchorCenterX = sprite.getWidth() / 2f; + anchorCenterY = sprite.getHeight(); + break; + case BottomRight: + // sprite.setAnchorCenter(1f, 0f); + sprite.setScaleCenter(sprite.getWidth(), sprite.getHeight()); + sprite.setRotationCenter(sprite.getWidth(), sprite.getHeight()); + sprite.setPosition(x - sprite.getWidth(), y - sprite.getHeight()); + anchorCenterX = sprite.getWidth(); + anchorCenterY = sprite.getHeight(); + break; + } + IEntityModifier[] entityModifiers = new IEntityModifier[eventList.size()]; + for (int i = 0; i < eventList.size(); i++) { + OsuEvent osuEvent = eventList.get(i); + if (osuEvent.startTime == spriteStartTime) { +// entityModifiers[i] = new SequenceEntityModifier( +// parseModifier(osuEvent) +// ); + entityModifiers[i] = parseModifier(osuEvent); + } else { + entityModifiers[i] = new SequenceEntityModifier( + new DelayModifier((osuEvent.startTime - spriteStartTime) / 1000f), + parseModifier(osuEvent) + ); + } + } + parallelEntityModifier = new ParallelEntityModifier(entityModifiers); + parallelEntityModifier.addModifierListener(new IModifier.IModifierListener() { - @Override - public void onModifierStarted(IModifier pModifier, IEntity pItem) { - sprite.setVisible(true); - } + @Override + public void onModifierStarted(IModifier pModifier, IEntity pItem) { + sprite.setVisible(true); + } - @Override - public void onModifierFinished(IModifier pModifier, IEntity pItem) { - sprite.setVisible(false); - sprite.setIgnoreUpdate(true); + @Override + public void onModifierFinished(IModifier pModifier, IEntity pItem) { + sprite.setVisible(false); + sprite.setIgnoreUpdate(true); - int total = StoryBoardTestActivity.activity.onScreenDrawCalls.decrementAndGet(); - Log.i("draw calls", "(detach) total draw calls: " + total); - } - }); - } + int total = StoryBoardTestActivity.activity.onScreenDrawCalls.decrementAndGet(); + Log.i("draw calls", "(detach) total draw calls: " + total); + } + }); + } - public void play() { - if (isValid) { - sprite.registerEntityModifier(parallelEntityModifier); - if (!sprite.hasParent()) { - switch (layer) { - case LAYER_BACKGROUND: - StoryBoardTestActivity.activity.attachBackground(sprite); - break; - case LAYER_FOREGROUND: - StoryBoardTestActivity.activity.attachForeground(sprite); - break; - case LAYER_PASS: - StoryBoardTestActivity.activity.attachPass(sprite); - break; - case LAYER_FAIL: - //ignoring fail -// StoryBoardTestActivity.activity.attachFail(sprite); - break; - } + public void play() { + if (isValid) { + sprite.registerEntityModifier(parallelEntityModifier); + if (!sprite.hasParent()) { + switch (layer) { + case LAYER_BACKGROUND: + StoryBoardTestActivity.activity.attachBackground(sprite); + break; + case LAYER_FOREGROUND: + StoryBoardTestActivity.activity.attachForeground(sprite); + break; + case LAYER_PASS: + StoryBoardTestActivity.activity.attachPass(sprite); + break; + case LAYER_FAIL: + //ignoring fail +// StoryBoardTestActivity.activity.attachFail(sprite); + break; + } - } - int total = StoryBoardTestActivity.activity.onScreenDrawCalls.incrementAndGet(); - Log.i("draw calls", "total draw calls: " + total); - } - } + } + int total = StoryBoardTestActivity.activity.onScreenDrawCalls.incrementAndGet(); + Log.i("draw calls", "total draw calls: " + total); + } + } - public String getDebugLine() { - return debugLine; - } + public String getDebugLine() { + return debugLine; + } - public void setDebugLine(String debugLine) { - this.debugLine = debugLine; - } + public void setDebugLine(String debugLine) { + this.debugLine = debugLine; + } - private IEntityModifier parseModifier(OsuEvent osuEvent) { - // TODO: ease变换的时候注意anchor - IEntityModifier iEntityModifier = null; - int ease = osuEvent.ease; - IEaseFunction iEaseFunction = null; - switch (ease) { - case 0://no easing - break; - case 1://the changes happen fast at first, but then slow down toward the end (Easing Out) - iEaseFunction = EaseQuadOut.getInstance(); - break; - case 2://the changes happen slowly at first, but then speed up toward the end (Easing In) - iEaseFunction = EaseQuadIn.getInstance(); - break; - } - float duration = (osuEvent.endTime - osuEvent.startTime) / 1000f; - switch (osuEvent.command) { - case F://Fade - if (iEaseFunction != null) { - iEntityModifier = new AlphaModifier(duration, osuEvent.params[0], osuEvent.params[1], iEaseFunction); - } else { - iEntityModifier = new AlphaModifier(duration, osuEvent.params[0], osuEvent.params[1]); - } - break; - case M://Move - if (iEaseFunction != null) { - iEntityModifier = new MoveModifier(duration, osuEvent.params[0] - anchorCenterX, osuEvent.params[2] - anchorCenterX, osuEvent.params[1] - anchorCenterY, osuEvent.params[3] - anchorCenterY, iEaseFunction); - } else { - iEntityModifier = new MoveModifier(duration, osuEvent.params[0] - anchorCenterX, osuEvent.params[2] - anchorCenterX, osuEvent.params[1] - anchorCenterY, osuEvent.params[3] - anchorCenterY); - } - break; - case MX://Move X - if (iEaseFunction != null) { - iEntityModifier = new MoveXModifier(duration, osuEvent.params[0] - anchorCenterX, osuEvent.params[1] - anchorCenterX, iEaseFunction); - } else { - iEntityModifier = new MoveXModifier(duration, osuEvent.params[0] - anchorCenterX, osuEvent.params[1] - anchorCenterX); - } - break; - case MY://Move Y - if (iEaseFunction != null) { - iEntityModifier = new MoveYModifier(duration, osuEvent.params[0] - anchorCenterY, osuEvent.params[1] - anchorCenterY, iEaseFunction); - } else { - iEntityModifier = new MoveYModifier(duration, osuEvent.params[0] - anchorCenterY, osuEvent.params[1] - anchorCenterY); - } - break; - case S://Scale - if (iEaseFunction != null) { - iEntityModifier = new ScaleModifier(duration, osuEvent.params[0], osuEvent.params[1], iEaseFunction); - } else { - iEntityModifier = new ScaleModifier(duration, osuEvent.params[0], osuEvent.params[1]); - } - break; - case V://Vector Scale - if (iEaseFunction != null) { - iEntityModifier = new ScaleModifier(duration, osuEvent.params[0], osuEvent.params[2], osuEvent.params[1], osuEvent.params[3], iEaseFunction); - } else { - iEntityModifier = new ScaleModifier(duration, osuEvent.params[0], osuEvent.params[2], osuEvent.params[1], osuEvent.params[3]); - } - break; - case R://Rotate - if (iEaseFunction != null) { - iEntityModifier = new RotationModifier(duration, osuEvent.params[0] * TO_DEGREES, osuEvent.params[1] * TO_DEGREES, iEaseFunction); - } else { - iEntityModifier = new RotationModifier(duration, osuEvent.params[0] * TO_DEGREES, osuEvent.params[1] * TO_DEGREES); - } - break; - case C://Colour - if (iEaseFunction != null) { - iEntityModifier = new ColorModifier(duration, osuEvent.params[0] / 255f, osuEvent.params[1] / 255f, osuEvent.params[2] / 255f, - osuEvent.params[3] / 255, osuEvent.params[4] / 255, osuEvent.params[5] / 255, iEaseFunction); - } else { - iEntityModifier = new ColorModifier(duration, osuEvent.params[0] / 255, osuEvent.params[1] / 255, osuEvent.params[2] / 255, - osuEvent.params[3] / 255, osuEvent.params[4] / 255, osuEvent.params[5] / 255); - } - break; - case P://Parameter - iEntityModifier = new DelayModifier(0f);//fake modifier - if (osuEvent.P.equals("H")) { - sprite.setFlippedHorizontal(true); - } else if (osuEvent.P.equals("V")) { - sprite.setFlippedVertical(true); - } else if (osuEvent.P.equals("A")) { - sprite.setBlendFunction(GLES10.GL_SRC_ALPHA, GLES10.GL_ONE); - } - break; - case L: { - ArrayList subEventList = osuEvent.subEvents; - IEntityModifier[] subEntityModifiers = new IEntityModifier[subEventList.size()]; - float firstSubTime = 0f; - if (subEventList.size() > 0) { - firstSubTime = subEventList.get(0).startTime; - } - for (int i = 0; i < subEventList.size(); i++) { - OsuEvent subOsuEvent = subEventList.get(i); - if (subOsuEvent.startTime == 0) { -// subEntityModifiers[i] = new SequenceEntityModifier( -// parseModifier(subOsuEvent) -// ); - subEntityModifiers[i] = parseModifier(subOsuEvent); - } else { - subEntityModifiers[i] = new SequenceEntityModifier( - new DelayModifier((subOsuEvent.startTime - firstSubTime) / 1000f), - parseModifier(subOsuEvent) - ); - } - } - iEntityModifier = new LoopEntityModifier(new ParallelEntityModifier(subEntityModifiers), osuEvent.loopCount); - } - break; - case T: { - ArrayList subEventList = osuEvent.subEvents; - ArrayList hitSounds = OsbParser.instance.getHitSounds(); - ArrayList entityModifierList = new ArrayList(); - int soundType; - if (osuEvent.triggerType.equals("HitSoundWhistle")) { - soundType = 2; - } else if (osuEvent.triggerType.equals("HitSoundFinish")) { - soundType = 4; - } else if (osuEvent.triggerType.equals("HitSoundClap")) { - soundType = 8; - } else { - break; - } - long firstSoundTime = -1; - for (HitSound hitSound : hitSounds) { - if (hitSound.time >= osuEvent.startTime && hitSound.time <= osuEvent.endTime && (hitSound.soundType & soundType) == soundType) { - if (firstSoundTime < 0) { - firstSoundTime = hitSound.time; - } - IEntityModifier[] subEntityModifiers = new IEntityModifier[subEventList.size()]; - long firstSubTime = 0; - if (subEventList.size() > 0) { - firstSubTime = subEventList.get(0).startTime; - } - for (int i = 0; i < subEventList.size(); i++) { - OsuEvent subOsuEvent = subEventList.get(i); - if (subOsuEvent.startTime == 0) { - subEntityModifiers[i] = parseModifier(subOsuEvent); - } else { - subEntityModifiers[i] = new SequenceEntityModifier( - new DelayModifier((subOsuEvent.startTime - firstSubTime) / 1000f), - parseModifier(subOsuEvent) - ); - } - } - if (firstSoundTime == hitSound.time) { - entityModifierList.add(new ParallelEntityModifier(subEntityModifiers)); - } else { - entityModifierList.add(new SequenceEntityModifier( - new DelayModifier((hitSound.time - firstSoundTime) / 1000f), - new ParallelEntityModifier(subEntityModifiers))); - } - } - if (hitSound.time > osuEvent.endTime) { - break; - } - } - if (entityModifierList.size() > 0) { - iEntityModifier = new ParallelEntityModifier(entityModifierList.toArray(new IEntityModifier[entityModifierList.size()])); - } - } - break; - case NONE://do nothing - break; - } - if (iEntityModifier == null) { - iEntityModifier = new DelayModifier(0f); - } - return iEntityModifier; - } + private IEntityModifier parseModifier(OsuEvent osuEvent) { + // TODO: ease变换的时候注意anchor + IEntityModifier iEntityModifier = null; + int ease = osuEvent.ease; + IEaseFunction iEaseFunction = null; + switch (ease) { + case 0://no easing + break; + case 1://the changes happen fast at first, but then slow down toward the end (Easing Out) + iEaseFunction = EaseQuadOut.getInstance(); + break; + case 2://the changes happen slowly at first, but then speed up toward the end (Easing In) + iEaseFunction = EaseQuadIn.getInstance(); + break; + } + float duration = (osuEvent.endTime - osuEvent.startTime) / 1000f; + switch (osuEvent.command) { + case F://Fade + if (iEaseFunction != null) { + iEntityModifier = new AlphaModifier(duration, osuEvent.params[0], osuEvent.params[1], iEaseFunction); + } else { + iEntityModifier = new AlphaModifier(duration, osuEvent.params[0], osuEvent.params[1]); + } + break; + case M://Move + if (iEaseFunction != null) { + iEntityModifier = new MoveModifier(duration, osuEvent.params[0] - anchorCenterX, osuEvent.params[2] - anchorCenterX, osuEvent.params[1] - anchorCenterY, osuEvent.params[3] - anchorCenterY, iEaseFunction); + } else { + iEntityModifier = new MoveModifier(duration, osuEvent.params[0] - anchorCenterX, osuEvent.params[2] - anchorCenterX, osuEvent.params[1] - anchorCenterY, osuEvent.params[3] - anchorCenterY); + } + break; + case MX://Move X + if (iEaseFunction != null) { + iEntityModifier = new MoveXModifier(duration, osuEvent.params[0] - anchorCenterX, osuEvent.params[1] - anchorCenterX, iEaseFunction); + } else { + iEntityModifier = new MoveXModifier(duration, osuEvent.params[0] - anchorCenterX, osuEvent.params[1] - anchorCenterX); + } + break; + case MY://Move Y + if (iEaseFunction != null) { + iEntityModifier = new MoveYModifier(duration, osuEvent.params[0] - anchorCenterY, osuEvent.params[1] - anchorCenterY, iEaseFunction); + } else { + iEntityModifier = new MoveYModifier(duration, osuEvent.params[0] - anchorCenterY, osuEvent.params[1] - anchorCenterY); + } + break; + case S://Scale + if (iEaseFunction != null) { + iEntityModifier = new ScaleModifier(duration, osuEvent.params[0], osuEvent.params[1], iEaseFunction); + } else { + iEntityModifier = new ScaleModifier(duration, osuEvent.params[0], osuEvent.params[1]); + } + break; + case V://Vector Scale + if (iEaseFunction != null) { + iEntityModifier = new ScaleModifier(duration, osuEvent.params[0], osuEvent.params[2], osuEvent.params[1], osuEvent.params[3], iEaseFunction); + } else { + iEntityModifier = new ScaleModifier(duration, osuEvent.params[0], osuEvent.params[2], osuEvent.params[1], osuEvent.params[3]); + } + break; + case R://Rotate + if (iEaseFunction != null) { + iEntityModifier = new RotationModifier(duration, osuEvent.params[0] * TO_DEGREES, osuEvent.params[1] * TO_DEGREES, iEaseFunction); + } else { + iEntityModifier = new RotationModifier(duration, osuEvent.params[0] * TO_DEGREES, osuEvent.params[1] * TO_DEGREES); + } + break; + case C://Colour + if (iEaseFunction != null) { + iEntityModifier = new ColorModifier(duration, osuEvent.params[0] / 255f, osuEvent.params[1] / 255f, osuEvent.params[2] / 255f, + osuEvent.params[3] / 255, osuEvent.params[4] / 255, osuEvent.params[5] / 255, iEaseFunction); + } else { + iEntityModifier = new ColorModifier(duration, osuEvent.params[0] / 255, osuEvent.params[1] / 255, osuEvent.params[2] / 255, + osuEvent.params[3] / 255, osuEvent.params[4] / 255, osuEvent.params[5] / 255); + } + break; + case P://Parameter + iEntityModifier = new DelayModifier(0f);//fake modifier + if (osuEvent.P.equals("H")) { + sprite.setFlippedHorizontal(true); + } else if (osuEvent.P.equals("V")) { + sprite.setFlippedVertical(true); + } else if (osuEvent.P.equals("A")) { + sprite.setBlendFunction(GLES10.GL_SRC_ALPHA, GLES10.GL_ONE); + } + break; + case L: { + ArrayList subEventList = osuEvent.subEvents; + IEntityModifier[] subEntityModifiers = new IEntityModifier[subEventList.size()]; + float firstSubTime = 0f; + if (subEventList.size() > 0) { + firstSubTime = subEventList.get(0).startTime; + } + for (int i = 0; i < subEventList.size(); i++) { + OsuEvent subOsuEvent = subEventList.get(i); + if (subOsuEvent.startTime == 0) { +// subEntityModifiers[i] = new SequenceEntityModifier( +// parseModifier(subOsuEvent) +// ); + subEntityModifiers[i] = parseModifier(subOsuEvent); + } else { + subEntityModifiers[i] = new SequenceEntityModifier( + new DelayModifier((subOsuEvent.startTime - firstSubTime) / 1000f), + parseModifier(subOsuEvent) + ); + } + } + iEntityModifier = new LoopEntityModifier(new ParallelEntityModifier(subEntityModifiers), osuEvent.loopCount); + } + break; + case T: { + ArrayList subEventList = osuEvent.subEvents; + ArrayList hitSounds = OsbParser.instance.getHitSounds(); + ArrayList entityModifierList = new ArrayList(); + int soundType; + if (osuEvent.triggerType.equals("HitSoundWhistle")) { + soundType = 2; + } else if (osuEvent.triggerType.equals("HitSoundFinish")) { + soundType = 4; + } else if (osuEvent.triggerType.equals("HitSoundClap")) { + soundType = 8; + } else { + break; + } + long firstSoundTime = -1; + for (HitSound hitSound : hitSounds) { + if (hitSound.time >= osuEvent.startTime && hitSound.time <= osuEvent.endTime && (hitSound.soundType & soundType) == soundType) { + if (firstSoundTime < 0) { + firstSoundTime = hitSound.time; + } + IEntityModifier[] subEntityModifiers = new IEntityModifier[subEventList.size()]; + long firstSubTime = 0; + if (subEventList.size() > 0) { + firstSubTime = subEventList.get(0).startTime; + } + for (int i = 0; i < subEventList.size(); i++) { + OsuEvent subOsuEvent = subEventList.get(i); + if (subOsuEvent.startTime == 0) { + subEntityModifiers[i] = parseModifier(subOsuEvent); + } else { + subEntityModifiers[i] = new SequenceEntityModifier( + new DelayModifier((subOsuEvent.startTime - firstSubTime) / 1000f), + parseModifier(subOsuEvent) + ); + } + } + if (firstSoundTime == hitSound.time) { + entityModifierList.add(new ParallelEntityModifier(subEntityModifiers)); + } else { + entityModifierList.add(new SequenceEntityModifier( + new DelayModifier((hitSound.time - firstSoundTime) / 1000f), + new ParallelEntityModifier(subEntityModifiers))); + } + } + if (hitSound.time > osuEvent.endTime) { + break; + } + } + if (entityModifierList.size() > 0) { + iEntityModifier = new ParallelEntityModifier(entityModifierList.toArray(new IEntityModifier[entityModifierList.size()])); + } + } + break; + case NONE://do nothing + break; + } + if (iEntityModifier == null) { + iEntityModifier = new DelayModifier(0f); + } + return iEntityModifier; + } - public enum Origin { - TopLeft, TopCentre, TopRight, CentreLeft, Centre, CentreRight, BottomLeft, BottomCentre, BottomRight, NONE; + public enum Origin { + TopLeft, TopCentre, TopRight, CentreLeft, Centre, CentreRight, BottomLeft, BottomCentre, BottomRight, NONE; - public static Origin getType(String type) { - try { - return valueOf(type.toUpperCase()); - } catch (Exception e) { - return NONE; - } - } - } + public static Origin getType(String type) { + try { + return valueOf(type.toUpperCase()); + } catch (Exception e) { + return NONE; + } + } + } } diff --git a/src/ru/nsu/ccfit/zuev/osu/storyboard/TimingPoint.java b/src/ru/nsu/ccfit/zuev/osu/storyboard/TimingPoint.java index 9ae87a9c..b65b6095 100644 --- a/src/ru/nsu/ccfit/zuev/osu/storyboard/TimingPoint.java +++ b/src/ru/nsu/ccfit/zuev/osu/storyboard/TimingPoint.java @@ -4,6 +4,6 @@ * Created by dgsrz on 16/9/16. */ public class TimingPoint { - public long startTime; - public float lengthPerBeat; + public long startTime; + public float lengthPerBeat; } diff --git a/src/ru/nsu/ccfit/zuev/push/PushNotificationService.java b/src/ru/nsu/ccfit/zuev/push/PushNotificationService.java index a4afaaad..920120e1 100644 --- a/src/ru/nsu/ccfit/zuev/push/PushNotificationService.java +++ b/src/ru/nsu/ccfit/zuev/push/PushNotificationService.java @@ -1,97 +1,97 @@ -package ru.nsu.ccfit.zuev.push; - -import android.app.NotificationChannel; -import android.app.NotificationManager; -import android.app.PendingIntent; -import android.content.Context; -import android.content.Intent; -import android.graphics.Bitmap; -import android.graphics.BitmapFactory; -import android.media.RingtoneManager; -import android.net.Uri; -import android.os.Build; - -import androidx.core.app.NotificationCompat; - -import com.google.firebase.messaging.FirebaseMessagingService; -import com.google.firebase.messaging.RemoteMessage; - -import java.util.HashMap; - -import org.anddev.andengine.util.Debug; - -import ru.nsu.ccfit.zuev.osu.MainActivity; -import ru.nsu.ccfit.zuev.osuplus.R; -import ru.nsu.ccfit.zuev.osu.helper.MD5Calcuator; -import ru.nsu.ccfit.zuev.osu.online.OnlineFileOperator; - -/** - * @author kairusds - */ -public class PushNotificationService extends FirebaseMessagingService { - - public static int notificationCount = 0; - - @Override - public void onMessageReceived(RemoteMessage remoteMessage) { - if(remoteMessage.getData().size() > 0) { - HashMap data = new HashMap(remoteMessage.getData()); - String channelId = "ru.nsu.ccfit.zuev.push"; - Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); - - String title = data.get("title"); - if(title == null) title = "osu!droid"; - String message = data.get("message"); - if(message == null) message = "error"; - String url = data.get("url"); - String imageUrl = data.get("imageUrl"); - - NotificationCompat.Builder notificationBuilder = - new NotificationCompat.Builder(this, channelId) - .setSmallIcon(R.drawable.notify_inso) - .setContentTitle(title) - .setContentText(message) - .setAutoCancel(true) - .setSound(defaultSoundUri); - - if(!imageUrl.isEmpty()) { - String filePath = getCacheDir().getPath() + "/" + MD5Calcuator.getStringMD5("osuplus" + imageUrl); - boolean downloaded = OnlineFileOperator.downloadFile(imageUrl, filePath); - if(downloaded) { - Bitmap bitmap = BitmapFactory.decodeFile(filePath); - notificationBuilder.setLargeIcon(bitmap) - .setStyle(new NotificationCompat.BigPictureStyle() - .bigPicture(bitmap) - .bigLargeIcon(null)); - } - } - - if(!url.isEmpty()) { - Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); - PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, - PendingIntent.FLAG_ONE_SHOT); - notificationBuilder.setContentIntent(pendingIntent); - }else { - Intent intent = new Intent(this, MainActivity.class); - intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, - PendingIntent.FLAG_ONE_SHOT); - notificationBuilder.setContentIntent(pendingIntent); - } - - NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); - - if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { - NotificationChannel channel = new NotificationChannel(channelId, - "osu!droid Push Notfications", - NotificationManager.IMPORTANCE_DEFAULT); - channel.setDescription("osu!droid Push Notfications"); - notificationManager.createNotificationChannel(channel); - } - - int notificationId = notificationCount++; - notificationManager.notify(notificationId, notificationBuilder.build()); - } - } - -} \ No newline at end of file +package ru.nsu.ccfit.zuev.push; + +import android.app.NotificationChannel; +import android.app.NotificationManager; +import android.app.PendingIntent; +import android.content.Context; +import android.content.Intent; +import android.graphics.Bitmap; +import android.graphics.BitmapFactory; +import android.media.RingtoneManager; +import android.net.Uri; +import android.os.Build; + +import androidx.core.app.NotificationCompat; + +import com.google.firebase.messaging.FirebaseMessagingService; +import com.google.firebase.messaging.RemoteMessage; + +import java.util.HashMap; + +import org.anddev.andengine.util.Debug; + +import ru.nsu.ccfit.zuev.osu.MainActivity; +import ru.nsu.ccfit.zuev.osuplus.R; +import ru.nsu.ccfit.zuev.osu.helper.MD5Calcuator; +import ru.nsu.ccfit.zuev.osu.online.OnlineFileOperator; + +/** + * @author kairusds + */ +public class PushNotificationService extends FirebaseMessagingService { + + public static int notificationCount = 0; + + @Override + public void onMessageReceived(RemoteMessage remoteMessage) { + if(remoteMessage.getData().size() > 0) { + HashMap data = new HashMap(remoteMessage.getData()); + String channelId = "ru.nsu.ccfit.zuev.push"; + Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); + + String title = data.get("title"); + if(title == null) title = "osu!droid"; + String message = data.get("message"); + if(message == null) message = "error"; + String url = data.get("url"); + String imageUrl = data.get("imageUrl"); + + NotificationCompat.Builder notificationBuilder = + new NotificationCompat.Builder(this, channelId) + .setSmallIcon(R.drawable.notify_inso) + .setContentTitle(title) + .setContentText(message) + .setAutoCancel(true) + .setSound(defaultSoundUri); + + if(!imageUrl.isEmpty()) { + String filePath = getCacheDir().getPath() + "/" + MD5Calcuator.getStringMD5("osuplus" + imageUrl); + boolean downloaded = OnlineFileOperator.downloadFile(imageUrl, filePath); + if(downloaded) { + Bitmap bitmap = BitmapFactory.decodeFile(filePath); + notificationBuilder.setLargeIcon(bitmap) + .setStyle(new NotificationCompat.BigPictureStyle() + .bigPicture(bitmap) + .bigLargeIcon(null)); + } + } + + if(!url.isEmpty()) { + Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); + PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, + PendingIntent.FLAG_ONE_SHOT); + notificationBuilder.setContentIntent(pendingIntent); + }else { + Intent intent = new Intent(this, MainActivity.class); + intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, + PendingIntent.FLAG_ONE_SHOT); + notificationBuilder.setContentIntent(pendingIntent); + } + + NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); + + if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { + NotificationChannel channel = new NotificationChannel(channelId, + "osu!droid Push Notfications", + NotificationManager.IMPORTANCE_DEFAULT); + channel.setDescription("osu!droid Push Notfications"); + notificationManager.createNotificationChannel(channel); + } + + int notificationId = notificationCount++; + notificationManager.notify(notificationId, notificationBuilder.build()); + } + } + +} diff --git a/src/test/tpdifficulty/TimingPoint.java b/src/test/tpdifficulty/TimingPoint.java index 4c00a341..58e5fe82 100644 --- a/src/test/tpdifficulty/TimingPoint.java +++ b/src/test/tpdifficulty/TimingPoint.java @@ -4,46 +4,46 @@ * Created by Fuuko on 2015/5/29. */ public class TimingPoint { - private float bpm; - private float offset; - private float speed; - - public TimingPoint(float bpm, float offset, float speed) { - this.bpm = bpm; - this.offset = offset; - this.speed = speed; - } - - public float getBpm() { - return bpm; - } - - public void setBpm(float bpm) { - this.bpm = bpm; - } - - public float getOffset() { - return offset; - } - - public void setOffset(float offset) { - this.offset = offset; - } - - public float getSpeed() { - return speed; - } - - public void setSpeed(float speed) { - this.speed = speed; - } - - @Override - public String toString() { - return "TimingPoint{" + - "bpm=" + bpm + - ", offset=" + offset + - ", speed=" + speed + - '}'; - } + private float bpm; + private float offset; + private float speed; + + public TimingPoint(float bpm, float offset, float speed) { + this.bpm = bpm; + this.offset = offset; + this.speed = speed; + } + + public float getBpm() { + return bpm; + } + + public void setBpm(float bpm) { + this.bpm = bpm; + } + + public float getOffset() { + return offset; + } + + public void setOffset(float offset) { + this.offset = offset; + } + + public float getSpeed() { + return speed; + } + + public void setSpeed(float speed) { + this.speed = speed; + } + + @Override + public String toString() { + return "TimingPoint{" + + "bpm=" + bpm + + ", offset=" + offset + + ", speed=" + speed + + '}'; + } } diff --git a/src/test/tpdifficulty/hitobject/HitCircle.java b/src/test/tpdifficulty/hitobject/HitCircle.java index bb323b71..7e71908e 100644 --- a/src/test/tpdifficulty/hitobject/HitCircle.java +++ b/src/test/tpdifficulty/hitobject/HitCircle.java @@ -9,20 +9,20 @@ */ public class HitCircle extends HitObject { - public HitCircle(int startTime, PointF pos, TimingPoint timingPoint) { - super(startTime, startTime, HitObjectType.Normal, pos, timingPoint); - this.repeat = 1; - } + public HitCircle(int startTime, PointF pos, TimingPoint timingPoint) { + super(startTime, startTime, HitObjectType.Normal, pos, timingPoint); + this.repeat = 1; + } - public String toString() { - return "HitCircle{" + - super.toString() + - ", Combo=" + getCombo(0, 0) + - "}"; - } + public String toString() { + return "HitCircle{" + + super.toString() + + ", Combo=" + getCombo(0, 0) + + "}"; + } - @Override - public int getCombo(float sliderTick, float sliderSpeed) { - return 1; - } + @Override + public int getCombo(float sliderTick, float sliderSpeed) { + return 1; + } } diff --git a/src/test/tpdifficulty/hitobject/HitObject.java b/src/test/tpdifficulty/hitobject/HitObject.java index 39a19b06..3e7a8a5c 100644 --- a/src/test/tpdifficulty/hitobject/HitObject.java +++ b/src/test/tpdifficulty/hitobject/HitObject.java @@ -8,84 +8,84 @@ * Created by Fuuko on 2015/5/29. */ public abstract class HitObject { - protected int startTime; - protected int endTime; - protected HitObjectType type; - protected PointF pos; - protected TimingPoint timingPoint; - protected int repeat; - - public HitObject(int startTime, int endTime, HitObjectType type, PointF pos, TimingPoint timingPoint) { - this.startTime = startTime; - this.endTime = endTime; - this.type = type; - this.pos = pos; - this.timingPoint = timingPoint; - } - - public int getRepeat() { - return repeat; - } - - public void setRepeat(int repeat) { - this.repeat = repeat; - } - - public int getStartTime() { - return startTime; - } - - public void setStartTime(int startTime) { - this.startTime = startTime; - } - - public int getEndTime() { - return endTime; - } - - public void setEndTime(int endTime) { - this.endTime = endTime; - } - - public HitObjectType getType() { - return type; - } - - public void setType(HitObjectType type) { - this.type = type; - } - - public PointF getPos() { - return pos; - } - - public void setPos(PointF pos) { - this.pos = pos; - } - - public int getLength() { - return this.endTime - this.startTime; - } - - public TimingPoint getTimingPoint() { - return timingPoint; - } - - public void setTimingPoint(TimingPoint timingPoint) { - this.timingPoint = timingPoint; - } - - @Override - public String toString() { - return "startTime=" + startTime + - ", endTime=" + endTime + - ", pos=" + pos + - ", timingPoint=" + timingPoint; - } - - public String toString(float sliderTick, float sliderSpeed) { - return ""; - } - - public abstract int getCombo(float sliderTick, float sliderSpeed); + protected int startTime; + protected int endTime; + protected HitObjectType type; + protected PointF pos; + protected TimingPoint timingPoint; + protected int repeat; + + public HitObject(int startTime, int endTime, HitObjectType type, PointF pos, TimingPoint timingPoint) { + this.startTime = startTime; + this.endTime = endTime; + this.type = type; + this.pos = pos; + this.timingPoint = timingPoint; + } + + public int getRepeat() { + return repeat; + } + + public void setRepeat(int repeat) { + this.repeat = repeat; + } + + public int getStartTime() { + return startTime; + } + + public void setStartTime(int startTime) { + this.startTime = startTime; + } + + public int getEndTime() { + return endTime; + } + + public void setEndTime(int endTime) { + this.endTime = endTime; + } + + public HitObjectType getType() { + return type; + } + + public void setType(HitObjectType type) { + this.type = type; + } + + public PointF getPos() { + return pos; + } + + public void setPos(PointF pos) { + this.pos = pos; + } + + public int getLength() { + return this.endTime - this.startTime; + } + + public TimingPoint getTimingPoint() { + return timingPoint; + } + + public void setTimingPoint(TimingPoint timingPoint) { + this.timingPoint = timingPoint; + } + + @Override + public String toString() { + return "startTime=" + startTime + + ", endTime=" + endTime + + ", pos=" + pos + + ", timingPoint=" + timingPoint; + } + + public String toString(float sliderTick, float sliderSpeed) { + return ""; + } + + public abstract int getCombo(float sliderTick, float sliderSpeed); } diff --git a/src/test/tpdifficulty/hitobject/HitObjectType.java b/src/test/tpdifficulty/hitobject/HitObjectType.java index 4fa75137..293134c1 100644 --- a/src/test/tpdifficulty/hitobject/HitObjectType.java +++ b/src/test/tpdifficulty/hitobject/HitObjectType.java @@ -4,37 +4,37 @@ * Created by Fuuko on 2015/5/29. */ public enum HitObjectType { - Normal(1), - Slider(2), - NewCombo(4), - NormalNewCombo(5), - SliderNewCombo(6), - Spinner(8); + Normal(1), + Slider(2), + NewCombo(4), + NormalNewCombo(5), + SliderNewCombo(6), + Spinner(8); - private int value; + private int value; - HitObjectType(int value) { - this.value = value; - } + HitObjectType(int value) { + this.value = value; + } - public static HitObjectType valueOf(int value) { - switch (value) { - case 1: - return Normal; - case 2: - return Slider; - case 4: - return NewCombo; - case 5: - return NormalNewCombo; - case 6: - return SliderNewCombo; - default: - return Spinner; - } - } + public static HitObjectType valueOf(int value) { + switch (value) { + case 1: + return Normal; + case 2: + return Slider; + case 4: + return NewCombo; + case 5: + return NormalNewCombo; + case 6: + return SliderNewCombo; + default: + return Spinner; + } + } - public int value() { - return this.value; - } + public int value() { + return this.value; + } } diff --git a/src/test/tpdifficulty/hitobject/Slider.java b/src/test/tpdifficulty/hitobject/Slider.java index b0b9a7a0..fded376e 100644 --- a/src/test/tpdifficulty/hitobject/Slider.java +++ b/src/test/tpdifficulty/hitobject/Slider.java @@ -10,69 +10,69 @@ * Created by Fuuko on 2015/5/29. */ public class Slider extends HitObject { - private SliderType sliderType; - private ArrayList curvePoints; - private float rawLength; + private SliderType sliderType; + private ArrayList curvePoints; + private float rawLength; - public Slider(int startTime, int endTime, PointF pos, TimingPoint timingPoint, SliderType sliderType, - int repeat, ArrayList curvePoints, float rawLength) { - super(startTime, endTime, HitObjectType.Slider, pos, timingPoint); - this.sliderType = sliderType; - this.repeat = repeat; - this.curvePoints = curvePoints; - this.rawLength = rawLength; - } + public Slider(int startTime, int endTime, PointF pos, TimingPoint timingPoint, SliderType sliderType, + int repeat, ArrayList curvePoints, float rawLength) { + super(startTime, endTime, HitObjectType.Slider, pos, timingPoint); + this.sliderType = sliderType; + this.repeat = repeat; + this.curvePoints = curvePoints; + this.rawLength = rawLength; + } - public SliderType getSliderType() { - return sliderType; - } + public SliderType getSliderType() { + return sliderType; + } - public void setSliderType(SliderType sliderType) { - this.sliderType = sliderType; - } + public void setSliderType(SliderType sliderType) { + this.sliderType = sliderType; + } - @Override - public int getLength() { - return super.getLength() * repeat; - } + @Override + public int getLength() { + return super.getLength() * repeat; + } - public float getRawLength() { - return rawLength; - } + public float getRawLength() { + return rawLength; + } - public void setRawLength(float rawLength) { - this.rawLength = rawLength; - } + public void setRawLength(float rawLength) { + this.rawLength = rawLength; + } - public ArrayList getCurvePoints() { - return curvePoints; - } + public ArrayList getCurvePoints() { + return curvePoints; + } - public void setCurvePoints(ArrayList curvePoints) { - this.curvePoints = curvePoints; - } + public void setCurvePoints(ArrayList curvePoints) { + this.curvePoints = curvePoints; + } - public String toString() { - return "Slider{" + - super.toString() + - "sliderType=" + sliderType + - ", repeat=" + repeat + - ", curvePoints=" + curvePoints + - '}'; - } + public String toString() { + return "Slider{" + + super.toString() + + "sliderType=" + sliderType + + ", repeat=" + repeat + + ", curvePoints=" + curvePoints + + '}'; + } - public String toString(float sliderTick, float sliderSpeed) { - return "Slider{" + - super.toString() + - "sliderType=" + sliderType + - ", repeat=" + repeat + - ", curvePoints=" + curvePoints + - ", Combo=" + getCombo(sliderTick, sliderSpeed) + - '}'; - } + public String toString(float sliderTick, float sliderSpeed) { + return "Slider{" + + super.toString() + + "sliderType=" + sliderType + + ", repeat=" + repeat + + ", curvePoints=" + curvePoints + + ", Combo=" + getCombo(sliderTick, sliderSpeed) + + '}'; + } - @Override - public int getCombo(float sliderTick, float sliderSpeed) { - return (int) Math.ceil(sliderTick * rawLength / (timingPoint.getSpeed() * sliderSpeed) / 100.01f) * repeat + 1; - } + @Override + public int getCombo(float sliderTick, float sliderSpeed) { + return (int) Math.ceil(sliderTick * rawLength / (timingPoint.getSpeed() * sliderSpeed) / 100.01f) * repeat + 1; + } } diff --git a/src/test/tpdifficulty/hitobject/SliderType.java b/src/test/tpdifficulty/hitobject/SliderType.java index 7bae53cc..205b977f 100644 --- a/src/test/tpdifficulty/hitobject/SliderType.java +++ b/src/test/tpdifficulty/hitobject/SliderType.java @@ -4,23 +4,23 @@ * Created by Fuuko on 2015/5/29. */ public enum SliderType { - Catmull, - Bezier, - Linear, - PerfectCurve; + Catmull, + Bezier, + Linear, + PerfectCurve; - public static SliderType parse(char value) { - switch (value) { - case 'C': - return Catmull; - case 'B': - return Bezier; - case 'L': - return Linear; - case 'P': - return PerfectCurve; - default: - return Bezier; - } - } + public static SliderType parse(char value) { + switch (value) { + case 'C': + return Catmull; + case 'B': + return Bezier; + case 'L': + return Linear; + case 'P': + return PerfectCurve; + default: + return Bezier; + } + } } diff --git a/src/test/tpdifficulty/hitobject/Spinner.java b/src/test/tpdifficulty/hitobject/Spinner.java index c0f1da75..348384b9 100644 --- a/src/test/tpdifficulty/hitobject/Spinner.java +++ b/src/test/tpdifficulty/hitobject/Spinner.java @@ -9,21 +9,21 @@ */ public class Spinner extends HitObject { - public Spinner(int startTime, int endTime, PointF pos, TimingPoint timingPoint) { - super(startTime, endTime, HitObjectType.Spinner, pos, timingPoint); - this.repeat = 1; - } + public Spinner(int startTime, int endTime, PointF pos, TimingPoint timingPoint) { + super(startTime, endTime, HitObjectType.Spinner, pos, timingPoint); + this.repeat = 1; + } - @Override - public String toString() { - return "Spinner{" + - super.toString() + - ", Combo=" + getCombo(0, 0) + - "}"; - } + @Override + public String toString() { + return "Spinner{" + + super.toString() + + ", Combo=" + getCombo(0, 0) + + "}"; + } - @Override - public int getCombo(float sliderTick, float sliderSpeed) { - return 1; - } + @Override + public int getCombo(float sliderTick, float sliderSpeed) { + return 1; + } } diff --git a/src/test/tpdifficulty/tp/AiModtpDifficulty.java b/src/test/tpdifficulty/tp/AiModtpDifficulty.java index a65d90d6..5274dead 100644 --- a/src/test/tpdifficulty/tp/AiModtpDifficulty.java +++ b/src/test/tpdifficulty/tp/AiModtpDifficulty.java @@ -12,189 +12,189 @@ * Created by Fuuko on 2015/5/30. */ public class AiModtpDifficulty { - private static double STAR_SCALING_FACTOR = 0.045 / 0.666; - private static double EXTREME_SCALING_FACTOR = 0.5; - private static float PLAYFIELD_WIDTH = 512; - // In milliseconds. For difficulty calculation we will only look at the highest strain value in each time interval of size STRAIN_STEP. - // This is to eliminate higher influence of stream over aim by simply having more HitObjects with high strain. - // The higher this value, the less strains there will be, indirectly giving long beatmaps an advantage. - private static double STRAIN_STEP = 400; - // The weighting of each strain value decays to 0.9 * it's previous value - private static double DECAY_WEIGHT = 0.9; - ArrayList tpHitObjects; - private double SpeedStars, AimStars, StarRating; - private double SpeedDifficulty, AimDifficulty; - - private double CalculateDifficulty(DifficultyType Type) { - // Find the highest strain value within each strain step - ArrayList HighestStrains = new ArrayList(); - double IntervalEndTime = STRAIN_STEP; - double MaximumStrain = 0; // We need to keep track of the maximum strain in the current interval - - tpHitObject PreviousHitObject = null; - for (tpHitObject hitObject : tpHitObjects) { - // While we are beyond the current interval push the currently available maximum to our strain list - while (hitObject.BaseHitObject.getStartTime() > IntervalEndTime) { - HighestStrains.add(MaximumStrain); - - // The maximum strain of the next interval is not zero by default! We need to take the last hitObject we encountered, take its strain and apply the decay - // until the beginning of the next interval. - if (PreviousHitObject == null) { - MaximumStrain = 0; - } else { - double Decay = Math.pow(tpHitObject.DECAY_BASE[Type.value()], (double) (IntervalEndTime - PreviousHitObject.BaseHitObject.getStartTime()) / 1000); - MaximumStrain = PreviousHitObject.Strains[Type.value()] * Decay; - } - - // Go to the next time interval - IntervalEndTime += STRAIN_STEP; - } - - // Obtain maximum strain - if (hitObject.Strains[Type.value()] > MaximumStrain) { - MaximumStrain = hitObject.Strains[Type.value()]; - } - - PreviousHitObject = hitObject; - } - /* don't forget to add the last strain interval */ - HighestStrains.add(MaximumStrain); - - // Build the weighted sum over the highest strains for each interval - double Difficulty = 0; - double Weight = 1; - Collections.sort(HighestStrains, Collections.reverseOrder()); // Sort from highest to lowest strain. - - for (double Strain : HighestStrains) { - Difficulty += Weight * Strain; - Weight *= DECAY_WEIGHT; - } - - return Difficulty; - } - - private Boolean CalculateStrainValues() { - // Traverse hitObjects in pairs to calculate the strain value of NextHitObject from the strain value of CurrentHitObject and environment. - Iterator HitObjectsIterator = tpHitObjects.iterator(); - if (HitObjectsIterator.hasNext() == false) { - return false; - } - - tpHitObject CurrentHitObject = HitObjectsIterator.next(); - tpHitObject NextHitObject; - - // First hitObject starts at strain 1. 1 is the default for strain values, so we don't need to set it here. See tpHitObject. - - while (HitObjectsIterator.hasNext()) { - NextHitObject = HitObjectsIterator.next(); - NextHitObject.CalculateStrains(CurrentHitObject); - CurrentHitObject = NextHitObject; - } - - return true; - } - public void CalculateAll(ArrayList hitObjects, float circleSize) { - CalculateAll(hitObjects,circleSize,1.0f); - } - public void CalculateAll(ArrayList hitObjects, float circleSize, float speed) { - // Fill our custom tpHitObject class, that carries additional information - tpHitObjects = new ArrayList(hitObjects.size()); - // The Max CS in osu!droid is 17.62, but in pc OSU! is about 12.14. so I map 10-17.62(gameplay CS) to 10-12.14(star calculate CS) - float cs = Math.min(circleSize, 17.62f); - if (cs > 10.0f) { - cs = 10.0f + (cs - 10.0f) * (12.14f - 10.0f) / (17.62f - 10.0f); - } - float CircleRadius = (PLAYFIELD_WIDTH / 16.0f) * (1.0f - 0.7f * (cs - 5.0f) / 5.0f); - for (HitObject hitObject : hitObjects) { - tpHitObject hitObj = new tpHitObject(hitObject, CircleRadius); - hitObj.BaseHitObject.setStartTime((int)(hitObj.BaseHitObject.getStartTime() / speed)); - hitObj.BaseHitObject.setEndTime((int)(hitObj.BaseHitObject.getEndTime() / speed)); - tpHitObjects.add(hitObj); - } - - // Sort tpHitObjects by StartTime of the HitObjects - just to make sure. Not using CompareTo, since it results in a crash (HitObjectBase inherits MarshalByRefObject) - Collections.sort(tpHitObjects); - - // Calculates the flow angle of the Hitobjects - tpHitObject prev1 = null; - tpHitObject prev2 = null; - int i = 0; - for(tpHitObject hitObject : tpHitObjects){ - if(i >= 2){ - PointF v1 = new PointF(prev2.getNormPosStart().x - prev1.getNormPosEnd().x, - prev2.getNormPosStart().y - prev1.getNormPosEnd().y); - PointF v2 = new PointF(hitObject.getNormPosStart().x - prev1.getNormPosEnd().x, - hitObject.getNormPosStart().y - prev1.getNormPosEnd().y); - double dot = v1.x * v2.x + v1.y * v2.y; - double det = v1.x * v2.y - v1.y * v2.x; - hitObject.angle = Math.abs(Math.atan2(det, dot)); - } - else { - hitObject.angle = Double.NaN; - } - prev2 = prev1; - prev1 = hitObject; - ++i; - } - - if (CalculateStrainValues() == false) { - System.out.println("Could not compute strain values. Aborting difficulty calculation."); - return; - } - - - SpeedDifficulty = CalculateDifficulty(DifficultyType.Speed); - AimDifficulty = CalculateDifficulty(DifficultyType.Aim); - - // OverallDifficulty is not considered in this algorithm and neither is HpDrainRate. That means, that in this form the algorithm determines how hard it physically is - // to play the map, assuming, that too much of an error will not lead to a death. - // It might be desirable to include OverallDifficulty into map difficulty, but in my personal opinion it belongs more to the weighting of the actual peformance - // and is superfluous in the beatmap difficulty rating. - // If it were to be considered, then I would look at the hit window of normal HitCircles only, since Sliders and Spinners are (almost) "free" 300s and take map length - // into account as well. - - System.out.println("Speed difficulty: " + SpeedDifficulty + " | Aim difficulty: " + AimDifficulty); - - // The difficulty can be scaled by any desired metric. - // In osu!tp it gets squared to account for the rapid increase in difficulty as the limit of a human is approached. (Of course it also gets scaled afterwards.) - // It would not be suitable for a star rating, therefore: - - // The following is a proposal to forge a star rating from 0 to 5. It consists of taking the square root of the difficulty, since by simply scaling the easier - // 5-star maps would end up with one star. - SpeedStars = Math.sqrt(SpeedDifficulty) * STAR_SCALING_FACTOR; - AimStars = Math.sqrt(AimDifficulty) * STAR_SCALING_FACTOR; - - System.out.println("Speed stars: " + SpeedStars + " | Aim stars: " + AimStars); - - // Again, from own observations and from the general opinion of the community a map with high speed and low aim (or vice versa) difficulty is harder, - // than a map with mediocre difficulty in both. Therefore we can not just add both difficulties together, but will introduce a scaling that favors extremes. - StarRating = SpeedStars + AimStars + Math.abs(SpeedStars - AimStars) * EXTREME_SCALING_FACTOR; - // Another approach to this would be taking Speed and Aim separately to a chosen power, which again would be equivalent. This would be more convenient if - // the hit window size is to be considered as well. - - // Note: The star rating is tuned extremely tight! Airman (/b/104229) and Freedom Dive (/b/126645), two of the hardest ranked maps, both score ~4.66 stars. - // Expect the easier kind of maps that officially get 5 stars to obtain around 2 by this metric. The tutorial still scores about half a star. - // Tune by yourself as you please. ;) - System.out.println("Total star rating: " + StarRating); - } - - public double getAimDifficulty() { - return AimDifficulty; - } - - public double getSpeedStars() { - return SpeedStars; - } - - public double getAimStars() { - return AimStars; - } - - public double getStarRating() { - return StarRating; - } - - public double getSpeedDifficulty() { - return SpeedDifficulty; - } + private static double STAR_SCALING_FACTOR = 0.045 / 0.666; + private static double EXTREME_SCALING_FACTOR = 0.5; + private static float PLAYFIELD_WIDTH = 512; + // In milliseconds. For difficulty calculation we will only look at the highest strain value in each time interval of size STRAIN_STEP. + // This is to eliminate higher influence of stream over aim by simply having more HitObjects with high strain. + // The higher this value, the less strains there will be, indirectly giving long beatmaps an advantage. + private static double STRAIN_STEP = 400; + // The weighting of each strain value decays to 0.9 * it's previous value + private static double DECAY_WEIGHT = 0.9; + ArrayList tpHitObjects; + private double SpeedStars, AimStars, StarRating; + private double SpeedDifficulty, AimDifficulty; + + private double CalculateDifficulty(DifficultyType Type) { + // Find the highest strain value within each strain step + ArrayList HighestStrains = new ArrayList(); + double IntervalEndTime = STRAIN_STEP; + double MaximumStrain = 0; // We need to keep track of the maximum strain in the current interval + + tpHitObject PreviousHitObject = null; + for (tpHitObject hitObject : tpHitObjects) { + // While we are beyond the current interval push the currently available maximum to our strain list + while (hitObject.BaseHitObject.getStartTime() > IntervalEndTime) { + HighestStrains.add(MaximumStrain); + + // The maximum strain of the next interval is not zero by default! We need to take the last hitObject we encountered, take its strain and apply the decay + // until the beginning of the next interval. + if (PreviousHitObject == null) { + MaximumStrain = 0; + } else { + double Decay = Math.pow(tpHitObject.DECAY_BASE[Type.value()], (double) (IntervalEndTime - PreviousHitObject.BaseHitObject.getStartTime()) / 1000); + MaximumStrain = PreviousHitObject.Strains[Type.value()] * Decay; + } + + // Go to the next time interval + IntervalEndTime += STRAIN_STEP; + } + + // Obtain maximum strain + if (hitObject.Strains[Type.value()] > MaximumStrain) { + MaximumStrain = hitObject.Strains[Type.value()]; + } + + PreviousHitObject = hitObject; + } + /* don't forget to add the last strain interval */ + HighestStrains.add(MaximumStrain); + + // Build the weighted sum over the highest strains for each interval + double Difficulty = 0; + double Weight = 1; + Collections.sort(HighestStrains, Collections.reverseOrder()); // Sort from highest to lowest strain. + + for (double Strain : HighestStrains) { + Difficulty += Weight * Strain; + Weight *= DECAY_WEIGHT; + } + + return Difficulty; + } + + private Boolean CalculateStrainValues() { + // Traverse hitObjects in pairs to calculate the strain value of NextHitObject from the strain value of CurrentHitObject and environment. + Iterator HitObjectsIterator = tpHitObjects.iterator(); + if (HitObjectsIterator.hasNext() == false) { + return false; + } + + tpHitObject CurrentHitObject = HitObjectsIterator.next(); + tpHitObject NextHitObject; + + // First hitObject starts at strain 1. 1 is the default for strain values, so we don't need to set it here. See tpHitObject. + + while (HitObjectsIterator.hasNext()) { + NextHitObject = HitObjectsIterator.next(); + NextHitObject.CalculateStrains(CurrentHitObject); + CurrentHitObject = NextHitObject; + } + + return true; + } + public void CalculateAll(ArrayList hitObjects, float circleSize) { + CalculateAll(hitObjects,circleSize,1.0f); + } + public void CalculateAll(ArrayList hitObjects, float circleSize, float speed) { + // Fill our custom tpHitObject class, that carries additional information + tpHitObjects = new ArrayList(hitObjects.size()); + // The Max CS in osu!droid is 17.62, but in pc OSU! is about 12.14. so I map 10-17.62(gameplay CS) to 10-12.14(star calculate CS) + float cs = Math.min(circleSize, 17.62f); + if (cs > 10.0f) { + cs = 10.0f + (cs - 10.0f) * (12.14f - 10.0f) / (17.62f - 10.0f); + } + float CircleRadius = (PLAYFIELD_WIDTH / 16.0f) * (1.0f - 0.7f * (cs - 5.0f) / 5.0f); + for (HitObject hitObject : hitObjects) { + tpHitObject hitObj = new tpHitObject(hitObject, CircleRadius); + hitObj.BaseHitObject.setStartTime((int)(hitObj.BaseHitObject.getStartTime() / speed)); + hitObj.BaseHitObject.setEndTime((int)(hitObj.BaseHitObject.getEndTime() / speed)); + tpHitObjects.add(hitObj); + } + + // Sort tpHitObjects by StartTime of the HitObjects - just to make sure. Not using CompareTo, since it results in a crash (HitObjectBase inherits MarshalByRefObject) + Collections.sort(tpHitObjects); + + // Calculates the flow angle of the Hitobjects + tpHitObject prev1 = null; + tpHitObject prev2 = null; + int i = 0; + for(tpHitObject hitObject : tpHitObjects){ + if(i >= 2){ + PointF v1 = new PointF(prev2.getNormPosStart().x - prev1.getNormPosEnd().x, + prev2.getNormPosStart().y - prev1.getNormPosEnd().y); + PointF v2 = new PointF(hitObject.getNormPosStart().x - prev1.getNormPosEnd().x, + hitObject.getNormPosStart().y - prev1.getNormPosEnd().y); + double dot = v1.x * v2.x + v1.y * v2.y; + double det = v1.x * v2.y - v1.y * v2.x; + hitObject.angle = Math.abs(Math.atan2(det, dot)); + } + else { + hitObject.angle = Double.NaN; + } + prev2 = prev1; + prev1 = hitObject; + ++i; + } + + if (CalculateStrainValues() == false) { + System.out.println("Could not compute strain values. Aborting difficulty calculation."); + return; + } + + + SpeedDifficulty = CalculateDifficulty(DifficultyType.Speed); + AimDifficulty = CalculateDifficulty(DifficultyType.Aim); + + // OverallDifficulty is not considered in this algorithm and neither is HpDrainRate. That means, that in this form the algorithm determines how hard it physically is + // to play the map, assuming, that too much of an error will not lead to a death. + // It might be desirable to include OverallDifficulty into map difficulty, but in my personal opinion it belongs more to the weighting of the actual peformance + // and is superfluous in the beatmap difficulty rating. + // If it were to be considered, then I would look at the hit window of normal HitCircles only, since Sliders and Spinners are (almost) "free" 300s and take map length + // into account as well. + + System.out.println("Speed difficulty: " + SpeedDifficulty + " | Aim difficulty: " + AimDifficulty); + + // The difficulty can be scaled by any desired metric. + // In osu!tp it gets squared to account for the rapid increase in difficulty as the limit of a human is approached. (Of course it also gets scaled afterwards.) + // It would not be suitable for a star rating, therefore: + + // The following is a proposal to forge a star rating from 0 to 5. It consists of taking the square root of the difficulty, since by simply scaling the easier + // 5-star maps would end up with one star. + SpeedStars = Math.sqrt(SpeedDifficulty) * STAR_SCALING_FACTOR; + AimStars = Math.sqrt(AimDifficulty) * STAR_SCALING_FACTOR; + + System.out.println("Speed stars: " + SpeedStars + " | Aim stars: " + AimStars); + + // Again, from own observations and from the general opinion of the community a map with high speed and low aim (or vice versa) difficulty is harder, + // than a map with mediocre difficulty in both. Therefore we can not just add both difficulties together, but will introduce a scaling that favors extremes. + StarRating = SpeedStars + AimStars + Math.abs(SpeedStars - AimStars) * EXTREME_SCALING_FACTOR; + // Another approach to this would be taking Speed and Aim separately to a chosen power, which again would be equivalent. This would be more convenient if + // the hit window size is to be considered as well. + + // Note: The star rating is tuned extremely tight! Airman (/b/104229) and Freedom Dive (/b/126645), two of the hardest ranked maps, both score ~4.66 stars. + // Expect the easier kind of maps that officially get 5 stars to obtain around 2 by this metric. The tutorial still scores about half a star. + // Tune by yourself as you please. ;) + System.out.println("Total star rating: " + StarRating); + } + + public double getAimDifficulty() { + return AimDifficulty; + } + + public double getSpeedStars() { + return SpeedStars; + } + + public double getAimStars() { + return AimStars; + } + + public double getStarRating() { + return StarRating; + } + + public double getSpeedDifficulty() { + return SpeedDifficulty; + } } diff --git a/src/test/tpdifficulty/tp/DifficultyType.java b/src/test/tpdifficulty/tp/DifficultyType.java index 1dbbaec6..c640e9f7 100644 --- a/src/test/tpdifficulty/tp/DifficultyType.java +++ b/src/test/tpdifficulty/tp/DifficultyType.java @@ -4,15 +4,15 @@ * Created by Fuuko on 2015/5/30. */ public enum DifficultyType { - Speed(0), - Aim(1); - private int value = 0; + Speed(0), + Aim(1); + private int value = 0; - DifficultyType(int value) { - this.value = value; - } + DifficultyType(int value) { + this.value = value; + } - public int value() { - return this.value; - } + public int value() { + return this.value; + } } diff --git a/src/test/tpdifficulty/tp/tpHitObject.java b/src/test/tpdifficulty/tp/tpHitObject.java index 73017731..c9184fe7 100644 --- a/src/test/tpdifficulty/tp/tpHitObject.java +++ b/src/test/tpdifficulty/tp/tpHitObject.java @@ -10,249 +10,249 @@ * Created by Fuuko on 2015/5/30. */ public class tpHitObject implements Comparable { - // Factor by how much speed / aim strain decays per second. Those values are results of tweaking a lot and taking into account general feedback. - public static double[] DECAY_BASE = {0.3, 0.15}; // Opinionated observation: Speed is easier to maintain than accurate jumps. - - private static double ALMOST_DIAMETER = 90; // Almost the normed diameter of a circle (104 osu pixel). That is -after- position transforming. - - // Pseudo threshold values to distinguish between "singles" and "streams". Of course the border can not be defined clearly, therefore the algorithm - // has a smooth transition between those values. They also are based on tweaking and general feedback. - private static double STREAM_SPACING_TRESHOLD = 110; - private static double SINGLE_SPACING_TRESHOLD = 125; - - // Scaling values for weightings to keep aim and speed difficulty in balance. Found from testing a very large map pool (containing all ranked maps) and keeping the - // average values the same. - private static double[] SPACING_WEIGHT_SCALING = {1400, 26.25}; - - // In milliseconds. The smaller the value, the more accurate sliders are approximated. 0 leads to an infinite loop, so use something bigger. - private static int LAZY_SLIDER_STEP_LENGTH = 1; - public HitObject BaseHitObject; - public double[] Strains = {0, 0}; - private PointF NormalizedStartPosition; - private PointF NormalizedEndPosition; - private float LazySliderLengthFirst = 0; - private float LazySliderLengthSubsequent = 0; - public double delta_time = 0.0; - public double d_distance = 0.0; - public double angle = 0.0; - - private final static double MIN_SPEED_BONUS = 75.0; // ~200BPM - private final static double MAX_SPEED_BONUS = 45.0; // ~330BPM - private final static double ANGLE_BONUS_SCALE = 90.0; - private final static double AIM_TIMING_THRESHOLD = 107; - private final static double SPEED_ANGLE_BONUS_BEGIN = 5 * Math.PI / 6; //if angle < this, buff speed - private final static double AIM_ANGLE_BONUS_BEGIN = Math.PI / 3; //if angle > this, buff aim - private final static double CIRCLESIZE_BUFF_THRESHOLD = 30.0; - private final static double SPEED_BALANCING_FACTOR = 40; - - public tpHitObject(HitObject BaseHitObject, float CircleRadius) { - this.BaseHitObject = BaseHitObject; - - // We will scale everything by this factor, so we can assume a uniform CircleSize among beatmaps. - float ScalingFactor = (52.0f / CircleRadius); - if (CircleRadius < CIRCLESIZE_BUFF_THRESHOLD) - { - ScalingFactor *= 1.0 + - Math.min(CIRCLESIZE_BUFF_THRESHOLD - CircleRadius, 5.0) / 50.0; - } - NormalizedStartPosition = new PointF(BaseHitObject.getPos().x * ScalingFactor, BaseHitObject.getPos().y * ScalingFactor); - if (BaseHitObject.getType() == HitObjectType.Slider) { - PointF endPos = ((Slider) BaseHitObject).getCurvePoints().get(((Slider) BaseHitObject).getCurvePoints().size() - 1); - NormalizedEndPosition = new PointF(endPos.x * ScalingFactor, endPos.y * ScalingFactor); - - float approxFollowCircleRadius = CircleRadius * 3; - float sliderLength = (float)Math.sqrt(Math.pow((NormalizedStartPosition.x - NormalizedEndPosition.x), 2) + - Math.pow((NormalizedStartPosition.y - NormalizedEndPosition.y), 2)); - if(sliderLength > approxFollowCircleRadius){ - LazySliderLengthFirst = sliderLength - approxFollowCircleRadius; - } - if(sliderLength > approxFollowCircleRadius * 2){ - LazySliderLengthSubsequent = sliderLength - approxFollowCircleRadius * 2; - } - } else { - NormalizedEndPosition = new PointF(BaseHitObject.getPos().x * ScalingFactor, BaseHitObject.getPos().y * ScalingFactor); - } - } - - public PointF getNormPosStart(){ - return NormalizedStartPosition; - } - - public PointF getNormPosEnd(){ - return NormalizedEndPosition; - } - - // Caution: The subjective values are strong with this one - // private static double SpacingWeight(double distance, DifficultyType Type) { - - // switch (Type) { - // case Speed: - - // { - // double Weight; - - // if (distance > SINGLE_SPACING_TRESHOLD) { - // Weight = 2.5; - // } else if (distance > STREAM_SPACING_TRESHOLD) { - // Weight = 1.6 + 0.9 * (distance - STREAM_SPACING_TRESHOLD) / (SINGLE_SPACING_TRESHOLD - STREAM_SPACING_TRESHOLD); - // } else if (distance > ALMOST_DIAMETER) { - // Weight = 1.2 + 0.4 * (distance - ALMOST_DIAMETER) / (STREAM_SPACING_TRESHOLD - ALMOST_DIAMETER); - // } else if (distance > ALMOST_DIAMETER / 2) { - // Weight = 0.95 + 0.25 * (distance - (ALMOST_DIAMETER / 2)) / (ALMOST_DIAMETER / 2); - // } else { - // Weight = 0.95; - // } - - // return Weight; - // } - - - // case Aim: - - // return Math.pow(distance, 0.99); - - - // // Should never happen. - // default: - // return 0; - // } - // } - - public void CalculateStrains(tpHitObject PreviousHitObject) { - CalculateSpecificStrain(PreviousHitObject, DifficultyType.Speed); - CalculateSpecificStrain(PreviousHitObject, DifficultyType.Aim); - } - - private void CalculateSpecificStrain(tpHitObject PreviousHitObject, DifficultyType Type) { - double Addition = 0; - double TimeElapsed = BaseHitObject.getStartTime() - PreviousHitObject.BaseHitObject.getStartTime(); - double Decay = Math.pow(DECAY_BASE[Type.value()], TimeElapsed / 1000); - double Distance = DistanceTo(PreviousHitObject); - delta_time = TimeElapsed; - if (BaseHitObject.getType() == HitObjectType.Spinner) { - // Do nothing for spinners - } else if (BaseHitObject.getType() == HitObjectType.Slider) { - d_distance = Distance; - switch (Type) { - case Speed: - // For speed strain we treat the whole slider as a single spacing entity, since "Speed" is about how hard it is to click buttons fast. - // The spacing weight exists to differentiate between being able to easily alternate or having to single. - // Addition = - // SpacingWeight(PreviousHitObject.LazySliderLengthFirst + - // PreviousHitObject.LazySliderLengthSubsequent * PreviousHitObject.BaseHitObject.getRepeat() + - // Distance, Type) * - // SPACING_WEIGHT_SCALING[Type.value()]; - Distance += PreviousHitObject.LazySliderLengthFirst + - PreviousHitObject.LazySliderLengthSubsequent * PreviousHitObject.BaseHitObject.getRepeat(); - Addition = d_spacing_weight(Type, Distance, TimeElapsed, PreviousHitObject.d_distance, PreviousHitObject.delta_time, angle); - Addition *= SPACING_WEIGHT_SCALING[Type.value()]; - break; - - - case Aim: - // For Aim strain we treat each slider segment and the jump after the end of the slider as separate jumps, since movement-wise there is no difference - // to multiple jumps. - // Addition = - // ( - // SpacingWeight(PreviousHitObject.LazySliderLengthFirst, Type) + - // SpacingWeight(PreviousHitObject.LazySliderLengthSubsequent, Type) * PreviousHitObject.BaseHitObject.getRepeat() + - // SpacingWeight(Distance, Type) - // ) * - // SPACING_WEIGHT_SCALING[Type.value()]; - Addition = d_spacing_weight(Type, Distance, TimeElapsed, PreviousHitObject.d_distance, PreviousHitObject.delta_time, angle); - Addition += d_spacing_weight(Type, PreviousHitObject.LazySliderLengthFirst, TimeElapsed, PreviousHitObject.d_distance, PreviousHitObject.delta_time, angle); - Addition += d_spacing_weight(Type, PreviousHitObject.LazySliderLengthSubsequent, TimeElapsed, PreviousHitObject.d_distance, PreviousHitObject.delta_time, angle) * PreviousHitObject.BaseHitObject.getRepeat(); - Addition *= SPACING_WEIGHT_SCALING[Type.value()]; - break; - } - - } else if (BaseHitObject.getType() == HitObjectType.Normal) { - d_distance = Distance; - Addition = d_spacing_weight(Type, Distance, TimeElapsed, PreviousHitObject.d_distance, PreviousHitObject.delta_time, angle); - Addition *= SPACING_WEIGHT_SCALING[Type.value()]; - //Addition = SpacingWeight(DistanceTo(PreviousHitObject), Type) * SPACING_WEIGHT_SCALING[Type.value()]; - } - - // Scale addition by the time, that elapsed. Filter out HitObjects that are too close to be played anyway to avoid crazy values by division through close to zero. - // You will never find maps that require this amongst ranked maps. - // but it works in d_spacing_weight(), so i use // - // Addition /= Math.max(TimeElapsed, 50); - - Strains[Type.value()] = PreviousHitObject.Strains[Type.value()] * Decay + Addition; - } - - public double DistanceTo(tpHitObject other) { - // Scale the distance by circle size. - return Math.sqrt(Math.pow((NormalizedStartPosition.x - other.NormalizedEndPosition.x), 2) + - Math.pow((NormalizedStartPosition.y - other.NormalizedEndPosition.y), 2)); - } - - public int compareTo(tpHitObject o1) { - return this.BaseHitObject.getStartTime() - o1.BaseHitObject.getStartTime(); - } - - //this method is Copy from https://github.com/Francesco149/koohii - private double d_spacing_weight(DifficultyType type, double distance, double delta_time, - double prev_distance, double prev_delta_time, double angle) - { - double strain_time = Math.max(delta_time, 50.0); - double prev_strain_time = Math.max(prev_delta_time, 50.0); - double angle_bonus; - switch (type) - { - case Aim: { - double result = 0.0; - if (!Double.isNaN(angle) && angle > AIM_ANGLE_BONUS_BEGIN) { - angle_bonus = Math.sqrt( - Math.max(prev_distance - ANGLE_BONUS_SCALE, 0.0) * - Math.pow(Math.sin(angle - AIM_ANGLE_BONUS_BEGIN), 2.0) * - Math.max(distance - ANGLE_BONUS_SCALE, 0.0) - ); - result = ( - 1.5 * Math.pow(Math.max(0.0, angle_bonus), 0.99) / - Math.max(AIM_TIMING_THRESHOLD, prev_strain_time) - ); - } - double weighted_distance = Math.pow(distance, 0.99); - return Math.max(result + - weighted_distance / - Math.max(AIM_TIMING_THRESHOLD, strain_time), - weighted_distance / strain_time); - } - - case Speed: { - distance = Math.min(distance, SINGLE_SPACING_TRESHOLD); - delta_time = Math.max(delta_time, MAX_SPEED_BONUS); - double speed_bonus = 1.0; - if (delta_time < MIN_SPEED_BONUS) { - speed_bonus += - Math.pow((MIN_SPEED_BONUS - delta_time) / SPEED_BALANCING_FACTOR, 2); - } - angle_bonus = 1.0; - if (!Double.isNaN(angle) && angle < SPEED_ANGLE_BONUS_BEGIN) { - double s = Math.sin(1.5 * (SPEED_ANGLE_BONUS_BEGIN - angle)); - angle_bonus += Math.pow(s, 2) / 3.57; - if (angle < Math.PI / 2.0) { - angle_bonus = 1.28; - if (distance < ANGLE_BONUS_SCALE && angle < Math.PI / 4.0) { - angle_bonus += (1.0 - angle_bonus) * - Math.min((ANGLE_BONUS_SCALE - distance) / 10.0, 1.0); - } else if (distance < ANGLE_BONUS_SCALE) { - angle_bonus += (1.0 - angle_bonus) * - Math.min((ANGLE_BONUS_SCALE - distance) / 10.0, 1.0) * - Math.sin((Math.PI / 2.0 - angle) * 4.0 / Math.PI); - } - } - } - return ((1 + (speed_bonus - 1) * 0.75) * angle_bonus * - (0.95 + speed_bonus * Math.pow(distance / SINGLE_SPACING_TRESHOLD, 3.5))) - / strain_time; - } - } - - throw new UnsupportedOperationException( - "this difficulty type does not exist" - ); - } + // Factor by how much speed / aim strain decays per second. Those values are results of tweaking a lot and taking into account general feedback. + public static double[] DECAY_BASE = {0.3, 0.15}; // Opinionated observation: Speed is easier to maintain than accurate jumps. + + private static double ALMOST_DIAMETER = 90; // Almost the normed diameter of a circle (104 osu pixel). That is -after- position transforming. + + // Pseudo threshold values to distinguish between "singles" and "streams". Of course the border can not be defined clearly, therefore the algorithm + // has a smooth transition between those values. They also are based on tweaking and general feedback. + private static double STREAM_SPACING_TRESHOLD = 110; + private static double SINGLE_SPACING_TRESHOLD = 125; + + // Scaling values for weightings to keep aim and speed difficulty in balance. Found from testing a very large map pool (containing all ranked maps) and keeping the + // average values the same. + private static double[] SPACING_WEIGHT_SCALING = {1400, 26.25}; + + // In milliseconds. The smaller the value, the more accurate sliders are approximated. 0 leads to an infinite loop, so use something bigger. + private static int LAZY_SLIDER_STEP_LENGTH = 1; + public HitObject BaseHitObject; + public double[] Strains = {0, 0}; + private PointF NormalizedStartPosition; + private PointF NormalizedEndPosition; + private float LazySliderLengthFirst = 0; + private float LazySliderLengthSubsequent = 0; + public double delta_time = 0.0; + public double d_distance = 0.0; + public double angle = 0.0; + + private final static double MIN_SPEED_BONUS = 75.0; // ~200BPM + private final static double MAX_SPEED_BONUS = 45.0; // ~330BPM + private final static double ANGLE_BONUS_SCALE = 90.0; + private final static double AIM_TIMING_THRESHOLD = 107; + private final static double SPEED_ANGLE_BONUS_BEGIN = 5 * Math.PI / 6; //if angle < this, buff speed + private final static double AIM_ANGLE_BONUS_BEGIN = Math.PI / 3; //if angle > this, buff aim + private final static double CIRCLESIZE_BUFF_THRESHOLD = 30.0; + private final static double SPEED_BALANCING_FACTOR = 40; + + public tpHitObject(HitObject BaseHitObject, float CircleRadius) { + this.BaseHitObject = BaseHitObject; + + // We will scale everything by this factor, so we can assume a uniform CircleSize among beatmaps. + float ScalingFactor = (52.0f / CircleRadius); + if (CircleRadius < CIRCLESIZE_BUFF_THRESHOLD) + { + ScalingFactor *= 1.0 + + Math.min(CIRCLESIZE_BUFF_THRESHOLD - CircleRadius, 5.0) / 50.0; + } + NormalizedStartPosition = new PointF(BaseHitObject.getPos().x * ScalingFactor, BaseHitObject.getPos().y * ScalingFactor); + if (BaseHitObject.getType() == HitObjectType.Slider) { + PointF endPos = ((Slider) BaseHitObject).getCurvePoints().get(((Slider) BaseHitObject).getCurvePoints().size() - 1); + NormalizedEndPosition = new PointF(endPos.x * ScalingFactor, endPos.y * ScalingFactor); + + float approxFollowCircleRadius = CircleRadius * 3; + float sliderLength = (float)Math.sqrt(Math.pow((NormalizedStartPosition.x - NormalizedEndPosition.x), 2) + + Math.pow((NormalizedStartPosition.y - NormalizedEndPosition.y), 2)); + if(sliderLength > approxFollowCircleRadius){ + LazySliderLengthFirst = sliderLength - approxFollowCircleRadius; + } + if(sliderLength > approxFollowCircleRadius * 2){ + LazySliderLengthSubsequent = sliderLength - approxFollowCircleRadius * 2; + } + } else { + NormalizedEndPosition = new PointF(BaseHitObject.getPos().x * ScalingFactor, BaseHitObject.getPos().y * ScalingFactor); + } + } + + public PointF getNormPosStart(){ + return NormalizedStartPosition; + } + + public PointF getNormPosEnd(){ + return NormalizedEndPosition; + } + + // Caution: The subjective values are strong with this one + // private static double SpacingWeight(double distance, DifficultyType Type) { + + // switch (Type) { + // case Speed: + + // { + // double Weight; + + // if (distance > SINGLE_SPACING_TRESHOLD) { + // Weight = 2.5; + // } else if (distance > STREAM_SPACING_TRESHOLD) { + // Weight = 1.6 + 0.9 * (distance - STREAM_SPACING_TRESHOLD) / (SINGLE_SPACING_TRESHOLD - STREAM_SPACING_TRESHOLD); + // } else if (distance > ALMOST_DIAMETER) { + // Weight = 1.2 + 0.4 * (distance - ALMOST_DIAMETER) / (STREAM_SPACING_TRESHOLD - ALMOST_DIAMETER); + // } else if (distance > ALMOST_DIAMETER / 2) { + // Weight = 0.95 + 0.25 * (distance - (ALMOST_DIAMETER / 2)) / (ALMOST_DIAMETER / 2); + // } else { + // Weight = 0.95; + // } + + // return Weight; + // } + + + // case Aim: + + // return Math.pow(distance, 0.99); + + + // // Should never happen. + // default: + // return 0; + // } + // } + + public void CalculateStrains(tpHitObject PreviousHitObject) { + CalculateSpecificStrain(PreviousHitObject, DifficultyType.Speed); + CalculateSpecificStrain(PreviousHitObject, DifficultyType.Aim); + } + + private void CalculateSpecificStrain(tpHitObject PreviousHitObject, DifficultyType Type) { + double Addition = 0; + double TimeElapsed = BaseHitObject.getStartTime() - PreviousHitObject.BaseHitObject.getStartTime(); + double Decay = Math.pow(DECAY_BASE[Type.value()], TimeElapsed / 1000); + double Distance = DistanceTo(PreviousHitObject); + delta_time = TimeElapsed; + if (BaseHitObject.getType() == HitObjectType.Spinner) { + // Do nothing for spinners + } else if (BaseHitObject.getType() == HitObjectType.Slider) { + d_distance = Distance; + switch (Type) { + case Speed: + // For speed strain we treat the whole slider as a single spacing entity, since "Speed" is about how hard it is to click buttons fast. + // The spacing weight exists to differentiate between being able to easily alternate or having to single. + // Addition = + // SpacingWeight(PreviousHitObject.LazySliderLengthFirst + + // PreviousHitObject.LazySliderLengthSubsequent * PreviousHitObject.BaseHitObject.getRepeat() + + // Distance, Type) * + // SPACING_WEIGHT_SCALING[Type.value()]; + Distance += PreviousHitObject.LazySliderLengthFirst + + PreviousHitObject.LazySliderLengthSubsequent * PreviousHitObject.BaseHitObject.getRepeat(); + Addition = d_spacing_weight(Type, Distance, TimeElapsed, PreviousHitObject.d_distance, PreviousHitObject.delta_time, angle); + Addition *= SPACING_WEIGHT_SCALING[Type.value()]; + break; + + + case Aim: + // For Aim strain we treat each slider segment and the jump after the end of the slider as separate jumps, since movement-wise there is no difference + // to multiple jumps. + // Addition = + // ( + // SpacingWeight(PreviousHitObject.LazySliderLengthFirst, Type) + + // SpacingWeight(PreviousHitObject.LazySliderLengthSubsequent, Type) * PreviousHitObject.BaseHitObject.getRepeat() + + // SpacingWeight(Distance, Type) + // ) * + // SPACING_WEIGHT_SCALING[Type.value()]; + Addition = d_spacing_weight(Type, Distance, TimeElapsed, PreviousHitObject.d_distance, PreviousHitObject.delta_time, angle); + Addition += d_spacing_weight(Type, PreviousHitObject.LazySliderLengthFirst, TimeElapsed, PreviousHitObject.d_distance, PreviousHitObject.delta_time, angle); + Addition += d_spacing_weight(Type, PreviousHitObject.LazySliderLengthSubsequent, TimeElapsed, PreviousHitObject.d_distance, PreviousHitObject.delta_time, angle) * PreviousHitObject.BaseHitObject.getRepeat(); + Addition *= SPACING_WEIGHT_SCALING[Type.value()]; + break; + } + + } else if (BaseHitObject.getType() == HitObjectType.Normal) { + d_distance = Distance; + Addition = d_spacing_weight(Type, Distance, TimeElapsed, PreviousHitObject.d_distance, PreviousHitObject.delta_time, angle); + Addition *= SPACING_WEIGHT_SCALING[Type.value()]; + //Addition = SpacingWeight(DistanceTo(PreviousHitObject), Type) * SPACING_WEIGHT_SCALING[Type.value()]; + } + + // Scale addition by the time, that elapsed. Filter out HitObjects that are too close to be played anyway to avoid crazy values by division through close to zero. + // You will never find maps that require this amongst ranked maps. + // but it works in d_spacing_weight(), so i use // + // Addition /= Math.max(TimeElapsed, 50); + + Strains[Type.value()] = PreviousHitObject.Strains[Type.value()] * Decay + Addition; + } + + public double DistanceTo(tpHitObject other) { + // Scale the distance by circle size. + return Math.sqrt(Math.pow((NormalizedStartPosition.x - other.NormalizedEndPosition.x), 2) + + Math.pow((NormalizedStartPosition.y - other.NormalizedEndPosition.y), 2)); + } + + public int compareTo(tpHitObject o1) { + return this.BaseHitObject.getStartTime() - o1.BaseHitObject.getStartTime(); + } + + //this method is Copy from https://github.com/Francesco149/koohii + private double d_spacing_weight(DifficultyType type, double distance, double delta_time, + double prev_distance, double prev_delta_time, double angle) + { + double strain_time = Math.max(delta_time, 50.0); + double prev_strain_time = Math.max(prev_delta_time, 50.0); + double angle_bonus; + switch (type) + { + case Aim: { + double result = 0.0; + if (!Double.isNaN(angle) && angle > AIM_ANGLE_BONUS_BEGIN) { + angle_bonus = Math.sqrt( + Math.max(prev_distance - ANGLE_BONUS_SCALE, 0.0) * + Math.pow(Math.sin(angle - AIM_ANGLE_BONUS_BEGIN), 2.0) * + Math.max(distance - ANGLE_BONUS_SCALE, 0.0) + ); + result = ( + 1.5 * Math.pow(Math.max(0.0, angle_bonus), 0.99) / + Math.max(AIM_TIMING_THRESHOLD, prev_strain_time) + ); + } + double weighted_distance = Math.pow(distance, 0.99); + return Math.max(result + + weighted_distance / + Math.max(AIM_TIMING_THRESHOLD, strain_time), + weighted_distance / strain_time); + } + + case Speed: { + distance = Math.min(distance, SINGLE_SPACING_TRESHOLD); + delta_time = Math.max(delta_time, MAX_SPEED_BONUS); + double speed_bonus = 1.0; + if (delta_time < MIN_SPEED_BONUS) { + speed_bonus += + Math.pow((MIN_SPEED_BONUS - delta_time) / SPEED_BALANCING_FACTOR, 2); + } + angle_bonus = 1.0; + if (!Double.isNaN(angle) && angle < SPEED_ANGLE_BONUS_BEGIN) { + double s = Math.sin(1.5 * (SPEED_ANGLE_BONUS_BEGIN - angle)); + angle_bonus += Math.pow(s, 2) / 3.57; + if (angle < Math.PI / 2.0) { + angle_bonus = 1.28; + if (distance < ANGLE_BONUS_SCALE && angle < Math.PI / 4.0) { + angle_bonus += (1.0 - angle_bonus) * + Math.min((ANGLE_BONUS_SCALE - distance) / 10.0, 1.0); + } else if (distance < ANGLE_BONUS_SCALE) { + angle_bonus += (1.0 - angle_bonus) * + Math.min((ANGLE_BONUS_SCALE - distance) / 10.0, 1.0) * + Math.sin((Math.PI / 2.0 - angle) * 4.0 / Math.PI); + } + } + } + return ((1 + (speed_bonus - 1) * 0.75) * angle_bonus * + (0.95 + speed_bonus * Math.pow(distance / SINGLE_SPACING_TRESHOLD, 3.5))) + / strain_time; + } + } + + throw new UnsupportedOperationException( + "this difficulty type does not exist" + ); + } }