code
stringlengths
3
1.18M
language
stringclasses
1 value
package org.anddev.andengine.entity.text; import javax.microedition.khronos.opengles.GL10; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.opengl.font.Font; import org.anddev.andengine.opengl.vertex.TextVertexBuffer; import org.anddev.andengine.util.HorizontalAlign; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 10:02:04 - 05.05.2010 */ public class TickerText extends Text { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private float mCharactersPerSecond; private int mCharactersVisible = 0; private float mSecondsElapsed = 0; private boolean mReverse = false; private float mDuration; // =========================================================== // Constructors // =========================================================== public TickerText(final float pX, final float pY, final Font pFont, final String pText, final HorizontalAlign pHorizontalAlign, final float pCharactersPerSecond) { super(pX, pY, pFont, pText, pHorizontalAlign); this.setCharactersPerSecond(pCharactersPerSecond); } // =========================================================== // Getter & Setter // =========================================================== public boolean isReverse() { return this.mReverse; } public void setReverse(final boolean pReverse) { this.mReverse = pReverse; } public float getCharactersPerSecond() { return this.mCharactersPerSecond; } public void setCharactersPerSecond(final float pCharactersPerSecond) { this.mCharactersPerSecond = pCharactersPerSecond; this.mDuration = this.mCharactersMaximum * this.mCharactersPerSecond; } public int getCharactersVisible() { return this.mCharactersVisible; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override protected void onManagedUpdate(final float pSecondsElapsed) { super.onManagedUpdate(pSecondsElapsed); if(this.mReverse){ if(this.mCharactersVisible < this.mCharactersMaximum){ this.mSecondsElapsed = Math.max(0, this.mSecondsElapsed - pSecondsElapsed); this.mCharactersVisible = (int)(this.mSecondsElapsed * this.mCharactersPerSecond); } } else { if(this.mCharactersVisible < this.mCharactersMaximum){ this.mSecondsElapsed = Math.min(this.mDuration, this.mSecondsElapsed + pSecondsElapsed); this.mCharactersVisible = (int)(this.mSecondsElapsed * this.mCharactersPerSecond); } } } @Override protected void drawVertices(final GL10 pGL, final Camera pCamera) { pGL.glDrawArrays(GL10.GL_TRIANGLES, 0, this.mCharactersVisible * TextVertexBuffer.VERTICES_PER_CHARACTER); } @Override public void reset() { super.reset(); this.mCharactersVisible = 0; this.mSecondsElapsed = 0; this.mReverse = false; } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.entity; import java.util.Comparator; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.handler.IUpdateHandler; import org.anddev.andengine.engine.handler.runnable.RunnableHandler; import org.anddev.andengine.entity.modifier.IEntityModifier; import org.anddev.andengine.entity.modifier.IEntityModifier.IEntityModifierMatcher; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.opengl.IDrawable; import org.anddev.andengine.util.IMatcher; import org.anddev.andengine.util.ParameterCallable; import org.anddev.andengine.util.Transformation; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 11:20:25 - 08.03.2010 */ public interface IEntity extends IDrawable, IUpdateHandler { // =========================================================== // Final Fields // =========================================================== // =========================================================== // Methods // =========================================================== public boolean isVisible(); public void setVisible(final boolean pVisible); public boolean isIgnoreUpdate(); public void setIgnoreUpdate(boolean pIgnoreUpdate); public boolean isChildrenVisible(); public void setChildrenVisible(final boolean pChildrenVisible); public boolean isChildrenIgnoreUpdate(); public void setChildrenIgnoreUpdate(boolean pChildrenIgnoreUpdate); public int getZIndex(); public void setZIndex(final int pZIndex); public boolean hasParent(); public IEntity getParent(); public void setParent(final IEntity pEntity); public float getX(); public float getY(); public float getInitialX(); public float getInitialY(); public void setInitialPosition(); public void setPosition(final IEntity pOtherEntity); public void setPosition(final float pX, final float pY); public boolean isRotated(); public float getRotation(); public void setRotation(final float pRotation); public float getRotationCenterX(); public float getRotationCenterY(); public void setRotationCenterX(final float pRotationCenterX); public void setRotationCenterY(final float pRotationCenterY); public void setRotationCenter(final float pRotationCenterX, final float pRotationCenterY); public boolean isScaled(); public float getScaleX(); public float getScaleY(); public void setScaleX(final float pScaleX); public void setScaleY(final float pScaleY); public void setScale(final float pScale); public void setScale(final float pScaleX, final float pScaleY); public float getScaleCenterX(); public float getScaleCenterY(); public void setScaleCenterX(final float pScaleCenterX); public void setScaleCenterY(final float pScaleCenterY); public void setScaleCenter(final float pScaleCenterX, final float pScaleCenterY); public float getRed(); public float getGreen(); public float getBlue(); public float getAlpha(); public void setAlpha(final float pAlpha); public void setColor(final float pRed, final float pGreen, final float pBlue); public void setColor(final float pRed, final float pGreen, final float pBlue, final float pAlpha); /** * @return a shared(!) float[] of length 2. */ public float[] getSceneCenterCoordinates(); /** * @param pX * @param pY * @return a shared(!) float[] of length 2. */ public float[] convertLocalToSceneCoordinates(final float pX, final float pY); /** * @param pX * @param pY * @param pReuse must be of length 2. * @return <code>pReuse</code> as a convenience. */ public float[] convertLocalToSceneCoordinates(final float pX, final float pY, final float[] pReuse); /** * @param pCoordinates must be of length 2. * @return a shared(!) float[] of length 2. */ public float[] convertLocalToSceneCoordinates(final float[] pCoordinates); /** * @param pCoordinates must be of length 2. * @param pReuse must be of length 2. * @return <code>pReuse</code> as a convenience. */ public float[] convertLocalToSceneCoordinates(final float[] pCoordinates, final float[] pReuse); /** * @param pX * @param pY * @return a shared(!) float[] of length 2. */ public float[] convertSceneToLocalCoordinates(final float pX, final float pY); /** * @param pX * @param pY * @param pReuse must be of length 2. * @return <code>pReuse</code> as a convenience. */ public float[] convertSceneToLocalCoordinates(final float pX, final float pY, final float[] pReuse); /** * @param pCoordinates must be of length 2. * @return a shared(!) float[] of length 2. */ public float[] convertSceneToLocalCoordinates(final float[] pCoordinates); /** * @param pCoordinates must be of length 2. * @param pReuse must be of length 2. * @return <code>pReuse</code> as a convenience. */ public float[] convertSceneToLocalCoordinates(final float[] pCoordinates, final float[] pReuse); public Transformation getLocalToSceneTransformation(); public Transformation getSceneToLocalTransformation(); // public Transformation getLocalToParentTransformation(); // TODO Add this method. // public Transformation getParentToLocalTransformation(); // TODO Add this method. public int getChildCount(); public void onAttached(); public void onDetached(); public void attachChild(final IEntity pEntity); public boolean attachChild(final IEntity pEntity, final int pIndex); public IEntity getChild(final int pIndex); public IEntity getFirstChild(); public IEntity getLastChild(); public int getChildIndex(final IEntity pEntity); public boolean setChildIndex(final IEntity pEntity, final int pIndex); public IEntity findChild(final IEntityMatcher pEntityMatcher); public boolean swapChildren(final int pIndexA, final int pIndexB); public boolean swapChildren(final IEntity pEntityA, final IEntity pEntityB); /** * Sorts the {@link IEntity}s based on their ZIndex. Sort is stable. */ public void sortChildren(); /** * Sorts the {@link IEntity}s based on the {@link Comparator} supplied. Sort is stable. * @param pEntityComparator */ public void sortChildren(final Comparator<IEntity> pEntityComparator); public boolean detachSelf(); /** * <b><i>WARNING:</i> This function should be called from within * {@link RunnableHandler#postRunnable(Runnable)} which is registered * to a {@link Scene} or the {@link Engine} itself, because otherwise * it may throw an {@link IndexOutOfBoundsException} in the * Update-Thread or the GL-Thread!</b> */ public boolean detachChild(final IEntity pEntity); /** * <b><i>WARNING:</i> This function should be called from within * {@link RunnableHandler#postRunnable(Runnable)} which is registered * to a {@link Scene} or the {@link Engine} itself, because otherwise * it may throw an {@link IndexOutOfBoundsException} in the * Update-Thread or the GL-Thread!</b> */ public IEntity detachChild(final IEntityMatcher pEntityMatcher); /** * <b><i>WARNING:</i> This function should be called from within * {@link RunnableHandler#postRunnable(Runnable)} which is registered * to a {@link Scene} or the {@link Engine} itself, because otherwise * it may throw an {@link IndexOutOfBoundsException} in the * Update-Thread or the GL-Thread!</b> */ public boolean detachChildren(final IEntityMatcher pEntityMatcher); public void detachChildren(); public void callOnChildren(final IEntityCallable pEntityCallable); public void callOnChildren(final IEntityMatcher pEntityMatcher, final IEntityCallable pEntityCallable); public void registerUpdateHandler(final IUpdateHandler pUpdateHandler); public boolean unregisterUpdateHandler(final IUpdateHandler pUpdateHandler); public boolean unregisterUpdateHandlers(final IUpdateHandlerMatcher pUpdateHandlerMatcher); public void clearUpdateHandlers(); public void registerEntityModifier(final IEntityModifier pEntityModifier); public boolean unregisterEntityModifier(final IEntityModifier pEntityModifier); public boolean unregisterEntityModifiers(final IEntityModifierMatcher pEntityModifierMatcher); public void clearEntityModifiers(); public void setUserData(Object pUserData); public Object getUserData(); // =========================================================== // Inner and Anonymous Classes // =========================================================== public interface IEntityMatcher extends IMatcher<IEntity> { // =========================================================== // Constants // =========================================================== // =========================================================== // Methods // =========================================================== @Override public boolean matches(final IEntity pEntity); } public interface IEntityCallable extends ParameterCallable<IEntity> { // =========================================================== // Constants // =========================================================== // =========================================================== // Methods // =========================================================== @Override public void call(final IEntity pEntity); } }
Java
package org.anddev.andengine.entity.particle.emitter; 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.util.MathUtils; import org.anddev.andengine.util.constants.MathConstants; import android.util.FloatMath; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 20:18:41 - 01.10.2010 */ public class CircleOutlineParticleEmitter extends BaseCircleParticleEmitter { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== public CircleOutlineParticleEmitter(final float pCenterX, final float pCenterY, final float pRadius) { super(pCenterX, pCenterY, pRadius); } public CircleOutlineParticleEmitter(final float pCenterX, final float pCenterY, final float pRadiusX, final float pRadiusY) { super(pCenterX, pCenterY, pRadiusX, pRadiusY); } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public void getPositionOffset(final float[] pOffset) { final float random = MathUtils.RANDOM.nextFloat() * MathConstants.PI * 2; pOffset[VERTEX_INDEX_X] = this.mCenterX + FloatMath.cos(random) * this.mRadiusX; pOffset[VERTEX_INDEX_Y] = this.mCenterY + FloatMath.sin(random) * this.mRadiusY; } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.entity.particle.emitter; 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.util.MathUtils; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 15:48:00 - 01.10.2010 */ public class RectangleOutlineParticleEmitter extends BaseRectangleParticleEmitter { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== public RectangleOutlineParticleEmitter(final float pCenterX, final float pCenterY, final float pWidth, final float pHeight) { super(pCenterX, pCenterY, pWidth, pHeight); } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public void getPositionOffset(final float[] pOffset) { pOffset[VERTEX_INDEX_X] = this.mCenterX + MathUtils.randomSign() * this.mWidthHalf; pOffset[VERTEX_INDEX_Y] = this.mCenterY + MathUtils.randomSign() * this.mHeightHalf; } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.entity.particle.emitter; 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.util.MathUtils; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 15:48:00 - 01.10.2010 */ public class RectangleParticleEmitter extends BaseRectangleParticleEmitter { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== public RectangleParticleEmitter(final float pCenterX, final float pCenterY, final float pWidth, final float pHeight) { super(pCenterX, pCenterY, pWidth, pHeight); } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public void getPositionOffset(final float[] pOffset) { pOffset[VERTEX_INDEX_X] = this.mCenterX - this.mWidthHalf + MathUtils.RANDOM.nextFloat() * this.mWidth; pOffset[VERTEX_INDEX_Y] = this.mCenterY - this.mHeightHalf + MathUtils.RANDOM.nextFloat() * this.mHeight; } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.entity.particle.emitter; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 18:53:18 - 01.10.2010 */ public abstract class BaseRectangleParticleEmitter extends BaseParticleEmitter { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== protected float mWidth; protected float mHeight; protected float mWidthHalf; protected float mHeightHalf; // =========================================================== // Constructors // =========================================================== public BaseRectangleParticleEmitter(final float pCenterX, final float pCenterY, final float pSize) { this(pCenterX, pCenterY, pSize, pSize); } public BaseRectangleParticleEmitter(final float pCenterX, final float pCenterY, final float pWidth, final float pHeight) { super(pCenterX, pCenterY); this.setWidth(pWidth); this.setHeight(pHeight); } // =========================================================== // Getter & Setter // =========================================================== public float getWidth() { return this.mWidth; } public void setWidth(final float pWidth) { this.mWidth = pWidth; this.mWidthHalf = pWidth * 0.5f; } public float getHeight() { return this.mHeight; } public void setHeight(final float pHeight) { this.mHeight = pHeight; this.mHeightHalf = pHeight * 0.5f; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.entity.particle.emitter; import static org.anddev.andengine.util.constants.Constants.VERTEX_INDEX_X; import static org.anddev.andengine.util.constants.Constants.VERTEX_INDEX_Y; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 23:14:42 - 01.10.2010 */ public class PointParticleEmitter extends BaseParticleEmitter { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== public PointParticleEmitter(final float pCenterX, final float pCenterY) { super(pCenterX, pCenterY); } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public void getPositionOffset(final float[] pOffset) { pOffset[VERTEX_INDEX_X] = this.mCenterX; pOffset[VERTEX_INDEX_Y] = this.mCenterY; } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.entity.particle.emitter; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 15:58:12 - 01.10.2010 */ public abstract class BaseParticleEmitter implements IParticleEmitter { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== protected float mCenterX; protected float mCenterY; // =========================================================== // Constructors // =========================================================== public BaseParticleEmitter(final float pCenterX, final float pCenterY) { this.mCenterX = pCenterX; this.mCenterY = pCenterY; } // =========================================================== // Getter & Setter // =========================================================== public float getCenterX() { return this.mCenterX; } public float getCenterY() { return this.mCenterY; } public void setCenterX(final float pCenterX) { this.mCenterX = pCenterX; } public void setCenterY(final float pCenterY) { this.mCenterY = pCenterY; } public void setCenter(final float pCenterX, final float pCenterY) { this.mCenterX = pCenterX; this.mCenterY = pCenterY; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public void onUpdate(final float pSecondsElapsed) { } @Override public void reset() { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.entity.particle.emitter; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 20:14:43 - 01.10.2010 */ public abstract class BaseCircleParticleEmitter extends BaseParticleEmitter { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== protected float mRadiusX; protected float mRadiusY; // =========================================================== // Constructors // =========================================================== public BaseCircleParticleEmitter(final float pCenterX, final float pCenterY, final float pRadius) { this(pCenterX, pCenterY, pRadius, pRadius); } public BaseCircleParticleEmitter(final float pCenterX, final float pCenterY, final float pRadiusX, final float pRadiusY) { super(pCenterX, pCenterY); this.setRadiusX(pRadiusX); this.setRadiusY(pRadiusY); } // =========================================================== // Getter & Setter // =========================================================== public float getRadiusX() { return this.mRadiusX; } public void setRadiusX(final float pRadiusX) { this.mRadiusX = pRadiusX; } public float getRadiusY() { return this.mRadiusY; } public void setRadiusY(final float pRadiusY) { this.mRadiusY = pRadiusY; } public void setRadius(final float pRadius) { this.mRadiusX = pRadius; this.mRadiusY = pRadius; } public void setRadius(final float pRadiusX, final float pRadiusY) { this.mRadiusX = pRadiusX; this.mRadiusY = pRadiusY; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.entity.particle.emitter; import org.anddev.andengine.engine.handler.IUpdateHandler; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 15:48:09 - 01.10.2010 */ public interface IParticleEmitter extends IUpdateHandler { // =========================================================== // Final Fields // =========================================================== // =========================================================== // Methods // =========================================================== public void getPositionOffset(final float[] pOffset); }
Java
package org.anddev.andengine.entity.particle.emitter; 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.util.MathUtils; import org.anddev.andengine.util.constants.MathConstants; import android.util.FloatMath; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 20:18:41 - 01.10.2010 */ public class CircleParticleEmitter extends BaseCircleParticleEmitter { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== public CircleParticleEmitter(final float pCenterX, final float pCenterY, final float pRadius) { super(pCenterX, pCenterY, pRadius); } public CircleParticleEmitter(final float pCenterX, final float pCenterY, final float pRadiusX, final float pRadiusY) { super(pCenterX, pCenterY, pRadiusX, pRadiusY); } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public void getPositionOffset(final float[] pOffset) { final float random = MathUtils.RANDOM.nextFloat() * MathConstants.PI * 2; pOffset[VERTEX_INDEX_X] = this.mCenterX + FloatMath.cos(random) * this.mRadiusX * MathUtils.RANDOM.nextFloat(); pOffset[VERTEX_INDEX_Y] = this.mCenterY + FloatMath.sin(random) * this.mRadiusY * MathUtils.RANDOM.nextFloat(); } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.entity.particle.initializer; import org.anddev.andengine.entity.particle.Particle; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 10:17:42 - 29.06.2010 */ public class RotationInitializer extends BaseSingleValueInitializer { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== public RotationInitializer(final float pRotation) { this(pRotation, pRotation); } public RotationInitializer(final float pMinRotation, final float pMaxRotation) { super(pMinRotation, pMaxRotation); } // =========================================================== // Getter & Setter // =========================================================== public float getMinRotation() { return this.mMinValue; } public float getMaxRotation() { return this.mMaxValue; } public void setRotation(final float pRotation) { this.mMinValue = pRotation; this.mMaxValue = pRotation; } public void setRotation(final float pMinRotation, final float pMaxRotation) { this.mMinValue = pMinRotation; this.mMaxValue = pMaxRotation; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public void onInitializeParticle(final Particle pParticle, final float pRotation) { pParticle.setRotation(pRotation); } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.entity.particle.initializer; import android.hardware.SensorManager; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 12:04:00 - 15.03.2010 */ public class GravityInitializer extends AccelerationInitializer { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== public GravityInitializer() { super(0, SensorManager.GRAVITY_EARTH); } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.entity.particle.initializer; import static org.anddev.andengine.util.MathUtils.RANDOM; import org.anddev.andengine.entity.particle.Particle; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 15:58:29 - 04.05.2010 */ public abstract class BaseDoubleValueInitializer extends BaseSingleValueInitializer { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== protected float mMinValueB; protected float mMaxValueB; // =========================================================== // Constructors // =========================================================== public BaseDoubleValueInitializer(final float pMinValueA, final float pMaxValueA, final float pMinValueB, final float pMaxValueB) { super(pMinValueA, pMaxValueA); this.mMinValueB = pMinValueB; this.mMaxValueB = pMaxValueB; } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== protected abstract void onInitializeParticle(final Particle pParticle, final float pValueA, final float pValueB); @Override protected final void onInitializeParticle(final Particle pParticle, final float pValueA) { this.onInitializeParticle(pParticle, pValueA, this.getRandomValueB()); } // =========================================================== // Methods // =========================================================== private final float getRandomValueB() { if(this.mMinValueB == this.mMaxValueB) { return this.mMaxValueB; } else { return RANDOM.nextFloat() * (this.mMaxValueB - this.mMinValueB) + this.mMinValueB; } } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.entity.particle.initializer; import static org.anddev.andengine.util.MathUtils.RANDOM; import org.anddev.andengine.entity.particle.Particle; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 10:18:06 - 29.06.2010 */ public abstract class BaseSingleValueInitializer implements IParticleInitializer { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== protected float mMinValue; protected float mMaxValue; // =========================================================== // Constructors // =========================================================== public BaseSingleValueInitializer(final float pMinValue, final float pMaxValue) { this.mMinValue = pMinValue; this.mMaxValue = pMaxValue; } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== protected abstract void onInitializeParticle(final Particle pParticle, final float pValue); @Override public final void onInitializeParticle(final Particle pParticle) { this.onInitializeParticle(pParticle, this.getRandomValue()); } // =========================================================== // Methods // =========================================================== private final float getRandomValue() { if(this.mMinValue == this.mMaxValue) { return this.mMaxValue; } else { return RANDOM.nextFloat() * (this.mMaxValue - this.mMinValue) + this.mMinValue; } } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.entity.particle.initializer; import org.anddev.andengine.entity.particle.Particle; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 18:53:41 - 02.10.2010 */ public class AlphaInitializer extends BaseSingleValueInitializer { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== public AlphaInitializer(final float pAlpha) { super(pAlpha, pAlpha); } public AlphaInitializer(final float pMinAlpha, final float pMaxAlpha) { super(pMinAlpha, pMaxAlpha); } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override protected void onInitializeParticle(final Particle pParticle, final float pAlpha) { pParticle.setAlpha(pAlpha); } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.entity.particle.initializer; import org.anddev.andengine.entity.particle.Particle; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 21:21:10 - 14.03.2010 */ public class AccelerationInitializer extends BaseDoubleValueInitializer { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== public AccelerationInitializer(final float pAcceleration) { this(pAcceleration, pAcceleration); } public AccelerationInitializer(final float pAccelerationX, final float pAccelerationY) { this(pAccelerationX, pAccelerationX, pAccelerationY, pAccelerationY); } public AccelerationInitializer(final float pMinAccelerationX, final float pMaxAccelerationX, final float pMinAccelerationY, final float pMaxAccelerationY) { super(pMinAccelerationX, pMaxAccelerationX, pMinAccelerationY, pMaxAccelerationY); } // =========================================================== // Getter & Setter // =========================================================== public float getMinAccelerationX() { return this.mMinValue; } public float getMaxAccelerationX() { return this.mMaxValue; } public float getMinAccelerationY() { return this.mMinValueB; } public float getMaxAccelerationY() { return this.mMaxValueB; } public void setAccelerationX(final float pAccelerationX) { this.mMinValue = pAccelerationX; this.mMaxValue = pAccelerationX; } public void setAccelerationY(final float pAccelerationY) { this.mMinValueB = pAccelerationY; this.mMaxValueB = pAccelerationY; } public void setAccelerationX(final float pMinAccelerationX, final float pMaxAccelerationX) { this.mMinValue = pMinAccelerationX; this.mMaxValue = pMaxAccelerationX; } public void setAccelerationY(final float pMinAccelerationY, final float pMaxAccelerationY) { this.mMinValueB = pMinAccelerationY; this.mMaxValueB = pMaxAccelerationY; } public void setAcceleration(final float pMinAccelerationX, final float pMaxAccelerationX, final float pMinAccelerationY, final float pMaxAccelerationY) { this.mMinValue = pMinAccelerationX; this.mMaxValue = pMaxAccelerationX; this.mMinValueB = pMinAccelerationY; this.mMaxValueB = pMaxAccelerationY; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public void onInitializeParticle(final Particle pParticle, final float pAccelerationX, final float pAccelerationY) { pParticle.getPhysicsHandler().accelerate(pAccelerationX, pAccelerationY); } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.entity.particle.initializer; import org.anddev.andengine.entity.particle.Particle; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 10:17:42 - 29.06.2010 */ public class ColorInitializer extends BaseTripleValueInitializer { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== public ColorInitializer(final float pRed, final float pGreen, final float pBlue) { super(pRed, pRed, pGreen, pGreen, pBlue, pBlue); } public ColorInitializer(final float pMinRed, final float pMaxRed, final float pMinGreen, final float pMaxGreen, final float pMinBlue, final float pMaxBlue) { super(pMinRed, pMaxRed, pMinGreen, pMaxGreen, pMinBlue, pMaxBlue); } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override protected void onInitializeParticle(final Particle pParticle, final float pRed, final float pGreen, final float pBlue) { pParticle.setColor(pRed, pGreen, pBlue); } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.entity.particle.initializer; import org.anddev.andengine.entity.particle.Particle; import org.anddev.andengine.entity.particle.initializer.BaseSingleValueInitializer; /** * (c) 2011 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Scott Kennedy * @since 15:14:00 - 08.08.2011 */ public class ScaleInitializer extends BaseSingleValueInitializer { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== public ScaleInitializer(final float pScale) { this(pScale, pScale); } public ScaleInitializer(final float pMinScale, final float pMaxScale) { super(pMinScale, pMaxScale); } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override protected void onInitializeParticle(final Particle pParticle, final float pScale) { pParticle.setScale(pScale); } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.entity.particle.initializer; import org.anddev.andengine.entity.particle.Particle; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 21:21:10 - 14.03.2010 */ public class VelocityInitializer extends BaseDoubleValueInitializer { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== public VelocityInitializer(final float pVelocity) { this(pVelocity, pVelocity, pVelocity, pVelocity); } public VelocityInitializer(final float pVelocityX, final float pVelocityY) { this(pVelocityX, pVelocityX, pVelocityY, pVelocityY); } public VelocityInitializer(final float pMinVelocityX, final float pMaxVelocityX, final float pMinVelocityY, final float pMaxVelocityY) { super(pMinVelocityX, pMaxVelocityX, pMinVelocityY, pMaxVelocityY); } // =========================================================== // Getter & Setter // =========================================================== public float getMinVelocityX() { return this.mMinValue; } public float getMaxVelocityX() { return this.mMaxValue; } public float getMinVelocityY() { return this.mMinValueB; } public float getMaxVelocityY() { return this.mMaxValueB; } public void setVelocityX(final float pVelocityX) { this.mMinValue = pVelocityX; this.mMaxValue = pVelocityX; } public void setVelocityY(final float pVelocityY) { this.mMinValueB = pVelocityY; this.mMaxValueB = pVelocityY; } public void setVelocityX(final float pMinVelocityX, final float pMaxVelocityX) { this.mMinValue = pMinVelocityX; this.mMaxValue = pMaxVelocityX; } public void setVelocityY(final float pMinVelocityY, final float pMaxVelocityY) { this.mMinValueB = pMinVelocityY; this.mMaxValueB = pMaxVelocityY; } public void setVelocity(final float pMinVelocityX, final float pMaxVelocityX, final float pMinVelocityY, final float pMaxVelocityY) { this.mMinValue = pMinVelocityX; this.mMaxValue = pMaxVelocityX; this.mMinValueB = pMinVelocityY; this.mMaxValueB = pMaxVelocityY; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public void onInitializeParticle(final Particle pParticle, final float pVelocityX, final float pVelocityY) { pParticle.getPhysicsHandler().setVelocity(pVelocityX, pVelocityY); } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.entity.particle.initializer; import static org.anddev.andengine.util.MathUtils.RANDOM; import org.anddev.andengine.entity.particle.Particle; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 15:58:29 - 04.05.2010 */ public abstract class BaseTripleValueInitializer extends BaseDoubleValueInitializer { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== protected float mMinValueC; protected float mMaxValueC; // =========================================================== // Constructors // =========================================================== public BaseTripleValueInitializer(final float pMinValueA, final float pMaxValueA, final float pMinValueB, final float pMaxValueB, final float pMinValueC, final float pMaxValueC) { super(pMinValueA, pMaxValueA, pMinValueB, pMaxValueB); this.mMinValueC = pMinValueC; this.mMaxValueC = pMaxValueC; } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== protected abstract void onInitializeParticle(final Particle pParticle, final float pValueA, final float pValueB, final float pValueC); @Override protected final void onInitializeParticle(final Particle pParticle, final float pValueA, final float pValueB) { this.onInitializeParticle(pParticle, pValueA, pValueB, this.getRandomValueC()); } // =========================================================== // Methods // =========================================================== private final float getRandomValueC() { if(this.mMinValueC == this.mMaxValueC) { return this.mMaxValueC; } else { return RANDOM.nextFloat() * (this.mMaxValueC - this.mMinValueC) + this.mMinValueC; } } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.entity.particle.initializer; import org.anddev.andengine.entity.particle.Particle; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 10:12:09 - 29.06.2010 */ public interface IParticleInitializer { // =========================================================== // Final Fields // =========================================================== // =========================================================== // Methods // =========================================================== public void onInitializeParticle(final Particle pParticle); }
Java
package org.anddev.andengine.entity.particle; import static org.anddev.andengine.util.MathUtils.RANDOM; import static org.anddev.andengine.util.constants.Constants.VERTEX_INDEX_X; import static org.anddev.andengine.util.constants.Constants.VERTEX_INDEX_Y; import java.util.ArrayList; import javax.microedition.khronos.opengles.GL10; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.entity.Entity; import org.anddev.andengine.entity.particle.emitter.IParticleEmitter; import org.anddev.andengine.entity.particle.emitter.RectangleParticleEmitter; import org.anddev.andengine.entity.particle.initializer.IParticleInitializer; import org.anddev.andengine.entity.particle.modifier.IParticleModifier; import org.anddev.andengine.opengl.texture.region.TextureRegion; import org.anddev.andengine.opengl.vertex.RectangleVertexBuffer; import android.util.FloatMath; /** * TODO Check if SpriteBatch can be used here to improve performance. * * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 19:42:27 - 14.03.2010 */ public class ParticleSystem extends Entity { // =========================================================== // Constants // =========================================================== private static final int BLENDFUNCTION_SOURCE_DEFAULT = GL10.GL_ONE; private static final int BLENDFUNCTION_DESTINATION_DEFAULT = GL10.GL_ONE_MINUS_SRC_ALPHA; private final float[] POSITION_OFFSET = new float[2]; // =========================================================== // Fields // =========================================================== private final IParticleEmitter mParticleEmitter; private final Particle[] mParticles; private int mSourceBlendFunction = BLENDFUNCTION_SOURCE_DEFAULT; private int mDestinationBlendFunction = BLENDFUNCTION_DESTINATION_DEFAULT; private final ArrayList<IParticleInitializer> mParticleInitializers = new ArrayList<IParticleInitializer>(); private final ArrayList<IParticleModifier> mParticleModifiers = new ArrayList<IParticleModifier>(); private final float mRateMinimum; private final float mRateMaximum; private final TextureRegion mTextureRegion; private boolean mParticlesSpawnEnabled = true; private final int mParticlesMaximum; private int mParticlesAlive; private float mParticlesDueToSpawn; private int mParticleModifierCount; private int mParticleInitializerCount; private RectangleVertexBuffer mSharedParticleVertexBuffer; // =========================================================== // Constructors // =========================================================== /** * Creates a ParticleSystem with a {@link RectangleParticleEmitter}. * @deprecated Instead use {@link ParticleSystem#ParticleSystem(IParticleEmitter, float, float, int, TextureRegion)}. */ @Deprecated public ParticleSystem(final float pX, final float pY, final float pWidth, final float pHeight, final float pRateMinimum, final float pRateMaximum, final int pParticlesMaximum, final TextureRegion pTextureRegion) { this(new RectangleParticleEmitter(pX + pWidth * 0.5f, pY + pHeight * 0.5f, pWidth, pHeight), pRateMinimum, pRateMaximum, pParticlesMaximum, pTextureRegion); } public ParticleSystem(final IParticleEmitter pParticleEmitter, final float pRateMinimum, final float pRateMaximum, final int pParticlesMaximum, final TextureRegion pTextureRegion) { super(0, 0); this.mParticleEmitter = pParticleEmitter; this.mParticles = new Particle[pParticlesMaximum]; this.mRateMinimum = pRateMinimum; this.mRateMaximum = pRateMaximum; this.mParticlesMaximum = pParticlesMaximum; this.mTextureRegion = pTextureRegion; this.registerUpdateHandler(this.mParticleEmitter); } // =========================================================== // Getter & Setter // =========================================================== public boolean isParticlesSpawnEnabled() { return this.mParticlesSpawnEnabled; } public void setParticlesSpawnEnabled(final boolean pParticlesSpawnEnabled) { this.mParticlesSpawnEnabled = pParticlesSpawnEnabled; } public void setBlendFunction(final int pSourceBlendFunction, final int pDestinationBlendFunction) { this.mSourceBlendFunction = pSourceBlendFunction; this.mDestinationBlendFunction = pDestinationBlendFunction; } public IParticleEmitter getParticleEmitter() { return this.mParticleEmitter; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public void reset() { super.reset(); this.mParticlesDueToSpawn = 0; this.mParticlesAlive = 0; } @Override protected void onManagedDraw(final GL10 pGL, final Camera pCamera) { final Particle[] particles = this.mParticles; for(int i = this.mParticlesAlive - 1; i >= 0; i--) { particles[i].onDraw(pGL, pCamera); } } @Override protected void onManagedUpdate(final float pSecondsElapsed) { super.onManagedUpdate(pSecondsElapsed); if(this.mParticlesSpawnEnabled) { this.spawnParticles(pSecondsElapsed); } final Particle[] particles = this.mParticles; final ArrayList<IParticleModifier> particleModifiers = this.mParticleModifiers; final int particleModifierCountMinusOne = this.mParticleModifierCount - 1; for(int i = this.mParticlesAlive - 1; i >= 0; i--) { final Particle particle = particles[i]; /* Apply all particleModifiers */ for(int j = particleModifierCountMinusOne; j >= 0; j--) { particleModifiers.get(j).onUpdateParticle(particle); } particle.onUpdate(pSecondsElapsed); if(particle.mDead){ this.mParticlesAlive--; final int particlesAlive = this.mParticlesAlive; particles[i] = particles[particlesAlive]; particles[particlesAlive] = particle; } } } // =========================================================== // Methods // =========================================================== public void addParticleModifier(final IParticleModifier pParticleModifier) { this.mParticleModifiers.add(pParticleModifier); this.mParticleModifierCount++; } public void removeParticleModifier(final IParticleModifier pParticleModifier) { this.mParticleModifierCount--; this.mParticleModifiers.remove(pParticleModifier); } public void addParticleInitializer(final IParticleInitializer pParticleInitializer) { this.mParticleInitializers.add(pParticleInitializer); this.mParticleInitializerCount++; } public void removeParticleInitializer(final IParticleInitializer pParticleInitializer) { this.mParticleInitializerCount--; this.mParticleInitializers.remove(pParticleInitializer); } private void spawnParticles(final float pSecondsElapsed) { final float currentRate = this.determineCurrentRate(); final float newParticlesThisFrame = currentRate * pSecondsElapsed; this.mParticlesDueToSpawn += newParticlesThisFrame; final int particlesToSpawnThisFrame = Math.min(this.mParticlesMaximum - this.mParticlesAlive, (int)FloatMath.floor(this.mParticlesDueToSpawn)); this.mParticlesDueToSpawn -= particlesToSpawnThisFrame; for(int i = 0; i < particlesToSpawnThisFrame; i++){ this.spawnParticle(); } } private void spawnParticle() { final Particle[] particles = this.mParticles; final int particlesAlive = this.mParticlesAlive; if(particlesAlive < this.mParticlesMaximum){ Particle particle = particles[particlesAlive]; /* New particle needs to be created. */ this.mParticleEmitter.getPositionOffset(this.POSITION_OFFSET); final float x = this.POSITION_OFFSET[VERTEX_INDEX_X]; final float y = this.POSITION_OFFSET[VERTEX_INDEX_Y]; if(particle != null) { particle.reset(); particle.setPosition(x, y); } else { if(particlesAlive == 0) { /* This is the very first particle. */ particle = new Particle(x, y, this.mTextureRegion); this.mSharedParticleVertexBuffer = particle.getVertexBuffer(); } else { particle = new Particle(x, y, this.mTextureRegion, this.mSharedParticleVertexBuffer); } particles[particlesAlive] = particle; } particle.setBlendFunction(this.mSourceBlendFunction, this.mDestinationBlendFunction); /* Apply particle initializers. */ { final ArrayList<IParticleInitializer> particleInitializers = this.mParticleInitializers; for(int i = this.mParticleInitializerCount - 1; i >= 0; i--) { particleInitializers.get(i).onInitializeParticle(particle); } final ArrayList<IParticleModifier> particleModifiers = this.mParticleModifiers; for(int i = this.mParticleModifierCount - 1; i >= 0; i--) { particleModifiers.get(i).onInitializeParticle(particle); } } this.mParticlesAlive++; } } private float determineCurrentRate() { if(this.mRateMinimum == this.mRateMaximum){ return this.mRateMinimum; } else { return (RANDOM.nextFloat() * (this.mRateMaximum - this.mRateMinimum)) + this.mRateMinimum; } } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.entity.particle; import org.anddev.andengine.engine.handler.physics.PhysicsHandler; import org.anddev.andengine.entity.sprite.Sprite; import org.anddev.andengine.opengl.texture.region.TextureRegion; import org.anddev.andengine.opengl.vertex.RectangleVertexBuffer; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 19:37:13 - 14.03.2010 */ public class Particle extends Sprite { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private float mLifeTime; private float mDeathTime = -1; boolean mDead = false; private final PhysicsHandler mPhysicsHandler = new PhysicsHandler(this); // =========================================================== // Constructors // ===========================================================; public Particle(final float pX, final float pY, final TextureRegion pTextureRegion) { super(pX, pY, pTextureRegion); this.mLifeTime = 0; } public Particle(final float pX, final float pY, final TextureRegion pTextureRegion, final RectangleVertexBuffer pRectangleVertexBuffer) { super(pX, pY, pTextureRegion, pRectangleVertexBuffer); this.mLifeTime = 0; } // =========================================================== // Getter & Setter // =========================================================== public float getLifeTime() { return this.mLifeTime; } public float getDeathTime() { return this.mDeathTime; } public void setDeathTime(final float pDeathTime) { this.mDeathTime = pDeathTime; } public boolean isDead() { return this.mDead ; } public void setDead(final boolean pDead) { this.mDead = pDead; } public PhysicsHandler getPhysicsHandler() { return this.mPhysicsHandler; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override protected void onManagedUpdate(final float pSecondsElapsed) { if(!this.mDead){ this.mLifeTime += pSecondsElapsed; this.mPhysicsHandler.onUpdate(pSecondsElapsed); super.onManagedUpdate(pSecondsElapsed); final float deathTime = this.mDeathTime; if(deathTime != -1 && this.mLifeTime > deathTime) { this.setDead(true); } } } // =========================================================== // Methods // =========================================================== @Override public void reset() { super.reset(); this.mPhysicsHandler.reset(); this.mDead = false; this.mDeathTime = -1; this.mLifeTime = 0; } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.entity.particle.modifier; import org.anddev.andengine.entity.particle.Particle; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 15:22:26 - 29.06.2010 */ public class ColorModifier extends BaseTripleValueSpanModifier { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== public ColorModifier(final float pFromRed, final float pToRed, final float pFromGreen, final float pToGreen, final float pFromBlue, final float pToBlue, final float pFromTime, final float pToTime) { super(pFromRed, pToRed, pFromGreen, pToGreen, pFromBlue, pToBlue, pFromTime, pToTime); } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override protected void onSetInitialValues(final Particle pParticle, final float pRed, final float pGreen, final float pBlue) { pParticle.setColor(pRed, pGreen, pBlue); } @Override protected void onSetValues(final Particle pParticle, final float pRed, final float pGreen, final float pBlue) { pParticle.setColor(pRed, pGreen, pBlue); } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.entity.particle.modifier; import static org.anddev.andengine.util.MathUtils.RANDOM; import org.anddev.andengine.entity.particle.Particle; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 21:21:10 - 14.03.2010 */ public class ExpireModifier implements IParticleModifier { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private float mMinLifeTime; private float mMaxLifeTime; // =========================================================== // Constructors // =========================================================== public ExpireModifier(final float pLifeTime) { this(pLifeTime, pLifeTime); } public ExpireModifier(final float pMinLifeTime, final float pMaxLifeTime) { this.mMinLifeTime = pMinLifeTime; this.mMaxLifeTime = pMaxLifeTime; } // =========================================================== // Getter & Setter // =========================================================== public float getMinLifeTime() { return this.mMinLifeTime; } public float getMaxLifeTime() { return this.mMaxLifeTime; } public void setLifeTime(final float pLifeTime) { this.mMinLifeTime = pLifeTime; this.mMaxLifeTime = pLifeTime; } public void setLifeTime(final float pMinLifeTime, final float pMaxLifeTime) { this.mMinLifeTime = pMinLifeTime; this.mMaxLifeTime = pMaxLifeTime; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public void onInitializeParticle(final Particle pParticle) { pParticle.setDeathTime((RANDOM.nextFloat() * (this.mMaxLifeTime - this.mMinLifeTime) + this.mMinLifeTime)); } @Override public void onUpdateParticle(final Particle pParticle) { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.entity.particle.modifier; import org.anddev.andengine.entity.particle.Particle; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 20:37:27 - 04.05.2010 */ public class ScaleModifier extends BaseDoubleValueSpanModifier { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== public ScaleModifier(final float pFromScale, final float pToScale, final float pFromTime, final float pToTime) { this(pFromScale, pToScale, pFromScale, pToScale, pFromTime, pToTime); } public ScaleModifier(final float pFromScaleX, final float pToScaleX, final float pFromScaleY, final float pToScaleY, final float pFromTime, final float pToTime) { super(pFromScaleX, pToScaleX, pFromScaleY, pToScaleY, pFromTime, pToTime); } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override protected void onSetInitialValues(final Particle pParticle, final float pScaleX, final float pScaleY) { pParticle.setScale(pScaleX, pScaleY); } @Override protected void onSetValues(final Particle pParticle, final float pScaleX, final float pScaleY) { pParticle.setScale(pScaleX, pScaleY); } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.entity.particle.modifier; import org.anddev.andengine.entity.particle.Particle; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 10:36:18 - 29.06.2010 */ public class RotationModifier extends BaseSingleValueSpanModifier { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== public RotationModifier(final float pFromRotation, final float pToRotation, final float pFromTime, final float pToTime) { super(pFromRotation, pToRotation, pFromTime, pToTime); } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override protected void onSetInitialValue(final Particle pParticle, final float pRotation) { pParticle.setRotation(pRotation); } @Override protected void onSetValue(final Particle pParticle, final float pRotation) { pParticle.setRotation(pRotation); } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.entity.particle.modifier; import java.util.ArrayList; import java.util.List; import org.anddev.andengine.entity.particle.Particle; /** * <p>An {@link ExpireModifier} that holds other {@link BaseSingleValueSpanModifier}s, overriding their * <code>toTime</code>s to match the <code>lifeTime</code> of the particle based on the value from the * ExpireModifier.</p> * * <p>(c) 2011 Nicolas Gramlich<br> * (c) 2011 Zynga Inc.</p> * * @author Scott Kennedy * @since 21:01:00 - 08.08.2011 */ public class ContainerExpireModifier extends ExpireModifier { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private final List<BaseSingleValueSpanModifier> mModifiers = new ArrayList<BaseSingleValueSpanModifier>(); // =========================================================== // Constructors // =========================================================== public ContainerExpireModifier(final float pLifeTime) { super(pLifeTime); } public ContainerExpireModifier(final float pMinLifeTime, final float pMaxLifeTime) { super(pMinLifeTime, pMaxLifeTime); } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public void onUpdateParticle(final Particle pParticle) { // Apply all the contained modifiers for (final BaseSingleValueSpanModifier modifier : mModifiers) { modifier.onUpdateParticle(pParticle, pParticle.getDeathTime()); } } // =========================================================== // Methods // =========================================================== /** * <p>Adds the specified modifier to the contained modifier list.</p> * * <p>The <code>toTime</code> in the modifier will be ignored, and replaced with the actual * lifetime of the {@link Particle}.</p> * * @param pModifier The modifier to add */ public void addParticleModifier(final BaseSingleValueSpanModifier pModifier) { mModifiers.add(pModifier); } /** * <p>Removes the specified modifier from the contained modifier list.</p> * @param pModifier The modifier to remove * @return true if the list was modified by this operation, false otherwise. */ public boolean removeParticleModifier(final BaseSingleValueSpanModifier pModifier) { return mModifiers.remove(pModifier); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.entity.particle.modifier; import org.anddev.andengine.entity.particle.Particle; import org.anddev.andengine.entity.particle.initializer.IParticleInitializer; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 20:06:05 - 14.03.2010 */ public interface IParticleModifier extends IParticleInitializer { // =========================================================== // Final Fields // =========================================================== // =========================================================== // Methods // =========================================================== public void onUpdateParticle(final Particle pParticle); }
Java
package org.anddev.andengine.entity.particle.modifier; import org.anddev.andengine.entity.particle.Particle; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 16:10:16 - 04.05.2010 */ public abstract class BaseSingleValueSpanModifier implements IParticleModifier { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private final float mFromValue; private final float mToValue; private final float mFromTime; private final float mToTime; private final float mDuration; private final float mSpanValue; // =========================================================== // Constructors // =========================================================== public BaseSingleValueSpanModifier(final float pFromValue, final float pToValue, final float pFromTime, final float pToTime) { this.mFromValue = pFromValue; this.mToValue = pToValue; this.mFromTime = pFromTime; this.mToTime = pToTime; this.mSpanValue = this.mToValue - this.mFromValue; this.mDuration = this.mToTime - this.mFromTime; } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== protected abstract void onSetInitialValue(final Particle pParticle, final float pValue); protected abstract void onSetValue(final Particle pParticle, final float pValue); @Override public void onInitializeParticle(final Particle pParticle) { this.onSetInitialValue(pParticle, this.mFromValue); } @Override public void onUpdateParticle(final Particle pParticle) { final float lifeTime = pParticle.getLifeTime(); if(lifeTime > this.mFromTime && lifeTime < this.mToTime) { final float percent = (lifeTime - this.mFromTime) / this.mDuration; this.onSetValueInternal(pParticle, percent); } } public void onUpdateParticle(final Particle pParticle, final float overrideToTime) { final float lifeTime = pParticle.getLifeTime(); if (lifeTime > this.mFromTime) { final float percent = (lifeTime - this.mFromTime) / (overrideToTime - this.mFromTime); this.onSetValueInternal(pParticle, percent); } } protected void onSetValueInternal(final Particle pParticle, final float pPercent) { this.onSetValue(pParticle, this.calculateValue(pPercent)); } protected final float calculateValue(final float pPercent) { return this.mFromValue + this.mSpanValue * pPercent; } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.entity.particle.modifier; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.entity.particle.Particle; import org.anddev.andengine.entity.particle.modifier.OffCameraExpireModifier; /** * <p>Causes the particle to expire after it has entered and left the view of the camera.</p> * * <p>This allows you to create a particle off camera, move it on camera, and have it expire once it leaves the camera.</p> * * <p>(c) 2011 Nicolas Gramlich<br> * (c) 2011 Zynga Inc.</p> * * @author Scott Kennedy * @since 27:10:00 - 08.08.2011 */ public class OnAndOffCameraExpireModifier extends OffCameraExpireModifier { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private boolean mHasBeenOnCamera = false; // =========================================================== // Constructors // =========================================================== public OnAndOffCameraExpireModifier(final Camera pCamera) { super(pCamera); } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public void onUpdateParticle(final Particle pParticle) { if(!this.mHasBeenOnCamera && getCamera().isRectangularShapeVisible(pParticle)) { mHasBeenOnCamera = true; } if(this.mHasBeenOnCamera) { super.onUpdateParticle(pParticle); } } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.entity.particle.modifier; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.entity.particle.Particle; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 21:21:10 - 14.03.2010 */ public class OffCameraExpireModifier implements IParticleModifier { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private final Camera mCamera; // =========================================================== // Constructors // =========================================================== public OffCameraExpireModifier(final Camera pCamera) { this.mCamera = pCamera; } // =========================================================== // Getter & Setter // =========================================================== public Camera getCamera() { return this.mCamera; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public void onInitializeParticle(final Particle pParticle) { } @Override public void onUpdateParticle(final Particle pParticle) { if(!this.mCamera.isRectangularShapeVisible(pParticle)) { pParticle.setDead(true); } } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.entity.particle.modifier; import org.anddev.andengine.entity.particle.Particle; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 15:19:46 - 29.06.2010 */ public abstract class BaseDoubleValueSpanModifier extends BaseSingleValueSpanModifier { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private final float mFromValueB; private final float mToValueB; private final float mSpanValueB; // =========================================================== // Constructors // =========================================================== public BaseDoubleValueSpanModifier(final float pFromValueA, final float pToValueA, final float pFromValueB, final float pToValueB, final float pFromTime, final float pToTime) { super(pFromValueA, pToValueA, pFromTime, pToTime); this.mFromValueB = pFromValueB; this.mToValueB = pToValueB; this.mSpanValueB = this.mToValueB - this.mFromValueB; } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override @Deprecated protected void onSetValue(final Particle pParticle, final float pValue) { } protected abstract void onSetInitialValues(final Particle pParticle, final float pValueA, final float pValueB); protected abstract void onSetValues(final Particle pParticle, final float pValueA, final float pValueB); @Override public void onSetInitialValue(final Particle pParticle, final float pValueA) { this.onSetInitialValues(pParticle, pValueA, this.mFromValueB); } @Override protected void onSetValueInternal(final Particle pParticle, final float pPercent) { this.onSetValues(pParticle, super.calculateValue(pPercent), this.calculateValueB(pPercent)); } // =========================================================== // Methods // =========================================================== protected final float calculateValueB(final float pPercent) { return this.mFromValueB + this.mSpanValueB * pPercent; } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.entity.particle.modifier; import org.anddev.andengine.entity.particle.Particle; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 15:19:46 - 29.06.2010 */ public abstract class BaseTripleValueSpanModifier extends BaseDoubleValueSpanModifier { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private final float mFromValueC; private final float mToValueC; private final float mSpanValueC; // =========================================================== // Constructors // =========================================================== public BaseTripleValueSpanModifier(final float pFromValueA, final float pToValueA, final float pFromValueB, final float pToValueB, final float pFromValueC, final float pToValueC, final float pFromTime, final float pToTime) { super(pFromValueA, pToValueA, pFromValueB, pToValueB, pFromTime, pToTime); this.mFromValueC = pFromValueC; this.mToValueC = pToValueC; this.mSpanValueC = this.mToValueC - this.mFromValueC; } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== protected abstract void onSetInitialValues(final Particle pParticle, final float pValueA, final float pValueB, final float pValueC); protected abstract void onSetValues(final Particle pParticle, final float pValueA, final float pValueB, final float pValueC); @Override @Deprecated protected void onSetValues(final Particle pParticle, final float pValueA, final float pValueB) { } @Override public void onSetInitialValues(final Particle pParticle, final float pValueA, final float pValueB) { this.onSetInitialValues(pParticle, pValueA, pValueB, this.mFromValueC); } @Override protected void onSetValueInternal(final Particle pParticle, final float pPercent) { this.onSetValues(pParticle, super.calculateValue(pPercent), super.calculateValueB(pPercent), this.calculateValueC(pPercent)); } // =========================================================== // Methods // =========================================================== private final float calculateValueC(final float pPercent) { return this.mFromValueC + this.mSpanValueC * pPercent; } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.entity.particle.modifier; import org.anddev.andengine.entity.particle.Particle; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 21:21:10 - 14.03.2010 */ public class AlphaModifier extends BaseSingleValueSpanModifier { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== public AlphaModifier(final float pFromAlpha, final float pToAlpha, final float pFromTime, final float pToTime) { super(pFromAlpha, pToAlpha, pFromTime, pToTime); } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override protected void onSetInitialValue(final Particle pParticle, final float pAlpha) { pParticle.setAlpha(pAlpha); } @Override protected void onSetValue(final Particle pParticle, final float pAlpha) { pParticle.setAlpha(pAlpha); } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.entity.shape; import javax.microedition.khronos.opengles.GL10; import org.anddev.andengine.collision.RectangularShapeCollisionChecker; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.entity.primitive.Line; import org.anddev.andengine.opengl.vertex.VertexBuffer; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 11:37:50 - 04.04.2010 */ public abstract class RectangularShape extends Shape { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== protected float mBaseWidth; protected float mBaseHeight; protected float mWidth; protected float mHeight; protected final VertexBuffer mVertexBuffer; // =========================================================== // Constructors // =========================================================== public RectangularShape(final float pX, final float pY, final float pWidth, final float pHeight, final VertexBuffer pVertexBuffer) { super(pX, pY); this.mBaseWidth = pWidth; this.mBaseHeight = pHeight; this.mWidth = pWidth; this.mHeight = pHeight; this.mVertexBuffer = pVertexBuffer; this.mRotationCenterX = pWidth * 0.5f; this.mRotationCenterY = pHeight * 0.5f; this.mScaleCenterX = this.mRotationCenterX; this.mScaleCenterY = this.mRotationCenterY; } // =========================================================== // Getter & Setter // =========================================================== @Override public VertexBuffer getVertexBuffer() { return this.mVertexBuffer; } @Override public float getWidth() { return this.mWidth; } @Override public float getHeight() { return this.mHeight; } @Override public float getBaseWidth() { return this.mBaseWidth; } @Override public float getBaseHeight() { return this.mBaseHeight; } public void setWidth(final float pWidth) { this.mWidth = pWidth; this.updateVertexBuffer(); } public void setHeight(final float pHeight) { this.mHeight = pHeight; this.updateVertexBuffer(); } public void setSize(final float pWidth, final float pHeight) { this.mWidth = pWidth; this.mHeight = pHeight; this.updateVertexBuffer(); } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== public void setBaseSize() { if(this.mWidth != this.mBaseWidth || this.mHeight != this.mBaseHeight) { this.mWidth = this.mBaseWidth; this.mHeight = this.mBaseHeight; this.updateVertexBuffer(); } } @Override protected boolean isCulled(final Camera pCamera) { // TODO Advanced culling! final float x = this.mX; final float y = this.mY; return x > pCamera.getMaxX() || y > pCamera.getMaxY() || x + this.getWidth() < pCamera.getMinX() || y + this.getHeight() < pCamera.getMinY(); } @Override protected void drawVertices(final GL10 pGL, final Camera pCamera) { pGL.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, 4); } @Override public void reset() { super.reset(); this.setBaseSize(); final float baseWidth = this.getBaseWidth(); final float baseHeight = this.getBaseHeight(); this.mRotationCenterX = baseWidth * 0.5f; this.mRotationCenterY = baseHeight * 0.5f; this.mScaleCenterX = this.mRotationCenterX; this.mScaleCenterY = this.mRotationCenterY; } @Override public boolean contains(final float pX, final float pY) { return RectangularShapeCollisionChecker.checkContains(this, pX, pY); } @Override public float[] getSceneCenterCoordinates() { return this.convertLocalToSceneCoordinates(this.mWidth * 0.5f, this.mHeight * 0.5f); } @Override public boolean collidesWith(final IShape pOtherShape) { if(pOtherShape instanceof RectangularShape) { final RectangularShape pOtherRectangularShape = (RectangularShape) pOtherShape; return RectangularShapeCollisionChecker.checkCollision(this, pOtherRectangularShape); } else if(pOtherShape instanceof Line) { final Line line = (Line) pOtherShape; return RectangularShapeCollisionChecker.checkCollision(this, line); } else { return false; } } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.entity.shape; import org.anddev.andengine.entity.IEntity; import org.anddev.andengine.entity.scene.Scene.ITouchArea; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 13:32:52 - 07.07.2010 */ public interface IShape extends IEntity, ITouchArea { // =========================================================== // Final Fields // =========================================================== // =========================================================== // Methods // =========================================================== public boolean isCullingEnabled(); public void setCullingEnabled(final boolean pCullingEnabled); public float getWidth(); public float getHeight(); public float getBaseWidth(); public float getBaseHeight(); public float getWidthScaled(); public float getHeightScaled(); // public boolean isVisible(final Camera pCamera); // TODO. Could be use for automated culling. public boolean collidesWith(final IShape pOtherShape); public void setBlendFunction(final int pSourceBlendFunction, final int pDestinationBlendFunction); }
Java
package org.anddev.andengine.entity.shape; import javax.microedition.khronos.opengles.GL10; import javax.microedition.khronos.opengles.GL11; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.entity.Entity; import org.anddev.andengine.input.touch.TouchEvent; import org.anddev.andengine.opengl.buffer.BufferObjectManager; import org.anddev.andengine.opengl.util.GLHelper; import org.anddev.andengine.opengl.vertex.VertexBuffer; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 11:51:27 - 13.03.2010 */ public abstract class Shape extends Entity implements IShape { // =========================================================== // Constants // =========================================================== public static final int BLENDFUNCTION_SOURCE_DEFAULT = GL10.GL_SRC_ALPHA; public static final int BLENDFUNCTION_DESTINATION_DEFAULT = GL10.GL_ONE_MINUS_SRC_ALPHA; public static final int BLENDFUNCTION_SOURCE_PREMULTIPLYALPHA_DEFAULT = GL10.GL_ONE; public static final int BLENDFUNCTION_DESTINATION_PREMULTIPLYALPHA_DEFAULT = GL10.GL_ONE_MINUS_SRC_ALPHA; // =========================================================== // Fields // =========================================================== protected int mSourceBlendFunction = BLENDFUNCTION_SOURCE_DEFAULT; protected int mDestinationBlendFunction = BLENDFUNCTION_DESTINATION_DEFAULT; private boolean mCullingEnabled = false; // =========================================================== // Constructors // =========================================================== public Shape(final float pX, final float pY) { super(pX, pY); } // =========================================================== // Getter & Setter // =========================================================== @Override public void setBlendFunction(final int pSourceBlendFunction, final int pDestinationBlendFunction) { this.mSourceBlendFunction = pSourceBlendFunction; this.mDestinationBlendFunction = pDestinationBlendFunction; } @Override public boolean isCullingEnabled() { return this.mCullingEnabled; } @Override public void setCullingEnabled(final boolean pCullingEnabled) { this.mCullingEnabled = pCullingEnabled; } @Override public float getWidthScaled() { return this.getWidth() * this.mScaleX; } @Override public float getHeightScaled() { return this.getHeight() * this.mScaleY; } public boolean isVertexBufferManaged() { return this.getVertexBuffer().isManaged(); } /** * @param pVertexBufferManaged when passing <code>true</code> this {@link Shape} will make its {@link VertexBuffer} unload itself from the active {@link BufferObjectManager}, when this {@link Shape} is finalized/garbage-collected. <b><u>WARNING:</u></b> When passing <code>false</code> one needs to take care of that by oneself! */ public void setVertexBufferManaged(final boolean pVertexBufferManaged) { this.getVertexBuffer().setManaged(pVertexBufferManaged); } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== protected abstract void onUpdateVertexBuffer(); protected abstract VertexBuffer getVertexBuffer(); protected abstract void drawVertices(final GL10 pGL, final Camera pCamera); @Override protected void doDraw(final GL10 pGL, final Camera pCamera) { this.onInitDraw(pGL); this.onApplyVertices(pGL); this.drawVertices(pGL, pCamera); } @Override public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final float pTouchAreaLocalX, final float pTouchAreaLocalY) { return false; } /** * Will only be performed if {@link Shape#isCullingEnabled()} is true. * @param pCamera * @return <code>true</code> when this object is visible by the {@link Camera}, <code>false</code> otherwise. */ protected abstract boolean isCulled(final Camera pCamera); @Override protected void onManagedDraw(final GL10 pGL, final Camera pCamera) { if(!this.mCullingEnabled || !this.isCulled(pCamera)) { super.onManagedDraw(pGL, pCamera); } } @Override public void reset() { super.reset(); this.mSourceBlendFunction = BLENDFUNCTION_SOURCE_DEFAULT; this.mDestinationBlendFunction = BLENDFUNCTION_DESTINATION_DEFAULT; } @Override protected void finalize() throws Throwable { super.finalize(); final VertexBuffer vertexBuffer = this.getVertexBuffer(); if(vertexBuffer.isManaged()) { vertexBuffer.unloadFromActiveBufferObjectManager(); } } // =========================================================== // Methods // =========================================================== protected void onInitDraw(final GL10 pGL) { GLHelper.setColor(pGL, this.mRed, this.mGreen, this.mBlue, this.mAlpha); GLHelper.enableVertexArray(pGL); GLHelper.blendFunction(pGL, this.mSourceBlendFunction, this.mDestinationBlendFunction); } protected void onApplyVertices(final GL10 pGL) { if(GLHelper.EXTENSIONS_VERTEXBUFFEROBJECTS) { final GL11 gl11 = (GL11)pGL; this.getVertexBuffer().selectOnHardware(gl11); GLHelper.vertexZeroPointer(gl11); } else { GLHelper.vertexPointer(pGL, this.getVertexBuffer().getFloatBuffer()); } } protected void updateVertexBuffer() { this.onUpdateVertexBuffer(); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.entity; import java.util.Comparator; import java.util.List; import org.anddev.andengine.util.sort.InsertionSorter; public class ZIndexSorter extends InsertionSorter<IEntity> { // =========================================================== // Constants // =========================================================== private static ZIndexSorter INSTANCE; // =========================================================== // Fields // =========================================================== private final Comparator<IEntity> mZIndexComparator = new Comparator<IEntity>() { @Override public int compare(final IEntity pEntityA, final IEntity pEntityB) { return pEntityA.getZIndex() - pEntityB.getZIndex(); } }; // =========================================================== // Constructors // =========================================================== private ZIndexSorter() { } public static ZIndexSorter getInstance() { if(INSTANCE == null) { INSTANCE = new ZIndexSorter(); } return INSTANCE; } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== public void sort(final IEntity[] pEntities) { this.sort(pEntities, this.mZIndexComparator); } public void sort(final IEntity[] pEntities, final int pStart, final int pEnd) { this.sort(pEntities, pStart, pEnd, this.mZIndexComparator); } public void sort(final List<IEntity> pEntities) { this.sort(pEntities, this.mZIndexComparator); } public void sort(final List<IEntity> pEntities, final int pStart, final int pEnd) { this.sort(pEntities, pStart, pEnd, this.mZIndexComparator); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.audio.sound; import org.anddev.andengine.audio.BaseAudioManager; import android.media.AudioManager; import android.media.SoundPool; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 13:22:59 - 11.03.2010 */ public class SoundManager extends BaseAudioManager<Sound> { // =========================================================== // Constants // =========================================================== private static final int MAX_SIMULTANEOUS_STREAMS_DEFAULT = 5; // =========================================================== // Fields // =========================================================== private final SoundPool mSoundPool; // =========================================================== // Constructors // =========================================================== public SoundManager() { this(MAX_SIMULTANEOUS_STREAMS_DEFAULT); } public SoundManager(final int pMaxSimultaneousStreams) { this.mSoundPool = new SoundPool(pMaxSimultaneousStreams, AudioManager.STREAM_MUSIC, 0); } // =========================================================== // Getter & Setter // =========================================================== SoundPool getSoundPool() { return this.mSoundPool; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== @Override public void releaseAll() { super.releaseAll(); this.mSoundPool.release(); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.audio.sound; import org.anddev.andengine.audio.BaseAudioEntity; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 13:22:15 - 11.03.2010 */ public class Sound extends BaseAudioEntity { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private final int mSoundID; private int mStreamID = 0; private int mLoopCount = 0; private float mRate = 1.0f; // =========================================================== // Constructors // =========================================================== Sound(final SoundManager pSoundManager, final int pSoundID) { super(pSoundManager); this.mSoundID = pSoundID; } // =========================================================== // Getter & Setter // =========================================================== public void setLoopCount(final int pLoopCount) { this.mLoopCount = pLoopCount; if(this.mStreamID != 0) { this.getAudioManager().getSoundPool().setLoop(this.mStreamID, pLoopCount); } } public void setRate(final float pRate) { this.mRate = pRate; if(this.mStreamID != 0) { this.getAudioManager().getSoundPool().setRate(this.mStreamID, pRate); } } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== @Override protected SoundManager getAudioManager() { return (SoundManager)super.getAudioManager(); } @Override public void play() { final float masterVolume = this.getMasterVolume(); final float leftVolume = this.mLeftVolume * masterVolume; final float rightVolume = this.mRightVolume * masterVolume; this.mStreamID = this.getAudioManager().getSoundPool().play(this.mSoundID, leftVolume, rightVolume, 1, this.mLoopCount, this.mRate); } @Override public void stop() { if(this.mStreamID != 0) { this.getAudioManager().getSoundPool().stop(this.mStreamID); } } @Override public void resume() { if(this.mStreamID != 0) { this.getAudioManager().getSoundPool().resume(this.mStreamID); } } @Override public void pause() { if(this.mStreamID != 0) { this.getAudioManager().getSoundPool().pause(this.mStreamID); } } @Override public void release() { } @Override public void setLooping(final boolean pLooping) { this.setLoopCount((pLooping) ? -1 : 0); } @Override public void setVolume(final float pLeftVolume, final float pRightVolume) { super.setVolume(pLeftVolume, pRightVolume); if(this.mStreamID != 0){ final float masterVolume = this.getMasterVolume(); final float leftVolume = this.mLeftVolume * masterVolume; final float rightVolume = this.mRightVolume * masterVolume; this.getAudioManager().getSoundPool().setVolume(this.mStreamID, leftVolume, rightVolume); } } @Override public void onMasterVolumeChanged(final float pMasterVolume) { this.setVolume(this.mLeftVolume, this.mRightVolume); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.audio.sound; import java.io.FileDescriptor; import java.io.IOException; import android.content.Context; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 14:23:03 - 11.03.2010 */ public class SoundFactory { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private static String sAssetBasePath = ""; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== /** * @param pAssetBasePath must end with '<code>/</code>' or have <code>.length() == 0</code>. */ public static void setAssetBasePath(final String pAssetBasePath) { if(pAssetBasePath.endsWith("/") || pAssetBasePath.length() == 0) { SoundFactory.sAssetBasePath = pAssetBasePath; } else { throw new IllegalStateException("pAssetBasePath must end with '/' or be lenght zero."); } } public static void reset() { SoundFactory.setAssetBasePath(""); } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== public static Sound createSoundFromPath(final SoundManager pSoundManager, final String pPath) throws IOException { final int soundID = pSoundManager.getSoundPool().load(pPath, 1); final Sound sound = new Sound(pSoundManager, soundID); pSoundManager.add(sound); return sound; } public static Sound createSoundFromAsset(final SoundManager pSoundManager, final Context pContext, final String pAssetPath) throws IOException { final int soundID = pSoundManager.getSoundPool().load(pContext.getAssets().openFd(SoundFactory.sAssetBasePath + pAssetPath), 1); final Sound sound = new Sound(pSoundManager, soundID); pSoundManager.add(sound); return sound; } public static Sound createSoundFromResource(final SoundManager pSoundManager, final Context pContext, final int pSoundResID) { final int soundID = pSoundManager.getSoundPool().load(pContext, pSoundResID, 1); final Sound sound = new Sound(pSoundManager, soundID); pSoundManager.add(sound); return sound; } public static Sound createSoundFromFileDescriptor(final SoundManager pSoundManager, final FileDescriptor pFileDescriptor, final long pOffset, final long pLength) throws IOException { final int soundID = pSoundManager.getSoundPool().load(pFileDescriptor, pOffset, pLength, 1); final Sound sound = new Sound(pSoundManager, soundID); pSoundManager.add(sound); return sound; } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.audio.sound; import org.anddev.andengine.util.Library; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 20:41:56 - 20.08.2010 */ public class SoundLibrary extends Library<Sound> { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.audio; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 16:35:37 - 13.06.2010 */ public abstract class BaseAudioEntity implements IAudioEntity { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private final IAudioManager<? extends IAudioEntity> mAudioManager; protected float mLeftVolume = 1.0f; protected float mRightVolume = 1.0f; // =========================================================== // Constructors // =========================================================== public BaseAudioEntity(final IAudioManager<? extends IAudioEntity> pAudioManager) { this.mAudioManager = pAudioManager; } // =========================================================== // Getter & Setter // =========================================================== protected IAudioManager<? extends IAudioEntity> getAudioManager() { return this.mAudioManager; } public float getActualLeftVolume() { return this.mLeftVolume * this.getMasterVolume(); } public float getActualRightVolume() { return this.mRightVolume * this.getMasterVolume(); } protected float getMasterVolume() { return this.mAudioManager.getMasterVolume(); } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public float getVolume() { return (this.mLeftVolume + this.mRightVolume) * 0.5f; } @Override public float getLeftVolume() { return this.mLeftVolume; } @Override public float getRightVolume() { return this.mRightVolume; } @Override public final void setVolume(final float pVolume) { this.setVolume(pVolume, pVolume); } @Override public void setVolume(final float pLeftVolume, final float pRightVolume) { this.mLeftVolume = pLeftVolume; this.mRightVolume = pRightVolume; } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.audio.music; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import android.content.Context; import android.content.res.AssetFileDescriptor; import android.media.MediaPlayer; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 15:05:49 - 13.06.2010 */ public class MusicFactory { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private static String sAssetBasePath = ""; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== /** * @param pAssetBasePath must end with '<code>/</code>' or have <code>.length() == 0</code>. */ public static void setAssetBasePath(final String pAssetBasePath) { if(pAssetBasePath.endsWith("/") || pAssetBasePath.length() == 0) { MusicFactory.sAssetBasePath = pAssetBasePath; } else { throw new IllegalStateException("pAssetBasePath must end with '/' or be lenght zero."); } } public static void reset() { MusicFactory.setAssetBasePath(""); } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== public static Music createMusicFromFile(final MusicManager pMusicManager, final File pFile) throws IOException { final MediaPlayer mediaPlayer = new MediaPlayer(); mediaPlayer.setDataSource(new FileInputStream(pFile).getFD()); mediaPlayer.prepare(); final Music music = new Music(pMusicManager, mediaPlayer); pMusicManager.add(music); return music; } public static Music createMusicFromAsset(final MusicManager pMusicManager, final Context pContext, final String pAssetPath) throws IOException { final MediaPlayer mediaPlayer = new MediaPlayer(); final AssetFileDescriptor assetFileDescritor = pContext.getAssets().openFd(MusicFactory.sAssetBasePath + pAssetPath); mediaPlayer.setDataSource(assetFileDescritor.getFileDescriptor(), assetFileDescritor.getStartOffset(), assetFileDescritor.getLength()); mediaPlayer.prepare(); final Music music = new Music(pMusicManager, mediaPlayer); pMusicManager.add(music); return music; } public static Music createMusicFromResource(final MusicManager pMusicManager, final Context pContext, final int pMusicResID) throws IOException { final MediaPlayer mediaPlayer = MediaPlayer.create(pContext, pMusicResID); mediaPlayer.prepare(); final Music music = new Music(pMusicManager, mediaPlayer); pMusicManager.add(music); return music; } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.audio.music; import org.anddev.andengine.audio.BaseAudioManager; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 15:01:23 - 13.06.2010 */ public class MusicManager extends BaseAudioManager<Music> { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== public MusicManager() { } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.audio.music; import org.anddev.andengine.audio.BaseAudioEntity; import android.media.MediaPlayer; import android.media.MediaPlayer.OnCompletionListener; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 14:53:12 - 13.06.2010 */ public class Music extends BaseAudioEntity { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private final MediaPlayer mMediaPlayer; // =========================================================== // Constructors // =========================================================== Music(final MusicManager pMusicManager, final MediaPlayer pMediaPlayer) { super(pMusicManager); this.mMediaPlayer = pMediaPlayer; } // =========================================================== // Getter & Setter // =========================================================== public boolean isPlaying() { return this.mMediaPlayer.isPlaying(); } public MediaPlayer getMediaPlayer() { return this.mMediaPlayer; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override protected MusicManager getAudioManager() { return (MusicManager)super.getAudioManager(); } @Override public void play() { this.mMediaPlayer.start(); } @Override public void stop() { this.mMediaPlayer.stop(); } @Override public void resume() { this.mMediaPlayer.start(); } @Override public void pause() { this.mMediaPlayer.pause(); } @Override public void release() { this.mMediaPlayer.release(); } @Override public void setLooping(final boolean pLooping) { this.mMediaPlayer.setLooping(pLooping); } @Override public void setVolume(final float pLeftVolume, final float pRightVolume) { super.setVolume(pLeftVolume, pRightVolume); final float masterVolume = this.getAudioManager().getMasterVolume(); final float actualLeftVolume = pLeftVolume * masterVolume; final float actualRightVolume = pRightVolume * masterVolume; this.mMediaPlayer.setVolume(actualLeftVolume, actualRightVolume); } @Override public void onMasterVolumeChanged(final float pMasterVolume) { this.setVolume(this.mLeftVolume, this.mRightVolume); } // =========================================================== // Methods // =========================================================== public void seekTo(final int pMilliseconds) { this.mMediaPlayer.seekTo(pMilliseconds); } public void setOnCompletionListener(final OnCompletionListener pOnCompletionListener) { this.mMediaPlayer.setOnCompletionListener(pOnCompletionListener); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.audio; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 15:02:06 - 13.06.2010 */ public interface IAudioManager<T extends IAudioEntity> { // =========================================================== // Final Fields // =========================================================== // =========================================================== // Methods // =========================================================== public float getMasterVolume(); public void setMasterVolume(final float pMasterVolume); public void add(final T pAudioEntity); public void releaseAll(); }
Java
package org.anddev.andengine.audio; import java.util.ArrayList; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 18:07:02 - 13.06.2010 */ public abstract class BaseAudioManager<T extends IAudioEntity> implements IAudioManager<T> { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== protected final ArrayList<T> mAudioEntities = new ArrayList<T>(); protected float mMasterVolume = 1.0f; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public float getMasterVolume() { return this.mMasterVolume; } @Override public void setMasterVolume(final float pMasterVolume) { this.mMasterVolume = pMasterVolume; final ArrayList<T> audioEntities = this.mAudioEntities; for(int i = audioEntities.size() - 1; i >= 0; i--) { final T audioEntity = audioEntities.get(i); audioEntity.onMasterVolumeChanged(pMasterVolume); } } @Override public void add(final T pAudioEntity) { this.mAudioEntities.add(pAudioEntity); } @Override public void releaseAll() { final ArrayList<T> audioEntities = this.mAudioEntities; for(int i = audioEntities.size() - 1; i >= 0; i--) { final T audioEntity = audioEntities.get(i); audioEntity.stop(); audioEntity.release(); } } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.audio; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 14:53:29 - 13.06.2010 */ public interface IAudioEntity { // =========================================================== // Final Fields // =========================================================== // =========================================================== // Methods // =========================================================== public void play(); public void pause(); public void resume(); public void stop(); public float getVolume(); public void setVolume(final float pVolume); public float getLeftVolume(); public float getRightVolume(); public void setVolume(final float pLeftVolume, final float pRightVolume); public void onMasterVolumeChanged(final float pMasterVolume); public void setLooping(final boolean pLooping); public void release(); }
Java
package org.anddev.andengine.ui.activity; import org.anddev.andengine.audio.music.MusicManager; import org.anddev.andengine.audio.sound.SoundManager; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.WakeLockOptions; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.opengl.font.FontManager; import org.anddev.andengine.opengl.texture.TextureManager; import org.anddev.andengine.opengl.view.RenderSurfaceView; 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.LocationSensorOptions; import org.anddev.andengine.sensor.orientation.IOrientationListener; import org.anddev.andengine.sensor.orientation.OrientationSensorOptions; import org.anddev.andengine.ui.IGameInterface; import org.anddev.andengine.util.ActivityUtils; import org.anddev.andengine.util.Debug; import android.content.Context; import android.content.pm.ActivityInfo; import android.media.AudioManager; import android.os.Bundle; import android.os.PowerManager; import android.os.PowerManager.WakeLock; import android.view.Gravity; import android.widget.FrameLayout.LayoutParams; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 11:27:06 - 08.03.2010 */ public abstract class BaseGameActivity extends BaseActivity implements IGameInterface { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== protected Engine mEngine; private WakeLock mWakeLock; protected RenderSurfaceView mRenderSurfaceView; protected boolean mHasWindowFocused; private boolean mPaused; private boolean mGameLoaded; // =========================================================== // Constructors // =========================================================== @Override protected void onCreate(final Bundle pSavedInstanceState) { super.onCreate(pSavedInstanceState); this.mPaused = true; this.mEngine = this.onLoadEngine(); this.applyEngineOptions(this.mEngine.getEngineOptions()); this.onSetContentView(); } @Override protected void onResume() { super.onResume(); if(this.mPaused && this.mHasWindowFocused) { this.doResume(); } } @Override public void onWindowFocusChanged(final boolean pHasWindowFocus) { super.onWindowFocusChanged(pHasWindowFocus); if(pHasWindowFocus) { if(this.mPaused) { this.doResume(); } this.mHasWindowFocused = true; } else { if(!this.mPaused) { this.doPause(); } this.mHasWindowFocused = false; } } @Override protected void onPause() { super.onPause(); if(!this.mPaused) { this.doPause(); } } @Override protected void onDestroy() { super.onDestroy(); this.mEngine.interruptUpdateThread(); this.onUnloadResources(); } @Override public void onUnloadResources() { if(this.mEngine.getEngineOptions().needsMusic()) { this.getMusicManager().releaseAll(); } if(this.mEngine.getEngineOptions().needsSound()) { this.getSoundManager().releaseAll(); } } // =========================================================== // Getter & Setter // =========================================================== public Engine getEngine() { return this.mEngine; } public TextureManager getTextureManager() { return this.mEngine.getTextureManager(); } public FontManager getFontManager() { return this.getFontManager(); } public SoundManager getSoundManager() { return this.mEngine.getSoundManager(); } public MusicManager getMusicManager() { return this.mEngine.getMusicManager(); } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public void onResumeGame() { } @Override public void onPauseGame() { } // =========================================================== // Methods // =========================================================== private void doResume() { if(!this.mGameLoaded) { this.onLoadResources(); final Scene scene = this.onLoadScene(); this.mEngine.onLoadComplete(scene); this.onLoadComplete(); this.mGameLoaded = true; } this.mPaused = false; this.acquireWakeLock(this.mEngine.getEngineOptions().getWakeLockOptions()); this.mEngine.onResume(); this.mRenderSurfaceView.onResume(); this.mEngine.start(); this.onResumeGame(); } private void doPause() { this.mPaused = true; this.releaseWakeLock(); this.mEngine.onPause(); this.mEngine.stop(); this.mRenderSurfaceView.onPause(); this.onPauseGame(); } public void runOnUpdateThread(final Runnable pRunnable) { this.mEngine.runOnUpdateThread(pRunnable); } protected void onSetContentView() { this.mRenderSurfaceView = new RenderSurfaceView(this); this.mRenderSurfaceView.setEGLConfigChooser(false); this.mRenderSurfaceView.setRenderer(this.mEngine); this.setContentView(this.mRenderSurfaceView, this.createSurfaceViewLayoutParams()); } private void acquireWakeLock(final WakeLockOptions pWakeLockOptions) { if(pWakeLockOptions == WakeLockOptions.SCREEN_ON) { ActivityUtils.keepScreenOn(this); } else { final PowerManager pm = (PowerManager) this.getSystemService(Context.POWER_SERVICE); this.mWakeLock = pm.newWakeLock(pWakeLockOptions.getFlag() | PowerManager.ON_AFTER_RELEASE, "AndEngine"); try { this.mWakeLock.acquire(); } catch (final SecurityException e) { Debug.e("You have to add\n\t<uses-permission android:name=\"android.permission.WAKE_LOCK\"/>\nto your AndroidManifest.xml !", e); } } } private void releaseWakeLock() { if(this.mWakeLock != null && this.mWakeLock.isHeld()) { this.mWakeLock.release(); } } private void applyEngineOptions(final EngineOptions pEngineOptions) { if(pEngineOptions.isFullscreen()) { ActivityUtils.requestFullscreen(this); } if(pEngineOptions.needsMusic() || pEngineOptions.needsSound()) { this.setVolumeControlStream(AudioManager.STREAM_MUSIC); } switch(pEngineOptions.getScreenOrientation()) { case LANDSCAPE: this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); break; case PORTRAIT: this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); break; } } protected LayoutParams createSurfaceViewLayoutParams() { final LayoutParams layoutParams = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT); layoutParams.gravity = Gravity.CENTER; return layoutParams; } protected void enableVibrator() { this.mEngine.enableVibrator(this); } /** * @see {@link Engine#enableLocationSensor(Context, ILocationListener, LocationSensorOptions)} */ protected void enableLocationSensor(final ILocationListener pLocationListener, final LocationSensorOptions pLocationSensorOptions) { this.mEngine.enableLocationSensor(this, pLocationListener, pLocationSensorOptions); } /** * @see {@link Engine#disableLocationSensor(Context)} */ protected void disableLocationSensor() { this.mEngine.disableLocationSensor(this); } /** * @see {@link Engine#enableAccelerometerSensor(Context, IAccelerometerListener)} */ protected boolean enableAccelerometerSensor(final IAccelerometerListener pAccelerometerListener) { return this.mEngine.enableAccelerometerSensor(this, pAccelerometerListener); } /** * @see {@link Engine#enableAccelerometerSensor(Context, IAccelerometerListener, AccelerometerSensorOptions)} */ protected boolean enableAccelerometerSensor(final IAccelerometerListener pAccelerometerListener, final AccelerometerSensorOptions pAccelerometerSensorOptions) { return this.mEngine.enableAccelerometerSensor(this, pAccelerometerListener, pAccelerometerSensorOptions); } /** * @see {@link Engine#disableAccelerometerSensor(Context)} */ protected boolean disableAccelerometerSensor() { return this.mEngine.disableAccelerometerSensor(this); } /** * @see {@link Engine#enableOrientationSensor(Context, IOrientationListener)} */ protected boolean enableOrientationSensor(final IOrientationListener pOrientationListener) { return this.mEngine.enableOrientationSensor(this, pOrientationListener); } /** * @see {@link Engine#enableOrientationSensor(Context, IOrientationListener, OrientationSensorOptions)} */ protected boolean enableOrientationSensor(final IOrientationListener pOrientationListener, final OrientationSensorOptions pLocationSensorOptions) { return this.mEngine.enableOrientationSensor(this, pOrientationListener, pLocationSensorOptions); } /** * @see {@link Engine#disableOrientationSensor(Context)} */ protected boolean disableOrientationSensor() { return this.mEngine.disableOrientationSensor(this); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.ui.activity; import org.anddev.andengine.opengl.view.RenderSurfaceView; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 10:18:50 - 06.10.2010 */ public abstract class LayoutGameActivity extends BaseGameActivity { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== protected abstract int getLayoutID(); protected abstract int getRenderSurfaceViewID(); @Override protected void onSetContentView() { super.setContentView(this.getLayoutID()); this.mRenderSurfaceView = (RenderSurfaceView) this.findViewById(this.getRenderSurfaceViewID()); this.mRenderSurfaceView.setEGLConfigChooser(false); this.mRenderSurfaceView.setRenderer(this.mEngine); } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.ui.activity; import java.util.concurrent.Callable; import org.anddev.andengine.util.ActivityUtils; import org.anddev.andengine.util.AsyncCallable; import org.anddev.andengine.util.Callback; import org.anddev.andengine.util.progress.ProgressCallable; import android.app.Activity; import android.app.ProgressDialog; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 18:35:28 - 29.08.2009 */ public abstract class BaseActivity extends Activity { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== /** * Performs a task in the background, showing a {@link ProgressDialog}, * while the {@link Callable} is being processed. * * @param <T> * @param pTitleResID * @param pMessageResID * @param pErrorMessageResID * @param pCallable * @param pCallback */ protected <T> void doAsync(final int pTitleResID, final int pMessageResID, final Callable<T> pCallable, final Callback<T> pCallback) { this.doAsync(pTitleResID, pMessageResID, pCallable, pCallback, null); } /** * Performs a task in the background, showing a indeterminate {@link ProgressDialog}, * while the {@link Callable} is being processed. * * @param <T> * @param pTitleResID * @param pMessageResID * @param pErrorMessageResID * @param pCallable * @param pCallback * @param pExceptionCallback */ protected <T> void doAsync(final int pTitleResID, final int pMessageResID, final Callable<T> pCallable, final Callback<T> pCallback, final Callback<Exception> pExceptionCallback) { ActivityUtils.doAsync(this, pTitleResID, pMessageResID, pCallable, pCallback, pExceptionCallback); } /** * Performs a task in the background, showing a {@link ProgressDialog} with an ProgressBar, * while the {@link AsyncCallable} is being processed. * * @param <T> * @param pTitleResID * @param pMessageResID * @param pErrorMessageResID * @param pAsyncCallable * @param pCallback */ protected <T> void doProgressAsync(final int pTitleResID, final ProgressCallable<T> pCallable, final Callback<T> pCallback) { this.doProgressAsync(pTitleResID, pCallable, pCallback, null); } /** * Performs a task in the background, showing a {@link ProgressDialog} with a ProgressBar, * while the {@link AsyncCallable} is being processed. * * @param <T> * @param pTitleResID * @param pMessageResID * @param pErrorMessageResID * @param pAsyncCallable * @param pCallback * @param pExceptionCallback */ protected <T> void doProgressAsync(final int pTitleResID, final ProgressCallable<T> pCallable, final Callback<T> pCallback, final Callback<Exception> pExceptionCallback) { ActivityUtils.doProgressAsync(this, pTitleResID, pCallable, pCallback, pExceptionCallback); } /** * Performs a task in the background, showing an indeterminate {@link ProgressDialog}, * while the {@link AsyncCallable} is being processed. * * @param <T> * @param pTitleResID * @param pMessageResID * @param pErrorMessageResID * @param pAsyncCallable * @param pCallback * @param pExceptionCallback */ protected <T> void doAsync(final int pTitleResID, final int pMessageResID, final AsyncCallable<T> pAsyncCallable, final Callback<T> pCallback, final Callback<Exception> pExceptionCallback) { ActivityUtils.doAsync(this, pTitleResID, pMessageResID, pAsyncCallable, pCallback, pExceptionCallback); } // =========================================================== // Inner and Anonymous Classes // =========================================================== public static class CancelledException extends Exception { private static final long serialVersionUID = -78123211381435596L; } }
Java
package org.anddev.andengine.ui.activity; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.handler.timer.ITimerCallback; import org.anddev.andengine.engine.handler.timer.TimerHandler; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.IResolutionPolicy; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.SplashScene; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasFactory; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.atlas.bitmap.source.IBitmapTextureAtlasSource; import org.anddev.andengine.opengl.texture.bitmap.BitmapTexture.BitmapTextureFormat; import org.anddev.andengine.opengl.texture.region.TextureRegion; import android.app.Activity; import android.content.Intent; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 08:25:31 - 03.05.2010 */ public abstract class BaseSplashActivity extends BaseGameActivity { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private Camera mCamera; private IBitmapTextureAtlasSource mSplashTextureAtlasSource; private TextureRegion mLoadingScreenTextureRegion; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== protected abstract ScreenOrientation getScreenOrientation(); protected abstract IBitmapTextureAtlasSource onGetSplashTextureAtlasSource(); protected abstract float getSplashDuration(); protected abstract Class<? extends Activity> getFollowUpActivity(); protected float getSplashScaleFrom() { return 1f; } protected float getSplashScaleTo() { return 1f; } @Override public void onLoadComplete() { } @Override public Engine onLoadEngine() { this.mSplashTextureAtlasSource = this.onGetSplashTextureAtlasSource(); final int width = this.mSplashTextureAtlasSource.getWidth(); final int height = this.mSplashTextureAtlasSource.getHeight(); this.mCamera = this.getSplashCamera(width, height); return new Engine(new EngineOptions(true, this.getScreenOrientation(), this.getSplashResolutionPolicy(width, height), this.mCamera)); } @Override public void onLoadResources() { final BitmapTextureAtlas loadingScreenBitmapTextureAtlas = BitmapTextureAtlasFactory.createForTextureAtlasSourceSize(BitmapTextureFormat.RGBA_8888, this.mSplashTextureAtlasSource, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mLoadingScreenTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromSource(loadingScreenBitmapTextureAtlas, this.mSplashTextureAtlasSource, 0, 0); this.getEngine().getTextureManager().loadTexture(loadingScreenBitmapTextureAtlas); } @Override public Scene onLoadScene() { final float splashDuration = this.getSplashDuration(); final SplashScene splashScene = new SplashScene(this.mCamera, this.mLoadingScreenTextureRegion, splashDuration, this.getSplashScaleFrom(), this.getSplashScaleTo()); splashScene.registerUpdateHandler(new TimerHandler(splashDuration, new ITimerCallback() { @Override public void onTimePassed(final TimerHandler pTimerHandler) { BaseSplashActivity.this.startActivity(new Intent(BaseSplashActivity.this, BaseSplashActivity.this.getFollowUpActivity())); BaseSplashActivity.this.finish(); } })); return splashScene; } // =========================================================== // Methods // =========================================================== protected Camera getSplashCamera(final int pSplashwidth, final int pSplashHeight) { return new Camera(0, 0, pSplashwidth, pSplashHeight); } protected IResolutionPolicy getSplashResolutionPolicy(final int pSplashwidth, final int pSplashHeight) { return new RatioResolutionPolicy(pSplashwidth, pSplashHeight); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.ui; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.entity.scene.Scene; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 12:03:08 - 14.03.2010 */ public interface IGameInterface { // =========================================================== // Final Fields // =========================================================== // =========================================================== // Methods // =========================================================== public Engine onLoadEngine(); public void onLoadResources(); public void onUnloadResources(); public Scene onLoadScene(); public void onLoadComplete(); public void onPauseGame(); public void onResumeGame(); }
Java
package org.anddev.andengine.ui.dialog; import org.anddev.andengine.util.Callback; import android.content.Context; import android.content.DialogInterface.OnCancelListener; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 09:46:00 - 14.12.2009 */ public class StringInputDialogBuilder extends GenericInputDialogBuilder<String> { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== public StringInputDialogBuilder(final Context pContext, final int pTitleResID, final int pMessageResID, final int pErrorResID, final int pIconResID, final Callback<String> pSuccessCallback, final OnCancelListener pOnCancelListener) { super(pContext, pTitleResID, pMessageResID, pErrorResID, pIconResID, pSuccessCallback, pOnCancelListener); } public StringInputDialogBuilder(final Context pContext, final int pTitleResID, final int pMessageResID, final int pErrorResID, final int pIconResID, final String pDefaultText, final Callback<String> pSuccessCallback, final OnCancelListener pOnCancelListener) { super(pContext, pTitleResID, pMessageResID, pErrorResID, pIconResID, pDefaultText, pSuccessCallback, pOnCancelListener); } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override protected String generateResult(final String pInput) { return pInput; } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.ui.dialog; import org.anddev.andengine.util.Callback; import org.anddev.andengine.util.Debug; import android.app.AlertDialog; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnCancelListener; import android.content.DialogInterface.OnClickListener; import android.widget.EditText; import android.widget.Toast; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 09:35:55 - 14.12.2009 */ public abstract class GenericInputDialogBuilder<T> { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== protected final Callback<T> mSuccessCallback; protected final OnCancelListener mOnCancelListener; protected final int mTitleResID; protected final int mMessageResID; protected final int mIconResID; protected final Context mContext; private final int mErrorResID; private final String mDefaultText; // =========================================================== // Constructors // =========================================================== public GenericInputDialogBuilder(final Context pContext, final int pTitleResID, final int pMessageResID, final int pErrorResID, final int pIconResID, final Callback<T> pSuccessCallback, final OnCancelListener pOnCancelListener){ this(pContext, pTitleResID, pMessageResID, pErrorResID, pIconResID, "", pSuccessCallback, pOnCancelListener); } public GenericInputDialogBuilder(final Context pContext, final int pTitleResID, final int pMessageResID, final int pErrorResID, final int pIconResID, final String pDefaultText, final Callback<T> pSuccessCallback, final OnCancelListener pOnCancelListener){ this.mContext = pContext; this.mTitleResID = pTitleResID; this.mMessageResID = pMessageResID; this.mErrorResID = pErrorResID; this.mIconResID = pIconResID; this.mDefaultText = pDefaultText; this.mSuccessCallback = pSuccessCallback; this.mOnCancelListener = pOnCancelListener; } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== protected abstract T generateResult(final String pInput); // =========================================================== // Methods // =========================================================== public Dialog create() { final EditText etInput = new EditText(this.mContext); etInput.setText(this.mDefaultText); final AlertDialog.Builder ab = new AlertDialog.Builder(this.mContext); if(this.mTitleResID != 0) { ab.setTitle(this.mTitleResID); } if(this.mMessageResID != 0) { ab.setMessage(this.mMessageResID); } if(this.mIconResID != 0) { ab.setIcon(this.mIconResID); } this.setView(ab, etInput); ab.setOnCancelListener(this.mOnCancelListener) .setPositiveButton(android.R.string.ok, new OnClickListener() { @Override public void onClick(final DialogInterface pDialog, final int pWhich) { final T result; try{ result = GenericInputDialogBuilder.this.generateResult(etInput.getText().toString()); } catch (final IllegalArgumentException e) { Debug.e("Error in GenericInputDialogBuilder.generateResult()", e); Toast.makeText(GenericInputDialogBuilder.this.mContext, GenericInputDialogBuilder.this.mErrorResID, Toast.LENGTH_SHORT).show(); return; } GenericInputDialogBuilder.this.mSuccessCallback.onCallback(result); pDialog.dismiss(); } }) .setNegativeButton(android.R.string.cancel, new OnClickListener() { @Override public void onClick(final DialogInterface pDialog, final int pWhich) { GenericInputDialogBuilder.this.mOnCancelListener.onCancel(pDialog); pDialog.dismiss(); } }); return ab.create(); } protected void setView(final AlertDialog.Builder pBuilder, final EditText pInputEditText) { pBuilder.setView(pInputEditText); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
/* * Copyright (C) 2011 Google Inc. * * 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.ros.message; import org.jboss.netty.buffer.ChannelBuffer; /** * @author damonkohler@google.com (Damon Kohler) * * @param <T> * the type of message that the {@link MessageSerializer} can serialize */ public interface MessageSerializer<T> { void serialize(T message, ChannelBuffer buffer); }
Java
/* * Copyright (C) 2011 Google Inc. * * 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.ros.message; /** * @author damonkohler@google.com (Damon Kohler) */ public interface MessageFactory { /** * @param messageType * the type of message to create * @return a new message */ <T> T newFromType(String messageType); }
Java
/* * Software License Agreement (BSD License) * * Copyright (c) 2008, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package org.ros.message; /** * ROS Duration representation. Time and Duration are primitive types in ROS. * ROS represents each as two 32-bit integers: seconds and nanoseconds since * epoch. * * http://www.ros.org/wiki/msg * * @author Jason Wolfe * @author kwc@willowgarage.com (Ken Conley) * */ public class Duration implements Comparable<Duration> { public static final Duration MAX_VALUE = new Duration(Integer.MAX_VALUE, 999999999); public int secs; public int nsecs; public Duration() { } public Duration(int secs, int nsecs) { this.secs = secs; this.nsecs = nsecs; normalize(); } public Duration(double secs) { this.secs = (int) secs; this.nsecs = (int) ((secs - this.secs) * 1000000000); normalize(); } public Duration(Duration t) { this.secs = t.secs; this.nsecs = t.nsecs; } public Duration add(Duration d) { return new Duration(secs + d.secs, nsecs + d.nsecs); } public Duration subtract(Duration d) { return new Duration(secs - d.secs, nsecs - d.nsecs); } public static Duration fromMillis(long durationInMillis) { int secs = (int) (durationInMillis / 1000); int nsecs = (int) (durationInMillis % 1000) * 1000000; return new Duration(secs, nsecs); } public static Duration fromNano(long durationInNs) { int secs = (int) (durationInNs / 1000000000); int nsecs = (int) (durationInNs % 1000000000); return new Duration(secs, nsecs); } public void normalize() { while (nsecs < 0) { nsecs += 1000000000; secs -= 1; } while (nsecs >= 1000000000) { nsecs -= 1000000000; secs += 1; } } public long totalNsecs() { return ((long) secs) * 1000000000 + nsecs; } public boolean isZero() { return totalNsecs() == 0; } public boolean isPositive() { return totalNsecs() > 0; } public boolean isNegative() { return totalNsecs() < 0; } @Override public String toString() { return secs + ":" + nsecs; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + nsecs; result = prime * result + secs; return result; } @Override /** * Check for equality between Time objects. * equals() does not normalize Time representations, so fields must match exactly. */ public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Duration other = (Duration) obj; if (nsecs != other.nsecs) return false; if (secs != other.secs) return false; return true; } @Override public int compareTo(Duration d) { if ((secs > d.secs) || ((secs == d.secs) && nsecs > d.nsecs)) { return 1; } if ((secs == d.secs) && (nsecs == d.nsecs)) { return 0; } return -1; } }
Java
/* * Copyright (C) 2012 Google Inc. * * 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. */ /** * Provides the classes for representing messages. * * @see <a href="http://ros.org/wiki/Messages">messages documentation</a> */ package org.ros.message;
Java
/* * Copyright (C) 2011 Google Inc. * * 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.ros.message; import com.google.common.base.Preconditions; /** * Uniquely identifies a message. * * @author damonkohler@google.com (Damon Kohler) */ public class MessageIdentifier { private String type; private String pkg; private String name; public static MessageIdentifier of(String pkg, String name) { Preconditions.checkNotNull(pkg); Preconditions.checkNotNull(name); return new MessageIdentifier(pkg, name); } public static MessageIdentifier of(String type) { Preconditions.checkNotNull(type); // We're not using Preconditions.checkArgument() here because we want a // useful error message without paying the performance penalty of // constructing it every time. if (!type.contains("/")) { throw new IllegalArgumentException(String.format( "Type name is invalid or not fully qualified: \"%s\"", type)); } return new MessageIdentifier(type); } private MessageIdentifier(String type) { this.type = type; } private MessageIdentifier(String pkg, String name) { this.pkg = pkg; this.name = name; } public String getType() { if (type == null) { // Using StringBuilder like this is about 40% faster than using the + // operator. StringBuilder stringBuilder = new StringBuilder(pkg.length() + name.length() + 1); stringBuilder.append(pkg); stringBuilder.append("/"); stringBuilder.append(name); type = stringBuilder.toString(); } return type; } private void splitType() { String[] packageAndName = type.split("/", 2); pkg = packageAndName[0]; name = packageAndName[1]; } public String getPackage() { if (pkg == null) { splitType(); } return pkg; } public String getName() { if (name == null) { splitType(); } return name; } @Override public String toString() { return String.format("MessageIdentifier<%s>", type); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((type == null) ? 0 : type.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; MessageIdentifier other = (MessageIdentifier) obj; if (type == null) { if (other.type != null) return false; } else if (!type.equals(other.type)) return false; return true; } }
Java
/* * Copyright (C) 2011 Google Inc. * * 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.ros.message; public interface MessageFactoryProvider { MessageFactory get(MessageIdentifier messageIdentifier); boolean has(MessageIdentifier messageIdentifier); }
Java
/* * Copyright (C) 2011 Google Inc. * * 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.ros.message; import org.jboss.netty.buffer.ChannelBuffer; /** * @author damonkohler@google.com (Damon Kohler) * * @param <T> * the type of message that this {@link MessageDeserializer} can * deserialize */ public interface MessageDeserializer<T> { T deserialize(ChannelBuffer buffer); }
Java
/* * Copyright (C) 2011 Google Inc. * * 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.ros.message; import java.util.Collection; /** * @author damonkohler@google.com (Damon Kohler) */ public interface MessageDefinitionProvider { /** * @param messageType * the type of message definition to provide * @return the message definition for the specified type */ String get(String messageType); /** * @param messageType * the type of message definition to provide * @return {@code true} if the definition for the specified type is available, * {@code false} otherwise */ boolean has(String messageType); Collection<String> getPackages(); /** * @param pkg * the name of the package to filter on * @return the {@link MessageIdentifier}s for all messages defined in the * specified package */ Collection<MessageIdentifier> getMessageIdentifiersByPackage(String pkg); }
Java
/* * Copyright (C) 2011 Google Inc. * * 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.ros.message; /** * A callback for asynchronous message-related operations. * * @author damonkohler@google.com (Damon Kohler) * * @param <T> * the type of message expected */ public interface MessageListener<T> { /** * Called when a new message arrives. * * @param message * the new message */ void onNewMessage(T message); }
Java
/* * Software License Agreement (BSD License) * * Copyright (c) 2008, Willow Garage, Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * Redistributions in binary * form must reproduce the above copyright notice, this list of conditions and * the following disclaimer in the documentation and/or other materials provided * with the distribution. * Neither the name of Willow Garage, Inc. nor the * names of its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package org.ros.message; /** * ROS Time representation. Time and Time are primitive types in ROS. ROS * represents each as two 32-bit integers: seconds and nanoseconds since epoch. * * @see "http://www.ros.org/wiki/msg" * * @author Jason Wolfe * @author kwc@willowgarage.com (Ken Conley) */ public class Time implements Comparable<Time> { public int secs; public int nsecs; public Time() { secs = 0; nsecs = 0; } public Time(int secs, int nsecs) { this.secs = secs; this.nsecs = nsecs; normalize(); } public Time(double secs) { this.secs = (int) secs; this.nsecs = (int) ((secs - this.secs) * 1000000000); normalize(); } public Time(Time t) { this.secs = t.secs; this.nsecs = t.nsecs; } public Time add(Duration d) { return new Time(secs + d.secs, nsecs + d.nsecs); } public Time subtract(Duration d) { return new Time(secs - d.secs, nsecs - d.nsecs); } public Duration subtract(Time t) { return new Duration(secs - t.secs, nsecs - t.nsecs); } public static Time fromMillis(long timeInMillis) { int secs = (int) (timeInMillis / 1000); int nsecs = (int) (timeInMillis % 1000) * 1000000; return new Time(secs, nsecs); } public static Time fromNano(long timeInNs) { int secs = (int) (timeInNs / 1000000000); int nsecs = (int) (timeInNs % 1000000000); return new Time(secs, nsecs); } @Override public String toString() { return secs + ":" + nsecs; } public double toSeconds() { return totalNsecs() / 1e9; } public long totalNsecs() { return ((long) secs) * 1000000000 + nsecs; } public boolean isZero() { return totalNsecs() == 0; } public void normalize() { while (nsecs < 0) { nsecs += 1000000000; secs -= 1; } while (nsecs >= 1000000000) { nsecs -= 1000000000; secs += 1; } } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + nsecs; result = prime * result + secs; return result; } /** * Check for equality between {@link Time} objects. * <p> * This method does not normalize {@link Time} representations, so fields must match * exactly. */ @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Time other = (Time) obj; if (nsecs != other.nsecs) return false; if (secs != other.secs) return false; return true; } @Override public int compareTo(Time t) { if ((secs > t.secs) || ((secs == t.secs) && nsecs > t.nsecs)) { return 1; } if ((secs == t.secs) && (nsecs == t.nsecs)) { return 0; } return -1; } }
Java
/* * Copyright (C) 2011 Google Inc. * * 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.ros.message; /** * @author damonkohler@google.com (Damon Kohler) */ public interface MessageSerializationFactory { /** * @param messageType * the type of message that the new {@link MessageSerializer} should * serialize * @return a new {@link MessageSerializer} for the provided message type */ <T> MessageSerializer<T> newMessageSerializer(String messageType); /** * @param messageType * the type of message that the new {@link MessageDeserializer} * should deserialize * @return a new {@link MessageDeserializer} for the provided message type */ <T> MessageDeserializer<T> newMessageDeserializer(String messageType); /** * @param serviceType * the type of service that the new {@link MessageSerializer} should * serialize requests for * @return a new {@link MessageSerializer} for requests to the provided * service type */ <T> MessageSerializer<T> newServiceRequestSerializer(String serviceType); /** * @param serviceType * the type of service that the new {@link MessageDeserializer} * should deserialize requests for * @return a new {@link MessageDeserializer} for requests to the provided * service type */ <T> MessageDeserializer<T> newServiceRequestDeserializer(String serviceType); /** * @param serviceType * the type of service that the new {@link MessageSerializer} should * serialize responses for * @return a new {@link MessageSerializer} for responses from the provided * service type */ <T> MessageSerializer<T> newServiceResponseSerializer(String serviceType); /** * @param serviceType * the type of service that the new {@link MessageDeserializer} * should deserialize responses for * @return a new {@link MessageDeserializer} for responses from the provided * service type */ <T> MessageDeserializer<T> newServiceResponseDeserializer(String serviceType); }
Java
/* * Copyright (C) 2011 Google Inc. * * 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.ros.message; import com.google.common.base.Preconditions; /** * An {@link MessageIdentifier} and definition pair from which all qualities of * the message uniquely identifiable by the {@link MessageIdentifier} can be * derived. * * @author damonkohler@google.com (Damon Kohler) */ public class MessageDeclaration { private final MessageIdentifier messageIdentifier; private final String definition; public static MessageDeclaration of(String type, String definition) { Preconditions.checkNotNull(type); Preconditions.checkNotNull(definition); return new MessageDeclaration(MessageIdentifier.of(type), definition); } /** * @param messageIdentifier * the {@link MessageIdentifier} * @param definition * the message definition */ public MessageDeclaration(MessageIdentifier messageIdentifier, String definition) { Preconditions.checkNotNull(messageIdentifier); Preconditions.checkNotNull(definition); this.messageIdentifier = messageIdentifier; this.definition = definition; } public MessageIdentifier getMessageIdentifier() { return messageIdentifier; } public String getType() { return messageIdentifier.getType(); } public String getPackage() { return messageIdentifier.getPackage(); } public String getName() { return messageIdentifier.getName(); } public String getDefinition() { Preconditions.checkNotNull(definition); return definition; } @Override public String toString() { return String.format("MessageDeclaration<%s>", messageIdentifier.toString()); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((definition == null) ? 0 : definition.hashCode()); result = prime * result + ((messageIdentifier == null) ? 0 : messageIdentifier.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; MessageDeclaration other = (MessageDeclaration) obj; if (definition == null) { if (other.definition != null) return false; } else if (!definition.equals(other.definition)) return false; if (messageIdentifier == null) { if (other.messageIdentifier != null) return false; } else if (!messageIdentifier.equals(other.messageIdentifier)) return false; return true; } }
Java
/* * Copyright (C) 2012 Google Inc. * * 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. */ /** * Provides the classes that are core to ROS development in Java. * * @see <a href="http://docs.rosjava.googlecode.com/hg/rosjava_core/html/index.html">rosjava_core documentation</a> */ package org.ros;
Java
/* * Copyright (C) 2011 Google Inc. * * 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.ros; /** * ROS environment variables. * * @author kwc@willowgarage.com (Ken Conley) */ public interface EnvironmentVariables { public static String ROS_MASTER_URI = "ROS_MASTER_URI"; public static String ROS_IP = "ROS_IP"; public static String ROS_HOSTNAME = "ROS_HOSTNAME"; public static String ROS_NAMESPACE = "ROS_NAMESPACE"; public static String ROS_ROOT = "ROS_ROOT"; public static String ROS_PACKAGE_PATH = "ROS_PACKAGE_PATH"; }
Java
/* * Copyright (C) 2011 Google Inc. * * 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.ros.namespace; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import org.ros.exception.RosRuntimeException; import java.util.concurrent.atomic.AtomicInteger; import java.util.regex.Pattern; /** * ROS graph resource name. * * @see <a href="http://www.ros.org/wiki/Names">Names documentation</a> * * @author damonkohler@google.com (Damon Kohler) */ public class GraphName { @VisibleForTesting static final String ANONYMOUS_PREFIX = "anonymous_"; private static final String ROOT = "/"; private static final String SEPARATOR = "/"; // TODO(damonkohler): Why make empty names valid? /** * Graph names must match this pattern to be valid. * <p> * Note that empty graph names are considered valid. */ private static final Pattern VALID_GRAPH_NAME_PATTERN = Pattern .compile("^([\\~\\/A-Za-z][\\w_\\/]*)?$"); private static AtomicInteger anonymousCounter = new AtomicInteger(); private final String name; // TODO(damonkohler): This is not safe across multiple hosts/processes. // Instead, try to use the same algorithm as in cpp and Python. /** * Creates an anonymous {@link GraphName}. * * @return a new {@link GraphName} suitable for creating an anonymous node */ public static GraphName newAnonymous() { return new GraphName(ANONYMOUS_PREFIX + anonymousCounter.incrementAndGet()); } /** * @return a {@link GraphName} representing the root namespace */ public static GraphName root() { return new GraphName(ROOT); } /** * @return an empty {@link GraphName} */ public static GraphName empty() { return new GraphName(""); } /** * Returns a new {@link GraphName} of the specified {@link #name}. * * @param name * the name of this resource * @return a new {@link GraphName} for {@link #name} */ public static GraphName of(String name) { return new GraphName(canonicalize(name)); } private GraphName(String name) { Preconditions.checkNotNull(name); this.name = name; } /** * Validate and convert the graph name into its canonical representation. * Canonical representations have no trailing slashes and can be global, * private, or relative. * * @param name * @return the canonical name for this {@link GraphName} */ private static String canonicalize(String name) { if (!VALID_GRAPH_NAME_PATTERN.matcher(name).matches()) { throw new RosRuntimeException("Invalid graph name: " + name); } // Trim trailing slashes for canonical representation. while (!name.equals(GraphName.ROOT) && name.endsWith(SEPARATOR)) { name = name.substring(0, name.length() - 1); } if (name.startsWith("~/")) { name = "~" + name.substring(2); } return name; } /** * Is this a /global/name? * * <ul> * <li> * If node node1 in the global / namespace accesses the resource /bar, that * will resolve to the name /bar.</li> * <li> * If node node2 in the /wg/ namespace accesses the resource /foo, that will * resolve to the name /foo.</li> * <li> * If node node3 in the /wg/ namespace accesses the resource /foo/bar, that * will resolve to the name /foo/bar.</li> * </ul> * * @return {@code true} if this name is a global name, {@code false} otherwise */ public boolean isGlobal() { return !isEmpty() && name.charAt(0) == '/'; } /** * @return {@code true} if this {@link GraphName} represents the root * namespace, {@code false} otherwise */ public boolean isRoot() { return name.equals(GraphName.ROOT); } /** * @return {@code true} if this {@link GraphName} is empty, {@code false} * otherwise */ public boolean isEmpty() { return name.isEmpty(); } /** * Is this a ~private/name? * * <ul> * <li> * If node node1 in the global / namespace accesses the resource ~bar, that * will resolve to the name /node1/bar. * <li> * If node node2 in the /wg/ namespace accesses the resource ~foo, that will * resolve to the name /wg/node2/foo. * <li>If node node3 in the /wg/ namespace accesses the resource ~foo/bar, * that will resolve to the name /wg/node3/foo/bar. * </ul> * * @return {@code true} if the name is a private name, {@code false} otherwise */ public boolean isPrivate() { return !isEmpty() && name.charAt(0) == '~'; } /** * Is this a relative/name? * * <ul> * <li>If node node1 in the global / namespace accesses the resource ~bar, * that will resolve to the name /node1/bar. * <li>If node node2 in the /wg/ namespace accesses the resource ~foo, that * will resolve to the name /wg/node2/foo. * <li>If node node3 in the /wg/ namespace accesses the resource ~foo/bar, * that will resolve to the name /wg/node3/foo/bar. * </ul> * * @return true if the name is a relative name. */ public boolean isRelative() { return !isPrivate() && !isGlobal(); } /** * @return the parent of this {@link GraphName} in its canonical * representation or an empty {@link GraphName} if there is no parent */ public GraphName getParent() { if (name.length() == 0) { return GraphName.empty(); } if (name.equals(GraphName.ROOT)) { return GraphName.root(); } int slashIdx = name.lastIndexOf('/'); if (slashIdx > 1) { return new GraphName(name.substring(0, slashIdx)); } if (isGlobal()) { return GraphName.root(); } return GraphName.empty(); } /** * @return a {@link GraphName} without the leading parent namespace */ public GraphName getBasename() { int slashIdx = name.lastIndexOf('/'); if (slashIdx > -1) { if (slashIdx + 1 < name.length()) { return new GraphName(name.substring(slashIdx + 1)); } return GraphName.empty(); } return this; } /** * Convert name to a relative name representation. This does not take any * namespace into account; it simply strips any preceding characters for * global or private name representation. * * @return a relative {@link GraphName} */ public GraphName toRelative() { if (isPrivate() || isGlobal()) { return new GraphName(name.substring(1)); } return this; } /** * Convert name to a global name representation. This does not take any * namespace into account; it simply adds in the global prefix "/" if missing. * * @return a global {@link GraphName} */ public GraphName toGlobal() { if (isGlobal()) { return this; } if (isPrivate()) { return new GraphName(GraphName.ROOT + name.substring(1)); } return new GraphName(GraphName.ROOT + name); } /** * Join this {@link GraphName} with another. * * @param other * the {@link GraphName} to join with, if other is global, this will * return other * @return a {@link GraphName} representing the concatenation of this * {@link GraphName} and {@code other} */ public GraphName join(GraphName other) { if (other.isGlobal() || isEmpty()) { return other; } if (isRoot()) { return other.toGlobal(); } if (other.isEmpty()) { return this; } return new GraphName(toString() + SEPARATOR + other.toString()); } /** * @see #join(GraphName) */ public GraphName join(String other) { return join(GraphName.of(other)); } @Override public String toString() { return name; } @Override public int hashCode() { return name.hashCode(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; GraphName other = (GraphName) obj; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } }
Java
/* * Copyright (C) 2012 Google Inc. * * 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.ros.internal.message; import org.apache.commons.pool.ObjectPool; import org.apache.commons.pool.PoolableObjectFactory; import org.apache.commons.pool.impl.StackObjectPool; import org.jboss.netty.buffer.ChannelBuffer; import org.ros.exception.RosRuntimeException; /** * A pool of {@link ChannelBuffer}s for serializing and deserializing messages. * <p> * By contract, {@link ChannelBuffer}s provided by {@link #acquire()} must be * returned using {@link #release(ChannelBuffer)}. * * @author damonkohler@google.com (Damon Kohler) */ public class MessageBufferPool { private final ObjectPool<ChannelBuffer> pool; public MessageBufferPool() { pool = new StackObjectPool<ChannelBuffer>(new PoolableObjectFactory<ChannelBuffer>() { @Override public ChannelBuffer makeObject() throws Exception { return MessageBuffers.dynamicBuffer(); } @Override public void destroyObject(ChannelBuffer channelBuffer) throws Exception { } @Override public boolean validateObject(ChannelBuffer channelBuffer) { return true; } @Override public void activateObject(ChannelBuffer channelBuffer) throws Exception { } @Override public void passivateObject(ChannelBuffer channelBuffer) throws Exception { channelBuffer.clear(); } }); } /** * Acquired {@link ChannelBuffer}s must be returned using * {@link #release(ChannelBuffer)}. * * @return an unused {@link ChannelBuffer} */ public ChannelBuffer acquire() { try { return pool.borrowObject(); } catch (Exception e) { throw new RosRuntimeException(e); } } /** * Release a previously acquired {@link ChannelBuffer}. * * @param channelBuffer * the {@link ChannelBuffer} to release */ public void release(ChannelBuffer channelBuffer) { try { pool.returnObject(channelBuffer); } catch (Exception e) { throw new RosRuntimeException(e); } } }
Java
/* * Copyright (C) 2011 Google Inc. * * 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.ros.internal.message.field; import com.google.common.base.Preconditions; import org.jboss.netty.buffer.ChannelBuffer; import java.util.ArrayList; import java.util.List; /** * @author damonkohler@google.com (Damon Kohler) * * @param <T> * the value type */ public class ListField<T> extends Field { private List<T> value; public static <T> ListField<T> newVariable(FieldType type, String name) { return new ListField<T>(type, name); } private ListField(FieldType type, String name) { super(type, name, false); value = new ArrayList<T>(); } @SuppressWarnings("unchecked") @Override public List<T> getValue() { return value; } @SuppressWarnings("unchecked") @Override public void setValue(Object value) { Preconditions.checkNotNull(value); this.value = (List<T>) value; } @Override public void serialize(ChannelBuffer buffer) { buffer.writeInt(value.size()); for (T v : value) { type.serialize(v, buffer); } } @Override public void deserialize(ChannelBuffer buffer) { value.clear(); int size = buffer.readInt(); for (int i = 0; i < size; i++) { value.add(type.<T>deserialize(buffer)); } } @Override public String getMd5String() { return String.format("%s %s\n", type, name); } @Override public String getJavaTypeName() { return String.format("java.util.List<%s>", type.getJavaTypeName()); } @Override public String toString() { return "ListField<" + type + ", " + name + ">"; } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((value == null) ? 0 : value.hashCode()); return result; } @SuppressWarnings("rawtypes") @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; ListField other = (ListField) obj; if (value == null) { if (other.value != null) return false; } else if (!value.equals(other.value)) return false; return true; } }
Java
/* * Copyright (C) 2011 Google Inc. * * 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.ros.internal.message.field; import com.google.common.base.Preconditions; import org.jboss.netty.buffer.ChannelBuffer; import java.util.Arrays; /** * @author damonkohler@google.com (Damon Kohler) */ public class ByteArrayField extends Field { private final int size; private byte[] value; public static ByteArrayField newVariable(FieldType type, String name, int size) { return new ByteArrayField(type, name, size); } private ByteArrayField(FieldType type, String name, int size) { super(type, name, false); this.size = size; setValue(new byte[Math.max(0, size)]); } @SuppressWarnings("unchecked") @Override public byte[] getValue() { return value; } @Override public void setValue(Object value) { Preconditions.checkArgument(size < 0 || ((byte[]) value).length == size); this.value = (byte[]) value; } @Override public void serialize(ChannelBuffer buffer) { if (size < 0) { buffer.writeInt(value.length); } for (byte v : value) { type.serialize(v, buffer); } } @Override public void deserialize(ChannelBuffer buffer) { int currentSize = size; if (currentSize < 0) { currentSize = buffer.readInt(); } value = new byte[currentSize]; for (int i = 0; i < currentSize; i++) { value[i] = buffer.readByte(); } } @Override public String getMd5String() { return String.format("%s %s\n", type, name); } @Override public String getJavaTypeName() { return type.getJavaTypeName() + "[]"; } @Override public String toString() { return "ByteArrayField<" + type + ", " + name + ">"; } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((value == null) ? 0 : value.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; ByteArrayField other = (ByteArrayField) obj; if (value == null) { if (other.value != null) return false; } else if (!Arrays.equals(value, other.value)) return false; return true; } }
Java
/* * Copyright (C) 2011 Google Inc. * * 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.ros.internal.message.field; import com.google.common.base.Preconditions; import org.jboss.netty.buffer.ChannelBuffer; import java.util.Arrays; /** * @author damonkohler@google.com (Damon Kohler) */ public class FloatArrayField extends Field { private final int size; private float[] value; public static FloatArrayField newVariable(String name, int size) { return new FloatArrayField(PrimitiveFieldType.FLOAT32, name, size); } private FloatArrayField(FieldType type, String name, int size) { super(type, name, false); this.size = size; setValue(new float[Math.max(0, size)]); } @SuppressWarnings("unchecked") @Override public float[] getValue() { return value; } @Override public void setValue(Object value) { Preconditions.checkArgument(size < 0 || ((float[]) value).length == size); this.value = (float[]) value; } @Override public void serialize(ChannelBuffer buffer) { if (size < 0) { buffer.writeInt(value.length); } for (float v : value) { type.serialize(v, buffer); } } @Override public void deserialize(ChannelBuffer buffer) { int currentSize = size; if (currentSize < 0) { currentSize = buffer.readInt(); } value = new float[currentSize]; for (int i = 0; i < currentSize; i++) { value[i] = buffer.readFloat(); } } @Override public String getMd5String() { return String.format("%s %s\n", type, name); } @Override public String getJavaTypeName() { return type.getJavaTypeName() + "[]"; } @Override public String toString() { return "FloatArrayField<" + type + ", " + name + ">"; } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((value == null) ? 0 : value.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; FloatArrayField other = (FloatArrayField) obj; if (value == null) { if (other.value != null) return false; } else if (!Arrays.equals(value, other.value)) return false; return true; } }
Java
/* * Copyright (C) 2011 Google Inc. * * 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.ros.internal.message.field; import com.google.common.base.Preconditions; import org.jboss.netty.buffer.ChannelBuffer; import java.util.Arrays; /** * @author damonkohler@google.com (Damon Kohler) */ public class LongArrayField extends Field { private final int size; private long[] value; public static LongArrayField newVariable(FieldType type, String name, int size) { Preconditions.checkArgument(type.equals(PrimitiveFieldType.UINT32) || type.equals(PrimitiveFieldType.INT64) || type.equals(PrimitiveFieldType.UINT64)); return new LongArrayField(type, name, size); } private LongArrayField(FieldType type, String name, int size) { super(type, name, false); this.size = size; setValue(new long[Math.max(0, size)]); } @SuppressWarnings("unchecked") @Override public long[] getValue() { return value; } @Override public void setValue(Object value) { Preconditions.checkArgument(size < 0 || ((long[]) value).length == size); this.value = (long[]) value; } @Override public void serialize(ChannelBuffer buffer) { if (size < 0) { buffer.writeInt(value.length); } for (long v : value) { type.serialize(v, buffer); } } @Override public void deserialize(ChannelBuffer buffer) { int currentSize = size; if (currentSize < 0) { currentSize = buffer.readInt(); } value = new long[currentSize]; for (int i = 0; i < currentSize; i++) { value[i] = buffer.readLong(); } } @Override public String getMd5String() { return String.format("%s %s\n", type, name); } @Override public String getJavaTypeName() { return type.getJavaTypeName() + "[]"; } @Override public String toString() { return "LongArrayField<" + type + ", " + name + ">"; } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((value == null) ? 0 : value.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; LongArrayField other = (LongArrayField) obj; if (value == null) { if (other.value != null) return false; } else if (!Arrays.equals(value, other.value)) return false; return true; } }
Java
/* * Copyright (C) 2011 Google Inc. * * 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.ros.internal.message.field; import com.google.common.base.Preconditions; import org.jboss.netty.buffer.ChannelBuffer; import java.util.Arrays; /** * @author damonkohler@google.com (Damon Kohler) */ public class DoubleArrayField extends Field { private final int size; private double[] value; public static DoubleArrayField newVariable(String name, int size) { return new DoubleArrayField(PrimitiveFieldType.FLOAT64, name, size); } private DoubleArrayField(FieldType type, String name, int size) { super(type, name, false); this.size = size; setValue(new double[Math.max(0, size)]); } @SuppressWarnings("unchecked") @Override public double[] getValue() { return value; } @Override public void setValue(Object value) { Preconditions.checkArgument(size < 0 || ((double[]) value).length == size); this.value = (double[]) value; } @Override public void serialize(ChannelBuffer buffer) { if (size < 0) { buffer.writeInt(value.length); } for (double v : value) { type.serialize(v, buffer); } } @Override public void deserialize(ChannelBuffer buffer) { int currentSize = size; if (currentSize < 0) { currentSize = buffer.readInt(); } value = new double[currentSize]; for (int i = 0; i < currentSize; i++) { value[i] = buffer.readDouble(); } } @Override public String getMd5String() { return String.format("%s %s\n", type, name); } @Override public String getJavaTypeName() { return type.getJavaTypeName() + "[]"; } @Override public String toString() { return "DoubleArrayField<" + type + ", " + name + ">"; } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((value == null) ? 0 : value.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; DoubleArrayField other = (DoubleArrayField) obj; if (value == null) { if (other.value != null) return false; } else if (!Arrays.equals(value, other.value)) return false; return true; } }
Java
/* * Copyright (C) 2011 Google Inc. * * 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.ros.internal.message.field; /** * @author damonkohler@google.com (Damon Kohler) */ public interface FieldFactory { Field create(); }
Java
/* * Copyright (C) 2011 Google Inc. * * 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.ros.internal.message.field; import org.jboss.netty.buffer.ChannelBuffer; import org.ros.internal.message.DefaultMessageDeserializer; import org.ros.internal.message.DefaultMessageSerializer; import org.ros.internal.message.Message; import org.ros.message.MessageDeserializer; import org.ros.message.MessageFactory; import org.ros.message.MessageIdentifier; import org.ros.message.MessageSerializer; /** * @author damonkohler@google.com (Damon Kohler) */ public class MessageFieldType implements FieldType { private final MessageIdentifier messageIdentifier; private final MessageFactory messageFactory; private final MessageSerializer<Message> serializer; private final MessageDeserializer<Message> deserializer; public MessageFieldType(MessageIdentifier messageIdentifier, MessageFactory messageFactory) { this.messageIdentifier = messageIdentifier; this.messageFactory = messageFactory; serializer = new DefaultMessageSerializer(); deserializer = new DefaultMessageDeserializer<Message>(messageIdentifier, messageFactory); } public MessageFactory getMessageFactory() { return messageFactory; } @Override public Field newVariableValue(String name) { return ValueField.newVariable(this, name); } @Override public <T> Field newConstantValue(String name, T value) { throw new UnsupportedOperationException(); } @Override public Field newVariableList(String name, int size) { return ListField.newVariable(this, name); } @Override public <T> T getDefaultValue() { return getMessageFactory().newFromType(messageIdentifier.getType()); } @Override public String getMd5String() { return null; } @Override public String getJavaTypeName() { return String.format("%s.%s", messageIdentifier.getPackage(), messageIdentifier.getName()); } @Override public int getSerializedSize() { throw new UnsupportedOperationException(); } @Override public String getName() { return messageIdentifier.getType(); } @Override public <T> void serialize(T value, ChannelBuffer buffer) { serializer.serialize((Message) value, buffer); } @SuppressWarnings("unchecked") @Override public Message deserialize(ChannelBuffer buffer) { return deserializer.deserialize(buffer); } @SuppressWarnings("unchecked") @Override public Void parseFromString(String value) { throw new UnsupportedOperationException(); } @Override public String toString() { return "MessageField<" + messageIdentifier + ">"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((messageIdentifier == null) ? 0 : messageIdentifier.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; MessageFieldType other = (MessageFieldType) obj; if (messageIdentifier == null) { if (other.messageIdentifier != null) return false; } else if (!messageIdentifier.equals(other.messageIdentifier)) return false; return true; } }
Java
/* * Copyright (C) 2011 Google Inc. * * 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.ros.internal.message.field; import com.google.common.base.Preconditions; import org.jboss.netty.buffer.ChannelBuffer; import java.util.Arrays; /** * @author damonkohler@google.com (Damon Kohler) */ public class ShortArrayField extends Field { private final int size; private short[] value; public static ShortArrayField newVariable(FieldType type, String name, int size) { return new ShortArrayField(type, name, size); } private ShortArrayField(FieldType type, String name, int size) { super(type, name, false); this.size = size; setValue(new short[Math.max(0, size)]); } @SuppressWarnings("unchecked") @Override public short[] getValue() { return value; } @Override public void setValue(Object value) { Preconditions.checkArgument(size < 0 || ((short[]) value).length == size); this.value = (short[]) value; } @Override public void serialize(ChannelBuffer buffer) { if (size < 0) { buffer.writeInt(value.length); } for (short v : value) { type.serialize(v, buffer); } } @Override public void deserialize(ChannelBuffer buffer) { int currentSize = size; if (currentSize < 0) { currentSize = buffer.readInt(); } value = new short[currentSize]; for (int i = 0; i < currentSize; i++) { value[i] = buffer.readShort(); } } @Override public String getMd5String() { return String.format("%s %s\n", type, name); } @Override public String getJavaTypeName() { return type.getJavaTypeName() + "[]"; } @Override public String toString() { return "ShortArrayField<" + type + ", " + name + ">"; } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((value == null) ? 0 : value.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; ShortArrayField other = (ShortArrayField) obj; if (value == null) { if (other.value != null) return false; } else if (!Arrays.equals(value, other.value)) return false; return true; } }
Java
/* * Copyright (C) 2012 Google Inc. * * 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.ros.internal.message.field; import com.google.common.base.Preconditions; import org.jboss.netty.buffer.ChannelBuffer; import org.ros.internal.message.MessageBuffers; import java.nio.ByteOrder; /** * @author damonkohler@google.com (Damon Kohler) */ public class ChannelBufferField extends Field { private final int size; private ChannelBuffer value; public static ChannelBufferField newVariable(FieldType type, String name, int size) { return new ChannelBufferField(type, name, size); } private ChannelBufferField(FieldType type, String name, int size) { super(type, name, false); this.size = size; value = MessageBuffers.dynamicBuffer(); } @SuppressWarnings("unchecked") @Override public ChannelBuffer getValue() { // Return a defensive duplicate. Unlike with copy(), duplicated // ChannelBuffers share the same backing array, so this is relatively cheap. return value.duplicate(); } @Override public void setValue(Object value) { Preconditions.checkArgument(((ChannelBuffer) value).order() == ByteOrder.LITTLE_ENDIAN); Preconditions.checkArgument(size < 0 || ((ChannelBuffer) value).readableBytes() == size); this.value = (ChannelBuffer) value; } @Override public void serialize(ChannelBuffer buffer) { if (size < 0) { buffer.writeInt(value.readableBytes()); } // By specifying the start index and length we avoid modifying value's // indices and marks. buffer.writeBytes(value, 0, value.readableBytes()); } @Override public void deserialize(ChannelBuffer buffer) { int currentSize = size; if (currentSize < 0) { currentSize = buffer.readInt(); } value = buffer.readSlice(currentSize); } @Override public String getMd5String() { return String.format("%s %s\n", type, name); } @Override public String getJavaTypeName() { return "org.jboss.netty.buffer.ChannelBuffer"; } @Override public String toString() { return "ChannelBufferField<" + type + ", " + name + ">"; } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((value == null) ? 0 : value.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; ChannelBufferField other = (ChannelBufferField) obj; if (value == null) { if (other.value != null) return false; } else if (!value.equals(other.value)) return false; return true; } }
Java
/* * Copyright (C) 2011 Google Inc. * * 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.ros.internal.message.field; import org.jboss.netty.buffer.ChannelBuffer; /** * @author damonkohler@google.com (Damon Kohler) */ public abstract class Field { protected final FieldType type; protected final String name; protected final boolean isConstant; protected Field(FieldType type, String name, boolean isConstant) { this.name = name; this.type = type; this.isConstant = isConstant; } /** * @return the name */ public String getName() { return name; } /** * @return the type */ public FieldType getType() { return type; } /** * @return <code>true</code> if this {@link ListField} represents a constant */ public boolean isConstant() { return isConstant; } /** * @return the textual representation of this field used for computing the MD5 * of a message definition */ public String getMd5String() { if (isConstant()) { return String.format("%s %s=%s\n", getType().getMd5String(), getName(), getValue()); } return String.format("%s %s\n", getType().getMd5String(), getName()); } public abstract void serialize(ChannelBuffer buffer); public abstract void deserialize(ChannelBuffer buffer); public abstract <T> T getValue(); // TODO(damonkohler): Why not make Field generic? public abstract void setValue(Object value); public abstract String getJavaTypeName(); @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (isConstant ? 1231 : 1237); result = prime * result + ((name == null) ? 0 : name.hashCode()); result = prime * result + ((type == null) ? 0 : type.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Field other = (Field) obj; if (isConstant != other.isConstant) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; if (type == null) { if (other.type != null) return false; } else if (!type.equals(other.type)) return false; return true; } }
Java
/* * Copyright (C) 2011 Google Inc. * * 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.ros.internal.message.field; import org.jboss.netty.buffer.ChannelBuffer; /** * @author damonkohler@google.com (Damon Kohler) */ public interface FieldType { public <T> T getDefaultValue(); public String getName(); public <T> T parseFromString(String value); public String getMd5String(); public String getJavaTypeName(); /** * @return the serialized size of this {@link FieldType} in bytes */ public int getSerializedSize(); public <T> void serialize(T value, ChannelBuffer buffer); public <T> T deserialize(ChannelBuffer buffer); public Field newVariableValue(String name); public Field newVariableList(String name, int size); public <T> Field newConstantValue(String name, T value); }
Java
/* * Copyright (C) 2011 Google Inc. * * 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.ros.internal.message.field; import com.google.common.base.Preconditions; import org.jboss.netty.buffer.ChannelBuffer; import java.util.Arrays; /** * @author damonkohler@google.com (Damon Kohler) */ public class IntegerArrayField extends Field { private final int size; private int[] value; public static IntegerArrayField newVariable(FieldType type, String name, int size) { return new IntegerArrayField(type, name, size); } private IntegerArrayField(FieldType type, String name, int size) { super(type, name, false); this.size = size; setValue(new int[Math.max(0, size)]); } @SuppressWarnings("unchecked") @Override public int[] getValue() { return value; } @Override public void setValue(Object value) { Preconditions.checkArgument(size < 0 || ((int[]) value).length == size); this.value = (int[]) value; } @Override public void serialize(ChannelBuffer buffer) { if (size < 0) { buffer.writeInt(value.length); } for (int v : value) { type.serialize(v, buffer); } } @Override public void deserialize(ChannelBuffer buffer) { int currentSize = size; if (currentSize < 0) { currentSize = buffer.readInt(); } value = new int[currentSize]; for (int i = 0; i < currentSize; i++) { value[i] = buffer.readInt(); } } @Override public String getMd5String() { return String.format("%s %s\n", type, name); } @Override public String getJavaTypeName() { return type.getJavaTypeName() + "[]"; } @Override public String toString() { return "IntegerArrayField<" + type + ", " + name + ">"; } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((value == null) ? 0 : value.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; IntegerArrayField other = (IntegerArrayField) obj; if (value == null) { if (other.value != null) return false; } else if (!Arrays.equals(value, other.value)) return false; return true; } }
Java
/* * Copyright (C) 2011 Google Inc. * * 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.ros.internal.message.field; import com.google.common.base.Preconditions; import org.jboss.netty.buffer.ChannelBuffer; /** * @author damonkohler@google.com (Damon Kohler) */ class ValueField<T> extends Field { private T value; static <T> ValueField<T> newConstant(FieldType type, String name, T value) { return new ValueField<T>(type, name, value, true); } static <T> ValueField<T> newVariable(FieldType type, String name) { return new ValueField<T>(type, name, null, false); } private ValueField(FieldType type, String name, T value, boolean isConstant) { super(type, name, isConstant); this.value = value; } @SuppressWarnings("unchecked") @Override public T getValue() { if (value == null) { setValue(type.getDefaultValue()); } return value; } @SuppressWarnings("unchecked") @Override public void setValue(Object value) { Preconditions.checkNotNull(value); Preconditions.checkState(!isConstant); this.value = (T) value; } @Override public void serialize(ChannelBuffer buffer) { type.serialize(getValue(), buffer); } @Override public void deserialize(ChannelBuffer buffer) { Preconditions.checkState(!isConstant); setValue(type.<T>deserialize(buffer)); } @Override public String getMd5String() { return String.format("%s %s\n", type, name); } @Override public String getJavaTypeName() { return type.getJavaTypeName(); } @Override public String toString() { return "ValueField<" + type + ", " + name + ">"; } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((getValue() == null) ? 0 : getValue().hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; Field other = (Field) obj; if (getValue() == null) { if (other.getValue() != null) return false; } else if (!getValue().equals(other.getValue())) return false; return true; } }
Java
/* * Copyright (C) 2011 Google Inc. * * 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.ros.internal.message.field; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableSet; import org.jboss.netty.buffer.ChannelBuffer; import org.ros.message.Duration; import org.ros.message.Time; import java.nio.ByteBuffer; import java.nio.charset.Charset; /** * @author damonkohler@google.com (Damon Kohler) */ public enum PrimitiveFieldType implements FieldType { BOOL { @SuppressWarnings("unchecked") @Override public Boolean getDefaultValue() { return Boolean.FALSE; } @Override public BooleanArrayField newVariableList(String name, int size) { return BooleanArrayField.newVariable(name, size); } @Override public int getSerializedSize() { return 1; } @Override public <T> void serialize(T value, ChannelBuffer buffer) { Preconditions.checkArgument(value instanceof Boolean); buffer.writeByte((byte) ((Boolean) value ? 1 : 0)); } @SuppressWarnings("unchecked") @Override public Boolean deserialize(ChannelBuffer buffer) { return buffer.readByte() == 1; } @SuppressWarnings("unchecked") @Override public Boolean parseFromString(String value) { return value.equals("1"); } @Override public String getJavaTypeName() { return "boolean"; } }, INT8 { @SuppressWarnings("unchecked") @Override public Byte getDefaultValue() { return Byte.valueOf((byte) 0); } @Override public Field newVariableList(String name, int size) { return ChannelBufferField.newVariable(this, name, size); } @Override public int getSerializedSize() { return 1; } @Override public <T> void serialize(T value, ChannelBuffer buffer) { Preconditions.checkArgument(value instanceof Byte); buffer.writeByte((Byte) value); } @SuppressWarnings("unchecked") @Override public Byte deserialize(ChannelBuffer buffer) { return buffer.readByte(); } @SuppressWarnings("unchecked") @Override public Byte parseFromString(String value) { return Byte.parseByte(value); } @Override public String getJavaTypeName() { return "byte"; } }, /** * @deprecated replaced by {@link PrimitiveFieldType#INT8} */ BYTE { @SuppressWarnings("unchecked") @Override public Byte getDefaultValue() { return INT8.getDefaultValue(); } @Override public Field newVariableList(String name, int size) { return ChannelBufferField.newVariable(this, name, size); } @Override public int getSerializedSize() { return INT8.getSerializedSize(); } @Override public <T> void serialize(T value, ChannelBuffer buffer) { INT8.serialize(value, buffer); } @SuppressWarnings("unchecked") @Override public Byte deserialize(ChannelBuffer buffer) { return INT8.deserialize(buffer); } @SuppressWarnings("unchecked") @Override public Byte parseFromString(String value) { return INT8.parseFromString(value); } @Override public String getJavaTypeName() { return INT8.getJavaTypeName(); } }, UINT8 { @SuppressWarnings("unchecked") @Override public Byte getDefaultValue() { return INT8.getDefaultValue(); } @Override public Field newVariableList(String name, int size) { return ChannelBufferField.newVariable(this, name, size); } @Override public int getSerializedSize() { return INT8.getSerializedSize(); } @Override public <T> void serialize(T value, ChannelBuffer buffer) { INT8.serialize(value, buffer); } @SuppressWarnings("unchecked") @Override public Byte deserialize(ChannelBuffer buffer) { return INT8.deserialize(buffer); } @SuppressWarnings("unchecked") @Override public Byte parseFromString(String value) { return (byte) Short.parseShort(value); } @Override public String getJavaTypeName() { return INT8.getJavaTypeName(); } }, /** * @deprecated replaced by {@link PrimitiveFieldType#UINT8} */ CHAR { @SuppressWarnings("unchecked") @Override public Byte getDefaultValue() { return UINT8.getDefaultValue(); } @Override public Field newVariableList(String name, int size) { return ChannelBufferField.newVariable(this, name, size); } @Override public int getSerializedSize() { return UINT8.getSerializedSize(); } @Override public <T> void serialize(T value, ChannelBuffer buffer) { UINT8.serialize(value, buffer); } @SuppressWarnings("unchecked") @Override public Byte deserialize(ChannelBuffer buffer) { return UINT8.deserialize(buffer); } @SuppressWarnings("unchecked") @Override public Byte parseFromString(String value) { return UINT8.parseFromString(value); } @Override public String getJavaTypeName() { return UINT8.getJavaTypeName(); } }, INT16 { @SuppressWarnings("unchecked") @Override public Short getDefaultValue() { return Short.valueOf((short) 0); } @Override public Field newVariableList(String name, int size) { return ShortArrayField.newVariable(this, name, size); } @Override public int getSerializedSize() { return 2; } @Override public <T> void serialize(T value, ChannelBuffer buffer) { Preconditions.checkArgument(value instanceof Short); buffer.writeShort((Short) value); } @SuppressWarnings("unchecked") @Override public Short deserialize(ChannelBuffer buffer) { return buffer.readShort(); } @SuppressWarnings("unchecked") @Override public Short parseFromString(String value) { return Short.parseShort(value); } @Override public String getJavaTypeName() { return "short"; } }, UINT16 { @SuppressWarnings("unchecked") @Override public Short getDefaultValue() { return INT16.getDefaultValue(); } @Override public Field newVariableList(String name, int size) { return ShortArrayField.newVariable(this, name, size); } @Override public int getSerializedSize() { return INT16.getSerializedSize(); } @Override public <T> void serialize(T value, ChannelBuffer buffer) { INT16.serialize(value, buffer); } @SuppressWarnings("unchecked") @Override public Short deserialize(ChannelBuffer buffer) { return INT16.deserialize(buffer); } @SuppressWarnings("unchecked") @Override public Short parseFromString(String value) { return (short) Integer.parseInt(value); } @Override public String getJavaTypeName() { return INT16.getJavaTypeName(); } }, INT32 { @SuppressWarnings("unchecked") @Override public Integer getDefaultValue() { return Integer.valueOf(0); } @Override public Field newVariableList(String name, int size) { return IntegerArrayField.newVariable(this, name, size); } @Override public int getSerializedSize() { return 4; } @Override public <T> void serialize(T value, ChannelBuffer buffer) { Preconditions.checkArgument(value instanceof Integer); buffer.writeInt((Integer) value); } @SuppressWarnings("unchecked") @Override public Integer deserialize(ChannelBuffer buffer) { return buffer.readInt(); } @SuppressWarnings("unchecked") @Override public Integer parseFromString(String value) { return Integer.parseInt(value); } @Override public String getJavaTypeName() { return "int"; } }, UINT32 { @SuppressWarnings("unchecked") @Override public Integer getDefaultValue() { return INT32.getDefaultValue(); } @Override public Field newVariableList(String name, int size) { return IntegerArrayField.newVariable(this, name, size); } @Override public int getSerializedSize() { return INT32.getSerializedSize(); } @Override public <T> void serialize(T value, ChannelBuffer buffer) { INT32.serialize(value, buffer); } @SuppressWarnings("unchecked") @Override public Integer deserialize(ChannelBuffer buffer) { return INT32.deserialize(buffer); } @SuppressWarnings("unchecked") @Override public Integer parseFromString(String value) { return (int) Long.parseLong(value); } @Override public String getJavaTypeName() { return INT32.getJavaTypeName(); } }, INT64 { @SuppressWarnings("unchecked") @Override public Long getDefaultValue() { return Long.valueOf(0); } @Override public Field newVariableList(String name, int size) { return LongArrayField.newVariable(this, name, size); } @Override public int getSerializedSize() { return 8; } @Override public <T> void serialize(T value, ChannelBuffer buffer) { Preconditions.checkArgument(value instanceof Long); buffer.writeLong((Long) value); } @SuppressWarnings("unchecked") @Override public Long deserialize(ChannelBuffer buffer) { return buffer.readLong(); } @SuppressWarnings("unchecked") @Override public Long parseFromString(String value) { return Long.parseLong(value); } @Override public String getJavaTypeName() { return "long"; } }, UINT64 { @SuppressWarnings("unchecked") @Override public Long getDefaultValue() { return INT64.getDefaultValue(); } @Override public Field newVariableList(String name, int size) { return INT64.newVariableList(name, size); } @Override public int getSerializedSize() { return INT64.getSerializedSize(); } @Override public <T> void serialize(T value, ChannelBuffer buffer) { INT64.serialize(value, buffer); } @SuppressWarnings("unchecked") @Override public Long deserialize(ChannelBuffer buffer) { return INT64.deserialize(buffer); } @SuppressWarnings("unchecked") @Override public Long parseFromString(String value) { return INT64.parseFromString(value); } @Override public String getJavaTypeName() { return INT64.getJavaTypeName(); } }, FLOAT32 { @SuppressWarnings("unchecked") @Override public Float getDefaultValue() { return Float.valueOf(0); } @Override public Field newVariableList(String name, int size) { return FloatArrayField.newVariable(name, size); } @Override public int getSerializedSize() { return 4; } @Override public <T> void serialize(T value, ChannelBuffer buffer) { Preconditions.checkArgument(value instanceof Float); buffer.writeFloat((Float) value); } @SuppressWarnings("unchecked") @Override public Float deserialize(ChannelBuffer buffer) { return buffer.readFloat(); } @SuppressWarnings("unchecked") @Override public Float parseFromString(String value) { return Float.parseFloat(value); } @Override public String getJavaTypeName() { return "float"; } }, FLOAT64 { @SuppressWarnings("unchecked") @Override public Double getDefaultValue() { return Double.valueOf(0); } @Override public int getSerializedSize() { return 8; } @Override public Field newVariableList(String name, int size) { return DoubleArrayField.newVariable(name, size); } @Override public <T> void serialize(T value, ChannelBuffer buffer) { Preconditions.checkArgument(value instanceof Double); buffer.writeDouble((Double) value); } @SuppressWarnings("unchecked") @Override public Double deserialize(ChannelBuffer buffer) { return buffer.readDouble(); } @SuppressWarnings("unchecked") @Override public Double parseFromString(String value) { return Double.parseDouble(value); } @Override public String getJavaTypeName() { return "double"; } }, STRING { @SuppressWarnings("unchecked") @Override public String getDefaultValue() { return ""; } @Override public Field newVariableList(String name, int size) { return ListField.newVariable(this, name); } @Override public int getSerializedSize() { throw new UnsupportedOperationException(); } @Override public <T> void serialize(T value, ChannelBuffer buffer) { Preconditions.checkArgument(value instanceof String); byte[] bytes = ((String) value).getBytes(); buffer.writeInt(bytes.length); buffer.writeBytes(bytes); } @SuppressWarnings("unchecked") @Override public String deserialize(ChannelBuffer buffer) { int length = buffer.readInt(); ByteBuffer stringBuffer = buffer.readSlice(length).toByteBuffer(); return Charset.forName("US-ASCII").decode(stringBuffer).toString(); } @SuppressWarnings("unchecked") @Override public String parseFromString(String value) { return value; } @Override public String getJavaTypeName() { return "java.lang.String"; } }, TIME { @SuppressWarnings("unchecked") @Override public Time getDefaultValue() { return new Time(); } @Override public Field newVariableList(String name, int size) { return ListField.newVariable(this, name); } @Override public int getSerializedSize() { return 8; } @Override public <T> void serialize(T value, ChannelBuffer buffer) { Preconditions.checkArgument(value instanceof Time); buffer.writeInt(((Time) value).secs); buffer.writeInt(((Time) value).nsecs); } @SuppressWarnings("unchecked") @Override public Time deserialize(ChannelBuffer buffer) { return new Time(buffer.readInt(), buffer.readInt()); } @SuppressWarnings("unchecked") @Override public Void parseFromString(String value) { throw new UnsupportedOperationException(); } @Override public String getJavaTypeName() { return Time.class.getName(); } }, DURATION { @SuppressWarnings("unchecked") @Override public Duration getDefaultValue() { return new Duration(); } @Override public Field newVariableList(String name, int size) { return ListField.newVariable(this, name); } @Override public int getSerializedSize() { return 8; } @Override public <T> void serialize(T value, ChannelBuffer buffer) { Preconditions.checkArgument(value instanceof Duration); buffer.writeInt(((Duration) value).secs); buffer.writeInt(((Duration) value).nsecs); } @SuppressWarnings("unchecked") @Override public Duration deserialize(ChannelBuffer buffer) { return new Duration(buffer.readInt(), buffer.readInt()); } @SuppressWarnings("unchecked") @Override public Void parseFromString(String value) { throw new UnsupportedOperationException(); } @Override public String getJavaTypeName() { return Duration.class.getName(); } }; private static final ImmutableSet<String> TYPE_NAMES; static { ImmutableSet.Builder<String> builder = ImmutableSet.<String>builder(); for (PrimitiveFieldType type : values()) { builder.add(type.getName()); } TYPE_NAMES = builder.build(); } public static boolean existsFor(String name) { return TYPE_NAMES.contains(name); } @Override public Field newVariableValue(String name) { return ValueField.newVariable(this, name); } @Override public <T> Field newConstantValue(String name, T value) { return ValueField.newConstant(this, name, value); } @Override public String getName() { return toString().toLowerCase(); } @Override public String getMd5String() { return getName(); } }
Java
/* * Copyright (C) 2011 Google Inc. * * 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.ros.internal.message.field; import com.google.common.base.Preconditions; import org.jboss.netty.buffer.ChannelBuffer; import java.util.Arrays; /** * @author damonkohler@google.com (Damon Kohler) */ public class BooleanArrayField extends Field { private final int size; private boolean[] value; public static BooleanArrayField newVariable(String name, int size) { return new BooleanArrayField(PrimitiveFieldType.BOOL, name, size); } private BooleanArrayField(FieldType type, String name, int size) { super(type, name, false); this.size = size; setValue(new boolean[Math.max(0, size)]); } @SuppressWarnings("unchecked") @Override public boolean[] getValue() { return value; } @Override public void setValue(Object value) { Preconditions.checkArgument(size < 0 || ((boolean[]) value).length == size); this.value = (boolean[]) value; } @Override public void serialize(ChannelBuffer buffer) { if (size < 0) { buffer.writeInt(value.length); } for (boolean v : value) { type.serialize(v, buffer); } } @Override public void deserialize(ChannelBuffer buffer) { int currentSize = size; if (currentSize < 0) { currentSize = buffer.readInt(); } value = new boolean[currentSize]; for (int i = 0; i < currentSize; i++) { value[i] = buffer.readByte() == 1; } } @Override public String getMd5String() { return String.format("%s %s\n", type, name); } @Override public String getJavaTypeName() { return type.getJavaTypeName() + "[]"; } @Override public String toString() { return "BooleanArrayField<" + type + ", " + name + ">"; } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((value == null) ? 0 : value.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; BooleanArrayField other = (BooleanArrayField) obj; if (value == null) { if (other.value != null) return false; } else if (!Arrays.equals(value, other.value)) return false; return true; } }
Java
/* * Copyright (C) 2012 Google Inc. * * 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.ros.internal.message.field; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import org.ros.exception.RosRuntimeException; import org.ros.internal.message.context.MessageContext; import java.util.Collections; import java.util.List; import java.util.Map; /** * @author damonkohler@google.com (Damon Kohler) */ public class MessageFields { private final Map<String, Field> fields; private final Map<String, Field> setters; private final Map<String, Field> getters; private final List<Field> orderedFields; public MessageFields(MessageContext messageContext) { fields = Maps.newHashMap(); setters = Maps.newHashMap(); getters = Maps.newHashMap(); orderedFields = Lists.newArrayList(); for (String name : messageContext.getFieldNames()) { Field field = messageContext.getFieldFactory(name).create(); fields.put(name, field); getters.put(messageContext.getFieldGetterName(name), field); setters.put(messageContext.getFieldSetterName(name), field); orderedFields.add(field); } } public Field getField(String name) { return fields.get(name); } public Field getSetterField(String name) { return setters.get(name); } public Field getGetterField(String name) { return getters.get(name); } public List<Field> getFields() { return Collections.unmodifiableList(orderedFields); } public Object getFieldValue(String name) { Field field = fields.get(name); if (field != null) { return field.getValue(); } throw new RosRuntimeException("Uknown field: " + name); } public void setFieldValue(String name, Object value) { Field field = fields.get(name); if (field != null) { field.setValue(value); } else { throw new RosRuntimeException("Uknown field: " + name); } } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((fields == null) ? 0 : fields.hashCode()); result = prime * result + ((orderedFields == null) ? 0 : orderedFields.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; MessageFields other = (MessageFields) obj; if (fields == null) { if (other.fields != null) return false; } else if (!fields.equals(other.fields)) return false; if (orderedFields == null) { if (other.orderedFields != null) return false; } else if (!orderedFields.equals(other.orderedFields)) return false; return true; } }
Java
/* * Copyright (C) 2011 Google Inc. * * 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.ros.internal.message; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import org.apache.commons.io.DirectoryWalker; import org.apache.commons.io.FileUtils; import org.apache.commons.io.filefilter.FileFilterUtils; import org.apache.commons.io.filefilter.IOFileFilter; import org.ros.exception.RosRuntimeException; import java.io.File; import java.io.FileFilter; import java.io.IOException; import java.util.Collection; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; /** * @author damonkohler@google.com (Damon Kohler) */ public class StringFileProvider { private final Collection<File> directories; private final Map<File, String> strings; private final StringFileDirectoryWalker stringFileDirectoryWalker; private final class StringFileDirectoryWalker extends DirectoryWalker { private final Set<File> directories; private StringFileDirectoryWalker(FileFilter filter, int depthLimit) { super(filter, depthLimit); directories = Sets.newHashSet(); } // TODO(damonkohler): Update Apache Commons IO to the latest version. @SuppressWarnings("rawtypes") @Override protected boolean handleDirectory(File directory, int depth, Collection results) throws IOException { File canonicalDirectory = directory.getCanonicalFile(); if (directories.contains(canonicalDirectory)) { return false; } directories.add(canonicalDirectory); return true; } @SuppressWarnings("rawtypes") @Override protected void handleFile(File file, int depth, Collection results) { String content; try { content = FileUtils.readFileToString(file, "US-ASCII"); } catch (IOException e) { throw new RosRuntimeException(e); } strings.put(file, content); } public void update(File directory) { try { walk(directory, null); } catch (IOException e) { throw new RosRuntimeException(e); } } } public StringFileProvider(IOFileFilter ioFileFilter) { directories = Lists.newArrayList(); strings = Maps.newConcurrentMap(); IOFileFilter directoryFilter = FileFilterUtils.directoryFileFilter(); FileFilter fileFilter = FileFilterUtils.orFileFilter(directoryFilter, ioFileFilter); stringFileDirectoryWalker = new StringFileDirectoryWalker(fileFilter, -1); } public void update() { for (File directory : directories) { stringFileDirectoryWalker.update(directory); } } /** * Adds a new directory to be scanned for topic definition files. * * @param directory * the directory to add */ public void addDirectory(File directory) { Preconditions.checkArgument(directory.isDirectory()); directories.add(directory); } public Map<File, String> getStrings() { return ImmutableMap.copyOf(strings); } public String get(File file) { if (!has(file)) { throw new NoSuchElementException("File does not exist: " + file); } return strings.get(file); } public boolean has(File file) { return strings.containsKey(file); } }
Java
/* * Copyright (C) 2011 Google Inc. * * 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.ros.internal.message; import com.google.common.base.Preconditions; import org.ros.internal.message.context.MessageContext; import org.ros.internal.message.context.MessageContextProvider; import org.ros.message.MessageDeclaration; import org.ros.message.MessageFactory; import java.lang.reflect.Proxy; import java.util.concurrent.atomic.AtomicInteger; /** * @author damonkohler@google.com (Damon Kohler) */ public class MessageProxyFactory { // We can't use the constant here since the rosjava_messages package depends // on rosjava_bootstrap. private static final String HEADER_MESSAGE_TYPE = "std_msgs/Header"; private static final String SEQUENCE_FIELD_NAME = "seq"; private static final AtomicInteger SEQUENCE_NUMBER = new AtomicInteger(0); private final MessageInterfaceClassProvider messageInterfaceClassProvider; private final MessageContextProvider messageContextProvider; public MessageProxyFactory(MessageInterfaceClassProvider messageInterfaceClassProvider, MessageFactory messageFactory) { this.messageInterfaceClassProvider = messageInterfaceClassProvider; messageContextProvider = new MessageContextProvider(messageFactory); } @SuppressWarnings("unchecked") public <T> T newMessageProxy(MessageDeclaration messageDeclaration) { Preconditions.checkNotNull(messageDeclaration); MessageContext messageContext = messageContextProvider.get(messageDeclaration); MessageImpl messageImpl = new MessageImpl(messageContext); // Header messages are automatically populated with a monotonically // increasing sequence number. if (messageImpl.getType().equals(HEADER_MESSAGE_TYPE)) { messageImpl.setUInt32(SEQUENCE_FIELD_NAME, SEQUENCE_NUMBER.getAndIncrement()); } Class<T> messageInterfaceClass = (Class<T>) messageInterfaceClassProvider.get(messageDeclaration.getType()); return newProxy(messageInterfaceClass, messageImpl); } /** * @param interfaceClass * the interface class to provide * @param messageImpl * the instance to proxy * @return a new proxy for {@code implementation} that implements * {@code interfaceClass} */ @SuppressWarnings("unchecked") private <T> T newProxy(Class<T> interfaceClass, final MessageImpl messageImpl) { ClassLoader classLoader = messageImpl.getClass().getClassLoader(); Class<?>[] interfaces = new Class<?>[] { interfaceClass, GetInstance.class }; MessageProxyInvocationHandler invocationHandler = new MessageProxyInvocationHandler(messageImpl); return (T) Proxy.newProxyInstance(classLoader, interfaces, invocationHandler); } }
Java
/* * Copyright (C) 2011 Google Inc. * * 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.ros.internal.message; import com.google.common.base.Preconditions; import com.google.common.collect.Lists; import org.ros.internal.message.definition.MessageDefinitionParser; import org.ros.internal.message.definition.MessageDefinitionTupleParser; import org.ros.internal.message.definition.MessageDefinitionParser.MessageDefinitionVisitor; import org.apache.commons.codec.digest.DigestUtils; import org.ros.internal.message.field.PrimitiveFieldType; import org.ros.message.MessageDefinitionProvider; import java.util.List; /** * @author damonkohler@google.com (Damon Kohler) */ public class Md5Generator { private final MessageDefinitionProvider messageDefinitionProvider; public Md5Generator(MessageDefinitionProvider messageDefinitionProvider) { this.messageDefinitionProvider = messageDefinitionProvider; } public String generate(String messageType) { String messageDefinition = messageDefinitionProvider.get(messageType); Preconditions.checkNotNull(messageDefinition, "No definition for message type: " + messageType); List<String> parts = MessageDefinitionTupleParser.parse(messageDefinition, -1); StringBuilder text = new StringBuilder(); for (String part : parts) { text.append(generateText(messageType, part)); } return DigestUtils.md5Hex(text.toString()); } private String generateText(String messageType, String messageDefinition) { final List<String> constants = Lists.newArrayList(); final List<String> variables = Lists.newArrayList(); MessageDefinitionVisitor visitor = new MessageDefinitionVisitor() { @Override public void variableValue(String type, String name) { if (!PrimitiveFieldType.existsFor(type)) { type = generate(type); } variables.add(String.format("%s %s\n", type, name)); } @Override public void variableList(String type, int size, String name) { if (!PrimitiveFieldType.existsFor(type)) { String md5Checksum = generate(type); variables.add(String.format("%s %s\n", md5Checksum, name)); } else { if (size != -1) { variables.add(String.format("%s[%d] %s\n", type, size, name)); } else { variables.add(String.format("%s[] %s\n", type, name)); } } } @Override public void constantValue(String type, String name, String value) { constants.add(String.format("%s %s=%s\n", type, name, value)); } }; MessageDefinitionParser messageDefinitionParser = new MessageDefinitionParser(visitor); messageDefinitionParser.parse(messageType, messageDefinition); String text = ""; for (String constant : constants) { text += constant; } for (String variable : variables) { text += variable; } return text.trim(); } }
Java
/* * Copyright (C) 2012 Google Inc. * * 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.ros.internal.message; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBuffers; import java.nio.ByteOrder; /** * Provides {@link ChannelBuffer}s for serializing and deserializing messages. * * @author damonkohler@google.com (Damon Kohler) */ public class MessageBuffers { static final int ESTIMATED_LENGTH = 256; private MessageBuffers() { // Utility class. } /** * @return a new {@link ChannelBuffer} for {@link Message} serialization that * grows dynamically */ public static ChannelBuffer dynamicBuffer() { return ChannelBuffers.dynamicBuffer(ByteOrder.LITTLE_ENDIAN, ESTIMATED_LENGTH); } }
Java
/* * Copyright (C) 2011 Google Inc. * * 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.ros.internal.message; import com.google.common.base.Preconditions; import com.google.common.collect.Sets; import org.apache.commons.lang.StringEscapeUtils; import org.ros.exception.RosRuntimeException; import org.ros.internal.message.context.MessageContext; import org.ros.internal.message.context.MessageContextProvider; import org.ros.internal.message.field.Field; import org.ros.internal.message.field.FieldType; import org.ros.internal.message.field.MessageFields; import org.ros.internal.message.field.PrimitiveFieldType; import org.ros.message.MessageDeclaration; import org.ros.message.MessageFactory; import java.util.Set; /** * @author damonkohler@google.com (Damon Kohler) */ public class MessageInterfaceBuilder { private MessageDeclaration messageDeclaration; private String packageName; private String interfaceName; private boolean addConstantsAndMethods; private String nestedContent; // TODO(damonkohler): Upgrade Apache Commons Lang. See // https://issues.apache.org/jira/browse/LANG-437 private static String escapeJava(String str) { return StringEscapeUtils.escapeJava(str).replace("\\/", "/").replace("'", "\\'"); } public MessageDeclaration getMessageDeclaration() { return messageDeclaration; } public MessageInterfaceBuilder setMessageDeclaration(MessageDeclaration messageDeclaration) { Preconditions.checkNotNull(messageDeclaration); this.messageDeclaration = messageDeclaration; return this; } public String getPackageName() { return packageName; } /** * @param packageName * the package name of the interface or {@code null} if no package * name should be specified * @return this {@link MessageInterfaceBuilder} */ public MessageInterfaceBuilder setPackageName(String packageName) { this.packageName = packageName; return this; } public String getInterfaceName() { return interfaceName; } public MessageInterfaceBuilder setInterfaceName(String interfaceName) { Preconditions.checkNotNull(interfaceName); this.interfaceName = interfaceName; return this; } public boolean getAddConstantsAndMethods() { return addConstantsAndMethods; } public void setAddConstantsAndMethods(boolean enabled) { addConstantsAndMethods = enabled; } public String getNestedContent() { return nestedContent; } public void setNestedContent(String nestedContent) { this.nestedContent = nestedContent; } public String build(MessageFactory messageFactory) { Preconditions.checkNotNull(messageDeclaration); Preconditions.checkNotNull(interfaceName); StringBuilder builder = new StringBuilder(); if (packageName != null) { builder.append(String.format("package %s;\n\n", packageName)); } builder.append(String.format( "public interface %s extends org.ros.internal.message.Message {\n", interfaceName)); builder.append(String.format(" static final java.lang.String _TYPE = \"%s\";\n", messageDeclaration.getType())); builder.append(String.format(" static final java.lang.String _DEFINITION = \"%s\";\n", escapeJava(messageDeclaration.getDefinition()))); if (addConstantsAndMethods) { MessageContextProvider messageContextProvider = new MessageContextProvider(messageFactory); MessageContext messageContext = messageContextProvider.get(messageDeclaration); appendConstants(messageContext, builder); appendSettersAndGetters(messageContext, builder); } if (nestedContent != null) { builder.append("\n"); builder.append(nestedContent); } builder.append("}\n"); return builder.toString(); } @SuppressWarnings("deprecation") private String getJavaValue(PrimitiveFieldType primitiveFieldType, String value) { switch (primitiveFieldType) { case BOOL: return Boolean.valueOf(!value.equals("0") && !value.equals("false")).toString(); case FLOAT32: return value + "f"; case STRING: return "\"" + escapeJava(value) + "\""; case BYTE: case CHAR: case INT8: case UINT8: case INT16: case UINT16: case INT32: case UINT32: case INT64: case UINT64: case FLOAT64: return value; default: throw new RosRuntimeException("Unsupported PrimitiveFieldType: " + primitiveFieldType); } } private void appendConstants(MessageContext messageContext, StringBuilder builder) { MessageFields messageFields = new MessageFields(messageContext); for (Field field : messageFields.getFields()) { if (field.isConstant()) { Preconditions.checkState(field.getType() instanceof PrimitiveFieldType); // We use FieldType and cast back to PrimitiveFieldType below to avoid a // bug in the Sun JDK: http://gs.sun.com/view_bug.do?bug_id=6522780 FieldType fieldType = (FieldType) field.getType(); String value = getJavaValue((PrimitiveFieldType) fieldType, field.getValue().toString()); builder.append(String.format(" static final %s %s = %s;\n", fieldType.getJavaTypeName(), field.getName(), value)); } } } private void appendSettersAndGetters(MessageContext messageContext, StringBuilder builder) { MessageFields messageFields = new MessageFields(messageContext); Set<String> getters = Sets.newHashSet(); for (Field field : messageFields.getFields()) { if (field.isConstant()) { continue; } String type = field.getJavaTypeName(); String getter = messageContext.getFieldGetterName(field.getName()); String setter = messageContext.getFieldSetterName(field.getName()); if (getters.contains(getter)) { // In the case that two or more message fields have the same name except // for capitalization, we only generate a getter and setter pair for the // first one. The following fields will only be accessible via the // RawMessage interface. continue; } getters.add(getter); builder.append(String.format(" %s %s();\n", type, getter)); builder.append(String.format(" void %s(%s value);\n", setter, type)); } } }
Java
/* * Copyright (C) 2011 Google Inc. * * 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.ros.internal.message; import org.ros.internal.message.service.ServiceRequestMessageFactory; import org.ros.internal.message.service.ServiceResponseMessageFactory; import org.ros.message.MessageDefinitionProvider; import org.ros.message.MessageDeserializer; import org.ros.message.MessageFactory; import org.ros.message.MessageIdentifier; import org.ros.message.MessageSerializationFactory; import org.ros.message.MessageSerializer; /** * @author damonkohler@google.com (Damon Kohler) */ public class DefaultMessageSerializationFactory implements MessageSerializationFactory { private final MessageFactory topicMessageFactory; private final ServiceRequestMessageFactory serviceRequestMessageFactory; private final ServiceResponseMessageFactory serviceResponseMessageFactory; public DefaultMessageSerializationFactory(MessageDefinitionProvider messageDefinitionProvider) { topicMessageFactory = new DefaultMessageFactory(messageDefinitionProvider); serviceRequestMessageFactory = new ServiceRequestMessageFactory(messageDefinitionProvider); serviceResponseMessageFactory = new ServiceResponseMessageFactory(messageDefinitionProvider); } @SuppressWarnings("unchecked") @Override public <T> MessageSerializer<T> newMessageSerializer(String messageType) { return (MessageSerializer<T>) new DefaultMessageSerializer(); } @Override public <T> MessageDeserializer<T> newMessageDeserializer(String messageType) { return new DefaultMessageDeserializer<T>(MessageIdentifier.of(messageType), topicMessageFactory); } @SuppressWarnings("unchecked") @Override public <T> MessageSerializer<T> newServiceRequestSerializer(String serviceType) { return (MessageSerializer<T>) new DefaultMessageSerializer(); } @Override public <T> org.ros.message.MessageDeserializer<T> newServiceRequestDeserializer(String serviceType) { return new DefaultMessageDeserializer<T>(MessageIdentifier.of(serviceType), serviceRequestMessageFactory); } @SuppressWarnings("unchecked") @Override public <T> org.ros.message.MessageSerializer<T> newServiceResponseSerializer(String serviceType) { return (MessageSerializer<T>) new DefaultMessageSerializer(); } @Override public <T> org.ros.message.MessageDeserializer<T> newServiceResponseDeserializer( String serviceType) { return new DefaultMessageDeserializer<T>(MessageIdentifier.of(serviceType), serviceResponseMessageFactory); } }
Java
/* * Copyright (C) 2011 Google Inc. * * 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.ros.internal.message; /** * @author damonkohler@google.com (Damon Kohler) */ public interface MessageInterfaceClassProvider { /** * @param <T> * the message interface class type * @param messageType * the type of message to provide an interface class for * @return the interface class for the specified message type */ <T> Class<T> get(String messageType); }
Java
/* * Copyright (C) 2011 Google Inc. * * 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.ros.internal.message; import org.jboss.netty.buffer.ChannelBuffer; import org.ros.internal.message.field.Field; import org.ros.message.Duration; import org.ros.message.MessageIdentifier; import org.ros.message.Time; import java.util.List; /** * @author damonkohler@google.com (Damon Kohler) */ public interface RawMessage extends Message { boolean getBool(String name); boolean[] getBoolArray(String name); /** * @deprecated replaced by {@link #getInt8(String)} */ byte getByte(String name); /** * @deprecated replaced by {@link #getInt8Array(String)} */ byte[] getByteArray(String name); /** * @deprecated replaced by {@link #getUInt8(String)} */ short getChar(String name); /** * @deprecated replaced by {@link #getUInt8Array(String)} */ short[] getCharArray(String name); String getDefinition(); Duration getDuration(String name); List<Duration> getDurationList(String name); List<Field> getFields(); float getFloat32(String name); float[] getFloat32Array(String name); double getFloat64(String name); double[] getFloat64Array(String name); MessageIdentifier getIdentifier(); short getInt16(String name); short[] getInt16Array(String name); int getInt32(String name); int[] getInt32Array(String name); long getInt64(String name); long[] getInt64Array(String name); byte getInt8(String name); byte[] getInt8Array(String name); <T extends Message> T getMessage(String name); <T extends Message> List<T> getMessageList(String name); String getName(); String getPackage(); String getString(String name); List<String> getStringList(String name); Time getTime(String name); List<Time> getTimeList(String name); String getType(); short getUInt16(String name); short[] getUInt16Array(String name); int getUInt32(String name); int[] getUInt32Array(String name); long getUInt64(String name); long[] getUInt64Array(String name); short getUInt8(String name); short[] getUInt8Array(String name); void setBool(String name, boolean value); void setBoolArray(String name, boolean[] value); /** * @deprecated replaced by {@link #setInt8(String, byte)} */ void setByte(String name, byte value); /** * @deprecated replaced by {@link #setInt8Array(String, byte[])} */ void setByteArray(String name, byte[] value); /** * @deprecated replaced by {@link #setUInt8(String, byte)} */ void setChar(String name, short value); /** * @deprecated replaced by {@link #setUInt8Array(String, byte[])} */ void setCharArray(String name, short[] value); void setDuration(String name, Duration value); void setDurationList(String name, List<Duration> value); void setFloat32(String name, float value); void setFloat32Array(String name, float[] value); void setFloat64(String name, double value); void setFloat64Array(String name, double[] value); void setInt16(String name, short value); void setInt16Array(String name, short[] value); void setInt32(String name, int value); void setInt32Array(String name, int[] value); void setInt64(String name, long value); void setInt64Array(String name, long[] value); void setInt8(String name, byte value); void setInt8Array(String name, byte[] value); void setMessage(String name, Message value); void setMessageList(String name, List<Message> value); void setString(String name, String value); void setStringList(String name, List<String> value); void setTime(String name, Time value); void setTimeList(String name, List<Time> value); void setUInt16(String name, short value); void setUInt16Array(String name, short[] value); void setUInt32(String name, int value); void setUInt32Array(String name, int[] value); void setUInt64(String name, long value); void setUInt64Array(String name, long[] value); void setUInt8(String name, byte value); void setUInt8Array(String name, byte[] value); void setChannelBuffer(String name, ChannelBuffer value); ChannelBuffer getChannelBuffer(String name); }
Java
/* * Copyright (C) 2012 Google Inc. * * 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.ros.internal.message; import org.ros.internal.message.field.Field; import org.ros.internal.message.field.MessageFields; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; /** * @author damonkohler@google.com (Damon Kohler) */ public class MessageProxyInvocationHandler implements InvocationHandler { private final MessageImpl messageImpl; MessageProxyInvocationHandler(MessageImpl messageImpl) { this.messageImpl = messageImpl; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { String methodName = method.getName(); MessageFields mesageFields = messageImpl.getMessageFields(); Field getterField = mesageFields.getGetterField(methodName); if (getterField != null) { return getterField.getValue(); } Field setterField = mesageFields.getSetterField(methodName); if (setterField != null) { setterField.setValue(args[0]); return null; } return method.invoke(messageImpl, args); } }
Java
/* * Copyright (C) 2012 Google Inc. * * 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. */ /** * Provides internal classes for representing messages. * <p> * These classes should _not_ be used directly outside of the org.ros package. */ package org.ros.internal.message;
Java