code
stringlengths
3
1.18M
language
stringclasses
1 value
package org.anddev.andengine.examples; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.IEntity; import org.anddev.andengine.entity.modifier.IEntityModifier.IEntityModifierListener; import org.anddev.andengine.entity.modifier.ParallelEntityModifier; import org.anddev.andengine.entity.modifier.RotationByModifier; import org.anddev.andengine.entity.modifier.RotationModifier; import org.anddev.andengine.entity.modifier.ScaleModifier; import org.anddev.andengine.entity.modifier.SequenceEntityModifier; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.sprite.AnimatedSprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TiledTextureRegion; import org.anddev.andengine.util.modifier.IModifier; import android.widget.Toast; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 21:42:39 - 06.07.2010 */ public class EntityModifierIrregularExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mBitmapTextureAtlas; private TiledTextureRegion mFaceTextureRegion; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { Toast.makeText(this, "Shapes can have variable rotation and scale centers.", Toast.LENGTH_LONG).show(); this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override public void onLoadResources() { this.mBitmapTextureAtlas = new BitmapTextureAtlas(64, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA); BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "face_box_tiled.png", 0, 0, 2, 1); this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); final int centerX = (CAMERA_WIDTH - this.mFaceTextureRegion.getWidth()) / 2; final int centerY = (CAMERA_HEIGHT - this.mFaceTextureRegion.getHeight()) / 2; final AnimatedSprite face1 = new AnimatedSprite(centerX - 100, centerY, this.mFaceTextureRegion); face1.setRotationCenter(0, 0); face1.setScaleCenter(0, 0); face1.animate(100); final AnimatedSprite face2 = new AnimatedSprite(centerX + 100, centerY, this.mFaceTextureRegion); face2.animate(100); final SequenceEntityModifier entityModifier = new SequenceEntityModifier( new IEntityModifierListener() { @Override public void onModifierStarted(final IModifier<IEntity> pModifier, final IEntity pItem) { EntityModifierIrregularExample.this.runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(EntityModifierIrregularExample.this, "Sequence started.", Toast.LENGTH_LONG).show(); } }); } @Override public void onModifierFinished(final IModifier<IEntity> pEntityModifier, final IEntity pEntity) { EntityModifierIrregularExample.this.runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(EntityModifierIrregularExample.this, "Sequence finished.", Toast.LENGTH_LONG).show(); } }); } }, new ScaleModifier(2, 1.0f, 0.75f, 1.0f, 2.0f), new ScaleModifier(2, 0.75f, 2.0f, 2.0f, 1.25f), new ParallelEntityModifier( new ScaleModifier(3, 2.0f, 5.0f, 1.25f, 5.0f), new RotationByModifier(3, 180) ), new ParallelEntityModifier( new ScaleModifier(3, 5, 1), new RotationModifier(3, 180, 0) ) ); face1.registerEntityModifier(entityModifier); face2.registerEntityModifier(entityModifier.deepCopy()); scene.attachChild(face1); scene.attachChild(face2); /* Create some not-modified sprites, that act as fixed references to the modified ones. */ final AnimatedSprite face1Reference = new AnimatedSprite(centerX - 100, centerY, this.mFaceTextureRegion); final AnimatedSprite face2Reference = new AnimatedSprite(centerX + 100, centerY, this.mFaceTextureRegion); scene.attachChild(face1Reference); scene.attachChild(face2Reference); return scene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import java.io.IOException; import java.io.InputStream; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.SmoothCamera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.Scene.IOnSceneTouchListener; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.sprite.Sprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.examples.adt.ZoomState; import org.anddev.andengine.input.touch.TouchEvent; import org.anddev.andengine.opengl.texture.ITexture; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.compressed.pvr.PVRCCZTexture; import org.anddev.andengine.opengl.texture.compressed.pvr.PVRTexture.PVRTextureFormat; import org.anddev.andengine.opengl.texture.region.TextureRegion; import org.anddev.andengine.opengl.texture.region.TextureRegionFactory; import org.anddev.andengine.util.Debug; import android.widget.Toast; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 15:31:11 - 27.07.2011 */ public class PVRCCZTextureExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; // =========================================================== // Fields // =========================================================== private SmoothCamera mSmoothCamera; private ITexture mTexture; private TextureRegion mHouseTextureRegion; private ZoomState mZoomState = ZoomState.NONE; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { Toast.makeText(this, "Click the top half of the screen to zoom in or the bottom half to zoom out!", Toast.LENGTH_LONG); this.mSmoothCamera = new SmoothCamera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT, 0, 0, 0.1f) { @Override public void onUpdate(final float pSecondsElapsed) { switch (PVRCCZTextureExample.this.mZoomState) { case IN: this.setZoomFactor(this.getZoomFactor() + 0.1f * pSecondsElapsed); break; case OUT: this.setZoomFactor(this.getZoomFactor() - 0.1f * pSecondsElapsed); break; } super.onUpdate(pSecondsElapsed); } }; return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mSmoothCamera)); } @Override public void onLoadResources() { try { this.mTexture = new PVRCCZTexture(PVRTextureFormat.RGBA_8888, TextureOptions.BILINEAR) { @Override protected InputStream onGetInputStream() throws IOException { return PVRCCZTextureExample.this.getResources().openRawResource(R.raw.house_pvrccz_argb_8888); } }; this.mHouseTextureRegion = TextureRegionFactory.extractFromTexture(this.mTexture, 0, 0, 512, 512, true); this.mEngine.getTextureManager().loadTextures(this.mTexture); } catch (final Throwable e) { Debug.e(e); } } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); final int centerX = (CAMERA_WIDTH - this.mHouseTextureRegion.getWidth()) / 2; final int centerY = (CAMERA_HEIGHT - this.mHouseTextureRegion.getHeight()) / 2; scene.attachChild(new Sprite(centerX, centerY, this.mHouseTextureRegion)); scene.setOnSceneTouchListener(new IOnSceneTouchListener() { @Override public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) { if (pSceneTouchEvent.isActionDown() || pSceneTouchEvent.isActionMove()) { if(pSceneTouchEvent.getY() < CAMERA_HEIGHT / 2) { PVRCCZTextureExample.this.mZoomState = ZoomState.IN; } else { PVRCCZTextureExample.this.mZoomState = ZoomState.OUT; } } else { PVRCCZTextureExample.this.mZoomState = ZoomState.NONE; } return true; } }); return scene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import org.anddev.andengine.ui.activity.BaseGameActivity; import android.view.Menu; import android.view.MenuItem; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 22:10:28 - 11.04.2010 */ public abstract class BaseExample extends BaseGameActivity { // =========================================================== // Constants // =========================================================== private static final int MENU_TRACE = Menu.FIRST; // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public boolean onCreateOptionsMenu(final Menu pMenu) { pMenu.add(Menu.NONE, MENU_TRACE, Menu.NONE, "Start Method Tracing"); return super.onCreateOptionsMenu(pMenu); } @Override public boolean onPrepareOptionsMenu(final Menu pMenu) { pMenu.findItem(MENU_TRACE).setTitle(this.mEngine.isMethodTracing() ? "Stop Method Tracing" : "Start Method Tracing"); return super.onPrepareOptionsMenu(pMenu); } @Override public boolean onMenuItemSelected(final int pFeatureId, final MenuItem pItem) { switch(pItem.getItemId()) { case MENU_TRACE: if(this.mEngine.isMethodTracing()) { this.mEngine.stopMethodTracing(); } else { this.mEngine.startMethodTracing("AndEngine_" + System.currentTimeMillis() + ".trace"); } return true; default: return super.onMenuItemSelected(pFeatureId, pItem); } } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.primitive.Rectangle; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.Scene.IOnSceneTouchListener; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.shape.Shape; import org.anddev.andengine.entity.sprite.AnimatedSprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.extension.physics.box2d.PhysicsConnector; import org.anddev.andengine.extension.physics.box2d.PhysicsFactory; import org.anddev.andengine.extension.physics.box2d.PhysicsWorld; import org.anddev.andengine.extension.physics.box2d.util.Vector2Pool; import org.anddev.andengine.input.touch.TouchEvent; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TiledTextureRegion; import org.anddev.andengine.sensor.accelerometer.AccelerometerData; import org.anddev.andengine.sensor.accelerometer.IAccelerometerListener; import org.anddev.andengine.util.Debug; import android.hardware.SensorManager; import android.widget.Toast; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.Body; import com.badlogic.gdx.physics.box2d.BodyDef.BodyType; import com.badlogic.gdx.physics.box2d.FixtureDef; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 14:33:38 - 03.10.2010 */ public class PhysicsCollisionFilteringExample extends BaseExample implements IAccelerometerListener, IOnSceneTouchListener { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; /* The categories. */ public static final short CATEGORYBIT_WALL = 1; public static final short CATEGORYBIT_BOX = 2; public static final short CATEGORYBIT_CIRCLE = 4; /* And what should collide with what. */ public static final short MASKBITS_WALL = CATEGORYBIT_WALL + CATEGORYBIT_BOX + CATEGORYBIT_CIRCLE; public static final short MASKBITS_BOX = CATEGORYBIT_WALL + CATEGORYBIT_BOX; // Missing: CATEGORYBIT_CIRCLE public static final short MASKBITS_CIRCLE = CATEGORYBIT_WALL + CATEGORYBIT_CIRCLE; // Missing: CATEGORYBIT_BOX public static final FixtureDef WALL_FIXTURE_DEF = PhysicsFactory.createFixtureDef(0, 0.5f, 0.5f, false, CATEGORYBIT_WALL, MASKBITS_WALL, (short)0); public static final FixtureDef BOX_FIXTURE_DEF = PhysicsFactory.createFixtureDef(1, 0.5f, 0.5f, false, CATEGORYBIT_BOX, MASKBITS_BOX, (short)0); public static final FixtureDef CIRCLE_FIXTURE_DEF = PhysicsFactory.createFixtureDef(1, 0.5f, 0.5f, false, CATEGORYBIT_CIRCLE, MASKBITS_CIRCLE, (short)0); // =========================================================== // Fields // =========================================================== private BitmapTextureAtlas mBitmapTextureAtlas; private TiledTextureRegion mBoxFaceTextureRegion; private TiledTextureRegion mCircleFaceTextureRegion; private Scene mScene; private PhysicsWorld mPhysicsWorld; private int mFaceCount = 0; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { Toast.makeText(this, "Touch the screen to add objects.", Toast.LENGTH_LONG).show(); Toast.makeText(this, "Boxes will only collide with boxes.\nCircles will only collide with circles.", Toast.LENGTH_LONG).show(); final Camera camera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); final EngineOptions engineOptions = new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), camera); engineOptions.getTouchOptions().setRunOnUpdateThread(true); return new Engine(engineOptions); } @Override public void onLoadResources() { /* Textures. */ this.mBitmapTextureAtlas = new BitmapTextureAtlas(64, 64, TextureOptions.BILINEAR_PREMULTIPLYALPHA); BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); /* TextureRegions. */ this.mBoxFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "face_box_tiled.png", 0, 0, 2, 1); // 64x32 this.mCircleFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "face_circle_tiled.png", 0, 32, 2, 1); // 64x32 this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); this.mScene = new Scene(); this.mScene.setBackground(new ColorBackground(0, 0, 0)); this.mScene.setOnSceneTouchListener(this); this.mPhysicsWorld = new PhysicsWorld(new Vector2(0, SensorManager.GRAVITY_EARTH), false); final Shape ground = new Rectangle(0, CAMERA_HEIGHT - 2, CAMERA_WIDTH, 2); final Shape roof = new Rectangle(0, 0, CAMERA_WIDTH, 2); final Shape left = new Rectangle(0, 0, 2, CAMERA_HEIGHT); final Shape right = new Rectangle(CAMERA_WIDTH - 2, 0, 2, CAMERA_HEIGHT); PhysicsFactory.createBoxBody(this.mPhysicsWorld, ground, BodyType.StaticBody, WALL_FIXTURE_DEF); PhysicsFactory.createBoxBody(this.mPhysicsWorld, roof, BodyType.StaticBody, WALL_FIXTURE_DEF); PhysicsFactory.createBoxBody(this.mPhysicsWorld, left, BodyType.StaticBody, WALL_FIXTURE_DEF); PhysicsFactory.createBoxBody(this.mPhysicsWorld, right, BodyType.StaticBody, WALL_FIXTURE_DEF); this.mScene.attachChild(ground); this.mScene.attachChild(roof); this.mScene.attachChild(left); this.mScene.attachChild(right); this.mScene.registerUpdateHandler(this.mPhysicsWorld); return this.mScene; } @Override public void onLoadComplete() { } @Override public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) { if(this.mPhysicsWorld != null) { if(pSceneTouchEvent.isActionDown()) { this.addFace(pSceneTouchEvent.getX(), pSceneTouchEvent.getY()); return true; } } return false; } @Override public void onAccelerometerChanged(final AccelerometerData pAccelerometerData) { final Vector2 gravity = Vector2Pool.obtain(pAccelerometerData.getX(), pAccelerometerData.getY()); this.mPhysicsWorld.setGravity(gravity); Vector2Pool.recycle(gravity); } @Override public void onResumeGame() { super.onResumeGame(); this.enableAccelerometerSensor(this); } @Override public void onPauseGame() { super.onPauseGame(); this.disableAccelerometerSensor(); } // =========================================================== // Methods // =========================================================== private void addFace(final float pX, final float pY) { this.mFaceCount++; Debug.d("Faces: " + this.mFaceCount); final AnimatedSprite face; final Body body; if(this.mFaceCount % 2 == 0) { face = new AnimatedSprite(pX, pY, this.mBoxFaceTextureRegion); body = PhysicsFactory.createBoxBody(this.mPhysicsWorld, face, BodyType.DynamicBody, BOX_FIXTURE_DEF); } else { face = new AnimatedSprite(pX, pY, this.mCircleFaceTextureRegion); body = PhysicsFactory.createCircleBody(this.mPhysicsWorld, face, BodyType.DynamicBody, CIRCLE_FIXTURE_DEF); } face.animate(200); this.mScene.attachChild(face); this.mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(face, body, true, true)); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import java.io.IOException; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.sprite.AnimatedSprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.level.LevelLoader; import org.anddev.andengine.level.LevelLoader.IEntityLoader; import org.anddev.andengine.level.util.constants.LevelConstants; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TiledTextureRegion; import org.anddev.andengine.util.Debug; import org.anddev.andengine.util.SAXUtils; import org.xml.sax.Attributes; import android.widget.Toast; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 17:16:10 - 11.10.2010 */ public class LevelLoaderExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 480; private static final int CAMERA_HEIGHT = 320; private static final String TAG_ENTITY = "entity"; private static final String TAG_ENTITY_ATTRIBUTE_X = "x"; private static final String TAG_ENTITY_ATTRIBUTE_Y = "y"; private static final String TAG_ENTITY_ATTRIBUTE_WIDTH = "width"; private static final String TAG_ENTITY_ATTRIBUTE_HEIGHT = "height"; private static final String TAG_ENTITY_ATTRIBUTE_TYPE = "type"; private static final Object TAG_ENTITY_ATTRIBUTE_TYPE_VALUE_BOX = "box"; private static final Object TAG_ENTITY_ATTRIBUTE_TYPE_VALUE_CIRCLE = "circle"; private static final Object TAG_ENTITY_ATTRIBUTE_TYPE_VALUE_TRIANGLE = "triangle"; private static final Object TAG_ENTITY_ATTRIBUTE_TYPE_VALUE_HEXAGON = "hexagon"; // =========================================================== // Fields // =========================================================== private BitmapTextureAtlas mBitmapTextureAtlas; private TiledTextureRegion mBoxFaceTextureRegion; private TiledTextureRegion mCircleFaceTextureRegion; private TiledTextureRegion mTriangleFaceTextureRegion; private TiledTextureRegion mHexagonFaceTextureRegion; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { Toast.makeText(this, "Loading level...", Toast.LENGTH_SHORT).show(); final Camera camera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), camera)); } @Override public void onLoadResources() { /* Textures. */ this.mBitmapTextureAtlas = new BitmapTextureAtlas(64, 128, TextureOptions.BILINEAR_PREMULTIPLYALPHA); BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); /* TextureRegions. */ this.mBoxFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "face_box_tiled.png", 0, 0, 2, 1); // 64x32 this.mCircleFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "face_circle_tiled.png", 0, 32, 2, 1); // 64x32 this.mTriangleFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "face_triangle_tiled.png", 0, 64, 2, 1); // 64x32 this.mHexagonFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "face_hexagon_tiled.png", 0, 96, 2, 1); // 64x32 this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); scene.setBackground(new ColorBackground(0, 0, 0)); final LevelLoader levelLoader = new LevelLoader(); levelLoader.setAssetBasePath("level/"); levelLoader.registerEntityLoader(LevelConstants.TAG_LEVEL, new IEntityLoader() { @Override public void onLoadEntity(final String pEntityName, final Attributes pAttributes) { final int width = SAXUtils.getIntAttributeOrThrow(pAttributes, LevelConstants.TAG_LEVEL_ATTRIBUTE_WIDTH); final int height = SAXUtils.getIntAttributeOrThrow(pAttributes, LevelConstants.TAG_LEVEL_ATTRIBUTE_HEIGHT); Toast.makeText(LevelLoaderExample.this, "Loaded level with width=" + width + " and height=" + height + ".", Toast.LENGTH_LONG).show(); } }); levelLoader.registerEntityLoader(TAG_ENTITY, new IEntityLoader() { @Override public void onLoadEntity(final String pEntityName, final Attributes pAttributes) { final int x = SAXUtils.getIntAttributeOrThrow(pAttributes, TAG_ENTITY_ATTRIBUTE_X); final int y = SAXUtils.getIntAttributeOrThrow(pAttributes, TAG_ENTITY_ATTRIBUTE_Y); final int width = SAXUtils.getIntAttributeOrThrow(pAttributes, TAG_ENTITY_ATTRIBUTE_WIDTH); final int height = SAXUtils.getIntAttributeOrThrow(pAttributes, TAG_ENTITY_ATTRIBUTE_HEIGHT); final String type = SAXUtils.getAttributeOrThrow(pAttributes, TAG_ENTITY_ATTRIBUTE_TYPE); LevelLoaderExample.this.addFace(scene, x, y, width, height, type); } }); try { levelLoader.loadLevelFromAsset(this, "example.lvl"); } catch (final IOException e) { Debug.e(e); } return scene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== private void addFace(final Scene pScene, final float pX, final float pY, final int pWidth, final int pHeight, final String pType) { final AnimatedSprite face; if(pType.equals(TAG_ENTITY_ATTRIBUTE_TYPE_VALUE_BOX)) { face = new AnimatedSprite(pX, pY, pWidth, pHeight, this.mBoxFaceTextureRegion); } else if(pType.equals(TAG_ENTITY_ATTRIBUTE_TYPE_VALUE_CIRCLE)) { face = new AnimatedSprite(pX, pY, pWidth, pHeight, this.mCircleFaceTextureRegion); } else if(pType.equals(TAG_ENTITY_ATTRIBUTE_TYPE_VALUE_TRIANGLE)) { face = new AnimatedSprite(pX, pY, pWidth, pHeight, this.mTriangleFaceTextureRegion); } else if(pType.equals(TAG_ENTITY_ATTRIBUTE_TYPE_VALUE_HEXAGON)) { face = new AnimatedSprite(pX, pY, pWidth, pHeight, this.mHexagonFaceTextureRegion); } else { throw new IllegalArgumentException(); } face.animate(200); pScene.attachChild(face); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples.benchmark; import javax.microedition.khronos.opengles.GL10; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.particle.ParticleSystem; import org.anddev.andengine.entity.particle.emitter.PointParticleEmitter; import org.anddev.andengine.entity.particle.initializer.AccelerationInitializer; import org.anddev.andengine.entity.particle.initializer.ColorInitializer; import org.anddev.andengine.entity.particle.initializer.RotationInitializer; import org.anddev.andengine.entity.particle.initializer.VelocityInitializer; import org.anddev.andengine.entity.particle.modifier.AlphaModifier; import org.anddev.andengine.entity.particle.modifier.ColorModifier; import org.anddev.andengine.entity.particle.modifier.ExpireModifier; import org.anddev.andengine.entity.particle.modifier.ScaleModifier; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TextureRegion; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 09:27:21 - 29.06.2010 */ public class ParticleSystemBenchmark extends BaseBenchmark { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 480; private static final int CAMERA_HEIGHT = 320; private static final float RATE_MIN = 15; private static final float RATE_MAX = 20; private static final int PARTICLES_MAX = 200; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mBitmapTextureAtlas; private TextureRegion mParticleTextureRegion; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override protected int getBenchmarkID() { return PARTICLESYSTEMBENCHMARK_ID; } @Override protected float getBenchmarkStartOffset() { return 5; } @Override protected float getBenchmarkDuration() { return 15; } @Override public Engine onLoadEngine() { this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override public void onLoadResources() { this.mBitmapTextureAtlas = new BitmapTextureAtlas(32, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA); BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mParticleTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "particle_fire.png", 0, 0); this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { final Scene scene = new Scene(); scene.setBackground(new ColorBackground(0.0f, 0.0f, 0.0f)); /* LowerLeft to LowerRight Particle System. */ { final ParticleSystem particleSystem = new ParticleSystem(new PointParticleEmitter(-32, CAMERA_HEIGHT - 32), RATE_MIN, RATE_MAX, PARTICLES_MAX, this.mParticleTextureRegion); particleSystem.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE); particleSystem.addParticleInitializer(new VelocityInitializer(35, 45, 0, -10)); particleSystem.addParticleInitializer(new AccelerationInitializer(5, -11)); particleSystem.addParticleInitializer(new RotationInitializer(0.0f, 360.0f)); particleSystem.addParticleInitializer(new ColorInitializer(1.0f, 1.0f, 0.0f)); particleSystem.addParticleModifier(new ScaleModifier(0.5f, 2.0f, 0, 5)); particleSystem.addParticleModifier(new ExpireModifier(6.5f)); particleSystem.addParticleModifier(new ColorModifier(1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 2.5f, 5.5f)); particleSystem.addParticleModifier(new AlphaModifier(1.0f, 0.0f, 2.5f, 6.5f)); scene.attachChild(particleSystem); } /* LowerRight to LowerLeft Particle System. */ { final ParticleSystem particleSystem = new ParticleSystem(new PointParticleEmitter(CAMERA_WIDTH, CAMERA_HEIGHT - 32), RATE_MIN, RATE_MAX, PARTICLES_MAX, this.mParticleTextureRegion); particleSystem.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE); particleSystem.addParticleInitializer(new VelocityInitializer(-35, -45, 0, -10)); particleSystem.addParticleInitializer(new AccelerationInitializer(-5, -11)); particleSystem.addParticleInitializer(new RotationInitializer(0.0f, 360.0f)); particleSystem.addParticleInitializer(new ColorInitializer(0.0f, 1.0f, 0.0f)); particleSystem.addParticleModifier(new ScaleModifier(0.5f, 2.0f, 0, 5)); particleSystem.addParticleModifier(new ExpireModifier(6.5f)); particleSystem.addParticleModifier(new ColorModifier(0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 2.5f, 5.5f)); particleSystem.addParticleModifier(new AlphaModifier(1.0f, 0.0f, 2.5f, 6.5f)); scene.attachChild(particleSystem); } /* UpperLeft to UpperRight Particle System. */ { final ParticleSystem particleSystem = new ParticleSystem(new PointParticleEmitter(-32, 0), RATE_MIN, RATE_MAX, PARTICLES_MAX, this.mParticleTextureRegion); particleSystem.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE); particleSystem.addParticleInitializer(new VelocityInitializer(35, 45, 0, 10)); particleSystem.addParticleInitializer(new AccelerationInitializer(5, 11)); particleSystem.addParticleInitializer(new RotationInitializer(0.0f, 360.0f)); particleSystem.addParticleInitializer(new ColorInitializer(0.0f, 0.0f, 1.0f)); particleSystem.addParticleModifier(new ScaleModifier(0.5f, 2.0f, 0, 5)); particleSystem.addParticleModifier(new ExpireModifier(6.5f)); particleSystem.addParticleModifier(new ColorModifier(0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 2.5f, 5.5f)); particleSystem.addParticleModifier(new AlphaModifier(1.0f, 0.0f, 2.5f, 6.5f)); scene.attachChild(particleSystem); } /* UpperRight to UpperLeft Particle System. */ { final ParticleSystem particleSystem = new ParticleSystem(new PointParticleEmitter(CAMERA_WIDTH, 0), RATE_MIN, RATE_MAX, PARTICLES_MAX, this.mParticleTextureRegion); particleSystem.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE); particleSystem.addParticleInitializer(new VelocityInitializer(-35, -45, 0, 10)); particleSystem.addParticleInitializer(new AccelerationInitializer(-5, 12)); particleSystem.addParticleInitializer(new RotationInitializer(0.0f, 360.0f)); particleSystem.addParticleInitializer(new ColorInitializer(1.0f, 0.0f, 0.0f)); particleSystem.addParticleModifier(new ScaleModifier(0.5f, 2.0f, 0, 5)); particleSystem.addParticleModifier(new ExpireModifier(6.5f)); particleSystem.addParticleModifier(new ColorModifier(1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 2.5f, 5.5f)); particleSystem.addParticleModifier(new AlphaModifier(1.0f, 0.0f, 2.5f, 6.5f)); scene.attachChild(particleSystem); } return scene; } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples.benchmark; import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.concurrent.Callable; import org.anddev.andengine.engine.handler.timer.ITimerCallback; import org.anddev.andengine.engine.handler.timer.TimerHandler; import org.anddev.andengine.entity.util.FPSCounter; import org.anddev.andengine.examples.R; import org.anddev.andengine.opengl.util.GLHelper; import org.anddev.andengine.ui.activity.BaseGameActivity; import org.anddev.andengine.util.Callback; import org.anddev.andengine.util.Debug; import org.anddev.andengine.util.StreamUtils; import org.anddev.andengine.util.SystemUtils; import org.anddev.andengine.util.SystemUtils.SystemUtilsException; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import android.app.AlertDialog; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.os.Build; import android.telephony.TelephonyManager; import android.util.DisplayMetrics; import android.widget.Toast; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 10:38:36 - 27.06.2010 */ public abstract class BaseBenchmark extends BaseGameActivity { // =========================================================== // Constants // =========================================================== /* Initializing the Random generator produces a comparable result over different versions. */ private static final long RANDOM_SEED = 1234567890; private static final int DIALOG_SHOW_RESULT = 1; private static final String SUBMIT_URL = "http://www.andengine.org/sys/benchmark/submit.php"; protected static final int ANIMATIONBENCHMARK_ID = 0; protected static final int PARTICLESYSTEMBENCHMARK_ID = ANIMATIONBENCHMARK_ID + 1; protected static final int PHYSICSBENCHMARK_ID = PARTICLESYSTEMBENCHMARK_ID + 1; protected static final int ENTITYMODIFIERBENCHMARK_ID = PHYSICSBENCHMARK_ID + 1; protected static final int SPRITEBENCHMARK_ID = ENTITYMODIFIERBENCHMARK_ID + 1; protected static final int TICKERTEXTBENCHMARK_ID = SPRITEBENCHMARK_ID + 1; // =========================================================== // Fields // =========================================================== private float mFPS; protected final Random mRandom = new Random(RANDOM_SEED); // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // ===========================================================; protected void showResult(final float pFPS) { this.mFPS = pFPS; this.runOnUiThread(new Runnable() { @Override public void run() { BaseBenchmark.this.showDialog(DIALOG_SHOW_RESULT); } }); } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== protected abstract int getBenchmarkID(); protected abstract float getBenchmarkDuration(); protected abstract float getBenchmarkStartOffset(); @Override public void onLoadComplete() { this.mEngine.registerUpdateHandler(new TimerHandler(this.getBenchmarkStartOffset(), new ITimerCallback() { @Override public void onTimePassed(final TimerHandler pTimerHandler) { BaseBenchmark.this.mEngine.unregisterUpdateHandler(pTimerHandler); System.gc(); BaseBenchmark.this.setUpBenchmarkHandling(); } })); } protected void setUpBenchmarkHandling() { final FPSCounter fpsCounter = new FPSCounter(); this.mEngine.registerUpdateHandler(fpsCounter); this.mEngine.registerUpdateHandler(new TimerHandler(this.getBenchmarkDuration(), new ITimerCallback() { @Override public void onTimePassed(final TimerHandler pTimerHandler) { BaseBenchmark.this.showResult(fpsCounter.getFPS()); } })); } @Override protected Dialog onCreateDialog(final int pID) { switch(pID) { case DIALOG_SHOW_RESULT: return new AlertDialog.Builder(this) .setTitle(this.getClass().getSimpleName()) .setMessage(String.format("Result: %.2f FPS", this.mFPS)) .setPositiveButton("Submit (Please!)", new OnClickListener() { @Override public void onClick(final DialogInterface pDialog, final int pWhich) { BaseBenchmark.this.submitResults(); } }) .setNegativeButton(android.R.string.cancel, new OnClickListener() { @Override public void onClick(final DialogInterface pDialog, final int pWhich) { BaseBenchmark.this.finish(); } }) .create(); default: return super.onCreateDialog(pID); } } // =========================================================== // Methods // =========================================================== private void submitResults() { this.doAsync(R.string.dialog_benchmark_submit_title, R.string.dialog_benchmark_submit_message, new Callable<Boolean>() { @Override public Boolean call() throws Exception { // Create a new HttpClient and Post Header final HttpClient httpClient = new DefaultHttpClient(); final HttpPost httpPost = new HttpPost(SUBMIT_URL); // Add your data final List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(18); nameValuePairs.add(new BasicNameValuePair("benchmark_id", String.valueOf(BaseBenchmark.this.getBenchmarkID()))); nameValuePairs.add(new BasicNameValuePair("benchmark_versionname", BaseBenchmark.getVersionName(BaseBenchmark.this))); nameValuePairs.add(new BasicNameValuePair("benchmark_versioncode", String.valueOf(BaseBenchmark.getVersionCode(BaseBenchmark.this)))); nameValuePairs.add(new BasicNameValuePair("benchmark_fps", String.valueOf(BaseBenchmark.this.mFPS).replace(",", "."))); nameValuePairs.add(new BasicNameValuePair("device_model", Build.MODEL)); nameValuePairs.add(new BasicNameValuePair("device_android_version", Build.VERSION.RELEASE)); nameValuePairs.add(new BasicNameValuePair("device_sdk_version", String.valueOf(Build.VERSION.SDK_INT))); nameValuePairs.add(new BasicNameValuePair("device_manufacturer", Build.MANUFACTURER)); nameValuePairs.add(new BasicNameValuePair("device_brand", Build.BRAND)); nameValuePairs.add(new BasicNameValuePair("device_build_id", Build.ID)); nameValuePairs.add(new BasicNameValuePair("device_build", Build.DISPLAY)); nameValuePairs.add(new BasicNameValuePair("device_device", Build.DEVICE)); nameValuePairs.add(new BasicNameValuePair("device_product", Build.PRODUCT)); nameValuePairs.add(new BasicNameValuePair("device_cpuabi", Build.CPU_ABI)); nameValuePairs.add(new BasicNameValuePair("device_board", Build.BOARD)); nameValuePairs.add(new BasicNameValuePair("device_fingerprint", Build.FINGERPRINT)); nameValuePairs.add(new BasicNameValuePair("benchmark_extension_vbo", GLHelper.EXTENSIONS_VERTEXBUFFEROBJECTS ? "1" : "0")); nameValuePairs.add(new BasicNameValuePair("benchmark_extension_drawtexture", GLHelper.EXTENSIONS_DRAWTEXTURE ? "1" : "0")); final TelephonyManager telephonyManager = (TelephonyManager)BaseBenchmark.this.getSystemService(Context.TELEPHONY_SERVICE); nameValuePairs.add(new BasicNameValuePair("device_imei", telephonyManager.getDeviceId())); final DisplayMetrics displayMetrics = new DisplayMetrics(); BaseBenchmark.this.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics); nameValuePairs.add(new BasicNameValuePair("device_displaymetrics_widthpixels", String.valueOf(displayMetrics.widthPixels))); nameValuePairs.add(new BasicNameValuePair("device_displaymetrics_heightpixels", String.valueOf(displayMetrics.heightPixels))); nameValuePairs.add(new BasicNameValuePair("device_displaymetrics_xdpi", String.valueOf(displayMetrics.xdpi))); nameValuePairs.add(new BasicNameValuePair("device_displaymetrics_ydpi", String.valueOf(displayMetrics.ydpi))); try{ final float bogoMips = SystemUtils.getCPUBogoMips(); nameValuePairs.add(new BasicNameValuePair("device_cpuinfo_bogomips", String.valueOf(bogoMips))); }catch(IllegalStateException e) { Debug.e(e); } try{ final float memoryTotal = SystemUtils.getMemoryTotal(); final float memoryFree = SystemUtils.getMemoryFree(); nameValuePairs.add(new BasicNameValuePair("device_memoryinfo_total", String.valueOf(memoryTotal))); nameValuePairs.add(new BasicNameValuePair("device_memoryinfo_free", String.valueOf(memoryFree))); }catch(IllegalStateException e) { Debug.e(e); } try{ final int cpuFrequencyCurrent = SystemUtils.getCPUFrequencyCurrent(); final int cpuFrequencyMax = SystemUtils.getCPUFrequencyMax(); nameValuePairs.add(new BasicNameValuePair("device_cpuinfo_frequency_current", String.valueOf(cpuFrequencyCurrent))); nameValuePairs.add(new BasicNameValuePair("device_cpuinfo_frequency_max", String.valueOf(cpuFrequencyMax))); }catch(SystemUtilsException e) { Debug.e(e); } httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); // Execute HTTP Post Request final HttpResponse response = httpClient.execute(httpPost); final int statusCode = response.getStatusLine().getStatusCode(); Debug.d(StreamUtils.readFully(response.getEntity().getContent())); if(statusCode == HttpStatus.SC_OK) { return true; } else { throw new RuntimeException(); } } }, new Callback<Boolean>() { @Override public void onCallback(final Boolean pCallbackValue) { BaseBenchmark.this.runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(BaseBenchmark.this, "Success", Toast.LENGTH_LONG).show(); BaseBenchmark.this.finish(); } }); } }, new Callback<Exception>() { @Override public void onCallback(final Exception pException) { Debug.e(pException); Toast.makeText(BaseBenchmark.this, "Exception occurred: " + pException.getClass().getSimpleName(), Toast.LENGTH_SHORT).show(); BaseBenchmark.this.finish(); } }); } public static String getVersionName(final Context ctx) { try { final PackageInfo pi = ctx.getPackageManager().getPackageInfo(ctx.getPackageName(), 0); return pi.versionName; } catch (final PackageManager.NameNotFoundException e) { Debug.e("Package name not found", e); return "?"; } } public static int getVersionCode(final Context ctx) { try { final PackageInfo pi = ctx.getPackageManager().getPackageInfo(ctx.getPackageName(), 0); return pi.versionCode; } catch (final PackageManager.NameNotFoundException e) { Debug.e("Package name not found", e); return -1; } } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples.benchmark; 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.RatioResolutionPolicy; import org.anddev.andengine.entity.primitive.Rectangle; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.Scene.IOnSceneTouchListener; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.shape.Shape; import org.anddev.andengine.entity.sprite.AnimatedSprite; import org.anddev.andengine.extension.physics.box2d.PhysicsConnector; import org.anddev.andengine.extension.physics.box2d.PhysicsFactory; import org.anddev.andengine.extension.physics.box2d.PhysicsWorld; import org.anddev.andengine.extension.physics.box2d.util.Vector2Pool; import org.anddev.andengine.extension.physics.box2d.util.constants.PhysicsConstants; import org.anddev.andengine.input.touch.TouchEvent; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TiledTextureRegion; import android.hardware.SensorManager; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.Body; import com.badlogic.gdx.physics.box2d.BodyDef.BodyType; import com.badlogic.gdx.physics.box2d.FixtureDef; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 18:47:08 - 19.03.2010 */ public class PhysicsBenchmark extends BaseBenchmark implements IOnSceneTouchListener { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; private static final int COUNT_HORIZONTAL = 17; private static final int COUNT_VERTICAL = 15; // =========================================================== // Fields // =========================================================== private BitmapTextureAtlas mBitmapTextureAtlas; private TiledTextureRegion mBoxFaceTextureRegion; private TiledTextureRegion mCircleFaceTextureRegion; private Scene mScene; private PhysicsWorld mPhysicsWorld; private int mFaceCount = 0; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override protected int getBenchmarkID() { return PHYSICSBENCHMARK_ID; } @Override protected float getBenchmarkStartOffset() { return 2; } @Override protected float getBenchmarkDuration() { return 20; } @Override public Engine onLoadEngine() { final Camera camera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), camera)); } @Override public void onLoadResources() { this.mBitmapTextureAtlas = new BitmapTextureAtlas(64, 64, TextureOptions.BILINEAR_PREMULTIPLYALPHA); BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mBoxFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "face_box_tiled.png", 0, 0, 2, 1); // 64x32 this.mCircleFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "face_circle_tiled.png", 0, 32, 2, 1); // 64x32 this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { this.mScene = new Scene(); this.mScene.setBackground(new ColorBackground(0, 0, 0)); this.mScene.setOnSceneTouchListener(this); this.mPhysicsWorld = new PhysicsWorld(new Vector2(0, 2 * SensorManager.GRAVITY_EARTH / PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT), false); final Shape ground = new Rectangle(0, CAMERA_HEIGHT - 2, CAMERA_WIDTH, 2); final Shape roof = new Rectangle(0, 0, CAMERA_WIDTH, 2); final Shape left = new Rectangle(0, 0, 2, CAMERA_HEIGHT); final Shape right = new Rectangle(CAMERA_WIDTH - 2, 0, 2, CAMERA_HEIGHT); final FixtureDef wallFixtureDef = PhysicsFactory.createFixtureDef(0, 0.5f, 0.5f); PhysicsFactory.createBoxBody(this.mPhysicsWorld, ground, BodyType.StaticBody, wallFixtureDef); PhysicsFactory.createBoxBody(this.mPhysicsWorld, roof, BodyType.StaticBody, wallFixtureDef); PhysicsFactory.createBoxBody(this.mPhysicsWorld, left, BodyType.StaticBody, wallFixtureDef); PhysicsFactory.createBoxBody(this.mPhysicsWorld, right, BodyType.StaticBody, wallFixtureDef); this.mScene.attachChild(ground); this.mScene.attachChild(roof); this.mScene.attachChild(left); this.mScene.attachChild(right); for(int x = 1; x < COUNT_HORIZONTAL; x++) { for(int y = 1; y < COUNT_VERTICAL; y++) { final float pX = (((float)CAMERA_WIDTH) / COUNT_HORIZONTAL) * x + y; final float pY = (((float)CAMERA_HEIGHT) / COUNT_VERTICAL) * y; this.addFace(this.mScene, pX - 16, pY - 16); } } this.mScene.registerUpdateHandler(new TimerHandler(2, new ITimerCallback() { @Override public void onTimePassed(final TimerHandler pTimerHandler) { PhysicsBenchmark.this.mScene.unregisterUpdateHandler(pTimerHandler); PhysicsBenchmark.this.mScene.registerUpdateHandler(PhysicsBenchmark.this.mPhysicsWorld); PhysicsBenchmark.this.mScene.registerUpdateHandler(new TimerHandler(10, new ITimerCallback() { @Override public void onTimePassed(final TimerHandler pTimerHandler) { final Vector2 gravity = Vector2Pool.obtain(0, -SensorManager.GRAVITY_EARTH / 32); PhysicsBenchmark.this.mPhysicsWorld.setGravity(gravity); Vector2Pool.recycle(gravity); } })); } })); return this.mScene; } @Override public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) { if(this.mPhysicsWorld != null) { if(pSceneTouchEvent.isActionDown()) { this.addFace(pScene, pSceneTouchEvent.getX(), pSceneTouchEvent.getY()); return true; } } return false; } // =========================================================== // Methods // =========================================================== private void addFace(final Scene pScene, final float pX, final float pY) { this.mFaceCount++; final AnimatedSprite face; final Body body; final FixtureDef objectFixtureDef = PhysicsFactory.createFixtureDef(1, 0.5f, 0.5f); if(this.mFaceCount % 2 == 0) { face = new AnimatedSprite(pX, pY, this.mBoxFaceTextureRegion); body = PhysicsFactory.createBoxBody(this.mPhysicsWorld, face, BodyType.DynamicBody, objectFixtureDef); } else { face = new AnimatedSprite(pX, pY, this.mCircleFaceTextureRegion); body = PhysicsFactory.createCircleBody(this.mPhysicsWorld, face, BodyType.DynamicBody, objectFixtureDef); } pScene.attachChild(face); this.mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(face, body, true, true)); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples.benchmark; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.text.Text; import org.anddev.andengine.entity.text.TickerText; import org.anddev.andengine.opengl.font.Font; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.util.HorizontalAlign; import android.graphics.Color; import android.graphics.Typeface; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 21:00:56 - 28.06.2010 */ public class TickerTextBenchmark extends BaseBenchmark { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; private static final int TEXT_COUNT = 200; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mFontTexture; private Font mFont; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override protected int getBenchmarkID() { return TICKERTEXTBENCHMARK_ID; } @Override protected float getBenchmarkStartOffset() { return 2; } @Override protected float getBenchmarkDuration() { return 10; } @Override public Engine onLoadEngine() { this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override public void onLoadResources() { this.mFontTexture = new BitmapTextureAtlas(256, 256, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mFont = new Font(this.mFontTexture, Typeface.create(Typeface.DEFAULT, Typeface.BOLD), 22, true, Color.WHITE); this.mEngine.getTextureManager().loadTexture(this.mFontTexture); this.getFontManager().loadFont(this.mFont); } @Override public Scene onLoadScene() { final Scene scene = new Scene(); scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); for(int i = 0; i < TEXT_COUNT; i++) { final Text text = new TickerText(this.mRandom.nextInt(30), this.mRandom.nextFloat() * (CAMERA_HEIGHT - 20), this.mFont, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", HorizontalAlign.CENTER, 5 + 5 * this.mRandom.nextFloat()); text.setColor(this.mRandom.nextFloat(), this.mRandom.nextFloat(), this.mRandom.nextFloat()); scene.attachChild(text); } return scene; } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples.benchmark; import javax.microedition.khronos.opengles.GL10; import javax.microedition.khronos.opengles.GL11; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.sprite.Sprite; import org.anddev.andengine.entity.sprite.batch.SpriteBatch; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TextureRegion; import org.anddev.andengine.opengl.vertex.RectangleVertexBuffer; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 10:34:22 - 27.06.2010 */ public class SpriteBenchmark extends BaseBenchmark { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; private static final int SPRITE_COUNT = 1000; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mBitmapTextureAtlas; private TextureRegion mFaceTextureRegion; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override protected int getBenchmarkID() { return SPRITEBENCHMARK_ID; } @Override protected float getBenchmarkStartOffset() { return 2; } @Override protected float getBenchmarkDuration() { return 10; } @Override public Engine onLoadEngine() { this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override public void onLoadResources() { this.mBitmapTextureAtlas = new BitmapTextureAtlas(32, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA); BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "face_box.png", 0, 0); this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { final Scene scene = new Scene(); scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); this.drawUsingSprites(scene); // this.drawUsingSpritesWithSharedVertexBuffer(scene); // this.drawUsingSpriteBatch(scene); return scene; } // =========================================================== // Methods // =========================================================== private void drawUsingSprites(final Scene scene) { for(int i = 0; i < SPRITE_COUNT; i++) { final Sprite face = new Sprite(this.mRandom.nextFloat() * (CAMERA_WIDTH - 32), this.mRandom.nextFloat() * (CAMERA_HEIGHT - 32), this.mFaceTextureRegion); face.setBlendFunction(GL10.GL_ONE, GL10.GL_ONE_MINUS_SRC_ALPHA); face.setIgnoreUpdate(true); scene.attachChild(face); } } private void drawUsingSpritesWithSharedVertexBuffer(final Scene scene) { /* As we are creating quite a lot of the same Sprites, we can let them share a VertexBuffer to significantly increase performance. */ final RectangleVertexBuffer sharedVertexBuffer = new RectangleVertexBuffer(GL11.GL_STATIC_DRAW, true); sharedVertexBuffer.update(this.mFaceTextureRegion.getWidth(), this.mFaceTextureRegion.getHeight()); for(int i = 0; i < SPRITE_COUNT; i++) { final Sprite face = new Sprite(this.mRandom.nextFloat() * (CAMERA_WIDTH - 32), this.mRandom.nextFloat() * (CAMERA_HEIGHT - 32), this.mFaceTextureRegion, sharedVertexBuffer); face.setBlendFunction(GL10.GL_ONE, GL10.GL_ONE_MINUS_SRC_ALPHA); face.setIgnoreUpdate(true); scene.attachChild(face); } } private void drawUsingSpriteBatch(final Scene scene) { final int width = this.mFaceTextureRegion.getWidth(); final int height = this.mFaceTextureRegion.getHeight(); final SpriteBatch spriteBatch = new SpriteBatch(this.mBitmapTextureAtlas, SPRITE_COUNT); spriteBatch.setBlendFunction(GL10.GL_ONE, GL10.GL_ONE_MINUS_SRC_ALPHA); for(int i = 0; i < SPRITE_COUNT; i++) { final float x = this.mRandom.nextFloat() * (CAMERA_WIDTH - 32); final float y = this.mRandom.nextFloat() * (CAMERA_HEIGHT - 32); spriteBatch.draw(this.mFaceTextureRegion, x, y, width, height); } spriteBatch.submit(); scene.attachChild(spriteBatch); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples.benchmark; import javax.microedition.khronos.opengles.GL11; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.modifier.AlphaModifier; import org.anddev.andengine.entity.modifier.DelayModifier; import org.anddev.andengine.entity.modifier.IEntityModifier; import org.anddev.andengine.entity.modifier.ParallelEntityModifier; import org.anddev.andengine.entity.modifier.RotationByModifier; import org.anddev.andengine.entity.modifier.RotationModifier; import org.anddev.andengine.entity.modifier.ScaleModifier; import org.anddev.andengine.entity.modifier.SequenceEntityModifier; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.sprite.Sprite; import org.anddev.andengine.entity.sprite.batch.SpriteGroup; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TextureRegion; import org.anddev.andengine.opengl.vertex.RectangleVertexBuffer; import android.opengl.GLES20; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 20:24:17 - 27.06.2010 */ public class EntityModifierBenchmark extends BaseBenchmark { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; private static final int SPRITE_COUNT = 1000; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mBitmapTextureAtlas; private TextureRegion mFaceTextureRegion; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override protected int getBenchmarkID() { return ENTITYMODIFIERBENCHMARK_ID; } @Override protected float getBenchmarkStartOffset() { return 2; } @Override protected float getBenchmarkDuration() { return 10; } @Override public Engine onLoadEngine() { this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override public void onLoadResources() { this.mBitmapTextureAtlas = new BitmapTextureAtlas(32, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA); BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "face_box.png", 0, 0); this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { final Scene scene = new Scene(); scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); // this.drawUsingSprites(scene); // this.drawUsingSpritesWithSharedVertexBuffer(scene); this.drawUsingSpriteBatch(scene); return scene; } // =========================================================== // Methods // =========================================================== private void drawUsingSprites(final Scene pScene) { final IEntityModifier faceEntityModifier = new SequenceEntityModifier( new RotationByModifier(2, 90), new AlphaModifier(1.5f, 1, 0), new AlphaModifier(1.5f, 0, 1), new ScaleModifier(2.5f, 1, 0.5f), new DelayModifier(0.5f), new ParallelEntityModifier( new ScaleModifier(2f, 0.5f, 5), new RotationByModifier(2, 90) ), new ParallelEntityModifier( new ScaleModifier(2f, 5, 1), new RotationModifier(2f, 180, 0) ) ); for(int i = 0; i < SPRITE_COUNT; i++) { final Sprite face = new Sprite((CAMERA_WIDTH - 32) * this.mRandom.nextFloat(), (CAMERA_HEIGHT - 32) * this.mRandom.nextFloat(), this.mFaceTextureRegion); face.setBlendFunction(GLES20.GL_SRC_ALPHA, GLES20.GL_ONE_MINUS_SRC_ALPHA); face.registerEntityModifier(faceEntityModifier.deepCopy()); pScene.attachChild(face); } } private void drawUsingSpritesWithSharedVertexBuffer(final Scene pScene) { final IEntityModifier faceEntityModifier = new SequenceEntityModifier( new RotationByModifier(2, 90), new AlphaModifier(1.5f, 1, 0), new AlphaModifier(1.5f, 0, 1), new ScaleModifier(2.5f, 1, 0.5f), new DelayModifier(0.5f), new ParallelEntityModifier( new ScaleModifier(2f, 0.5f, 5), new RotationByModifier(2, 90) ), new ParallelEntityModifier( new ScaleModifier(2f, 5, 1), new RotationModifier(2f, 180, 0) ) ); /* As we are creating quite a lot of the same Sprites, we can let them share a VertexBuffer to significantly increase performance. */ final RectangleVertexBuffer sharedVertexBuffer = new RectangleVertexBuffer(GL11.GL_DYNAMIC_DRAW, true); sharedVertexBuffer.update(this.mFaceTextureRegion.getWidth(), this.mFaceTextureRegion.getHeight()); for(int i = 0; i < SPRITE_COUNT; i++) { final Sprite face = new Sprite((CAMERA_WIDTH - 32) * this.mRandom.nextFloat(), (CAMERA_HEIGHT - 32) * this.mRandom.nextFloat(), this.mFaceTextureRegion, sharedVertexBuffer); face.setBlendFunction(GLES20.GL_SRC_ALPHA, GLES20.GL_ONE_MINUS_SRC_ALPHA); face.registerEntityModifier(faceEntityModifier.deepCopy()); pScene.attachChild(face); } } private void drawUsingSpriteBatch(final Scene pScene) { final IEntityModifier faceEntityModifier = new SequenceEntityModifier( new RotationByModifier(2, 90), // new AlphaModifier(1.5f, 1, 0), // new AlphaModifier(1.5f, 0, 1), new DelayModifier(1.5f + 1.5f), new ScaleModifier(2.5f, 1, 0.5f), new DelayModifier(0.5f), new ParallelEntityModifier( new ScaleModifier(2f, 0.5f, 5), new RotationByModifier(2, 90) ), new ParallelEntityModifier( new ScaleModifier(2f, 5, 1), new RotationModifier(2f, 180, 0) ) ); final IEntityModifier spriteBatchEntityModifier = new SequenceEntityModifier( new DelayModifier(2), new AlphaModifier(1.5f, 1, 0), new AlphaModifier(1.5f, 0, 1) ); final SpriteGroup spriteGroup = new SpriteGroup(this.mBitmapTextureAtlas, SPRITE_COUNT); spriteGroup.setBlendFunction(GLES20.GL_SRC_ALPHA, GLES20.GL_ONE_MINUS_SRC_ALPHA); for(int i = 0; i < SPRITE_COUNT; i++) { final Sprite face = new Sprite((CAMERA_WIDTH - 32) * this.mRandom.nextFloat(), (CAMERA_HEIGHT - 32) * this.mRandom.nextFloat(), this.mFaceTextureRegion); face.registerEntityModifier(faceEntityModifier.deepCopy()); spriteGroup.attachChild(face); } spriteGroup.registerEntityModifier(spriteBatchEntityModifier); pScene.attachChild(spriteGroup); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples.benchmark; import javax.microedition.khronos.opengles.GL11; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.sprite.AnimatedSprite; import org.anddev.andengine.entity.sprite.batch.SpriteGroup; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TiledTextureRegion; import org.anddev.andengine.opengl.vertex.RectangleVertexBuffer; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 11:28:45 - 28.06.2010 */ public class AnimationBenchmark extends BaseBenchmark { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; private static final int SPRITE_COUNT = 250; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mBitmapTextureAtlas; private TiledTextureRegion mSnapdragonTextureRegion; private TiledTextureRegion mHelicopterTextureRegion; private TiledTextureRegion mBananaTextureRegion; private TiledTextureRegion mFaceTextureRegion; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override protected int getBenchmarkID() { return ANIMATIONBENCHMARK_ID; } @Override protected float getBenchmarkStartOffset() { return 2; } @Override protected float getBenchmarkDuration() { return 10; } @Override public Engine onLoadEngine() { this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); final EngineOptions engineOptions = new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera); // engineOptions.getRenderOptions().disableExtensionVertexBufferObjects(); return new Engine(engineOptions); } @Override public void onLoadResources() { this.mBitmapTextureAtlas = new BitmapTextureAtlas(512, 256, TextureOptions.BILINEAR_PREMULTIPLYALPHA); BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mSnapdragonTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "snapdragon_tiled.png", 0, 0, 4, 3); this.mHelicopterTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "helicopter_tiled.png", 400, 0, 2, 2); this.mBananaTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "banana_tiled.png", 0, 180, 4, 2); this.mFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "face_box_tiled.png", 132, 180, 2, 1); this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { final Scene scene = new Scene(); scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); this.drawUsingSprites(scene); // this.drawUsingSpritesWithSharedVertexBuffer(scene); // this.drawUsingSpriteBatch(scene); return scene; } private void drawUsingSprites(Scene pScene) { for(int i = 0; i < SPRITE_COUNT; i++) { /* Quickly twinkling face. */ final AnimatedSprite face = new AnimatedSprite(this.mRandom.nextFloat() * (CAMERA_WIDTH - 32), this.mRandom.nextFloat() * (CAMERA_HEIGHT - 32), this.mFaceTextureRegion.deepCopy()); face.animate(50 + this.mRandom.nextInt(100)); pScene.attachChild(face); /* Continuously flying helicopter. */ final AnimatedSprite helicopter = new AnimatedSprite(this.mRandom.nextFloat() * (CAMERA_WIDTH - 48), this.mRandom.nextFloat() * (CAMERA_HEIGHT - 48), this.mHelicopterTextureRegion.deepCopy()); helicopter.animate(new long[] { 50 + this.mRandom.nextInt(100), 50 + this.mRandom.nextInt(100) }, 1, 2, true); pScene.attachChild(helicopter); /* Snapdragon. */ final AnimatedSprite snapdragon = new AnimatedSprite(this.mRandom.nextFloat() * (CAMERA_WIDTH - 100), this.mRandom.nextFloat() * (CAMERA_HEIGHT - 60), this.mSnapdragonTextureRegion.deepCopy()); snapdragon.animate(50 + this.mRandom.nextInt(100)); pScene.attachChild(snapdragon); /* Funny banana. */ final AnimatedSprite banana = new AnimatedSprite(this.mRandom.nextFloat() * (CAMERA_WIDTH - 32), this.mRandom.nextFloat() * (CAMERA_HEIGHT - 32), this.mBananaTextureRegion.deepCopy()); banana.animate(50 + this.mRandom.nextInt(100)); pScene.attachChild(banana); } } private void drawUsingSpritesWithSharedVertexBuffer(Scene pScene) { /* As we are creating quite a lot of the same Sprites, we can let them share a VertexBuffer to significantly increase performance. */ final RectangleVertexBuffer faceSharedVertexBuffer = new RectangleVertexBuffer(GL11.GL_DYNAMIC_DRAW, true); faceSharedVertexBuffer.update(this.mFaceTextureRegion.getWidth(), this.mFaceTextureRegion.getHeight()); final RectangleVertexBuffer helicopterSharedVertexBuffer = new RectangleVertexBuffer(GL11.GL_DYNAMIC_DRAW, true); helicopterSharedVertexBuffer.update(this.mHelicopterTextureRegion.getWidth(), this.mHelicopterTextureRegion.getHeight()); final RectangleVertexBuffer snapdragonSharedVertexBuffer = new RectangleVertexBuffer(GL11.GL_DYNAMIC_DRAW, true); snapdragonSharedVertexBuffer.update(this.mSnapdragonTextureRegion.getWidth(), this.mSnapdragonTextureRegion.getHeight()); final RectangleVertexBuffer bananaSharedVertexBuffer = new RectangleVertexBuffer(GL11.GL_DYNAMIC_DRAW, true); bananaSharedVertexBuffer.update(this.mBananaTextureRegion.getWidth(), this.mBananaTextureRegion.getHeight()); for(int i = 0; i < SPRITE_COUNT; i++) { /* Quickly twinkling face. */ final AnimatedSprite face = new AnimatedSprite(this.mRandom.nextFloat() * (CAMERA_WIDTH - 32), this.mRandom.nextFloat() * (CAMERA_HEIGHT - 32), this.mFaceTextureRegion.deepCopy(), faceSharedVertexBuffer); face.animate(50 + this.mRandom.nextInt(100)); pScene.attachChild(face); /* Continuously flying helicopter. */ final AnimatedSprite helicopter = new AnimatedSprite(this.mRandom.nextFloat() * (CAMERA_WIDTH - 48), this.mRandom.nextFloat() * (CAMERA_HEIGHT - 48), this.mHelicopterTextureRegion.deepCopy(), helicopterSharedVertexBuffer); helicopter.animate(new long[] { 50 + this.mRandom.nextInt(100), 50 + this.mRandom.nextInt(100) }, 1, 2, true); pScene.attachChild(helicopter); /* Snapdragon. */ final AnimatedSprite snapdragon = new AnimatedSprite(this.mRandom.nextFloat() * (CAMERA_WIDTH - 100), this.mRandom.nextFloat() * (CAMERA_HEIGHT - 60), this.mSnapdragonTextureRegion.deepCopy(), snapdragonSharedVertexBuffer); snapdragon.animate(50 + this.mRandom.nextInt(100)); pScene.attachChild(snapdragon); /* Funny banana. */ final AnimatedSprite banana = new AnimatedSprite(this.mRandom.nextFloat() * (CAMERA_WIDTH - 32), this.mRandom.nextFloat() * (CAMERA_HEIGHT - 32), this.mBananaTextureRegion.deepCopy(), bananaSharedVertexBuffer); banana.animate(50 + this.mRandom.nextInt(100)); pScene.attachChild(banana); } } private void drawUsingSpriteBatch(Scene pScene) { final SpriteGroup spriteGroup = new SpriteGroup(this.mBitmapTextureAtlas, 4 * SPRITE_COUNT); for(int i = 0; i < SPRITE_COUNT; i++) { /* Quickly twinkling face. */ final AnimatedSprite face = new AnimatedSprite(this.mRandom.nextFloat() * (CAMERA_WIDTH - 32), this.mRandom.nextFloat() * (CAMERA_HEIGHT - 32), this.mFaceTextureRegion.deepCopy()); //, faceSharedVertexBuffer); face.animate(50 + this.mRandom.nextInt(100)); spriteGroup.attachChild(face); /* Continuously flying helicopter. */ final AnimatedSprite helicopter = new AnimatedSprite(this.mRandom.nextFloat() * (CAMERA_WIDTH - 48), this.mRandom.nextFloat() * (CAMERA_HEIGHT - 48), this.mHelicopterTextureRegion.deepCopy()); //, helicopterSharedVertexBuffer); helicopter.animate(new long[] { 50 + this.mRandom.nextInt(100), 50 + this.mRandom.nextInt(100) }, 1, 2, true); spriteGroup.attachChild(helicopter); /* Snapdragon. */ final AnimatedSprite snapdragon = new AnimatedSprite(this.mRandom.nextFloat() * (CAMERA_WIDTH - 100), this.mRandom.nextFloat() * (CAMERA_HEIGHT - 60), this.mSnapdragonTextureRegion.deepCopy()); //, snapdragonSharedVertexBuffer); snapdragon.animate(50 + this.mRandom.nextInt(100)); spriteGroup.attachChild(snapdragon); /* Funny banana. */ final AnimatedSprite banana = new AnimatedSprite(this.mRandom.nextFloat() * (CAMERA_WIDTH - 32), this.mRandom.nextFloat() * (CAMERA_HEIGHT - 32), this.mBananaTextureRegion.deepCopy()); //, bananaSharedVertexBuffer); banana.animate(50 + this.mRandom.nextInt(100)); spriteGroup.attachChild(banana); } pScene.attachChild(spriteGroup); } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.sprite.Sprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.atlas.bitmap.source.AssetBitmapTextureAtlasSource; import org.anddev.andengine.opengl.texture.atlas.bitmap.source.decorator.ColorKeyBitmapTextureAtlasSourceDecorator; import org.anddev.andengine.opengl.texture.atlas.bitmap.source.decorator.shape.RectangleBitmapTextureAtlasSourceDecoratorShape; import org.anddev.andengine.opengl.texture.region.TextureRegion; import android.graphics.Color; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 11:54:51 - 03.04.2010 */ public class ColorKeyTextureSourceDecoratorExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 480; private static final int CAMERA_HEIGHT = 320; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mBitmapTextureAtlas; private TextureRegion mChromaticCircleTextureRegion; private TextureRegion mChromaticCircleColorKeyedTextureRegion; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override public void onLoadResources() { this.mBitmapTextureAtlas = new BitmapTextureAtlas(256, 128, TextureOptions.BILINEAR_PREMULTIPLYALPHA); /* The actual AssetTextureSource. */ BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); final AssetBitmapTextureAtlasSource baseTextureSource = new AssetBitmapTextureAtlasSource(this, "chromatic_circle.png"); this.mChromaticCircleTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromSource(this.mBitmapTextureAtlas, baseTextureSource, 0, 0); /* We will remove both the red and the green segment of the chromatic circle, * by nesting two ColorKeyTextureSourceDecorators around the actual baseTextureSource. */ final int colorKeyRed = Color.rgb(255, 0, 51); // Red segment final int colorKeyGreen = Color.rgb(0, 179, 0); // Green segment final ColorKeyBitmapTextureAtlasSourceDecorator colorKeyBitmapTextureAtlasSource = new ColorKeyBitmapTextureAtlasSourceDecorator(new ColorKeyBitmapTextureAtlasSourceDecorator(baseTextureSource, RectangleBitmapTextureAtlasSourceDecoratorShape.getDefaultInstance(), colorKeyRed), RectangleBitmapTextureAtlasSourceDecoratorShape.getDefaultInstance(), colorKeyGreen); this.mChromaticCircleColorKeyedTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromSource(this.mBitmapTextureAtlas, colorKeyBitmapTextureAtlasSource, 128, 0); this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); final int centerX = (CAMERA_WIDTH - this.mChromaticCircleTextureRegion.getWidth()) / 2; final int centerY = (CAMERA_HEIGHT - this.mChromaticCircleTextureRegion.getHeight()) / 2; final Sprite chromaticCircle = new Sprite(centerX - 80, centerY, this.mChromaticCircleTextureRegion); final Sprite chromaticCircleColorKeyed = new Sprite(centerX + 80, centerY, this.mChromaticCircleColorKeyedTextureRegion); scene.attachChild(chromaticCircle); scene.attachChild(chromaticCircleColorKeyed); return scene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import java.util.HashMap; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.sprite.Sprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.examples.adt.card.Card; import org.anddev.andengine.extension.input.touch.controller.MultiTouch; import org.anddev.andengine.extension.input.touch.controller.MultiTouchController; import org.anddev.andengine.extension.input.touch.exception.MultiTouchException; import org.anddev.andengine.input.touch.TouchEvent; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TextureRegion; import org.anddev.andengine.opengl.texture.region.TextureRegionFactory; import android.widget.Toast; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 18:20:40 - 18.06.2010 */ public class MultiTouchExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mCardDeckTexture; private Scene mScene; private HashMap<Card, TextureRegion> mCardTotextureRegionMap; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); final Engine engine = new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); try { if(MultiTouch.isSupported(this)) { engine.setTouchController(new MultiTouchController()); if(MultiTouch.isSupportedDistinct(this)) { Toast.makeText(this, "MultiTouch detected --> Drag multiple Sprites with multiple fingers!", Toast.LENGTH_LONG).show(); } else { Toast.makeText(this, "MultiTouch detected --> Drag multiple Sprites with multiple fingers!\n\n(Your device might have problems to distinguish between separate fingers.)", Toast.LENGTH_LONG).show(); } } else { Toast.makeText(this, "Sorry your device does NOT support MultiTouch!\n\n(Falling back to SingleTouch.)", Toast.LENGTH_LONG).show(); } } catch (final MultiTouchException e) { Toast.makeText(this, "Sorry your Android Version does NOT support MultiTouch!\n\n(Falling back to SingleTouch.)", Toast.LENGTH_LONG).show(); } return engine; } @Override public void onLoadResources() { this.mCardDeckTexture = new BitmapTextureAtlas(1024, 512, TextureOptions.BILINEAR_PREMULTIPLYALPHA); BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mCardDeckTexture, this, "carddeck_tiled.png", 0, 0); this.mCardTotextureRegionMap = new HashMap<Card, TextureRegion>(); /* Extract the TextureRegion of each card in the whole deck. */ for(final Card card : Card.values()) { final TextureRegion cardTextureRegion = TextureRegionFactory.extractFromTexture(this.mCardDeckTexture, card.getTexturePositionX(), card.getTexturePositionY(), Card.CARD_WIDTH, Card.CARD_HEIGHT, true); this.mCardTotextureRegionMap.put(card, cardTextureRegion); } this.mEngine.getTextureManager().loadTexture(this.mCardDeckTexture); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); this.mScene = new Scene(); this.mScene.setOnAreaTouchTraversalFrontToBack(); this.addCard(Card.CLUB_ACE, 200, 100); this.addCard(Card.HEART_ACE, 200, 260); this.addCard(Card.DIAMOND_ACE, 440, 100); this.addCard(Card.SPADE_ACE, 440, 260); this.mScene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); this.mScene.setTouchAreaBindingEnabled(true); return this.mScene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== private void addCard(final Card pCard, final int pX, final int pY) { final Sprite sprite = new Sprite(pX, pY, this.mCardTotextureRegionMap.get(pCard)) { boolean mGrabbed = false; @Override public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final float pTouchAreaLocalX, final float pTouchAreaLocalY) { switch(pSceneTouchEvent.getAction()) { case TouchEvent.ACTION_DOWN: this.setScale(1.25f); this.mGrabbed = true; break; case TouchEvent.ACTION_MOVE: if(this.mGrabbed) { this.setPosition(pSceneTouchEvent.getX() - Card.CARD_WIDTH / 2, pSceneTouchEvent.getY() - Card.CARD_HEIGHT / 2); } break; case TouchEvent.ACTION_UP: if(this.mGrabbed) { this.mGrabbed = false; this.setScale(1.0f); } break; } return true; } }; this.mScene.attachChild(sprite); this.mScene.registerTouchArea(sprite); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import javax.microedition.khronos.opengles.GL10; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.particle.ParticleSystem; import org.anddev.andengine.entity.particle.emitter.CircleOutlineParticleEmitter; import org.anddev.andengine.entity.particle.initializer.AlphaInitializer; import org.anddev.andengine.entity.particle.initializer.ColorInitializer; import org.anddev.andengine.entity.particle.initializer.RotationInitializer; import org.anddev.andengine.entity.particle.initializer.VelocityInitializer; import org.anddev.andengine.entity.particle.modifier.AlphaModifier; import org.anddev.andengine.entity.particle.modifier.ColorModifier; import org.anddev.andengine.entity.particle.modifier.ExpireModifier; import org.anddev.andengine.entity.particle.modifier.ScaleModifier; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.Scene.IOnSceneTouchListener; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.input.touch.TouchEvent; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TextureRegion; import android.widget.Toast; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 11:54:51 - 03.04.2010 */ public class ParticleSystemSimpleExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mBitmapTextureAtlas; private TextureRegion mParticleTextureRegion; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { Toast.makeText(this, "Touch the screen to move the particlesystem.", Toast.LENGTH_LONG).show(); this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override public void onLoadResources() { this.mBitmapTextureAtlas = new BitmapTextureAtlas(32, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA); BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mParticleTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "particle_point.png", 0, 0); this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); final CircleOutlineParticleEmitter particleEmitter = new CircleOutlineParticleEmitter(CAMERA_WIDTH * 0.5f, CAMERA_HEIGHT * 0.5f + 20, 80); final ParticleSystem particleSystem = new ParticleSystem(particleEmitter, 60, 60, 360, this.mParticleTextureRegion); scene.setOnSceneTouchListener(new IOnSceneTouchListener() { @Override public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) { particleEmitter.setCenter(pSceneTouchEvent.getX(), pSceneTouchEvent.getY()); return true; } }); particleSystem.addParticleInitializer(new ColorInitializer(1, 0, 0)); particleSystem.addParticleInitializer(new AlphaInitializer(0)); particleSystem.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE); particleSystem.addParticleInitializer(new VelocityInitializer(-2, 2, -20, -10)); particleSystem.addParticleInitializer(new RotationInitializer(0.0f, 360.0f)); particleSystem.addParticleModifier(new ScaleModifier(1.0f, 2.0f, 0, 5)); particleSystem.addParticleModifier(new ColorModifier(1, 1, 0, 0.5f, 0, 0, 0, 3)); particleSystem.addParticleModifier(new ColorModifier(1, 1, 0.5f, 1, 0, 1, 4, 6)); particleSystem.addParticleModifier(new AlphaModifier(0, 1, 0, 1)); particleSystem.addParticleModifier(new AlphaModifier(1, 0, 5, 6)); particleSystem.addParticleModifier(new ExpireModifier(6, 6)); scene.attachChild(particleSystem); return scene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.Scene.IOnSceneTouchListener; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.sprite.Sprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.input.touch.TouchEvent; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TextureRegion; import org.anddev.andengine.util.pool.RunnablePoolItem; import org.anddev.andengine.util.pool.RunnablePoolUpdateHandler; import android.widget.Toast; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 14:56:22 - 15.06.2011 */ public class RunnablePoolUpdateHandlerExample extends BaseExample implements IOnSceneTouchListener { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; private static final int FACE_COUNT = 2; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mBitmapTextureAtlas; private TextureRegion mFaceTextureRegion; private int mTargetFaceIndex = 0; private final Sprite[] mFaces = new Sprite[FACE_COUNT]; private final RunnablePoolUpdateHandler<FaceRotateRunnablePoolItem> mFaceRotateRunnablePoolUpdateHandler = new RunnablePoolUpdateHandler<FaceRotateRunnablePoolItem>() { @Override protected FaceRotateRunnablePoolItem onAllocatePoolItem() { return new FaceRotateRunnablePoolItem(); } }; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { Toast.makeText(this, "Touch the screen to rotate the sprites using RunnablePoolItems.", Toast.LENGTH_LONG).show(); this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override public void onLoadResources() { this.mBitmapTextureAtlas = new BitmapTextureAtlas(32, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA); BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "face_box.png", 0, 0); this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); scene.registerUpdateHandler(this.mFaceRotateRunnablePoolUpdateHandler); /* Calculate the coordinates for the face, so its centered on the camera. */ final int centerX = (CAMERA_WIDTH - this.mFaceTextureRegion.getWidth()) / 2; final int centerY = (CAMERA_HEIGHT - this.mFaceTextureRegion.getHeight()) / 2; this.mFaces[0] = new Sprite(centerX - 50, centerY, this.mFaceTextureRegion); this.mFaces[1] = new Sprite(centerX + 50, centerY, this.mFaceTextureRegion); scene.attachChild(this.mFaces[0]); scene.attachChild(this.mFaces[1]); scene.setOnSceneTouchListener(this); return scene; } @Override public void onLoadComplete() { } @Override public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) { if(pSceneTouchEvent.isActionDown()) { this.mTargetFaceIndex = (this.mTargetFaceIndex + 1) % FACE_COUNT; final FaceRotateRunnablePoolItem faceRotateRunnablePoolItem = this.mFaceRotateRunnablePoolUpdateHandler.obtainPoolItem(); faceRotateRunnablePoolItem.setTargetFace(this.mFaces[this.mTargetFaceIndex]); this.mFaceRotateRunnablePoolUpdateHandler.postPoolItem(faceRotateRunnablePoolItem); } return true; } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== public class FaceRotateRunnablePoolItem extends RunnablePoolItem { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private Sprite mTargetFace; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== public void setTargetFace(final Sprite pTargetFace) { this.mTargetFace = pTargetFace; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public void run() { this.mTargetFace.setRotation(this.mTargetFace.getRotation() + 45); } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== } }
Java
package org.anddev.andengine.examples; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.IEntity; import org.anddev.andengine.entity.modifier.LoopEntityModifier; import org.anddev.andengine.entity.modifier.PathModifier; import org.anddev.andengine.entity.modifier.PathModifier.IPathModifierListener; import org.anddev.andengine.entity.modifier.PathModifier.Path; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.background.RepeatingSpriteBackground; import org.anddev.andengine.entity.sprite.AnimatedSprite; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.atlas.bitmap.source.AssetBitmapTextureAtlasSource; import org.anddev.andengine.opengl.texture.region.TiledTextureRegion; import org.anddev.andengine.util.Debug; import org.anddev.andengine.util.modifier.ease.EaseSineInOut; import android.widget.Toast; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 11:54:51 - 03.04.2010 */ public class PathModifierExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; // =========================================================== // Fields // =========================================================== private Camera mCamera; private RepeatingSpriteBackground mGrassBackground; private BitmapTextureAtlas mBitmapTextureAtlas; private TiledTextureRegion mPlayerTextureRegion; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { Toast.makeText(this, "You move my sprite right round, right round...", Toast.LENGTH_LONG).show(); this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override public void onLoadResources() { this.mBitmapTextureAtlas = new BitmapTextureAtlas(128, 128, TextureOptions.DEFAULT); BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mPlayerTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "player.png", 0, 0, 3, 4); this.mGrassBackground = new RepeatingSpriteBackground(CAMERA_WIDTH, CAMERA_HEIGHT, this.mEngine.getTextureManager(), new AssetBitmapTextureAtlasSource(this, "background_grass.png")); this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { // this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); scene.setBackground(this.mGrassBackground); /* Create the face and add it to the scene. */ final AnimatedSprite player = new AnimatedSprite(10, 10, 48, 64, this.mPlayerTextureRegion); final Path path = new Path(5).to(10, 10).to(10, CAMERA_HEIGHT - 74).to(CAMERA_WIDTH - 58, CAMERA_HEIGHT - 74).to(CAMERA_WIDTH - 58, 10).to(10, 10); /* Add the proper animation when a waypoint of the path is passed. */ player.registerEntityModifier(new LoopEntityModifier(new PathModifier(30, path, null, new IPathModifierListener() { @Override public void onPathStarted(final PathModifier pPathModifier, final IEntity pEntity) { Debug.d("onPathStarted"); } @Override public void onPathWaypointStarted(final PathModifier pPathModifier, final IEntity pEntity, final int pWaypointIndex) { Debug.d("onPathWaypointStarted: " + pWaypointIndex); switch(pWaypointIndex) { case 0: player.animate(new long[]{200, 200, 200}, 6, 8, true); break; case 1: player.animate(new long[]{200, 200, 200}, 3, 5, true); break; case 2: player.animate(new long[]{200, 200, 200}, 0, 2, true); break; case 3: player.animate(new long[]{200, 200, 200}, 9, 11, true); break; } } @Override public void onPathWaypointFinished(final PathModifier pPathModifier, final IEntity pEntity, final int pWaypointIndex) { Debug.d("onPathWaypointFinished: " + pWaypointIndex); } @Override public void onPathFinished(final PathModifier pPathModifier, final IEntity pEntity) { Debug.d("onPathFinished"); } }, EaseSineInOut.getInstance()))); scene.attachChild(player); return scene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.Scene.IOnSceneTouchListener; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.sprite.AnimatedSprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.input.touch.TouchEvent; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TiledTextureRegion; import android.widget.Toast; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 12:14:22 - 30.06.2010 */ public class UpdateTextureExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 480; private static final int CAMERA_HEIGHT = 320; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mBitmapTextureAtlas; private TiledTextureRegion mFaceTextureRegion; private boolean mToggleBox = true; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { Toast.makeText(this, "Touch the screen to update (redraw) an existing BitmapTextureAtlas with every touch!", Toast.LENGTH_LONG).show(); this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override public void onLoadResources() { this.mBitmapTextureAtlas = new BitmapTextureAtlas(64, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA); BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "face_box_tiled.png", 0, 0, 2, 1); this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); /* Calculate the coordinates for the face, so its centered on the camera. */ final int x = (CAMERA_WIDTH - this.mFaceTextureRegion.getTileWidth()) / 2; final int y = (CAMERA_HEIGHT - this.mFaceTextureRegion.getTileHeight()) / 2; /* Create the face and add it to the scene. */ final AnimatedSprite face = new AnimatedSprite(x, y, this.mFaceTextureRegion); face.animate(100); scene.attachChild(face); scene.setOnSceneTouchListener(new IOnSceneTouchListener() { @Override public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) { if(pSceneTouchEvent.isActionDown()) { UpdateTextureExample.this.toggle(); } return true; } }); return scene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== private void toggle() { this.mBitmapTextureAtlas.clearTextureAtlasSources(); this.mToggleBox = !this.mToggleBox; BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, this.mToggleBox ? "face_box_tiled.png" : "face_circle_tiled.png", 0, 0, 2, 1); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.primitive.Rectangle; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.Scene.IOnSceneTouchListener; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.shape.Shape; import org.anddev.andengine.entity.sprite.AnimatedSprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.extension.physics.box2d.PhysicsConnector; import org.anddev.andengine.extension.physics.box2d.PhysicsFactory; import org.anddev.andengine.extension.physics.box2d.PhysicsWorld; import org.anddev.andengine.extension.physics.box2d.util.Vector2Pool; import org.anddev.andengine.input.touch.TouchEvent; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TiledTextureRegion; import org.anddev.andengine.sensor.accelerometer.AccelerometerData; import org.anddev.andengine.sensor.accelerometer.IAccelerometerListener; import org.anddev.andengine.util.Debug; import org.anddev.andengine.util.MathUtils; import android.hardware.SensorManager; import android.widget.Toast; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.Body; import com.badlogic.gdx.physics.box2d.BodyDef.BodyType; import com.badlogic.gdx.physics.box2d.FixtureDef; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 18:47:08 - 19.03.2010 */ public class BasePhysicsJointExample extends BaseExample implements IAccelerometerListener, IOnSceneTouchListener { // =========================================================== // Constants // =========================================================== protected static final int CAMERA_WIDTH = 720; protected static final int CAMERA_HEIGHT = 480; // =========================================================== // Fields // =========================================================== private BitmapTextureAtlas mBitmapTextureAtlas; private Scene mScene; protected TiledTextureRegion mBoxFaceTextureRegion; protected TiledTextureRegion mCircleFaceTextureRegion; protected PhysicsWorld mPhysicsWorld; private int mFaceCount = 0; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { Toast.makeText(this, "Touch the screen to add objects.", Toast.LENGTH_LONG).show(); final Camera camera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); final EngineOptions engineOptions = new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), camera); engineOptions.getTouchOptions().setRunOnUpdateThread(true); return new Engine(engineOptions); } @Override public void onLoadResources() { this.mBitmapTextureAtlas = new BitmapTextureAtlas(64, 64, TextureOptions.BILINEAR_PREMULTIPLYALPHA); BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mBoxFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "face_box_tiled.png", 0, 0, 2, 1); // 64x32 this.mCircleFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "face_circle_tiled.png", 0, 32, 2, 1); // 64x32 this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); this.mScene = new Scene(); this.mScene.setBackground(new ColorBackground(0, 0, 0)); this.mScene.setOnSceneTouchListener(this); this.mPhysicsWorld = new PhysicsWorld(new Vector2(0, SensorManager.GRAVITY_EARTH), false); final Shape ground = new Rectangle(0, CAMERA_HEIGHT - 2, CAMERA_WIDTH, 2); final Shape roof = new Rectangle(0, 0, CAMERA_WIDTH, 2); final Shape left = new Rectangle(0, 0, 2, CAMERA_HEIGHT); final Shape right = new Rectangle(CAMERA_WIDTH - 2, 0, 2, CAMERA_HEIGHT); final FixtureDef wallFixtureDef = PhysicsFactory.createFixtureDef(0, 0.5f, 0.5f); PhysicsFactory.createBoxBody(this.mPhysicsWorld, ground, BodyType.StaticBody, wallFixtureDef); PhysicsFactory.createBoxBody(this.mPhysicsWorld, roof, BodyType.StaticBody, wallFixtureDef); PhysicsFactory.createBoxBody(this.mPhysicsWorld, left, BodyType.StaticBody, wallFixtureDef); PhysicsFactory.createBoxBody(this.mPhysicsWorld, right, BodyType.StaticBody, wallFixtureDef); this.mScene.attachChild(ground); this.mScene.attachChild(roof); this.mScene.attachChild(left); this.mScene.attachChild(right); this.mScene.registerUpdateHandler(this.mPhysicsWorld); return this.mScene; } @Override public void onLoadComplete() { } @Override public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) { if(this.mPhysicsWorld != null) { if(pSceneTouchEvent.isActionDown()) { this.addFace(pSceneTouchEvent.getX(), pSceneTouchEvent.getY()); return true; } } return false; } @Override public void onAccelerometerChanged(final AccelerometerData pAccelerometerData) { final Vector2 gravity = Vector2Pool.obtain(pAccelerometerData.getX(), pAccelerometerData.getY()); this.mPhysicsWorld.setGravity(gravity); Vector2Pool.recycle(gravity); } @Override public void onResumeGame() { super.onResumeGame(); this.enableAccelerometerSensor(this); } @Override public void onPauseGame() { super.onPauseGame(); this.disableAccelerometerSensor(); } // =========================================================== // Methods // =========================================================== private void addFace(final float pX, final float pY) { this.mFaceCount++; Debug.d("Faces: " + this.mFaceCount); final AnimatedSprite face; final Body body; final FixtureDef objectFixtureDef = PhysicsFactory.createFixtureDef(1, 0.5f, 0.5f); if(this.mFaceCount % 2 == 0) { face = new AnimatedSprite(pX, pY, this.mCircleFaceTextureRegion); face.setScale(MathUtils.random(0.5f, 1.25f)); body = PhysicsFactory.createCircleBody(this.mPhysicsWorld, face, BodyType.DynamicBody, objectFixtureDef); } else { face = new AnimatedSprite(pX, pY, this.mBoxFaceTextureRegion); face.setScale(MathUtils.random(0.5f, 1.25f)); body = PhysicsFactory.createBoxBody(this.mPhysicsWorld, face, BodyType.DynamicBody, objectFixtureDef); } face.animate(200); this.mScene.attachChild(face); this.mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(face, body, true, true)); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import org.anddev.andengine.entity.primitive.Line; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.sprite.AnimatedSprite; import org.anddev.andengine.extension.physics.box2d.PhysicsConnector; import org.anddev.andengine.extension.physics.box2d.PhysicsFactory; import org.anddev.andengine.extension.physics.box2d.util.constants.PhysicsConstants; import android.widget.Toast; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.Body; import com.badlogic.gdx.physics.box2d.BodyDef.BodyType; import com.badlogic.gdx.physics.box2d.FixtureDef; import com.badlogic.gdx.physics.box2d.joints.RevoluteJointDef; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 18:47:08 - 19.03.2010 */ public class PhysicsRevoluteJointExample extends BasePhysicsJointExample { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Scene onLoadScene() { final Scene scene = super.onLoadScene(); this.initJoints(scene); Toast.makeText(this, "In this example, the revolute joints have their motor enabled.", Toast.LENGTH_LONG).show(); return scene; } // =========================================================== // Methods // =========================================================== private void initJoints(final Scene pScene) { final int centerX = CAMERA_WIDTH / 2; final int centerY = CAMERA_HEIGHT / 2; final int spriteWidth = this.mBoxFaceTextureRegion.getTileWidth(); final int spriteHeight = this.mBoxFaceTextureRegion.getTileHeight(); final FixtureDef objectFixtureDef = PhysicsFactory.createFixtureDef(10, 0.2f, 0.5f); for(int i = 0; i < 3; i++) { final float anchorFaceX = centerX - spriteWidth * 0.5f + 220 * (i - 1); final float anchorFaceY = centerY - spriteHeight * 0.5f; final AnimatedSprite anchorFace = new AnimatedSprite(anchorFaceX, anchorFaceY, this.mBoxFaceTextureRegion); final Body anchorBody = PhysicsFactory.createBoxBody(this.mPhysicsWorld, anchorFace, BodyType.StaticBody, objectFixtureDef); final AnimatedSprite movingFace = new AnimatedSprite(anchorFaceX, anchorFaceY + 90, this.mCircleFaceTextureRegion); final Body movingBody = PhysicsFactory.createCircleBody(this.mPhysicsWorld, movingFace, BodyType.DynamicBody, objectFixtureDef); anchorFace.animate(200); anchorFace.animate(200); final Line connectionLine = new Line(anchorFaceX + spriteWidth / 2, anchorFaceY + spriteHeight / 2, anchorFaceX + spriteWidth / 2, anchorFaceY + spriteHeight / 2); pScene.attachChild(connectionLine); pScene.attachChild(anchorFace); pScene.attachChild(movingFace); this.mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(anchorFace, anchorBody, true, true){ @Override public void onUpdate(final float pSecondsElapsed) { super.onUpdate(pSecondsElapsed); final Vector2 movingBodyWorldCenter = movingBody.getWorldCenter(); connectionLine.setPosition(connectionLine.getX1(), connectionLine.getY1(), movingBodyWorldCenter.x * PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT, movingBodyWorldCenter.y * PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT); } }); this.mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(movingFace, movingBody, true, true)); final RevoluteJointDef revoluteJointDef = new RevoluteJointDef(); revoluteJointDef.initialize(anchorBody, movingBody, anchorBody.getWorldCenter()); revoluteJointDef.enableMotor = true; revoluteJointDef.motorSpeed = 10; revoluteJointDef.maxMotorTorque = 200; this.mPhysicsWorld.createJoint(revoluteJointDef); } } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.sprite.AnimatedSprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TiledTextureRegion; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 11:54:51 - 03.04.2010 */ public class AnimatedSpritesExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 480; private static final int CAMERA_HEIGHT = 320; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mBitmapTextureAtlas; private TiledTextureRegion mSnapdragonTextureRegion; private TiledTextureRegion mHelicopterTextureRegion; private TiledTextureRegion mBananaTextureRegion; private TiledTextureRegion mFaceTextureRegion; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override public void onLoadResources() { this.mBitmapTextureAtlas = new BitmapTextureAtlas(512, 256, TextureOptions.BILINEAR); BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mSnapdragonTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "snapdragon_tiled.png", 0, 0, 4, 3); this.mHelicopterTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "helicopter_tiled.png", 400, 0, 2, 2); this.mBananaTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "banana_tiled.png", 0, 180, 4, 2); this.mFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "face_box_tiled.png", 132, 180, 2, 1); this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); /* Quickly twinkling face. */ final AnimatedSprite face = new AnimatedSprite(100, 50, this.mFaceTextureRegion); face.animate(100); scene.attachChild(face); /* Continuously flying helicopter. */ final AnimatedSprite helicopter = new AnimatedSprite(320, 50, this.mHelicopterTextureRegion); helicopter.animate(new long[] { 100, 100 }, 1, 2, true); scene.attachChild(helicopter); /* Snapdragon. */ final AnimatedSprite snapdragon = new AnimatedSprite(300, 200, this.mSnapdragonTextureRegion); snapdragon.animate(100); scene.attachChild(snapdragon); /* Funny banana. */ final AnimatedSprite banana = new AnimatedSprite(100, 220, this.mBananaTextureRegion); banana.animate(100); scene.attachChild(banana); return scene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import javax.microedition.khronos.opengles.GL10; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.particle.ParticleSystem; import org.anddev.andengine.entity.particle.emitter.PointParticleEmitter; import org.anddev.andengine.entity.particle.initializer.AccelerationInitializer; import org.anddev.andengine.entity.particle.initializer.ColorInitializer; import org.anddev.andengine.entity.particle.initializer.RotationInitializer; import org.anddev.andengine.entity.particle.initializer.VelocityInitializer; import org.anddev.andengine.entity.particle.modifier.AlphaModifier; import org.anddev.andengine.entity.particle.modifier.ColorModifier; import org.anddev.andengine.entity.particle.modifier.ExpireModifier; import org.anddev.andengine.entity.particle.modifier.ScaleModifier; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TextureRegion; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 11:54:51 - 03.04.2010 */ public class ParticleSystemCoolExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 480; private static final int CAMERA_HEIGHT = 320; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mBitmapTextureAtlas; private TextureRegion mParticleTextureRegion; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override public void onLoadResources() { this.mBitmapTextureAtlas = new BitmapTextureAtlas(32, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA); BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mParticleTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "particle_fire.png", 0, 0); this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); scene.setBackground(new ColorBackground(0.0f, 0.0f, 0.0f)); /* Left to right Particle System. */ { final ParticleSystem particleSystem = new ParticleSystem(new PointParticleEmitter(0, CAMERA_HEIGHT), 6, 10, 200, this.mParticleTextureRegion); particleSystem.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE); particleSystem.addParticleInitializer(new VelocityInitializer(15, 22, -60, -90)); particleSystem.addParticleInitializer(new AccelerationInitializer(5, 15)); particleSystem.addParticleInitializer(new RotationInitializer(0.0f, 360.0f)); particleSystem.addParticleInitializer(new ColorInitializer(1.0f, 0.0f, 0.0f)); particleSystem.addParticleModifier(new ScaleModifier(0.5f, 2.0f, 0, 5)); particleSystem.addParticleModifier(new ExpireModifier(11.5f)); particleSystem.addParticleModifier(new AlphaModifier(1.0f, 0.0f, 2.5f, 3.5f)); particleSystem.addParticleModifier(new AlphaModifier(0.0f, 1.0f, 3.5f, 4.5f)); particleSystem.addParticleModifier(new ColorModifier(1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 11.5f)); particleSystem.addParticleModifier(new AlphaModifier(1.0f, 0.0f, 4.5f, 11.5f)); scene.attachChild(particleSystem); } /* Right to left Particle System. */ { final ParticleSystem particleSystem = new ParticleSystem(new PointParticleEmitter(CAMERA_WIDTH - 32, CAMERA_HEIGHT), 8, 12, 200, this.mParticleTextureRegion); particleSystem.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE); particleSystem.addParticleInitializer(new VelocityInitializer(-15, -22, -60, -90)); particleSystem.addParticleInitializer(new AccelerationInitializer(-5, 15)); particleSystem.addParticleInitializer(new RotationInitializer(0.0f, 360.0f)); particleSystem.addParticleInitializer(new ColorInitializer(0.0f, 0.0f, 1.0f)); particleSystem.addParticleModifier(new ScaleModifier(0.5f, 2.0f, 0, 5)); particleSystem.addParticleModifier(new ExpireModifier(11.5f)); particleSystem.addParticleModifier(new AlphaModifier(1.0f, 0.0f, 2.5f, 3.5f)); particleSystem.addParticleModifier(new AlphaModifier(0.0f, 1.0f, 3.5f, 4.5f)); particleSystem.addParticleModifier(new ColorModifier(0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 11.5f)); particleSystem.addParticleModifier(new AlphaModifier(1.0f, 0.0f, 4.5f, 11.5f)); scene.attachChild(particleSystem); } return scene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.text.Text; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.opengl.font.Font; import org.anddev.andengine.opengl.font.StrokeFont; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import android.graphics.Color; import android.graphics.Typeface; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 22:49:43 - 26.07.2010 */ public class StrokeFontExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; private static final int FONT_SIZE = 48; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mFontTexture; private BitmapTextureAtlas mStrokeFontTexture; private BitmapTextureAtlas mStrokeOnlyFontTexture; private Font mFont; private StrokeFont mStrokeFont; private StrokeFont mStrokeOnlyFont; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override public void onLoadResources() { this.mFontTexture = new BitmapTextureAtlas(256, 256, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mStrokeFontTexture = new BitmapTextureAtlas(256, 256, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mStrokeOnlyFontTexture = new BitmapTextureAtlas(256, 256, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mFont = new Font(this.mFontTexture, Typeface.create(Typeface.DEFAULT, Typeface.BOLD), FONT_SIZE, true, Color.BLACK); this.mStrokeFont = new StrokeFont(this.mStrokeFontTexture, Typeface.create(Typeface.DEFAULT, Typeface.BOLD), FONT_SIZE, true, Color.BLACK, 2, Color.WHITE); this.mStrokeOnlyFont = new StrokeFont(this.mStrokeOnlyFontTexture, Typeface.create(Typeface.DEFAULT, Typeface.BOLD), FONT_SIZE, true, Color.BLACK, 2, Color.WHITE, true); this.mEngine.getTextureManager().loadTextures(this.mFontTexture, this.mStrokeFontTexture, this.mStrokeOnlyFontTexture); this.getFontManager().loadFonts(this.mFont, this.mStrokeFont, this.mStrokeOnlyFont); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); final Text textNormal = new Text(100, 100, this.mFont, "Just some normal Text."); final Text textStroke = new Text(100, 200, this.mStrokeFont, "Text with fill and stroke."); final Text textStrokeOnly = new Text(100, 300, this.mStrokeOnlyFont, "Text with stroke only."); scene.attachChild(textNormal); scene.attachChild(textStroke); scene.attachChild(textStrokeOnly); return scene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.primitive.Rectangle; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.Scene.IOnAreaTouchListener; import org.anddev.andengine.entity.scene.Scene.IOnSceneTouchListener; import org.anddev.andengine.entity.scene.Scene.ITouchArea; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.shape.Shape; import org.anddev.andengine.entity.sprite.AnimatedSprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.extension.physics.box2d.PhysicsConnector; import org.anddev.andengine.extension.physics.box2d.PhysicsFactory; import org.anddev.andengine.extension.physics.box2d.PhysicsWorld; import org.anddev.andengine.extension.physics.box2d.util.Vector2Pool; import org.anddev.andengine.input.touch.TouchEvent; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TiledTextureRegion; import org.anddev.andengine.sensor.accelerometer.AccelerometerData; import org.anddev.andengine.sensor.accelerometer.IAccelerometerListener; import android.hardware.SensorManager; import android.widget.Toast; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.Body; import com.badlogic.gdx.physics.box2d.BodyDef.BodyType; import com.badlogic.gdx.physics.box2d.FixtureDef; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 21:18:08 - 27.06.2010 */ public class PhysicsJumpExample extends BaseExample implements IAccelerometerListener, IOnSceneTouchListener, IOnAreaTouchListener { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 360; private static final int CAMERA_HEIGHT = 240; // =========================================================== // Fields // =========================================================== private BitmapTextureAtlas mBitmapTextureAtlas; private TiledTextureRegion mBoxFaceTextureRegion; private TiledTextureRegion mCircleFaceTextureRegion; private int mFaceCount = 0; private PhysicsWorld mPhysicsWorld; private float mGravityX; private float mGravityY; private Scene mScene; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { Toast.makeText(this, "Touch the screen to add objects. Touch an object to shoot it up into the air.", Toast.LENGTH_LONG).show(); final Camera camera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); final EngineOptions engineOptions = new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), camera); engineOptions.getTouchOptions().setRunOnUpdateThread(true); return new Engine(engineOptions); } @Override public void onLoadResources() { this.mBitmapTextureAtlas = new BitmapTextureAtlas(64, 64, TextureOptions.BILINEAR_PREMULTIPLYALPHA); BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mBoxFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "face_box_tiled.png", 0, 0, 2, 1); // 64x32 this.mCircleFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "face_circle_tiled.png", 0, 32, 2, 1); // 64x32 this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); this.mPhysicsWorld = new PhysicsWorld(new Vector2(0, SensorManager.GRAVITY_EARTH), false); this.mScene = new Scene(); this.mScene.setBackground(new ColorBackground(0, 0, 0)); this.mScene.setOnSceneTouchListener(this); final Shape ground = new Rectangle(0, CAMERA_HEIGHT - 2, CAMERA_WIDTH, 2); final Shape roof = new Rectangle(0, 0, CAMERA_WIDTH, 2); final Shape left = new Rectangle(0, 0, 2, CAMERA_HEIGHT); final Shape right = new Rectangle(CAMERA_WIDTH - 2, 0, 2, CAMERA_HEIGHT); final FixtureDef wallFixtureDef = PhysicsFactory.createFixtureDef(0, 0.5f, 0.5f); PhysicsFactory.createBoxBody(this.mPhysicsWorld, ground, BodyType.StaticBody, wallFixtureDef); PhysicsFactory.createBoxBody(this.mPhysicsWorld, roof, BodyType.StaticBody, wallFixtureDef); PhysicsFactory.createBoxBody(this.mPhysicsWorld, left, BodyType.StaticBody, wallFixtureDef); PhysicsFactory.createBoxBody(this.mPhysicsWorld, right, BodyType.StaticBody, wallFixtureDef); this.mScene.attachChild(ground); this.mScene.attachChild(roof); this.mScene.attachChild(left); this.mScene.attachChild(right); this.mScene.registerUpdateHandler(this.mPhysicsWorld); this.mScene.setOnAreaTouchListener(this); return this.mScene; } @Override public boolean onAreaTouched( final TouchEvent pSceneTouchEvent, final ITouchArea pTouchArea,final float pTouchAreaLocalX, final float pTouchAreaLocalY) { if(pSceneTouchEvent.isActionDown()) { final AnimatedSprite face = (AnimatedSprite) pTouchArea; this.jumpFace(face); return true; } return false; } @Override public void onLoadComplete() { } @Override public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) { if(this.mPhysicsWorld != null) { if(pSceneTouchEvent.isActionDown()) { this.addFace(pSceneTouchEvent.getX(), pSceneTouchEvent.getY()); return true; } } return false; } @Override public void onAccelerometerChanged(final AccelerometerData pAccelerometerData) { this.mGravityX = pAccelerometerData.getX(); this.mGravityY = pAccelerometerData.getY(); final Vector2 gravity = Vector2Pool.obtain(this.mGravityX, this.mGravityY); this.mPhysicsWorld.setGravity(gravity); Vector2Pool.recycle(gravity); } @Override public void onResumeGame() { super.onResumeGame(); this.enableAccelerometerSensor(this); } @Override public void onPauseGame() { super.onPauseGame(); this.disableAccelerometerSensor(); } // =========================================================== // Methods // =========================================================== private void addFace(final float pX, final float pY) { this.mFaceCount++; final AnimatedSprite face; final Body body; final FixtureDef objectFixtureDef = PhysicsFactory.createFixtureDef(1, 0.5f, 0.5f); if(this.mFaceCount % 2 == 1){ face = new AnimatedSprite(pX, pY, this.mBoxFaceTextureRegion); body = PhysicsFactory.createBoxBody(this.mPhysicsWorld, face, BodyType.DynamicBody, objectFixtureDef); } else { face = new AnimatedSprite(pX, pY, this.mCircleFaceTextureRegion); body = PhysicsFactory.createCircleBody(this.mPhysicsWorld, face, BodyType.DynamicBody, objectFixtureDef); } this.mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(face, body, true, true)); face.animate(new long[]{200,200}, 0, 1, true); face.setUserData(body); this.mScene.registerTouchArea(face); this.mScene.attachChild(face); } private void jumpFace(final AnimatedSprite face) { final Body faceBody = (Body)face.getUserData(); final Vector2 velocity = Vector2Pool.obtain(this.mGravityX * -50, this.mGravityY * -50); faceBody.setLinearVelocity(velocity); Vector2Pool.recycle(velocity); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import java.io.IOException; import java.io.InputStream; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.SmoothCamera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.Scene.IOnSceneTouchListener; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.sprite.Sprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.examples.adt.ZoomState; import org.anddev.andengine.input.touch.TouchEvent; import org.anddev.andengine.opengl.texture.ITexture; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.compressed.etc1.ETC1Texture; import org.anddev.andengine.opengl.texture.region.TextureRegion; import org.anddev.andengine.opengl.texture.region.TextureRegionFactory; import org.anddev.andengine.util.Debug; import android.widget.Toast; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 11:54:51 - 03.04.2010 */ public class ETC1TextureExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; // =========================================================== // Fields // =========================================================== private SmoothCamera mSmoothCamera; private ITexture mTexture; private TextureRegion mHouseTextureRegion; private ZoomState mZoomState = ZoomState.NONE; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { Toast.makeText(this, "Click the top half of the screen to zoom in or the bottom half to zoom out!", Toast.LENGTH_LONG); this.mSmoothCamera = new SmoothCamera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT, 0, 0, 0.1f) { @Override public void onUpdate(final float pSecondsElapsed) { switch (ETC1TextureExample.this.mZoomState) { case IN: this.setZoomFactor(this.getZoomFactor() + 0.1f * pSecondsElapsed); break; case OUT: this.setZoomFactor(this.getZoomFactor() - 0.1f * pSecondsElapsed); break; } super.onUpdate(pSecondsElapsed); } }; return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mSmoothCamera)); } @Override public void onLoadResources() { try { this.mTexture = new ETC1Texture(TextureOptions.BILINEAR) { @Override protected InputStream getInputStream() throws IOException { return ETC1TextureExample.this.getResources().openRawResource(R.raw.house_etc1); } }; this.mHouseTextureRegion = TextureRegionFactory.extractFromTexture(this.mTexture, 0, 0, 512, 512, true); this.mEngine.getTextureManager().loadTextures(this.mTexture); } catch (final Throwable e) { Debug.e(e); } } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); final int centerX = (CAMERA_WIDTH - this.mHouseTextureRegion.getWidth()) / 2; final int centerY = (CAMERA_HEIGHT - this.mHouseTextureRegion.getHeight()) / 2; scene.attachChild(new Sprite(centerX, centerY, this.mHouseTextureRegion)); scene.setOnSceneTouchListener(new IOnSceneTouchListener() { @Override public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) { if (pSceneTouchEvent.isActionDown() || pSceneTouchEvent.isActionMove()) { if(pSceneTouchEvent.getY() < CAMERA_HEIGHT / 2) { ETC1TextureExample.this.mZoomState = ZoomState.IN; } else { ETC1TextureExample.this.mZoomState = ZoomState.OUT; } } else { ETC1TextureExample.this.mZoomState = ZoomState.NONE; } return true; } }); return scene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.text.Text; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.opengl.font.Font; import org.anddev.andengine.opengl.font.FontFactory; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import android.graphics.Color; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 11:54:51 - 03.04.2010 */ public class CustomFontExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; private static final int FONT_SIZE = 48; // =========================================================== // Fields // =========================================================== private Camera mCamera; private Font mDroidFont; private Font mPlokFont; private Font mNeverwinterNightsFont; private Font mUnrealTournamenFont; private Font mKingdomOfHeartsFont; private BitmapTextureAtlas mDroidFontTexture; private BitmapTextureAtlas mPlokFontTexture; private BitmapTextureAtlas mNeverwinterNightsFontTexture; private BitmapTextureAtlas mUnrealTournamentFontTexture; private BitmapTextureAtlas mKingdomOfHeartsFontTexture; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override public void onLoadResources() { /* The custom fonts. */ this.mDroidFontTexture = new BitmapTextureAtlas(256, 256, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mKingdomOfHeartsFontTexture = new BitmapTextureAtlas(256, 256, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mNeverwinterNightsFontTexture = new BitmapTextureAtlas(256, 256, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mPlokFontTexture = new BitmapTextureAtlas(256, 256, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mUnrealTournamentFontTexture = new BitmapTextureAtlas(256, 256, TextureOptions.BILINEAR_PREMULTIPLYALPHA); FontFactory.setAssetBasePath("font/"); this.mDroidFont = FontFactory.createFromAsset(this.mDroidFontTexture, this, "Droid.ttf", FONT_SIZE, true, Color.BLACK); this.mKingdomOfHeartsFont = FontFactory.createFromAsset(this.mKingdomOfHeartsFontTexture, this, "KingdomOfHearts.ttf", FONT_SIZE + 20, true, Color.BLACK); this.mNeverwinterNightsFont = FontFactory.createFromAsset(this.mNeverwinterNightsFontTexture, this, "NeverwinterNights.ttf", FONT_SIZE, true, Color.BLACK); this.mPlokFont = FontFactory.createFromAsset(this.mPlokFontTexture, this, "Plok.ttf", FONT_SIZE, true, Color.BLACK); this.mUnrealTournamenFont = FontFactory.createFromAsset(this.mUnrealTournamentFontTexture, this, "UnrealTournament.ttf", FONT_SIZE, true, Color.BLACK); this.mEngine.getTextureManager().loadTextures(this.mDroidFontTexture, this.mKingdomOfHeartsFontTexture, this.mNeverwinterNightsFontTexture, this.mPlokFontTexture, this.mUnrealTournamentFontTexture); this.getFontManager().loadFonts(this.mDroidFont, this.mKingdomOfHeartsFont, this.mNeverwinterNightsFont, this.mPlokFont, this.mUnrealTournamenFont); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); scene.attachChild(new Text(230, 30, this.mDroidFont, "Droid Font")); scene.attachChild(new Text(160, 120, this.mKingdomOfHeartsFont, "Kingdom Of Hearts Font")); scene.attachChild(new Text(110, 210, this.mNeverwinterNightsFont, "Neverwinter Nights Font")); scene.attachChild(new Text(140, 300, this.mPlokFont, "Plok Font")); scene.attachChild(new Text(25, 390, this.mUnrealTournamenFont, "Unreal Tournament Font")); return scene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import javax.microedition.khronos.opengles.GL10; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.camera.hud.controls.AnalogOnScreenControl; import org.anddev.andengine.engine.camera.hud.controls.AnalogOnScreenControl.IAnalogOnScreenControlListener; import org.anddev.andengine.engine.camera.hud.controls.BaseOnScreenControl; import org.anddev.andengine.engine.handler.IUpdateHandler; import org.anddev.andengine.engine.handler.physics.PhysicsHandler; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.modifier.LoopEntityModifier; import org.anddev.andengine.entity.modifier.ParallelEntityModifier; import org.anddev.andengine.entity.modifier.RotationModifier; import org.anddev.andengine.entity.modifier.ScaleModifier; import org.anddev.andengine.entity.modifier.SequenceEntityModifier; import org.anddev.andengine.entity.primitive.Line; import org.anddev.andengine.entity.primitive.Rectangle; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.sprite.Sprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.extension.input.touch.controller.MultiTouch; import org.anddev.andengine.extension.input.touch.controller.MultiTouchController; import org.anddev.andengine.extension.input.touch.exception.MultiTouchException; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TextureRegion; import org.anddev.andengine.util.MathUtils; import android.widget.Toast; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 00:06:23 - 11.07.2010 */ public class CollisionDetectionExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 480; private static final int CAMERA_HEIGHT = 320; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mBitmapTextureAtlas; private TextureRegion mFaceTextureRegion; private BitmapTextureAtlas mOnScreenControlTexture; private TextureRegion mOnScreenControlBaseTextureRegion; private TextureRegion mOnScreenControlKnobTextureRegion; private boolean mPlaceOnScreenControlsAtDifferentVerticalLocations = false; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); final Engine engine = new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); try { if(MultiTouch.isSupported(this)) { engine.setTouchController(new MultiTouchController()); if(MultiTouch.isSupportedDistinct(this)) { Toast.makeText(this, "MultiTouch detected --> Both controls will work properly!", Toast.LENGTH_SHORT).show(); } else { this.mPlaceOnScreenControlsAtDifferentVerticalLocations = true; Toast.makeText(this, "MultiTouch detected, but your device has problems distinguishing between fingers.\n\nControls are placed at different vertical locations.", Toast.LENGTH_LONG).show(); } } else { Toast.makeText(this, "Sorry your device does NOT support MultiTouch!\n\n(Falling back to SingleTouch.)\n\nControls are placed at different vertical locations.", Toast.LENGTH_LONG).show(); } } catch (final MultiTouchException e) { Toast.makeText(this, "Sorry your Android Version does NOT support MultiTouch!\n\n(Falling back to SingleTouch.)\n\nControls are placed at different vertical locations.", Toast.LENGTH_LONG).show(); } return engine; } @Override public void onLoadResources() { BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mBitmapTextureAtlas = new BitmapTextureAtlas(32, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "face_box.png", 0, 0); this.mOnScreenControlTexture = new BitmapTextureAtlas(256, 128, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mOnScreenControlBaseTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mOnScreenControlTexture, this, "onscreen_control_base.png", 0, 0); this.mOnScreenControlKnobTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mOnScreenControlTexture, this, "onscreen_control_knob.png", 128, 0); this.mEngine.getTextureManager().loadTextures(this.mBitmapTextureAtlas, this.mOnScreenControlTexture); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); final int centerX = (CAMERA_WIDTH - this.mFaceTextureRegion.getWidth()) / 2; final int centerY = (CAMERA_HEIGHT - this.mFaceTextureRegion.getHeight()) / 2; final LoopEntityModifier entityModifier = new LoopEntityModifier(new ParallelEntityModifier(new RotationModifier(6, 0, 360), new SequenceEntityModifier(new ScaleModifier(3, 1, 1.5f), new ScaleModifier(3, 1.5f, 1)))); /* Create A spinning rectangle and a line. */ final Rectangle centerRectangle = new Rectangle(centerX - 50, centerY - 16, 32, 32); centerRectangle.registerEntityModifier(entityModifier); scene.attachChild(centerRectangle); final Line line = new Line(centerX + 50 - 16, centerY, centerX + 50 + 16, centerY); line.registerEntityModifier(entityModifier.deepCopy()); scene.attachChild(line); final Sprite face = new Sprite(centerX, centerY + 42, this.mFaceTextureRegion); final PhysicsHandler physicsHandler = new PhysicsHandler(face); face.registerUpdateHandler(physicsHandler); scene.attachChild(face); /* Velocity control (left). */ final int x1 = 0; final int y1 = CAMERA_HEIGHT - this.mOnScreenControlBaseTextureRegion.getHeight(); final AnalogOnScreenControl velocityOnScreenControl = new AnalogOnScreenControl(x1, y1, this.mCamera, this.mOnScreenControlBaseTextureRegion, this.mOnScreenControlKnobTextureRegion, 0.1f, new IAnalogOnScreenControlListener() { @Override public void onControlChange(final BaseOnScreenControl pBaseOnScreenControl, final float pValueX, final float pValueY) { physicsHandler.setVelocity(pValueX * 100, pValueY * 100); } @Override public void onControlClick(final AnalogOnScreenControl pAnalogOnScreenControl) { /* Nothing. */ } }); velocityOnScreenControl.getControlBase().setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); velocityOnScreenControl.getControlBase().setAlpha(0.5f); scene.setChildScene(velocityOnScreenControl); /* Rotation control (right). */ final int y2 = (this.mPlaceOnScreenControlsAtDifferentVerticalLocations) ? 0 : y1; final int x2 = CAMERA_WIDTH - this.mOnScreenControlBaseTextureRegion.getWidth(); final AnalogOnScreenControl rotationOnScreenControl = new AnalogOnScreenControl(x2, y2, this.mCamera, this.mOnScreenControlBaseTextureRegion, this.mOnScreenControlKnobTextureRegion, 0.1f, new IAnalogOnScreenControlListener() { @Override public void onControlChange(final BaseOnScreenControl pBaseOnScreenControl, final float pValueX, final float pValueY) { if(pValueX == x1 && pValueY == x1) { face.setRotation(x1); } else { face.setRotation(MathUtils.radToDeg((float)Math.atan2(pValueX, -pValueY))); } } @Override public void onControlClick(final AnalogOnScreenControl pAnalogOnScreenControl) { /* Nothing. */ } }); rotationOnScreenControl.getControlBase().setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); rotationOnScreenControl.getControlBase().setAlpha(0.5f); velocityOnScreenControl.setChildScene(rotationOnScreenControl); /* The actual collision-checking. */ scene.registerUpdateHandler(new IUpdateHandler() { @Override public void reset() { } @Override public void onUpdate(final float pSecondsElapsed) { if(centerRectangle.collidesWith(face)) { centerRectangle.setColor(1, 0, 0); } else { centerRectangle.setColor(0, 1, 0); } if(line.collidesWith(face)){ line.setColor(1, 0, 0); } else { line.setColor(0, 1, 0); } if(!mCamera.isRectangularShapeVisible(face)) { centerRectangle.setColor(1, 0, 1); } } }); return scene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import java.io.IOException; import org.anddev.andengine.audio.music.Music; import org.anddev.andengine.audio.music.MusicFactory; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.Scene.IOnAreaTouchListener; import org.anddev.andengine.entity.scene.Scene.ITouchArea; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.sprite.Sprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.input.touch.TouchEvent; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TextureRegion; import org.anddev.andengine.util.Debug; import android.widget.Toast; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 15:51:47 - 13.06.2010 */ public class MusicExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; // =========================================================== // Fields // =========================================================== private BitmapTextureAtlas mBitmapTextureAtlas; private TextureRegion mNotesTextureRegion; private Music mMusic; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { Toast.makeText(this, "Touch the notes to hear some Music.", Toast.LENGTH_LONG).show(); final Camera camera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), camera).setNeedsMusic(true)); } @Override public void onLoadResources() { this.mBitmapTextureAtlas = new BitmapTextureAtlas(128, 128, TextureOptions.BILINEAR_PREMULTIPLYALPHA); BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mNotesTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "notes.png", 0, 0); MusicFactory.setAssetBasePath("mfx/"); try { this.mMusic = MusicFactory.createMusicFromAsset(this.mEngine.getMusicManager(), this, "wagner_the_ride_of_the_valkyries.ogg"); this.mMusic.setLooping(true); } catch (final IOException e) { Debug.e(e); } this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); final int x = (CAMERA_WIDTH - this.mNotesTextureRegion.getWidth()) / 2; final int y = (CAMERA_HEIGHT - this.mNotesTextureRegion.getHeight()) / 2; final Sprite notes = new Sprite(x, y, this.mNotesTextureRegion); scene.attachChild(notes); scene.registerTouchArea(notes); scene.setOnAreaTouchListener(new IOnAreaTouchListener() { @Override public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final ITouchArea pTouchArea, final float pTouchAreaLocalX, final float pTouchAreaLocalY) { if(pSceneTouchEvent.isActionDown()) { if(MusicExample.this.mMusic.isPlaying()) { MusicExample.this.mMusic.pause(); } else { MusicExample.this.mMusic.play(); } } return true; } }); return scene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import javax.microedition.khronos.opengles.GL10; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.camera.hud.controls.AnalogOnScreenControl; import org.anddev.andengine.engine.camera.hud.controls.AnalogOnScreenControl.IAnalogOnScreenControlListener; import org.anddev.andengine.engine.camera.hud.controls.BaseOnScreenControl; import org.anddev.andengine.engine.handler.physics.PhysicsHandler; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.sprite.Sprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.extension.input.touch.controller.MultiTouch; import org.anddev.andengine.extension.input.touch.controller.MultiTouchController; import org.anddev.andengine.extension.input.touch.exception.MultiTouchException; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TextureRegion; import org.anddev.andengine.util.MathUtils; import android.widget.Toast; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 00:06:23 - 11.07.2010 */ public class AnalogOnScreenControlsExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 480; private static final int CAMERA_HEIGHT = 320; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mBitmapTextureAtlas; private TextureRegion mFaceTextureRegion; private BitmapTextureAtlas mOnScreenControlTexture; private TextureRegion mOnScreenControlBaseTextureRegion; private TextureRegion mOnScreenControlKnobTextureRegion; private boolean mPlaceOnScreenControlsAtDifferentVerticalLocations = false; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); final Engine engine = new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); try { if(MultiTouch.isSupported(this)) { engine.setTouchController(new MultiTouchController()); if(MultiTouch.isSupportedDistinct(this)) { Toast.makeText(this, "MultiTouch detected --> Both controls will work properly!", Toast.LENGTH_LONG).show(); } else { this.mPlaceOnScreenControlsAtDifferentVerticalLocations = true; Toast.makeText(this, "MultiTouch detected, but your device has problems distinguishing between fingers.\n\nControls are placed at different vertical locations.", Toast.LENGTH_LONG).show(); } } else { Toast.makeText(this, "Sorry your device does NOT support MultiTouch!\n\n(Falling back to SingleTouch.)\n\nControls are placed at different vertical locations.", Toast.LENGTH_LONG).show(); } } catch (final MultiTouchException e) { Toast.makeText(this, "Sorry your Android Version does NOT support MultiTouch!\n\n(Falling back to SingleTouch.)\n\nControls are placed at different vertical locations.", Toast.LENGTH_LONG).show(); } return engine; } @Override public void onLoadResources() { BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mBitmapTextureAtlas = new BitmapTextureAtlas(32, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "face_box.png", 0, 0); this.mOnScreenControlTexture = new BitmapTextureAtlas(256, 128, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mOnScreenControlBaseTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mOnScreenControlTexture, this, "onscreen_control_base.png", 0, 0); this.mOnScreenControlKnobTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mOnScreenControlTexture, this, "onscreen_control_knob.png", 128, 0); this.mEngine.getTextureManager().loadTextures(this.mBitmapTextureAtlas, this.mOnScreenControlTexture); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); final int centerX = (CAMERA_WIDTH - this.mFaceTextureRegion.getWidth()) / 2; final int centerY = (CAMERA_HEIGHT - this.mFaceTextureRegion.getHeight()) / 2; final Sprite face = new Sprite(centerX, centerY, this.mFaceTextureRegion); final PhysicsHandler physicsHandler = new PhysicsHandler(face); face.registerUpdateHandler(physicsHandler); scene.attachChild(face); /* Velocity control (left). */ final int x1 = 0; final int y1 = CAMERA_HEIGHT - this.mOnScreenControlBaseTextureRegion.getHeight(); final AnalogOnScreenControl velocityOnScreenControl = new AnalogOnScreenControl(x1, y1, this.mCamera, this.mOnScreenControlBaseTextureRegion, this.mOnScreenControlKnobTextureRegion, 0.1f, new IAnalogOnScreenControlListener() { @Override public void onControlChange(final BaseOnScreenControl pBaseOnScreenControl, final float pValueX, final float pValueY) { physicsHandler.setVelocity(pValueX * 100, pValueY * 100); } @Override public void onControlClick(final AnalogOnScreenControl pAnalogOnScreenControl) { /* Nothing. */ } }); velocityOnScreenControl.getControlBase().setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); velocityOnScreenControl.getControlBase().setAlpha(0.5f); scene.setChildScene(velocityOnScreenControl); /* Rotation control (right). */ final int y2 = (this.mPlaceOnScreenControlsAtDifferentVerticalLocations) ? 0 : y1; final int x2 = CAMERA_WIDTH - this.mOnScreenControlBaseTextureRegion.getWidth(); final AnalogOnScreenControl rotationOnScreenControl = new AnalogOnScreenControl(x2, y2, this.mCamera, this.mOnScreenControlBaseTextureRegion, this.mOnScreenControlKnobTextureRegion, 0.1f, new IAnalogOnScreenControlListener() { @Override public void onControlChange(final BaseOnScreenControl pBaseOnScreenControl, final float pValueX, final float pValueY) { if(pValueX == x1 && pValueY == x1) { face.setRotation(x1); } else { face.setRotation(MathUtils.radToDeg((float)Math.atan2(pValueX, -pValueY))); } } @Override public void onControlClick(final AnalogOnScreenControl pAnalogOnScreenControl) { /* Nothing. */ } }); rotationOnScreenControl.getControlBase().setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); rotationOnScreenControl.getControlBase().setAlpha(0.5f); velocityOnScreenControl.setChildScene(rotationOnScreenControl); return scene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package com.ams.io; import java.lang.ref.ReferenceQueue; import java.lang.ref.WeakReference; import java.nio.ByteBuffer; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.concurrent.ConcurrentLinkedQueue; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class BufferAllocator implements IBufferAllocator { final private Logger logger = LoggerFactory .getLogger(BufferAllocator.class); private ByteBuffer byteBuffer = null; private int chunkSize = 2 * 1024 * 1024; // 2M private int poolSize = 64 * 1024 * 1024; // 64M private ConcurrentLinkedQueue<ByteBuffer> chunkPool = new ConcurrentLinkedQueue<ByteBuffer>(); public void init() { byteBuffer = null; for (int i = 0; i < poolSize / chunkSize; i++) { ByteBuffer buf = allocateBuffer(chunkSize); chunkPool.offer(buf); } ByteBufferCollector collector = new ByteBufferCollector(); collector.start(); } private ByteBuffer allocateBuffer(int size) { return ByteBuffer.allocateDirect(size); } private ByteBuffer newBuffer(int size) { ByteBuffer chunk = null; if (size > chunkSize) { chunk = allocateBuffer(size); logger.debug("allocate direct buffer:{}", size); } else { chunk = chunkPool.poll(); if (chunk == null) { chunk = allocateBuffer(chunkSize); logger.debug("allocate direct buffer:{}", chunkSize); } } ByteBuffer chunkHolder = chunk.duplicate(); referenceList.add(new ChunkReference(chunkHolder, chunk)); return chunkHolder; } private class ChunkReference extends WeakReference<ByteBuffer> { private ByteBuffer chunk; public ChunkReference(ByteBuffer referent, ByteBuffer chunk) { super(referent, chunkReferenceQueue); this.chunk = chunk; } public ByteBuffer getChunk() { return chunk; } }; private static ReferenceQueue<ByteBuffer> chunkReferenceQueue = new ReferenceQueue<ByteBuffer>(); private static List<ChunkReference> referenceList = Collections .synchronizedList(new LinkedList<ChunkReference>()); private class ByteBufferCollector extends Thread { private static final int COLLECT_INTERVAL_MS = 1000; private void recycle(ByteBuffer buf) { buf.clear(); chunkPool.offer(buf); } private void collect() { ChunkReference ref; int n = 0; while ((ref = (ChunkReference) chunkReferenceQueue.poll()) != null) { ByteBuffer chunk = ref.getChunk(); recycle(chunk); referenceList.remove(ref); n++; } if (n > 0) { logger.debug("collected {} chunk buffers", n); } } public ByteBufferCollector() { super(); try { setDaemon(true); } catch (Exception e) { } } public void run() { try { while (!Thread.interrupted()) { sleep(COLLECT_INTERVAL_MS); collect(); } } catch (InterruptedException e) { interrupt(); } } } public synchronized ByteBuffer allocate(int size) { if (byteBuffer == null || byteBuffer.capacity() - byteBuffer.limit() < size) { byteBuffer = newBuffer(size); } byteBuffer.limit(byteBuffer.position() + size); ByteBuffer slice = byteBuffer.slice(); byteBuffer.position(byteBuffer.limit()); return slice; } public void setPoolSize(int poolSize) { this.poolSize = poolSize; } public void setChunkSize(int chunkSize) { this.chunkSize = chunkSize; } }
Java
package com.ams.io; import java.io.File; import java.io.IOException; import java.io.RandomAccessFile; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; public class RandomAccessFileWriter implements IBufferWriter { private RandomAccessFile file; private FileChannel channel = null; private RandomAccessFile openFile(String fileName) throws IOException { RandomAccessFile raFile = null; try { raFile = new RandomAccessFile(new File(fileName), "rw"); } catch (Exception e) { if (raFile != null) { raFile.close(); throw new IOException("Corrupted File '" + fileName + "'"); } throw new IOException("File not found '" + fileName + "'"); } return raFile; } public RandomAccessFileWriter(String fileName, boolean append) throws IOException { this.file = openFile(fileName); if (append) { this.file.seek(this.file.length()); } this.channel = file.getChannel(); } public void write(ByteBuffer[] data) throws IOException { channel.write(data); } public void close() throws IOException { file.close(); } public void write(byte[] data, int offset, int len) throws IOException { ByteBuffer buf = BufferFactory.allocate(len); buf.put(data, offset, len); buf.flip(); channel.write(buf); } }
Java
package com.ams.io; import java.io.IOException; import java.io.OutputStream; import java.nio.ByteBuffer; import com.ams.util.Utils; public class BufferOutputStream extends OutputStream { protected static final int WRITE_BUFFER_SIZE = 512; protected ByteBuffer writeBuffer = null; protected IBufferWriter writer = null; public BufferOutputStream(IBufferWriter writer) { this.writer = writer; } public synchronized void flush() throws IOException { if (writeBuffer != null) { writeBuffer.flip(); writer.write(new ByteBuffer[] { writeBuffer }); writeBuffer = null; } } public synchronized void write(byte[] data, int offset, int len) throws IOException { while (true) { if (writeBuffer == null) { int size = Math.max(len, WRITE_BUFFER_SIZE); writeBuffer = BufferFactory.allocate(size); } if (writeBuffer.remaining() >= len) { writeBuffer.put(data, offset, len); break; } flush(); } } public void write(byte[] data) throws IOException { write(data, 0, data.length); } public void write(int data) throws IOException { byte[] b = new byte[1]; b[0] = (byte) (data & 0xFF); write(b, 0, 1); } public void writeByte(int v) throws IOException { byte[] b = new byte[1]; b[0] = (byte) (v & 0xFF); write(b, 0, 1); } public void write16Bit(int v) throws IOException { write(Utils.to16Bit(v)); } public void write24Bit(int v) throws IOException { write(Utils.to24Bit(v)); // 24bit } public void write32Bit(long v) throws IOException { write(Utils.to32Bit(v)); // 32bit } public void write16BitLittleEndian(int v) throws IOException { // 16bit write, LITTLE-ENDIAN write(Utils.to16BitLittleEndian(v)); } public void write24BitLittleEndian(int v) throws IOException { write(Utils.to24BitLittleEndian(v)); // 24bit } public void write32BitLittleEndian(long v) throws IOException { // 32bit write, LITTLE-ENDIAN write(Utils.to32BitLittleEndian(v)); } public void writeByteBuffer(BufferList data) throws IOException { writeByteBuffer(data.getBuffers()); } public void writeByteBuffer(ByteBuffer[] data) throws IOException { flush(); writer.write(data); } }
Java
package com.ams.io; import java.io.EOFException; import java.io.File; import java.io.IOException; import java.io.RandomAccessFile; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.util.ArrayList; import com.ams.util.BufferUtils; public class RandomAccessFileReader implements IBufferReader { private static int BUFFER_SIZE = 8 * 1024; private RandomAccessFile file; private FileChannel channel = null; private ByteBuffer buffer = null; private long position = 0; private boolean eof = false; private RandomAccessFile openFile(String fileName) throws IOException { RandomAccessFile raFile = null; try { raFile = new RandomAccessFile(new File(fileName), "r"); } catch (Exception e) { if (raFile != null) { raFile.close(); throw new IOException("Corrupted File '" + fileName + "'"); } throw new IOException("File not found '" + fileName + "'"); } return raFile; } public RandomAccessFileReader(String fileName, long startPosition) throws IOException { this.file = openFile(fileName); this.channel = file.getChannel(); file.seek(startPosition); position = startPosition; } public int readByte() throws IOException { byte[] one = new byte[1]; // read 1 byte int amount = read(one, 0, 1); // return EOF / the byte return (amount < 0) ? -1 : one[0] & 0xff; } public synchronized int read(byte[] data, int offset, int size) throws IOException { // throw an exception if eof if (eof) { throw new EOFException("stream is eof"); } int amount = 0; int length = size; while (length > 0) { // read a buffer if (buffer != null && buffer.hasRemaining()) { int remain = buffer.remaining(); if (length >= remain) { buffer.get(data, offset, remain); buffer = null; length -= remain; position += remain; offset += remain; amount += remain; } else { buffer.get(data, offset, length); position += length; offset += length; amount += length; length = 0; } } else { this.buffer = BufferFactory.allocate(BUFFER_SIZE); int len = channel.read(buffer); if (len < 0) { eof = true; this.buffer = null; throw new EOFException("stream is eof"); } buffer.flip(); } } // end while return amount; } public synchronized ByteBuffer[] read(int size) throws IOException { // throw an exception if eof if (eof) { throw new EOFException("stream is eof"); } ArrayList<ByteBuffer> list = new ArrayList<ByteBuffer>(); int length = size; while (length > 0) { // read a buffer if (buffer != null && buffer.hasRemaining()) { int remain = buffer.remaining(); if (length >= remain) { list.add(buffer); buffer = null; length -= remain; position += remain; } else { ByteBuffer slice = BufferUtils.trim(buffer, length); list.add(slice); position += length; length = 0; } } else { this.buffer = BufferFactory.allocate(BUFFER_SIZE); int len = channel.read(buffer); if (len < 0) { eof = true; this.buffer = null; throw new EOFException("stream is eof"); } buffer.flip(); } } // end while return list.toArray(new ByteBuffer[list.size()]); } public synchronized void seek(long startPosition) throws IOException { if (this.buffer != null) { int bufferPosition = buffer.position(); if (startPosition >= position - bufferPosition && startPosition < position + buffer.remaining()) { buffer.position((int) (startPosition - position + bufferPosition)); position = startPosition; return; } } position = startPosition; file.seek(position); this.buffer = null; this.eof = false; } public void skip(long bytes) throws IOException { seek(position + bytes); } public boolean isEof() { return eof; } public void close() throws IOException { file.close(); } public long getPosition() { return position; } }
Java
package com.ams.io; import java.io.IOException; import java.nio.ByteBuffer; public interface IBufferWriter { public void write(ByteBuffer[] data) throws IOException; }
Java
package com.ams.io; import java.io.IOException; import java.nio.ByteBuffer; public interface IBufferReader { public ByteBuffer[] read(int size) throws IOException; }
Java
package com.ams.io; import java.nio.ByteBuffer; public final class BufferFactory { private static IBufferAllocator allocator = null; public static ByteBuffer allocate(int size) { if (allocator == null) { return ByteBuffer.allocateDirect(size); } return allocator.allocate(size); } public static void setAllocator(IBufferAllocator alloc) { allocator = alloc; } }
Java
package com.ams.io; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import com.ams.util.BufferUtils; public class BufferList implements IBufferReader, IBufferWriter { private LinkedList<ByteBuffer> bufferList; public BufferList() { this.bufferList = new LinkedList<ByteBuffer>(); } public BufferList(ByteBuffer[] buffers) { if (buffers == null) throw new NullPointerException(); this.bufferList = new LinkedList<ByteBuffer>(Arrays.asList(buffers)); } public BufferList(List<ByteBuffer> buffers) { if (buffers == null) throw new NullPointerException(); this.bufferList = new LinkedList<ByteBuffer>(buffers); } public boolean hasRemaining() { boolean hasRemaining = false; for (ByteBuffer buf : bufferList) { if (buf.hasRemaining()) { hasRemaining = true; break; } } return hasRemaining; } public int remaining() { int remaining = 0; for (ByteBuffer buf : bufferList) { remaining += buf.remaining(); } return remaining; } public ByteBuffer[] getBuffers() { return bufferList.toArray(new ByteBuffer[bufferList.size()]); } public BufferList duplicate() { List<ByteBuffer> dupList = new ArrayList<ByteBuffer>(); for (ByteBuffer buf : bufferList) { dupList.add(buf.duplicate()); } return new BufferList(dupList); } public byte get(int index) { if (index < 0) { throw new IndexOutOfBoundsException(); } int remain = 0; for (ByteBuffer buf : bufferList) { remain += buf.remaining(); if (index < remain) { int pos = buf.position() + index; return buf.get(pos); } index -= remain; } throw new IndexOutOfBoundsException(); } public void put(byte[] data) { if (data == null) return; ByteBuffer buf = BufferFactory.allocate(data.length); buf.put(data); buf.flip(); bufferList.add(buf); } public ByteBuffer[] read(int size) { if (bufferList.isEmpty()) return null; List<ByteBuffer> list = new ArrayList<ByteBuffer>(); int length = size; while (length > 0 && !bufferList.isEmpty()) { // read a buffer ByteBuffer buffer = bufferList.peek(); int remain = buffer.remaining(); if (length >= remain) { list.add(buffer); bufferList.poll(); length -= remain; } else { ByteBuffer buf = BufferUtils.trim(buffer, length); list.add(buf); length = 0; } } return list.toArray(new ByteBuffer[list.size()]); } public void write(ByteBuffer[] data) { if (data == null) return; for (ByteBuffer buf : data) { bufferList.add(buf); } } }
Java
package com.ams.io.network.connection; import java.nio.ByteBuffer; public interface IFramer { public ByteBuffer[] parseFrame(ByteBuffer frame); public ByteBuffer[] buildFrame(ByteBuffer[] buf); }
Java
package com.ams.io.network.connection; import java.io.EOFException; import java.io.IOException; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.nio.ByteBuffer; import java.nio.channels.SelectableChannel; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.SocketChannel; import com.ams.io.BufferFactory; import com.ams.io.network.ChannelInterestOps; public class SocketConnector extends NetworkConnector { protected static final int MIN_READ_BUFFER_SIZE = 256; protected static final int MAX_READ_BUFFER_SIZE = 64 * 1024; protected static final int CONNECT_TIMEOUT = 30000; protected SocketChannel channel = null; protected ByteBuffer readBuffer = null; public SocketConnector(SocketChannel channel) { super(); this.channel = channel; } public static SocketConnector connect(InetSocketAddress remote) throws IOException { ConnectionListener listener = new ConnectionListener() { public void connectionEstablished(Connection conn) { synchronized (conn) { conn.notifyAll(); } } public void connectionClosed(Connection conn) { } }; SocketChannel channel = SocketChannel.open(); // channel.socket().setReuseAddress(true); SocketAddress bindPoint = new InetSocketAddress(0); // bind temp port; channel.socket().bind(bindPoint); channel.configureBlocking(false); SocketConnector connector = new SocketConnector(channel); connector.addListener(listener); getDispatcher().addChannelToRegister( new ChannelInterestOps(channel, SelectionKey.OP_CONNECT, connector)); long start = System.currentTimeMillis(); try { synchronized (connector) { channel.connect(remote); connector.wait(CONNECT_TIMEOUT); } } catch (Exception e) { throw new IOException("connect error"); } finally { connector.removeListener(listener); } long now = System.currentTimeMillis(); if (now - start >= CONNECT_TIMEOUT) { throw new IOException("connect time out"); } return connector; } public boolean finishConnect() throws IOException { if (channel.isConnectionPending()) { boolean success = channel.finishConnect(); if (success) { open(); } return success; } return false; } public void readChannel() throws IOException { if (readBuffer == null || readBuffer.remaining() < MIN_READ_BUFFER_SIZE) { readBuffer = BufferFactory.allocate(MAX_READ_BUFFER_SIZE); } int readBytes = channel.read(readBuffer); if (readBytes > 0) { ByteBuffer slicedBuffer = readBuffer.slice(); readBuffer.flip(); offerInBuffers(new ByteBuffer[] { readBuffer }); readBuffer = slicedBuffer; if (isClosed()) { open(); } } else if (readBytes == -1) { throw new EOFException("read channel eof"); } } public synchronized void writeToChannel(ByteBuffer[] data) throws IOException { Selector writeSelector = null; SelectionKey writeKey = null; int retry = 0; int writeTimeout = 1000; try { while (data != null) { long len = channel.write(data); if (len < 0) { throw new EOFException(); } boolean hasRemaining = false; for (ByteBuffer buf : data) { if (buf.hasRemaining()) { hasRemaining = true; break; } } if (!hasRemaining) { break; } if (len > 0) { retry = 0; } else { retry++; // Check if there are more to be written. if (writeSelector == null) { writeSelector = Selector.open(); try { writeKey = channel.register(writeSelector, SelectionKey.OP_WRITE); } catch (Exception e) { e.printStackTrace(); } } if (writeSelector.select(writeTimeout) == 0) { if (retry > 2) { throw new IOException("Client disconnected"); } } } } } finally { if (writeKey != null) { writeKey.cancel(); writeKey = null; } if (writeSelector != null) { writeSelector.selectNow(); } keepAlive(); } } public SocketAddress getLocalEndpoint() { return channel.socket().getLocalSocketAddress(); } public SocketAddress getRemoteEndpoint() { return channel.socket().getRemoteSocketAddress(); } public SelectableChannel getChannel() { return channel; } }
Java
package com.ams.io.network.connection; import java.io.IOException; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.atomic.AtomicLong; import com.ams.io.IBufferReader; import com.ams.io.IBufferWriter; import com.ams.io.BufferInputStream; import com.ams.io.BufferOutputStream; import com.ams.util.BufferUtils; public class Connection implements IBufferReader, IBufferWriter { protected static final int DEFAULT_TIMEOUT_MS = 30000; protected static final int MAX_QUEUE_SIZE = 1024; protected ConcurrentLinkedQueue<ByteBuffer> inBufferQueue = new ConcurrentLinkedQueue<ByteBuffer>(); protected ConcurrentLinkedQueue<ByteBuffer> outBufferQueue = new ConcurrentLinkedQueue<ByteBuffer>(); protected AtomicLong available = new AtomicLong(0); protected boolean closed = true; protected List<ConnectionListener> listeners = new ArrayList<ConnectionListener>(); protected BufferInputStream inStream; protected BufferOutputStream outStream; public Connection() { this.inStream = new BufferInputStream(this); this.outStream = new BufferOutputStream(this); } public synchronized void open() { if (!isClosed()) return; closed = false; for (ConnectionListener listener : listeners) { listener.connectionEstablished(this); } } public void close(boolean keepAlive) { close(); } public synchronized void close() { closed = true; try { flush(); } catch (IOException e) { } for (ConnectionListener listener : listeners) { listener.connectionClosed(this); } } public boolean isClosed() { return closed; } public boolean isWriteBlocking() { return outBufferQueue.size() > MAX_QUEUE_SIZE; } public long available() { return available.get(); } public void offerInBuffers(ByteBuffer buffers[]) { for (ByteBuffer buffer : buffers) { inBufferQueue.offer(buffer); available.addAndGet(buffer.remaining()); } synchronized (inBufferQueue) { inBufferQueue.notifyAll(); } } public ByteBuffer[] pollOutBuffers() { List<ByteBuffer> buffers = new ArrayList<ByteBuffer>(); ByteBuffer data; while ((data = outBufferQueue.poll()) != null) { buffers.add(data); } return buffers.toArray(new ByteBuffer[buffers.size()]); } public ByteBuffer[] read(int size) throws IOException { return read(size, DEFAULT_TIMEOUT_MS); } public ByteBuffer[] read(int size, int readTimeout) throws IOException { List<ByteBuffer> list = new ArrayList<ByteBuffer>(); int length = size; while (length > 0) { // read a buffer with blocking ByteBuffer buffer = inBufferQueue.peek(); if (buffer != null) { int remain = buffer.remaining(); if (length >= remain) { list.add(inBufferQueue.poll()); length -= remain; available.addAndGet(-remain); } else { ByteBuffer slice = BufferUtils.trim(buffer, length); list.add(slice); available.addAndGet(-length); length = 0; } } else { // wait new buffer append to queue // sleep for timeout ms long start = System.currentTimeMillis(); try { synchronized (inBufferQueue) { inBufferQueue.wait(readTimeout); } } catch (InterruptedException e) { throw new IOException("read interrupted"); } long now = System.currentTimeMillis(); if (now - start >= readTimeout) { throw new IOException("read time out"); } } } // end while return list.toArray(new ByteBuffer[list.size()]); } public void write(ByteBuffer[] data) throws IOException { if (data == null) { return; } for (ByteBuffer buf : data) { outBufferQueue.offer(buf); } } public void flush() throws IOException { if (outStream != null) { outStream.flush(); } } public BufferInputStream getInputStream() { return inStream; } public BufferOutputStream getOutputStream() { return outStream; } public void addListener(ConnectionListener listener) { if (!this.listeners.contains(listener)) { this.listeners.add(listener); } } public boolean removeListener(ConnectionListener listener) { return this.listeners.remove(listener); } }
Java
package com.ams.io.network.connection; import java.io.IOException; import java.net.SocketAddress; import java.nio.ByteBuffer; import java.nio.channels.*; import com.ams.io.network.Dispatcher; public abstract class NetworkConnector extends Connection { private static Dispatcher dispatcher = null; protected long keepAliveTime; public abstract boolean finishConnect() throws IOException; public abstract void readChannel() throws IOException; public abstract void writeToChannel(ByteBuffer[] data) throws IOException; public abstract SelectableChannel getChannel(); public abstract SocketAddress getLocalEndpoint(); public abstract SocketAddress getRemoteEndpoint(); public void keepAlive() { keepAliveTime = System.currentTimeMillis(); } public long getKeepAliveTime() { return keepAliveTime; } public synchronized void flush() throws IOException { if (outStream != null) { outStream.flush(); } ByteBuffer[] buf = pollOutBuffers(); if (buf.length > 0) { writeToChannel(buf); } } public void close(boolean keepAlive) { close(); try { if (!keepAlive) { Channel channel = getChannel(); if (channel != null) channel.close(); } } catch (IOException e) { } } protected static synchronized Dispatcher getDispatcher() throws IOException { if (dispatcher == null) { dispatcher = new Dispatcher(); Thread t = new Thread(dispatcher, "connector dispatcher"); t.setDaemon(true); t.start(); } return dispatcher; } }
Java
package com.ams.io.network.connection; public interface ConnectionListener { public void connectionEstablished(Connection conn); public void connectionClosed(Connection conn); }
Java
package com.ams.io.network.connection; public interface IFramerFactory { public IFramer create(); }
Java
package com.ams.io.network.connection; import java.io.IOException; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.nio.ByteBuffer; import java.nio.channels.DatagramChannel; import java.nio.channels.SelectableChannel; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.util.HashMap; import java.util.concurrent.TimeUnit; import com.ams.io.BufferFactory; import com.ams.io.network.ChannelInterestOps; public class DatagramConnector extends NetworkConnector { protected static final int PACKET_BUFFER_SIZE = 1500; protected static HashMap<SocketAddress, DatagramConnector> connectorMap = new HashMap<SocketAddress, DatagramConnector>();; protected DatagramChannel channel; protected SocketAddress remoteAddr = null; private int writeDelayTime = 10; // nano second protected IFramer framer = null; protected IFramerFactory framerFactory = null; public DatagramConnector(DatagramChannel channel, SocketAddress remoteAddr) { super(); this.channel = channel; this.remoteAddr = remoteAddr; } public static DatagramConnector connect(InetSocketAddress remoteAddr) throws IOException { DatagramChannel channel = DatagramChannel.open(); channel.configureBlocking(false); SocketAddress bindPoint = new InetSocketAddress(0); // bind temp port; channel.socket().bind(bindPoint); DatagramConnector connector = new DatagramConnector(channel, remoteAddr); getDispatcher() .addChannelToRegister( new ChannelInterestOps(channel, SelectionKey.OP_READ, connector)); connector.open(); return connector; } public boolean finishConnect() throws IOException { // nothing to do return true; } public void readChannel() throws IOException { ByteBuffer readBuffer = BufferFactory.allocate(PACKET_BUFFER_SIZE); SocketAddress remote = null; if ((remote = channel.receive(readBuffer)) != null) { readBuffer.flip(); DatagramConnector conn = connectorMap.get(remote); if (conn == null) { conn = new DatagramConnector(channel, remote); conn.setFramerFactory(framerFactory); for (ConnectionListener listener : listeners) { conn.addListener(listener); } connectorMap.put(remote, conn); } conn.readChannel(readBuffer); } } protected void readChannel(ByteBuffer readBuffer) throws IOException { ByteBuffer[] frames = null; if (framer != null) { frames = framer.parseFrame(readBuffer); if (frames == null) { return; } } else { frames = new ByteBuffer[] { readBuffer }; } offerInBuffers(frames); if (isClosed()) { open(); } keepAlive(); } public synchronized void writeToChannel(ByteBuffer[] buf) throws IOException { if (framer != null) { buf = framer.buildFrame(buf); } Selector writeSelector = null; SelectionKey writeKey = null; int writeTimeout = 1000; try { for (ByteBuffer frame : buf) { int retry = 0; while (channel.send(frame, remoteAddr) == 0) { retry++; writeDelayTime += 10; // Check if there are more to be written. if (writeSelector == null) { writeSelector = Selector.open(); try { writeKey = channel.register(writeSelector, SelectionKey.OP_WRITE); } catch (Exception e) { e.printStackTrace(); } } if (writeSelector.select(writeTimeout) == 0) { if (retry > 2) { throw new IOException("Client disconnected"); } } } try { TimeUnit.NANOSECONDS.sleep(writeDelayTime); } catch (InterruptedException e) { } } } finally { if (writeKey != null) { writeKey.cancel(); writeKey = null; } if (writeSelector != null) { writeSelector.selectNow(); } keepAlive(); } } public SocketAddress getLocalEndpoint() { return channel.socket().getLocalSocketAddress(); } public SocketAddress getRemoteEndpoint() { return channel.socket().getRemoteSocketAddress(); } public SelectableChannel getChannel() { return channel; } public void setFramerFactory(IFramerFactory framerFactory) { this.framerFactory = framerFactory; this.framer = framerFactory.create(); } }
Java
package com.ams.io.network; import java.nio.channels.SelectableChannel; import com.ams.io.network.connection.NetworkConnector; public class ChannelInterestOps { private SelectableChannel channel; private int interestOps; private NetworkConnector connector; public ChannelInterestOps(SelectableChannel channel, int interestOps, NetworkConnector connector) { this.channel = channel; this.interestOps = interestOps; this.connector = connector; } public SelectableChannel getChannel() { return channel; } public int getInterestOps() { return interestOps; } public NetworkConnector getConnector() { return connector; } }
Java
package com.ams.io.network; import java.io.IOException; import java.nio.channels.SelectableChannel; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.util.Iterator; import java.util.concurrent.ConcurrentLinkedQueue; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.ams.io.network.connection.NetworkConnector; public class Dispatcher extends NetworkHandler { final private Logger logger = LoggerFactory.getLogger(Dispatcher.class); private static final long SELECT_TIMEOUT = 2 * 1000; private long timeExpire = 2 * 60 * 1000; private long lastExpirationTime = 0; private Selector selector = null; private ConcurrentLinkedQueue<ChannelInterestOps> registerChannelQueue = null; public Dispatcher() throws IOException { selector = Selector.open(); registerChannelQueue = new ConcurrentLinkedQueue<ChannelInterestOps>(); } public void addChannelToRegister(ChannelInterestOps channelInterestOps) { registerChannelQueue.offer(channelInterestOps); selector.wakeup(); } public void run() { while (isRunning()) { // register a new channel registerNewChannel(); // do select doSelect(); // collect idle keys that will not be used expireIdleKeys(); } closeAllKeys(); } private void registerNewChannel() { ChannelInterestOps channelInterestOps = null; while ((channelInterestOps = registerChannelQueue.poll()) != null) { try { SelectableChannel channel = channelInterestOps.getChannel(); int interestOps = channelInterestOps.getInterestOps(); NetworkConnector connector = channelInterestOps.getConnector(); channel.configureBlocking(false); channel.register(selector, interestOps, connector); } catch (Exception e) { logger.debug("register channel error"); } } } private void doSelect() { int selectedKeys = 0; try { selectedKeys = selector.select(SELECT_TIMEOUT); } catch (Exception e) { logger.debug("select key error"); if (selector.isOpen()) { return; } } if (selectedKeys == 0) { return; } Iterator<SelectionKey> it = selector.selectedKeys().iterator(); while (it.hasNext()) { SelectionKey key = it.next(); it.remove(); if (!key.isValid()) { continue; } NetworkConnector connector = (NetworkConnector) key.attachment(); connector.keepAlive(); try { if (key.isConnectable()) { if (connector.finishConnect()) { key.interestOps(SelectionKey.OP_READ); } } if (key.isReadable()) { connector.readChannel(); } } catch (Exception e) { // logger.debug("read channel error"); key.cancel(); key.attach(null); connector.close(); } } } private void expireIdleKeys() { // check every timeExpire long now = System.currentTimeMillis(); long elapsedTime = now - lastExpirationTime; if (elapsedTime < timeExpire) { return; } lastExpirationTime = now; for (SelectionKey key : selector.keys()) { // Keep-alive expired NetworkConnector connector = (NetworkConnector) key.attachment(); if (connector != null) { long keepAliveTime = connector.getKeepAliveTime(); if (now - keepAliveTime > timeExpire) { logger.debug("close expired idle connector!"); key.cancel(); key.attach(null); connector.close(); } } } } private void closeAllKeys() { // close all keys for (SelectionKey key : selector.keys()) { // Keep-alive expired NetworkConnector connector = (NetworkConnector) key.attachment(); if (connector != null) { key.cancel(); key.attach(null); connector.close(); } } } public void setTimeExpire(long timeExpire) { this.timeExpire = timeExpire; } }
Java
package com.ams.io.network; import java.net.Socket; import java.net.SocketException; public final class SocketProperties { private int rxBufSize = 25188; private int txBufSize = 43800; private boolean tcpNoDelay = true; private boolean soKeepAlive = false; private boolean ooBInline = true; private boolean soReuseAddress = true; private boolean soLingerOn = true; private int soLingerTime = 25; private int soTimeout = 5000; private int soTrafficClass = 0x04 | 0x08 | 0x010; private int performanceConnectionTime = 1; private int performanceLatency = 0; private int performanceBandwidth = 1; public void setSocketProperties(Socket socket) throws SocketException { socket.setReceiveBufferSize(rxBufSize); socket.setSendBufferSize(txBufSize); socket.setOOBInline(ooBInline); socket.setKeepAlive(soKeepAlive); socket.setPerformancePreferences(performanceConnectionTime, performanceLatency, performanceBandwidth); socket.setReuseAddress(soReuseAddress); socket.setSoLinger(soLingerOn, soLingerTime); socket.setSoTimeout(soTimeout); socket.setTcpNoDelay(tcpNoDelay); socket.setTrafficClass(soTrafficClass); } }
Java
package com.ams.io.network; import java.io.IOException; import java.net.SocketAddress; import java.nio.channels.DatagramChannel; import java.nio.channels.SelectionKey; import com.ams.io.network.connection.ConnectionListener; import com.ams.io.network.connection.DatagramConnector; import com.ams.io.network.connection.IFramerFactory; public class DatagramAcceptor extends NetworkHandler { private SocketAddress listenEndpoint; private IFramerFactory framerFactory = null; private DatagramChannel datagramChannel; private Dispatcher dispatcher; private ConnectionListener listener; public DatagramAcceptor(SocketAddress listenEndpoint) { this.listenEndpoint = listenEndpoint; } private void openChannel() throws IOException { datagramChannel = DatagramChannel.open(); datagramChannel.socket().bind(listenEndpoint); datagramChannel.configureBlocking(false); DatagramConnector connector = new DatagramConnector(datagramChannel, null); if (framerFactory != null) { connector.setFramerFactory(framerFactory); } if (listener != null) { connector.addListener(listener); } dispatcher = new Dispatcher(); dispatcher.addChannelToRegister(new ChannelInterestOps(datagramChannel, SelectionKey.OP_READ, connector)); } private void closeChannel() { try { datagramChannel.close(); } catch (IOException e) { } } public SocketAddress getListenEndpoint() { return listenEndpoint; } public void start(String name) { try { openChannel(); } catch (IOException e) { } dispatcher.start("datagram dispatcher"); super.start("datagram acceptor"); } public void stop() { synchronized (this) { notifyAll(); } dispatcher.stop(); closeChannel(); super.stop(); } public void run() { try { synchronized (this) { wait(); } } catch (InterruptedException e) { } } public void setConnectionListener(ConnectionListener listener) { this.listener = listener; } public void setFramerFactory(IFramerFactory framerFactory) { this.framerFactory = framerFactory; } }
Java
package com.ams.io.network; public abstract class NetworkHandler implements Runnable { protected static int TIMEOUT = 5000; protected boolean running = true; protected Thread thread = null; public boolean isRunning() { return running; } public void start(String name) { running = true; this.thread = new Thread(this, name); this.thread.start(); } public void stop() { running = false; try { if (thread != null) { thread.interrupt(); thread.join(TIMEOUT); } } catch (InterruptedException e) { } } }
Java
package com.ams.io.network; import java.io.IOException; import java.net.SocketAddress; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.util.ArrayList; import java.util.Iterator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.ams.io.network.connection.ConnectionListener; import com.ams.io.network.connection.SocketConnector; public class SocketAcceptor extends NetworkHandler { final private Logger logger = LoggerFactory.getLogger(SocketAcceptor.class); private SocketAddress listenEndpoint; private SocketProperties socketProperties = null; private ServerSocketChannel serverChannel; private Selector selector; private int dispatcherSize = 1; private ArrayList<Dispatcher> dispatchers = new ArrayList<Dispatcher>(); private int nextDispatcher = 0; private ConnectionListener listener; public SocketAcceptor(SocketAddress host) throws IOException { listenEndpoint = host; createDispatcher(); } public SocketAcceptor(SocketAddress host, int dispatcherSize) throws IOException { listenEndpoint = host; this.dispatcherSize = dispatcherSize; createDispatcher(); } private void createDispatcher() throws IOException { for (int i = 0; i < dispatcherSize; i++) { Dispatcher dispatcher = new Dispatcher(); dispatchers.add(dispatcher); } } private void openChannel() throws IOException { serverChannel = ServerSocketChannel.open(); serverChannel.socket().bind(listenEndpoint); serverChannel.configureBlocking(false); selector = Selector.open(); serverChannel.register(selector, SelectionKey.OP_ACCEPT); } private void closeChannel() { try { serverChannel.close(); selector.close(); } catch (IOException e) { e.printStackTrace(); } } public void run() { int selectedKeys = 0; while (isRunning()) { try { selectedKeys = selector.select(); } catch (Exception e) { if (selector.isOpen()) { continue; } else { try { selector.selectNow(); selector = Selector.open(); serverChannel .register(selector, SelectionKey.OP_ACCEPT); } catch (Exception e1) { } } } if (selectedKeys == 0) { continue; } Iterator<SelectionKey> it = selector.selectedKeys().iterator(); while (it.hasNext()) { SelectionKey key = it.next(); it.remove(); if (!key.isValid()) { continue; } try { ServerSocketChannel serverChannel = (ServerSocketChannel) key .channel(); SocketChannel channel = serverChannel.accept(); //if (socketProperties != null) { // socketProperties.setSocketProperties(channel.socket()); //} if (dispatchers != null) { Dispatcher dispatcher = dispatchers .get(nextDispatcher++); SocketConnector connector = new SocketConnector(channel); if (listener != null) { connector.addListener(listener); } dispatcher.addChannelToRegister(new ChannelInterestOps( channel, SelectionKey.OP_READ, connector)); if (nextDispatcher >= dispatchers.size()) { nextDispatcher = 0; } } } catch (Exception e) { key.cancel(); } } } } public void setSocketProperties(SocketProperties socketProperties) { this.socketProperties = socketProperties; } public SocketAddress getListenEndpoint() { return this.listenEndpoint; } public void start(String name) { for (int i = 0; i < dispatchers.size(); i++) { Dispatcher dispatcher = dispatchers.get(i); dispatcher.start("socket dispatcher"); } try { openChannel(); } catch (IOException e) { e.printStackTrace(); } super.start("socket acceptor"); } public void stop() { for (int i = 0; i < dispatchers.size(); i++) { dispatchers.get(i).stop(); } closeChannel(); super.stop(); } public void setConnectionListener(ConnectionListener listener) { this.listener = listener; } }
Java
package com.ams.io; import java.nio.ByteBuffer; public interface IBufferAllocator { ByteBuffer allocate(int size); }
Java
package com.ams.io; import java.io.*; import java.nio.ByteBuffer; import com.ams.util.Utils; public class BufferInputStream extends InputStream { protected IBufferReader reader = null; protected byte[] line = new byte[4096]; public BufferInputStream(IBufferReader reader) { this.reader = reader; } public synchronized String readLine() throws IOException { // throw an exception if the stream is closed // closedCheck(); int index = 0; boolean marked = false; while (true) { int c = read(); if (c != -1) { byte ch = (byte) c; if (ch == '\r') { // expect next byte is CR marked = true; } else if (ch == '\n') { // have read a line, exit if (marked) index--; break; } else { marked = false; } line[index++] = ch; // need to expand the line buffer int capacity = line.length; if (index >= capacity) { capacity = capacity * 2 + 1; byte[] tmp = new byte[capacity]; System.arraycopy(line, 0, tmp, 0, index); line = tmp; } } else { if (marked) { index--; } break; } } // while return new String(line, 0, index, "UTF-8"); } public int read() throws IOException { byte[] one = new byte[1]; // read 1 byte int amount = read(one, 0, 1); // return EOF / the byte return (amount < 0) ? -1 : one[0] & 0xff; } public int read(byte data[], int offset, int length) throws IOException { // check parameters if (data == null) { throw new NullPointerException(); } else if ((offset < 0) || (offset + length > data.length) || (length < 0)) { // check indices throw new IndexOutOfBoundsException(); } ByteBuffer[] buffers = reader.read(length); if (buffers == null) return -1; int readBytes = 0; for (ByteBuffer buffer : buffers) { int size = buffer.remaining(); buffer.get(data, offset, size); offset += size; readBytes += size; } return readBytes; } public byte readByte() throws IOException { byte[] b = new byte[1]; read(b, 0, 1); return b[0]; } public int read16Bit() throws IOException { byte[] b = new byte[2]; read(b, 0, 2); // 16Bit read return Utils.from16Bit(b); } public int read24Bit() throws IOException { byte[] b = new byte[3]; read(b, 0, 3); // 24Bit read return Utils.from24Bit(b); } public long read32Bit() throws IOException { byte[] b = new byte[4]; read(b, 0, 4); // 32Bit read return Utils.from32Bit(b); } public int read16BitLittleEndian() throws IOException { byte[] b = new byte[2]; read(b, 0, 2); // 16 Bit read, LITTLE-ENDIAN return Utils.from16BitLittleEndian(b); } public int read24BitLittleEndian() throws IOException { byte[] b = new byte[3]; read(b, 0, 3); // 24 Bit read, LITTLE-ENDIAN return Utils.from24BitLittleEndian(b); } public long read32BitLittleEndian() throws IOException { byte[] b = new byte[4]; read(b, 0, 4); // 32 Bit read, LITTLE-ENDIAN return Utils.from32BitLittleEndian(b); } public ByteBuffer[] readByteBuffer(int size) throws IOException { return reader.read(size); } }
Java
package com.ams.protocol; import java.util.HashMap; public class Context { protected HashMap<String, String> attributes = new HashMap<String, String>(); public void setAttribute(String key, String value) { attributes.put(key, value); } public String getAttribute(String key) { return attributes.get(key); } }
Java
/** * */ package com.ams.protocol.http; public class Cookie { public String value = ""; public long expires = 0; public String domain = ""; public String path = ""; public boolean secure = false; public Cookie(String value, long expires, String domain, String path, boolean secure) { this.value = value; this.expires = expires; this.domain = domain; this.path = path; this.secure = secure; } }
Java
package com.ams.protocol.http; import java.io.*; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.ams.util.ObjectCache; import com.ams.util.BufferUtils; public class DefaultServlet { private final Logger logger = LoggerFactory.getLogger(DefaultServlet.class); private class MapedFile { public long size; public String contentType; public long lastModified; public ByteBuffer data; } private HttpContext context = null; private static ObjectCache<MapedFile> fileCache = new ObjectCache<MapedFile>(); public DefaultServlet(HttpContext context) { this.context = context; } public void service(HttpRequest req, HttpResponse res) throws IOException { String realPath = null; try { realPath = context.getRealPath(req.getLocation()); } catch (Exception e) { logger.warn(e.getMessage()); } File file = new File(realPath); if (!file.exists()) { res.setHttpResult(HTTP.HTTP_NOT_FOUND); res.flush(); } else if (!context.securize(file)) { res.setHttpResult(HTTP.HTTP_FORBIDDEN); res.flush(); } else { if (!writeFile(req.getLocation(), file, req, res)) { res.setHttpResult(HTTP.HTTP_INTERNAL_ERROR); res.flush(); } } } private boolean writeFile(String url, File file, HttpRequest req, HttpResponse res) { boolean result = true; try { MapedFile mapedFile = fileCache.get(url); if (mapedFile == null) { // open the resource stream mapedFile = new MapedFile(); mapedFile.lastModified = file.lastModified(); mapedFile.size = file.length(); mapedFile.contentType = context.getMimeType(file.getName()); FileInputStream fis = new FileInputStream(file); FileChannel fileChannel = fis.getChannel(); mapedFile.data = fileChannel.map(FileChannel.MapMode.READ_ONLY, 0, fileChannel.size()); fileChannel.close(); fis.close(); fileCache.put(url, mapedFile, 60); } res.setContentType(mapedFile.contentType); res.setLastModified(mapedFile.lastModified); res.setHttpResult(HTTP.HTTP_OK); // read all bytes and send them ByteBuffer data = mapedFile.data.slice(); // get range data int size = data.remaining(); int start = 0, end = size - 1; String range = req.getHeader("range"); if (range != null) { Matcher m = Pattern.compile("bytes=([0-9]*)-([0-9]*)").matcher( range); if (m.find()) { start = (m.group(1).length() == 0) ? 0 : Integer.parseInt(m .group(1)); end = (m.group(2).length() == 0) ? end : Integer.parseInt(m .group(2)); } res.setHeader( HTTP.HEADER_CONTENT_RANGE, "bytes " + Integer.toString(start) + "-" + Integer.toString(end) + "/" + Integer.toString(size)); res.setHttpResult(HTTP.HTTP_PARTIAL_CONTENT); data = BufferUtils.slice(data, start, end); } // using transfer encoing res.startChunkedTransfer(); res.flushChunk(data); res.endChunkedTransfer(); } catch (IOException e) { result = false; logger.warn(e.getMessage()); } return result; } }
Java
package com.ams.protocol.http; import java.io.File; import java.io.IOException; import com.ams.protocol.Context; public final class HttpContext extends Context { private final File contextRoot; public HttpContext(String root) { contextRoot = new File(root); } public String getMimeType(String file) { int index = file.lastIndexOf('.'); return (index++ > 0) ? MimeTypes.getContentType(file.substring(index)) : "unkown/unkown"; } public String getRealPath(String path) { return new File(contextRoot, path).getAbsolutePath(); } // security check public boolean securize(File file) throws IOException { if (file.getCanonicalPath().startsWith(contextRoot.getCanonicalPath())) { return true; } return false; } }
Java
/** * */ package com.ams.protocol.http; import java.io.File; public class HttpFileUpload { public final static int RESULT_OK = 0; public final static int RESULT_SIZE = 1; public final static int RESULT_PARTIAL = 3; public final static int RESULT_NOFILE = 4; public final static long MAXSIZE_FILE_UPLOAD = 10 * 1024 * 1024; // max 10M public String filename; public File tempFile; public int result; public HttpFileUpload(String filename, File tempFile, int result) { this.filename = filename; this.tempFile = tempFile; this.result = result; } }
Java
package com.ams.protocol.http; public final class HTTP { /** HTTP method */ public final static int HTTP_METHOD_GET = 0; public final static int HTTP_METHOD_POST = 1; public final static int HTTP_METHOD_HEAD = 2; public final static int HTTP_METHOD_PUT = 3; public final static int HTTP_METHOD_DELETE = 4; public final static int HTTP_METHOD_TRACE = 5; public final static int HTTP_METHOD_OPTIONS = 6; /** HTTP Status-Code */ public final static int HTTP_OK = 200; public final static int HTTP_PARTIAL_CONTENT = 206; public final static int HTTP_MOVED_PERMANENTLY = 301; public final static int HTTP_BAD_REQUEST = 400; public final static int HTTP_UNAUTHORIZED = 401; public final static int HTTP_FORBIDDEN = 403; public final static int HTTP_NOT_FOUND = 404; public final static int HTTP_BAD_METHOD = 405; public final static int HTTP_LENGTH_REQUIRED = 411; public final static int HTTP_INTERNAL_ERROR = 500; /** HTTP header definitions */ public static final String HEADER_ACCEPT = "Accept"; public static final String HEADER_ACCEPT_CHARSET = "Accept-Charset"; public static final String HEADER_ACCEPT_LANGUAGE = "Accept-Language"; public static final String HEADER_AGE = "Age"; public static final String HEADER_ALLOW = "Allow"; public static final String HEADER_AUTHORIZATION = "Authorization"; public static final String HEADER_CACHE_CONTROL = "Cache-Control"; public static final String HEADER_CONN_DIRECTIVE = "Connection"; public static final String HEADER_CONTENT_LANGUAGE = "Content-Language"; public static final String HEADER_CONTENT_LENGTH = "Content-Length"; public static final String HEADER_CONTENT_LOCATION = "Content-Location"; public static final String HEADER_CONTENT_MD5 = "Content-MD5"; public static final String HEADER_CONTENT_RANGE = "Content-Range"; public static final String HEADER_CONTENT_TYPE = "Content-Type"; public static final String HEADER_DATE = "Date"; public static final String HEADER_EXPECT = "Expect"; public static final String HEADER_EXPIRES = "Expires"; public static final String HEADER_FROM = "From"; public static final String HEADER_HOST = "Host"; public static final String HEADER_IF_MODIFIED_SINCE = "If-Modified-Since"; public static final String HEADER_IF_UNMODIFIED_SINCE = "If-Unmodified-Since"; public static final String HEADER_LAST_MODIFIED = "Last-Modified"; public static final String HEADER_LOCATION = "Location"; public static final String HEADER_MAX_FORWARDS = "Max-Forwards"; public static final String HEADER_PRAGMA = "Pragma"; public static final String HEADER_RANGE = "Range"; public static final String HEADER_REFER = "Referer"; public static final String HEADER_REFER_AFTER = "Retry-After"; public static final String HEADER_SERVER = "Server"; public static final String HEADER_UPGRADE = "Upgrade"; public static final String HEADER_USER_AGENT = "User-Agent"; public static final String HEADER_VARY = "Vary"; public static final String HEADER_VIA = "Via"; public static final String HEADER_WWW_AUTHORIZATION = "WWW-Authenticate"; public static final String HEADER_CONTENT_DISPOSITION = "Content-Disposition"; public static final String HEADER_COOKIE = "Cookie"; public static final String HEADER_SET_COOKIE = "Set-Cookie"; public static final String HEADER_TRANSFER_ENCODING = "Transfer-Encoding"; public static final String HEADER_CONTENT_ENCODING = "Content-Encoding"; /** HTTP expectations */ public static final String EXPECT_CONTINUE = "100-Continue"; /** HTTP connection control */ public static final String CONN_CLOSE = "Close"; public static final String CONN_KEEP_ALIVE = "Keep-Alive"; /** Transfer encoding definitions */ public static final String CHUNK_CODING = "chunked"; public static final String IDENTITY_CODING = "identity"; /** Common charset definitions */ public static final String UTF_8 = "UTF-8"; public static final String UTF_16 = "UTF-16"; public static final String US_ASCII = "US-ASCII"; public static final String ASCII = "ASCII"; public static final String ISO_8859_1 = "ISO-8859-1"; /** Default charsets */ public static final String DEFAULT_CONTENT_CHARSET = ISO_8859_1; public static final String DEFAULT_PROTOCOL_CHARSET = US_ASCII; /** Content type definitions */ public final static String OCTET_STREAM_TYPE = "application/octet-stream"; public final static String PLAIN_TEXT_TYPE = "text/plain"; public final static String HTML_TEXT_TYPE = "html/text"; public final static String CHARSET_PARAM = "; charset="; /** Default content type */ public final static String DEFAULT_CONTENT_TYPE = OCTET_STREAM_TYPE; }
Java
package com.ams.protocol.http; import java.io.*; import java.net.URLEncoder; import java.nio.ByteBuffer; import java.text.SimpleDateFormat; import java.util.*; import com.ams.io.BufferFactory; import com.ams.io.BufferOutputStream; public class HttpResponse { private BufferOutputStream out; private StringBuilder headerBuffer = new StringBuilder(1024); private StringBuilder bodyBuffer = new StringBuilder(); private String resultHeader; private Map<String, String> headers = new LinkedHashMap<String, String>(); private Map<String, Cookie> cookies = new LinkedHashMap<String, Cookie>(); private boolean headerWrote = false; private static String NEWLINE = "\r\n"; private static SimpleDateFormat dateFormatGMT; static { dateFormatGMT = new SimpleDateFormat("d MMM yyyy HH:mm:ss 'GMT'"); dateFormatGMT.setTimeZone(TimeZone.getTimeZone("GMT")); } public HttpResponse(BufferOutputStream out) { this.out = out; init(); } public void clear() { headerBuffer = new StringBuilder(1024); bodyBuffer = new StringBuilder(); resultHeader = null; headers.clear(); cookies.clear(); headerWrote = false; init(); } private void init() { resultHeader = "HTTP/1.1 200 OK"; headers.put(HTTP.HEADER_DATE, dateFormatGMT.format(new Date())); headers.put(HTTP.HEADER_SERVER, "annuus http server"); headers.put(HTTP.HEADER_CONTENT_TYPE, "text/html; charset=utf-8"); headers.put(HTTP.HEADER_CACHE_CONTROL, "no-cache, no-store, must-revalidate, private"); headers.put(HTTP.HEADER_PRAGMA, "no-cache"); } private void putHeader(String data) throws IOException { headerBuffer.append(data); } private void putHeaderValue(String name, String value) throws IOException { putHeader(name + ": " + value + NEWLINE); } public void setHttpResult(int code) { StringBuilder message = new StringBuilder(); message.append("HTTP/1.1 " + code + " "); switch (code) { case HTTP.HTTP_OK: message.append("OK"); break; case HTTP.HTTP_PARTIAL_CONTENT: message.append("Partial content"); break; case HTTP.HTTP_BAD_REQUEST: message.append("Bad Request"); break; case HTTP.HTTP_NOT_FOUND: message.append("Not Found"); break; case HTTP.HTTP_BAD_METHOD: message.append("Method Not Allowed"); break; case HTTP.HTTP_LENGTH_REQUIRED: message.append("Length Required"); break; case HTTP.HTTP_INTERNAL_ERROR: default: message.append("Internal Server Error"); break; } this.resultHeader = message.toString(); } public void setContentLength(long length) { setHeader(HTTP.HEADER_CONTENT_LENGTH, Long.toString(length)); } public void setContentType(String contentType) { setHeader(HTTP.HEADER_CONTENT_TYPE, contentType); } public void setLastModified(long lastModified) { setHeader(HTTP.HEADER_LAST_MODIFIED, dateFormatGMT.format(new Date(lastModified))); } public void setKeepAlive(boolean keepAlive) { if (keepAlive) { setHeader(HTTP.HEADER_CONN_DIRECTIVE, HTTP.CONN_KEEP_ALIVE); } else { setHeader(HTTP.HEADER_CONN_DIRECTIVE, HTTP.CONN_CLOSE); } } public void setHeader(String name, String value) { if (headers.containsKey(name)) { headers.remove(name); } headers.put(name, value); } public void setCookie(String name, Cookie cookie) { if (cookies.containsKey(name)) { cookies.remove(name); } cookies.put(name, cookie); } public void print(String data) throws IOException { bodyBuffer.append(data); } public void println(String data) throws IOException { print(data + NEWLINE); } public ByteBuffer writeHeader() throws IOException { if (headerWrote) { return null; } headerWrote = true; // write the headers putHeader(resultHeader + NEWLINE); // write all headers Iterator<String> it = this.headers.keySet().iterator(); while (it.hasNext()) { String name = it.next(); String value = headers.get(name); putHeaderValue(name, value); } // write all cookies it = this.cookies.keySet().iterator(); while (it.hasNext()) { String key = it.next(); Cookie cookie = cookies.get(key); StringBuilder cookieString = new StringBuilder(); cookieString.append(key + "=" + URLEncoder.encode(cookie.value, "UTF-8")); if (cookie.expires != 0) { Date d = new Date(cookie.expires); cookieString.append("; expires=" + dateFormatGMT.format(d)); } if (!cookie.path.equals("")) { cookieString.append("; path=" + cookie.path); } if (!cookie.domain.equals("")) { cookieString.append("; domain=" + cookie.domain); } if (cookie.secure) { cookieString.append("; secure"); } putHeaderValue(HTTP.HEADER_SET_COOKIE, cookieString.toString()); } putHeader(NEWLINE); // write header to socket channel byte[] data = headerBuffer.toString().getBytes("UTF-8"); ByteBuffer buffer = BufferFactory.allocate(data.length); buffer.put(data); buffer.flip(); return buffer; } public void startChunkedTransfer() throws IOException { setHeader(HTTP.HEADER_TRANSFER_ENCODING, "chunked"); // write to socket out.writeByteBuffer(new ByteBuffer[] { writeHeader() }); } public void flushChunk(ByteBuffer data) throws IOException { flushChunk(new ByteBuffer[] { data }); } public void flushChunk(ByteBuffer[] data) throws IOException { long dataSize = 0; ByteBuffer[] buf = new ByteBuffer[data.length + 2]; for (int i = 0, len = data.length; i < len; i++) { buf[i + 1] = data[i]; dataSize += data[i].remaining(); } // chunk size CRLF byte[] chunkSize = Long.toHexString(dataSize).getBytes(); ByteBuffer buffer = BufferFactory.allocate(chunkSize.length + 2); buffer.put(chunkSize); buffer.put((byte) 0x0d); buffer.put((byte) 0x0a); buffer.flip(); buf[0] = buffer; // chunked data CRLF buffer = BufferFactory.allocate(2); buffer.put((byte) 0x0d); buffer.put((byte) 0x0a); buffer.flip(); buf[buf.length - 1] = buffer; // write to socket out.writeByteBuffer(buf); } public void endChunkedTransfer() throws IOException { // last Chunk ByteBuffer buf = BufferFactory.allocate(5); buf.put((byte) 0x30); buf.put((byte) 0x0d); buf.put((byte) 0x0a); buf.put((byte) 0x0d); buf.put((byte) 0x0a); buf.flip(); // write to socket out.writeByteBuffer(new ByteBuffer[] { buf }); } public void flush() throws IOException { byte[] body = bodyBuffer.toString().getBytes("UTF-8"); setHeader(HTTP.HEADER_CONTENT_LENGTH, Long.toString(body.length)); ByteBuffer headerBuffer = writeHeader(); ByteBuffer bodyBuffer = BufferFactory.allocate(body.length); bodyBuffer.put(body); bodyBuffer.flip(); ByteBuffer[] buf = { headerBuffer, bodyBuffer }; // write to socket out.writeByteBuffer(buf); } public void flush(ByteBuffer data) throws IOException { flush(new ByteBuffer[] { data }); } public void flush(ByteBuffer[] data) throws IOException { long dataSize = 0; // body ByteBuffer[] buf = new ByteBuffer[data.length + 1]; for (int i = 0, len = data.length; i < len; i++) { buf[i + 1] = data[i]; dataSize += data[i].remaining(); } // set length header setHeader(HTTP.HEADER_CONTENT_LENGTH, Long.toString(dataSize)); // header ByteBuffer headerBuffer = writeHeader(); buf[0] = headerBuffer; // write to socket out.writeByteBuffer(buf); } }
Java
package com.ams.protocol.http; import java.util.HashMap; public class MimeTypes { public static HashMap<String, String> mimeMap = new HashMap<String, String>(); static { mimeMap.put("", "content/unknown"); mimeMap.put("fcs", "application/x-fcs"); mimeMap.put("uu", "application/octet-stream"); mimeMap.put("exe", "application/octet-stream"); mimeMap.put("ps", "application/postscript"); mimeMap.put("zip", "application/zip"); mimeMap.put("sh", "application/x-shar"); mimeMap.put("tar", "application/x-tar"); mimeMap.put("snd", "audio/basic"); mimeMap.put("au", "audio/basic"); mimeMap.put("avi", "video/avi"); mimeMap.put("wav", "audio/x-wav"); mimeMap.put("gif", "image/gif"); mimeMap.put("jpe", "image/jpeg"); mimeMap.put("jpg", "image/jpeg"); mimeMap.put("jpeg", "image/jpeg"); mimeMap.put("png", "image/png"); mimeMap.put("bmp", "image/bmp"); mimeMap.put("htm", "text/html"); mimeMap.put("html", "text/html"); mimeMap.put("text", "text/plain"); mimeMap.put("c", "text/plain"); mimeMap.put("cc", "text/plain"); mimeMap.put("c++", "text/plain"); mimeMap.put("h", "text/plain"); mimeMap.put("pl", "text/plain"); mimeMap.put("txt", "text/plain"); mimeMap.put("java", "text/plain"); mimeMap.put("js", "application/x-javascript"); mimeMap.put("css", "text/css"); mimeMap.put("xml", "text/xml"); }; public static String getContentType(String extension) { String contentType = mimeMap.get(extension); if (contentType == null) contentType = "unkown/unkown"; return contentType; } }
Java
package com.ams.protocol.http; import java.io.*; import java.net.*; import java.nio.ByteBuffer; import java.text.SimpleDateFormat; import java.util.*; import com.ams.io.BufferInputStream; public class HttpRequest { private BufferInputStream in = null; private int method; private String location; private String rawGet; private String rawPost; private ByteBuffer[] rawPostBodyData = null; private Map<String, String> headers = new LinkedHashMap<String, String>(); private Map<String, String> cookies = new LinkedHashMap<String, String>(); private Map<String, String> getValues = new LinkedHashMap<String, String>(); private Map<String, String> postValues = new LinkedHashMap<String, String>(); private Map<String, HttpFileUpload> postFiles = new LinkedHashMap<String, HttpFileUpload>(); private static SimpleDateFormat dateFormatGMT; static { dateFormatGMT = new SimpleDateFormat("d MMM yyyy HH:mm:ss 'GMT'"); dateFormatGMT.setTimeZone(TimeZone.getTimeZone("GMT")); } public HttpRequest(BufferInputStream in) { this.in = in; } public void clear() { method = -1; location = null; rawGet = null; rawPost = null; headers.clear(); cookies.clear(); getValues.clear(); postValues.clear(); postFiles.clear(); } public void parse() throws IOException { if (in == null) { throw new IOException("no input stream"); } if (HTTP.HTTP_OK != parseHttp()) { throw new IOException("bad http"); } } private void parseRawString(String options, Map<String, String> output, String seperator) { String[] tokens = options.split(seperator); for (int i = 0, len = tokens.length; i < len; i++) { String[] items = tokens[i].split("="); String key = ""; String value = ""; key = items[0]; if (items.length > 1) { try { value = URLDecoder.decode(items[1], "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } output.put(key, value); } } private int parseRequestLine() throws IOException { // first read and parse the first line String line = in.readLine(); // parse the request line String[] tokens = line.split(" "); if (tokens.length < 2) { return HTTP.HTTP_BAD_REQUEST; } // get the method String token = tokens[0].toUpperCase(); if ("GET".equals(token)) { method = HTTP.HTTP_METHOD_GET; } else if ("POST".equals(token)) { method = HTTP.HTTP_METHOD_POST; } else if ("HEAD".equals(token)) { method = HTTP.HTTP_METHOD_HEAD; } else { return HTTP.HTTP_BAD_METHOD; } // get the raw url String rawUrl = tokens[1]; // parse the get methods // remove anchor tag location = (rawUrl.indexOf('#') > 0) ? rawUrl.split("#")[0] : rawUrl; // get 'GET' part rawGet = ""; if (location.indexOf('?') > 0) { tokens = location.split("\\?"); location = tokens[0]; rawGet = tokens[1]; parseRawString(rawGet, getValues, "&"); } // return ok return HTTP.HTTP_OK; } private int parseHeader() throws IOException { String line = null; // parse the header while (((line = in.readLine()) != null) && !line.equals("")) { String[] tokens = line.split(": "); headers.put(tokens[0].toLowerCase(), tokens[1].toLowerCase()); } // get cookies if (headers.containsKey("cookie")) { parseRawString(headers.get("cookie"), cookies, ";"); } return HTTP.HTTP_OK; } private int parseMessageBody() throws IOException { // if method is post, parse the post values if (method == HTTP.HTTP_METHOD_POST) { String contentType = headers.get("content-type"); // if multi-form part if ((contentType != null) && contentType.startsWith("multipart/form-data")) { rawPost = ""; int result = parseMultipartBody(); if (result != HTTP.HTTP_OK) { return result; } } else if ((contentType != null) && contentType.startsWith("application/x-fcs")) { if (!headers.containsKey("content-length")) { return HTTP.HTTP_LENGTH_REQUIRED; } int len = Integer.parseInt(headers.get("content-length"), 10); rawPostBodyData = in.readByteBuffer(len); } else { if (!headers.containsKey("content-length")) { return HTTP.HTTP_LENGTH_REQUIRED; } int len = Integer.parseInt(headers.get("content-length"), 10); byte[] buf = new byte[len]; in.read(buf, 0, len); rawPost = new String(buf, "UTF-8"); parseRawString(rawPost, postValues, "&"); } } // handle POST end return HTTP.HTTP_OK; } private int parseMultipartBody() throws IOException { String contentType = headers.get("content-type"); String boundary = "--" + contentType.replaceAll("^.*boundary=\"?([^\";,]+)\"?.*$", "$1"); int blength = boundary.length(); if ((blength > 80) || (blength < 2)) { return HTTP.HTTP_BAD_REQUEST; } boolean done = false; String line = in.readLine(); while (!done && (line != null)) { if (boundary.equals(line)) { line = in.readLine(); } // parse the header HashMap<String, String> item = new HashMap<String, String>(); while (!line.equals("")) { String[] tokens = line.split(": "); item.put(tokens[0].toLowerCase(), tokens[1].toLowerCase()); line = in.readLine(); } // read body String disposition = item.get("content-disposition"); String name = disposition.replaceAll("^.* name=\"?([^\";]*)\"?.*$", "$1"); String filename = disposition.replaceAll( "^.* filename=\"?([^\";]*)\"?.*$", "$1"); if (disposition.equals(filename)) { filename = null; } // normal field if (filename == null) { String value = ""; // shouldn't be used more than once. while (((line = in.readLine()) != null) && !line.startsWith(boundary)) { value += line; } // read end if ((boundary + "--").equals(line)) { done = true; } // save post field postValues.put(name, value); // make rawPost if (rawPost.length() > 0) { rawPost += "&"; } try { rawPost += name + "=" + URLEncoder.encode(value, "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } else { // read file data // should we create a temporary file ? File tempfile = File.createTempFile("httpd", ".file"); FileOutputStream out = new FileOutputStream(tempfile); // read the data until we much the content boundry byte[] buf = new byte[boundary.length() + 2]; byte[] bound = ("\r\n" + boundary).getBytes(); int len = in.read(buf, 0, buf.length); if (len < buf.length) { return HTTP.HTTP_BAD_REQUEST; } while (!Arrays.equals(buf, bound)) { // check boundry out.write(buf[0]); // write a byte to file // shift buffer to left System.arraycopy(buf, 1, buf, 0, buf.length - 1); // read a byte if (0 > in.read(buf, buf.length - 1, 1)) { return HTTP.HTTP_BAD_REQUEST; } } // close tempofle if (tempfile != null) { out.close(); } // result of reading file int fileResult = HttpFileUpload.RESULT_NOFILE; if (tempfile.length() > HttpFileUpload.MAXSIZE_FILE_UPLOAD) { fileResult = HttpFileUpload.RESULT_SIZE; } else if (tempfile.length() > 0) { fileResult = HttpFileUpload.RESULT_OK; } postFiles.put(name, new HttpFileUpload(filename, tempfile, fileResult)); // read the newline and check the end int ch = in.read(); if (ch != '\r') { if ((ch == '-') && (in.read() == '-')) { // is "--" done = true; } } else { // '\n' ch = in.read(); } if (ch == -1) { // eof done = true; } line = in.readLine(); } // if normal field or file } // while readLine // return ok return HTTP.HTTP_OK; } private int parseHttp() throws IOException { // parse request line int result = parseRequestLine(); if (result != HTTP.HTTP_OK) { return result; } // parse eader part result = parseHeader(); if (result != HTTP.HTTP_OK) { return result; } // parse body part result = parseMessageBody(); if (result != HTTP.HTTP_OK) { return result; } return HTTP.HTTP_OK; } public int getMethod() { return method; } public boolean isKeepAlive() { String connection = getHeader("connection"); if (connection != null) { return connection.charAt(0) == 'k'; // keep-alive or close } return false; } public String getHeader(String key) { return headers.get(key); } public String getCookie(String key) { return cookies.get(key); } public String getGet(String key) { return getValues.get(key); } public String getPost(String key) { return postValues.get(key); } public String getParameter(String key) { String value = getGet(key); if (value == null) { value = getPost(key); } if (value == null) { value = getCookie(key); } return value; } public String getLocation() { return location; } public Map<String, String> getCookies() { return cookies; } public Map<String, String> getGetValues() { return getValues; } public Map<String, String> getHeaders() { return headers; } public Map<String, HttpFileUpload> getPostFiles() { return postFiles; } public Map<String, String> getPostValues() { return postValues; } public String getRawGet() { return rawGet; } public String getRawPost() { return rawPost; } public ByteBuffer[] getRawPostBodyData() { return rawPostBodyData; } }
Java
package com.ams.protocol.rtp; import java.nio.ByteBuffer; import java.util.ArrayList; import com.ams.io.network.connection.IFramer; import com.ams.util.BufferUtils; public class RtpSession implements IFramer { private class AssembleBuffer { private ByteBuffer[] buffers; private int lastFrameIndex = 0; public AssembleBuffer(int capacity) { buffers = new ByteBuffer[capacity]; } public void set(int index, ByteBuffer buf) { int capacity = buffers.length; if (index >= capacity) { ByteBuffer[] tmp = new ByteBuffer[capacity * 2]; System.arraycopy(buffers, 0, tmp, 0, capacity); buffers = tmp; } buffers[index] = buf; } public void lastFrame(int index) { lastFrameIndex = index; } public boolean hasLostFrame() { for (int i = 0; i <= lastFrameIndex; i++) { if (buffers[i] == null) return true; } return false; } public ByteBuffer[] getFrames() { ByteBuffer[] buf = new ByteBuffer[lastFrameIndex + 1]; System.arraycopy(buffers, 0, buf, 0, buf.length); return buf; } public void clear() { for (int i = 0, len = buffers.length; i < len; i++) { buffers[i] = null; } lastFrameIndex = 0; } } private AssembleBuffer readFrameBuffer = new AssembleBuffer(1024); private long readSessionId = 0; private long writeSessionId = System.currentTimeMillis(); private ByteBuffer[] getFrames() { return readFrameBuffer.getFrames(); } public ByteBuffer[] parseFrame(ByteBuffer frame) { RtpPacket packet = new RtpPacket(frame); if (readSessionId == 0) { readSessionId = packet.syncSourceId; } long sessionId = packet.syncSourceId; if (sessionId < readSessionId) { // drop frame return null; } if (sessionId > readSessionId) { readSessionId = sessionId; readFrameBuffer.clear(); } readFrameBuffer.set(packet.sequenceNum, packet.payload); if (packet.payloadType == 1) { // last frame? readFrameBuffer.lastFrame(packet.sequenceNum); if (!readFrameBuffer.hasLostFrame()) { return getFrames(); } readSessionId = 0; readFrameBuffer.clear(); } return null; } public ByteBuffer[] buildFrame(ByteBuffer[] buf) { ArrayList<RtpPacket> packets = new ArrayList<RtpPacket>(); int sequnceNum = 0; int i = 0; writeSessionId++; RtpPacket packet = null; ByteBuffer payload = null; while (i < buf.length) { if (packet == null) { packet = new RtpPacket(); packet.syncSourceId = writeSessionId; packet.payloadType = 0; packet.sequenceNum = sequnceNum++; payload = packet.getPayload(); } ByteBuffer data = buf[i]; int remaining = payload.remaining(); if (remaining >= data.remaining()) { payload.put(data); i++; } else { if (remaining > 0) { ByteBuffer slice = BufferUtils.trim(data, remaining); payload.put(slice); } packets.add(packet); packet = null; } } if (packet != null) { packets.add(packet); } ByteBuffer[] frames = new ByteBuffer[packets.size()]; for (int index = 0, len = frames.length; index < len; index++) { RtpPacket pkt = packets.get(index); if (index == len - 1) { pkt.payloadType = 1; } pkt.build(); frames[index] = pkt.getFrame(); frames[index].flip(); } return frames; } }
Java
package com.ams.protocol.rtp; import com.ams.io.network.connection.IFramer; import com.ams.io.network.connection.IFramerFactory; public class RtpSessionFactory implements IFramerFactory { @Override public IFramer create() { return new RtpSession(); } }
Java
package com.ams.protocol.rtp; import java.nio.ByteBuffer; import com.ams.io.BufferFactory; public class RtpPacket { public static final int FRAME_SIZE = 1500; public byte version = -128; public byte padding = 0; public byte extension = 0; public byte contribute = 0; public byte marker; public byte payloadType; // 0: data frame, 1: last frame public int sequenceNum; public long timestamp; public long syncSourceId; public ByteBuffer payload; private ByteBuffer frame = null; public RtpPacket(ByteBuffer frame) { this.frame = frame; } public RtpPacket() { ByteBuffer frame = BufferFactory.allocate(FRAME_SIZE); payload = frame.duplicate(); payload.position(12); } public void parse() { frame.position(0); frame.get(); // skip, version, padding, extension, contribute byte b = frame.get(); // marker, payloadType marker = (byte) (b & 0x80); payloadType = (byte) (b & 0x7F); sequenceNum = frame.getShort(); timestamp = frame.getInt(); syncSourceId = frame.getInt(); payload = frame.slice(); } public void build() { byte[] header = new byte[12]; header[0] = (byte) (version | padding | extension | contribute); header[1] = (byte) (marker | payloadType); header[2] = (byte) (sequenceNum >> 8); header[3] = (byte) (sequenceNum >> 0); header[4] = (byte) (timestamp >> 24); header[5] = (byte) (timestamp >> 16); header[6] = (byte) (timestamp >> 8); header[7] = (byte) (timestamp >> 0); header[8] = (byte) (syncSourceId >> 24); header[9] = (byte) (syncSourceId >> 16); header[10] = (byte) (syncSourceId >> 8); header[11] = (byte) (syncSourceId >> 0); ByteBuffer f = frame.duplicate(); f.position(0); f.put(header); } public void put(ByteBuffer data) { payload.put(data); } public void put(byte[] data) { payload.put(data); } public ByteBuffer getPayload() { return payload; } public ByteBuffer getFrame() { return frame; } }
Java
package com.ams.protocol.rtmp; import java.io.IOException; import java.util.Random; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import com.ams.io.BufferInputStream; import com.ams.io.BufferOutputStream; import com.ams.io.network.connection.Connection; public class RtmpHandShake { private final static int HANDSHAKE_SIZE = 0x600; private final static int STATE_UNINIT = 0; private final static int STATE_VERSION_SENT = 1; private final static int STATE_ACK_SENT = 2; private final static int STATE_HANDSHAKE_DONE = 3; private static final byte[] HANDSHAKE_SERVER_BYTES = { (byte) 0x01, (byte) 0x86, (byte) 0x4f, (byte) 0x7f, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x6b, (byte) 0x04, (byte) 0x67, (byte) 0x52, (byte) 0xa2, (byte) 0x70, (byte) 0x5b, (byte) 0x51, (byte) 0xa2, (byte) 0x89, (byte) 0xca, (byte) 0xcc, (byte) 0x8e, (byte) 0x70, (byte) 0xf0, (byte) 0x06, (byte) 0x70, (byte) 0x0e, (byte) 0xd7, (byte) 0xb3, (byte) 0x73, (byte) 0x7f, (byte) 0x07, (byte) 0xc1, (byte) 0x72, (byte) 0xd6, (byte) 0xcb, (byte) 0x4c, (byte) 0xc0, (byte) 0x45, (byte) 0x0f, (byte) 0xf5, (byte) 0x4f, (byte) 0xec, (byte) 0xd0, (byte) 0x2f, (byte) 0x46, (byte) 0x2b, (byte) 0x76, (byte) 0x10, (byte) 0x92, (byte) 0x1b, (byte) 0x0e, (byte) 0xb6, (byte) 0xed, (byte) 0x71, (byte) 0x73, (byte) 0x45, (byte) 0xc1, (byte) 0xc6, (byte) 0x26, (byte) 0x0c, (byte) 0x69, (byte) 0x59, (byte) 0x7b, (byte) 0xbb, (byte) 0x53, (byte) 0xb9, (byte) 0x10, (byte) 0x4d, (byte) 0xea, (byte) 0xc1, (byte) 0xe7, (byte) 0x7b, (byte) 0x70, (byte) 0xde, (byte) 0xdc, (byte) 0xf8, (byte) 0x84, (byte) 0x90, (byte) 0xbf, (byte) 0x80, (byte) 0xe8, (byte) 0x85, (byte) 0xb2, (byte) 0x46, (byte) 0x2c, (byte) 0x78, (byte) 0xa1, (byte) 0x85, (byte) 0x01, (byte) 0x8f, (byte) 0x8b, (byte) 0x05, (byte) 0x3f, (byte) 0xa1, (byte) 0x0c, (byte) 0x1a, (byte) 0x78, (byte) 0x70, (byte) 0x8c, (byte) 0x8e, (byte) 0x77, (byte) 0x67, (byte) 0xbc, (byte) 0x19, (byte) 0x2f, (byte) 0xab, (byte) 0x26, (byte) 0xa1, (byte) 0x7e, (byte) 0x88, (byte) 0xd8, (byte) 0xce, (byte) 0x24, (byte) 0x63, (byte) 0x21, (byte) 0x75, (byte) 0x3a, (byte) 0x5a, (byte) 0x6f, (byte) 0xc2, (byte) 0xa1, (byte) 0x2d, (byte) 0x4f, (byte) 0x64, (byte) 0xb7, (byte) 0x7b, (byte) 0xf7, (byte) 0xef, (byte) 0xda, (byte) 0x45, (byte) 0xb2, (byte) 0x51, (byte) 0xfd, (byte) 0xcb, (byte) 0x74, (byte) 0x49, (byte) 0xfd, (byte) 0x63, (byte) 0x8b, (byte) 0x88, (byte) 0xfb, (byte) 0xde, (byte) 0x5a, (byte) 0x3b, (byte) 0xab, (byte) 0x7f, (byte) 0x75, (byte) 0x25, (byte) 0xbb, (byte) 0x35, (byte) 0x51, (byte) 0x03, (byte) 0x81, (byte) 0x12, (byte) 0xff, (byte) 0x66, (byte) 0x02, (byte) 0x3d, (byte) 0x88, (byte) 0xdc, (byte) 0x66, (byte) 0xa2, (byte) 0xfb, (byte) 0x09, (byte) 0x24, (byte) 0x9d, (byte) 0x86, (byte) 0xfd, (byte) 0xc4, (byte) 0x00, (byte) 0xc2, (byte) 0x8b, (byte) 0x6f, (byte) 0xb7, (byte) 0xb2, (byte) 0x15, (byte) 0x10, (byte) 0xc0, (byte) 0x1b, (byte) 0x71, (byte) 0xa8, (byte) 0x3e, (byte) 0x88, (byte) 0xeb, (byte) 0x7e, (byte) 0xf3, (byte) 0xb2, (byte) 0xe3, (byte) 0xe8, (byte) 0x3c, (byte) 0x00, (byte) 0x9b, (byte) 0x26, (byte) 0xba, (byte) 0xb4, (byte) 0x5f, (byte) 0x2c, (byte) 0x36, (byte) 0xf3, (byte) 0x4a, (byte) 0x59, (byte) 0x09, (byte) 0x1b, (byte) 0xe5, (byte) 0x00, (byte) 0x9d, (byte) 0xe4, (byte) 0x66, (byte) 0x4d, (byte) 0x05, (byte) 0x66, (byte) 0xd0, (byte) 0xd1, (byte) 0xd6, (byte) 0x94, (byte) 0x4f, (byte) 0x64, (byte) 0xa1, (byte) 0x2e, (byte) 0x8d, (byte) 0x2f, (byte) 0xb0, (byte) 0x06, (byte) 0x01, (byte) 0xb3, (byte) 0x00, (byte) 0x3d, (byte) 0x77, (byte) 0xcd, (byte) 0x1b, (byte) 0xdd, (byte) 0xcc, (byte) 0xbf, (byte) 0xe9, (byte) 0xcd, (byte) 0x1a, (byte) 0x6b, (byte) 0x68, (byte) 0xdd, (byte) 0x1c, (byte) 0x7b, (byte) 0xfd, (byte) 0x2e, (byte) 0xb1, (byte) 0x8b, (byte) 0x45, (byte) 0xfd, (byte) 0x5b, (byte) 0x48, (byte) 0x52, (byte) 0x03, (byte) 0x01, (byte) 0xe8, (byte) 0xf1, (byte) 0x0f, (byte) 0xe7, (byte) 0x27, (byte) 0xfc, (byte) 0x2a, (byte) 0x52, (byte) 0x7c, (byte) 0x14, (byte) 0x22, (byte) 0x8b, (byte) 0x74, (byte) 0xbd, (byte) 0xd9, (byte) 0x97, (byte) 0x63, (byte) 0xef, (byte) 0xfa, (byte) 0xa3, (byte) 0xd9, (byte) 0x21, (byte) 0x12, (byte) 0x0b, (byte) 0x04, (byte) 0x62, (byte) 0x02, (byte) 0x98, (byte) 0x41, (byte) 0xf2, (byte) 0xb4, (byte) 0xc3, (byte) 0xe3, (byte) 0xe2, (byte) 0x2b, (byte) 0x2a, (byte) 0xff, (byte) 0xca, (byte) 0xb4, (byte) 0x48, (byte) 0x1e, (byte) 0x82, (byte) 0x50, (byte) 0x90, (byte) 0x94, (byte) 0x37, (byte) 0x24, (byte) 0x7e, (byte) 0xa1, (byte) 0x03, (byte) 0x1a, (byte) 0xf0, (byte) 0x9f, (byte) 0x2b, (byte) 0xbe, (byte) 0x64, (byte) 0xe5, (byte) 0x53, (byte) 0xb9, (byte) 0xb6, (byte) 0x43, (byte) 0x8e, (byte) 0x26, (byte) 0x6c, (byte) 0x63, (byte) 0x72, (byte) 0x8d, (byte) 0xb7, (byte) 0x7c, (byte) 0xb8, (byte) 0x21, (byte) 0x8f, (byte) 0xbb, (byte) 0x1c, (byte) 0x2a, (byte) 0x4e, (byte) 0xc7, (byte) 0xec, (byte) 0xa7, (byte) 0xa9, (byte) 0xbc, (byte) 0x15, (byte) 0x10, (byte) 0xe9, (byte) 0x4c, (byte) 0x46, (byte) 0xa5, (byte) 0x60, (byte) 0xa9, (byte) 0x71, (byte) 0x41, (byte) 0xdd, (byte) 0x25, (byte) 0xf5, (byte) 0xc1, (byte) 0xf6, (byte) 0xbd, (byte) 0x75, (byte) 0x1f, (byte) 0xb0, (byte) 0x15, (byte) 0xe0, (byte) 0xed, (byte) 0xc2, (byte) 0x4b, (byte) 0xac, (byte) 0xf1, (byte) 0xc8, (byte) 0xef, (byte) 0xa3, (byte) 0x44, (byte) 0xbe, (byte) 0x90, (byte) 0xab, (byte) 0x77, (byte) 0x28, (byte) 0xbf, (byte) 0xc0, (byte) 0xe0, (byte) 0x63, (byte) 0xaf, (byte) 0xd9, (byte) 0x07, (byte) 0x9d, (byte) 0x93, (byte) 0x16, (byte) 0x90, (byte) 0x7a, (byte) 0xe2, (byte) 0xb4, (byte) 0xe8, (byte) 0xe2, (byte) 0x3e, (byte) 0x4b, (byte) 0x18, (byte) 0x5f, (byte) 0x3e, (byte) 0x87, (byte) 0x09, (byte) 0xbe, (byte) 0x36, (byte) 0xd0, (byte) 0x8f, (byte) 0x7c, (byte) 0x22, (byte) 0x13, (byte) 0x9f, (byte) 0xc5, (byte) 0x78, (byte) 0xe0, (byte) 0x54, (byte) 0x4c, (byte) 0xa7, (byte) 0x77, (byte) 0x3f, (byte) 0xdf, (byte) 0x87, (byte) 0x4a, (byte) 0x28, (byte) 0x7b, (byte) 0x47, (byte) 0x80, (byte) 0x6a, (byte) 0xf0, (byte) 0x50, (byte) 0xcc, (byte) 0xde, (byte) 0x4c, (byte) 0x44, (byte) 0x41, (byte) 0x74, (byte) 0x3d, (byte) 0x03, (byte) 0x37, (byte) 0x8b, (byte) 0xbf, (byte) 0x79, (byte) 0x5b, (byte) 0x8c, (byte) 0xb0, (byte) 0x2f, (byte) 0x6e, (byte) 0x9c, (byte) 0x98, (byte) 0x29, (byte) 0x22, (byte) 0x49, (byte) 0x2f, (byte) 0xc9, (byte) 0x6d, (byte) 0xf1, (byte) 0x08, (byte) 0xc4, (byte) 0x4f, (byte) 0xb1, (byte) 0x91, (byte) 0xb3, (byte) 0xee, (byte) 0x57, (byte) 0xc1, (byte) 0x17, (byte) 0x5d, (byte) 0xd0, (byte) 0xe8, (byte) 0x19, (byte) 0xfb, (byte) 0x9b, (byte) 0xd6, (byte) 0xa8, (byte) 0x56, (byte) 0x92, (byte) 0x04, (byte) 0x4c, (byte) 0x0e, (byte) 0xe0, (byte) 0x52, (byte) 0x93, (byte) 0x9a, (byte) 0xec, (byte) 0xed, (byte) 0xf3, (byte) 0xf7, (byte) 0xef, (byte) 0xd7, (byte) 0x33, (byte) 0xe3, (byte) 0xcd, (byte) 0xc7, (byte) 0x4b, (byte) 0xac, (byte) 0xb7, (byte) 0xa9, (byte) 0xa5, (byte) 0x13, (byte) 0x09, (byte) 0x6c, (byte) 0x94, (byte) 0x49, (byte) 0x72, (byte) 0x03, (byte) 0xf3, (byte) 0xcf, (byte) 0x15, (byte) 0x31, (byte) 0xbc, (byte) 0xb5, (byte) 0x68, (byte) 0xc2, (byte) 0x49, (byte) 0xe1, (byte) 0x6e, (byte) 0x7d, (byte) 0xcb, (byte) 0x4e, (byte) 0xec, (byte) 0xfc, (byte) 0xa7, (byte) 0xb7, (byte) 0xed, (byte) 0x1c, (byte) 0x02, (byte) 0x49, (byte) 0x0e, (byte) 0x7f, (byte) 0x25, (byte) 0xeb, (byte) 0xd1, (byte) 0x81, (byte) 0x81, (byte) 0xc0, (byte) 0xa7, (byte) 0x49, (byte) 0x32, (byte) 0x16, (byte) 0x11, (byte) 0x31, (byte) 0x59, (byte) 0x12, (byte) 0x43, (byte) 0xd3, (byte) 0xa6, (byte) 0x95, (byte) 0x4a, (byte) 0xc5, (byte) 0xfe, (byte) 0xdf, (byte) 0x14, (byte) 0xda, (byte) 0xa6, (byte) 0x5a, (byte) 0xc0, (byte) 0xd5, (byte) 0x6a, (byte) 0xaf, (byte) 0xb3, (byte) 0xde, (byte) 0x32, (byte) 0x2a, (byte) 0x13, (byte) 0x03, (byte) 0xd3, (byte) 0x10, (byte) 0x71, (byte) 0x0b, (byte) 0xc0, (byte) 0x1e, (byte) 0xcf, (byte) 0xdb, (byte) 0xaa, (byte) 0xcc, (byte) 0xa6, (byte) 0xb5, (byte) 0x65, (byte) 0x2e, (byte) 0xc4, (byte) 0x0b, (byte) 0x5c, (byte) 0xa7, (byte) 0x1c, (byte) 0x8b, (byte) 0x2d, (byte) 0x7f, (byte) 0xc0, (byte) 0x4c, (byte) 0x4a, (byte) 0xa4, (byte) 0x0b, (byte) 0xa0, (byte) 0x60, (byte) 0xc4, (byte) 0xcf, (byte) 0xb1, (byte) 0xbe, (byte) 0xe4, (byte) 0xe4, (byte) 0x50, (byte) 0xc9, (byte) 0xcc, (byte) 0xa0, (byte) 0xe8, (byte) 0x79, (byte) 0x12, (byte) 0xc4, (byte) 0xb4, (byte) 0x70, (byte) 0xf5, (byte) 0x84, (byte) 0x98, (byte) 0x83, (byte) 0xe2, (byte) 0xa9, (byte) 0x8f, (byte) 0xba, (byte) 0xff, (byte) 0x88, (byte) 0xa2, (byte) 0x21, (byte) 0xba, (byte) 0x00, (byte) 0x3d, (byte) 0xc4, (byte) 0x57, (byte) 0xe6, (byte) 0x6a, (byte) 0xf4, (byte) 0xdc, (byte) 0x01, (byte) 0x1e, (byte) 0xac, (byte) 0x0a, (byte) 0xcc, (byte) 0x49, (byte) 0xaf, (byte) 0x9c, (byte) 0xc7, (byte) 0xcd, (byte) 0xc1, (byte) 0x14, (byte) 0x6e, (byte) 0x12, (byte) 0x87, (byte) 0xf8, (byte) 0x22, (byte) 0xeb, (byte) 0xdf, (byte) 0x48, (byte) 0xda, (byte) 0x9f, (byte) 0xf2, (byte) 0x8b, (byte) 0xc1, (byte) 0xd2, (byte) 0x44, (byte) 0x94, (byte) 0xe4, (byte) 0x3e, (byte) 0xd0, (byte) 0x85, (byte) 0x56, (byte) 0xe4, (byte) 0x9a, (byte) 0xfd, (byte) 0xb9, (byte) 0xb3, (byte) 0x35, (byte) 0x38, (byte) 0x1d, (byte) 0x15, (byte) 0x4d, (byte) 0x28, (byte) 0xab, (byte) 0xb0, (byte) 0x17, (byte) 0xc0, (byte) 0x5b, (byte) 0x09, (byte) 0x86, (byte) 0x07, (byte) 0xfa, (byte) 0x69, (byte) 0xda, (byte) 0x65, (byte) 0xb8, (byte) 0xd9, (byte) 0x8f, (byte) 0xe6, (byte) 0xa1, (byte) 0x83, (byte) 0xab, (byte) 0x07, (byte) 0x98, (byte) 0x3c, (byte) 0x79, (byte) 0xf4, (byte) 0x59, (byte) 0x08, (byte) 0x8f, (byte) 0x83, (byte) 0x77, (byte) 0xbd, (byte) 0xa1, (byte) 0xa1, (byte) 0x76, (byte) 0x28, (byte) 0x9c, (byte) 0x0f, (byte) 0xcc, (byte) 0xdc, (byte) 0xce, (byte) 0x1f, (byte) 0x16, (byte) 0x02, (byte) 0x47, (byte) 0x98, (byte) 0x37, (byte) 0x96, (byte) 0x87, (byte) 0xb1, (byte) 0x70, (byte) 0x3a, (byte) 0xea, (byte) 0xa4, (byte) 0x65, (byte) 0x77, (byte) 0x98, (byte) 0x12, (byte) 0x27, (byte) 0x23, (byte) 0x47, (byte) 0xa8, (byte) 0x1b, (byte) 0x79, (byte) 0xc0, (byte) 0xec, (byte) 0x53, (byte) 0x32, (byte) 0xe6, (byte) 0xc1, (byte) 0x61, (byte) 0x7b, (byte) 0xa0, (byte) 0x98, (byte) 0x9f, (byte) 0xfc, (byte) 0x8d, (byte) 0xe8, (byte) 0x5c, (byte) 0xaf, (byte) 0xc6, (byte) 0xbf, (byte) 0x1f, (byte) 0xd1, (byte) 0x40, (byte) 0xdc, (byte) 0x28, (byte) 0x81, (byte) 0x34, (byte) 0x68, (byte) 0xb7, (byte) 0xda, (byte) 0x10, (byte) 0xf2, (byte) 0x63, (byte) 0x52, (byte) 0xcb, (byte) 0xe7, (byte) 0x18, (byte) 0x85, (byte) 0xd5, (byte) 0x99, (byte) 0x33, (byte) 0xee, (byte) 0x9a, (byte) 0x28, (byte) 0xfa, (byte) 0xdf, (byte) 0x6d, (byte) 0xcb, (byte) 0xc2, (byte) 0xce, (byte) 0x9d, (byte) 0xed, (byte) 0x9d, (byte) 0xbd, (byte) 0xfd, (byte) 0xd7, (byte) 0x0a, (byte) 0xe4, (byte) 0x89, (byte) 0xd3, (byte) 0x10, (byte) 0x9b, (byte) 0xdb, (byte) 0x6f, (byte) 0xd9, (byte) 0x37, (byte) 0x8b, (byte) 0x79, (byte) 0x9c, (byte) 0x94, (byte) 0xc2, (byte) 0x44, (byte) 0x31, (byte) 0x9f, (byte) 0x24, (byte) 0xef, (byte) 0x21, (byte) 0x1d, (byte) 0x5f, (byte) 0xd6, (byte) 0xf9, (byte) 0x99, (byte) 0x7b, (byte) 0xef, (byte) 0x59, (byte) 0xe6, (byte) 0xd6, (byte) 0xdd, (byte) 0x6a, (byte) 0x74, (byte) 0x82, (byte) 0xb8, (byte) 0xc5, (byte) 0xfb, (byte) 0x1d, (byte) 0xe8, (byte) 0xfc, (byte) 0x67, (byte) 0x4f, (byte) 0x4d, (byte) 0xb5, (byte) 0xcf, (byte) 0xa9, (byte) 0x52, (byte) 0x94, (byte) 0xc5, (byte) 0xb7, (byte) 0x32, (byte) 0xa0, (byte) 0x45, (byte) 0x0a, (byte) 0x35, (byte) 0x44, (byte) 0x59, (byte) 0x1e, (byte) 0x1c, (byte) 0x64, (byte) 0x89, (byte) 0x51, (byte) 0x80, (byte) 0x7b, (byte) 0x1f, (byte) 0x02, (byte) 0x77, (byte) 0x81, (byte) 0xfa, (byte) 0xe9, (byte) 0x26, (byte) 0x4c, (byte) 0x5f, (byte) 0xe2, (byte) 0x0d, (byte) 0x05, (byte) 0x55, (byte) 0xee, (byte) 0x71, (byte) 0x71, (byte) 0xfc, (byte) 0x35, (byte) 0x33, (byte) 0x22, (byte) 0x63, (byte) 0xf5, (byte) 0x36, (byte) 0x45, (byte) 0xf6, (byte) 0x2f, (byte) 0xd0, (byte) 0x13, (byte) 0xb7, (byte) 0x58, (byte) 0x4f, (byte) 0x35, (byte) 0x19, (byte) 0x59, (byte) 0x0a, (byte) 0xe5, (byte) 0xf8, (byte) 0x8a, (byte) 0x4c, (byte) 0x59, (byte) 0x32, (byte) 0xbf, (byte) 0xca, (byte) 0xb0, (byte) 0x06, (byte) 0xc2, (byte) 0x6c, (byte) 0xa9, (byte) 0x48, (byte) 0x5b, (byte) 0x4c, (byte) 0x76, (byte) 0x24, (byte) 0xae, (byte) 0x9d, (byte) 0x5b, (byte) 0x7b, (byte) 0x79, (byte) 0x38, (byte) 0x4e, (byte) 0x9e, (byte) 0x47, (byte) 0x12, (byte) 0x8a, (byte) 0xc6, (byte) 0xe0, (byte) 0x04, (byte) 0x37, (byte) 0x72, (byte) 0xdd, (byte) 0xaf, (byte) 0x3d, (byte) 0x0d, (byte) 0x68, (byte) 0x7e, (byte) 0xd8, (byte) 0x80, (byte) 0x7b, (byte) 0x07, (byte) 0x23, (byte) 0xce, (byte) 0x40, (byte) 0x4a, (byte) 0xed, (byte) 0x83, (byte) 0x55, (byte) 0x56, (byte) 0xfd, (byte) 0xdb, (byte) 0x95, (byte) 0xb3, (byte) 0x1c, (byte) 0x33, (byte) 0xf1, (byte) 0x43, (byte) 0xa8, (byte) 0x0e, (byte) 0x5e, (byte) 0x67, (byte) 0xd6, (byte) 0x3a, (byte) 0xd0, (byte) 0x89, (byte) 0x5e, (byte) 0x72, (byte) 0x77, (byte) 0x7f, (byte) 0x10, (byte) 0x3c, (byte) 0xc4, (byte) 0x7c, (byte) 0x9a, (byte) 0xa3, (byte) 0x55, (byte) 0xc5, (byte) 0xd3, (byte) 0x5b, (byte) 0x3a, (byte) 0xae, (byte) 0x12, (byte) 0x0c, (byte) 0x71, (byte) 0x73, (byte) 0xa0, (byte) 0x58, (byte) 0x90, (byte) 0x54, (byte) 0xa8, (byte) 0x1c, (byte) 0x31, (byte) 0x20, (byte) 0xdb, (byte) 0xde, (byte) 0xdd, (byte) 0x35, (byte) 0xb1, (byte) 0x09, (byte) 0xa2, (byte) 0xd0, (byte) 0x6e, (byte) 0x39, (byte) 0x39, (byte) 0xa5, (byte) 0x0a, (byte) 0x3d, (byte) 0x8a, (byte) 0x00, (byte) 0x4b, (byte) 0x95, (byte) 0x6f, (byte) 0x8c, (byte) 0x12, (byte) 0x41, (byte) 0xc6, (byte) 0x46, (byte) 0x10, (byte) 0x5e, (byte) 0x9d, (byte) 0x50, (byte) 0x85, (byte) 0x0e, (byte) 0x6b, (byte) 0x81, (byte) 0xa7, (byte) 0x3b, (byte) 0x35, (byte) 0xa6, (byte) 0x38, (byte) 0xf5, (byte) 0xc2, (byte) 0xba, (byte) 0x6c, (byte) 0x02, (byte) 0xda, (byte) 0x27, (byte) 0x29, (byte) 0x6e, (byte) 0xe9, (byte) 0x54, (byte) 0x41, (byte) 0xa4, (byte) 0x94, (byte) 0x75, (byte) 0xe8, (byte) 0x55, (byte) 0xc0, (byte) 0xe3, (byte) 0xc2, (byte) 0x91, (byte) 0x8a, (byte) 0x1d, (byte) 0xfb, (byte) 0x2b, (byte) 0xba, (byte) 0x43, (byte) 0xe7, (byte) 0x45, (byte) 0x85, (byte) 0xe8, (byte) 0x13, (byte) 0x07, (byte) 0x1d, (byte) 0x9c, (byte) 0x37, (byte) 0xa8, (byte) 0xf3, (byte) 0xca, (byte) 0xf4, (byte) 0x19, (byte) 0x77, (byte) 0xc4, (byte) 0x65, (byte) 0xd6, (byte) 0x18, (byte) 0x3e, (byte) 0x60, (byte) 0x08, (byte) 0x74, (byte) 0x49, (byte) 0xba, (byte) 0xc8, (byte) 0x86, (byte) 0x37, (byte) 0x8a, (byte) 0x0f, (byte) 0x79, (byte) 0x91, (byte) 0x53, (byte) 0x20, (byte) 0x23, (byte) 0x00, (byte) 0xb9, (byte) 0xc5, (byte) 0x1b, (byte) 0x01, (byte) 0xdd, (byte) 0x10, (byte) 0x34, (byte) 0x05, (byte) 0x42, (byte) 0xa0, (byte) 0x64, (byte) 0xab, (byte) 0x4d, (byte) 0x51, (byte) 0xf4, (byte) 0x53, (byte) 0x35, (byte) 0x18, (byte) 0xde, (byte) 0x20, (byte) 0x1f, (byte) 0xaa, (byte) 0xe2, (byte) 0x40, (byte) 0x0d, (byte) 0x6d, (byte) 0x77, (byte) 0x36, (byte) 0x1f, (byte) 0xee, (byte) 0x3a, (byte) 0x93, (byte) 0xdb, (byte) 0x1d, (byte) 0xd6, (byte) 0xa0, (byte) 0x23, (byte) 0xcc, (byte) 0xe6, (byte) 0xa8, (byte) 0x44, (byte) 0x8e, (byte) 0xae, (byte) 0x9c, (byte) 0xd7, (byte) 0x97, (byte) 0x6a, (byte) 0x99, (byte) 0xee, (byte) 0x40, (byte) 0x15, (byte) 0xd5, (byte) 0x5a, (byte) 0x6d, (byte) 0xf6, (byte) 0x9c, (byte) 0x2c, (byte) 0x52, (byte) 0xcd, (byte) 0xfa, (byte) 0xf4, (byte) 0xc8, (byte) 0x02, (byte) 0xee, (byte) 0xf2, (byte) 0x76, (byte) 0x8b, (byte) 0x49, (byte) 0x6d, (byte) 0x66, (byte) 0x83, (byte) 0x5f, (byte) 0xbe, (byte) 0x05, (byte) 0x8e, (byte) 0xf2, (byte) 0x27, (byte) 0x73, (byte) 0xdb, (byte) 0x00, (byte) 0xeb, (byte) 0x9a, (byte) 0xb4, (byte) 0xbf, (byte) 0x47, (byte) 0x9a, (byte) 0xbd, (byte) 0xf1, (byte) 0x4f, (byte) 0x70, (byte) 0xed, (byte) 0x33, (byte) 0xce, (byte) 0x31, (byte) 0x9d, (byte) 0x9f, (byte) 0x95, (byte) 0x80, (byte) 0x9e, (byte) 0x73, (byte) 0x11, (byte) 0x6c, (byte) 0x03, (byte) 0x7b, (byte) 0x6e, (byte) 0x62, (byte) 0x9c, (byte) 0xd0, (byte) 0xaa, (byte) 0xf6, (byte) 0x5d, (byte) 0xe0, (byte) 0xd8, (byte) 0x96, (byte) 0x94, (byte) 0x46, (byte) 0xd1, (byte) 0x10, (byte) 0x3c, (byte) 0x1b, (byte) 0x9d, (byte) 0x40, (byte) 0xdd, (byte) 0xab, (byte) 0xec, (byte) 0x8a, (byte) 0x5b, (byte) 0x1a, (byte) 0xb6, (byte) 0x19, (byte) 0x57, (byte) 0x99, (byte) 0x09, (byte) 0xe8, (byte) 0xec, (byte) 0x82, (byte) 0xdc, (byte) 0x06, (byte) 0x39, (byte) 0x86, (byte) 0x25, (byte) 0x3b, (byte) 0x67, (byte) 0xb5, (byte) 0x17, (byte) 0xc5, (byte) 0x6e, (byte) 0x6e, (byte) 0x1c, (byte) 0x6c, (byte) 0xea, (byte) 0xbe, (byte) 0xb8, (byte) 0xdd, (byte) 0x68, (byte) 0xf8, (byte) 0xf3, (byte) 0x18, (byte) 0xf2, (byte) 0x3c, (byte) 0x99, (byte) 0xdc, (byte) 0xa9, (byte) 0xd3, (byte) 0xb2, (byte) 0x7a, (byte) 0x40, (byte) 0x70, (byte) 0x4b, (byte) 0xc2, (byte) 0xd2, (byte) 0xa7, (byte) 0xb3, (byte) 0x42, (byte) 0x19, (byte) 0xff, (byte) 0x0b, (byte) 0xdf, (byte) 0x07, (byte) 0x0e, (byte) 0x6b, (byte) 0x8e, (byte) 0xef, (byte) 0x63, (byte) 0x92, (byte) 0xd6, (byte) 0x15, (byte) 0x57, (byte) 0x62, (byte) 0x12, (byte) 0x99, (byte) 0x96, (byte) 0x96, (byte) 0xa5, (byte) 0x34, (byte) 0x5a, (byte) 0x2c, (byte) 0x7c, (byte) 0xf6, (byte) 0xbc, (byte) 0x16, (byte) 0xb2, (byte) 0x90, (byte) 0xc3, (byte) 0x11, (byte) 0x5e, (byte) 0xba, (byte) 0x0e, (byte) 0xe4, (byte) 0x22, (byte) 0x84, (byte) 0x32, (byte) 0x50, (byte) 0xda, (byte) 0x1e, (byte) 0x37, (byte) 0x06, (byte) 0x5b, (byte) 0xef, (byte) 0x69, (byte) 0xb7, (byte) 0x6f, (byte) 0x10, (byte) 0xcb, (byte) 0xdc, (byte) 0x4d, (byte) 0xfd, (byte) 0xdb, (byte) 0xa3, (byte) 0xef, (byte) 0x54, (byte) 0xea, (byte) 0xda, (byte) 0x55, (byte) 0xba, (byte) 0x32, (byte) 0xf4, (byte) 0x86, (byte) 0x6b, (byte) 0xb1, (byte) 0xc8, (byte) 0xfc, (byte) 0x12, (byte) 0x9a, (byte) 0xfc, (byte) 0xda, (byte) 0xfd, (byte) 0x2a, (byte) 0xc2, (byte) 0x7f, (byte) 0x70, (byte) 0xce, (byte) 0x34, (byte) 0x38, (byte) 0xe6, (byte) 0x6a, (byte) 0x7d, (byte) 0x33, (byte) 0xa0, (byte) 0x16, (byte) 0xfb, (byte) 0xfd, (byte) 0xa7, (byte) 0xdf, (byte) 0x2e, (byte) 0xe3, (byte) 0x5f, (byte) 0x93, (byte) 0x39, (byte) 0xaa, (byte) 0x00, (byte) 0xc7, (byte) 0x38, (byte) 0x2e, (byte) 0x9c, (byte) 0xf3, (byte) 0xc4, (byte) 0x12, (byte) 0x46, (byte) 0xcf, (byte) 0x06, (byte) 0xfe, (byte) 0x0f, (byte) 0x82, (byte) 0x82, (byte) 0x74, (byte) 0x00, (byte) 0x71, (byte) 0xf8, (byte) 0x28, (byte) 0x2f, (byte) 0x9b, (byte) 0x3f, (byte) 0x9a, (byte) 0x42, (byte) 0x1b, (byte) 0x3e, (byte) 0xa6, (byte) 0x0e, (byte) 0x90, (byte) 0xa7, (byte) 0x45, (byte) 0xa6, (byte) 0xcd, (byte) 0x6e, (byte) 0x88, (byte) 0x94, (byte) 0x08, (byte) 0x3a, (byte) 0xe5, (byte) 0x56, (byte) 0x36, (byte) 0x77, (byte) 0x68, (byte) 0x2e, (byte) 0x39, (byte) 0xd3, (byte) 0x45, (byte) 0xee, (byte) 0x89, (byte) 0xf0, (byte) 0x71, (byte) 0x42, (byte) 0x2d, (byte) 0xe2, (byte) 0x1b, (byte) 0xf5, (byte) 0x11, (byte) 0xf0, (byte) 0xff, (byte) 0x05, (byte) 0x0c, (byte) 0x78, (byte) 0xa1, (byte) 0x65, (byte) 0xcf, (byte) 0x3c, (byte) 0x9e, (byte) 0xe3, (byte) 0x37, (byte) 0x72, (byte) 0x3a, (byte) 0x32, (byte) 0xcb, (byte) 0x1f, (byte) 0xfd, (byte) 0x9d, (byte) 0x4a, (byte) 0x0e, (byte) 0xf7, (byte) 0x0b, (byte) 0x2b, (byte) 0xaa, (byte) 0x57, (byte) 0x2c, (byte) 0x27, (byte) 0xb3, (byte) 0xa0, (byte) 0x2a, (byte) 0x0f, (byte) 0x85, (byte) 0x16, (byte) 0x6c, (byte) 0xe2, (byte) 0xe0, (byte) 0xa1, (byte) 0x48, (byte) 0x8e, (byte) 0x00, (byte) 0x8d, (byte) 0x6d, (byte) 0xc8, (byte) 0x10, (byte) 0xfd, (byte) 0x43, (byte) 0x96, (byte) 0x50, (byte) 0x07, (byte) 0x07, (byte) 0x9a, (byte) 0xbf, (byte) 0x50, (byte) 0x62, (byte) 0x76, (byte) 0x3e, (byte) 0xe1, (byte) 0xf7, (byte) 0x70, (byte) 0xc1, (byte) 0xb0, (byte) 0x79, (byte) 0x8e, (byte) 0x61, (byte) 0xe3, (byte) 0xfb, (byte) 0x05, (byte) 0x5f, (byte) 0xbb, (byte) 0x2d, (byte) 0x76, (byte) 0x69, (byte) 0x89, (byte) 0xf3, (byte) 0x1e, (byte) 0x62, (byte) 0xf6, (byte) 0x27, (byte) 0x3d, (byte) 0x3e, (byte) 0x41, (byte) 0x0f, (byte) 0xf5, (byte) 0x0f, (byte) 0xc7, (byte) 0xf3, (byte) 0x0e, (byte) 0x3b, (byte) 0xd5, (byte) 0xed, (byte) 0xcf, (byte) 0xef, (byte) 0x58, (byte) 0xfa, (byte) 0x39, (byte) 0xdf, (byte) 0x75, (byte) 0x85, (byte) 0x2b, (byte) 0x8b, (byte) 0xaa, (byte) 0x08, (byte) 0x72, (byte) 0x52, (byte) 0xa7, (byte) 0x98, (byte) 0x42, (byte) 0x95, (byte) 0x7b, (byte) 0xb7, (byte) 0xe7, (byte) 0x10, (byte) 0xfe, (byte) 0xdb, (byte) 0x54, (byte) 0x34, (byte) 0xfb, (byte) 0x91, (byte) 0x24, (byte) 0x1c, (byte) 0x07, (byte) 0xfb, (byte) 0x9c, (byte) 0xce, (byte) 0xd0, (byte) 0x46, (byte) 0xcf, (byte) 0xc4, (byte) 0x9d, (byte) 0x09, (byte) 0x49, (byte) 0x24, (byte) 0xec, }; private final static byte[] GenuineFMSConst = { (byte) 0x47, (byte) 0x65, (byte) 0x6e, (byte) 0x75, (byte) 0x69, (byte) 0x6e, (byte) 0x65, (byte) 0x20, (byte) 0x41, (byte) 0x64, (byte) 0x6f, (byte) 0x62, (byte) 0x65, (byte) 0x20, (byte) 0x46, (byte) 0x6c, (byte) 0x61, (byte) 0x73, (byte) 0x68, (byte) 0x20, (byte) 0x4d, (byte) 0x65, (byte) 0x64, (byte) 0x69, (byte) 0x61, (byte) 0x20, (byte) 0x53, (byte) 0x65, (byte) 0x72, (byte) 0x76, (byte) 0x65, (byte) 0x72, (byte) 0x20, (byte) 0x30, (byte) 0x30, (byte) 0x31, (byte) 0xf0, (byte) 0xee, (byte) 0xc2, (byte) 0x4a, (byte) 0x80, (byte) 0x68, (byte) 0xbe, (byte) 0xe8, (byte) 0x2e, (byte) 0x00, (byte) 0xd0, (byte) 0xd1, (byte) 0x02, (byte) 0x9e, (byte) 0x7e, (byte) 0x57, (byte) 0x6e, (byte) 0xec, (byte) 0x5d, (byte) 0x2d, (byte) 0x29, (byte) 0x80, (byte) 0x6f, (byte) 0xab, (byte) 0x93, (byte) 0xb8, (byte) 0xe6, (byte) 0x36, (byte) 0xcf, (byte) 0xeb, (byte) 0x31, (byte) 0xae }; private int state = STATE_UNINIT; private byte[] handShake; private Mac hmacSHA256; private Connection conn; private BufferInputStream in; private BufferOutputStream out; public RtmpHandShake(RtmpConnection rtmp) { this.conn = rtmp.getConnector(); this.in = conn.getInputStream(); this.out = conn.getOutputStream(); try { hmacSHA256 = Mac.getInstance("HmacSHA256"); } catch (Exception e) { e.printStackTrace(); } } private void readVersion() throws IOException, RtmpException { if ((in.readByte() & 0xFF) != 3) // version throw new RtmpException("Invalid version"); } private void writeVersion() throws IOException { out.writeByte(3); } private void writeHandshake() throws IOException { out.write32Bit(0); out.write32Bit(0); handShake = new byte[HANDSHAKE_SIZE - 8]; Random rnd = new Random(); rnd.nextBytes(handShake); out.write(handShake, 0, handShake.length); } private byte[] readHandshake() throws IOException { byte[] b = new byte[HANDSHAKE_SIZE]; in.read(b, 0, b.length); return b; } private void writeHandshake(byte[] b) throws IOException { out.write(b, 0, b.length); } private byte[] calculateHmacSHA256(byte[] key, byte[] in) { byte[] out = null; try { hmacSHA256.init(new SecretKeySpec(key, "HmacSHA256")); out = hmacSHA256.doFinal(in); } catch (Exception e) { e.printStackTrace(); } return out; } private int GetClientGenuineConstDigestOffset(byte[] b) { return ((b[8] & 0x0ff) + (b[9] & 0x0ff) + (b[10] & 0x0ff) + (b[11] & 0x0ff)) % 728 + 12; } private int GetServerGenuineConstDigestOffset(byte[] b) { return ((b[772] & 0x0ff) + (b[773] & 0x0ff) + (b[774] & 0x0ff) + (b[775] & 0x0ff)) % 728 + 776; } private byte[] getHandshake(byte[] b) { long schema = (((b[4] & 0xFF) << 24) | ((b[5] & 0xFF) << 16) | ((b[6] & 0xFF) << 8) | (b[7] & 0xFF)) & 0xFFFFFFFFL; // Flash Player 10.0.32.18 int offset = schema < 0x80000302L ? GetClientGenuineConstDigestOffset(b) : GetServerGenuineConstDigestOffset(b); byte[] digest = new byte[32]; System.arraycopy(b, offset, digest, 0, 32); byte[] newKey = calculateHmacSHA256(GenuineFMSConst, digest); byte[] hash = new byte[HANDSHAKE_SIZE - 32]; Random rnd = new Random(); rnd.nextBytes(hash); byte[] newHandShake = new byte[HANDSHAKE_SIZE]; System.arraycopy(hash, 0, newHandShake, 0, hash.length); byte[] newPart = calculateHmacSHA256(newKey, hash); System.arraycopy(newPart, 0, newHandShake, hash.length, newPart.length); return newHandShake; } public boolean doClientHandshake() throws IOException, RtmpException { boolean stateChanged = false; long available = conn.available(); switch (state) { case STATE_UNINIT: writeVersion(); // write C0 message writeHandshake(); // write c1 message state = STATE_VERSION_SENT; stateChanged = true; break; case STATE_VERSION_SENT: if (available < 1 + HANDSHAKE_SIZE) break; readVersion(); // read S0 message byte[] hs1 = readHandshake(); // read S1 message writeHandshake(hs1); // write C2 message state = STATE_ACK_SENT; stateChanged = true; break; case STATE_ACK_SENT: if (available < HANDSHAKE_SIZE) break; byte[] hs2 = readHandshake(); // read S2 message // if(!Arrays.equals(handShake, hs2)) { // throw new RtmpException("Invalid Handshake"); // } state = STATE_HANDSHAKE_DONE; stateChanged = true; break; } return stateChanged; } public void doServerHandshake() throws IOException, RtmpException { long available = conn.available(); switch (state) { case STATE_UNINIT: if (available < 1) break; readVersion(); // read C0 message writeVersion(); // write S0 message writeHandshake(HANDSHAKE_SERVER_BYTES); // write S1 message state = STATE_VERSION_SENT; break; case STATE_VERSION_SENT: if (available < HANDSHAKE_SIZE) break; byte[] hs1 = readHandshake(); // read C1 message if (hs1[4] == 0) { // < Flash Player 9.0.115.0(Flash Player 9 update // 3) writeHandshake(hs1); // write S2 message } else { writeHandshake(getHandshake(hs1)); // write S2 message } state = STATE_ACK_SENT; break; case STATE_ACK_SENT: if (available < HANDSHAKE_SIZE) break; byte[] hs2 = readHandshake(); // read C2 message // if(!Arrays.equals(handShake, hs2)) { // throw new RtmpException("Invalid Handshake"); // } state = STATE_HANDSHAKE_DONE; break; } } public boolean isHandshakeDone() { return (state == STATE_HANDSHAKE_DONE); } }
Java
package com.ams.protocol.rtmp; import java.io.IOException; import com.ams.io.BufferOutputStream; public class RtmpHeaderSerializer { private BufferOutputStream out; public RtmpHeaderSerializer(BufferOutputStream out) { super(); this.out = out; } public void write(RtmpHeader header) throws IOException { int fmt; long timestamp = header.getTimestamp(); int size = header.getSize(); int type = header.getType(); int streamId = header.getStreamId(); if (timestamp != -1 && size != -1 && type != -1 && streamId != -1) fmt = 0; else if (timestamp != -1 && size != -1 && type != -1) fmt = 1; else if (timestamp != -1) fmt = 2; else fmt = 3; // write Chunk Basic Header int chunkStreamId = header.getChunkStreamId(); if (chunkStreamId >= 2 && chunkStreamId <= 63) { // 1 byte version out.writeByte(fmt << 6 | chunkStreamId); // csid = 2 indicates // Protocol Control // Messages } else if (chunkStreamId >= 64 && chunkStreamId <= 319) { // 2 byte // version out.writeByte(fmt << 6 | 0); out.writeByte(chunkStreamId - 64); } else { // 3 byte version out.writeByte(fmt << 6 | 1); int h = chunkStreamId - 64; out.write16BitLittleEndian(h); } if (fmt == 0 || fmt == 1 || fmt == 2) { // type 0, type 1, type 2 header if (timestamp >= 0x00FFFFFF) timestamp = 0x00FFFFFF; // send extended time stamp out.write24Bit((int) timestamp); } if (fmt == 0 || fmt == 1) { // type 0, type 1 header out.write24Bit(size); out.writeByte(type); } if (fmt == 0) { // type 0 header out.write32BitLittleEndian(streamId); } if (fmt == 3) { // type 3 header } // write extended time stamp if ((fmt == 0 || fmt == 1 || fmt == 2) && timestamp >= 0x00FFFFFF) { out.write32Bit(timestamp); } } }
Java
package com.ams.protocol.rtmp.client; import java.io.EOFException; import java.io.IOException; import java.net.InetSocketAddress; import java.util.HashMap; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.ams.io.network.connection.SocketConnector; import com.ams.protocol.rtmp.RtmpConnection; import com.ams.protocol.rtmp.RtmpException; import com.ams.protocol.rtmp.RtmpHandShake; import com.ams.protocol.rtmp.amf.AmfException; import com.ams.protocol.rtmp.amf.AmfValue; import com.ams.protocol.rtmp.message.RtmpMessage; import com.ams.protocol.rtmp.message.RtmpMessageCommand; import com.ams.protocol.rtmp.net.NetStream; import com.ams.protocol.rtmp.net.StreamPlayer; public class RtmpClient implements Runnable { final static private Logger logger = LoggerFactory .getLogger(RtmpClient.class); private static int DEFAULT_TIMEOUT = 60 * 1000; private SocketConnector conn; private RtmpConnection rtmp; private RtmpHandShake handshake; private final static int TANSACTION_ID = 1; private final static int CHANNEL_RTMP_COMMAND = 3; private final static int CHANNEL_RTMP_PUBLISH = 7; private final static String CREATE_STREAM_ID_KEY = "createStreamId"; private final static String PUBLISH_STREAM_ID_KEY = "publishStreamId"; private final static String PUBLISH_FILE_NAME_KEY = "publishFileName"; private final static String PUBLISH_PLAYER_KEY = "publishPlayer"; private HashMap<String, Object> context = new HashMap<String, Object>(); private boolean success = false; private String errorMsg = ""; private RtmpClientEventListener eventListener = null; private boolean running = true; public RtmpClient(String host, int port) throws IOException { conn = SocketConnector.connect(new InetSocketAddress(host, port)); rtmp = new RtmpConnection(conn); handshake = new RtmpHandShake(rtmp); if (!handShake()) throw new IOException("handshake failed"); Thread t = new Thread(this, "rtmp client"); // t.setDaemon(true); t.start(); } private void readResponse() throws IOException, AmfException, RtmpException { // waiting for data arriving rtmp.readRtmpMessage(); if (!rtmp.isRtmpMessageReady()) return; RtmpMessage message = rtmp.getCurrentMessage(); if (!(message instanceof RtmpMessageCommand)) return; RtmpMessageCommand msg = (RtmpMessageCommand) message; if (eventListener == null) return; if ("_result".equals(msg.getName())) { eventListener.onResult(msg.getArgs()); } else if ("onStatus".equals(msg.getName())) { eventListener.onStatus(msg.getArgs()); } synchronized (this) { notifyAll(); } } private boolean waitResponse() { boolean timeout = false; long start = System.currentTimeMillis(); try { synchronized (this) { wait(DEFAULT_TIMEOUT); } } catch (InterruptedException e) { } long now = System.currentTimeMillis(); if (now - start >= DEFAULT_TIMEOUT) { timeout = true; } if (timeout) { errorMsg = "Waitint response timeout"; } return !timeout; } public boolean connect(String app) throws IOException { success = false; errorMsg = ""; eventListener = new RtmpClientEventListener() { public void onResult(AmfValue[] result) { Map<String, AmfValue> r = result[1].object(); if ("NetConnection.Connect.Success".equals(r.get("code") .string())) { logger.debug("rtmp connected."); success = true; } } public void onStatus(AmfValue[] status) { Map<String, AmfValue> r = status[1].object(); if ("NetConnection.Error".equals(r.get("code").string())) { success = false; errorMsg = r.get("details").string(); } } }; AmfValue[] args = { AmfValue.newObject().put("app", app) }; RtmpMessage message = new RtmpMessageCommand("connect", TANSACTION_ID, args); rtmp.writeRtmpMessage(CHANNEL_RTMP_COMMAND, 0, 0, message); if (!waitResponse()) { success = false; } return success; } public int createStream() throws IOException { context.put(CREATE_STREAM_ID_KEY, -1); errorMsg = ""; eventListener = new RtmpClientEventListener() { public void onResult(AmfValue[] result) { int streamId = result[1].integer(); context.put(CREATE_STREAM_ID_KEY, streamId); logger.debug("rtmp stream created."); } public void onStatus(AmfValue[] status) { } }; AmfValue[] args = { new AmfValue(null) }; RtmpMessage message = new RtmpMessageCommand("createStream", TANSACTION_ID, args); rtmp.writeRtmpMessage(CHANNEL_RTMP_COMMAND, 0, 0, message); if (!waitResponse()) { context.put(CREATE_STREAM_ID_KEY, -1); } return (Integer) context.get(CREATE_STREAM_ID_KEY); } public boolean publish(int streamId, String publishName, String fileName) throws IOException { success = false; errorMsg = ""; context.put(PUBLISH_STREAM_ID_KEY, streamId); context.put(PUBLISH_FILE_NAME_KEY, fileName); eventListener = new RtmpClientEventListener() { public void onResult(AmfValue[] result) { } public void onStatus(AmfValue[] status) { Map<String, AmfValue> result = status[1].object(); String level = result.get("level").string(); if ("status".equals(level)) { int streamId = (Integer) context.get(PUBLISH_STREAM_ID_KEY); String fileName = (String) context .get(PUBLISH_FILE_NAME_KEY); NetStream stream = new NetStream(rtmp, streamId); try { StreamPlayer player = StreamPlayer.createPlayer(stream, null, fileName); if (player != null) { player.seek(0); context.put(PUBLISH_PLAYER_KEY, player); logger.debug("rtmp stream start to publish."); success = true; } } catch (IOException e) { logger.debug(e.getMessage()); } } else { errorMsg = result.get("details").string(); } } }; AmfValue[] args = AmfValue.array(null, publishName, "live"); RtmpMessage message = new RtmpMessageCommand("publish", TANSACTION_ID, args); rtmp.writeRtmpMessage(CHANNEL_RTMP_PUBLISH, streamId, 0, message); if (!waitResponse()) { success = false; } return success; } public void closeStream(int streamId) throws IOException { AmfValue[] args = { new AmfValue(null) }; RtmpMessage message = new RtmpMessageCommand("closeStream", 0, args); rtmp.writeRtmpMessage(CHANNEL_RTMP_COMMAND, streamId, 0, message); success = true; errorMsg = ""; logger.debug("rtmp stream closed."); } public NetStream createNetStream(int streamId) { return new NetStream(rtmp, streamId); } public void close() { running = false; } private boolean handShake() { boolean success = true; while (!handshake.isHandshakeDone()) { try { handshake.doClientHandshake(); // write to socket channel conn.flush(); } catch (Exception e) { success = false; break; } } return success; } public void run() { try { while (running) { StreamPlayer player = (StreamPlayer) context .get(PUBLISH_PLAYER_KEY); if (player != null) { player.play(); } readResponse(); // write to socket channel conn.flush(); } } catch (EOFException e) { Integer streamId = (Integer) context.get(PUBLISH_STREAM_ID_KEY); if (streamId != null) try { closeStream(streamId); } catch (IOException e1) { } } catch (Exception e) { } conn.close(); } public String getErrorMsg() { return errorMsg; } }
Java
package com.ams.protocol.rtmp.client; import com.ams.protocol.rtmp.amf.AmfValue; public interface RtmpClientEventListener { public void onResult(AmfValue[] result); public void onStatus(AmfValue[] status); }
Java
package com.ams.protocol.rtmp.message; public class RtmpMessageWindowAckSize extends RtmpMessage { private int size; public RtmpMessageWindowAckSize(int size) { super(MESSAGE_WINDOW_ACK_SIZE); this.size = size; } public int getSize() { return size; } }
Java
package com.ams.protocol.rtmp.message; import com.ams.protocol.rtmp.amf.AmfValue; public class RtmpMessageCommand extends RtmpMessage { private String name; private int transactionId; private AmfValue[] args; public RtmpMessageCommand(String name, int transactionId, AmfValue[] args) { super(MESSAGE_AMF0_COMMAND); this.name = name; this.transactionId = transactionId; this.args = args; } public AmfValue[] getArgs() { return args; } public AmfValue getCommandObject() { return args[0]; } public int getTransactionId() { return transactionId; } public String getName() { return name; } }
Java
package com.ams.protocol.rtmp.message; public class RtmpMessageAbort extends RtmpMessage { private int streamId; public RtmpMessageAbort(int streamId) { super(MESSAGE_ABORT); this.streamId = streamId; } public int getStreamId() { return streamId; } }
Java
package com.ams.protocol.rtmp.message; public class RtmpMessageChunkSize extends RtmpMessage { private int chunkSize; public RtmpMessageChunkSize(int chunkSize) { super(MESSAGE_CHUNK_SIZE); this.chunkSize = chunkSize; } public int getChunkSize() { return chunkSize; } }
Java
package com.ams.protocol.rtmp.message; import com.ams.io.BufferList; public class RtmpMessageUnknown extends RtmpMessage { private int messageType; private BufferList data; public RtmpMessageUnknown(int type, BufferList data) { super(MESSAGE_UNKNOWN); this.messageType = type; this.data = data; } public int getMessageType() { return messageType; } public BufferList getData() { return data; } }
Java
package com.ams.protocol.rtmp.message; public class RtmpMessagePeerBandwidth extends RtmpMessage { private int windowAckSize; private byte limitType; public RtmpMessagePeerBandwidth(int windowAckSize, byte limitTypemitType) { super(MESSAGE_PEER_BANDWIDTH); this.windowAckSize = windowAckSize; this.limitType = limitTypemitType; } public int getWindowAckSize() { return windowAckSize; } public byte getLimitType() { return limitType; } }
Java
package com.ams.protocol.rtmp.message; import com.ams.io.BufferList; public class RtmpMessageAudio extends RtmpMessage { private BufferList data; public RtmpMessageAudio(BufferList data) { super(MESSAGE_AUDIO); this.data = data; } public BufferList getData() { return data; } }
Java
package com.ams.protocol.rtmp.message; import com.ams.protocol.rtmp.so.SoMessage; public class RtmpMessageSharedObject extends RtmpMessage { private SoMessage data; public RtmpMessageSharedObject(SoMessage data) { super(MESSAGE_SHARED_OBJECT); this.data = data; } public SoMessage getData() { return data; } }
Java
package com.ams.protocol.rtmp.message; public class RtmpMessageAck extends RtmpMessage { private int bytes; public RtmpMessageAck(int bytes) { super(MESSAGE_ACK); this.bytes = bytes; } public int getBytes() { return bytes; } }
Java
package com.ams.protocol.rtmp.message; import com.ams.media.MediaMessage; public class RtmpMessage { /* * 01 Protocol control message 1, Set Chunk Size 02 Protocol control message * 2, Abort Message 03 Protocol control message 3, Acknowledgement 04 * Protocol control message 4, User Control Message 05 Protocol control * message 5, Window Acknowledgement Size 06 Protocol control message 6, Set * Peer Bandwidth 07 Protocol control message 7, used between edge server * and origin server 08 Audio Data packet containing audio 09 Video Data * packet containing video data 0F AMF3 data message 11 AMF3 command message * 12 AMF0 data message 13 Shared Object has subtypes 14 AMF0 command * message 16 Aggregate message [FMS3] Set of one or more FLV tags, as * documented on the Flash Video (FLV) page. Each tag will have an 11 byte * header - [1 byte Type][3 bytes Size][3 bytes Timestamp][1 byte timestamp * extention][3 bytes streamID], followed by the body, followed by a 4 byte * footer containing the size of the body. */ public final static int MESSAGE_CHUNK_SIZE = 0x01; public final static int MESSAGE_ABORT = 0x02; public final static int MESSAGE_ACK = 0x03; public final static int MESSAGE_USER_CONTROL = 0x04; public final static int MESSAGE_WINDOW_ACK_SIZE = 0x05; public final static int MESSAGE_PEER_BANDWIDTH = 0x06; public final static int MESSAGE_AUDIO = 0x08; public final static int MESSAGE_VIDEO = 0x09; public final static int MESSAGE_AMF3_DATA = 0x0F; public final static int MESSAGE_AMF3_COMMAND = 0x11; public final static int MESSAGE_AMF0_DATA = 0x12; public final static int MESSAGE_AMF0_COMMAND = 0x14; public final static int MESSAGE_SHARED_OBJECT = 0x13; public final static int MESSAGE_AGGREGATE = 0x16; public final static int MESSAGE_UNKNOWN = 0xFF; protected int type = 0; public RtmpMessage(int type) { this.type = type; } public int getType() { return type; } public MediaMessage toMediaMessage(long timestamp) { MediaMessage mediaMessage = null; switch (type) { case RtmpMessage.MESSAGE_AUDIO: RtmpMessageAudio audio = (RtmpMessageAudio) this; mediaMessage = new MediaMessage(MediaMessage.MEDIA_AUDIO, timestamp, audio.getData()); break; case RtmpMessage.MESSAGE_VIDEO: RtmpMessageVideo video = (RtmpMessageVideo) this; mediaMessage = new MediaMessage(MediaMessage.MEDIA_VIDEO, timestamp, video.getData()); break; case RtmpMessage.MESSAGE_AMF0_DATA: RtmpMessageData m = (RtmpMessageData) this; mediaMessage = new MediaMessage(MediaMessage.MEDIA_META, timestamp, m.getData()); break; } return mediaMessage; } }
Java
package com.ams.protocol.rtmp.message; import com.ams.io.BufferList; public class RtmpMessageData extends RtmpMessage { private BufferList data; public RtmpMessageData(BufferList data) { super(MESSAGE_AMF0_DATA); this.data = data; } public BufferList getData() { return data; } }
Java
package com.ams.protocol.rtmp.message; import com.ams.io.BufferList; public class RtmpMessageVideo extends RtmpMessage { private BufferList data; public RtmpMessageVideo(BufferList data) { super(MESSAGE_VIDEO); this.data = data; } public BufferList getData() { return data; } }
Java
package com.ams.protocol.rtmp.message; public class RtmpMessageUserControl extends RtmpMessage { public final static int EVT_STREAM_BEGIN = 0; public final static int EVT_STREAM_EOF = 1; public final static int EVT_STREAM_DRY = 2; public final static int EVT_SET_BUFFER_LENGTH = 3; public final static int EVT_STREAM_IS_RECORDED = 4; public final static int EVT_PING_REQUEST = 6; public final static int EVT_PING_RESPONSE = 7; public final static int EVT_UNKNOW = 0xFF; private int event; private int streamId = -1; private int timestamp = -1; public RtmpMessageUserControl(int event, int streamId, int timestamp) { super(MESSAGE_USER_CONTROL); this.event = event; this.streamId = streamId; this.timestamp = timestamp; } public RtmpMessageUserControl(int event, int streamId) { super(MESSAGE_USER_CONTROL); this.event = event; this.streamId = streamId; } public int getStreamId() { return streamId; } public int getEvent() { return event; } public int getTimestamp() { return timestamp; } }
Java
package com.ams.protocol.rtmp.so; import java.util.Map; import com.ams.protocol.rtmp.amf.AmfValue; public class SoEventChange extends SoEvent { private Map<String, AmfValue> data; public SoEventChange(Map<String, AmfValue> data) { super(SO_EVT_CHANGE); this.data = data; } public Map<String, AmfValue> getData() { return data; } }
Java
package com.ams.protocol.rtmp.so; import com.ams.protocol.rtmp.amf.AmfValue; public class SoEventSendMessage extends SoEvent { private AmfValue msg; public SoEventSendMessage(AmfValue msg) { super(SO_EVT_SEND_MESSAGE); this.msg = msg; } public AmfValue getMsg() { return msg; } }
Java
package com.ams.protocol.rtmp.so; public class SoEventStatus extends SoEvent { private String msg; private String msgType; public SoEventStatus(String msg, String msgType) { super(SO_EVT_STATUS); this.msg = msg; this.msgType = msgType; } public String getMsg() { return msg; } public String getMsgType() { return msgType; } }
Java
package com.ams.protocol.rtmp.so; public class SoEventRequestRemove extends SoEvent { private String name; public SoEventRequestRemove(String name) { super(SO_EVT_REQUEST_REMOVE); this.name = name; } public String getName() { return name; } }
Java
package com.ams.protocol.rtmp.so; public class SoEventSuceess extends SoEvent { private String name; public SoEventSuceess(String name) { super(SO_EVT_SUCCESS); this.name = name; } public String getName() { return name; } }
Java
package com.ams.protocol.rtmp.so; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.EOFException; import java.io.IOException; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import com.ams.protocol.rtmp.amf.Amf0Deserializer; import com.ams.protocol.rtmp.amf.Amf0Serializer; import com.ams.protocol.rtmp.amf.AmfException; import com.ams.protocol.rtmp.amf.AmfValue; public class SoEvent { public static final int SO_EVT_USE = 1; public static final int SO_EVT_RELEASE = 2; public static final int SO_EVT_REQUEST_CHANGE = 3; public static final int SO_EVT_CHANGE = 4; public static final int SO_EVT_SUCCESS = 5; public static final int SO_EVT_SEND_MESSAGE = 6; public static final int SO_EVT_STATUS = 7; public static final int SO_EVT_CLEAR = 8; public static final int SO_EVT_REMOVE = 9; public static final int SO_EVT_REQUEST_REMOVE = 10; public static final int SO_EVT_USE_SUCCESS = 11; private int kind = 0; public SoEvent(int kind) { this.kind = kind; } public int getKind() { return kind; } public static SoEvent read(DataInputStream in, int kind, int size) throws IOException, AmfException { Amf0Deserializer deserializer = new Amf0Deserializer(in); SoEvent event = null; switch (kind) { case SoEvent.SO_EVT_USE: event = new SoEvent(SoEvent.SO_EVT_USE); break; case SoEvent.SO_EVT_RELEASE: event = new SoEvent(SoEvent.SO_EVT_RELEASE); break; case SoEvent.SO_EVT_REQUEST_CHANGE: event = new SoEventRequestChange(in.readUTF(), deserializer.read()); break; case SoEvent.SO_EVT_CHANGE: Map<String, AmfValue> hash = new LinkedHashMap<String, AmfValue>(); while (true) { String key = null; try { key = in.readUTF(); } catch (EOFException e) { break; } hash.put(key, deserializer.read()); } event = new SoEventChange(hash); break; case SoEvent.SO_EVT_SUCCESS: event = new SoEventSuceess(in.readUTF()); break; case SoEvent.SO_EVT_SEND_MESSAGE: event = new SoEventSendMessage(deserializer.read()); break; case SoEvent.SO_EVT_STATUS: String msg = in.readUTF(); String type = in.readUTF(); event = new SoEventStatus(msg, type); break; case SoEvent.SO_EVT_CLEAR: event = new SoEvent(SoEvent.SO_EVT_CLEAR); break; case SoEvent.SO_EVT_REMOVE: event = new SoEvent(SoEvent.SO_EVT_REMOVE); break; case SoEvent.SO_EVT_REQUEST_REMOVE: event = new SoEventRequestRemove(in.readUTF()); break; case SoEvent.SO_EVT_USE_SUCCESS: event = new SoEvent(SoEvent.SO_EVT_USE_SUCCESS); } return event; } public static void write(DataOutputStream out, SoEvent event) throws IOException { Amf0Serializer serializer = new Amf0Serializer(out); switch (event.getKind()) { case SoEvent.SO_EVT_USE: case SoEvent.SO_EVT_RELEASE: case SoEvent.SO_EVT_CLEAR: case SoEvent.SO_EVT_REMOVE: case SoEvent.SO_EVT_USE_SUCCESS: // nothing break; case SoEvent.SO_EVT_REQUEST_CHANGE: out.writeUTF(((SoEventRequestChange) event).getName()); serializer.write(((SoEventRequestChange) event).getValue()); break; case SoEvent.SO_EVT_CHANGE: Map<String, AmfValue> data = ((SoEventChange) event).getData(); Iterator<String> it = data.keySet().iterator(); while (it.hasNext()) { String key = it.next(); out.writeUTF(key); serializer.write(data.get(key)); } break; case SoEvent.SO_EVT_SUCCESS: out.writeUTF(((SoEventSuceess) event).getName()); break; case SoEvent.SO_EVT_SEND_MESSAGE: serializer.write(((SoEventSendMessage) event).getMsg()); break; case SoEvent.SO_EVT_STATUS: out.writeUTF(((SoEventStatus) event).getMsg()); out.writeUTF(((SoEventStatus) event).getMsgType()); break; case SoEvent.SO_EVT_REQUEST_REMOVE: out.writeUTF(((SoEventRequestRemove) event).getName()); break; } } }
Java
package com.ams.protocol.rtmp.so; import com.ams.protocol.rtmp.amf.AmfValue; public class SoEventRequestChange extends SoEvent { private String name; private AmfValue value; public SoEventRequestChange(String name, AmfValue value) { super(SO_EVT_REQUEST_CHANGE); this.name = name; this.value = value; } public String getName() { return name; } public AmfValue getValue() { return value; } }
Java
package com.ams.protocol.rtmp.so; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.EOFException; import java.io.IOException; import java.util.ArrayList; import com.ams.protocol.rtmp.amf.AmfException; public class SoMessage { private String name; private int version; private boolean persist; private int unknown; private ArrayList<SoEvent> events; public SoMessage(String name, int version, boolean persist, int unknown, ArrayList<SoEvent> events) { this.name = name; this.version = version; this.persist = persist; this.unknown = unknown; this.events = events; } public ArrayList<SoEvent> getEvents() { return events; } public String getName() { return name; } public boolean isPersist() { return persist; } public int getVersion() { return version; } public int getUnknown() { return unknown; } public static SoMessage read(DataInputStream in) throws IOException, AmfException { String name = in.readUTF(); int version = in.readInt(); boolean persist = (in.readInt() == 2); int unknown = in.readInt(); ArrayList<SoEvent> events = new ArrayList<SoEvent>(); while (true) { int kind; try { kind = in.readByte() & 0xFF; } catch (EOFException e) { break; } int size = in.readInt(); SoEvent event = SoEvent.read(in, kind, size); if (event != null) { events.add(event); } } return new SoMessage(name, version, persist, unknown, events); } public static void write(DataOutputStream out, SoMessage so) throws IOException { out.writeUTF(so.getName()); out.writeInt(so.getVersion()); out.writeInt(so.isPersist() ? 2 : 0); out.writeInt(so.getUnknown()); ArrayList<SoEvent> events = so.getEvents(); for (int i = 0, len = events.size(); i < len; i++) { SoEvent event = events.get(i); out.writeByte(event.getKind()); ByteArrayOutputStream bos = new ByteArrayOutputStream(); SoEvent.write(new DataOutputStream(bos), event); byte[] data = bos.toByteArray(); out.writeInt(data.length); out.write(data); } } }
Java
package com.ams.protocol.rtmp; import java.io.DataInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import com.ams.io.BufferList; import com.ams.io.BufferInputStream; import com.ams.protocol.rtmp.amf.Amf0Deserializer; import com.ams.protocol.rtmp.amf.Amf3Deserializer; import com.ams.protocol.rtmp.amf.AmfException; import com.ams.protocol.rtmp.amf.AmfSwitchToAmf3Exception; import com.ams.protocol.rtmp.amf.AmfValue; import com.ams.protocol.rtmp.message.RtmpMessage; import com.ams.protocol.rtmp.message.RtmpMessageAbort; import com.ams.protocol.rtmp.message.RtmpMessageAck; import com.ams.protocol.rtmp.message.RtmpMessageAudio; import com.ams.protocol.rtmp.message.RtmpMessageChunkSize; import com.ams.protocol.rtmp.message.RtmpMessageCommand; import com.ams.protocol.rtmp.message.RtmpMessageData; import com.ams.protocol.rtmp.message.RtmpMessagePeerBandwidth; import com.ams.protocol.rtmp.message.RtmpMessageSharedObject; import com.ams.protocol.rtmp.message.RtmpMessageUnknown; import com.ams.protocol.rtmp.message.RtmpMessageUserControl; import com.ams.protocol.rtmp.message.RtmpMessageVideo; import com.ams.protocol.rtmp.message.RtmpMessageWindowAckSize; import com.ams.protocol.rtmp.so.SoMessage; public class RtmpMessageDeserializer { private int readChunkSize = 128; protected HashMap<Integer, RtmpChunkDataReader> chunkDataMap; protected BufferInputStream in; public RtmpMessageDeserializer(BufferInputStream in) { super(); this.in = in; this.chunkDataMap = new HashMap<Integer, RtmpChunkDataReader>(); } public RtmpMessage read(RtmpHeader header) throws IOException, AmfException, RtmpException { int chunkStreamId = header.getChunkStreamId(); RtmpChunkDataReader chunkData = chunkDataMap.get(chunkStreamId); if (chunkData == null) { chunkData = new RtmpChunkDataReader(header); chunkDataMap.put(chunkStreamId, chunkData); } int remain = chunkData.getChunkSize(); if (remain > readChunkSize) { // continue to read chunkData.read(in, readChunkSize); return null; } chunkData.read(in, remain); // got a chunk data chunkDataMap.remove(chunkStreamId); return parseChunkData(chunkData); } private RtmpMessage parseChunkData(RtmpChunkDataReader chunk) throws IOException, AmfException, RtmpException { RtmpHeader header = chunk.getHeader(); BufferList data = chunk.getChunkData(); BufferInputStream bis = new BufferInputStream(data); switch (header.getType()) { case RtmpMessage.MESSAGE_USER_CONTROL: int event = bis.read16Bit(); int streamId = -1; int timestamp = -1; switch (event) { case RtmpMessageUserControl.EVT_STREAM_BEGIN: case RtmpMessageUserControl.EVT_STREAM_EOF: case RtmpMessageUserControl.EVT_STREAM_DRY: case RtmpMessageUserControl.EVT_STREAM_IS_RECORDED: streamId = (int) bis.read32Bit(); break; case RtmpMessageUserControl.EVT_SET_BUFFER_LENGTH: streamId = (int) bis.read32Bit(); timestamp = (int) bis.read32Bit(); // buffer length break; case RtmpMessageUserControl.EVT_PING_REQUEST: case RtmpMessageUserControl.EVT_PING_RESPONSE: timestamp = (int) bis.read32Bit(); // timestamp break; default: event = RtmpMessageUserControl.EVT_UNKNOW; } return new RtmpMessageUserControl(event, streamId, timestamp); case RtmpMessage.MESSAGE_AMF3_COMMAND: bis.readByte(); // no used byte, continue to amf0 parsing case RtmpMessage.MESSAGE_AMF0_COMMAND: { DataInputStream dis = new DataInputStream(bis); Amf0Deserializer amf0Deserializer = new Amf0Deserializer(dis); Amf3Deserializer amf3Deserializer = new Amf3Deserializer(dis); String name = amf0Deserializer.read().string(); int transactionId = amf0Deserializer.read().integer(); ArrayList<AmfValue> argArray = new ArrayList<AmfValue>(); boolean amf3Object = false; while (true) { try { if (amf3Object) { argArray.add(amf3Deserializer.read()); } else { argArray.add(amf0Deserializer.read()); } } catch (AmfSwitchToAmf3Exception e) { amf3Object = true; } catch (IOException e) { break; } } AmfValue[] args = new AmfValue[argArray.size()]; argArray.toArray(args); return new RtmpMessageCommand(name, transactionId, args); } case RtmpMessage.MESSAGE_VIDEO: return new RtmpMessageVideo(data); case RtmpMessage.MESSAGE_AUDIO: return new RtmpMessageAudio(data); case RtmpMessage.MESSAGE_AMF0_DATA: case RtmpMessage.MESSAGE_AMF3_DATA: return new RtmpMessageData(data); case RtmpMessage.MESSAGE_SHARED_OBJECT: SoMessage so = SoMessage.read(new DataInputStream(bis)); return new RtmpMessageSharedObject(so); case RtmpMessage.MESSAGE_CHUNK_SIZE: readChunkSize = (int) bis.read32Bit(); return new RtmpMessageChunkSize(readChunkSize); case RtmpMessage.MESSAGE_ABORT: return new RtmpMessageAbort((int) bis.read32Bit()); case RtmpMessage.MESSAGE_ACK: return new RtmpMessageAck((int) bis.read32Bit()); case RtmpMessage.MESSAGE_WINDOW_ACK_SIZE: return new RtmpMessageWindowAckSize((int) bis.read32Bit()); case RtmpMessage.MESSAGE_PEER_BANDWIDTH: int windowAckSize = (int) bis.read32Bit(); byte limitType = bis.readByte(); return new RtmpMessagePeerBandwidth(windowAckSize, limitType); // case RtmpMessage.MESSAGE_AGGREGATE: default: return new RtmpMessageUnknown(header.getType(), data); } } public int getReadChunkSize() { return readChunkSize; } public void setReadChunkSize(int readChunkSize) { this.readChunkSize = readChunkSize; } }
Java
package com.ams.protocol.rtmp; import java.io.IOException; import com.ams.io.BufferInputStream; import com.ams.io.BufferOutputStream; import com.ams.io.network.connection.Connection; import com.ams.protocol.rtmp.amf.*; import com.ams.protocol.rtmp.message.*; public class RtmpConnection { private Connection conn; private BufferInputStream in; private BufferOutputStream out; private RtmpHeaderDeserializer headerDeserializer; private RtmpMessageSerializer messageSerializer; private RtmpMessageDeserializer messageDeserializer; private RtmpHeader currentHeader = null; private RtmpMessage currentMessage = null; public RtmpConnection(Connection conn) { this.conn = conn; this.in = conn.getInputStream(); this.out = conn.getOutputStream(); this.headerDeserializer = new RtmpHeaderDeserializer(in); this.messageSerializer = new RtmpMessageSerializer(out); this.messageDeserializer = new RtmpMessageDeserializer(in); } public boolean readRtmpMessage() throws IOException, AmfException, RtmpException { if (conn.available() == 0) { return false; } if (currentHeader != null && currentMessage != null) { currentHeader = null; currentMessage = null; } // read header every time, a message maybe break into several chunks if (currentHeader == null) { currentHeader = headerDeserializer.read(); } if (currentMessage == null) { currentMessage = messageDeserializer.read(currentHeader); if (currentMessage == null) { // continue read header currentHeader = null; } } return true; } public boolean isRtmpMessageReady() { return (currentHeader != null && currentMessage != null); } public synchronized void writeRtmpMessage(int chunkStreamId, int streamId, long timestamp, RtmpMessage message) throws IOException { messageSerializer.write(chunkStreamId, streamId, timestamp, message); } public synchronized void writeProtocolControlMessage(RtmpMessage message) throws IOException { messageSerializer.write(2, 0, 0, message); } public Connection getConnector() { return conn; } public RtmpHeader getCurrentHeader() { return currentHeader; } public RtmpMessage getCurrentMessage() { return currentMessage; } public void flush() throws IOException { conn.flush(); } }
Java
package com.ams.protocol.rtmp.amf; import java.io.DataInputStream; import java.util.ArrayList; import java.util.Date; import java.util.LinkedHashMap; import java.util.Map; import java.io.IOException; public class Amf0Deserializer { protected ArrayList<AmfValue> storedObjects = new ArrayList<AmfValue>(); protected ArrayList<AmfValue> storedStrings = new ArrayList<AmfValue>(); protected DataInputStream in; public Amf0Deserializer(DataInputStream in) { this.in = in; } private String readLongString() throws IOException { int len = in.readInt(); // 32bit read byte[] buf = new byte[len]; in.read(buf, 0, len); return new String(buf, "UTF-8"); } private AmfValue readByType(int type) throws IOException, AmfException { AmfValue amfValue = null; switch (type) { case 0x00: // This specifies the data in the AMF packet is a numeric value. // All numeric values in Flash are 64 bit, big-endian. amfValue = new AmfValue(in.readDouble()); break; case 0x01: // This specifies the data in the AMF packet is a boolean value. amfValue = new AmfValue(in.readBoolean()); break; case 0x02: // This specifies the data in the AMF packet is an ASCII string. amfValue = new AmfValue(in.readUTF()); break; case 0x04: // This specifies the data in the AMF packet is a Flash movie. break; case 0x05: // This specifies the data in the AMF packet is a NULL value. amfValue = new AmfValue(null); break; case 0x06: // This specifies the data in the AMF packet is a undefined. amfValue = new AmfValue(); break; case 0x07: // This specifies the data in the AMF packet is a reference. break; case 0x03: // This specifies the data in the AMF packet is a Flash object. case 0x08: // This specifies the data in the AMF packet is a ECMA array. Map<String, AmfValue> hash = new LinkedHashMap<String, AmfValue>(); boolean isEcmaArray = (type == 0x08); int size = -1; if (isEcmaArray) { size = in.readInt(); // 32bit read } while (true) { String key = in.readUTF(); int k = in.readByte() & 0xFF; if (k == 0x09) break; // end of Object hash.put(key, readByType(k)); } amfValue = new AmfValue(hash); break; case 0x09: // This specifies the data in the AMF packet is the end of an object // definition. break; case 0x0A: // This specifies the data in the AMF packet is a Strict array. ArrayList<AmfValue> array = new ArrayList<AmfValue>(); int len = in.readInt(); for (int i = 0; i < len; i++) { int k = in.readByte() & 0xFF; array.add(readByType(k)); } amfValue = new AmfValue(array); break; case 0x0B: // This specifies the data in the AMF packet is a date. double time_ms = in.readDouble(); int tz_min = in.readInt(); // 16bit amfValue = new AmfValue(new Date( (long) (time_ms + tz_min * 60 * 1000.0))); break; case 0x0C: // This specifies the data in the AMF packet is a multi-byte string. amfValue = new AmfValue(readLongString()); // 32bit case 0x0D: // This specifies the data in the AMF packet is a an unsupported // feature. break; case 0x0E: // This specifies the data in the AMF packet is a record set. break; case 0x0F: // This specifies the data in the AMF packet is a XML object. amfValue = new AmfXml(readLongString()); // 32bit break; case 0x10: // This specifies the data in the AMF packet is a typed object. case 0x11: // the AMF 0 format was extended to allow an AMF 0 encoding context // to be switched to AMF 3. throw new AmfSwitchToAmf3Exception("Switch To AMF3"); default: throw new AmfException("Unknown AMF0: " + type); } return amfValue; } public AmfValue read() throws IOException, AmfException { int type = in.readByte() & 0xFF; return readByType(type); } }
Java
package com.ams.protocol.rtmp.amf; public class AmfSwitchToAmf3Exception extends AmfException { private static final long serialVersionUID = 1L; public AmfSwitchToAmf3Exception() { super(); } public AmfSwitchToAmf3Exception(String arg0) { super(arg0); } }
Java
package com.ams.protocol.rtmp.amf; import java.io.DataOutputStream; import java.util.Date; import java.util.Map; import java.io.IOException; public class Amf0Serializer { protected DataOutputStream out; public Amf0Serializer(DataOutputStream out) { this.out = out; } private void writeLongString(String s) throws IOException { byte[] b = s.getBytes("UTF-8"); out.writeInt(b.length); out.write(b); } public void write(AmfValue amfValue) throws IOException { switch (amfValue.getKind()) { case AmfValue.AMF_INT: case AmfValue.AMF_NUMBER: out.writeByte(0x00); out.writeDouble(amfValue.number()); break; case AmfValue.AMF_BOOL: out.writeByte(0x01); out.writeBoolean(amfValue.bool()); break; case AmfValue.AMF_STRING: String s = amfValue.string(); if (s.length() <= 0xFFFF) { out.writeByte(0x02); out.writeUTF(s); } else { out.writeByte(0x0C); writeLongString(s); } break; case AmfValue.AMF_OBJECT: if (amfValue.isEcmaArray()) { out.writeByte(0x08); // ECMA Array out.writeInt(0); } else { out.writeByte(0x03); } Map<String, AmfValue> v = amfValue.object(); for (String key : v.keySet()) { out.writeUTF(key); write(v.get(key)); } // end of Object out.writeByte(0); out.writeByte(0); out.writeByte(0x09); break; case AmfValue.AMF_ARRAY: out.writeByte(0x0A); AmfValue[] array = amfValue.array(); int len = array.length; out.writeInt(len); for (int i = 0; i < len; i++) { write(array[i]); } break; case AmfValue.AMF_DATE: Date d = amfValue.date(); out.writeDouble(d.getTime()); out.writeShort(0); // loose TZ break; case AmfValue.AMF_XML: String xml = amfValue.xml(); out.writeByte(0x0F); writeLongString(xml); break; case AmfValue.AMF_NULL: out.writeByte(0x05); break; case AmfValue.AMF_UNDEFINED: out.writeByte(0x06); break; } } }
Java
package com.ams.protocol.rtmp.amf; public class AmfXml extends AmfValue { public AmfXml(String value) { this.kind = AMF_XML; this.value = value; } }
Java
package com.ams.protocol.rtmp.amf; import java.io.DataOutputStream; import java.io.IOException; import java.util.Date; import java.util.LinkedHashMap; import java.util.Map; import com.ams.io.BufferList; import com.ams.io.BufferOutputStream; public class AmfValue { public final static int AMF_INT = 1; public final static int AMF_NUMBER = 2; public final static int AMF_BOOL = 3; public final static int AMF_STRING = 4; public final static int AMF_OBJECT = 5; public final static int AMF_ARRAY = 6; public final static int AMF_DATE = 7; public final static int AMF_XML = 8; public final static int AMF_NULL = 9; public final static int AMF_UNDEFINED = 0; protected int kind = 0; protected Object value; protected boolean ecmaArray = false; public AmfValue() { this.kind = AMF_UNDEFINED; } public AmfValue(Object value) { if (value == null) this.kind = AMF_NULL; else if (value instanceof Byte || value instanceof Short || value instanceof Integer || value instanceof Long) this.kind = AMF_INT; else if (value instanceof Float || value instanceof Double) this.kind = AMF_NUMBER; else if (value instanceof Boolean) this.kind = AMF_BOOL; else if (value instanceof String) this.kind = AMF_STRING; else if (value instanceof Map) this.kind = AMF_OBJECT; else if (value instanceof Object[]) this.kind = AMF_ARRAY; else if (value instanceof Date) this.kind = AMF_DATE; this.value = value; } public AmfValue put(String key, Object v) { object().put(key, v instanceof AmfValue ? (AmfValue) v : new AmfValue(v)); return this; } public static AmfValue newObject() { return new AmfValue(new LinkedHashMap<String, AmfValue>()); } public static AmfValue newEcmaArray() { AmfValue value = new AmfValue(new LinkedHashMap<String, AmfValue>()); value.setEcmaArray(true); return value; } public static AmfValue newArray(Object... values) { AmfValue[] array = new AmfValue[values.length]; for (int i = 0, len = values.length; i < len; i++) { Object v = values[i]; array[i] = v instanceof AmfValue ? (AmfValue) v : new AmfValue(v); } return new AmfValue(array); } public static AmfValue[] array(Object... values) { AmfValue[] array = new AmfValue[values.length]; for (int i = 0, len = values.length; i < len; i++) { Object v = values[i]; array[i] = v instanceof AmfValue ? (AmfValue) v : new AmfValue(v); } return array; } public int getKind() { return kind; } public Integer integer() { if (value == null) { throw new NullPointerException("parameter is null"); } if (kind != AmfValue.AMF_INT && kind != AmfValue.AMF_NUMBER) { throw new IllegalArgumentException( "parameter is not a Amf Integer or Amf Number"); } return ((Number) value).intValue(); } public Double number() { if (value == null) { throw new NullPointerException("parameter is null"); } if (kind != AmfValue.AMF_INT && kind != AmfValue.AMF_NUMBER) { throw new IllegalArgumentException( "parameter is not a Amf Integer or Amf Number"); } return ((Number) value).doubleValue(); } public Boolean bool() { if (value == null) { throw new NullPointerException("parameter is null"); } if (kind != AmfValue.AMF_BOOL) { throw new IllegalArgumentException("parameter is not a Amf Bool"); } return (Boolean) value; } public String string() { if (value == null) { throw new NullPointerException("parameter is null"); } if (kind != AmfValue.AMF_STRING) { throw new IllegalArgumentException("parameter is not a Amf String"); } return (String) value; } public AmfValue[] array() { if (value == null) { throw new NullPointerException("parameter is null"); } if (kind != AmfValue.AMF_ARRAY) { throw new IllegalArgumentException("parameter is not a Amf Array"); } return (AmfValue[]) value; } public Map<String, AmfValue> object() { if (value == null) { throw new NullPointerException("parameter is null"); } if (kind != AmfValue.AMF_ARRAY && kind != AmfValue.AMF_OBJECT) { throw new IllegalArgumentException("parameter is not a Amf Object"); } return (Map<String, AmfValue>) value; } public Date date() { if (value == null) { throw new NullPointerException("parameter is null"); } if (kind != AmfValue.AMF_DATE) { throw new IllegalArgumentException("parameter is not a Amf Date"); } return (Date) value; } public String xml() { if (value == null) { throw new NullPointerException("parameter is null"); } if (kind != AmfValue.AMF_XML) { throw new IllegalArgumentException("parameter is not a Amf Xml"); } return (String) value; } public boolean isNull() { return kind == AmfValue.AMF_NULL; } public boolean isUndefined() { return kind == AmfValue.AMF_UNDEFINED; } public String toString() { String result; boolean first; switch (kind) { case AmfValue.AMF_INT: case AmfValue.AMF_NUMBER: case AmfValue.AMF_BOOL: case AmfValue.AMF_DATE: return value.toString(); case AmfValue.AMF_STRING: return "'" + (String) value + "'"; case AmfValue.AMF_OBJECT: Map<String, AmfValue> v = object(); result = "{"; first = true; for (String key : v.keySet()) { result += (first ? " " : ", ") + key + " => " + v.get(key).toString(); first = false; } result += "}"; return result; case AmfValue.AMF_ARRAY: AmfValue[] array = array(); result = "["; first = true; int len = array.length; for (int i = 0; i < len; i++) { result += (first ? " " : ", ") + array[i].toString(); first = false; } result += "]"; return result; case AmfValue.AMF_XML: return (String) value; case AmfValue.AMF_NULL: return "null"; case AmfValue.AMF_UNDEFINED: return "undefined"; } return ""; } public boolean isEcmaArray() { return ecmaArray; } public void setEcmaArray(boolean ecmaArray) { this.ecmaArray = ecmaArray; } public static BufferList toBinary(AmfValue[] values) { BufferList buf = new BufferList(); BufferOutputStream out = new BufferOutputStream(buf); Amf0Serializer serializer = new Amf0Serializer( new DataOutputStream(out)); try { for (int i = 0, len = values.length; i < len; i++) { serializer.write(values[i]); } out.flush(); } catch (IOException e) { return null; } return buf; } }
Java
package com.ams.protocol.rtmp.amf; import java.io.DataOutputStream; import java.util.ArrayList; import java.util.Date; import java.util.Map; import java.io.IOException; public class Amf3Serializer { protected ArrayList<String> stringRefTable = new ArrayList<String>(); protected ArrayList<AmfValue> objectRefTable = new ArrayList<AmfValue>(); protected DataOutputStream out; public Amf3Serializer(DataOutputStream out) { this.out = out; } private void writeAmf3Int(int value) throws IOException { // Sign contraction - the high order bit of the resulting value must // match every bit removed from the number // Clear 3 bits value &= 0x1fffffff; if (value < 0x80) { out.writeByte(value); } else if (value < 0x4000) { out.writeByte(value >> 7 & 0x7f | 0x80); out.writeByte(value & 0x7f); } else if (value < 0x200000) { out.writeByte(value >> 14 & 0x7f | 0x80); out.writeByte(value >> 7 & 0x7f | 0x80); out.writeByte(value & 0x7f); } else { out.writeByte(value >> 22 & 0x7f | 0x80); out.writeByte(value >> 15 & 0x7f | 0x80); out.writeByte(value >> 8 & 0x7f | 0x80); out.writeByte(value & 0xff); } } private void writeAmf3RefInt(int value) throws IOException { writeAmf3Int(value << 1); // low bit is 0 } private void writeAmf3ValueInt(int value) throws IOException { writeAmf3Int(value << 1 + 1); // low bit is 1 } private void writeAmf3EmptyString() throws IOException { out.writeByte(0x01); } private void writeAmf3String(String s) throws IOException { if (s.length() == 0) { // Write 0x01 to specify the empty string writeAmf3EmptyString(); } else { for (int i = 0, len = stringRefTable.size(); i < len; i++) { if (s.equals(stringRefTable.get(i))) { writeAmf3RefInt(i); return; } } byte[] b = s.getBytes("UTF-8"); writeAmf3ValueInt(b.length); out.write(b); stringRefTable.add(s); } } private void writeAmf3Object(AmfValue amfValue) throws IOException { for (int i = 0, len = objectRefTable.size(); i < len; i++) { if (amfValue.equals(objectRefTable.get(i))) { writeAmf3RefInt(i); return; } } writeAmf3ValueInt(0); Map<String, AmfValue> obj = amfValue.object(); for (String key : obj.keySet()) { writeAmf3String(key); write(obj.get(key)); } // end of Object writeAmf3EmptyString(); objectRefTable.add(amfValue); } private void writeAmf3Array(AmfValue amfValue) throws IOException { for (int i = 0, len = objectRefTable.size(); i < len; i++) { if (amfValue.equals(objectRefTable.get(i))) { writeAmf3RefInt(i); return; } } AmfValue[] array = amfValue.array(); int len = array.length; writeAmf3ValueInt(len); writeAmf3EmptyString(); for (int i = 0; i < len; i++) { write(array[i]); } objectRefTable.add(amfValue); } public void write(AmfValue amfValue) throws IOException { switch (amfValue.getKind()) { case AmfValue.AMF_INT: int v = amfValue.integer(); if (v >= -0x10000000 && v <= 0xFFFFFFF) { // check valid range for // 29bits out.writeByte(0x04); writeAmf3Int(v); } else { // overflow condition would occur upon int conversion out.writeByte(0x05); out.writeDouble(v); } break; case AmfValue.AMF_NUMBER: out.writeByte(0x05); out.writeDouble(amfValue.number()); break; case AmfValue.AMF_BOOL: out.writeByte(amfValue.bool() ? 0x02 : 0x03); break; case AmfValue.AMF_STRING: out.writeByte(0x06); writeAmf3String(amfValue.string()); break; case AmfValue.AMF_OBJECT: // out.writeByte(0x0A); out.writeByte(0x09); writeAmf3Object(amfValue); break; case AmfValue.AMF_ARRAY: out.writeByte(0x09); writeAmf3Array(amfValue); break; case AmfValue.AMF_DATE: out.writeByte(0x08); writeAmf3Int(0x01); Date d = amfValue.date(); out.writeDouble(d.getTime()); break; case AmfValue.AMF_XML: out.writeByte(0x07); writeAmf3String(amfValue.string()); break; case AmfValue.AMF_NULL: out.writeByte(0x01); break; case AmfValue.AMF_UNDEFINED: out.writeByte(0x00); break; } } }
Java
package com.ams.protocol.rtmp.amf; public class AmfException extends Exception { private static final long serialVersionUID = 1L; public AmfException() { super(); } public AmfException(String arg0) { super(arg0); } }
Java
package com.ams.protocol.rtmp.amf; import java.io.DataInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.Map; public class Amf3Deserializer { protected ArrayList<String> stringRefTable = new ArrayList<String>(); protected ArrayList<AmfValue> objectRefTable = new ArrayList<AmfValue>(); protected DataInputStream in; public Amf3Deserializer(DataInputStream in) { this.in = in; } private int readAmf3Int() throws IOException { byte b1 = in.readByte(); if (b1 >= 0 && b1 <= 0x7f) { return b1; } byte b2 = in.readByte(); if (b2 >= 0 && b2 <= 0x7f) { return (b1 & 0x7f) << 7 | b2; } byte b3 = in.readByte(); if (b3 >= 0 && b3 <= 0x7f) { return (b1 & 0x7f) << 14 | (b2 & 0x7f) << 7 | b3; } byte b4 = in.readByte(); return (b1 & 0x7f) << 22 | (b2 & 0x7f) << 15 | (b3 & 0x7f) << 8 | b4; } private String readAmf3String() throws IOException { int v = readAmf3Int(); if (v == 1) { return ""; } if ((v & 0x01) == 0) { return stringRefTable.get(v >> 1); } byte[] b = new byte[v >> 1]; in.read(b); String str = new String(b, "UTF-8"); stringRefTable.add(str); return str; } private AmfValue readAmf3Array() throws IOException, AmfException { int v = readAmf3Int(); if ((v & 0x01) == 0) { // ref return objectRefTable.get(v >> 1); } int len = v >> 1; String s = readAmf3String(); if (s.equals("")) { // Strict Array ArrayList<AmfValue> array = new ArrayList<AmfValue>(); for (int i = 0; i < len; i++) { int k = in.readByte() & 0xFF; array.add(readByType(k)); } AmfValue obj = new AmfValue(array); objectRefTable.add(obj); return obj; } else { // assoc Array Map<String, AmfValue> hash = new LinkedHashMap<String, AmfValue>(); String key = s; while (true) { int k = in.readByte() & 0xFF; if (k == 0x01) break; // end of Object hash.put(key, readByType(k)); key = readAmf3String(); } AmfValue obj = new AmfValue(hash); objectRefTable.add(obj); return obj; } } private AmfValue readAmf3Object() throws IOException, AmfException { int v = readAmf3Int(); if ((v & 0x01) == 0) { // ref return objectRefTable.get(v >> 1); } readAmf3String(); // class name Map<String, AmfValue> hash = new LinkedHashMap<String, AmfValue>(); while (true) { String key = readAmf3String(); int k = in.readByte() & 0xFF; if (k == 0x01) break; // end of Object hash.put(key, readByType(k)); } AmfValue obj = new AmfValue(hash); objectRefTable.add(obj); return obj; } private AmfValue readByType(int type) throws IOException, AmfException { AmfValue amfValue = null; switch (type) { case 0x00: // This specifies the data in the AMF packet is a undefined. amfValue = new AmfValue(); break; case 0x01: // This specifies the data in the AMF packet is a NULL value. amfValue = new AmfValue(null); break; case 0x02: // This specifies the data in the AMF packet is a false boolean // value. amfValue = new AmfValue(false); break; case 0x03: // This specifies the data in the AMF packet is a true boolean // value. amfValue = new AmfValue(true); break; case 0x04: // This specifies the data in the AMF packet is a integer value. amfValue = new AmfValue(readAmf3Int()); break; case 0x05: // This specifies the data in the AMF packet is a double value. amfValue = new AmfValue(in.readDouble()); break; case 0x06: // This specifies the data in the AMF packet is a string value. amfValue = new AmfValue(readAmf3String()); break; case 0x07: // This specifies the data in the AMF packet is a xml doc value. // TODO break; case 0x08: // This specifies the data in the AMF packet is a date value. // TODO break; case 0x09: // This specifies the data in the AMF packet is a array value. amfValue = readAmf3Array(); break; case 0x0A: // This specifies the data in the AMF packet is a object value. amfValue = readAmf3Object(); break; case 0x0B: // This specifies the data in the AMF packet is a xml value. // TODO break; case 0x0C: // This specifies the data in the AMF packet is a byte array value. // TODO break; default: throw new AmfException("Unknown AMF3: " + type); } return amfValue; } public AmfValue read() throws IOException, AmfException { int type = in.readByte() & 0xFF; return readByType(type); } }
Java
package com.ams.protocol.rtmp; import java.io.IOException; import java.util.HashMap; import com.ams.io.BufferInputStream; public class RtmpHeaderDeserializer { private HashMap<Integer, RtmpHeader> chunkHeaderMap; private BufferInputStream in; public RtmpHeaderDeserializer(BufferInputStream in) { super(); this.in = in; this.chunkHeaderMap = new HashMap<Integer, RtmpHeader>(); } private RtmpHeader getLastHeader(int chunkStreamId) { RtmpHeader h = chunkHeaderMap.get(chunkStreamId); if (h == null) { h = new RtmpHeader(chunkStreamId, 0, 0, 0, 0); chunkHeaderMap.put(chunkStreamId, h); } return h; } public RtmpHeader read() throws IOException { int h = in.readByte() & 0xFF; // Chunk Basic Header int chunkStreamId = h & 0x3F; // 1 byte version if (chunkStreamId == 0) { // 2 byte version chunkStreamId = in.readByte() & 0xFF + 64; } else if (chunkStreamId == 1) { // 3 byte version chunkStreamId = in.read16BitLittleEndian() + 64; } RtmpHeader lastHeader = getLastHeader(chunkStreamId); int fmt = h >>> 6; long ts = 0; if (fmt == 0) { // type 0 header ts = in.read24Bit(); lastHeader.setTimestamp(ts); // absolute timestamp } long lastTimestamp = lastHeader.getTimestamp(); if (fmt == 1 || fmt == 2) { // type 1, type 2 header ts = in.read24Bit(); lastHeader.setTimestamp(lastTimestamp + ts); // delta timestamp } if (fmt == 0 || fmt == 1) { // type 0, type 1 header int size = in.read24Bit(); lastHeader.setSize(size); lastHeader.setType(in.readByte() & 0xFF); } if (fmt == 0) { // type 0 header int streamId = (int) in.read32BitLittleEndian(); lastHeader.setStreamId(streamId); } if (fmt == 3) { // type 3 // 0 bytes } // extended time stamp if (fmt == 0 && ts >= 0x00FFFFFF) { ts = in.read32Bit(); lastHeader.setTimestamp(ts); } if ((fmt == 1 || fmt == 2) && ts >= 0x00FFFFFF) { ts = in.read32Bit(); lastHeader.setTimestamp(lastTimestamp + ts); } return new RtmpHeader(chunkStreamId, lastHeader.getTimestamp(), lastHeader.getSize(), lastHeader.getType(), lastHeader.getStreamId()); } }
Java