code stringlengths 1 2.01M | repo_name stringlengths 3 62 | path stringlengths 1 267 | language stringclasses 231 values | license stringclasses 13 values | size int64 1 2.01M |
|---|---|---|---|---|---|
package org.anddev.andengine.util.modifier.ease;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Gil
* @author Nicolas Gramlich
* @since 16:52:11 - 26.07.2010
*/
public class EaseQuintOut implements IEaseFunction {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private static EaseQuintOut INSTANCE;
// ===========================================================
// Constructors
// ===========================================================
private EaseQuintOut() {
}
public static EaseQuintOut getInstance() {
if(INSTANCE == null) {
INSTANCE = new EaseQuintOut();
}
return INSTANCE;
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public float getPercentage(final float pSecondsElapsed, final float pDuration) {
return EaseQuintOut.getValue(pSecondsElapsed / pDuration);
}
// ===========================================================
// Methods
// ===========================================================
public static float getValue(final float pPercentage) {
final float t = pPercentage - 1;
return 1 + (t * t * t * t * t);
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/util/modifier/ease/EaseQuintOut.java | Java | lgpl | 1,845 |
package org.anddev.andengine.util.modifier.ease;
import static org.anddev.andengine.util.constants.MathConstants.PI;
import android.util.FloatMath;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Gil
* @author Nicolas Gramlich
* @since 16:52:11 - 26.07.2010
*/
public class EaseSineInOut implements IEaseFunction {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private static EaseSineInOut INSTANCE;
// ===========================================================
// Constructors
// ===========================================================
private EaseSineInOut() {
}
public static EaseSineInOut getInstance() {
if(INSTANCE == null) {
INSTANCE = new EaseSineInOut();
}
return INSTANCE;
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public float getPercentage(final float pSecondsElapsed, final float pDuration) {
final float percentage = pSecondsElapsed / pDuration;
return -0.5f * (FloatMath.cos(percentage * PI) - 1);
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/util/modifier/ease/EaseSineInOut.java | Java | lgpl | 1,871 |
package org.anddev.andengine.util.modifier.ease;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Gil
* @author Nicolas Gramlich
* @since 16:52:11 - 26.07.2010
*/
public class EaseQuintInOut implements IEaseFunction {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private static EaseQuintInOut INSTANCE;
// ===========================================================
// Constructors
// ===========================================================
private EaseQuintInOut() {
}
public static EaseQuintInOut getInstance() {
if(INSTANCE == null) {
INSTANCE = new EaseQuintInOut();
}
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 * EaseQuintIn.getValue(2 * percentage);
} else {
return 0.5f + 0.5f * EaseQuintOut.getValue(percentage * 2 - 1);
}
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/util/modifier/ease/EaseQuintInOut.java | Java | lgpl | 1,885 |
package org.anddev.andengine.util.modifier.ease;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Gil
* @author Nicolas Gramlich
* @since 16:52:11 - 26.07.2010
*/
public class EaseBackInOut implements IEaseFunction {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private static EaseBackInOut INSTANCE;
// ===========================================================
// Constructors
// ===========================================================
private EaseBackInOut() {
}
public static EaseBackInOut getInstance() {
if(INSTANCE == null) {
INSTANCE = new EaseBackInOut();
}
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 * EaseBackIn.getValue(2 * percentage);
} else {
return 0.5f + 0.5f * EaseBackOut.getValue(percentage * 2 - 1);
}
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/util/modifier/ease/EaseBackInOut.java | Java | lgpl | 1,878 |
package org.anddev.andengine.util.modifier.ease;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Gil
* @author Nicolas Gramlich
* @since 16:52:11 - 26.07.2010
*/
public class EaseExponentialIn implements IEaseFunction {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private static EaseExponentialIn INSTANCE;
// ===========================================================
// Constructors
// ===========================================================
private EaseExponentialIn() {
}
public static EaseExponentialIn getInstance() {
if(INSTANCE == null) {
INSTANCE = new EaseExponentialIn();
}
return INSTANCE;
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public float getPercentage(final float pSecondsElapsed, final float pDuration) {
return EaseExponentialIn.getValue(pSecondsElapsed / pDuration);
}
// ===========================================================
// Methods
// ===========================================================
public static float getValue(final float pPercentage) {
return (float) ((pPercentage == 0) ? 0 : Math.pow(2, 10 * (pPercentage - 1)) - 0.001f);
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/util/modifier/ease/EaseExponentialIn.java | Java | lgpl | 1,897 |
package org.anddev.andengine.util.modifier.ease;
import org.anddev.andengine.util.constants.MathConstants;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Gil
* @author Nicolas Gramlich
* @since 16:52:11 - 26.07.2010
*/
public class EaseElasticInOut implements IEaseFunction, MathConstants {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private static EaseElasticInOut INSTANCE;
// ===========================================================
// Constructors
// ===========================================================
private EaseElasticInOut() {
}
public static EaseElasticInOut getInstance() {
if(INSTANCE == null) {
INSTANCE = new EaseElasticInOut();
}
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 * EaseElasticIn.getValue(2 * pSecondsElapsed, pDuration, 2 * percentage);
} else {
return 0.5f + 0.5f * EaseElasticOut.getValue(pSecondsElapsed * 2 - pDuration, pDuration, percentage * 2 - 1);
}
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/util/modifier/ease/EaseElasticInOut.java | Java | lgpl | 2,051 |
package org.anddev.andengine.util.modifier.ease;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Gil
* @author Nicolas Gramlich
* @since 16:52:11 - 26.07.2010
*/
public class EaseQuartOut implements IEaseFunction {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private static EaseQuartOut INSTANCE;
// ===========================================================
// Constructors
// ===========================================================
private EaseQuartOut() {
}
public static EaseQuartOut getInstance() {
if(INSTANCE == null) {
INSTANCE = new EaseQuartOut();
}
return INSTANCE;
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public float getPercentage(final float pSecondsElapsed, final float pDuration) {
return EaseQuartOut.getValue(pSecondsElapsed / pDuration);
}
// ===========================================================
// Methods
// ===========================================================
public static float getValue(final float pPercentage) {
final float t = pPercentage - 1;
return 1 - (t * t * t * t);
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/util/modifier/ease/EaseQuartOut.java | Java | lgpl | 1,841 |
package org.anddev.andengine.util.modifier.ease;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Gil
* @author Nicolas Gramlich
* @since 16:52:11 - 26.07.2010
*/
public class EaseBounceIn implements IEaseFunction {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private static EaseBounceIn INSTANCE;
// ===========================================================
// Constructors
// ===========================================================
private EaseBounceIn() {
}
public static EaseBounceIn getInstance() {
if(INSTANCE == null) {
INSTANCE = new EaseBounceIn();
}
return INSTANCE;
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public float getPercentage(final float pSecondsElapsed, final float pDuration) {
return EaseBounceIn.getValue(pSecondsElapsed / pDuration);
}
// ===========================================================
// Methods
// ===========================================================
public static float getValue(final float pPercentage) {
// TODO Inline?
return 1 - EaseBounceOut.getValue(1 - pPercentage);
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/util/modifier/ease/EaseBounceIn.java | Java | lgpl | 1,848 |
package org.anddev.andengine.util.modifier.ease;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Gil
* @author Nicolas Gramlich
* @since 16:50:40 - 26.07.2010
*/
public class EaseLinear implements IEaseFunction {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private static EaseLinear INSTANCE;
// ===========================================================
// Constructors
// ===========================================================
private EaseLinear() {
}
public static EaseLinear getInstance() {
if(INSTANCE == null) {
INSTANCE = new EaseLinear();
}
return INSTANCE;
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public float getPercentage(final float pSecondsElapsed, final float pDuration) {
return pSecondsElapsed / pDuration;
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/util/modifier/ease/EaseLinear.java | Java | lgpl | 1,677 |
package org.anddev.andengine.util.modifier.ease;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Gil
* @author Nicolas Gramlich
* @since 16:52:11 - 26.07.2010
*/
public class EaseCubicOut implements IEaseFunction {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private static EaseCubicOut INSTANCE;
// ===========================================================
// Constructors
// ===========================================================
private EaseCubicOut() {
}
public static EaseCubicOut getInstance() {
if(INSTANCE == null) {
INSTANCE = new EaseCubicOut();
}
return INSTANCE;
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public float getPercentage(final float pSecondsElapsed, final float pDuration) {
return EaseCubicOut.getValue(pSecondsElapsed / pDuration);
}
// ===========================================================
// Methods
// ===========================================================
public static float getValue(final float pPercentage) {
final float t = pPercentage - 1;
return 1 + (t * t * t);
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/util/modifier/ease/EaseCubicOut.java | Java | lgpl | 1,837 |
package org.anddev.andengine.util.modifier.ease;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Gil
* @author Nicolas Gramlich
* @since 16:52:11 - 26.07.2010
*/
public class EaseBounceOut implements IEaseFunction {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private static EaseBounceOut INSTANCE;
// ===========================================================
// Constructors
// ===========================================================
private EaseBounceOut() {
}
public static EaseBounceOut getInstance() {
if(INSTANCE == null) {
INSTANCE = new EaseBounceOut();
}
return INSTANCE;
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public float getPercentage(final float pSecondsElapsed, final float pDuration) {
return EaseBounceOut.getValue(pSecondsElapsed / pDuration);
}
// ===========================================================
// 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;
}
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/util/modifier/ease/EaseBounceOut.java | Java | lgpl | 2,236 |
package org.anddev.andengine.util.modifier;
import org.anddev.andengine.util.modifier.ease.IEaseFunction;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 23:29:22 - 19.03.2010
*/
public abstract class BaseSingleValueSpanModifier<T> extends BaseDurationModifier<T> {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private final float mFromValue;
private final 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<T> pModifierListener) {
this(pDuration, pFromValue, pToValue, pModifierListener, IEaseFunction.DEFAULT);
}
public BaseSingleValueSpanModifier(final float pDuration, final float pFromValue, final float pToValue, final IModifierListener<T> pModifierListener, final IEaseFunction pEaseFunction) {
super(pDuration, pModifierListener);
this.mFromValue = pFromValue;
this.mValueSpan = pToValue - pFromValue;
this.mEaseFunction = pEaseFunction;
}
protected BaseSingleValueSpanModifier(final BaseSingleValueSpanModifier<T> 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
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/util/modifier/BaseSingleValueSpanModifier.java | Java | lgpl | 3,480 |
package org.anddev.andengine.util.modifier;
import org.anddev.andengine.util.SmartList;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 10:47:23 - 03.09.2010
* @param <T>
*/
public abstract class BaseModifier<T> implements IModifier<T> {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
protected boolean mFinished;
private boolean mRemoveWhenFinished = true;
private final SmartList<IModifierListener<T>> mModifierListeners = new SmartList<IModifierListener<T>>(2);
// ===========================================================
// Constructors
// ===========================================================
public BaseModifier() {
}
public BaseModifier(final IModifierListener<T> 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<T> pModifierListener) {
if(pModifierListener != null) {
this.mModifierListeners.add(pModifierListener);
}
}
@Override
public boolean removeModifierListener(final IModifierListener<T> pModifierListener) {
if(pModifierListener == null) {
return false;
} else {
return this.mModifierListeners.remove(pModifierListener);
}
}
@Override
public abstract IModifier<T> deepCopy() throws DeepCopyNotSupportedException;
// ===========================================================
// Methods
// ===========================================================
protected void onModifierStarted(final T pItem) {
final SmartList<IModifierListener<T>> 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<IModifierListener<T>> 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
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/util/modifier/BaseModifier.java | Java | lgpl | 3,247 |
package org.anddev.andengine.util.modifier;
/**
* (c) Zynga 2011
*
* @author Nicolas Gramlich <ngramlich@zynga.com>
* @since 14:17:30 - 10.08.2011
*/
public abstract class BaseDoubleValueChangeModifier<T> extends BaseSingleValueChangeModifier<T> {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private float mValueChangeBPerSecond;
// ===========================================================
// 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, final IModifierListener<T> pModifierListener) {
super(pDuration, pValueChangeA, pModifierListener);
this.mValueChangeBPerSecond = pValueChangeB / pDuration;
}
protected BaseDoubleValueChangeModifier(final BaseDoubleValueChangeModifier<T> pBaseDoubleValueChangeModifier) {
super(pBaseDoubleValueChangeModifier);
this.mValueChangeBPerSecond = pBaseDoubleValueChangeModifier.mValueChangeBPerSecond;
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// 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);
}
protected abstract void onChangeValues(float pSecondsElapsed, T pItem, float pValueA, float pValueB);
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/util/modifier/BaseDoubleValueChangeModifier.java | Java | lgpl | 2,371 |
package org.anddev.andengine.util.modifier;
import org.anddev.andengine.util.modifier.ease.IEaseFunction;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 10:51:46 - 03.09.2010
* @param <T>
*/
public abstract class BaseDoubleValueSpanModifier<T> extends BaseSingleValueSpanModifier<T> {
// ===========================================================
// 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<T> 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<T> pModifierListener, final IEaseFunction pEaseFunction) {
super(pDuration, pFromValueA, pToValueA, pModifierListener, pEaseFunction);
this.mFromValueB = pFromValueB;
this.mValueSpanB = pToValueB - pFromValueB;
}
protected BaseDoubleValueSpanModifier(final BaseDoubleValueSpanModifier<T> 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
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/util/modifier/BaseDoubleValueSpanModifier.java | Java | lgpl | 3,670 |
package org.anddev.andengine.util.modifier;
import org.anddev.andengine.util.modifier.ease.IEaseFunction;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 10:52:31 - 03.09.2010
* @param <T>
*/
public abstract class BaseTripleValueSpanModifier<T> extends BaseDoubleValueSpanModifier<T> {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private final float mFromValueC;
private final float mValueSpanC;
// ===========================================================
// 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 IModifierListener<T> pModifierListener, final IEaseFunction pEaseFunction) {
super(pDuration, pFromValueA, pToValueA, pFromValueB, pToValueB, pModifierListener, pEaseFunction);
this.mFromValueC = pFromValueC;
this.mValueSpanC = pToValueC - pFromValueC;
}
protected BaseTripleValueSpanModifier(final BaseTripleValueSpanModifier<T> pBaseTripleValueSpanModifier) {
super(pBaseTripleValueSpanModifier);
this.mFromValueC = pBaseTripleValueSpanModifier.mFromValueC;
this.mValueSpanC = pBaseTripleValueSpanModifier.mValueSpanC;
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// 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);
@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);
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/util/modifier/BaseTripleValueSpanModifier.java | Java | lgpl | 3,338 |
package org.anddev.andengine.util.modifier;
import java.util.Arrays;
import org.anddev.andengine.util.modifier.IModifier.IModifierListener;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 11:21:22 - 03.09.2010
* @param <T>
*/
public class ParallelModifier<T> extends BaseModifier<T> implements IModifierListener<T> {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private float mSecondsElapsed;
private final float mDuration;
private final IModifier<T>[] mModifiers;
private boolean mFinishedCached;
// ===========================================================
// Constructors
// ===========================================================
public ParallelModifier(final IModifier<T> ... pModifiers) throws IllegalArgumentException {
this(null, pModifiers);
}
public ParallelModifier(final IModifierListener<T> pModifierListener, final IModifier<T> ... 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<T> modifierWithLongestDuration = pModifiers[0];
this.mDuration = modifierWithLongestDuration.getDuration();
modifierWithLongestDuration.addModifierListener(this);
}
@SuppressWarnings("unchecked")
protected ParallelModifier(final ParallelModifier<T> pParallelModifier) throws DeepCopyNotSupportedException {
final IModifier<T>[] otherModifiers = pParallelModifier.mModifiers;
this.mModifiers = new IModifier[otherModifiers.length];
final IModifier<T>[] modifiers = this.mModifiers;
for(int i = modifiers.length - 1; i >= 0; i--) {
modifiers[i] = otherModifiers[i].deepCopy();
}
final IModifier<T> modifierWithLongestDuration = modifiers[0];
this.mDuration = modifierWithLongestDuration.getDuration();
modifierWithLongestDuration.addModifierListener(this);
}
@Override
public ParallelModifier<T> deepCopy() throws DeepCopyNotSupportedException{
return new ParallelModifier<T>(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<T>[] 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<T>[] shapeModifiers = this.mModifiers;
for(int i = shapeModifiers.length - 1; i >= 0; i--) {
shapeModifiers[i].reset();
}
}
@Override
public void onModifierStarted(final IModifier<T> pModifier, final T pItem) {
this.onModifierStarted(pItem);
}
@Override
public void onModifierFinished(final IModifier<T> pModifier, final T pItem) {
this.mFinished = true;
this.mFinishedCached = true;
this.onModifierFinished(pItem);
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/util/modifier/ParallelModifier.java | Java | lgpl | 4,648 |
package org.anddev.andengine.util.modifier;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 10:49:51 - 03.09.2010
* @param <T>
*/
public abstract class BaseSingleValueChangeModifier<T> extends BaseDurationModifier<T> {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private final float mValueChangePerSecond;
// ===========================================================
// Constructors
// ===========================================================
public BaseSingleValueChangeModifier(final float pDuration, final float pValueChange) {
this(pDuration, pValueChange, null);
}
public BaseSingleValueChangeModifier(final float pDuration, final float pValueChange, final IModifierListener<T> pModifierListener) {
super(pDuration, pModifierListener);
this.mValueChangePerSecond = pValueChange / pDuration;
}
protected BaseSingleValueChangeModifier(final BaseSingleValueChangeModifier<T> pBaseSingleValueChangeModifier) {
super(pBaseSingleValueChangeModifier);
this.mValueChangePerSecond = pBaseSingleValueChangeModifier.mValueChangePerSecond;
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
protected abstract void onChangeValue(final float pSecondsElapsed, final T pItem, final float pValue);
@Override
protected void onManagedInitialize(final T pItem) {
}
@Override
protected void onManagedUpdate(final float pSecondsElapsed, final T pItem) {
this.onChangeValue(pSecondsElapsed, pItem, this.mValueChangePerSecond * pSecondsElapsed);
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/util/modifier/BaseSingleValueChangeModifier.java | Java | lgpl | 2,409 |
package org.anddev.andengine.util;
import org.anddev.andengine.util.constants.DataConstants;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 15:01:49 - 20.03.2011
*/
public class DataUtils implements DataConstants {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
public static int unsignedByteToInt(final byte bByte) {
return bByte & 0xFF;
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/util/DataUtils.java | Java | lgpl | 1,451 |
package org.anddev.andengine.util;
import org.anddev.andengine.util.constants.TimeConstants;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @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
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/util/TimeUtils.java | Java | lgpl | 1,922 |
package org.anddev.andengine.util;
import java.util.ArrayList;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 12:43:39 - 11.03.2010
*/
public class ListUtils {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
public static <T> ArrayList<? extends T> toList(final T pItem) {
final ArrayList<T> out = new ArrayList<T>();
out.add(pItem);
return out;
}
public static <T> ArrayList<? extends T> toList(final T ... pItems) {
final ArrayList<T> out = new ArrayList<T>();
final int itemCount = pItems.length;
for(int i = 0; i < itemCount; i++) {
out.add(pItems[i]);
}
return out;
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/util/ListUtils.java | Java | lgpl | 1,713 |
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.anddev.andengine.util;
import java.io.UnsupportedEncodingException;
/**
* Utilities for encoding and decoding the Base64 representation of
* binary data. See RFCs <a
* href="http://www.ietf.org/rfc/rfc2045.txt">2045</a> and <a
* href="http://www.ietf.org/rfc/rfc3548.txt">3548</a>.
*/
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.
*
* <p>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.
*
* <p>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.
*
* <p>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
* <a href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045</a>).
*/
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
}
| zzy421-andengine | src/org/anddev/andengine/util/Base64.java | Java | lgpl | 24,366 |
package org.anddev.andengine.util;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import org.anddev.andengine.util.Debug;
/**
* (c) Zynga 2011
*
* @author Nicolas Gramlich <ngramlich@zynga.com>
* @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
// ===========================================================
} | zzy421-andengine | src/org/anddev/andengine/util/ByteBufferOutputStream.java | Java | lgpl | 2,923 |
package org.anddev.andengine.util;
import android.app.Dialog;
import android.view.WindowManager;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 13:04:09 - 12.05.2011
*/
public class DialogUtils {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
public static void keepScreenOn(final Dialog pDialog) {
pDialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/util/DialogUtils.java | Java | lgpl | 1,490 |
package org.anddev.andengine.util;
import org.xml.sax.Attributes;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 22:02:09 - 21.07.2010
*/
public class SAXUtils {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// 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 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 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 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 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 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 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 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 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 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 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 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 String pValue) {
pStringBuilder.append(' ').append(pName).append('=').append('\"').append(pValue).append('\"');
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/util/SAXUtils.java | Java | lgpl | 6,789 |
package org.anddev.andengine.util;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 15:00:30 - 14.05.2010
* @param <T>
*/
public interface AsyncCallable<T> {
// ===========================================================
// Final Fields
// ===========================================================
// ===========================================================
// 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<T> pCallback, final Callback<Exception> pExceptionCallback);
} | zzy421-andengine | src/org/anddev/andengine/util/AsyncCallable.java | Java | lgpl | 924 |
package org.anddev.andengine.util;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.util.Scanner;
import java.util.regex.MatchResult;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Build;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @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);
}
}
}
| zzy421-andengine | src/org/anddev/andengine/util/SystemUtils.java | Java | lgpl | 7,666 |
package org.anddev.andengine.util;
import java.util.ArrayList;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 16:54:24 - 07.11.2010
*/
public class ProbabilityGenerator<T> {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private float mProbabilitySum;
private final ArrayList<Entry<T>> mEntries = new ArrayList<Entry<T>>();
// ===========================================================
// 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<T>(pFactor, pElements));
}
public T next() {
float random = MathUtils.random(0, this.mProbabilitySum);
final ArrayList<Entry<T>> factors = this.mEntries;
for(int i = factors.size() - 1; i >= 0; i--){
final Entry<T> entry = factors.get(i);
random -= entry.mFactor;
if(random <= 0){
return entry.getReturnValue();
}
}
final Entry<T> 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<T> {
// ===========================================================
// 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
// ===========================================================
}
}
| zzy421-andengine | src/org/anddev/andengine/util/ProbabilityGenerator.java | Java | lgpl | 3,579 |
package org.anddev.andengine.util;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 09:40:55 - 14.12.2009S
*/
public interface Callback<T> {
// ===========================================================
// Final Fields
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
public void onCallback(final T pCallbackValue);
} | zzy421-andengine | src/org/anddev/andengine/util/Callback.java | Java | lgpl | 549 |
package org.anddev.andengine.util.progress;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @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);
}
}
}
| zzy421-andengine | src/org/anddev/andengine/util/progress/ProgressMonitor.java | Java | lgpl | 2,631 |
package org.anddev.andengine.util.progress;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 20:52:44 - 03.01.2010
*/
public interface ProgressCallable<T> {
// ===========================================================
// Final Fields
// ===========================================================
// ===========================================================
// 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;
} | zzy421-andengine | src/org/anddev/andengine/util/progress/ProgressCallable.java | Java | lgpl | 785 |
package org.anddev.andengine.util.progress;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 18:07:35 - 09.07.2009
*/
public interface IProgressListener {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
/**
* @param pProgress between 0 and 100.
*/
public void onProgressChanged(final int pProgress);
} | zzy421-andengine | src/org/anddev/andengine/util/progress/IProgressListener.java | Java | lgpl | 617 |
package org.anddev.andengine.util;
import java.util.Random;
import org.anddev.andengine.util.constants.MathConstants;
import android.util.FloatMath;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 20:42:15 - 17.12.2009
*/
public class MathUtils implements MathConstants {
// ===========================================================
// Constants
// ===========================================================
public static 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 = FloatMath.sin(rotationRad);
final float cosRotationInRad = FloatMath.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 FloatMath.sqrt((dX * dX) + (dY * dY));
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/util/MathUtils.java | Java | lgpl | 7,467 |
package org.anddev.andengine.util;
import java.util.HashMap;
import java.util.Iterator;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 16:54:24 - 07.11.2010
*/
public class MultiKeyHashMap<K, V> extends HashMap<MultiKey<K>, V> {
// ===========================================================
// Constants
// ==========================================================
private static final long serialVersionUID = -6262447639526561122L;
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
public V get(final K ... pKeys) {
final int hashCode = MultiKey.hash(pKeys);
final Iterator<Entry<MultiKey<K>, V>> it = this.entrySet().iterator();
while(it.hasNext()) {
final Entry<MultiKey<K>, V> entry = it.next();
final MultiKey<K> entryKey = entry.getKey();
if (entryKey.hashCode() == hashCode && this.isEqualKey(entryKey.getKeys(), pKeys)) {
return entry.getValue();
}
}
return null;
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// 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;
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/util/MultiKeyHashMap.java | Java | lgpl | 2,322 |
package org.anddev.andengine.util;
import java.util.GregorianCalendar;
import org.anddev.andengine.util.constants.Constants;
import android.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.SharedPreferences;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @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
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/util/BetaUtils.java | Java | lgpl | 3,617 |
package org.anddev.andengine.util.constants;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 17:59:55 - 14.07.2011
*/
public interface DataConstants {
// ===========================================================
// Final Fields
// ===========================================================
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_KILOBYTE = 1024;
public static final int BYTES_PER_MEGABYTE = 1024 * DataConstants.BYTES_PER_KILOBYTE;
// ===========================================================
// Methods
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/util/constants/DataConstants.java | Java | lgpl | 1,020 |
package org.anddev.andengine.util.constants;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 14:58:20 - 10.01.2011
*/
public interface MIMETypes {
// ===========================================================
// Final Fields
// ===========================================================
public static final String JPEG = "image/jpeg";
public static final String GIF = "image/gif";
public static final String PNG = "image/png";
// ===========================================================
// Methods
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/util/constants/MIMETypes.java | Java | lgpl | 654 |
package org.anddev.andengine.util.constants;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 16:49:25 - 26.07.2010
*/
public interface TimeConstants {
// ===========================================================
// Final Fields
// ===========================================================
public static final int MONTHSPERYEAR = 12;
public static final int DAYSPERWEEK = 7;
public static final int DAYSPERMONTH = 30;
public static final int HOURSPERDAY = 24;
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 long MICROSECONDSPERMILLISECOND = MICROSECONDSPERSECOND / 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
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/util/constants/TimeConstants.java | Java | lgpl | 1,892 |
package org.anddev.andengine.util.constants;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 10:21:46 - 19.07.2010
*/
public interface ColorConstants {
// ===========================================================
// Final Fields
// ===========================================================
public static final float COLOR_FACTOR_INT_TO_FLOAT = 255.0f;
// ===========================================================
// Methods
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/util/constants/ColorConstants.java | Java | lgpl | 577 |
package org.anddev.andengine.util.constants;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 16:49:25 - 26.07.2010
*/
public interface MathConstants {
// ===========================================================
// Final Fields
// ===========================================================
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 final float DEG_TO_RAD = PI / 180.0f;
public static final float RAD_TO_DEG = 180.0f / PI;
// ===========================================================
// Methods
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/util/constants/MathConstants.java | Java | lgpl | 761 |
package org.anddev.andengine.util.constants;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 13:52:21 - 08.03.2010
*/
public interface Constants {
// ===========================================================
// Final Fields
// ===========================================================
public static final String DEBUGTAG = "AndEngine";
public static final int VERTEX_INDEX_X = 0;
public static final int VERTEX_INDEX_Y = 1;
// ===========================================================
// Methods
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/util/constants/Constants.java | Java | lgpl | 655 |
package org.anddev.andengine.util;
import org.anddev.andengine.util.constants.Constants;
import android.util.Log;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @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) {
Debug.v(pMessage, null);
}
public static void v(final String pMessage, final Throwable pThrowable) {
if(sDebugLevel.isSameOrLessThan(DebugLevel.VERBOSE)) {
Log.v(sDebugTag, pMessage, pThrowable);
}
}
public static void d(final String pMessage) {
Debug.d(pMessage, null);
}
public static void d(final String pMessage, final Throwable pThrowable) {
if(sDebugLevel.isSameOrLessThan(DebugLevel.DEBUG)) {
Log.d(sDebugTag, pMessage, pThrowable);
}
}
public static void i(final String pMessage) {
Debug.i(pMessage, null);
}
public static void i(final String pMessage, final Throwable pThrowable) {
if(sDebugLevel.isSameOrLessThan(DebugLevel.INFO)) {
Log.i(sDebugTag, pMessage, pThrowable);
}
}
public static void w(final String pMessage) {
Debug.w(pMessage, null);
}
public static void w(final Throwable pThrowable) {
Debug.w("", pThrowable);
}
public static void w(final String pMessage, final Throwable pThrowable) {
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) {
Debug.e(pMessage, null);
}
public static void e(final Throwable pThrowable) {
Debug.e(sDebugTag, pThrowable);
}
public static void e(final String pMessage, final Throwable pThrowable) {
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<DebugLevel> {
NONE,
ERROR,
WARNING,
INFO,
DEBUG,
VERBOSE;
public static DebugLevel ALL = DebugLevel.VERBOSE;
private boolean isSameOrLessThan(final DebugLevel pDebugLevel) {
return this.compareTo(pDebugLevel) >= 0;
}
}
}
| zzy421-andengine | src/org/anddev/andengine/util/Debug.java | Java | lgpl | 3,993 |
package org.anddev.andengine.util;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 23:40:42 - 27.12.2010
*/
public interface ParameterCallable<T> {
// ===========================================================
// Final Fields
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
public void call(final T pParameter);
} | zzy421-andengine | src/org/anddev/andengine/util/ParameterCallable.java | Java | lgpl | 547 |
package org.anddev.andengine.util;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 12:32:22 - 26.12.2010
*/
public interface IMatcher<T> {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
public boolean matches(final T pObject);
}
| zzy421-andengine | src/org/anddev/andengine/util/IMatcher.java | Java | lgpl | 542 |
package org.anddev.andengine.util;
import java.util.Arrays;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 16:54:24 - 07.11.2010
*/
public class MultiKey<K> {
// ===========================================================
// 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
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/util/MultiKey.java | Java | lgpl | 2,256 |
package org.anddev.andengine.input.touch.detector;
import org.anddev.andengine.input.touch.TouchEvent;
import android.view.MotionEvent;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @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);
}
}
| zzy421-andengine | src/org/anddev/andengine/input/touch/detector/ClickDetector.java | Java | lgpl | 3,508 |
package org.anddev.andengine.input.touch.detector;
import org.anddev.andengine.entity.scene.Scene;
import org.anddev.andengine.entity.scene.Scene.IOnSceneTouchListener;
import org.anddev.andengine.input.touch.TouchEvent;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 15:59:00 - 05.11.2010
*/
public abstract class BaseDetector implements IOnSceneTouchListener {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private boolean mEnabled = true;
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
public boolean isEnabled() {
return this.mEnabled;
}
public void setEnabled(final boolean pEnabled) {
this.mEnabled = pEnabled;
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
protected abstract boolean onManagedTouchEvent(TouchEvent 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;
}
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/input/touch/detector/BaseDetector.java | Java | lgpl | 2,128 |
package org.anddev.andengine.input.touch.detector;
import org.anddev.andengine.input.touch.TouchEvent;
import android.view.MotionEvent;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @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);
}
}
| zzy421-andengine | src/org/anddev/andengine/input/touch/detector/ScrollDetector.java | Java | lgpl | 4,098 |
package org.anddev.andengine.input.touch.detector;
import org.anddev.andengine.input.touch.TouchEvent;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.MotionEvent;
/**
* @author rkpost
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @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
// ===========================================================
}
} | zzy421-andengine | src/org/anddev/andengine/input/touch/detector/SurfaceGestureDetector.java | Java | lgpl | 6,393 |
package org.anddev.andengine.input.touch.detector;
import org.anddev.andengine.input.touch.TouchEvent;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @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
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/input/touch/detector/SurfaceScrollDetector.java | Java | lgpl | 1,955 |
package org.anddev.andengine.input.touch.detector;
import org.anddev.andengine.engine.handler.IUpdateHandler;
import org.anddev.andengine.engine.handler.timer.ITimerCallback;
import org.anddev.andengine.engine.handler.timer.TimerHandler;
import org.anddev.andengine.entity.scene.Scene;
import org.anddev.andengine.input.touch.TouchEvent;
import android.os.SystemClock;
import android.view.MotionEvent;
/**
* Note: Needs to be registered as an {@link IUpdateHandler} to the {@link Engine} or {@link Scene} to work properly.
*
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 20:49:25 - 23.08.2010
*/
public class HoldDetector extends BaseDetector implements IUpdateHandler {
// ===========================================================
// Constants
// ===========================================================
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;
// ===========================================================
// 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);
}
}
| zzy421-andengine | src/org/anddev/andengine/input/touch/detector/HoldDetector.java | Java | lgpl | 7,317 |
package org.anddev.andengine.input.touch.controller;
import org.anddev.andengine.engine.options.TouchOptions;
import org.anddev.andengine.input.touch.TouchEvent;
import org.anddev.andengine.util.pool.RunnablePoolItem;
import org.anddev.andengine.util.pool.RunnablePoolUpdateHandler;
import android.view.MotionEvent;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 21:06:40 - 13.07.2010
*/
public abstract class BaseTouchController implements ITouchController {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private ITouchEventCallback mTouchEventCallback;
private boolean mRunOnUpdateThread;
private final RunnablePoolUpdateHandler<TouchEventRunnablePoolItem> mTouchEventRunnablePoolUpdateHandler = new RunnablePoolUpdateHandler<TouchEventRunnablePoolItem>() {
@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();
}
}
}
| zzy421-andengine | src/org/anddev/andengine/input/touch/controller/BaseTouchController.java | Java | lgpl | 4,512 |
package org.anddev.andengine.input.touch.controller;
import android.view.MotionEvent;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 20:23:33 - 13.07.2010
*/
public class SingleTouchControler extends BaseTouchController {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
public SingleTouchControler() {
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public boolean onHandleMotionEvent(final MotionEvent pMotionEvent) {
return this.fireTouchEvent(pMotionEvent.getX(), pMotionEvent.getY(), pMotionEvent.getAction(), 0, pMotionEvent);
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/input/touch/controller/SingleTouchControler.java | Java | lgpl | 1,617 |
package org.anddev.andengine.input.touch.controller;
import org.anddev.andengine.engine.handler.IUpdateHandler;
import org.anddev.andengine.engine.options.TouchOptions;
import org.anddev.andengine.input.touch.TouchEvent;
import android.view.MotionEvent;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 20:23:45 - 13.07.2010
*/
public interface ITouchController extends IUpdateHandler {
// ===========================================================
// Final Fields
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
public void setTouchEventCallback(final ITouchEventCallback pTouchEventCallback);
public void applyTouchOptions(final TouchOptions pTouchOptions);
public boolean onHandleMotionEvent(final MotionEvent pMotionEvent);
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
static interface ITouchEventCallback {
public boolean onTouchEvent(final TouchEvent pTouchEvent);
}
}
| zzy421-andengine | src/org/anddev/andengine/input/touch/controller/ITouchController.java | Java | lgpl | 1,254 |
package org.anddev.andengine.input.touch;
import org.anddev.andengine.util.pool.GenericPool;
import android.view.MotionEvent;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @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<TouchEvent> {
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
protected TouchEvent onAllocatePoolItem() {
return new TouchEvent();
}
}
}
| zzy421-andengine | src/org/anddev/andengine/input/touch/TouchEvent.java | Java | lgpl | 4,189 |
package org.anddev.andengine.engine;
import javax.microedition.khronos.opengles.GL10;
import org.anddev.andengine.engine.camera.Camera;
import org.anddev.andengine.engine.options.EngineOptions;
import org.anddev.andengine.entity.scene.Scene;
import org.anddev.andengine.input.touch.TouchEvent;
import org.anddev.andengine.opengl.util.GLHelper;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @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
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/engine/DoubleSceneSplitScreenEngine.java | Java | lgpl | 5,353 |
package org.anddev.andengine.engine;
import org.anddev.andengine.engine.options.EngineOptions;
/**
* A subclass of {@link Engine} that tries to achieve a specific amount of
* updates per second. When the time since the last update is bigger long the
* steplength, additional updates are executed.
*
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 10:17:47 - 02.08.2010
*/
public class LimitedFPSEngine extends Engine {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private final long mPreferredFrameLengthNanoseconds;
// ===========================================================
// Constructors
// ===========================================================
public LimitedFPSEngine(final EngineOptions pEngineOptions, final int pFramesPerSecond) {
super(pEngineOptions);
this.mPreferredFrameLengthNanoseconds = NANOSECONDSPERSECOND / pFramesPerSecond;
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@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);
Thread.sleep(sleepTimeMilliseconds);
super.onUpdate(pNanosecondsElapsed + deltaFrameLengthNanoseconds);
}
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/engine/LimitedFPSEngine.java | Java | lgpl | 2,444 |
package org.anddev.andengine.engine.camera;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @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;
this.mTargetCenterX = this.getCenterX();
this.mTargetCenterY = this.getCenterY();
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
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/engine/camera/SmoothCamera.java | Java | lgpl | 5,670 |
package org.anddev.andengine.engine.camera.hud.controls;
import static org.anddev.andengine.util.constants.Constants.VERTEX_INDEX_X;
import static org.anddev.andengine.util.constants.Constants.VERTEX_INDEX_Y;
import org.anddev.andengine.engine.camera.Camera;
import org.anddev.andengine.engine.camera.hud.HUD;
import org.anddev.andengine.engine.handler.timer.ITimerCallback;
import org.anddev.andengine.engine.handler.timer.TimerHandler;
import org.anddev.andengine.entity.scene.Scene;
import org.anddev.andengine.entity.scene.Scene.IOnSceneTouchListener;
import org.anddev.andengine.entity.sprite.Sprite;
import org.anddev.andengine.input.touch.TouchEvent;
import org.anddev.andengine.opengl.texture.region.TextureRegion;
import org.anddev.andengine.util.MathUtils;
import android.view.MotionEvent;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @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 <code>-0.5</code> (left) to <code>0.5</code> (right).
* @param pRelativeY from <code>-0.5</code> (top) to <code>0.5</code> (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 <code>-1</code> (left) to <code>1</code> (right).
* @param pValueY between <code>-1</code> (up) to <code>1</code> (down).
*/
public void onControlChange(final BaseOnScreenControl pBaseOnScreenControl, final float pValueX, final float pValueY);
}
}
| zzy421-andengine | src/org/anddev/andengine/engine/camera/hud/controls/BaseOnScreenControl.java | Java | lgpl | 8,064 |
package org.anddev.andengine.engine.camera.hud.controls;
import org.anddev.andengine.engine.camera.Camera;
import org.anddev.andengine.opengl.texture.region.TextureRegion;
import org.anddev.andengine.util.MathUtils;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 00:21:55 - 11.07.2010
*/
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
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/engine/camera/hud/controls/DigitalOnScreenControl.java | Java | lgpl | 4,814 |
package org.anddev.andengine.engine.camera.hud.controls;
import org.anddev.andengine.engine.camera.Camera;
import org.anddev.andengine.input.touch.TouchEvent;
import org.anddev.andengine.input.touch.detector.ClickDetector;
import org.anddev.andengine.input.touch.detector.ClickDetector.IClickDetectorListener;
import org.anddev.andengine.opengl.texture.region.TextureRegion;
import org.anddev.andengine.util.MathUtils;
import org.anddev.andengine.util.constants.TimeConstants;
import android.util.FloatMath;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @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(FloatMath.cos(angleRad) * 0.5f, FloatMath.sin(angleRad) * 0.5f);
}
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
public interface IAnalogOnScreenControlListener extends IOnScreenControlListener {
// ===========================================================
// Final Fields
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
public void onControlClick(final AnalogOnScreenControl pAnalogOnScreenControl);
}
}
| zzy421-andengine | src/org/anddev/andengine/engine/camera/hud/controls/AnalogOnScreenControl.java | Java | lgpl | 4,843 |
package org.anddev.andengine.engine.camera.hud;
import org.anddev.andengine.engine.camera.Camera;
import org.anddev.andengine.entity.scene.CameraScene;
import org.anddev.andengine.entity.scene.Scene;
/**
* While you can add a {@link HUD} to {@link Scene}, you should not do so.
* {@link HUD}s are meant to be added to {@link Camera}s via {@link Camera#setHUD(HUD)}.
*
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 14:13:13 - 01.04.2010
*/
public class HUD extends CameraScene {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
public HUD() {
super();
this.setBackgroundEnabled(false);
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/engine/camera/hud/HUD.java | Java | lgpl | 1,706 |
package org.anddev.andengine.engine.camera;
import android.content.Context;
import android.util.DisplayMetrics;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 13:50:42 - 03.07.2010
*/
public class CameraFactory {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
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);
}
private static DisplayMetrics getDisplayMetrics(final Context pContext) {
return pContext.getResources().getDisplayMetrics();
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/engine/camera/CameraFactory.java | Java | lgpl | 1,901 |
package org.anddev.andengine.engine.camera;
import static org.anddev.andengine.util.constants.Constants.VERTEX_INDEX_X;
import static org.anddev.andengine.util.constants.Constants.VERTEX_INDEX_Y;
import org.anddev.andengine.input.touch.TouchEvent;
import org.anddev.andengine.util.MathUtils;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 15:48:11 - 24.06.2010
* TODO min/max(X/Y) values could be cached and only updated once the zoomfactor/center changed.
*/
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
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/engine/camera/ZoomCamera.java | Java | lgpl | 4,651 |
package org.anddev.andengine.engine.camera;
import static org.anddev.andengine.util.constants.Constants.VERTEX_INDEX_X;
import static org.anddev.andengine.util.constants.Constants.VERTEX_INDEX_Y;
import javax.microedition.khronos.opengles.GL10;
import org.anddev.andengine.collision.RectangularShapeCollisionChecker;
import org.anddev.andengine.engine.camera.hud.HUD;
import org.anddev.andengine.engine.handler.IUpdateHandler;
import org.anddev.andengine.entity.IEntity;
import org.anddev.andengine.entity.primitive.Line;
import org.anddev.andengine.entity.shape.RectangularShape;
import org.anddev.andengine.input.touch.TouchEvent;
import org.anddev.andengine.opengl.util.GLHelper;
import org.anddev.andengine.util.MathUtils;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 10:24:18 - 25.03.2010
*/
public class Camera implements IUpdateHandler {
// ===========================================================
// Constants
// ===========================================================
protected static final float[] VERTICES_TOUCH_TMP = new float[2];
// ===========================================================
// Fields
// ===========================================================
private float mMinX;
private float mMaxX;
private float mMinY;
private float mMaxY;
private float mNearZ = -1.0f;
private float mFarZ = 1.0f;
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;
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public void onUpdate(final float pSecondsElapsed) {
if(this.mHUD != null) {
this.mHUD.onUpdate(pSecondsElapsed);
}
this.updateChaseEntity();
}
@Override
public void reset() {
}
// ===========================================================
// Methods
// ===========================================================
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 boolean isLineVisible(final Line pLine) {
return RectangularShapeCollisionChecker.isVisible(this, pLine);
}
public boolean isRectangularShapeVisible(final RectangularShape pRectangularShape) {
return RectangularShapeCollisionChecker.isVisible(this, pRectangularShape);
}
public void onApplySceneMatrix(final GL10 pGL) {
GLHelper.setProjectionIdentityMatrix(pGL);
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);
}
}
public void onApplySceneBackgroundMatrix(final GL10 pGL) {
GLHelper.setProjectionIdentityMatrix(pGL);
final float widthRaw = this.getWidthRaw();
final float heightRaw = this.getHeightRaw();
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);
}
}
public void onApplyCameraSceneMatrix(final GL10 pGL) {
GLHelper.setProjectionIdentityMatrix(pGL);
final float widthRaw = this.getWidthRaw();
final float heightRaw = this.getHeightRaw();
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);
}
}
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);
this.applySceneToCameraSceneOffset(pSceneTouchEvent);
this.applyCameraSceneRotation(pSceneTouchEvent);
}
public void convertCameraSceneToSceneTouchEvent(final TouchEvent pCameraSceneTouchEvent) {
this.unapplyCameraSceneRotation(pCameraSceneTouchEvent);
this.unapplySceneToCameraSceneOffset(pCameraSceneTouchEvent);
this.applySceneRotation(pCameraSceneTouchEvent);
}
protected void applySceneToCameraSceneOffset(final TouchEvent pSceneTouchEvent) {
pSceneTouchEvent.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();
MathUtils.rotateAroundCenter(VERTICES_TOUCH_TMP, rotation, this.getCenterX(), this.getCenterY());
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;
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());
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;
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);
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;
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);
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;
final float rotation = this.mRotation;
if(rotation == 0) {
relativeX = pSurfaceTouchEvent.getX() / pSurfaceWidth;
relativeY = pSurfaceTouchEvent.getY() / pSurfaceHeight;
} else if(rotation == 180) {
relativeX = 1 - (pSurfaceTouchEvent.getX() / pSurfaceWidth);
relativeY = 1 - (pSurfaceTouchEvent.getY() / pSurfaceHeight);
} else {
VERTICES_TOUCH_TMP[VERTEX_INDEX_X] = pSurfaceTouchEvent.getX();
VERTICES_TOUCH_TMP[VERTEX_INDEX_Y] = pSurfaceTouchEvent.getY();
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;
}
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();
final float x = minX + pRelativeX * (maxX - minX);
final float y = minY + pRelativeY * (maxY - minY);
pSurfaceTouchEvent.set(x, y);
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/engine/camera/Camera.java | Java | lgpl | 12,550 |
package org.anddev.andengine.engine.camera;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @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
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/engine/camera/BoundCamera.java | Java | lgpl | 5,183 |
package org.anddev.andengine.engine.handler.runnable;
import java.util.ArrayList;
import org.anddev.andengine.engine.handler.IUpdateHandler;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 10:24:39 - 18.06.2010
*/
public class RunnableHandler implements IUpdateHandler {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private final ArrayList<Runnable> mRunnables = new ArrayList<Runnable>();
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public synchronized void onUpdate(final float pSecondsElapsed) {
final ArrayList<Runnable> 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
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/engine/handler/runnable/RunnableHandler.java | Java | lgpl | 1,972 |
package org.anddev.andengine.engine.handler;
import org.anddev.andengine.util.SmartList;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 09:45:22 - 31.03.2010
*/
public class UpdateHandlerList extends SmartList<IUpdateHandler> implements IUpdateHandler {
// ===========================================================
// Constants
// ===========================================================
private static final long serialVersionUID = -8842562717687229277L;
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
public UpdateHandlerList() {
}
public UpdateHandlerList(final int pCapacity) {
super(pCapacity);
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// 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 reset() {
final int handlerCount = this.size();
for(int i = handlerCount - 1; i >= 0; i--) {
this.get(i).reset();
}
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/engine/handler/UpdateHandlerList.java | Java | lgpl | 1,960 |
package org.anddev.andengine.engine.handler.timer;
import org.anddev.andengine.engine.handler.IUpdateHandler;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @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
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/engine/handler/timer/TimerHandler.java | Java | lgpl | 3,303 |
package org.anddev.andengine.engine.handler.timer;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 16:23:25 - 12.03.2010
*/
public interface ITimerCallback {
// ===========================================================
// Final Fields
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
public void onTimePassed(final TimerHandler pTimerHandler);
}
| zzy421-andengine | src/org/anddev/andengine/engine/handler/timer/ITimerCallback.java | Java | lgpl | 581 |
package org.anddev.andengine.engine.handler;
import org.anddev.andengine.util.IMatcher;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 12:24:09 - 11.03.2010
*/
public interface IUpdateHandler {
// ===========================================================
// Final Fields
// ===========================================================
// ===========================================================
// 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)
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
public interface IUpdateHandlerMatcher extends IMatcher<IUpdateHandler> {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
}
}
| zzy421-andengine | src/org/anddev/andengine/engine/handler/IUpdateHandler.java | Java | lgpl | 1,305 |
package org.anddev.andengine.engine.handler.collision;
import java.util.ArrayList;
import org.anddev.andengine.engine.handler.IUpdateHandler;
import org.anddev.andengine.entity.shape.IShape;
import org.anddev.andengine.util.ListUtils;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @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<? extends IShape> 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<? extends IShape> 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<? extends IShape> 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
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/engine/handler/collision/CollisionHandler.java | Java | lgpl | 3,171 |
package org.anddev.andengine.engine.handler.collision;
import org.anddev.andengine.entity.shape.IShape;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 12:05:39 - 11.03.2010
*/
public interface ICollisionCallback {
// ===========================================================
// Final Fields
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
/**
* @param pCheckShape
* @param pTargetShape
* @return <code>true</code> to proceed, <code>false</code> to stop further collosion-checks.
*/
public boolean onCollision(final IShape pCheckShape, final IShape pTargetShape);
}
| zzy421-andengine | src/org/anddev/andengine/engine/handler/collision/ICollisionCallback.java | Java | lgpl | 819 |
package org.anddev.andengine.engine.handler;
import org.anddev.andengine.entity.IEntity;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 14:00:25 - 24.12.2010
*/
public abstract class BaseEntityUpdateHandler implements IUpdateHandler {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private final IEntity mEntity;
// ===========================================================
// Constructors
// ===========================================================
public BaseEntityUpdateHandler(final IEntity pEntity) {
this.mEntity = pEntity;
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
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 void reset() {
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/engine/handler/BaseEntityUpdateHandler.java | Java | lgpl | 1,770 |
package org.anddev.andengine.engine.handler.physics;
import org.anddev.andengine.engine.handler.BaseEntityUpdateHandler;
import org.anddev.andengine.entity.IEntity;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 13:53:07 - 24.12.2010
*/
public class PhysicsHandler extends BaseEntityUpdateHandler {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
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
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/engine/handler/physics/PhysicsHandler.java | Java | lgpl | 4,652 |
package org.anddev.andengine.engine;
import javax.microedition.khronos.opengles.GL10;
import javax.microedition.khronos.opengles.GL11;
import org.anddev.andengine.audio.music.MusicFactory;
import org.anddev.andengine.audio.music.MusicManager;
import org.anddev.andengine.audio.sound.SoundFactory;
import org.anddev.andengine.audio.sound.SoundManager;
import org.anddev.andengine.engine.camera.Camera;
import org.anddev.andengine.engine.handler.IUpdateHandler;
import org.anddev.andengine.engine.handler.UpdateHandlerList;
import org.anddev.andengine.engine.handler.runnable.RunnableHandler;
import org.anddev.andengine.engine.options.EngineOptions;
import org.anddev.andengine.entity.scene.Scene;
import org.anddev.andengine.input.touch.TouchEvent;
import org.anddev.andengine.input.touch.controller.ITouchController;
import org.anddev.andengine.input.touch.controller.ITouchController.ITouchEventCallback;
import org.anddev.andengine.input.touch.controller.SingleTouchControler;
import org.anddev.andengine.opengl.buffer.BufferObjectManager;
import org.anddev.andengine.opengl.font.FontFactory;
import org.anddev.andengine.opengl.font.FontManager;
import org.anddev.andengine.opengl.texture.TextureManager;
import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory;
import org.anddev.andengine.opengl.util.GLHelper;
import org.anddev.andengine.sensor.SensorDelay;
import org.anddev.andengine.sensor.accelerometer.AccelerometerData;
import org.anddev.andengine.sensor.accelerometer.AccelerometerSensorOptions;
import org.anddev.andengine.sensor.accelerometer.IAccelerometerListener;
import org.anddev.andengine.sensor.location.ILocationListener;
import org.anddev.andengine.sensor.location.LocationProviderStatus;
import org.anddev.andengine.sensor.location.LocationSensorOptions;
import org.anddev.andengine.sensor.orientation.IOrientationListener;
import org.anddev.andengine.sensor.orientation.OrientationData;
import org.anddev.andengine.sensor.orientation.OrientationSensorOptions;
import org.anddev.andengine.util.Debug;
import org.anddev.andengine.util.constants.TimeConstants;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.Bundle;
import android.os.Vibrator;
import android.view.Display;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.WindowManager;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 12:21:31 - 08.03.2010
*/
public class Engine implements SensorEventListener, OnTouchListener, ITouchEventCallback, TimeConstants, LocationListener {
// ===========================================================
// Constants
// ===========================================================
private static final SensorDelay SENSORDELAY_DEFAULT = SensorDelay.GAME;
private static final int UPDATEHANDLERS_CAPACITY_DEFAULT = 32;
// ===========================================================
// Fields
// ===========================================================
private boolean mRunning = false;
private long mLastTick = -1;
private float mSecondsElapsedTotal = 0;
private final State mThreadLocker = new State();
private final UpdateThread mUpdateThread = new UpdateThread();
private final RunnableHandler mUpdateThreadRunnableHandler = new RunnableHandler();
private final EngineOptions mEngineOptions;
protected final Camera mCamera;
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();
protected Scene mScene;
private Vibrator mVibrator;
private ILocationListener mLocationListener;
private Location mLocation;
private IAccelerometerListener mAccelerometerListener;
private AccelerometerData mAccelerometerData;
private IOrientationListener mOrientationListener;
private OrientationData mOrientationData;
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
private boolean mIsMethodTracing;
// ===========================================================
// Constructors
// ===========================================================
public Engine(final EngineOptions pEngineOptions) {
BitmapTextureAtlasTextureRegionFactory.reset();
SoundFactory.reset();
MusicFactory.reset();
FontFactory.reset();
BufferObjectManager.setActiveInstance(this.mBufferObjectManager);
this.mEngineOptions = pEngineOptions;
this.setTouchController(new SingleTouchControler());
this.mCamera = pEngineOptions.getCamera();
if(this.mEngineOptions.needsSound()) {
this.mSoundManager = new SoundManager();
}
if(this.mEngineOptions.needsMusic()) {
this.mMusicManager = new MusicManager();
}
this.mUpdateThread.start();
}
// ===========================================================
// Getter & Setter
// ===========================================================
public boolean isRunning() {
return this.mRunning;
}
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 Scene getScene() {
return this.mScene;
}
public void setScene(final Scene pScene) {
this.mScene = pScene;
}
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;
}
}
@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.
*/
Thread.sleep(20); // 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);
}
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;
}
public boolean enableVibrator(final Context pContext) {
this.mVibrator = (Vibrator) pContext.getSystemService(Context.VIBRATOR_SERVICE);
return this.mVibrator != null;
}
public void vibrate(final long pMilliseconds) throws IllegalStateException {
if(this.mVibrator != null) {
this.mVibrator.vibrate(pMilliseconds);
} else {
throw new IllegalStateException("You need to enable the Vibrator before you can use it!");
}
}
public void vibrate(final long[] pPattern, final int pRepeat) throws IllegalStateException {
if(this.mVibrator != null) {
this.mVibrator.vibrate(pPattern, pRepeat);
} else {
throw new IllegalStateException("You need to enable the Vibrator before you can use it!");
}
}
public void enableLocationSensor(final Context pContext, final ILocationListener pLocationListener, final LocationSensorOptions pLocationSensorOptions) {
this.mLocationListener = pLocationListener;
final LocationManager locationManager = (LocationManager) pContext.getSystemService(Context.LOCATION_SERVICE);
final String locationProvider = locationManager.getBestProvider(pLocationSensorOptions, pLocationSensorOptions.isEnabledOnly());
// TODO locationProvider can be null, in that case return false. Successful case should return true.
locationManager.requestLocationUpdates(locationProvider, pLocationSensorOptions.getMinimumTriggerTime(), pLocationSensorOptions.getMinimumTriggerDistance(), this);
this.onLocationChanged(locationManager.getLastKnownLocation(locationProvider));
}
public void disableLocationSensor(final Context pContext) {
final LocationManager locationManager = (LocationManager) pContext.getSystemService(Context.LOCATION_SERVICE);
locationManager.removeUpdates(this);
}
/**
* @see {@link Engine#enableAccelerometerSensor(Context, IAccelerometerListener, AccelerometerSensorOptions)}
*/
public boolean enableAccelerometerSensor(final Context pContext, final IAccelerometerListener pAccelerometerListener) {
return this.enableAccelerometerSensor(pContext, pAccelerometerListener, new AccelerometerSensorOptions(SENSORDELAY_DEFAULT));
}
/**
* @return <code>true</code> when the sensor was successfully enabled, <code>false</code> otherwise.
*/
public boolean enableAccelerometerSensor(final Context pContext, final IAccelerometerListener pAccelerometerListener, final AccelerometerSensorOptions pAccelerometerSensorOptions) {
final SensorManager sensorManager = (SensorManager) pContext.getSystemService(Context.SENSOR_SERVICE);
if(this.isSensorSupported(sensorManager, Sensor.TYPE_ACCELEROMETER)) {
this.mAccelerometerListener = pAccelerometerListener;
if(this.mAccelerometerData == null) {
final Display display = ((WindowManager) pContext.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
final int displayRotation = display.getOrientation();
this.mAccelerometerData = new AccelerometerData(displayRotation);
}
this.registerSelfAsSensorListener(sensorManager, Sensor.TYPE_ACCELEROMETER, pAccelerometerSensorOptions.getSensorDelay());
return true;
} else {
return false;
}
}
/**
* @return <code>true</code> when the sensor was successfully disabled, <code>false</code> otherwise.
*/
public boolean disableAccelerometerSensor(final Context pContext) {
final SensorManager sensorManager = (SensorManager) pContext.getSystemService(Context.SENSOR_SERVICE);
if(this.isSensorSupported(sensorManager, Sensor.TYPE_ACCELEROMETER)) {
this.unregisterSelfAsSensorListener(sensorManager, Sensor.TYPE_ACCELEROMETER);
return true;
} else {
return false;
}
}
/**
* @see {@link Engine#enableOrientationSensor(Context, IOrientationListener, OrientationSensorOptions)}
*/
public boolean enableOrientationSensor(final Context pContext, final IOrientationListener pOrientationListener) {
return this.enableOrientationSensor(pContext, pOrientationListener, new OrientationSensorOptions(SENSORDELAY_DEFAULT));
}
/**
* @return <code>true</code> when the sensor was successfully enabled, <code>false</code> otherwise.
*/
public boolean enableOrientationSensor(final Context pContext, final IOrientationListener pOrientationListener, final OrientationSensorOptions pOrientationSensorOptions) {
final SensorManager sensorManager = (SensorManager) pContext.getSystemService(Context.SENSOR_SERVICE);
if(this.isSensorSupported(sensorManager, Sensor.TYPE_ACCELEROMETER) && this.isSensorSupported(sensorManager, Sensor.TYPE_MAGNETIC_FIELD)) {
this.mOrientationListener = pOrientationListener;
if(this.mOrientationData == null) {
final Display display = ((WindowManager) pContext.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
final int displayRotation = display.getOrientation();
this.mOrientationData = new OrientationData(displayRotation);
}
this.registerSelfAsSensorListener(sensorManager, Sensor.TYPE_ACCELEROMETER, pOrientationSensorOptions.getSensorDelay());
this.registerSelfAsSensorListener(sensorManager, Sensor.TYPE_MAGNETIC_FIELD, pOrientationSensorOptions.getSensorDelay());
return true;
} else {
return false;
}
}
/**
* @return <code>true</code> when the sensor was successfully disabled, <code>false</code> otherwise.
*/
public boolean disableOrientationSensor(final Context pContext) {
final SensorManager sensorManager = (SensorManager) pContext.getSystemService(Context.SENSOR_SERVICE);
if(this.isSensorSupported(sensorManager, Sensor.TYPE_ACCELEROMETER) && this.isSensorSupported(sensorManager, Sensor.TYPE_MAGNETIC_FIELD)) {
this.unregisterSelfAsSensorListener(sensorManager, Sensor.TYPE_ACCELEROMETER);
this.unregisterSelfAsSensorListener(sensorManager, Sensor.TYPE_MAGNETIC_FIELD);
return true;
} else {
return false;
}
}
private boolean isSensorSupported(final SensorManager pSensorManager, final int pType) {
return pSensorManager.getSensorList(pType).size() > 0;
}
private void registerSelfAsSensorListener(final SensorManager pSensorManager, final int pType, final SensorDelay pSensorDelay) {
final Sensor sensor = pSensorManager.getSensorList(pType).get(0);
pSensorManager.registerListener(this, sensor, pSensorDelay.getDelay());
}
private void unregisterSelfAsSensorListener(final SensorManager pSensorManager, final int pType) {
final Sensor sensor = pSensorManager.getSensorList(pType).get(0);
pSensorManager.unregisterListener(this, sensor);
}
// ===========================================================
// 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");
}
}
}
| zzy421-andengine | src/org/anddev/andengine/engine/Engine.java | Java | lgpl | 25,036 |
package org.anddev.andengine.engine;
import javax.microedition.khronos.opengles.GL10;
import org.anddev.andengine.engine.camera.Camera;
import org.anddev.andengine.engine.options.EngineOptions;
import org.anddev.andengine.input.touch.TouchEvent;
import org.anddev.andengine.opengl.util.GLHelper;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @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
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/engine/SingleSceneSplitScreenEngine.java | Java | lgpl | 4,319 |
package org.anddev.andengine.engine;
import org.anddev.andengine.engine.options.EngineOptions;
/**
* A subclass of {@link Engine} that tries to achieve a specific amount of updates per second.
* When the time since the last update is bigger long the steplength, additional updates are executed.
*
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @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
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/engine/FixedStepEngine.java | Java | lgpl | 2,186 |
package org.anddev.andengine.engine.options;
import android.os.PowerManager;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @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 <b>WAKE_LOCK</b> permission! */
BRIGHT(PowerManager.FULL_WAKE_LOCK),
/** Screen is on at full brightness. Keyboard backlight will be allowed to go off. Requires <b>WAKE_LOCK</b> permission!*/
SCREEN_BRIGHT(PowerManager.SCREEN_BRIGHT_WAKE_LOCK),
/** Screen is on but may be dimmed. Keyboard backlight will be allowed to go off. Requires <b>WAKE_LOCK</b> permission!*/
SCREEN_DIM(PowerManager.SCREEN_DIM_WAKE_LOCK),
/** Screen is on at full brightness. Does <b>not</b> require <b>WAKE_LOCK</b> 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
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/engine/options/WakeLockOptions.java | Java | lgpl | 2,256 |
package org.anddev.andengine.engine.options;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 13:01:40 - 02.07.2010
*/
public class RenderOptions {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private boolean mDisableExtensionVertexBufferObjects = false;
private boolean mDisableExtensionDrawTexture = false;
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
/**
* <u><b>Default:</b></u> <code>false</code>
*/
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;
}
/**
* <u><b>Default:</b></u> <code>false</code>
*/
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
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/engine/options/RenderOptions.java | Java | lgpl | 2,653 |
package org.anddev.andengine.engine.options;
import org.anddev.andengine.engine.camera.Camera;
import org.anddev.andengine.engine.options.resolutionpolicy.IResolutionPolicy;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @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;
}
} | zzy421-andengine | src/org/anddev/andengine/engine/options/EngineOptions.java | Java | lgpl | 3,906 |
package org.anddev.andengine.engine.options.resolutionpolicy;
import org.anddev.andengine.opengl.view.RenderSurfaceView;
import android.view.View.MeasureSpec;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @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
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/engine/options/resolutionpolicy/RatioResolutionPolicy.java | Java | lgpl | 2,546 |
package org.anddev.andengine.engine.options.resolutionpolicy;
import org.anddev.andengine.opengl.view.RenderSurfaceView;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @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
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/engine/options/resolutionpolicy/FixedResolutionPolicy.java | Java | lgpl | 1,817 |
package org.anddev.andengine.engine.options.resolutionpolicy;
import org.anddev.andengine.opengl.view.RenderSurfaceView;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 11:02:35 - 29.03.2010
*/
public interface IResolutionPolicy {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
public void onMeasure(final RenderSurfaceView pRenderSurfaceView, final int pWidthMeasureSpec, final int pHeightMeasureSpec);
}
| zzy421-andengine | src/org/anddev/andengine/engine/options/resolutionpolicy/IResolutionPolicy.java | Java | lgpl | 720 |
package org.anddev.andengine.engine.options.resolutionpolicy;
import org.anddev.andengine.opengl.view.RenderSurfaceView;
import android.view.View.MeasureSpec;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @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
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/engine/options/resolutionpolicy/RelativeResolutionPolicy.java | Java | lgpl | 2,291 |
package org.anddev.andengine.engine.options.resolutionpolicy;
import org.anddev.andengine.opengl.view.RenderSurfaceView;
import android.view.View.MeasureSpec;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 11:22:48 - 29.03.2010
*/
public class FillResolutionPolicy extends BaseResolutionPolicy {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// 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 = MeasureSpec.getSize(pWidthMeasureSpec);
final int measuredHeight = MeasureSpec.getSize(pHeightMeasureSpec);
pRenderSurfaceView.setMeasuredDimensionProxy(measuredWidth, measuredHeight);
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/engine/options/resolutionpolicy/FillResolutionPolicy.java | Java | lgpl | 1,911 |
package org.anddev.andengine.engine.options.resolutionpolicy;
import android.view.View.MeasureSpec;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @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
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/engine/options/resolutionpolicy/BaseResolutionPolicy.java | Java | lgpl | 1,855 |
package org.anddev.andengine.engine.options;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @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;
}
/**
* <u><b>Default:</b></u> <code>true</code>
*/
public boolean isRunOnUpdateThread() {
return this.mRunOnUpdateThread;
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/engine/options/TouchOptions.java | Java | lgpl | 1,820 |
package org.anddev.andengine.opengl.buffer;
import javax.microedition.khronos.opengles.GL11;
import org.anddev.andengine.opengl.util.FastFloatBuffer;
import org.anddev.andengine.opengl.util.GLHelper;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 14:22:56 - 07.04.2010
*/
public abstract class BufferObject {
// ===========================================================
// Constants
// ===========================================================
private static final int[] HARDWAREBUFFERID_FETCHER = new int[1];
// ===========================================================
// Fields
// ===========================================================
protected final int[] mBufferData;
private final int mDrawType;
protected final FastFloatBuffer mFloatBuffer;
private int mHardwareBufferID = -1;
private boolean mLoadedToHardware;
private boolean mHardwareBufferNeedsUpdate = true;
private boolean mManaged;
// ===========================================================
// Constructors
// ===========================================================
/**
* @param pCapacity
* @param pDrawType
* @param pManaged when passing <code>true</code> this {@link BufferObject} loads itself to the active {@link BufferObjectManager}. <b><u>WARNING:</u></b> When passing <code>false</code> 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();
}
}
// ===========================================================
// Getter & Setter
// ===========================================================
public boolean isManaged() {
return this.mManaged;
}
public void setManaged(final boolean pManaged) {
this.mManaged = pManaged;
}
public FastFloatBuffer getFloatBuffer() {
return this.mFloatBuffer;
}
public int getHardwareBufferID() {
return this.mHardwareBufferID;
}
public boolean isLoadedToHardware() {
return this.mLoadedToHardware;
}
void setLoadedToHardware(final boolean pLoadedToHardware) {
this.mLoadedToHardware = pLoadedToHardware;
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
public void setHardwareBufferNeedsUpdate(){
this.mHardwareBufferNeedsUpdate = true;
}
// ===========================================================
// Methods
// ===========================================================
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)?
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 unloadFromActiveBufferObjectManager() {
BufferObjectManager.getActiveInstance().unloadBufferObject(this);
}
public void loadToHardware(final GL11 pGL11) {
this.mHardwareBufferID = this.generateHardwareBufferID(pGL11);
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
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/opengl/buffer/BufferObject.java | Java | lgpl | 4,395 |
package org.anddev.andengine.opengl.buffer;
import java.util.ArrayList;
import java.util.HashSet;
import javax.microedition.khronos.opengles.GL11;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 17:48:46 - 08.03.2010
*/
public class BufferObjectManager {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private static final HashSet<BufferObject> mBufferObjectsManaged = new HashSet<BufferObject>();
private static final ArrayList<BufferObject> mBufferObjectsLoaded = new ArrayList<BufferObject>();
private static final ArrayList<BufferObject> mBufferObjectsToBeLoaded = new ArrayList<BufferObject>();
private static final ArrayList<BufferObject> mBufferObjectsToBeUnloaded = new ArrayList<BufferObject>();
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<BufferObject> 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<BufferObject> bufferObjectsManaged = BufferObjectManager.mBufferObjectsManaged;
final ArrayList<BufferObject> bufferObjectsLoaded = BufferObjectManager.mBufferObjectsLoaded;
final ArrayList<BufferObject> bufferObjectsToBeLoaded = BufferObjectManager.mBufferObjectsToBeLoaded;
final ArrayList<BufferObject> 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
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/opengl/buffer/BufferObjectManager.java | Java | lgpl | 5,775 |
package org.anddev.andengine.opengl;
import javax.microedition.khronos.opengles.GL10;
import org.anddev.andengine.engine.camera.Camera;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 10:50:58 - 08.08.2010
*/
public interface IDrawable {
// ===========================================================
// Final Fields
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
public void onDraw(final GL10 pGL, final Camera pCamera);
}
| zzy421-andengine | src/org/anddev/andengine/opengl/IDrawable.java | Java | lgpl | 667 |
package org.anddev.andengine.opengl.view;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
import org.anddev.andengine.engine.Engine;
import org.anddev.andengine.opengl.util.GLHelper;
import org.anddev.andengine.util.Debug;
import android.content.Context;
import android.util.AttributeSet;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @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) {
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("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 {
this.mEngine.onDrawFrame(pGL);
} catch (final InterruptedException e) {
Debug.e("GLThread interrupted!", e);
}
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
}
| zzy421-andengine | src/org/anddev/andengine/opengl/view/RenderSurfaceView.java | Java | lgpl | 5,459 |
package org.anddev.andengine.opengl.view;
import javax.microedition.khronos.egl.EGL10;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.egl.EGLDisplay;
/**
* An interface for choosing an EGLConfig configuration from a list of
* potential configurations.
* <p>
* This interface must be implemented by clients wishing to call
* {@link GLSurfaceView#setEGLConfigChooser(EGLConfigChooser)}
*
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 20:53:49 - 28.06.2010
*/
public interface EGLConfigChooser {
// ===========================================================
// Final Fields
// ===========================================================
// ===========================================================
// 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);
} | zzy421-andengine | src/org/anddev/andengine/opengl/view/EGLConfigChooser.java | Java | lgpl | 1,430 |
/**
*
*/
package org.anddev.andengine.opengl.view;
import javax.microedition.khronos.egl.EGL10;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.egl.EGLDisplay;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 20:42:29 - 28.06.2010
*/
abstract class BaseConfigChooser implements EGLConfigChooser {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
protected final int[] mConfigSpec;
// ===========================================================
// Constructors
// ===========================================================
public BaseConfigChooser(final int[] pConfigSpec) {
this.mConfigSpec = pConfigSpec;
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
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);
final int numConfigs = num_config[0];
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;
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
} | zzy421-andengine | src/org/anddev/andengine/opengl/view/BaseConfigChooser.java | Java | lgpl | 2,428 |
package org.anddev.andengine.opengl.view;
import javax.microedition.khronos.opengles.GL;
/**
* An interface used to wrap a GL interface.
* <p>
* Typically used for implementing debugging and tracing on top of the default
* GL interface. You would typically use this by creating your own class that
* implemented all the GL methods by delegating to another GL instance. Then you
* could add your own behavior before or after calling the delegate. All the
* GLWrapper would do was instantiate and return the wrapper GL instance:
*
* <pre class="prettyprint">
* class MyGLWrapper implements GLWrapper {
* GL wrap(GL gl) {
* return new MyGLImplementation(gl);
* }
* static class MyGLImplementation implements GL,GL10,GL11,... {
* ...
* }
* }
* </pre>
*
* @see #setGLWrapper(GLWrapper)
*
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 20:53:38 - 28.06.2010
*/
public interface GLWrapper {
// ===========================================================
// Final Fields
// ===========================================================
// ===========================================================
// 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);
} | zzy421-andengine | src/org/anddev/andengine/opengl/view/GLWrapper.java | Java | lgpl | 1,578 |
package org.anddev.andengine.opengl.view;
import javax.microedition.khronos.egl.EGL10;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.egl.EGLDisplay;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 20:54:06 - 28.06.2010
*/
public class ComponentSizeChooser extends BaseConfigChooser {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// 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;
// ===========================================================
// 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;
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// 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;
}
// ===========================================================
// 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;
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
} | zzy421-andengine | src/org/anddev/andengine/opengl/view/ComponentSizeChooser.java | Java | lgpl | 3,797 |
package org.anddev.andengine.opengl.view;
/**
* This class will choose a supported surface as close to RGB565 as
* possible, with or without a depth buffer.
*
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @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
// ===========================================================
} | zzy421-andengine | src/org/anddev/andengine/opengl/view/SimpleEGLConfigChooser.java | Java | lgpl | 1,758 |
// ############################################################
// ############################################################
//
// This class is a replacement for the original GLSurfaceView, due to issue:
// http://code.google.com/p/android/issues/detail?id=2828
//
// Reason: Two sequential Activities using a GLSurfaceView leads to a deadlock in the GLThread!
//
// ############################################################
// ############################################################
package org.anddev.andengine.opengl.view;
import java.util.ArrayList;
import java.util.concurrent.Semaphore;
import javax.microedition.khronos.egl.EGL10;
import javax.microedition.khronos.egl.EGL11;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.egl.EGLContext;
import javax.microedition.khronos.egl.EGLDisplay;
import javax.microedition.khronos.egl.EGLSurface;
import javax.microedition.khronos.opengles.GL;
import javax.microedition.khronos.opengles.GL10;
import android.content.Context;
import android.util.AttributeSet;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
/**
* An implementation of SurfaceView that uses the dedicated surface for
* displaying OpenGL rendering.
* <p>
* A GLSurfaceView provides the following features:
* <p>
* <ul>
* <li>Manages a surface, which is a special piece of memory that can be
* composited into the Android view system.
* <li>Manages an EGL display, which enables OpenGL to render into a surface.
* <li>Accepts a user-provided Renderer object that does the actual rendering.
* <li>Renders on a dedicated thread to decouple rendering performance from the
* UI thread.
* <li>Supports both on-demand and continuous rendering.
* <li>Optionally wraps, traces, and/or error-checks the renderer'MAGIC_CONSTANT OpenGL
* calls.
* </ul>
*
* <h3>Using GLSurfaceView</h3>
* <p>
* Typically you use GLSurfaceView by subclassing it and overriding one or more
* of the View system input event methods. If your application does not need to
* override event methods then GLSurfaceView can be used as-is. For the most
* part GLSurfaceView behavior is customized by calling "set" methods rather
* than by subclassing. For example, unlike a regular View, drawing is delegated
* to a separate Renderer object which is registered with the GLSurfaceView
* using the {@link #setRenderer(Renderer)} call.
* <p>
* <h3>Initializing GLSurfaceView</h3>
* All you have to do to initialize a GLSurfaceView is call
* {@link #setRenderer(Renderer)}. However, if desired, you can modify the
* default behavior of GLSurfaceView by calling one or more of these methods
* before calling setRenderer:
* <ul>
* <li>{@link #setDebugFlags(int)}
* <li>{@link #setEGLConfigChooser(boolean)}
* <li>{@link #setEGLConfigChooser(EGLConfigChooser)}
* <li>{@link #setEGLConfigChooser(int, int, int, int, int, int)}
* <li>{@link #setGLWrapper(GLWrapper)}
* </ul>
* <p>
* <h4>Choosing an EGL Configuration</h4>
* A given Android device may support multiple possible types of drawing
* surfaces. The available surfaces may differ in how may channels of data are
* present, as well as how many bits are allocated to each channel. Therefore,
* the first thing GLSurfaceView has to do when starting to render is choose
* what type of surface to use.
* <p>
* By default GLSurfaceView chooses an available surface that'MAGIC_CONSTANT closest to a
* 16-bit R5G6B5 surface with a 16-bit depth buffer and no stencil. If you would
* prefer a different surface (for example, if you do not need a depth buffer)
* you can override the default behavior by calling one of the
* setEGLConfigChooser methods.
* <p>
* <h4>Debug Behavior</h4>
* You can optionally modify the behavior of GLSurfaceView by calling one or
* more of the debugging methods {@link #setDebugFlags(int)}, and
* {@link #setGLWrapper}. These methods may be called before and/or after
* setRenderer, but typically they are called before setRenderer so that they
* take effect immediately.
* <p>
* <h4>Setting a Renderer</h4>
* Finally, you must call {@link #setRenderer} to register a {@link Renderer}.
* The renderer is responsible for doing the actual OpenGL rendering.
* <p>
* <h3>Rendering Mode</h3>
* Once the renderer is set, you can control whether the renderer draws
* continuously or on-demand by calling {@link #setRenderMode}. The default is
* continuous rendering.
* <p>
* <h3>Activity Life-cycle</h3>
* A GLSurfaceView must be notified when the activity is paused and resumed.
* GLSurfaceView clients are required to call {@link #onPause()} when the
* activity pauses and {@link #onResume()} when the activity resumes. These
* calls allow GLSurfaceView to pause and resume the rendering thread, and also
* allow GLSurfaceView to release and recreate the OpenGL display.
* <p>
* <h3>Handling events</h3>
* <p>
* To handle an event you will typically subclass GLSurfaceView and override the
* appropriate method, just as you would with any other View. However, when
* handling the event, you may need to communicate with the Renderer object
* that'MAGIC_CONSTANT running in the rendering thread. You can do this using any standard
* Java cross-thread communication mechanism. In addition, one relatively easy
* way to communicate with your renderer is to call
* {@link #queueEvent(Runnable)}. For example:
*
* <pre class="prettyprint">
* class MyGLSurfaceView extends GLSurfaceView {
*
* private MyRenderer mMyRenderer;
*
* 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);
* }
* }
* </pre>
*
*/
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.
* <p>
* Wrapping is typically used for debugging purposes.
* <p>
* 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.
* <p>
* This method should be called once and only once in the life-cycle of a
* GLSurfaceView.
* <p>
* The following GLSurfaceView methods can only be called <em>before</em>
* setRenderer is called:
* <ul>
* <li>{@link #setEGLConfigChooser(boolean)}
* <li>{@link #setEGLConfigChooser(EGLConfigChooser)}
* <li>{@link #setEGLConfigChooser(int, int, int, int, int, int)}
* </ul>
* <p>
* The following GLSurfaceView methods can only be called <em>after</em>
* setRenderer is called:
* <ul>
* <li>{@link #getRenderMode()}
* <li>{@link #onPause()}
* <li>{@link #onResume()}
* <li>{@link #queueEvent(Runnable)}
* <li>{@link #requestRender()}
* <li>{@link #setRenderMode(int)}
* </ul>
*
* @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.
* <p>
* If this method is called, it must be called before
* {@link #setRenderer(Renderer)} is called.
* <p>
* 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.
* <p>
* If this method is called, it must be called before
* {@link #setRenderer(Renderer)} is called.
* <p>
* 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.
* <p>
* If this method is called, it must be called before
* {@link #setRenderer(Renderer)} is called.
* <p>
* 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.
* <p>
* 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.
* <p>
* 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<Runnable> mEventQueue = new ArrayList<Runnable>();
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.
* <p>
* The renderer is responsible for making OpenGL calls to render a frame.
* <p>
* GLSurfaceView clients typically create their own classes that implement
* this interface, and then call {@link GLSurfaceView#setRenderer} to
* register the renderer with the GLSurfaceView.
* <p>
* <h3>Threading</h3>
* 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.
* <p>
* <h3>EGL Context Lost</h3>
* 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.
* <p>
* 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.
* <p>
* 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.
* <p>
* 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.
* <p>
*
* @param gl
* the GL interface. Use <code>instanceof</code> 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.
* <p>
* Called after the surface is created and whenever the OpenGL ES
* surface size changes.
* <p>
* Typically you will set your viewport here. If your camera is fixed
* then you could also set your projection matrix here:
*
* <pre class="prettyprint">
* 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);
* }
* </pre>
*
* @param gl
* the GL interface. Use <code>instanceof</code> 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.
* <p>
* This method is responsible for drawing the current frame.
* <p>
* The implementation of this method typically looks like this:
*
* <pre class="prettyprint">
* void onDrawFrame(GL10 gl) {
* gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
* //... other gl calls to render the scene ...
* }
* </pre>
*
* @param gl
* the GL interface. Use <code>instanceof</code> to test if
* the interface supports GL11 or higher interfaces.
*/
void onDrawFrame(GL10 gl);
}
}
| zzy421-andengine | src/org/anddev/andengine/opengl/view/GLSurfaceView.java | Java | lgpl | 31,347 |
/**
*
*/
package org.anddev.andengine.opengl.view;
import java.io.Writer;
import android.util.Log;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 20:42:02 - 28.06.2010
*/
class LogWriter extends Writer {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private final StringBuilder mBuilder = new StringBuilder();
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public void close() {
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);
}
}
}
// ===========================================================
// Methods
// ===========================================================
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
// ===========================================================
} | zzy421-andengine | src/org/anddev/andengine/opengl/view/LogWriter.java | Java | lgpl | 2,006 |
package org.anddev.andengine.opengl.util;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.IntBuffer;
import javax.microedition.khronos.opengles.GL10;
import javax.microedition.khronos.opengles.GL11;
import org.anddev.andengine.engine.options.RenderOptions;
import org.anddev.andengine.opengl.texture.Texture.PixelFormat;
import org.anddev.andengine.util.Debug;
import android.graphics.Bitmap;
import android.opengl.GLException;
import android.opengl.GLUtils;
import android.os.Build;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 18:00:43 - 08.03.2010
*/
public class GLHelper {
// ===========================================================
// Constants
// ===========================================================
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 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;
// ===========================================================
// Methods
// ===========================================================
public static void reset(final GL10 pGL) {
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 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 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);
}
/**
* <b>Note:</b> does not pre-multiply the alpha channel!</br>
* Except that difference, same as: {@link GLUtils#texSubImage2D(int, int, int, int, Bitmap, int, int)}</br>
* </br>
* See topic: '<a href="http://groups.google.com/group/android-developers/browse_thread/thread/baa6c33e63f82fca">PNG loading that doesn't premultiply alpha?</a>'
* @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);
}
/**
* <b>Note:</b> does not pre-multiply the alpha channel!</br>
* Except that difference, same as: {@link GLUtils#texSubImage2D(int, int, int, int, Bitmap, int, int)}</br>
* </br>
* See topic: '<a href="http://groups.google.com/group/android-developers/browse_thread/thread/baa6c33e63f82fca">PNG loading that doesn't premultiply alpha?</a>'
*/
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
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/opengl/util/GLHelper.java | Java | lgpl | 20,659 |