code
stringlengths
3
1.18M
language
stringclasses
1 value
package org.anddev.andengine.examples.adt.card; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 18:59:33 - 18.06.2010 */ public enum Color { // =========================================================== // Elements // =========================================================== CLUB, // Kreuz DIAMOND, HEART, SPADE; // PIK // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples.adt.messages.client; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.anddev.andengine.extension.multiplayer.protocol.adt.message.client.ClientMessage; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 12:23:37 - 21.05.2011 */ public class ConnectionPingClientMessage extends ClientMessage implements ClientMessageFlags { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private long mTimestamp; // =========================================================== // Constructors // =========================================================== @Deprecated public ConnectionPingClientMessage() { } // =========================================================== // Getter & Setter // =========================================================== public long getTimestamp() { return this.mTimestamp; } public void setTimestamp(final long pTimestamp) { this.mTimestamp = pTimestamp; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public short getFlag() { return FLAG_MESSAGE_CLIENT_CONNECTION_PING; } @Override protected void onReadTransmissionData(final DataInputStream pDataInputStream) throws IOException { this.mTimestamp = pDataInputStream.readLong(); } @Override protected void onWriteTransmissionData(final DataOutputStream pDataOutputStream) throws IOException { pDataOutputStream.writeLong(this.mTimestamp); } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples.adt.messages.client; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 12:00:00 - 21.05.2011 */ public interface ClientMessageFlags { // =========================================================== // Final Fields // =========================================================== /* Connection Flags. */ public static final short FLAG_MESSAGE_CLIENT_CONNECTION_CLOSE = Short.MIN_VALUE; public static final short FLAG_MESSAGE_CLIENT_CONNECTION_ESTABLISH = FLAG_MESSAGE_CLIENT_CONNECTION_CLOSE + 1; public static final short FLAG_MESSAGE_CLIENT_CONNECTION_PING = FLAG_MESSAGE_CLIENT_CONNECTION_ESTABLISH + 1; // =========================================================== // Methods // =========================================================== }
Java
package org.anddev.andengine.examples.adt.messages.client; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.anddev.andengine.extension.multiplayer.protocol.adt.message.client.ClientMessage; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 12:00:31 - 21.05.2011 */ public class ConnectionEstablishClientMessage extends ClientMessage implements ClientMessageFlags { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private short mProtocolVersion; // =========================================================== // Constructors // =========================================================== @Deprecated public ConnectionEstablishClientMessage() { } public ConnectionEstablishClientMessage(final short pProtocolVersion) { this.mProtocolVersion = pProtocolVersion; } // =========================================================== // Getter & Setter // =========================================================== public short getProtocolVersion() { return this.mProtocolVersion; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public short getFlag() { return ClientMessageFlags.FLAG_MESSAGE_CLIENT_CONNECTION_ESTABLISH; } @Override protected void onReadTransmissionData(final DataInputStream pDataInputStream) throws IOException { this.mProtocolVersion = pDataInputStream.readShort(); } @Override protected void onWriteTransmissionData(final DataOutputStream pDataOutputStream) throws IOException { pDataOutputStream.writeShort(this.mProtocolVersion); } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples.adt.messages.client; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.anddev.andengine.extension.multiplayer.protocol.adt.message.client.ClientMessage; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 12:00:36 - 21.05.2011 */ public class ConnectionCloseClientMessage extends ClientMessage implements ClientMessageFlags { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== public ConnectionCloseClientMessage() { } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public short getFlag() { return FLAG_MESSAGE_CLIENT_CONNECTION_CLOSE; } @Override protected void onReadTransmissionData(final DataInputStream pDataInputStream) throws IOException { /* Nothing to read. */ } @Override protected void onWriteTransmissionData(final DataOutputStream pDataOutputStream) throws IOException { /* Nothing to write. */ } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples.adt.messages; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 12:18:34 - 21.05.2011 */ public class MessageConstants { // =========================================================== // Constants // =========================================================== public static final short PROTOCOL_VERSION = 1; // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples.adt.messages.server; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.anddev.andengine.extension.multiplayer.protocol.adt.message.server.ServerMessage; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 16:11:40 - 11.03.2011 */ public class ConnectionCloseServerMessage extends ServerMessage implements ServerMessageFlags { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== public ConnectionCloseServerMessage() { } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public short getFlag() { return FLAG_MESSAGE_SERVER_CONNECTION_CLOSE; } @Override protected void onReadTransmissionData(final DataInputStream pDataInputStream) throws IOException { /* Nothing to read. */ } @Override protected void onWriteTransmissionData(final DataOutputStream pDataOutputStream) throws IOException { /* Nothing to write. */ } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples.adt.messages.server; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.anddev.andengine.extension.multiplayer.protocol.adt.message.server.ServerMessage; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 12:23:15 - 21.05.2011 */ public class ConnectionRejectedProtocolMissmatchServerMessage extends ServerMessage implements ServerMessageFlags { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private short mProtocolVersion; // =========================================================== // Constructors // =========================================================== @Deprecated public ConnectionRejectedProtocolMissmatchServerMessage() { } public ConnectionRejectedProtocolMissmatchServerMessage(final short pProtocolVersion) { this.mProtocolVersion = pProtocolVersion; } // =========================================================== // Getter & Setter // =========================================================== public short getProtocolVersion() { return this.mProtocolVersion; } public void setProtocolVersion(final short pProtocolVersion) { this.mProtocolVersion = pProtocolVersion; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public short getFlag() { return FLAG_MESSAGE_SERVER_CONNECTION_REJECTED_PROTOCOL_MISSMATCH; } @Override protected void onReadTransmissionData(final DataInputStream pDataInputStream) throws IOException { this.mProtocolVersion = pDataInputStream.readShort(); } @Override protected void onWriteTransmissionData(final DataOutputStream pDataOutputStream) throws IOException { pDataOutputStream.writeShort(this.mProtocolVersion); } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples.adt.messages.server; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 11:59:39 - 21.05.2011 */ public interface ServerMessageFlags { // =========================================================== // Final Fields // =========================================================== /* Connection Flags. */ public static final short FLAG_MESSAGE_SERVER_CONNECTION_CLOSE = Short.MIN_VALUE; public static final short FLAG_MESSAGE_SERVER_CONNECTION_ESTABLISHED = FLAG_MESSAGE_SERVER_CONNECTION_CLOSE + 1; public static final short FLAG_MESSAGE_SERVER_CONNECTION_REJECTED_PROTOCOL_MISSMATCH = FLAG_MESSAGE_SERVER_CONNECTION_ESTABLISHED + 1; public static final short FLAG_MESSAGE_SERVER_CONNECTION_PONG = FLAG_MESSAGE_SERVER_CONNECTION_REJECTED_PROTOCOL_MISSMATCH + 1; // =========================================================== // Methods // =========================================================== }
Java
package org.anddev.andengine.examples.adt.messages.server; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.anddev.andengine.extension.multiplayer.protocol.adt.message.server.ServerMessage; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 12:23:20 - 21.05.2011 */ public class ConnectionPongServerMessage extends ServerMessage implements ServerMessageFlags { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private long mTimestamp; // =========================================================== // Constructors // =========================================================== @Deprecated public ConnectionPongServerMessage() { } public ConnectionPongServerMessage(final long pTimestamp) { this.mTimestamp = pTimestamp; } // =========================================================== // Getter & Setter // =========================================================== public long getTimestamp() { return this.mTimestamp; } public void setTimestamp(long pTimestamp) { this.mTimestamp = pTimestamp; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public short getFlag() { return FLAG_MESSAGE_SERVER_CONNECTION_PONG; } @Override protected void onReadTransmissionData(final DataInputStream pDataInputStream) throws IOException { this.mTimestamp = pDataInputStream.readLong(); } @Override protected void onWriteTransmissionData(final DataOutputStream pDataOutputStream) throws IOException { pDataOutputStream.writeLong(this.mTimestamp); } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples.adt.messages.server; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.anddev.andengine.extension.multiplayer.protocol.adt.message.server.ServerMessage; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 12:23:25 - 21.05.2011 */ public class ConnectionEstablishedServerMessage extends ServerMessage implements ServerMessageFlags { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== public ConnectionEstablishedServerMessage() { } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public short getFlag() { return FLAG_MESSAGE_SERVER_CONNECTION_ESTABLISHED; } @Override protected void onReadTransmissionData(final DataInputStream pDataInputStream) throws IOException { /* Nothing to read. */ } @Override protected void onWriteTransmissionData(final DataOutputStream pDataOutputStream) throws IOException { /* Nothing to write. */ } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples.adt.cityradar; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 20:32:16 - 28.10.2010 */ public class City { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private final String mName; private final double mLatitude; private final double mLongitude; private double mDistanceToUser; private double mBearingToUser; // =========================================================== // Constructors // =========================================================== public City(final String pName, final double pLatitude, final double pLongitude) { this.mName = pName; this.mLatitude = pLatitude; this.mLongitude = pLongitude; } // =========================================================== // Getter & Setter // =========================================================== public final String getName() { return this.mName; } public final double getLatitude() { return this.mLatitude; } public final double getLongitude() { return this.mLongitude; } public double getDistanceToUser() { return this.mDistanceToUser; } public void setDistanceToUser(final double pDistanceToUser) { this.mDistanceToUser = pDistanceToUser; } public double getBearingToUser() { return this.mBearingToUser; } public void setBearingToUser(final double pBearingToUser) { this.mBearingToUser = pBearingToUser; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples.adt; public enum ZoomState { // =========================================================== // Elements // =========================================================== IN, OUT, NONE; // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import java.io.DataInputStream; import java.io.DataOutputStream; 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.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.sprite.Sprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.examples.adt.messages.client.ClientMessageFlags; import org.anddev.andengine.examples.adt.messages.server.ConnectionCloseServerMessage; import org.anddev.andengine.examples.adt.messages.server.ServerMessageFlags; import org.anddev.andengine.examples.util.BluetoothListDevicesActivity; import org.anddev.andengine.extension.multiplayer.protocol.adt.message.IMessage; import org.anddev.andengine.extension.multiplayer.protocol.adt.message.server.IServerMessage; import org.anddev.andengine.extension.multiplayer.protocol.adt.message.server.ServerMessage; import org.anddev.andengine.extension.multiplayer.protocol.client.IServerMessageHandler; import org.anddev.andengine.extension.multiplayer.protocol.client.connector.BluetoothSocketConnectionServerConnector; import org.anddev.andengine.extension.multiplayer.protocol.client.connector.BluetoothSocketConnectionServerConnector.IBluetoothSocketConnectionServerConnectorListener; import org.anddev.andengine.extension.multiplayer.protocol.client.connector.ServerConnector; import org.anddev.andengine.extension.multiplayer.protocol.exception.BluetoothException; import org.anddev.andengine.extension.multiplayer.protocol.server.BluetoothSocketServer; import org.anddev.andengine.extension.multiplayer.protocol.server.BluetoothSocketServer.IBluetoothSocketServerListener; import org.anddev.andengine.extension.multiplayer.protocol.server.connector.BluetoothSocketConnectionClientConnector; import org.anddev.andengine.extension.multiplayer.protocol.server.connector.BluetoothSocketConnectionClientConnector.IBluetoothSocketConnectionClientConnectorListener; import org.anddev.andengine.extension.multiplayer.protocol.server.connector.ClientConnector; import org.anddev.andengine.extension.multiplayer.protocol.shared.BluetoothSocketConnection; import org.anddev.andengine.extension.multiplayer.protocol.util.MessagePool; 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.app.AlertDialog; import android.app.Dialog; import android.bluetooth.BluetoothAdapter; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.content.Intent; import android.os.Bundle; import android.util.SparseArray; import android.view.KeyEvent; import android.widget.Toast; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 11:45:03 - 06.03.2011 */ public class MultiplayerBluetoothExample extends BaseExample implements ClientMessageFlags, ServerMessageFlags { // =========================================================== // Constants // =========================================================== /** Create your own unique UUID at: http://www.uuidgenerator.com/ */ private static final String EXAMPLE_UUID = "6D2DF50E-06EF-C21C-7DB0-345099A5F64E"; private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; private static final short FLAG_MESSAGE_SERVER_ADD_FACE = 1; private static final short FLAG_MESSAGE_SERVER_MOVE_FACE = FLAG_MESSAGE_SERVER_ADD_FACE + 1; private static final int DIALOG_CHOOSE_SERVER_OR_CLIENT_ID = 0; private static final int DIALOG_SHOW_SERVER_IP_ID = DIALOG_CHOOSE_SERVER_OR_CLIENT_ID + 1; private static final int REQUESTCODE_BLUETOOTH_ENABLE = 0; private static final int REQUESTCODE_BLUETOOTH_CONNECT = REQUESTCODE_BLUETOOTH_ENABLE + 1; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mBitmapTextureAtlas; private TextureRegion mFaceTextureRegion; private int mFaceIDCounter; private final SparseArray<Sprite> mFaces = new SparseArray<Sprite>(); private String mServerMACAddress; private BluetoothSocketServer<BluetoothSocketConnectionClientConnector> mBluetoothSocketServer; private ServerConnector<BluetoothSocketConnection> mServerConnector; private final MessagePool<IMessage> mMessagePool = new MessagePool<IMessage>(); private BluetoothAdapter mBluetoothAdapter; // =========================================================== // Constructors // =========================================================== public MultiplayerBluetoothExample() { this.initMessagePool(); } private void initMessagePool() { this.mMessagePool.registerMessage(FLAG_MESSAGE_SERVER_ADD_FACE, AddFaceServerMessage.class); this.mMessagePool.registerMessage(FLAG_MESSAGE_SERVER_MOVE_FACE, MoveFaceServerMessage.class); } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override protected void onCreate(final Bundle pSavedInstanceState) { super.onCreate(pSavedInstanceState); this.mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); this.mServerMACAddress = BluetoothAdapter.getDefaultAdapter().getAddress(); if (this.mBluetoothAdapter == null) { Toast.makeText(this, "Bluetooth is not available!", Toast.LENGTH_LONG).show(); this.finish(); return; } else { if (this.mBluetoothAdapter.isEnabled()) { this.showDialog(DIALOG_CHOOSE_SERVER_OR_CLIENT_ID); } else { final Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); this.startActivityForResult(enableIntent, REQUESTCODE_BLUETOOTH_ENABLE); } } } @Override protected Dialog onCreateDialog(final int pID) { switch(pID) { case DIALOG_SHOW_SERVER_IP_ID: return new AlertDialog.Builder(this) .setIcon(android.R.drawable.ic_dialog_info) .setTitle("Server-Details") .setCancelable(false) .setMessage("The Name of your Server is:\n" + BluetoothAdapter.getDefaultAdapter().getName() + "\n" + "The MACAddress of your Server is:\n" + this.mServerMACAddress) .setPositiveButton(android.R.string.ok, null) .create(); case DIALOG_CHOOSE_SERVER_OR_CLIENT_ID: return new AlertDialog.Builder(this) .setIcon(android.R.drawable.ic_dialog_info) .setTitle("Be Server or Client ...") .setCancelable(false) .setPositiveButton("Client", new OnClickListener() { @Override public void onClick(final DialogInterface pDialog, final int pWhich) { final Intent intent = new Intent(MultiplayerBluetoothExample.this, BluetoothListDevicesActivity.class); MultiplayerBluetoothExample.this.startActivityForResult(intent, REQUESTCODE_BLUETOOTH_CONNECT); } }) .setNeutralButton("Server", new OnClickListener() { @Override public void onClick(final DialogInterface pDialog, final int pWhich) { MultiplayerBluetoothExample.this.toast("You can add and move sprites, which are only shown on the clients."); MultiplayerBluetoothExample.this.initServer(); MultiplayerBluetoothExample.this.showDialog(DIALOG_SHOW_SERVER_IP_ID); } }) .setNegativeButton("Both", new OnClickListener() { @Override public void onClick(final DialogInterface pDialog, final int pWhich) { MultiplayerBluetoothExample.this.toast("You can add sprites and move them, by dragging them."); MultiplayerBluetoothExample.this.initServerAndClient(); MultiplayerBluetoothExample.this.showDialog(DIALOG_SHOW_SERVER_IP_ID); } }) .create(); default: return super.onCreateDialog(pID); } } @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 protected void onDestroy() { if(this.mBluetoothSocketServer != null) { try { this.mBluetoothSocketServer.sendBroadcastServerMessage(new ConnectionCloseServerMessage()); } catch (final IOException e) { Debug.e(e); } this.mBluetoothSocketServer.terminate(); } if(this.mServerConnector != null) { this.mServerConnector.terminate(); } super.onDestroy(); } @Override public boolean onKeyUp(final int pKeyCode, final KeyEvent pEvent) { switch(pKeyCode) { case KeyEvent.KEYCODE_BACK: this.finish(); return true; } return super.onKeyUp(pKeyCode, pEvent); } @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)); /* We allow only the server to actively send around messages. */ if(MultiplayerBluetoothExample.this.mBluetoothSocketServer != null) { scene.setOnSceneTouchListener(new IOnSceneTouchListener() { @Override public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) { if(pSceneTouchEvent.isActionDown()) { try { final AddFaceServerMessage addFaceServerMessage = (AddFaceServerMessage) MultiplayerBluetoothExample.this.mMessagePool.obtainMessage(FLAG_MESSAGE_SERVER_ADD_FACE); addFaceServerMessage.set(MultiplayerBluetoothExample.this.mFaceIDCounter++, pSceneTouchEvent.getX(), pSceneTouchEvent.getY()); MultiplayerBluetoothExample.this.mBluetoothSocketServer.sendBroadcastServerMessage(addFaceServerMessage); MultiplayerBluetoothExample.this.mMessagePool.recycleMessage(addFaceServerMessage); } catch (final IOException e) { Debug.e(e); } return true; } else { return false; } } }); scene.setOnAreaTouchListener(new IOnAreaTouchListener() { @Override public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final ITouchArea pTouchArea, final float pTouchAreaLocalX, final float pTouchAreaLocalY) { try { final Sprite face = (Sprite)pTouchArea; final Integer faceID = (Integer)face.getUserData(); final MoveFaceServerMessage moveFaceServerMessage = (MoveFaceServerMessage) MultiplayerBluetoothExample.this.mMessagePool.obtainMessage(FLAG_MESSAGE_SERVER_MOVE_FACE); moveFaceServerMessage.set(faceID, pSceneTouchEvent.getX(), pSceneTouchEvent.getY()); MultiplayerBluetoothExample.this.mBluetoothSocketServer.sendBroadcastServerMessage(moveFaceServerMessage); MultiplayerBluetoothExample.this.mMessagePool.recycleMessage(moveFaceServerMessage); } catch (final IOException e) { Debug.e(e); return false; } return true; } }); scene.setTouchAreaBindingEnabled(true); } return scene; } @Override public void onLoadComplete() { } @Override protected void onActivityResult(final int pRequestCode, final int pResultCode, final Intent pData) { switch(pRequestCode) { case REQUESTCODE_BLUETOOTH_ENABLE: this.showDialog(DIALOG_CHOOSE_SERVER_OR_CLIENT_ID); break; case REQUESTCODE_BLUETOOTH_CONNECT: this.mServerMACAddress = pData.getExtras().getString(BluetoothListDevicesActivity.EXTRA_DEVICE_ADDRESS); this.initClient(); break; default: super.onActivityResult(pRequestCode, pResultCode, pData); } } // =========================================================== // Methods // =========================================================== public void addFace(final int pID, final float pX, final float pY) { final Scene scene = this.mEngine.getScene(); /* Create the face and add it to the scene. */ final Sprite face = new Sprite(0, 0, this.mFaceTextureRegion); face.setPosition(pX - face.getWidth() * 0.5f, pY - face.getHeight() * 0.5f); face.setUserData(pID); this.mFaces.put(pID, face); scene.registerTouchArea(face); scene.attachChild(face); } public void moveFace(final int pID, final float pX, final float pY) { /* Find and move the face. */ final Sprite face = this.mFaces.get(pID); face.setPosition(pX - face.getWidth() * 0.5f, pY - face.getHeight() * 0.5f); } private void initServerAndClient() { this.initServer(); /* Wait some time after the server has been started, so it actually can start up. */ try { Thread.sleep(500); } catch (final Throwable t) { Debug.e(t); } this.initClient(); } private void initServer() { this.mServerMACAddress = BluetoothAdapter.getDefaultAdapter().getAddress(); try { this.mBluetoothSocketServer = new BluetoothSocketServer<BluetoothSocketConnectionClientConnector>(EXAMPLE_UUID, new ExampleClientConnectorListener(), new ExampleServerStateListener()) { @Override protected BluetoothSocketConnectionClientConnector newClientConnector(final BluetoothSocketConnection pBluetoothSocketConnection) throws IOException { try { return new BluetoothSocketConnectionClientConnector(pBluetoothSocketConnection); } catch (final BluetoothException e) { Debug.e(e); /* Actually cannot happen. */ return null; } } }; } catch (final BluetoothException e) { Debug.e(e); } this.mBluetoothSocketServer.start(); } private void initClient() { try { this.mServerConnector = new BluetoothSocketConnectionServerConnector(new BluetoothSocketConnection(this.mBluetoothAdapter, this.mServerMACAddress, EXAMPLE_UUID), new ExampleServerConnectorListener()); this.mServerConnector.registerServerMessage(FLAG_MESSAGE_SERVER_CONNECTION_CLOSE, ConnectionCloseServerMessage.class, new IServerMessageHandler<BluetoothSocketConnection>() { @Override public void onHandleMessage(final ServerConnector<BluetoothSocketConnection> pServerConnector, final IServerMessage pServerMessage) throws IOException { MultiplayerBluetoothExample.this.finish(); } }); this.mServerConnector.registerServerMessage(FLAG_MESSAGE_SERVER_ADD_FACE, AddFaceServerMessage.class, new IServerMessageHandler<BluetoothSocketConnection>() { @Override public void onHandleMessage(final ServerConnector<BluetoothSocketConnection> pServerConnector, final IServerMessage pServerMessage) throws IOException { final AddFaceServerMessage addFaceServerMessage = (AddFaceServerMessage)pServerMessage; MultiplayerBluetoothExample.this.addFace(addFaceServerMessage.mID, addFaceServerMessage.mX, addFaceServerMessage.mY); } }); this.mServerConnector.registerServerMessage(FLAG_MESSAGE_SERVER_MOVE_FACE, MoveFaceServerMessage.class, new IServerMessageHandler<BluetoothSocketConnection>() { @Override public void onHandleMessage(final ServerConnector<BluetoothSocketConnection> pServerConnector, final IServerMessage pServerMessage) throws IOException { final MoveFaceServerMessage moveFaceServerMessage = (MoveFaceServerMessage)pServerMessage; MultiplayerBluetoothExample.this.moveFace(moveFaceServerMessage.mID, moveFaceServerMessage.mX, moveFaceServerMessage.mY); } }); this.mServerConnector.getConnection().start(); } catch (final Throwable t) { Debug.e(t); } } private void log(final String pMessage) { Debug.d(pMessage); } private void toast(final String pMessage) { this.log(pMessage); this.runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(MultiplayerBluetoothExample.this, pMessage, Toast.LENGTH_SHORT).show(); } }); } // =========================================================== // Inner and Anonymous Classes // =========================================================== public static class AddFaceServerMessage extends ServerMessage { private int mID; private float mX; private float mY; public AddFaceServerMessage() { } public AddFaceServerMessage(final int pID, final float pX, final float pY) { this.mID = pID; this.mX = pX; this.mY = pY; } public void set(final int pID, final float pX, final float pY) { this.mID = pID; this.mX = pX; this.mY = pY; } @Override public short getFlag() { return FLAG_MESSAGE_SERVER_ADD_FACE; } @Override protected void onReadTransmissionData(final DataInputStream pDataInputStream) throws IOException { this.mID = pDataInputStream.readInt(); this.mX = pDataInputStream.readFloat(); this.mY = pDataInputStream.readFloat(); } @Override protected void onWriteTransmissionData(final DataOutputStream pDataOutputStream) throws IOException { pDataOutputStream.writeInt(this.mID); pDataOutputStream.writeFloat(this.mX); pDataOutputStream.writeFloat(this.mY); } } public static class MoveFaceServerMessage extends ServerMessage { private int mID; private float mX; private float mY; public MoveFaceServerMessage() { } public MoveFaceServerMessage(final int pID, final float pX, final float pY) { this.mID = pID; this.mX = pX; this.mY = pY; } public void set(final int pID, final float pX, final float pY) { this.mID = pID; this.mX = pX; this.mY = pY; } @Override public short getFlag() { return FLAG_MESSAGE_SERVER_MOVE_FACE; } @Override protected void onReadTransmissionData(final DataInputStream pDataInputStream) throws IOException { this.mID = pDataInputStream.readInt(); this.mX = pDataInputStream.readFloat(); this.mY = pDataInputStream.readFloat(); } @Override protected void onWriteTransmissionData(final DataOutputStream pDataOutputStream) throws IOException { pDataOutputStream.writeInt(this.mID); pDataOutputStream.writeFloat(this.mX); pDataOutputStream.writeFloat(this.mY); } } private class ExampleServerConnectorListener implements IBluetoothSocketConnectionServerConnectorListener { @Override public void onStarted(final ServerConnector<BluetoothSocketConnection> pConnector) { MultiplayerBluetoothExample.this.toast("CLIENT: Connected to server."); } @Override public void onTerminated(final ServerConnector<BluetoothSocketConnection> pConnector) { MultiplayerBluetoothExample.this.toast("CLIENT: Disconnected from Server..."); MultiplayerBluetoothExample.this.finish(); } } private class ExampleServerStateListener implements IBluetoothSocketServerListener<BluetoothSocketConnectionClientConnector> { @Override public void onStarted(final BluetoothSocketServer<BluetoothSocketConnectionClientConnector> pBluetoothSocketServer) { MultiplayerBluetoothExample.this.toast("SERVER: Started."); } @Override public void onTerminated(final BluetoothSocketServer<BluetoothSocketConnectionClientConnector> pBluetoothSocketServer) { MultiplayerBluetoothExample.this.toast("SERVER: Terminated."); } @Override public void onException(final BluetoothSocketServer<BluetoothSocketConnectionClientConnector> pBluetoothSocketServer, final Throwable pThrowable) { Debug.e(pThrowable); MultiplayerBluetoothExample.this.toast("SERVER: Exception: " + pThrowable); } } private class ExampleClientConnectorListener implements IBluetoothSocketConnectionClientConnectorListener { @Override public void onStarted(final ClientConnector<BluetoothSocketConnection> pConnector) { MultiplayerBluetoothExample.this.toast("SERVER: Client connected: " + pConnector.getConnection().getBluetoothSocket().getRemoteDevice().getAddress()); } @Override public void onTerminated(final ClientConnector<BluetoothSocketConnection> pConnector) { MultiplayerBluetoothExample.this.toast("SERVER: Client disconnected: " + pConnector.getConnection().getBluetoothSocket().getRemoteDevice().getAddress()); } } }
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.modifier.LoopEntityModifier; import org.anddev.andengine.entity.modifier.RotationModifier; 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.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.util.GLHelper; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 10:10:10 - 10.10.2010 */ public class Rotation3DExample 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 mFaceTextureRegion; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); this.mCamera.setZClippingPlanes(-100, 100); 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)); /* 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; /* Create the face and add it to the scene. */ final Sprite face = new Sprite(centerX, centerY, this.mFaceTextureRegion) { @Override protected void applyRotation(final GL10 pGL) { /* Disable culling so we can see the backside of this sprite. */ GLHelper.disableCulling(pGL); final float rotation = this.mRotation; if(rotation != 0) { final float rotationCenterX = this.mRotationCenterX; final float rotationCenterY = this.mRotationCenterY; pGL.glTranslatef(rotationCenterX, rotationCenterY, 0); /* Note we are applying rotation around the y-axis and not the z-axis anymore! */ pGL.glRotatef(rotation, 0, 1, 0); pGL.glTranslatef(-rotationCenterX, -rotationCenterY, 0); } } @Override protected void drawVertices(final GL10 pGL, final Camera pCamera) { super.drawVertices(pGL, pCamera); /* Enable culling as 'normal' entities profit from culling. */ GLHelper.enableCulling(pGL); } }; face.registerEntityModifier(new LoopEntityModifier(new RotationModifier(6, 0, 360))); scene.attachChild(face); 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.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 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.sound.Sound; import org.anddev.andengine.audio.sound.SoundFactory; 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 11:54:51 - 11.06.2010 */ public class SoundExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; // =========================================================== // Fields // =========================================================== private BitmapTextureAtlas mBitmapTextureAtlas; private TextureRegion mTankTextureRegion; private Sound mExplosionSound; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { Toast.makeText(this, "Touch the tank to hear an explosion sound.", 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).setNeedsSound(true)); } @Override public void onLoadResources() { this.mBitmapTextureAtlas = new BitmapTextureAtlas(128, 256, TextureOptions.BILINEAR_PREMULTIPLYALPHA); BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mTankTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "tank.png", 0, 0); SoundFactory.setAssetBasePath("mfx/"); try { this.mExplosionSound = SoundFactory.createSoundFromAsset(this.mEngine.getSoundManager(), this, "explosion.ogg"); } 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.mTankTextureRegion.getWidth()) / 2; final int y = (CAMERA_HEIGHT - this.mTankTextureRegion.getHeight()) / 2; final Sprite tank = new Sprite(x, y, this.mTankTextureRegion); scene.attachChild(tank); scene.registerTouchArea(tank); scene.setOnAreaTouchListener(new IOnAreaTouchListener() { @Override public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final ITouchArea pTouchArea, final float pTouchAreaLocalX, final float pTouchAreaLocalY) { if(pSceneTouchEvent.isActionDown()) { SoundExample.this.mExplosionSound.play(); } return true; } }); return scene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples.launcher; import org.anddev.andengine.examples.R; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseExpandableListAdapter; import android.widget.TextView; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 20:43:54 - 16.06.2010 */ class ExpandableExampleLauncherListAdapter extends BaseExpandableListAdapter { // =========================================================== // Constants // =========================================================== private static final ExampleGroup[] EXAMPLEGROUPS = { ExampleGroup.SIMPLE, ExampleGroup.MODIFIER_AND_ANIMATION, ExampleGroup.TOUCH, ExampleGroup.PARTICLESYSTEM, ExampleGroup.MULTIPLAYER, ExampleGroup.PHYSICS, ExampleGroup.TEXT, ExampleGroup.AUDIO, ExampleGroup.ADVANCED, ExampleGroup.BACKGROUND, ExampleGroup.OTHER, ExampleGroup.APP, ExampleGroup.GAME, ExampleGroup.BENCHMARK }; // =========================================================== // Fields // =========================================================== private final Context mContext; // =========================================================== // Constructors // =========================================================== public ExpandableExampleLauncherListAdapter(final Context pContext) { this.mContext = pContext; } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Example getChild(final int pGroupPosition, final int pChildPosition) { return EXAMPLEGROUPS[pGroupPosition].mExamples[pChildPosition]; } @Override public long getChildId(final int pGroupPosition, final int pChildPosition) { return pChildPosition; } @Override public int getChildrenCount(final int pGroupPosition) { return EXAMPLEGROUPS[pGroupPosition].mExamples.length; } @Override public View getChildView(final int pGroupPosition, final int pChildPosition, final boolean pIsLastChild, final View pConvertView, final ViewGroup pParent) { final View childView; if (pConvertView != null){ childView = pConvertView; }else{ childView = LayoutInflater.from(this.mContext).inflate(R.layout.listrow_example, null); } ((TextView)childView.findViewById(R.id.tv_listrow_example_name)).setText(this.getChild(pGroupPosition, pChildPosition).NAMERESID); return childView; } @Override public View getGroupView(final int pGroupPosition, final boolean pIsExpanded, final View pConvertView, final ViewGroup pParent) { final View groupView; if (pConvertView != null){ groupView = pConvertView; }else{ groupView = LayoutInflater.from(this.mContext).inflate(R.layout.listrow_examplegroup, null); } ((TextView)groupView.findViewById(R.id.tv_listrow_examplegroup_name)).setText(this.getGroup(pGroupPosition).mNameResourceID); return groupView; } @Override public ExampleGroup getGroup(final int pGroupPosition) { return EXAMPLEGROUPS[pGroupPosition]; } @Override public int getGroupCount() { return EXAMPLEGROUPS.length; } @Override public long getGroupId(final int pGroupPosition) { return pGroupPosition; } @Override public boolean isChildSelectable(final int pGroupPosition, final int pChildPosition) { return true; } @Override public boolean hasStableIds() { return true; } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples.launcher; import org.anddev.andengine.examples.R; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 11:13:34 - 27.06.2010 */ public enum ExampleGroup { // =========================================================== // Elements // =========================================================== SIMPLE(R.string.examplegroup_simple, Example.LINE, Example.RECTANGLE, Example.SPRITE, Example.SPRITEREMOVE, Example.SPRITEBATCH), MODIFIER_AND_ANIMATION(R.string.examplegroup_modifier_and_animation, Example.MOVINGBALL, Example.ENTITYMODIFIER, Example.ENTITYMODIFIERIRREGULAR, Example.PATHMODIFIER, Example.ANIMATEDSPRITES, Example.EASEFUNCTION, Example.ROTATION3D ), TOUCH(R.string.examplegroup_touch, Example.TOUCHDRAG, Example.MULTITOUCH, Example.ANALOGONSCREENCONTROL, Example.DIGITALONSCREENCONTROL, Example.ANALOGONSCREENCONTROLS, Example.COORDINATECONVERSION, Example.PINCHZOOM), PARTICLESYSTEM(R.string.examplegroup_particlesystems, Example.PARTICLESYSTEMSIMPLE, Example.PARTICLESYSTEMCOOL, Example.PARTICLESYSTEMNEXUS), MULTIPLAYER(R.string.examplegroup_multiplayer, Example.MULTIPLAYER, Example.MULTIPLAYERSERVERDISCOVERY, Example.MULTIPLAYERBLUETOOTH), PHYSICS(R.string.examplegroup_physics, Example.COLLISIONDETECTION, Example.PHYSICS, Example.PHYSICSFIXEDSTEP, Example.PHYSICSCOLLISIONFILTERING, Example.PHYSICSJUMP, Example.PHYSICSREVOLUTEJOINT, Example.PHYSICSMOUSEJOINT, Example.PHYSICSREMOVE), TEXT(R.string.examplegroup_text, Example.TEXT, Example.TICKERTEXT, Example.CHANGEABLETEXT, Example.CUSTOMFONT, Example.STROKEFONT), AUDIO(R.string.examplegroup_audio, Example.SOUND, Example.MUSIC, Example.MODPLAYER), ADVANCED(R.string.examplegroup_advanced, Example.SPLITSCREEN, Example.BOUNDCAMERA ), // Example.AUGMENTEDREALITY, Example.AUGMENTEDREALITYHORIZON), BACKGROUND(R.string.examplegroup_background, Example.REPEATINGSPRITEBACKGROUND, Example.AUTOPARALLAXBACKGROUND, Example.TMXTILEDMAP), OTHER(R.string.examplegroup_other, Example.SCREENCAPTURE, Example.PAUSE, Example.MENU, Example.SUBMENU, Example.TEXTMENU, Example.ZOOM , Example.IMAGEFORMATS, Example.PVRTEXTURE, Example.PVRCCZTEXTURE, Example.PVRGZTEXTURE, Example.ETC1TEXTURE, Example.TEXTUREOPTIONS, Example.TEXTUREPACKER, Example.COLORKEYTEXTURESOURCEDECORATOR, Example.LOADTEXTURE, Example.UPDATETEXTURE, Example.RUNNABLEPOOLUPDATEHANDLER, Example.SVGTEXTUREREGION, Example.XMLLAYOUT, Example.LEVELLOADER), APP(R.string.examplegroup_app, Example.APP_CITYRADAR), GAME(R.string.examplegroup_game, Example.GAME_PONG, Example.GAME_SNAKE, Example.GAME_RACER), BENCHMARK(R.string.examplegroup_benchmark, Example.BENCHMARK_SPRITE, Example.BENCHMARK_ENTITYMODIFIER, Example.BENCHMARK_ANIMATION, Example.BENCHMARK_TICKERTEXT, Example.BENCHMARK_PARTICLESYSTEM, Example.BENCHMARK_PHYSICS); // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== public final Example[] mExamples; public final int mNameResourceID; // =========================================================== // Constructors // =========================================================== private ExampleGroup(final int pNameResourceID, final Example ... pExamples) { this.mNameResourceID = pNameResourceID; this.mExamples = pExamples; } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples.launcher; import java.util.Arrays; import org.anddev.andengine.examples.R; import org.anddev.andengine.util.Debug; import android.app.AlertDialog; import android.app.Dialog; import android.app.ExpandableListActivity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.net.Uri; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.ExpandableListView; import android.widget.Toast; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 22:56:46 - 16.06.2010 */ public class ExampleLauncher extends ExpandableListActivity { // =========================================================== // Constants // =========================================================== private static final String PREF_LAST_APP_LAUNCH_VERSIONCODE_ID = "last.app.launch.versioncode"; private static final int DIALOG_FIRST_APP_LAUNCH = 0; private static final int DIALOG_NEW_IN_THIS_VERSION = DIALOG_FIRST_APP_LAUNCH + 1; private static final int DIALOG_BENCHMARKS_SUBMIT_PLEASE = DIALOG_NEW_IN_THIS_VERSION + 1; // =========================================================== // Fields // =========================================================== private ExpandableExampleLauncherListAdapter mExpandableExampleLauncherListAdapter; private int mVersionCodeCurrent; private int mVersionCodeLastLaunch; // =========================================================== // Constructors // =========================================================== @Override public void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.setContentView(R.layout.list_examples); this.mExpandableExampleLauncherListAdapter = new ExpandableExampleLauncherListAdapter(this); this.setListAdapter(this.mExpandableExampleLauncherListAdapter); this.findViewById(R.id.btn_get_involved).setOnClickListener(new OnClickListener() { @Override public void onClick(final View pView) { ExampleLauncher.this.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.andengine.org"))); } }); final SharedPreferences prefs = this.getPreferences(Context.MODE_PRIVATE); this.mVersionCodeCurrent = this.getVersionCode(); this.mVersionCodeLastLaunch = prefs.getInt(PREF_LAST_APP_LAUNCH_VERSIONCODE_ID, -1); if(this.isFirstTime("first.app.launch")) { this.showDialog(DIALOG_FIRST_APP_LAUNCH); } else if(this.mVersionCodeLastLaunch != -1 && this.mVersionCodeLastLaunch < this.mVersionCodeCurrent){ this.showDialog(DIALOG_NEW_IN_THIS_VERSION); } else if(isFirstTime("please.submit.benchmarks")){ this.showDialog(DIALOG_BENCHMARKS_SUBMIT_PLEASE); } prefs.edit().putInt(PREF_LAST_APP_LAUNCH_VERSIONCODE_ID, this.mVersionCodeCurrent).commit(); } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override protected Dialog onCreateDialog(final int pId) { switch(pId) { case DIALOG_FIRST_APP_LAUNCH: return new AlertDialog.Builder(this) .setTitle(R.string.dialog_first_app_launch_title) .setMessage(R.string.dialog_first_app_launch_message) .setIcon(android.R.drawable.ic_dialog_info) .setPositiveButton(android.R.string.ok, null) .create(); case DIALOG_BENCHMARKS_SUBMIT_PLEASE: return new AlertDialog.Builder(this) .setTitle(R.string.dialog_benchmarks_submit_please_title) .setMessage(R.string.dialog_benchmarks_submit_please_message) .setIcon(android.R.drawable.ic_dialog_info) .setPositiveButton(android.R.string.ok, null) .create(); case DIALOG_NEW_IN_THIS_VERSION: final int[] versionCodes = this.getResources().getIntArray(R.array.new_in_version_versioncode); final int versionDescriptionsStartIndex = Math.max(0, Arrays.binarySearch(versionCodes, this.mVersionCodeLastLaunch) + 1); final String[] versionDescriptions = this.getResources().getStringArray(R.array.new_in_version_changes); final StringBuilder sb = new StringBuilder(); for(int i = versionDescriptions.length - 1; i >= versionDescriptionsStartIndex; i--) { sb.append("--------------------------\n"); sb.append(">>> Version: " + versionCodes[i] + "\n"); sb.append("--------------------------\n"); sb.append(versionDescriptions[i]); if(i > versionDescriptionsStartIndex){ sb.append("\n\n"); } } return new AlertDialog.Builder(this) .setTitle(R.string.dialog_new_in_this_version_title) .setMessage(sb.toString()) .setIcon(android.R.drawable.ic_dialog_info) .setPositiveButton(android.R.string.ok, null) .create(); default: return super.onCreateDialog(pId); } } @Override public void onGroupExpand(int pGroupPosition) { switch(this.mExpandableExampleLauncherListAdapter.getGroup(pGroupPosition)){ case BENCHMARK: Toast.makeText(this, "When running a benchmark, a dialog with the results will appear after some seconds.", Toast.LENGTH_SHORT).show(); } super.onGroupExpand(pGroupPosition); } @Override public boolean onChildClick(final ExpandableListView pParent, final View pV, final int pGroupPosition, final int pChildPosition, final long pId) { final Example example = this.mExpandableExampleLauncherListAdapter.getChild(pGroupPosition, pChildPosition); this.startActivity(new Intent(this, example.CLASS)); return super.onChildClick(pParent, pV, pGroupPosition, pChildPosition, pId); } // =========================================================== // Methods // =========================================================== public boolean isFirstTime(final String pKey){ final SharedPreferences prefs = this.getPreferences(Context.MODE_PRIVATE); if(prefs.getBoolean(pKey, true)){ prefs.edit().putBoolean(pKey, false).commit(); return true; } return false; } public int getVersionCode() { try { final PackageInfo pi = this.getPackageManager().getPackageInfo(this.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.launcher; import org.anddev.andengine.examples.AnalogOnScreenControlExample; import org.anddev.andengine.examples.AnalogOnScreenControlsExample; import org.anddev.andengine.examples.AnimatedSpritesExample; import org.anddev.andengine.examples.AugmentedRealityExample; import org.anddev.andengine.examples.AugmentedRealityHorizonExample; import org.anddev.andengine.examples.AutoParallaxBackgroundExample; import org.anddev.andengine.examples.BoundCameraExample; import org.anddev.andengine.examples.ChangeableTextExample; import org.anddev.andengine.examples.CollisionDetectionExample; import org.anddev.andengine.examples.ColorKeyTextureSourceDecoratorExample; import org.anddev.andengine.examples.CoordinateConversionExample; import org.anddev.andengine.examples.CustomFontExample; import org.anddev.andengine.examples.DigitalOnScreenControlExample; import org.anddev.andengine.examples.ETC1TextureExample; import org.anddev.andengine.examples.EaseFunctionExample; import org.anddev.andengine.examples.EntityModifierExample; import org.anddev.andengine.examples.EntityModifierIrregularExample; import org.anddev.andengine.examples.ImageFormatsExample; import org.anddev.andengine.examples.LevelLoaderExample; import org.anddev.andengine.examples.LineExample; import org.anddev.andengine.examples.LoadTextureExample; import org.anddev.andengine.examples.MenuExample; import org.anddev.andengine.examples.ModPlayerExample; import org.anddev.andengine.examples.MovingBallExample; import org.anddev.andengine.examples.MultiTouchExample; import org.anddev.andengine.examples.MultiplayerBluetoothExample; import org.anddev.andengine.examples.MultiplayerExample; import org.anddev.andengine.examples.MultiplayerServerDiscoveryExample; import org.anddev.andengine.examples.MusicExample; import org.anddev.andengine.examples.PVRCCZTextureExample; import org.anddev.andengine.examples.PVRGZTextureExample; import org.anddev.andengine.examples.PVRTextureExample; import org.anddev.andengine.examples.ParticleSystemCoolExample; import org.anddev.andengine.examples.ParticleSystemNexusExample; import org.anddev.andengine.examples.ParticleSystemSimpleExample; import org.anddev.andengine.examples.PathModifierExample; import org.anddev.andengine.examples.PauseExample; import org.anddev.andengine.examples.PhysicsCollisionFilteringExample; import org.anddev.andengine.examples.PhysicsExample; import org.anddev.andengine.examples.PhysicsFixedStepExample; import org.anddev.andengine.examples.PhysicsJumpExample; import org.anddev.andengine.examples.PhysicsMouseJointExample; import org.anddev.andengine.examples.PhysicsRemoveExample; import org.anddev.andengine.examples.PhysicsRevoluteJointExample; import org.anddev.andengine.examples.PinchZoomExample; import org.anddev.andengine.examples.R; import org.anddev.andengine.examples.RectangleExample; import org.anddev.andengine.examples.RepeatingSpriteBackgroundExample; import org.anddev.andengine.examples.Rotation3DExample; import org.anddev.andengine.examples.RunnablePoolUpdateHandlerExample; import org.anddev.andengine.examples.SVGTextureRegionExample; import org.anddev.andengine.examples.ScreenCaptureExample; import org.anddev.andengine.examples.SoundExample; import org.anddev.andengine.examples.SplitScreenExample; import org.anddev.andengine.examples.SpriteBatchExample; import org.anddev.andengine.examples.SpriteExample; import org.anddev.andengine.examples.SpriteRemoveExample; import org.anddev.andengine.examples.StrokeFontExample; import org.anddev.andengine.examples.SubMenuExample; import org.anddev.andengine.examples.TMXTiledMapExample; import org.anddev.andengine.examples.TextExample; import org.anddev.andengine.examples.TextMenuExample; import org.anddev.andengine.examples.TextureOptionsExample; import org.anddev.andengine.examples.TexturePackerExample; import org.anddev.andengine.examples.TickerTextExample; import org.anddev.andengine.examples.TouchDragExample; import org.anddev.andengine.examples.UnloadResourcesExample; import org.anddev.andengine.examples.UpdateTextureExample; import org.anddev.andengine.examples.XMLLayoutExample; import org.anddev.andengine.examples.ZoomExample; import org.anddev.andengine.examples.app.cityradar.CityRadarActivity; import org.anddev.andengine.examples.benchmark.AnimationBenchmark; import org.anddev.andengine.examples.benchmark.EntityModifierBenchmark; import org.anddev.andengine.examples.benchmark.ParticleSystemBenchmark; import org.anddev.andengine.examples.benchmark.PhysicsBenchmark; import org.anddev.andengine.examples.benchmark.SpriteBenchmark; import org.anddev.andengine.examples.benchmark.TickerTextBenchmark; import org.anddev.andengine.examples.game.pong.PongGameActivity; import org.anddev.andengine.examples.game.racer.RacerGameActivity; import org.anddev.andengine.examples.game.snake.SnakeGameActivity; import org.anddev.andengine.ui.activity.BaseGameActivity; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 20:42:27 - 16.06.2010 */ enum Example { // =========================================================== // Elements // =========================================================== ANALOGONSCREENCONTROL(AnalogOnScreenControlExample.class, R.string.example_analogonscreencontrol), ANALOGONSCREENCONTROLS(AnalogOnScreenControlsExample.class, R.string.example_analogonscreencontrols), ANIMATEDSPRITES(AnimatedSpritesExample.class, R.string.example_animatedsprites), AUGMENTEDREALITY(AugmentedRealityExample.class, R.string.example_augmentedreality), AUGMENTEDREALITYHORIZON(AugmentedRealityHorizonExample.class, R.string.example_augmentedrealityhorizon), AUTOPARALLAXBACKGROUND(AutoParallaxBackgroundExample.class, R.string.example_autoparallaxbackground), BOUNDCAMERA(BoundCameraExample.class, R.string.example_boundcamera), CHANGEABLETEXT(ChangeableTextExample.class, R.string.example_changeabletext), COLLISIONDETECTION(CollisionDetectionExample.class, R.string.example_collisiondetection), COLORKEYTEXTURESOURCEDECORATOR(ColorKeyTextureSourceDecoratorExample.class, R.string.example_colorkeytexturesourcedecorator), COORDINATECONVERSION(CoordinateConversionExample.class, R.string.example_coordinateconversion), CUSTOMFONT(CustomFontExample.class, R.string.example_customfont), DIGITALONSCREENCONTROL(DigitalOnScreenControlExample.class, R.string.example_digitalonscreencontrol), EASEFUNCTION(EaseFunctionExample.class, R.string.example_easefunction), ENTITYMODIFIER(EntityModifierExample.class, R.string.example_entitymodifier), ENTITYMODIFIERIRREGULAR(EntityModifierIrregularExample.class, R.string.example_entitymodifierirregular), ETC1TEXTURE(ETC1TextureExample.class, R.string.example_etc1texture), IMAGEFORMATS(ImageFormatsExample.class, R.string.example_imageformats), LEVELLOADER(LevelLoaderExample.class, R.string.example_levelloader), LINE(LineExample.class, R.string.example_line), LOADTEXTURE(LoadTextureExample.class, R.string.example_loadtexture), MENU(MenuExample.class, R.string.example_menu), MODPLAYER(ModPlayerExample.class, R.string.example_modplayer), MOVINGBALL(MovingBallExample.class, R.string.example_movingball), MULTIPLAYER(MultiplayerExample.class, R.string.example_multiplayer), MULTIPLAYERSERVERDISCOVERY(MultiplayerServerDiscoveryExample.class, R.string.example_multiplayerserverdiscovery), MULTIPLAYERBLUETOOTH(MultiplayerBluetoothExample.class, R.string.example_multiplayerbluetooth), MULTITOUCH(MultiTouchExample.class, R.string.example_multitouch), MUSIC(MusicExample.class, R.string.example_music), PAUSE(PauseExample.class, R.string.example_pause), PATHMODIFIER(PathModifierExample.class, R.string.example_pathmodifier), PARTICLESYSTEMNEXUS(ParticleSystemNexusExample.class, R.string.example_particlesystemnexus), PARTICLESYSTEMCOOL(ParticleSystemCoolExample.class, R.string.example_particlesystemcool), PARTICLESYSTEMSIMPLE(ParticleSystemSimpleExample.class, R.string.example_particlesystemsimple), PHYSICSCOLLISIONFILTERING(PhysicsCollisionFilteringExample.class, R.string.example_physicscollisionfiltering), PHYSICS(PhysicsExample.class, R.string.example_physics), PHYSICSFIXEDSTEP(PhysicsFixedStepExample.class, R.string.example_physicsfixedstep), PHYSICSMOUSEJOINT(PhysicsMouseJointExample.class, R.string.example_physicsmousejoint), PHYSICSJUMP(PhysicsJumpExample.class, R.string.example_physicsjump), PHYSICSREVOLUTEJOINT(PhysicsRevoluteJointExample.class, R.string.example_physicsrevolutejoint), PHYSICSREMOVE(PhysicsRemoveExample.class, R.string.example_physicsremove), PINCHZOOM(PinchZoomExample.class, R.string.example_pinchzoom), PVRCCZTEXTURE(PVRCCZTextureExample.class, R.string.example_pvrccztexture), PVRGZTEXTURE(PVRGZTextureExample.class, R.string.example_pvrgztexture), PVRTEXTURE(PVRTextureExample.class, R.string.example_pvrtexture), RECTANGLE(RectangleExample.class, R.string.example_rectangle), REPEATINGSPRITEBACKGROUND(RepeatingSpriteBackgroundExample.class, R.string.example_repeatingspritebackground), ROTATION3D(Rotation3DExample.class, R.string.example_rotation3d), RUNNABLEPOOLUPDATEHANDLER(RunnablePoolUpdateHandlerExample.class, R.string.example_runnablepoolupdatehandler), SCREENCAPTURE(ScreenCaptureExample.class, R.string.example_screencapture), SOUND(SoundExample.class, R.string.example_sound), SPLITSCREEN(SplitScreenExample.class, R.string.example_splitscreen), SPRITEBATCH(SpriteBatchExample.class, R.string.example_spritebatch), SPRITE(SpriteExample.class, R.string.example_sprite), SPRITEREMOVE(SpriteRemoveExample.class, R.string.example_spriteremove), STROKEFONT(StrokeFontExample.class, R.string.example_strokefont), SUBMENU(SubMenuExample.class, R.string.example_submenu), SVGTEXTUREREGION(SVGTextureRegionExample.class, R.string.example_svgtextureregion), TEXT(TextExample.class, R.string.example_text), TEXTMENU(TextMenuExample.class, R.string.example_textmenu), TEXTUREOPTIONS(TextureOptionsExample.class, R.string.example_textureoptions), TEXTUREPACKER(TexturePackerExample.class, R.string.example_texturepacker), TMXTILEDMAP(TMXTiledMapExample.class, R.string.example_tmxtiledmap), TICKERTEXT(TickerTextExample.class, R.string.example_tickertext), TOUCHDRAG(TouchDragExample.class, R.string.example_touchdrag), UNLOADRESOURCES(UnloadResourcesExample.class, R.string.example_unloadresources), UPDATETEXTURE(UpdateTextureExample.class, R.string.example_updatetexture), XMLLAYOUT(XMLLayoutExample.class, R.string.example_xmllayout), ZOOM(ZoomExample.class, R.string.example_zoom), BENCHMARK_ANIMATION(AnimationBenchmark.class, R.string.example_benchmark_animation), BENCHMARK_PARTICLESYSTEM(ParticleSystemBenchmark.class, R.string.example_benchmark_particlesystem), BENCHMARK_PHYSICS(PhysicsBenchmark.class, R.string.example_benchmark_physics), BENCHMARK_ENTITYMODIFIER(EntityModifierBenchmark.class, R.string.example_benchmark_entitymodifier), BENCHMARK_SPRITE(SpriteBenchmark.class, R.string.example_benchmark_sprite), BENCHMARK_TICKERTEXT(TickerTextBenchmark.class, R.string.example_benchmark_tickertext), APP_CITYRADAR(CityRadarActivity.class, R.string.example_app_cityradar), GAME_PONG(PongGameActivity.class, R.string.example_game_pong), GAME_SNAKE(SnakeGameActivity.class, R.string.example_game_snake), GAME_RACER(RacerGameActivity.class, R.string.example_game_racer); // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== public final Class<? extends BaseGameActivity> CLASS; public final int NAMERESID; // =========================================================== // Constructors // =========================================================== private Example(final Class<? extends BaseGameActivity> pExampleClass, final int pNameResID) { this.CLASS = pExampleClass; this.NAMERESID = pNameResID; } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // 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.modifier.MoveModifier; import org.anddev.andengine.entity.scene.CameraScene; 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.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.view.KeyEvent; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 11:33:33 - 01.04.2010 */ public class PauseExample 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 Scene mMainScene; private TextureRegion mFaceTextureRegion; private TextureRegion mPausedTextureRegion; private CameraScene mPauseScene; // =========================================================== // 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); BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mPausedTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "paused.png", 0, 0); this.mFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "face_box_menu.png", 0, 50); this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); this.mPauseScene = new CameraScene(this.mCamera); /* Make the 'PAUSED'-label centered on the camera. */ final int x = CAMERA_WIDTH / 2 - this.mPausedTextureRegion.getWidth() / 2; final int y = CAMERA_HEIGHT / 2 - this.mPausedTextureRegion.getHeight() / 2; final Sprite pausedSprite = new Sprite(x, y, this.mPausedTextureRegion); this.mPauseScene.attachChild(pausedSprite); /* Makes the paused Game look through. */ this.mPauseScene.setBackgroundEnabled(false); /* Just a simple */ this.mMainScene = new Scene(); this.mMainScene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); final Sprite face = new Sprite(0, 0, this.mFaceTextureRegion); face.registerEntityModifier(new MoveModifier(30, 0, CAMERA_WIDTH - face.getWidth(), 0, CAMERA_HEIGHT - face.getHeight())); this.mMainScene.attachChild(face); return this.mMainScene; } @Override public void onLoadComplete() { } @Override public boolean onKeyDown(final int pKeyCode, final KeyEvent pEvent) { if(pKeyCode == KeyEvent.KEYCODE_MENU && pEvent.getAction() == KeyEvent.ACTION_DOWN) { if(this.mEngine.isRunning()) { this.mMainScene.setChildScene(this.mPauseScene, false, true, true); this.mEngine.stop(); } else { this.mMainScene.clearChildScene(); this.mEngine.start(); } return true; } else { return super.onKeyDown(pKeyCode, pEvent); } } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples.spritesheets; public interface TexturePackerExampleSpritesheet { public static final int FACE_BOX_ID = 0; public static final int FACE_CIRCLE_TILED_ID = 1; public static final int FACE_HEXAGON_TILED_ID = 2; public static final int FACE_TRIANGLE_TILED_ID = 3; }
Java
package org.anddev.andengine.examples; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.camera.hud.HUD; 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.MoveModifier; import org.anddev.andengine.entity.primitive.Line; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.sprite.Sprite; import org.anddev.andengine.entity.text.ChangeableText; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.input.touch.TouchEvent; 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.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TextureRegion; import org.anddev.andengine.util.modifier.ease.EaseBackIn; import org.anddev.andengine.util.modifier.ease.EaseBackInOut; import org.anddev.andengine.util.modifier.ease.EaseBackOut; import org.anddev.andengine.util.modifier.ease.EaseBounceIn; import org.anddev.andengine.util.modifier.ease.EaseBounceInOut; import org.anddev.andengine.util.modifier.ease.EaseBounceOut; import org.anddev.andengine.util.modifier.ease.EaseCircularIn; import org.anddev.andengine.util.modifier.ease.EaseCircularInOut; import org.anddev.andengine.util.modifier.ease.EaseCircularOut; import org.anddev.andengine.util.modifier.ease.EaseCubicIn; import org.anddev.andengine.util.modifier.ease.EaseCubicInOut; import org.anddev.andengine.util.modifier.ease.EaseCubicOut; import org.anddev.andengine.util.modifier.ease.EaseElasticIn; import org.anddev.andengine.util.modifier.ease.EaseElasticInOut; import org.anddev.andengine.util.modifier.ease.EaseElasticOut; import org.anddev.andengine.util.modifier.ease.EaseExponentialIn; import org.anddev.andengine.util.modifier.ease.EaseExponentialInOut; import org.anddev.andengine.util.modifier.ease.EaseExponentialOut; import org.anddev.andengine.util.modifier.ease.EaseLinear; import org.anddev.andengine.util.modifier.ease.EaseQuadIn; import org.anddev.andengine.util.modifier.ease.EaseQuadInOut; import org.anddev.andengine.util.modifier.ease.EaseQuadOut; import org.anddev.andengine.util.modifier.ease.EaseQuartIn; import org.anddev.andengine.util.modifier.ease.EaseQuartInOut; import org.anddev.andengine.util.modifier.ease.EaseQuartOut; import org.anddev.andengine.util.modifier.ease.EaseQuintIn; import org.anddev.andengine.util.modifier.ease.EaseQuintInOut; import org.anddev.andengine.util.modifier.ease.EaseQuintOut; import org.anddev.andengine.util.modifier.ease.EaseSineIn; import org.anddev.andengine.util.modifier.ease.EaseSineInOut; import org.anddev.andengine.util.modifier.ease.EaseSineOut; import org.anddev.andengine.util.modifier.ease.EaseStrongIn; import org.anddev.andengine.util.modifier.ease.EaseStrongInOut; import org.anddev.andengine.util.modifier.ease.EaseStrongOut; import org.anddev.andengine.util.modifier.ease.IEaseFunction; import android.graphics.Color; import android.graphics.Typeface; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 15:12:16 - 30.07.2010 */ public class EaseFunctionExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mFontTexture; private Font mFont; private BitmapTextureAtlas mBitmapTextureAtlas; private TextureRegion mBadgeTextureRegion; private TextureRegion mNextTextureRegion; private static final IEaseFunction[][] EASEFUNCTIONS = new IEaseFunction[][]{ new IEaseFunction[] { EaseLinear.getInstance(), EaseLinear.getInstance(), EaseLinear.getInstance() }, new IEaseFunction[] { EaseBackIn.getInstance(), EaseBackOut.getInstance(), EaseBackInOut.getInstance() }, new IEaseFunction[] { EaseBounceIn.getInstance(), EaseBounceOut.getInstance(), EaseBounceInOut.getInstance() }, new IEaseFunction[] { EaseCircularIn.getInstance(), EaseCircularOut.getInstance(), EaseCircularInOut.getInstance() }, new IEaseFunction[] { EaseCubicIn.getInstance(), EaseCubicOut.getInstance(), EaseCubicInOut.getInstance() }, new IEaseFunction[] { EaseElasticIn.getInstance(), EaseElasticOut.getInstance(), EaseElasticInOut.getInstance() }, new IEaseFunction[] { EaseExponentialIn.getInstance(), EaseExponentialOut.getInstance(), EaseExponentialInOut.getInstance() }, new IEaseFunction[] { EaseQuadIn.getInstance(), EaseQuadOut.getInstance(), EaseQuadInOut.getInstance() }, new IEaseFunction[] { EaseQuartIn.getInstance(), EaseQuartOut.getInstance(), EaseQuartInOut.getInstance() }, new IEaseFunction[] { EaseQuintIn.getInstance(), EaseQuintOut.getInstance(), EaseQuintInOut.getInstance() }, new IEaseFunction[] { EaseSineIn.getInstance(), EaseSineOut.getInstance(), EaseSineInOut.getInstance() }, new IEaseFunction[] { EaseStrongIn.getInstance(), EaseStrongOut.getInstance(), EaseStrongInOut.getInstance() } }; private int mCurrentEaseFunctionSet = 0; private final Sprite[] mBadges = new Sprite[3]; private final ChangeableText[] mEaseFunctionNameTexts = new ChangeableText[3]; // =========================================================== // 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 font. */ this.mFontTexture = new BitmapTextureAtlas(256, 256, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mFont = new Font(this.mFontTexture, Typeface.create(Typeface.DEFAULT, Typeface.BOLD), 32, true, Color.WHITE); this.mEngine.getTextureManager().loadTexture(this.mFontTexture); this.getFontManager().loadFont(this.mFont); /* The textures. */ BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mBitmapTextureAtlas = new BitmapTextureAtlas(256, 128, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mNextTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "next.png", 0, 0); this.mBadgeTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "badge.png", 97, 0); this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); final HUD hud = new HUD(); final Sprite nextSprite = new Sprite(CAMERA_WIDTH - 100 - this.mNextTextureRegion.getWidth(), 0, this.mNextTextureRegion){ @Override public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final float pTouchAreaLocalX, final float pTouchAreaLocalY) { if(pSceneTouchEvent.isActionDown()) { EaseFunctionExample.this.next(); } return true; }; }; final Sprite previousSprite = new Sprite(100, 0, this.mNextTextureRegion.deepCopy()){ @Override public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final float pTouchAreaLocalX, final float pTouchAreaLocalY) { if(pSceneTouchEvent.isActionDown()) { EaseFunctionExample.this.previous(); } return true; }; }; previousSprite.getTextureRegion().setFlippedHorizontal(true); hud.attachChild(nextSprite); hud.attachChild(previousSprite); hud.registerTouchArea(nextSprite); hud.registerTouchArea(previousSprite); this.mCamera.setHUD(hud); /* Create the sprites that will be moving. */ this.mBadges[0] = new Sprite(0, CAMERA_HEIGHT - 300, this.mBadgeTextureRegion); this.mBadges[1] = new Sprite(0, CAMERA_HEIGHT - 200, this.mBadgeTextureRegion); this.mBadges[2] = new Sprite(0, CAMERA_HEIGHT - 100, this.mBadgeTextureRegion); this.mEaseFunctionNameTexts[0] = new ChangeableText(0, CAMERA_HEIGHT - 250, this.mFont, "Function", 20); this.mEaseFunctionNameTexts[1] = new ChangeableText(0, CAMERA_HEIGHT - 150, this.mFont, "Function", 20); this.mEaseFunctionNameTexts[2] = new ChangeableText(0, CAMERA_HEIGHT - 50, this.mFont, "Function", 20); scene.attachChild(this.mBadges[0]); scene.attachChild(this.mBadges[1]); scene.attachChild(this.mBadges[2]); scene.attachChild(this.mEaseFunctionNameTexts[0]); scene.attachChild(this.mEaseFunctionNameTexts[1]); scene.attachChild(this.mEaseFunctionNameTexts[2]); scene.attachChild(new Line(0, CAMERA_HEIGHT - 110, CAMERA_WIDTH, CAMERA_HEIGHT - 110)); scene.attachChild(new Line(0, CAMERA_HEIGHT - 210, CAMERA_WIDTH, CAMERA_HEIGHT - 210)); scene.attachChild(new Line(0, CAMERA_HEIGHT - 310, CAMERA_WIDTH, CAMERA_HEIGHT - 310)); return scene; } @Override public void onLoadComplete() { this.reanimate(); } // =========================================================== // Methods // =========================================================== public void next() { this.mCurrentEaseFunctionSet++; this.mCurrentEaseFunctionSet %= EASEFUNCTIONS.length; this.reanimate(); } public void previous() { this.mCurrentEaseFunctionSet--; if(this.mCurrentEaseFunctionSet < 0) { this.mCurrentEaseFunctionSet += EASEFUNCTIONS.length; } this.reanimate(); } private void reanimate() { this.runOnUpdateThread(new Runnable() { @Override public void run() { final IEaseFunction[] currentEaseFunctionsSet = EASEFUNCTIONS[EaseFunctionExample.this.mCurrentEaseFunctionSet]; final ChangeableText[] easeFunctionNameTexts = EaseFunctionExample.this.mEaseFunctionNameTexts; final Sprite[] faces = EaseFunctionExample.this.mBadges; for(int i = 0; i < 3; i++) { easeFunctionNameTexts[i].setText(currentEaseFunctionsSet[i].getClass().getSimpleName()); final Sprite face = faces[i]; face.clearEntityModifiers(); final float y = face.getY(); face.setPosition(0, y); face.registerEntityModifier(new MoveModifier(3, 0, CAMERA_WIDTH - face.getWidth(), y, y, currentEaseFunctionsSet[i])); } } }); } // =========================================================== // 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.PVRGZTexture; 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 13:54:51 - 13.07.2011 */ public class PVRGZTextureExample 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 (PVRGZTextureExample.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 PVRGZTexture(PVRTextureFormat.RGBA_8888, TextureOptions.BILINEAR) { @Override protected InputStream onGetInputStream() throws IOException { return PVRGZTextureExample.this.getResources().openRawResource(R.raw.house_pvrgz_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) { PVRGZTextureExample.this.mZoomState = ZoomState.IN; } else { PVRGZTextureExample.this.mZoomState = ZoomState.OUT; } } else { PVRGZTextureExample.this.mZoomState = ZoomState.NONE; } return true; } }); return scene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.Socket; import java.net.UnknownHostException; 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.IOnSceneTouchListener; 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.examples.adt.messages.client.ClientMessageFlags; import org.anddev.andengine.examples.adt.messages.server.ConnectionCloseServerMessage; import org.anddev.andengine.examples.adt.messages.server.ServerMessageFlags; import org.anddev.andengine.extension.multiplayer.protocol.adt.message.IMessage; import org.anddev.andengine.extension.multiplayer.protocol.adt.message.server.IServerMessage; import org.anddev.andengine.extension.multiplayer.protocol.adt.message.server.ServerMessage; import org.anddev.andengine.extension.multiplayer.protocol.client.IServerMessageHandler; import org.anddev.andengine.extension.multiplayer.protocol.client.connector.ServerConnector; import org.anddev.andengine.extension.multiplayer.protocol.client.connector.SocketConnectionServerConnector; import org.anddev.andengine.extension.multiplayer.protocol.client.connector.SocketConnectionServerConnector.ISocketConnectionServerConnectorListener; import org.anddev.andengine.extension.multiplayer.protocol.server.SocketServer; import org.anddev.andengine.extension.multiplayer.protocol.server.SocketServer.ISocketServerListener; import org.anddev.andengine.extension.multiplayer.protocol.server.connector.ClientConnector; import org.anddev.andengine.extension.multiplayer.protocol.server.connector.SocketConnectionClientConnector; import org.anddev.andengine.extension.multiplayer.protocol.server.connector.SocketConnectionClientConnector.ISocketConnectionClientConnectorListener; import org.anddev.andengine.extension.multiplayer.protocol.shared.SocketConnection; import org.anddev.andengine.extension.multiplayer.protocol.util.MessagePool; import org.anddev.andengine.extension.multiplayer.protocol.util.WifiUtils; 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.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.util.SparseArray; import android.view.KeyEvent; import android.widget.EditText; import android.widget.Toast; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 17:10:24 - 19.06.2010 */ public class MultiplayerExample extends BaseExample implements ClientMessageFlags, ServerMessageFlags { // =========================================================== // Constants // =========================================================== private static final String LOCALHOST_IP = "127.0.0.1"; private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; private static final int SERVER_PORT = 4444; private static final short FLAG_MESSAGE_SERVER_ADD_FACE = 1; private static final short FLAG_MESSAGE_SERVER_MOVE_FACE = FLAG_MESSAGE_SERVER_ADD_FACE + 1; private static final int DIALOG_CHOOSE_SERVER_OR_CLIENT_ID = 0; private static final int DIALOG_ENTER_SERVER_IP_ID = DIALOG_CHOOSE_SERVER_OR_CLIENT_ID + 1; private static final int DIALOG_SHOW_SERVER_IP_ID = DIALOG_ENTER_SERVER_IP_ID + 1; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mBitmapTextureAtlas; private TextureRegion mFaceTextureRegion; private int mFaceIDCounter; private final SparseArray<Sprite> mFaces = new SparseArray<Sprite>(); private String mServerIP = LOCALHOST_IP; private SocketServer<SocketConnectionClientConnector> mSocketServer; private ServerConnector<SocketConnection> mServerConnector; private final MessagePool<IMessage> mMessagePool = new MessagePool<IMessage>(); // =========================================================== // Constructors // =========================================================== public MultiplayerExample() { this.initMessagePool(); } private void initMessagePool() { this.mMessagePool.registerMessage(FLAG_MESSAGE_SERVER_ADD_FACE, AddFaceServerMessage.class); this.mMessagePool.registerMessage(FLAG_MESSAGE_SERVER_MOVE_FACE, MoveFaceServerMessage.class); } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { this.showDialog(DIALOG_CHOOSE_SERVER_OR_CLIENT_ID); 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)); /* We allow only the server to actively send around messages. */ if(MultiplayerExample.this.mSocketServer != null) { scene.setOnSceneTouchListener(new IOnSceneTouchListener() { @Override public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) { if(pSceneTouchEvent.isActionDown()) { try { final AddFaceServerMessage addFaceServerMessage = (AddFaceServerMessage) MultiplayerExample.this.mMessagePool.obtainMessage(FLAG_MESSAGE_SERVER_ADD_FACE); addFaceServerMessage.set(MultiplayerExample.this.mFaceIDCounter++, pSceneTouchEvent.getX(), pSceneTouchEvent.getY()); MultiplayerExample.this.mSocketServer.sendBroadcastServerMessage(addFaceServerMessage); MultiplayerExample.this.mMessagePool.recycleMessage(addFaceServerMessage); } catch (final IOException e) { Debug.e(e); } return true; } else { return true; } } }); scene.setOnAreaTouchListener(new IOnAreaTouchListener() { @Override public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final ITouchArea pTouchArea, final float pTouchAreaLocalX, final float pTouchAreaLocalY) { try { final Sprite face = (Sprite)pTouchArea; final Integer faceID = (Integer)face.getUserData(); final MoveFaceServerMessage moveFaceServerMessage = (MoveFaceServerMessage) MultiplayerExample.this.mMessagePool.obtainMessage(FLAG_MESSAGE_SERVER_MOVE_FACE); moveFaceServerMessage.set(faceID, pSceneTouchEvent.getX(), pSceneTouchEvent.getY()); MultiplayerExample.this.mSocketServer.sendBroadcastServerMessage(moveFaceServerMessage); MultiplayerExample.this.mMessagePool.recycleMessage(moveFaceServerMessage); } catch (final IOException e) { Debug.e(e); return false; } return true; } }); scene.setTouchAreaBindingEnabled(true); } return scene; } @Override public void onLoadComplete() { } @Override protected Dialog onCreateDialog(final int pID) { switch(pID) { case DIALOG_SHOW_SERVER_IP_ID: try { return new AlertDialog.Builder(this) .setIcon(android.R.drawable.ic_dialog_info) .setTitle("Your Server-IP ...") .setCancelable(false) .setMessage("The IP of your Server is:\n" + WifiUtils.getWifiIPv4Address(this)) .setPositiveButton(android.R.string.ok, null) .create(); } catch (final UnknownHostException e) { return new AlertDialog.Builder(this) .setIcon(android.R.drawable.ic_dialog_alert) .setTitle("Your Server-IP ...") .setCancelable(false) .setMessage("Error retrieving IP of your Server: " + e) .setPositiveButton(android.R.string.ok, new OnClickListener() { @Override public void onClick(final DialogInterface pDialog, final int pWhich) { MultiplayerExample.this.finish(); } }) .create(); } case DIALOG_ENTER_SERVER_IP_ID: final EditText ipEditText = new EditText(this); return new AlertDialog.Builder(this) .setIcon(android.R.drawable.ic_dialog_info) .setTitle("Enter Server-IP ...") .setCancelable(false) .setView(ipEditText) .setPositiveButton("Connect", new OnClickListener() { @Override public void onClick(final DialogInterface pDialog, final int pWhich) { MultiplayerExample.this.mServerIP = ipEditText.getText().toString(); MultiplayerExample.this.initClient(); } }) .setNegativeButton(android.R.string.cancel, new OnClickListener() { @Override public void onClick(final DialogInterface pDialog, final int pWhich) { MultiplayerExample.this.finish(); } }) .create(); case DIALOG_CHOOSE_SERVER_OR_CLIENT_ID: return new AlertDialog.Builder(this) .setIcon(android.R.drawable.ic_dialog_info) .setTitle("Be Server or Client ...") .setCancelable(false) .setPositiveButton("Client", new OnClickListener() { @Override public void onClick(final DialogInterface pDialog, final int pWhich) { MultiplayerExample.this.showDialog(DIALOG_ENTER_SERVER_IP_ID); } }) .setNeutralButton("Server", new OnClickListener() { @Override public void onClick(final DialogInterface pDialog, final int pWhich) { MultiplayerExample.this.toast("You can add and move sprites, which are only shown on the clients."); MultiplayerExample.this.initServer(); MultiplayerExample.this.showDialog(DIALOG_SHOW_SERVER_IP_ID); } }) .setNegativeButton("Both", new OnClickListener() { @Override public void onClick(final DialogInterface pDialog, final int pWhich) { MultiplayerExample.this.toast("You can add sprites and move them, by dragging them."); MultiplayerExample.this.initServerAndClient(); MultiplayerExample.this.showDialog(DIALOG_SHOW_SERVER_IP_ID); } }) .create(); default: return super.onCreateDialog(pID); } } @Override protected void onDestroy() { if(this.mSocketServer != null) { try { this.mSocketServer.sendBroadcastServerMessage(new ConnectionCloseServerMessage()); } catch (final IOException e) { Debug.e(e); } this.mSocketServer.terminate(); } if(this.mServerConnector != null) { this.mServerConnector.terminate(); } super.onDestroy(); } @Override public boolean onKeyUp(final int pKeyCode, final KeyEvent pEvent) { switch(pKeyCode) { case KeyEvent.KEYCODE_BACK: this.finish(); return true; } return super.onKeyUp(pKeyCode, pEvent); } // =========================================================== // Methods // =========================================================== public void addFace(final int pID, final float pX, final float pY) { final Scene scene = this.mEngine.getScene(); /* Create the face and add it to the scene. */ final Sprite face = new Sprite(0, 0, this.mFaceTextureRegion); face.setPosition(pX - face.getWidth() * 0.5f, pY - face.getHeight() * 0.5f); face.setUserData(pID); this.mFaces.put(pID, face); scene.registerTouchArea(face); scene.attachChild(face); } public void moveFace(final int pID, final float pX, final float pY) { /* Find and move the face. */ final Sprite face = this.mFaces.get(pID); face.setPosition(pX - face.getWidth() * 0.5f, pY - face.getHeight() * 0.5f); } private void initServerAndClient() { this.initServer(); /* Wait some time after the server has been started, so it actually can start up. */ try { Thread.sleep(500); } catch (final Throwable t) { Debug.e(t); } this.initClient(); } private void initServer() { this.mSocketServer = new SocketServer<SocketConnectionClientConnector>(SERVER_PORT, new ExampleClientConnectorListener(), new ExampleServerStateListener()) { @Override protected SocketConnectionClientConnector newClientConnector(final SocketConnection pSocketConnection) throws IOException { return new SocketConnectionClientConnector(pSocketConnection); } }; this.mSocketServer.start(); } private void initClient() { try { this.mServerConnector = new SocketConnectionServerConnector(new SocketConnection(new Socket(this.mServerIP, SERVER_PORT)), new ExampleServerConnectorListener()); this.mServerConnector.registerServerMessage(FLAG_MESSAGE_SERVER_CONNECTION_CLOSE, ConnectionCloseServerMessage.class, new IServerMessageHandler<SocketConnection>() { @Override public void onHandleMessage(final ServerConnector<SocketConnection> pServerConnector, final IServerMessage pServerMessage) throws IOException { MultiplayerExample.this.finish(); } }); this.mServerConnector.registerServerMessage(FLAG_MESSAGE_SERVER_ADD_FACE, AddFaceServerMessage.class, new IServerMessageHandler<SocketConnection>() { @Override public void onHandleMessage(final ServerConnector<SocketConnection> pServerConnector, final IServerMessage pServerMessage) throws IOException { final AddFaceServerMessage addFaceServerMessage = (AddFaceServerMessage)pServerMessage; MultiplayerExample.this.addFace(addFaceServerMessage.mID, addFaceServerMessage.mX, addFaceServerMessage.mY); } }); this.mServerConnector.registerServerMessage(FLAG_MESSAGE_SERVER_MOVE_FACE, MoveFaceServerMessage.class, new IServerMessageHandler<SocketConnection>() { @Override public void onHandleMessage(final ServerConnector<SocketConnection> pServerConnector, final IServerMessage pServerMessage) throws IOException { final MoveFaceServerMessage moveFaceServerMessage = (MoveFaceServerMessage)pServerMessage; MultiplayerExample.this.moveFace(moveFaceServerMessage.mID, moveFaceServerMessage.mX, moveFaceServerMessage.mY); } }); this.mServerConnector.getConnection().start(); } catch (final Throwable t) { Debug.e(t); } } private void log(final String pMessage) { Debug.d(pMessage); } private void toast(final String pMessage) { this.log(pMessage); this.runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(MultiplayerExample.this, pMessage, Toast.LENGTH_SHORT).show(); } }); } // =========================================================== // Inner and Anonymous Classes // =========================================================== public static class AddFaceServerMessage extends ServerMessage { private int mID; private float mX; private float mY; public AddFaceServerMessage() { } public AddFaceServerMessage(final int pID, final float pX, final float pY) { this.mID = pID; this.mX = pX; this.mY = pY; } public void set(final int pID, final float pX, final float pY) { this.mID = pID; this.mX = pX; this.mY = pY; } @Override public short getFlag() { return FLAG_MESSAGE_SERVER_ADD_FACE; } @Override protected void onReadTransmissionData(final DataInputStream pDataInputStream) throws IOException { this.mID = pDataInputStream.readInt(); this.mX = pDataInputStream.readFloat(); this.mY = pDataInputStream.readFloat(); } @Override protected void onWriteTransmissionData(final DataOutputStream pDataOutputStream) throws IOException { pDataOutputStream.writeInt(this.mID); pDataOutputStream.writeFloat(this.mX); pDataOutputStream.writeFloat(this.mY); } } public static class MoveFaceServerMessage extends ServerMessage { private int mID; private float mX; private float mY; public MoveFaceServerMessage() { } public MoveFaceServerMessage(final int pID, final float pX, final float pY) { this.mID = pID; this.mX = pX; this.mY = pY; } public void set(final int pID, final float pX, final float pY) { this.mID = pID; this.mX = pX; this.mY = pY; } @Override public short getFlag() { return FLAG_MESSAGE_SERVER_MOVE_FACE; } @Override protected void onReadTransmissionData(final DataInputStream pDataInputStream) throws IOException { this.mID = pDataInputStream.readInt(); this.mX = pDataInputStream.readFloat(); this.mY = pDataInputStream.readFloat(); } @Override protected void onWriteTransmissionData(final DataOutputStream pDataOutputStream) throws IOException { pDataOutputStream.writeInt(this.mID); pDataOutputStream.writeFloat(this.mX); pDataOutputStream.writeFloat(this.mY); } } private class ExampleServerConnectorListener implements ISocketConnectionServerConnectorListener { @Override public void onStarted(final ServerConnector<SocketConnection> pConnector) { MultiplayerExample.this.toast("CLIENT: Connected to server."); } @Override public void onTerminated(final ServerConnector<SocketConnection> pConnector) { MultiplayerExample.this.toast("CLIENT: Disconnected from Server..."); MultiplayerExample.this.finish(); } } private class ExampleServerStateListener implements ISocketServerListener<SocketConnectionClientConnector> { @Override public void onStarted(final SocketServer<SocketConnectionClientConnector> pSocketServer) { MultiplayerExample.this.toast("SERVER: Started."); } @Override public void onTerminated(final SocketServer<SocketConnectionClientConnector> pSocketServer) { MultiplayerExample.this.toast("SERVER: Terminated."); } @Override public void onException(final SocketServer<SocketConnectionClientConnector> pSocketServer, final Throwable pThrowable) { Debug.e(pThrowable); MultiplayerExample.this.toast("SERVER: Exception: " + pThrowable); } } private class ExampleClientConnectorListener implements ISocketConnectionClientConnectorListener { @Override public void onStarted(final ClientConnector<SocketConnection> pConnector) { MultiplayerExample.this.toast("SERVER: Client connected: " + pConnector.getConnection().getSocket().getInetAddress().getHostAddress()); } @Override public void onTerminated(final ClientConnector<SocketConnection> pConnector) { MultiplayerExample.this.toast("SERVER: Client disconnected: " + pConnector.getConnection().getSocket().getInetAddress().getHostAddress()); } } }
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.modifier.MoveModifier; 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.augmentedreality.BaseAugmentedRealityGameActivity; 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 AugmentedRealityExample extends BaseAugmentedRealityGameActivity { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mBitmapTextureAtlas; private TextureRegion mFaceTextureRegion; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { Toast.makeText(this, "If you don't see a sprite moving over the screen, try starting this while already being in Landscape orientation!!", 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.setBackgroundEnabled(false); scene.setBackground(new ColorBackground(0.0f, 0.0f, 0.0f, 0.0f)); 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); face.registerEntityModifier(new MoveModifier(30, 0, CAMERA_WIDTH - face.getWidth(), 0, CAMERA_HEIGHT - face.getHeight())); scene.attachChild(face); return scene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== // =========================================================== // 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 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 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.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 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 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; 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 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; 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.util.HashMap; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.ZoomCamera; 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.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.detector.PinchZoomDetector; import org.anddev.andengine.extension.input.touch.detector.PinchZoomDetector.IPinchZoomDetectorListener; import org.anddev.andengine.extension.input.touch.exception.MultiTouchException; import org.anddev.andengine.input.touch.TouchEvent; import org.anddev.andengine.input.touch.detector.ScrollDetector; import org.anddev.andengine.input.touch.detector.ScrollDetector.IScrollDetectorListener; import org.anddev.andengine.input.touch.detector.SurfaceScrollDetector; 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 15:44:58 - 05.11.2010 */ public class PinchZoomExample extends BaseExample implements IOnSceneTouchListener, IScrollDetectorListener, IPinchZoomDetectorListener { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; // =========================================================== // Fields // =========================================================== private ZoomCamera mZoomCamera; private BitmapTextureAtlas mCardDeckTexture; private Scene mScene; private HashMap<Card, TextureRegion> mCardTotextureRegionMap; private SurfaceScrollDetector mScrollDetector; private PinchZoomDetector mPinchZoomDetector; private float mPinchZoomStartedCameraZoomFactor; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { this.mZoomCamera = new ZoomCamera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); final Engine engine = new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mZoomCamera)); try { if(MultiTouch.isSupported(this)) { engine.setTouchController(new MultiTouchController()); } else { Toast.makeText(this, "Sorry your device does NOT support MultiTouch!\n\n(No PinchZoom is possible!)", Toast.LENGTH_LONG).show(); } } catch (final MultiTouchException e) { Toast.makeText(this, "Sorry your Android Version does NOT support MultiTouch!\n\n(No PinchZoom is possible!)", 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.mScrollDetector = new SurfaceScrollDetector(this); if(MultiTouch.isSupportedByAndroidVersion()) { try { this.mPinchZoomDetector = new PinchZoomDetector(this); } catch (final MultiTouchException e) { this.mPinchZoomDetector = null; } } else { this.mPinchZoomDetector = null; } this.mScene.setOnSceneTouchListener(this); this.mScene.setTouchAreaBindingEnabled(true); return this.mScene; } @Override public void onLoadComplete() { } @Override public void onScroll(final ScrollDetector pScollDetector, final TouchEvent pTouchEvent, final float pDistanceX, final float pDistanceY) { final float zoomFactor = this.mZoomCamera.getZoomFactor(); this.mZoomCamera.offsetCenter(-pDistanceX / zoomFactor, -pDistanceY / zoomFactor); } @Override public void onPinchZoomStarted(final PinchZoomDetector pPinchZoomDetector, final TouchEvent pTouchEvent) { this.mPinchZoomStartedCameraZoomFactor = this.mZoomCamera.getZoomFactor(); } @Override public void onPinchZoom(final PinchZoomDetector pPinchZoomDetector, final TouchEvent pTouchEvent, final float pZoomFactor) { this.mZoomCamera.setZoomFactor(this.mPinchZoomStartedCameraZoomFactor * pZoomFactor); } @Override public void onPinchZoomFinished(final PinchZoomDetector pPinchZoomDetector, final TouchEvent pTouchEvent, final float pZoomFactor) { this.mZoomCamera.setZoomFactor(this.mPinchZoomStartedCameraZoomFactor * pZoomFactor); } @Override public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) { if(this.mPinchZoomDetector != null) { this.mPinchZoomDetector.onTouchEvent(pSceneTouchEvent); if(this.mPinchZoomDetector.isZooming()) { this.mScrollDetector.setEnabled(false); } else { if(pSceneTouchEvent.isActionDown()) { this.mScrollDetector.setEnabled(true); } this.mScrollDetector.onTouchEvent(pSceneTouchEvent); } } else { this.mScrollDetector.onTouchEvent(pSceneTouchEvent); } return true; } // =========================================================== // 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 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.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.ITextureAtlas; import org.anddev.andengine.opengl.texture.atlas.ITextureAtlas.ITextureAtlasStateListener; 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.IBitmapTextureAtlasSource; 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 ImageFormatsExample 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 mPNGTextureRegion; private TextureRegion mJPGTextureRegion; private TextureRegion mGIFTextureRegion; private TextureRegion mBMPTextureRegion; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { Toast.makeText(this, "GIF is not supported yet. Use PNG instead, it's the better format anyway!", 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.BILINEAR_PREMULTIPLYALPHA, new ITextureAtlasStateListener.TextureAtlasStateAdapter<IBitmapTextureAtlasSource>() { @Override public void onTextureAtlasSourceLoadExeption(final ITextureAtlas<IBitmapTextureAtlasSource> pTextureAtlas, final IBitmapTextureAtlasSource pBitmapTextureAtlasSource, final Throwable pThrowable) { ImageFormatsExample.this.runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(ImageFormatsExample.this, "Failed loading TextureSource: " + pBitmapTextureAtlasSource.toString(), Toast.LENGTH_LONG).show(); } }); } }); BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mPNGTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "imageformat_png.png", 0, 0); this.mJPGTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "imageformat_jpg.jpg", 49, 0); this.mGIFTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "imageformat_gif.gif", 0, 49); this.mBMPTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "imageformat_bmp.bmp", 49, 49); 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)); /* Create the icons and add them to the scene. */ scene.attachChild(new Sprite(160 - 24, 106 - 24, this.mPNGTextureRegion)); scene.attachChild(new Sprite(160 - 24, 213 - 24, this.mJPGTextureRegion)); scene.attachChild(new Sprite(320 - 24, 106 - 24, this.mGIFTextureRegion)); scene.attachChild(new Sprite(320 - 24, 213 - 24, this.mBMPTextureRegion)); 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.modifier.MoveModifier; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.scene.menu.MenuScene; import org.anddev.andengine.entity.scene.menu.MenuScene.IOnMenuItemClickListener; import org.anddev.andengine.entity.scene.menu.item.IMenuItem; import org.anddev.andengine.entity.scene.menu.item.SpriteMenuItem; 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.region.TextureRegion; import android.view.KeyEvent; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 01:30:15 - 02.04.2010 */ public class MenuExample extends BaseExample implements IOnMenuItemClickListener { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; protected static final int MENU_RESET = 0; protected static final int MENU_QUIT = MENU_RESET + 1; // =========================================================== // Fields // =========================================================== protected Camera mCamera; protected Scene mMainScene; private BitmapTextureAtlas mBitmapTextureAtlas; private TextureRegion mFaceTextureRegion; protected MenuScene mMenuScene; private BitmapTextureAtlas mMenuTexture; protected TextureRegion mMenuResetTextureRegion; protected TextureRegion mMenuQuitTextureRegion; // =========================================================== // 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() { BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mBitmapTextureAtlas = new BitmapTextureAtlas(64, 64, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "face_box_menu.png", 0, 0); this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); this.mMenuTexture = new BitmapTextureAtlas(256, 128, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mMenuResetTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mMenuTexture, this, "menu_reset.png", 0, 0); this.mMenuQuitTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mMenuTexture, this, "menu_quit.png", 0, 50); this.mEngine.getTextureManager().loadTexture(this.mMenuTexture); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); this.createMenuScene(); /* Just a simple scene with an animated face flying around. */ this.mMainScene = new Scene(); this.mMainScene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); final Sprite face = new Sprite(0, 0, this.mFaceTextureRegion); face.registerEntityModifier(new MoveModifier(30, 0, CAMERA_WIDTH - face.getWidth(), 0, CAMERA_HEIGHT - face.getHeight())); this.mMainScene.attachChild(face); return this.mMainScene; } @Override public void onLoadComplete() { } @Override public boolean onKeyDown(final int pKeyCode, final KeyEvent pEvent) { if(pKeyCode == KeyEvent.KEYCODE_MENU && pEvent.getAction() == KeyEvent.ACTION_DOWN) { if(this.mMainScene.hasChildScene()) { /* Remove the menu and reset it. */ this.mMenuScene.back(); } else { /* Attach the menu. */ this.mMainScene.setChildScene(this.mMenuScene, false, true, true); } return true; } else { return super.onKeyDown(pKeyCode, pEvent); } } @Override public boolean onMenuItemClicked(final MenuScene pMenuScene, final IMenuItem pMenuItem, final float pMenuItemLocalX, final float pMenuItemLocalY) { switch(pMenuItem.getID()) { case MENU_RESET: /* Restart the animation. */ this.mMainScene.reset(); /* Remove the menu and reset it. */ this.mMainScene.clearChildScene(); this.mMenuScene.reset(); return true; case MENU_QUIT: /* End Activity. */ this.finish(); return true; default: return false; } } // =========================================================== // Methods // =========================================================== protected void createMenuScene() { this.mMenuScene = new MenuScene(this.mCamera); final SpriteMenuItem resetMenuItem = new SpriteMenuItem(MENU_RESET, this.mMenuResetTextureRegion); resetMenuItem.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); this.mMenuScene.addMenuItem(resetMenuItem); final SpriteMenuItem quitMenuItem = new SpriteMenuItem(MENU_QUIT, this.mMenuQuitTextureRegion); quitMenuItem.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); this.mMenuScene.addMenuItem(quitMenuItem); this.mMenuScene.buildAnimations(); this.mMenuScene.setBackgroundEnabled(false); this.mMenuScene.setOnMenuItemClickListener(this); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import java.util.Random; 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.Line; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.util.FPSLogger; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 11:54:51 - 03.04.2010 */ public class LineExample extends BaseExample { // =========================================================== // Constants // =========================================================== /* Initializing the Random generator produces a comparable result over different versions. */ private static final long RANDOM_SEED = 1234567890; private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; private static final int LINE_COUNT = 100; // =========================================================== // Fields // =========================================================== private Camera mCamera; // =========================================================== // 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() { } @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 Random random = new Random(RANDOM_SEED); for(int i = 0; i < LINE_COUNT; i++) { final float x1 = random.nextFloat() * CAMERA_WIDTH; final float x2 = random.nextFloat() * CAMERA_WIDTH; final float y1 = random.nextFloat() * CAMERA_HEIGHT; final float y2 = random.nextFloat() * CAMERA_HEIGHT; final float lineWidth = random.nextFloat() * 5; final Line line = new Line(x1, y1, x2, y2, lineWidth); line.setColor(random.nextFloat(), random.nextFloat(), random.nextFloat()); scene.attachChild(line); } 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.engine.Engine; import org.anddev.andengine.engine.SingleSceneSplitScreenEngine; import org.anddev.andengine.engine.camera.BoundCamera; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.camera.hud.HUD; 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.shape.Shape; import org.anddev.andengine.entity.sprite.AnimatedSprite; import org.anddev.andengine.entity.sprite.TiledSprite; 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 18:08:29 - 27.07.2010 */ public class BoundCameraExample extends BaseExample implements IAccelerometerListener, IOnSceneTouchListener { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 400; private static final int CAMERA_HEIGHT = 480; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BoundCamera mBoundChaseCamera; private Scene mScene; private PhysicsWorld mPhysicsWorld; private BitmapTextureAtlas mBitmapTextureAtlas; private TiledTextureRegion mBoxFaceTextureRegion; private BitmapTextureAtlas mHUDTexture; private TiledTextureRegion mToggleButtonTextureRegion; private int mFaceCount; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { Toast.makeText(this, "Touch the screen to add boxes.", Toast.LENGTH_LONG).show(); this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); this.mBoundChaseCamera = new BoundCamera(0, 0, CAMERA_WIDTH / 2, CAMERA_HEIGHT / 2, 0, CAMERA_WIDTH, 0, CAMERA_HEIGHT); final EngineOptions engineOptions = new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH * 2, CAMERA_HEIGHT), this.mCamera); engineOptions.getTouchOptions().setRunOnUpdateThread(true); return new SingleSceneSplitScreenEngine(engineOptions, this.mBoundChaseCamera); } @Override public void onLoadResources() { BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mBitmapTextureAtlas = new BitmapTextureAtlas(64, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mBoxFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "face_box_tiled.png", 0, 0, 2, 1); // 64x32 this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); this.mHUDTexture = new BitmapTextureAtlas(256, 128,TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mToggleButtonTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mHUDTexture, this, "toggle_button.png", 0, 0, 2, 1); // 256x128 this.mEngine.getTextureManager().loadTexture(this.mHUDTexture); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); this.mScene = new Scene(); 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); final HUD hud = new HUD(); final TiledSprite toggleButton = new TiledSprite(CAMERA_WIDTH / 2 - this.mToggleButtonTextureRegion.getTileWidth(), CAMERA_HEIGHT / 2 - this.mToggleButtonTextureRegion.getTileHeight(), this.mToggleButtonTextureRegion){ @Override public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final float pTouchAreaLocalX, final float pTouchAreaLocalY) { if(pSceneTouchEvent.isActionDown()) { final boolean boundsEnabled = BoundCameraExample.this.mBoundChaseCamera.isBoundsEnabled(); if(boundsEnabled) { BoundCameraExample.this.mBoundChaseCamera.setBoundsEnabled(false); this.setCurrentTileIndex(1); BoundCameraExample.this.runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(BoundCameraExample.this, "Bounds Disabled.", Toast.LENGTH_SHORT).show(); } }); } else { BoundCameraExample.this.mBoundChaseCamera.setBoundsEnabled(true); this.setCurrentTileIndex(0); BoundCameraExample.this.runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(BoundCameraExample.this, "Bounds Enabled.", Toast.LENGTH_SHORT).show(); } }); } } return true; } }; hud.registerTouchArea(toggleButton); hud.attachChild(toggleButton); this.mBoundChaseCamera.setHUD(hud); 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) { final FixtureDef objectFixtureDef = PhysicsFactory.createFixtureDef(1, 0.5f, 0.5f); final AnimatedSprite face = new AnimatedSprite(pX, pY, this.mBoxFaceTextureRegion).animate(100); final Body body = PhysicsFactory.createBoxBody(this.mPhysicsWorld, face, BodyType.DynamicBody, objectFixtureDef); this.mScene.attachChild(face); this.mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(face, body, true, true)); if(this.mFaceCount == 0){ this.mBoundChaseCamera.setChaseEntity(face); } this.mFaceCount++; } // =========================================================== // 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 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 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.scene.Scene; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.text.ChangeableText; import org.anddev.andengine.entity.util.FPSCounter; import org.anddev.andengine.opengl.font.Font; 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 20:06:15 - 08.07.2010 */ public class ChangeableTextExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mFontTexture; private Font mFont; // =========================================================== // 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.mFont = new Font(this.mFontTexture, Typeface.create(Typeface.DEFAULT, Typeface.BOLD), 48, true, Color.BLACK); this.mEngine.getTextureManager().loadTexture(this.mFontTexture); this.getFontManager().loadFont(this.mFont); } @Override public Scene onLoadScene() { final FPSCounter fpsCounter = new FPSCounter(); this.mEngine.registerUpdateHandler(fpsCounter); final Scene scene = new Scene(); scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); final ChangeableText elapsedText = new ChangeableText(100, 160, this.mFont, "Seconds elapsed:", "Seconds elapsed: XXXXX".length()); final ChangeableText fpsText = new ChangeableText(250, 240, this.mFont, "FPS:", "FPS: XXXXX".length()); scene.attachChild(elapsedText); scene.attachChild(fpsText); scene.registerUpdateHandler(new TimerHandler(1 / 20.0f, true, new ITimerCallback() { @Override public void onTimePassed(final TimerHandler pTimerHandler) { elapsedText.setText("Seconds elapsed: " + ChangeableTextExample.this.mEngine.getSecondsElapsedTotal()); fpsText.setText("FPS: " + fpsCounter.getFPS()); } })); 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.sprite.Sprite; import org.anddev.andengine.entity.sprite.batch.DynamicSpriteBatch; import org.anddev.andengine.entity.sprite.batch.SpriteBatch; 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 14:27:22 - 14.06.2011 */ public class SpriteBatchExample 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 mFaceTextureRegion; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { this.mCamera = new Camera(0, 0, SpriteBatchExample.CAMERA_WIDTH, SpriteBatchExample.CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(SpriteBatchExample.CAMERA_WIDTH, SpriteBatchExample.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)); /* Calculate the coordinates for the face, so its centered on the camera. */ final int centerX = (SpriteBatchExample.CAMERA_WIDTH - this.mFaceTextureRegion.getWidth()) / 2; final int centerY = (SpriteBatchExample.CAMERA_HEIGHT - this.mFaceTextureRegion.getHeight()) / 2; final Sprite faceSprite1 = new Sprite(-50, 0, this.mFaceTextureRegion); final Sprite faceSprite2 = new Sprite(50, 0, this.mFaceTextureRegion); faceSprite1.setScale(2); faceSprite2.setRotation(45); /* Create the face and add it to the scene. */ final SpriteBatch dynamicSpriteBatch = new DynamicSpriteBatch(this.mBitmapTextureAtlas, 2) { @Override protected boolean onUpdateSpriteBatch() { this.draw(faceSprite1); this.draw(faceSprite2); return true; } }; final SpriteBatch staticSpriteBatch = new SpriteBatch(this.mBitmapTextureAtlas, 2); staticSpriteBatch.draw(this.mFaceTextureRegion, -50, 0, this.mFaceTextureRegion.getWidth(), this.mFaceTextureRegion.getHeight(), 2, 2); staticSpriteBatch.draw(this.mFaceTextureRegion, 50, 0, this.mFaceTextureRegion.getWidth(), this.mFaceTextureRegion.getHeight(), 45); staticSpriteBatch.submit(); dynamicSpriteBatch.setPosition(centerX, centerY - 50); staticSpriteBatch.setPosition(centerX, centerY + 50); scene.attachChild(dynamicSpriteBatch); scene.attachChild(staticSpriteBatch); 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.Entity; 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.util.FPSLogger; import org.anddev.andengine.entity.util.ScreenCapture; import org.anddev.andengine.entity.util.ScreenCapture.IScreenCaptureCallback; import org.anddev.andengine.input.touch.TouchEvent; import org.anddev.andengine.util.FileUtils; import android.widget.Toast; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 11:54:51 - 03.04.2010 */ public class RectangleExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; // =========================================================== // Fields // =========================================================== private Camera mCamera; // =========================================================== // 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() { } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); final ScreenCapture screenCapture = new ScreenCapture(); scene.attachChild(screenCapture); scene.setOnSceneTouchListener(new IOnSceneTouchListener() { @Override public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) { if(pSceneTouchEvent.isActionDown()) { screenCapture.capture(180, 60, 360, 360, FileUtils.getAbsolutePathOnExternalStorage(RectangleExample.this, "Screen_" + System.currentTimeMillis() + ".png"), new IScreenCaptureCallback() { @Override public void onScreenCaptured(final String pFilePath) { RectangleExample.this.runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(RectangleExample.this, "Screenshot: " + pFilePath + " taken!", Toast.LENGTH_SHORT).show(); } }); } @Override public void onScreenCaptureFailed(final String pFilePath, final Exception pException) { RectangleExample.this.runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(RectangleExample.this, "FAILED capturing Screenshot: " + pFilePath + " !", Toast.LENGTH_SHORT).show(); } }); } }); } return true; } }); scene.setBackground(new ColorBackground(0, 0, 0)); /* Create the rectangles. */ final Rectangle rect1 = this.makeColoredRectangle(-180, -180, 1, 0, 0); final Rectangle rect2 = this.makeColoredRectangle(0, -180, 0, 1, 0); final Rectangle rect3 = this.makeColoredRectangle(0, 0, 0, 0, 1); final Rectangle rect4 = this.makeColoredRectangle(-180, 0, 1, 1, 0); final Entity rectangleGroup = new Entity(CAMERA_WIDTH / 2, CAMERA_HEIGHT / 2); rectangleGroup.attachChild(rect1); rectangleGroup.attachChild(rect2); rectangleGroup.attachChild(rect3); rectangleGroup.attachChild(rect4); scene.attachChild(rectangleGroup); return scene; } private Rectangle makeColoredRectangle(final float pX, final float pY, final float pRed, final float pGreen, final float pBlue) { final Rectangle coloredRect = new Rectangle(pX, pY, 180, 180); coloredRect.setColor(pRed, pGreen, pBlue); return coloredRect; } @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.sprite.Sprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.extension.augmentedreality.BaseAugmentedRealityGameActivity; 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.sensor.orientation.IOrientationListener; import org.anddev.andengine.sensor.orientation.OrientationData; 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 AugmentedRealityHorizonExample extends BaseAugmentedRealityGameActivity implements IOrientationListener { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mBitmapTextureAtlas; private TextureRegion mFaceTextureRegion; private Sprite mFace; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { Toast.makeText(this, "If you don't see a sprite moving over the screen, try starting this while already being in Landscape orientation!!", 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.setBackgroundEnabled(false); scene.setBackground(new ColorBackground(0.0f, 0.0f, 0.0f, 0.0f)); final int centerX = (CAMERA_WIDTH - this.mFaceTextureRegion.getWidth()) / 2; final int centerY = (CAMERA_HEIGHT - this.mFaceTextureRegion.getHeight()) / 2; this.mFace = new Sprite(centerX, centerY, this.mFaceTextureRegion); scene.attachChild(this.mFace); return scene; } @Override public void onLoadComplete() { this.enableOrientationSensor(this); } @Override public void onOrientationChanged(final OrientationData pOrientationData) { final float roll = pOrientationData.getRoll(); Debug.d("Roll: " + pOrientationData.getRoll()); this.mFace.setPosition(CAMERA_WIDTH / 2, CAMERA_HEIGHT / 2 + (roll - 40) * 5); } // =========================================================== // 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.FixedStepPhysicsWorld; 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 18:47:08 - 19.03.2010 */ public class PhysicsFixedStepExample extends BaseExample implements IAccelerometerListener, IOnSceneTouchListener { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; // =========================================================== // 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_SHORT).show(); Toast.makeText(this, "The difference to the normal physics example is that here the simulation steps have a fixed size, which makes the simuation reproduceable.", 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 FixedStepPhysicsWorld(30, new Vector2(0, SensorManager.GRAVITY_EARTH), false, 3, 2); 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.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); } 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.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.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 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 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 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.IShape; 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.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 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; import com.badlogic.gdx.physics.box2d.BodyDef.BodyType; import com.badlogic.gdx.physics.box2d.FixtureDef; import com.badlogic.gdx.physics.box2d.joints.MouseJoint; import com.badlogic.gdx.physics.box2d.joints.MouseJointDef; /** * @author albrandroid * @author Nicolas Gramlich * @since 10:35:23 - 28.02.2011 */ public class PhysicsMouseJointExample extends BaseExample implements IAccelerometerListener, IOnSceneTouchListener, IOnAreaTouchListener { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; private static final FixtureDef FIXTURE_DEF = PhysicsFactory.createFixtureDef(1, 0.5f, 0.5f); // =========================================================== // Fields // =========================================================== private BitmapTextureAtlas mBitmapTextureAtlas; private TiledTextureRegion mBoxFaceTextureRegion; private TiledTextureRegion mCircleFaceTextureRegion; private Scene mScene; private PhysicsWorld mPhysicsWorld; private int mFaceCount = 0; private MouseJoint mMouseJointActive; private Body mGroundBody; // =========================================================== // 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() { /* 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.mScene.setOnAreaTouchListener(this); this.mPhysicsWorld = new PhysicsWorld(new Vector2(0, SensorManager.GRAVITY_EARTH), false); this.mGroundBody = this.mPhysicsWorld.createBody(new BodyDef()); 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() { this.mEngine.enableVibrator(this); } @Override public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) { if(this.mPhysicsWorld != null) { switch(pSceneTouchEvent.getAction()) { case TouchEvent.ACTION_DOWN: this.addFace(pSceneTouchEvent.getX(), pSceneTouchEvent.getY()); return true; case TouchEvent.ACTION_MOVE: if(this.mMouseJointActive != null) { final Vector2 vec = Vector2Pool.obtain(pSceneTouchEvent.getX() / PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT, pSceneTouchEvent.getY() / PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT); this.mMouseJointActive.setTarget(vec); Vector2Pool.recycle(vec); } return true; case TouchEvent.ACTION_UP: if(this.mMouseJointActive != null) { this.mPhysicsWorld.destroyJoint(this.mMouseJointActive); this.mMouseJointActive = null; } return true; } return false; } return false; } @Override public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final ITouchArea pTouchArea, final float pTouchAreaLocalX, final float pTouchAreaLocalY) { if(pSceneTouchEvent.isActionDown()) { final IShape face = (IShape) pTouchArea; /* * If we have a active MouseJoint, we are just moving it around * instead of creating a second one. */ if(this.mMouseJointActive == null) { this.mEngine.vibrate(100); this.mMouseJointActive = this.createMouseJoint(face, pTouchAreaLocalX, pTouchAreaLocalY); } 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 // =========================================================== public MouseJoint createMouseJoint(final IShape pFace, final float pTouchAreaLocalX, final float pTouchAreaLocalY) { final Body body = (Body) pFace.getUserData(); final MouseJointDef mouseJointDef = new MouseJointDef(); final Vector2 localPoint = Vector2Pool.obtain((pTouchAreaLocalX - pFace.getWidth() * 0.5f) / PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT, (pTouchAreaLocalY - pFace.getHeight() * 0.5f) / PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT); this.mGroundBody.setTransform(localPoint, 0); mouseJointDef.bodyA = this.mGroundBody; mouseJointDef.bodyB = body; mouseJointDef.dampingRatio = 0.95f; mouseJointDef.frequencyHz = 30; mouseJointDef.maxForce = (200.0f * body.getMass()); mouseJointDef.collideConnected = true; mouseJointDef.target.set(body.getWorldPoint(localPoint)); Vector2Pool.recycle(localPoint); return (MouseJoint) this.mPhysicsWorld.createJoint(mouseJointDef); } 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, FIXTURE_DEF); } else { face = new AnimatedSprite(pX, pY, this.mCircleFaceTextureRegion); body = PhysicsFactory.createCircleBody(this.mPhysicsWorld, face, BodyType.DynamicBody, FIXTURE_DEF); } face.setUserData(body); face.animate(200); this.mScene.registerTouchArea(face); 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.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.input.touch.TouchEvent; import org.anddev.andengine.opengl.buffer.BufferObjectManager; 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 UnloadResourcesExample 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 mClickToUnloadTextureRegion; // =========================================================== // 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(128, 128, TextureOptions.BILINEAR_PREMULTIPLYALPHA); BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mClickToUnloadTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "click_to_unload.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)); final int x = (CAMERA_WIDTH - this.mClickToUnloadTextureRegion.getWidth()) / 2; final int y = (CAMERA_HEIGHT - this.mClickToUnloadTextureRegion.getHeight()) / 2; final Sprite clickToUnload = new Sprite(x, y, this.mClickToUnloadTextureRegion) { @Override public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final float pTouchAreaLocalX, final float pTouchAreaLocalY) { /* Completely remove all resources associated with this sprite. */ BufferObjectManager.getActiveInstance().unloadBufferObject(this.getVertexBuffer()); BufferObjectManager.getActiveInstance().unloadBufferObject(UnloadResourcesExample.this.mClickToUnloadTextureRegion.getTextureBuffer()); UnloadResourcesExample.this.mEngine.getTextureManager().unloadTexture(UnloadResourcesExample.this.mBitmapTextureAtlas); /* And remove the sprite from the Scene. */ final Sprite thisRef = this; UnloadResourcesExample.this.runOnUiThread(new Runnable() { @Override public void run() { scene.detachChild(thisRef); } }); return true; } }; scene.attachChild(clickToUnload); scene.registerTouchArea(clickToUnload); 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.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.util; import java.util.Set; import org.anddev.andengine.examples.R; import android.app.Activity; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.view.View; import android.view.Window; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListView; import android.widget.TextView; /** * This Activity appears as a dialog. It lists any paired devices and * devices detected in the area after discovery. When a device is chosen * by the user, the MAC address of the device is sent back to the parent * Activity in the result Intent. * * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 12:19:52 - 06.03.2011 */ public class BluetoothListDevicesActivity extends Activity { // =========================================================== // Constants // =========================================================== public static String EXTRA_DEVICE_ADDRESS = "device_address"; // =========================================================== // Fields // =========================================================== private BluetoothAdapter mBluetoothAdapter; private ArrayAdapter<String> mPairedDevicesArrayAdapter; private ArrayAdapter<String> mNewDevicesArrayAdapter; private final OnItemClickListener mDeviceClickListener = new OnItemClickListener() { @Override public void onItemClick(final AdapterView<?> pAdapterView, final View pView, final int pPosition, final long pID) { // Cancel discovery because it's costly and we're about to connect BluetoothListDevicesActivity.this.mBluetoothAdapter.cancelDiscovery(); // Get the device MAC address, which is the last 17 chars in the View final String info = ((TextView) pView).getText().toString(); final String address = info.substring(info.length() - 17); // Create the result Intent and include the MAC address final Intent intent = new Intent(); intent.putExtra(EXTRA_DEVICE_ADDRESS, address); // Set result and finish this Activity BluetoothListDevicesActivity.this.setResult(Activity.RESULT_OK, intent); BluetoothListDevicesActivity.this.finish(); } }; // The BroadcastReceiver that listens for discovered devices and // changes the title when discovery is finished private final BroadcastReceiver mReceiver = new BroadcastReceiver() { @Override public void onReceive(final Context pContext, final Intent pIntent) { final String action = pIntent.getAction(); if (action.equals(BluetoothDevice.ACTION_FOUND)) { final BluetoothDevice device = pIntent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); if (device.getBondState() != BluetoothDevice.BOND_BONDED) { BluetoothListDevicesActivity.this.mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress()); } } else if (action.equals(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)) { BluetoothListDevicesActivity.this.setProgressBarIndeterminateVisibility(false); BluetoothListDevicesActivity.this.setTitle("Select a device to connect..."); if (BluetoothListDevicesActivity.this.mNewDevicesArrayAdapter.getCount() == 0) { BluetoothListDevicesActivity.this.mNewDevicesArrayAdapter.add("No devices found!"); } } } }; // =========================================================== // Constructors // =========================================================== @Override protected void onCreate(final Bundle pSavedInstanceState) { super.onCreate(pSavedInstanceState); this.requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); this.setContentView(R.layout.list_bluetooth_devices); // Set result CANCELED in case the user backs out this.setResult(Activity.RESULT_CANCELED); final Button scanButton = (Button) this.findViewById(R.id.button_scan); scanButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(final View v) { BluetoothListDevicesActivity.this.discoverBluetoothDevices(); v.setVisibility(View.GONE); } }); this.mPairedDevicesArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1); this.mNewDevicesArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1); final ListView pairedListView = (ListView) this.findViewById(R.id.paired_devices); pairedListView.setAdapter(this.mPairedDevicesArrayAdapter); pairedListView.setOnItemClickListener(this.mDeviceClickListener); final ListView newDevicesListView = (ListView) this.findViewById(R.id.new_devices); newDevicesListView.setAdapter(this.mNewDevicesArrayAdapter); newDevicesListView.setOnItemClickListener(this.mDeviceClickListener); // Register for broadcasts when a device is discovered IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); this.registerReceiver(this.mReceiver, filter); // Register for broadcasts when discovery has finished filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED); this.registerReceiver(this.mReceiver, filter); this.mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); // Get a set of currently paired devices final Set<BluetoothDevice> pairedDevices = this.mBluetoothAdapter.getBondedDevices(); if (pairedDevices.size() > 0) { this.findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE); for (final BluetoothDevice device : pairedDevices) { this.mPairedDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress()); } } else { this.mPairedDevicesArrayAdapter.add("No devices have been paired!"); } } @Override protected void onDestroy() { super.onDestroy(); // Make sure we're not doing discovery anymore if (this.mBluetoothAdapter != null) { this.mBluetoothAdapter.cancelDiscovery(); } // Unregister broadcast listeners this.unregisterReceiver(this.mReceiver); } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== private void discoverBluetoothDevices() { this.setProgressBarIndeterminateVisibility(true); this.setTitle("Scanning for devices..."); this.findViewById(R.id.title_new_devices).setVisibility(View.VISIBLE); if (this.mBluetoothAdapter.isDiscovering()) { this.mBluetoothAdapter.cancelDiscovery(); } this.mBluetoothAdapter.startDiscovery(); } // =========================================================== // 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.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 java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.InetAddress; import java.net.Socket; import java.net.SocketTimeoutException; import java.net.UnknownHostException; 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.IOnSceneTouchListener; 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.examples.adt.messages.client.ClientMessageFlags; import org.anddev.andengine.examples.adt.messages.server.ConnectionCloseServerMessage; import org.anddev.andengine.examples.adt.messages.server.ServerMessageFlags; import org.anddev.andengine.extension.multiplayer.protocol.adt.message.IMessage; import org.anddev.andengine.extension.multiplayer.protocol.adt.message.server.IServerMessage; import org.anddev.andengine.extension.multiplayer.protocol.adt.message.server.ServerMessage; import org.anddev.andengine.extension.multiplayer.protocol.client.IServerMessageHandler; import org.anddev.andengine.extension.multiplayer.protocol.client.SocketServerDiscoveryClient; import org.anddev.andengine.extension.multiplayer.protocol.client.SocketServerDiscoveryClient.ISocketServerDiscoveryClientListener; import org.anddev.andengine.extension.multiplayer.protocol.client.connector.ServerConnector; import org.anddev.andengine.extension.multiplayer.protocol.client.connector.SocketConnectionServerConnector; import org.anddev.andengine.extension.multiplayer.protocol.client.connector.SocketConnectionServerConnector.ISocketConnectionServerConnectorListener; import org.anddev.andengine.extension.multiplayer.protocol.server.SocketServer; import org.anddev.andengine.extension.multiplayer.protocol.server.SocketServer.ISocketServerListener; import org.anddev.andengine.extension.multiplayer.protocol.server.SocketServerDiscoveryServer; import org.anddev.andengine.extension.multiplayer.protocol.server.SocketServerDiscoveryServer.ISocketServerDiscoveryServerListener; import org.anddev.andengine.extension.multiplayer.protocol.server.connector.ClientConnector; import org.anddev.andengine.extension.multiplayer.protocol.server.connector.SocketConnectionClientConnector; import org.anddev.andengine.extension.multiplayer.protocol.server.connector.SocketConnectionClientConnector.ISocketConnectionClientConnectorListener; import org.anddev.andengine.extension.multiplayer.protocol.shared.IDiscoveryData.DefaultDiscoveryData; import org.anddev.andengine.extension.multiplayer.protocol.shared.SocketConnection; import org.anddev.andengine.extension.multiplayer.protocol.util.IPUtils; import org.anddev.andengine.extension.multiplayer.protocol.util.MessagePool; import org.anddev.andengine.extension.multiplayer.protocol.util.WifiUtils; 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.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.util.SparseArray; import android.view.KeyEvent; import android.widget.Toast; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 17:10:24 - 19.06.2010 */ public class MultiplayerServerDiscoveryExample extends BaseExample implements ClientMessageFlags, ServerMessageFlags { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; private static final int SERVER_PORT = 4444; private static final int DISCOVERY_PORT = 4445; private static final int LOCAL_PORT = 4446; private static final short FLAG_MESSAGE_SERVER_ADD_FACE = 1; private static final short FLAG_MESSAGE_SERVER_MOVE_FACE = FLAG_MESSAGE_SERVER_ADD_FACE + 1; private static final int DIALOG_CHOOSE_SERVER_OR_CLIENT_ID = 0; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mBitmapTextureAtlas; private TextureRegion mFaceTextureRegion; private int mFaceIDCounter; private final SparseArray<Sprite> mFaces = new SparseArray<Sprite>(); private SocketServer<SocketConnectionClientConnector> mSocketServer; private ServerConnector<SocketConnection> mServerConnector; private final MessagePool<IMessage> mMessagePool = new MessagePool<IMessage>(); private SocketServerDiscoveryServer<DefaultDiscoveryData> mSocketServerDiscoveryServer; private SocketServerDiscoveryClient<DefaultDiscoveryData> mSocketServerDiscoveryClient; // =========================================================== // Constructors // =========================================================== public MultiplayerServerDiscoveryExample() { this.initMessagePool(); } private void initMessagePool() { this.mMessagePool.registerMessage(FLAG_MESSAGE_SERVER_ADD_FACE, AddFaceServerMessage.class); this.mMessagePool.registerMessage(FLAG_MESSAGE_SERVER_MOVE_FACE, MoveFaceServerMessage.class); } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { this.showDialog(DIALOG_CHOOSE_SERVER_OR_CLIENT_ID); 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)); /* We allow only the server to actively send around messages. */ if(MultiplayerServerDiscoveryExample.this.mSocketServer != null) { scene.setOnSceneTouchListener(new IOnSceneTouchListener() { @Override public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) { if(pSceneTouchEvent.isActionDown()) { try { final AddFaceServerMessage addFaceServerMessage = (AddFaceServerMessage) MultiplayerServerDiscoveryExample.this.mMessagePool.obtainMessage(FLAG_MESSAGE_SERVER_ADD_FACE); addFaceServerMessage.set(MultiplayerServerDiscoveryExample.this.mFaceIDCounter++, pSceneTouchEvent.getX(), pSceneTouchEvent.getY()); MultiplayerServerDiscoveryExample.this.mSocketServer.sendBroadcastServerMessage(addFaceServerMessage); MultiplayerServerDiscoveryExample.this.mMessagePool.recycleMessage(addFaceServerMessage); } catch (final IOException e) { Debug.e(e); } return true; } else { return false; } } }); scene.setOnAreaTouchListener(new IOnAreaTouchListener() { @Override public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final ITouchArea pTouchArea, final float pTouchAreaLocalX, final float pTouchAreaLocalY) { try { final Sprite face = (Sprite)pTouchArea; final Integer faceID = (Integer)face.getUserData(); final MoveFaceServerMessage moveFaceServerMessage = (MoveFaceServerMessage) MultiplayerServerDiscoveryExample.this.mMessagePool.obtainMessage(FLAG_MESSAGE_SERVER_MOVE_FACE); moveFaceServerMessage.set(faceID, pSceneTouchEvent.getX(), pSceneTouchEvent.getY()); MultiplayerServerDiscoveryExample.this.mSocketServer.sendBroadcastServerMessage(moveFaceServerMessage); MultiplayerServerDiscoveryExample.this.mMessagePool.recycleMessage(moveFaceServerMessage); } catch (final IOException e) { Debug.e(e); return false; } return true; } }); scene.setTouchAreaBindingEnabled(true); } return scene; } @Override public void onLoadComplete() { } @Override protected Dialog onCreateDialog(final int pID) { switch(pID) { case DIALOG_CHOOSE_SERVER_OR_CLIENT_ID: return new AlertDialog.Builder(this) .setIcon(android.R.drawable.ic_dialog_info) .setTitle("Be Server or Client ...") .setMessage("For automatic ServerDiscovery to work, all devices need to be on the same WiFi!") .setCancelable(false) .setPositiveButton("Client", new OnClickListener() { @Override public void onClick(final DialogInterface pDialog, final int pWhich) { MultiplayerServerDiscoveryExample.this.initServerDiscovery(); } }) .setNeutralButton("Server", new OnClickListener() { @Override public void onClick(final DialogInterface pDialog, final int pWhich) { MultiplayerServerDiscoveryExample.this.toast("You can add and move sprites, which are only shown on the clients."); MultiplayerServerDiscoveryExample.this.initServer(); } }) .setNegativeButton("Both", new OnClickListener() { @Override public void onClick(final DialogInterface pDialog, final int pWhich) { MultiplayerServerDiscoveryExample.this.toast("You can add sprites and move them, by dragging them."); MultiplayerServerDiscoveryExample.this.initServerAndClient(); } }) .create(); default: return super.onCreateDialog(pID); } } @Override protected void onDestroy() { if(this.mSocketServer != null) { try { this.mSocketServer.sendBroadcastServerMessage(new ConnectionCloseServerMessage()); } catch (final IOException e) { Debug.e(e); } this.mSocketServer.terminate(); } if(this.mSocketServerDiscoveryServer != null) { this.mSocketServerDiscoveryServer.terminate(); } if(this.mServerConnector != null) { this.mServerConnector.terminate(); } if(this.mSocketServerDiscoveryClient != null) { this.mSocketServerDiscoveryClient.terminate(); } super.onDestroy(); } @Override public boolean onKeyUp(final int pKeyCode, final KeyEvent pEvent) { switch(pKeyCode) { case KeyEvent.KEYCODE_BACK: this.finish(); return true; } return super.onKeyUp(pKeyCode, pEvent); } // =========================================================== // Methods // =========================================================== public void addFace(final int pID, final float pX, final float pY) { final Scene scene = this.mEngine.getScene(); /* Create the face and add it to the scene. */ final Sprite face = new Sprite(0, 0, this.mFaceTextureRegion); face.setPosition(pX - face.getWidth() * 0.5f, pY - face.getHeight() * 0.5f); face.setUserData(pID); this.mFaces.put(pID, face); scene.registerTouchArea(face); scene.attachChild(face); } public void moveFace(final int pID, final float pX, final float pY) { /* Find and move the face. */ final Sprite face = this.mFaces.get(pID); face.setPosition(pX - face.getWidth() * 0.5f, pY - face.getHeight() * 0.5f); } private void initServerAndClient() { this.initServer(); /* Wait some time after the server has been started, so it actually can start up. */ try { Thread.sleep(500); } catch (final Throwable t) { Debug.e(t); } this.initServerDiscovery(); } private void initServer() { this.mSocketServer = new SocketServer<SocketConnectionClientConnector>(SERVER_PORT, new ExampleClientConnectorListener(), new ExampleServerStateListener()) { @Override protected SocketConnectionClientConnector newClientConnector(final SocketConnection pSocketConnection) throws IOException { return new SocketConnectionClientConnector(pSocketConnection); } }; this.mSocketServer.start(); try { final byte[] wifiIPv4Address = WifiUtils.getWifiIPv4AddressRaw(this); this.mSocketServerDiscoveryServer = new SocketServerDiscoveryServer<DefaultDiscoveryData>(DISCOVERY_PORT, new ExampleSocketServerDiscoveryServerListener()) { @Override protected DefaultDiscoveryData onCreateDiscoveryResponse() { return new DefaultDiscoveryData(wifiIPv4Address, SERVER_PORT); } }; this.mSocketServerDiscoveryServer.start(); } catch (final Throwable t) { Debug.e(t); } } private void initServerDiscovery() { try { this.mSocketServerDiscoveryClient = new SocketServerDiscoveryClient<DefaultDiscoveryData>(WifiUtils.getBroadcastIPAddressRaw(this), DISCOVERY_PORT, LOCAL_PORT, DefaultDiscoveryData.class, new ISocketServerDiscoveryClientListener<DefaultDiscoveryData>() { @Override public void onDiscovery(final SocketServerDiscoveryClient<DefaultDiscoveryData> pSocketServerDiscoveryClient, final DefaultDiscoveryData pDiscoveryData) { try { final String ipAddressAsString = IPUtils.ipAddressToString(pDiscoveryData.getServerIP()); MultiplayerServerDiscoveryExample.this.toast("DiscoveryClient: Server discovered at: " + ipAddressAsString + ":" + pDiscoveryData.getServerPort()); MultiplayerServerDiscoveryExample.this.initClient(ipAddressAsString, pDiscoveryData.getServerPort()); } catch (final UnknownHostException e) { MultiplayerServerDiscoveryExample.this.toast("DiscoveryClient: IPException: " + e); } } @Override public void onTimeout(final SocketServerDiscoveryClient<DefaultDiscoveryData> pSocketServerDiscoveryClient, final SocketTimeoutException pSocketTimeoutException) { Debug.e(pSocketTimeoutException); MultiplayerServerDiscoveryExample.this.toast("DiscoveryClient: Timeout: " + pSocketTimeoutException); } @Override public void onException(final SocketServerDiscoveryClient<DefaultDiscoveryData> pSocketServerDiscoveryClient, final Throwable pThrowable) { Debug.e(pThrowable); MultiplayerServerDiscoveryExample.this.toast("DiscoveryClient: Exception: " + pThrowable); } }); this.mSocketServerDiscoveryClient.discoverAsync(); } catch (final Throwable t) { Debug.e(t); } } private void initClient(final String pIPAddress, final int pPort) { try { this.mServerConnector = new SocketConnectionServerConnector(new SocketConnection(new Socket(pIPAddress, pPort)), new ExampleServerConnectorListener()); this.mServerConnector.registerServerMessage(FLAG_MESSAGE_SERVER_CONNECTION_CLOSE, ConnectionCloseServerMessage.class, new IServerMessageHandler<SocketConnection>() { @Override public void onHandleMessage(final ServerConnector<SocketConnection> pServerConnector, final IServerMessage pServerMessage) throws IOException { MultiplayerServerDiscoveryExample.this.finish(); } }); this.mServerConnector.registerServerMessage(FLAG_MESSAGE_SERVER_ADD_FACE, AddFaceServerMessage.class, new IServerMessageHandler<SocketConnection>() { @Override public void onHandleMessage(final ServerConnector<SocketConnection> pServerConnector, final IServerMessage pServerMessage) throws IOException { final AddFaceServerMessage addFaceServerMessage = (AddFaceServerMessage)pServerMessage; MultiplayerServerDiscoveryExample.this.addFace(addFaceServerMessage.mID, addFaceServerMessage.mX, addFaceServerMessage.mY); } }); this.mServerConnector.registerServerMessage(FLAG_MESSAGE_SERVER_MOVE_FACE, MoveFaceServerMessage.class, new IServerMessageHandler<SocketConnection>() { @Override public void onHandleMessage(final ServerConnector<SocketConnection> pServerConnector, final IServerMessage pServerMessage) throws IOException { final MoveFaceServerMessage moveFaceServerMessage = (MoveFaceServerMessage)pServerMessage; MultiplayerServerDiscoveryExample.this.moveFace(moveFaceServerMessage.mID, moveFaceServerMessage.mX, moveFaceServerMessage.mY); } }); this.mServerConnector.getConnection().start(); } catch (final Throwable t) { Debug.e(t); } } private void log(final String pMessage) { Debug.d(pMessage); } private void toast(final String pMessage) { this.log(pMessage); this.runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(MultiplayerServerDiscoveryExample.this, pMessage, Toast.LENGTH_SHORT).show(); } }); } // =========================================================== // Inner and Anonymous Classes // =========================================================== public static class AddFaceServerMessage extends ServerMessage { private int mID; private float mX; private float mY; public AddFaceServerMessage() { } public AddFaceServerMessage(final int pID, final float pX, final float pY) { this.mID = pID; this.mX = pX; this.mY = pY; } public void set(final int pID, final float pX, final float pY) { this.mID = pID; this.mX = pX; this.mY = pY; } @Override public short getFlag() { return FLAG_MESSAGE_SERVER_ADD_FACE; } @Override protected void onReadTransmissionData(final DataInputStream pDataInputStream) throws IOException { this.mID = pDataInputStream.readInt(); this.mX = pDataInputStream.readFloat(); this.mY = pDataInputStream.readFloat(); } @Override protected void onWriteTransmissionData(final DataOutputStream pDataOutputStream) throws IOException { pDataOutputStream.writeInt(this.mID); pDataOutputStream.writeFloat(this.mX); pDataOutputStream.writeFloat(this.mY); } } public static class MoveFaceServerMessage extends ServerMessage { private int mID; private float mX; private float mY; public MoveFaceServerMessage() { } public MoveFaceServerMessage(final int pID, final float pX, final float pY) { this.mID = pID; this.mX = pX; this.mY = pY; } public void set(final int pID, final float pX, final float pY) { this.mID = pID; this.mX = pX; this.mY = pY; } @Override public short getFlag() { return FLAG_MESSAGE_SERVER_MOVE_FACE; } @Override protected void onReadTransmissionData(final DataInputStream pDataInputStream) throws IOException { this.mID = pDataInputStream.readInt(); this.mX = pDataInputStream.readFloat(); this.mY = pDataInputStream.readFloat(); } @Override protected void onWriteTransmissionData(final DataOutputStream pDataOutputStream) throws IOException { pDataOutputStream.writeInt(this.mID); pDataOutputStream.writeFloat(this.mX); pDataOutputStream.writeFloat(this.mY); } } private class ExampleServerConnectorListener implements ISocketConnectionServerConnectorListener { @Override public void onStarted(final ServerConnector<SocketConnection> pConnector) { MultiplayerServerDiscoveryExample.this.toast("Client: Connected to server."); } @Override public void onTerminated(final ServerConnector<SocketConnection> pConnector) { MultiplayerServerDiscoveryExample.this.toast("Client: Disconnected from Server..."); MultiplayerServerDiscoveryExample.this.finish(); } } private class ExampleServerStateListener implements ISocketServerListener<SocketConnectionClientConnector> { @Override public void onStarted(final SocketServer<SocketConnectionClientConnector> pSocketServer) { MultiplayerServerDiscoveryExample.this.toast("Server: Started."); } @Override public void onTerminated(final SocketServer<SocketConnectionClientConnector> pSocketServer) { MultiplayerServerDiscoveryExample.this.toast("Server: Terminated."); } @Override public void onException(final SocketServer<SocketConnectionClientConnector> pSocketServer, final Throwable pThrowable) { Debug.e(pThrowable); MultiplayerServerDiscoveryExample.this.toast("Server: Exception: " + pThrowable); } } private class ExampleClientConnectorListener implements ISocketConnectionClientConnectorListener { @Override public void onStarted(final ClientConnector<SocketConnection> pConnector) { MultiplayerServerDiscoveryExample.this.toast("Server: Client connected: " + pConnector.getConnection().getSocket().getInetAddress().getHostAddress()); } @Override public void onTerminated(final ClientConnector<SocketConnection> pConnector) { MultiplayerServerDiscoveryExample.this.toast("Server: Client disconnected: " + pConnector.getConnection().getSocket().getInetAddress().getHostAddress()); } } public class ExampleSocketServerDiscoveryServerListener implements ISocketServerDiscoveryServerListener<DefaultDiscoveryData> { @Override public void onStarted(final SocketServerDiscoveryServer<DefaultDiscoveryData> pSocketServerDiscoveryServer) { MultiplayerServerDiscoveryExample.this.toast("DiscoveryServer: Started."); } @Override public void onTerminated(final SocketServerDiscoveryServer<DefaultDiscoveryData> pSocketServerDiscoveryServer) { MultiplayerServerDiscoveryExample.this.toast("DiscoveryServer: Terminated."); } @Override public void onException(final SocketServerDiscoveryServer<DefaultDiscoveryData> pSocketServerDiscoveryServer, final Throwable pThrowable) { Debug.e(pThrowable); MultiplayerServerDiscoveryExample.this.toast("DiscoveryServer: Exception: " + pThrowable); } @Override public void onDiscovered(final SocketServerDiscoveryServer<DefaultDiscoveryData> pSocketServerDiscoveryServer, final InetAddress pInetAddress, final int pPort) { MultiplayerServerDiscoveryExample.this.toast("DiscoveryServer: Discovered by: " + pInetAddress.getHostAddress() + ":" + pPort); } } }
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.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.region.TiledTextureRegion; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 13:58:48 - 19.07.2010 */ public class RepeatingSpriteBackgroundExample 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() { 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); /* Calculate the coordinates for the face, so its centered on the camera. */ final int centerX = (CAMERA_WIDTH - this.mPlayerTextureRegion.getTileWidth()) / 2; final int centerY = (CAMERA_HEIGHT - this.mPlayerTextureRegion.getTileHeight()) / 2; /* Create the sprite and add it to the scene. */ final AnimatedSprite player = new AnimatedSprite(centerX, centerY, 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); player.registerEntityModifier(new LoopEntityModifier(new PathModifier(30, path, null, new IPathModifierListener() { @Override public void onPathStarted(final PathModifier pPathModifier, final IEntity pEntity) { } @Override public void onPathWaypointStarted(final PathModifier pPathModifier, final IEntity pEntity, final int 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) { } @Override public void onPathFinished(final PathModifier pPathModifier, final IEntity pEntity) { } }))); scene.attachChild(player); return scene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import static org.anddev.andengine.extension.physics.box2d.util.constants.PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT; 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; import com.badlogic.gdx.physics.box2d.PolygonShape; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 18:47:08 - 19.03.2010 */ public class PhysicsExample extends BaseExample implements IAccelerometerListener, IOnSceneTouchListener { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; private static final FixtureDef FIXTURE_DEF = PhysicsFactory.createFixtureDef(1, 0.5f, 0.5f); // =========================================================== // Fields // =========================================================== private BitmapTextureAtlas mBitmapTextureAtlas; private TiledTextureRegion mBoxFaceTextureRegion; private TiledTextureRegion mCircleFaceTextureRegion; private TiledTextureRegion mTriangleFaceTextureRegion; private TiledTextureRegion mHexagonFaceTextureRegion; 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(); 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, 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()); 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; if(this.mFaceCount % 4 == 0) { face = new AnimatedSprite(pX, pY, this.mBoxFaceTextureRegion); body = PhysicsFactory.createBoxBody(this.mPhysicsWorld, face, BodyType.DynamicBody, FIXTURE_DEF); } else if (this.mFaceCount % 4 == 1) { face = new AnimatedSprite(pX, pY, this.mCircleFaceTextureRegion); body = PhysicsFactory.createCircleBody(this.mPhysicsWorld, face, BodyType.DynamicBody, FIXTURE_DEF); } else if (this.mFaceCount % 4 == 2) { face = new AnimatedSprite(pX, pY, this.mTriangleFaceTextureRegion); body = PhysicsExample.createTriangleBody(this.mPhysicsWorld, face, BodyType.DynamicBody, FIXTURE_DEF); } else { face = new AnimatedSprite(pX, pY, this.mHexagonFaceTextureRegion); body = PhysicsExample.createHexagonBody(this.mPhysicsWorld, face, BodyType.DynamicBody, FIXTURE_DEF); } face.animate(200); this.mScene.attachChild(face); this.mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(face, body, true, true)); } /** * Creates a {@link Body} based on a {@link PolygonShape} in the form of a triangle: * <pre> * /\ * /__\ * </pre> */ private static Body createTriangleBody(final PhysicsWorld pPhysicsWorld, final Shape pShape, final BodyType pBodyType, final FixtureDef pFixtureDef) { /* Remember that the vertices are relative to the center-coordinates of the Shape. */ final float halfWidth = pShape.getWidthScaled() * 0.5f / PIXEL_TO_METER_RATIO_DEFAULT; final float halfHeight = pShape.getHeightScaled() * 0.5f / PIXEL_TO_METER_RATIO_DEFAULT; final float top = -halfHeight; final float bottom = halfHeight; final float left = -halfHeight; final float centerX = 0; final float right = halfWidth; final Vector2[] vertices = { new Vector2(centerX, top), new Vector2(right, bottom), new Vector2(left, bottom) }; return PhysicsFactory.createPolygonBody(pPhysicsWorld, pShape, vertices, pBodyType, pFixtureDef); } /** * Creates a {@link Body} based on a {@link PolygonShape} in the form of a hexagon: * <pre> * /\ * / \ * | | * | | * \ / * \/ * </pre> */ private static Body createHexagonBody(final PhysicsWorld pPhysicsWorld, final Shape pShape, final BodyType pBodyType, final FixtureDef pFixtureDef) { /* Remember that the vertices are relative to the center-coordinates of the Shape. */ final float halfWidth = pShape.getWidthScaled() * 0.5f / PIXEL_TO_METER_RATIO_DEFAULT; final float halfHeight = pShape.getHeightScaled() * 0.5f / PIXEL_TO_METER_RATIO_DEFAULT; /* The top and bottom vertex of the hexagon are on the bottom and top of hexagon-sprite. */ final float top = -halfHeight; final float bottom = halfHeight; final float centerX = 0; /* The left and right vertices of the heaxgon are not on the edge of the hexagon-sprite, so we need to inset them a little. */ final float left = -halfWidth + 2.5f / PIXEL_TO_METER_RATIO_DEFAULT; final float right = halfWidth - 2.5f / PIXEL_TO_METER_RATIO_DEFAULT; final float higher = top + 8.25f / PIXEL_TO_METER_RATIO_DEFAULT; final float lower = bottom - 8.25f / PIXEL_TO_METER_RATIO_DEFAULT; final Vector2[] vertices = { new Vector2(centerX, top), new Vector2(right, higher), new Vector2(right, lower), new Vector2(centerX, bottom), new Vector2(left, lower), new Vector2(left, higher) }; return PhysicsFactory.createPolygonBody(pPhysicsWorld, pShape, vertices, pBodyType, pFixtureDef); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package ambient_network_simulation; import java.util.List; /** * * @author DTT */ public class TreeVertice { private VirtualNetwork vn; private ReadWriteLock lock; private int hierarchieLevel; private TreeEdge edgeUp; private List<TreeEdge> edgesDown; public TreeVertice(VirtualNetwork vn, int h, TreeEdge up, List<TreeEdge> down) { this.vn = vn; this.hierarchieLevel = h; this.edgeUp = up; this.edgesDown = down; this.lock = new ReadWriteLock(); } /** * Visszaadja a tartalmazott VirtualNetwork-öt * @return VirtualNetwork */ public VirtualNetwork getVn() { return vn; } /** * Vissza adja, hogy melyik hierarchia szinten van. * @return int hierarchiLevel */ public int getHierarchieLevel() { return hierarchieLevel; } /** * Beállítja a hierarchia szintet. * @param hierarchieLevel amire be akarjuk állítani */ public void setHierarchieLevel(int hierarchieLevel) { this.hierarchieLevel = hierarchieLevel; } /** * A lefelé mutató élekhez tudunk ezzel hozzáadni egyet. * @param d a hozzáadandó él. */ public void addEdgeDown(TreeEdge d) { this.edgesDown.add(d); } /** * Beállítja a felfelé mutató élet. * @param edgeUp a felfelé mutató él */ public void setEdgeUp(TreeEdge edgeUp) { this.edgeUp = edgeUp; } /** * Visszadja, hogy a paraméterként kapott TreeVertice ezen csúcs felett van-e, mint gateway. * @param v TreeVertice, amiről tudni akarjuk, hogy ennek gateway-je-e * @return true, ha gateway, false, ha nincs felette. */ public boolean isChild(TreeVertice v) { if (this.edgeUp != null) { if (this.edgeUp.getNeighbour(this) == v) { return true; } else { this.edgeUp.getNeighbour(this).isChild(v); } } return false; } /** * A paraméterként kapott élet eltávolítja a lefelé muatató éllistájából. * @param te az eltávolítandó él. */ public void removeEdge(TreeEdge te) { if (te == this.edgeUp) { this.edgeUp = null; } else { edgesDown.remove(te); } } }
Java
package ambient_network_simulation; /** * * @author DTT */ public class Simulate { private Graph physicalLayer; private Graph virtualLayer; private Graph hierarchicalLayer; public void start() { throw new UnsupportedOperationException(); } public void composition() { throw new UnsupportedOperationException(); } }
Java
package ambient_network_simulation; import java.util.List; /** * * @author Karcsi */ public class Node { private String name; private List<Policy> policy; private boolean isSuperPeer; private VirtualNetwork isInThisVn; public void exit() { throw new UnsupportedOperationException(); } public void updateVn() { throw new UnsupportedOperationException(); } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ambient_network_simulation; import java.util.ArrayList; import java.util.List; /** * * @author Karcsi */ public class Main { /** * @param args the command line arguments */ public static void main(String[] args) { // Property a=new Property("tibi", 50, 60); // Property b=new Property("kari", 40, 70); // Property c=new Property("csaba", 30, 60); // Property d=new Property("kari", 40, 50); // Property e=new Property("tibi", 50, 50); // Property f=new Property("csaba", 40, 70); // // List<Property> pla=new ArrayList<Property>(); // List<Property> plb=new ArrayList<Property>(); // // pla.add(a); // pla.add(b); // pla.add(c); // // plb.add(d); // plb.add(e); // plb.add(f); // // Policy x=new Policy(pla); // Policy y=new Policy(plb); // // x.checkPolicy(y); // System.out.println("---------------------------"); // y.checkPolicy(x); // System.out.println("---------------------------"); // x.evaluatePolicy(y); // System.out.println("---------------------------"); Vertice v1=new Vertice(null); Vertice v2=new Vertice(null); Vertice v3=new Vertice(null); Vertice v4=new Vertice(null); Vertice v5=new Vertice(null); Edge e1= new Edge(v1, v5); Edge e2= new Edge(v2, v5); Edge e3= new Edge(v3, v5); Edge e4= new Edge(v4, v5); Edge e5= new Edge(v1, v3); Edge e6= new Edge(v3, v2); List<Edge> el= new ArrayList<Edge>(); el.add(e1); el.add(e2); el.add(e3); el.add(e4); el.add(e5); el.add(e6); List<Vertice> vl=new ArrayList<Vertice>(); vl.add(v1); vl.add(v2); vl.add(v3); vl.add(v4); vl.add(v5); System. out.println("-------------------------------------------"); Graph g= new Graph(vl, el); e1.counterplus(1); System. out.println("1-------------------------------------------"); g.unio(v1, v3); System. out.println("2-------------------------------------------"); g.unio(v4, v5); System. out.println("3-------------------------------------------"); g.removeVertice(v2); // TODO code application logic here } }
Java
package ambient_network_simulation; import java.util.Iterator; import java.util.List; import java.util.Random; /** * * @author Karcsi */ public class Graph { private List<Vertice> vertices; private List<Edge> edges; /** * Konstruktor * @param vertices * @param edges */ public Graph(List<Vertice> vertices, List<Edge> edges) { this.vertices = vertices; this.edges = edges; } /** * A paraméterként kapott b csúcs éleit a megfelelő módon hozzáadja az a csúcshoz. * @param a amelyikhez hozzá akarjuk adni b éleit * @param b amelyik éleit hozzáadjuk a-hoz */ public void unio(Vertice a, Vertice b) { a.join(b); } /** * Kiszed egy csúcsot a gráfból * @param v */ public void removeVertice(Vertice v) { Iterator<Edge> it = this.edges.iterator(); while (it.hasNext()) { it.next().delete(true); } this.vertices.remove(v); } public Vertice getRandomV(int seed) { System.out.println("Random él visszaadása."); int numberOfVertices=this.vertices.size(); int random; Random rand= new Random(seed); random=rand.nextInt(numberOfVertices+1); return this.vertices.get(random); } }
Java
package ambient_network_simulation; import java.util.List; /** * * @author DTT */ public class TreeGraph { private List<TreeVertice> vertices; private List<TreeEdge> edges; public TreeGraph(List<TreeVertice> vertices, List<TreeEdge> edges) { this.vertices = vertices; this.edges = edges; } }
Java
package ambient_network_simulation; /** * * @author DTT */ public class TreeEdge { private TreeVertice verticeUp; private TreeVertice verticeDown; public TreeEdge(TreeVertice verticeUp, TreeVertice verticeDown) { this.verticeUp = verticeUp; verticeUp.setEdgeUp(this); this.verticeDown = verticeDown; verticeDown.addEdgeDown(this); } /** * A paraméterben megadott csúcs szomszédját adja vissza * @param v * @return */ public TreeVertice getNeighbour(TreeVertice v){ if (this.verticeUp == v){ return this.verticeDown; } else{ return this.verticeUp; } } /** * törli az élet: kitörli magát a két végpontjának az éllistájából. */ public void delete(){ this.verticeUp.removeEdge(this); this.verticeDown.removeEdge(this); } }
Java
package ambient_network_simulation; /** * Ezek az objektumok egy-egy tulajdonságot tartalmaznak. * Ehhez a tulajdonsághoz tartozik egy név, egy szolgáltatott érték, és egy elvárt érték. * @author DTT */ public class Property { private String name; private int required; private int provided; /** * Ezt a konstruktort akkor használjuk, ha Gateway-t hozunk létre. * @param a egyik tul. * @param b másik tul. */ public Property(Property a, Property b) { name = a.name; this.provided = (int) ((a.provided + b.provided) / 2); if (a.required < b.required) { this.required = a.required; } else { this.required = b.required; } } /** * Konstruktor * @param name * @param required * @param provided */ public Property(String name, int required, int provided) { this.name = name; this.required = required; this.provided = provided; } /** * Név lekérése * @return tulajdonság neve */ public String getName() { return name; } /** * Ellenörzi, hogy a paramétreként kapott tulajdonság milyen csatlakozáshoz elég. * @param p másik tulajdonsága, akihez csatlakozni akar a vn. * @return true ha abszorbcióra is jó, false ha csak gateway */ public boolean check(Property p) { System.out.println("Check: "+ this.name + " és " + p.name); if (this.required >= p.provided && this.provided >= p.required && p.required >= this.provided && p.provided >= this.required) { System.out.println("Chechk lefutott false értékkel."); return false; } else { System.out.println("Chechk lefutott true értékkel."); return true; } } /** * Ez a függvény értékeli ki a tulajdonságokat egymáshoz viszonyítva * @param p másik tulajdonsága, akihez csatlakozni akar a vn. * @return a két tulajdonság átlaga */ public int evaluate(Property p) { System.out.println("Eveluate: "+ this.name + " és " + p.name + " Értéke: " + ((int) ((this.provided + p.provided) / 2))); return (int) ((this.provided + p.provided) / 2); } /** * Ez a függvény állítja be az új tulajdonságot abszorbció után. * Ezt a függvényt azon vn tulajdonságaiban hívjuk meg, amelyhez csatlakoznak. * @param p a csatlakozni kívánó fél egyik tulajdonsága */ public void updateAbs(Property p) { System.out.println("updateAbs: "+ this.name + " és " + p.name); if (this.required < p.required) { this.required = p.required; } this.provided = evaluate(p); System.out.println("Új értékek: szolgáltatott:"+ this.provided + ", elvárt:" + this.required); } }
Java
package ambient_network_simulation; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * Csúcsok osztálya * @author DTT */ public class Vertice { private VirtualNetwork vn; private List<Edge> edges; private ReadWriteLock lock; /** * Konstruktor * @param vn */ public Vertice(VirtualNetwork vn) { this.vn = vn; this.edges = new ArrayList<Edge>(); this.lock = new ReadWriteLock(); } /** * Megadja a csúcshoz tartozó VirtualNetwork-öt * @return */ public VirtualNetwork getVn() { return vn; } /** * Él eltávolítása * @param e */ public void removeEdge(Edge e) { edges.remove(e); System.out.println("Csúcs éllistájából él törölve."); } /** * Él hozzáadása a listához. * Amennyiben már szerepelt akkor csak az él számlálóját növeljük. * @param e */ public void addEdge(Edge e) { Iterator<Edge> it = this.edges.iterator(); while (it.hasNext()) { Edge temp = it.next(); if (temp.equal(e)) { temp.counterplus(e.getCounter()); return; } } edges.add(e); System.out.println("Csúcs éllistájához él hozzáadva."); } /** * A csúcs szomszédait adja meg egy listában. (VirtualNetwork lista) * @return */ public List<VirtualNetwork> getNeighbours() { List<VirtualNetwork> result = new ArrayList<VirtualNetwork>(); Iterator<Edge> it = this.edges.iterator(); while (it.hasNext()) { result.add(it.next().getNeighbour(this).getVn()); } return result; } /** * Egy másik csúcs szomszédait hozzáadja ehhez a csúcshoz. * @param v a másik csúcs */ public void join(Vertice v) { System.out.println("Csúcs join elindult."); Iterator<Edge> itThis = this.edges.iterator(); Iterator<Edge> itV = v.edges.iterator(); /** * Végigiterálunk ennek és a paraméterként kapott csúcsnak az élein, és a kettő közötti éleket töröljük, * illetve az azonos egyéb csúcsra mutató éleknél ennek a csúcsnak a megfelelő élének beállítjuk a számlálóját, * majd a másik csúcs listájából töröljük. * Így ez a részlet lefutása után v-nek csak azok az élei maradnak, amikhez ennek a csúcsnak eddig semmi köze nem volt. */ while (itThis.hasNext()) { Edge tempThis = itThis.next(); while (itV.hasNext()) { Edge tempV = itV.next(); if (tempV.equal(tempThis)) { tempV.delete(true); } else if (this == tempV.getNeighbour(v)) { if (tempThis.getNeighbour(this) == tempV.getNeighbour(v)) { tempThis.counterplus(tempV.getCounter()); tempV.delete(true); } } } itV = v.edges.iterator(); } /** * Visszaállítjuk az iterátorokat a lista elejére. */ itV = v.edges.iterator(); /** * v maradék éleit hozzáadjuk this-hez. Ezt úgy oldja meg, hogy mindig létrehoz egy új élet, * ami a konstruktorából fakadóan rögtön bejegyzi magát a megfelelő helyekre. */ while (itV.hasNext()) { Edge tempV = itV.next(); new Edge(this, tempV.getNeighbour(v)); } System.out.println("Csúcs join véget ért."); } }
Java
package ambient_network_simulation; /** * * @author Karcsi */ public class Edge { private Vertice verticeLeft; private Vertice verticeRight; private int counter; /** * Konstruktor * @param vertceLeft * @param verticeRight */ public Edge(Vertice verticeLeft, Vertice verticeRight) { this.verticeLeft = verticeLeft; verticeLeft.addEdge(this); this.verticeRight = verticeRight; verticeRight.addEdge(this); this.counter = 1; } /** * A számlálóhoz hozzáad n-t * @param n a hozzáadandó szám */ public void counterplus(int n){ this.counter+=n; System.out.println("\t Él counter növelve "+ n +". Új érték: "+ this.counter); } /** * Visszaadja a számláló éretékét * @return int-ként a számláló értéke */ public int getCounter() { return counter; } /** * összehasonlítja egy másik éllel. * @param e összehasonlítandó él * @return */ public boolean equal(Edge e) { if ((this.verticeLeft == e.verticeLeft && this.verticeRight == e.verticeRight) || (this.verticeLeft == e.verticeRight && this.verticeRight == e.verticeLeft)) { System.out.println("\t Él equal lefutott true értékkel."); return true; } System.out.println("\t Él equal lefutott false értékkel."); return false; } /** * Az él bejegyzéseinek törlése a két végpontból * Ha több kapcsolat volt a kettő között akkor csak csökkentjuk a kapcsolatok számát, * de ha true értéket kap változóként, akkor számlálótól függetlenül törli. * @param violently igaz érték esetén erőszakosan törli az élet, false esetén csak ha a számláló kisebb mint 1. */ public void delete(boolean violently) { if(this.counter == 0 || violently==true){ verticeLeft.removeEdge(this); verticeRight.removeEdge(this); System.out.println("\t Él törölve."); } else{ System.out.println("\t Él counter csökkent"); counter--; } } /** * A paraméterben megadott csúcs szomszédját adja vissza * @param v * @return */ public Vertice getNeighbour(Vertice v){ if (this.verticeLeft == v){ return this.verticeRight; } else{ return this.verticeLeft; } } }
Java
package ambient_network_simulation; import java.util.Iterator; import java.util.List; /** * * @author DTT */ public class VirtualNetwork { private int id; private Node members; private Policy policy; private double time; private Vertice vertice; private TreeVertice treeVertice; private boolean nextAction; /** * Ez a függvény kiértékeli a szomszédaival való viszonyát a policy(k) alapján, és mindegyikhez rendel egy értéket. Visszaadja a legjobb elemet. * @return a composition-re kiválasztott elem */ private VirtualNetwork evaluateNeighbours() { Iterator<VirtualNetwork> itNeighbours = this.vertice.getNeighbours().iterator(); VirtualNetwork result = itNeighbours.next(); boolean check = this.policy.checkPolicy(result.policy); while (itNeighbours.hasNext()) { VirtualNetwork temp = itNeighbours.next(); if (this.policy.checkPolicy(temp.policy) == check) { if (this.policy.evaluatePolicy(result.policy) >= this.policy.evaluatePolicy(temp.policy)) { result = temp; } } else if (this.policy.checkPolicy(temp.policy)) { check = true; result = temp; } } return result; } private void absorbtion(VirtualNetwork in) { throw new UnsupportedOperationException(); } private void gateway(VirtualNetwork in) { throw new UnsupportedOperationException(); } public void vnComposition() { VirtualNetwork target = evaluateNeighbours(); if (this.policy.checkPolicy(target.policy)) { target.absorbtion(this); } else { target.gateway(this); } } }
Java
package ambient_network_simulation; import java.util.HashMap; import java.util.Map; /** * Lock obkektum. Megoldja az írás/olvasás kizárást. * */ public class ReadWriteLock{ private Map<Thread, Integer> readingThreads = new HashMap<Thread, Integer>(); private int writeAccesses = 0; private int writeRequests = 0; private Thread writingThread = null; public synchronized void lockRead() throws InterruptedException{ Thread callingThread = Thread.currentThread(); while(! canGrantReadAccess(callingThread)){ wait(); } readingThreads.put(callingThread, (getReadAccessCount(callingThread) + 1)); } private boolean canGrantReadAccess(Thread callingThread){ if( isWriter(callingThread) ) return true; if( hasWriter() ) return false; if( isReader(callingThread) ) return true; if( hasWriteRequests() ) return false; return true; } public synchronized void unlockRead(){ Thread callingThread = Thread.currentThread(); if(!isReader(callingThread)){ throw new IllegalMonitorStateException("Calling Thread does not" + " hold a read lock on this ReadWriteLock"); } int accessCount = getReadAccessCount(callingThread); if(accessCount == 1){ readingThreads.remove(callingThread); } else { readingThreads.put(callingThread, (accessCount -1)); } notifyAll(); } public synchronized void lockWrite() throws InterruptedException{ writeRequests++; Thread callingThread = Thread.currentThread(); while(! canGrantWriteAccess(callingThread)){ wait(); } writeRequests--; writeAccesses++; writingThread = callingThread; } public synchronized void unlockWrite() throws InterruptedException{ if(!isWriter(Thread.currentThread())){ throw new IllegalMonitorStateException("Calling Thread does not" + " hold the write lock on this ReadWriteLock"); } writeAccesses--; if(writeAccesses == 0){ writingThread = null; } notifyAll(); } private boolean canGrantWriteAccess(Thread callingThread){ if(isOnlyReader(callingThread)) return true; if(hasReaders()) return false; if(writingThread == null) return true; if(!isWriter(callingThread)) return false; return true; } private int getReadAccessCount(Thread callingThread){ Integer accessCount = readingThreads.get(callingThread); if(accessCount == null) return 0; return accessCount.intValue(); } private boolean hasReaders(){ return readingThreads.size() > 0; } private boolean isReader(Thread callingThread){ return readingThreads.get(callingThread) != null; } private boolean isOnlyReader(Thread callingThread){ return readingThreads.size() == 1 && readingThreads.get(callingThread) != null; } private boolean hasWriter(){ return writingThread != null; } private boolean isWriter(Thread callingThread){ return writingThread == callingThread; } private boolean hasWriteRequests(){ return this.writeRequests > 0; } }
Java
package ambient_network_simulation; import java.util.Iterator; import java.util.List; /** * Ezek az objektumok egy policy-t reprezentálnak: több tulajdonságot tartalmazhatnak. * @author DTT */ public class Policy { private List<Property> properties; /** * Konstruktor * @param properties tulajdonság lista */ public Policy(List<Property> properties) { this.properties = properties; } /** * Konstruktor Gateway esetén. * A két átadott policy tualjdonságai közül kiválasztja a megegyező nevűeket. * @param a * @param b */ public Policy(Policy a, Policy b) { Iterator<Property> itA = a.properties.iterator(); Iterator<Property> itB = b.properties.iterator(); while(itA.hasNext()){ Property tempA = itA.next(); while(itB.hasNext()){ Property tempB = itB.next(); if(tempA.getName().equals(tempB.getName())){ this.properties.add(new Property(tempA, tempB)); } } itB= b.properties.iterator(); } } /** * minden tulajdonságot kiértékelha megfelelő abszorbcióra, akkor true értékkel, * különben false értékkel tér vissza. * @param In a célpont policy-ja * @return ha megfelelő abszorbcióra, akkor true értékkel, különben false értékkel tér vissza. */ public boolean checkPolicy(Policy In) { System.out.print("CheckPolicy: "); /** * Ha nem egyezik meg a két policy tulajdonság-listájának a mérete akkor gateway lesz */ if (this.properties.size() != In.properties.size()){ System.out.println("különböző méretű tul. listák."); return false;} Iterator<Property> itThis = this.properties.iterator(); Iterator<Property> itIn = In.properties.iterator(); boolean check = false; /** * Végigmegyünk a két policy tulajdonságlistáján és megkeressük a megegyezű nevű elemeket. * Ha talákunk ilyet kiértékeljük. Amennyiben egy esetben false-t kapunk akkor vége. * Ha nem találunk egyező nevű tulajdonságot akkor is false-al vége. */ while(itThis.hasNext()){ Property tempThis = itThis.next(); while(itIn.hasNext()){ Property tempIn = itIn.next(); if(tempThis.getName().equals(tempIn.getName())){ check = tempThis.check(tempIn); break; } } itIn=In.properties.iterator(); if(!check) return false; } System.out.println(" lefutott "+ check +" értékkel."); return check; } /** * ez a fv. kiértékeli a kapcsolat értékét. * @param In a célpont policy-ja * @return a policy értéke */ public int evaluatePolicy(Policy In) { Iterator<Property> itThis = this.properties.iterator(); Iterator<Property> itIn = In.properties.iterator(); int result = 0; while(itThis.hasNext()){ Property tempThis = itThis.next(); while(itIn.hasNext()){ Property tempIn = itIn.next(); if(tempThis.getName().equals(tempIn.getName())){ result += tempThis.evaluate(tempIn); } } itIn=In.properties.iterator(); } System.out.print("evaluatePolicy lefutott, értéke: " + result); return result; } /** * a abszorbció esetén a célpont policy értékét módosítja * @param In a csatlakozni kívánó fél policy-je */ public void updatePolicy(Policy In) { Iterator<Property> itThis = this.properties.iterator(); Iterator<Property> itIn = In.properties.iterator(); while(itThis.hasNext()){ Property tempThis = itThis.next(); while(itIn.hasNext()){ Property tempIn = itIn.next(); if(tempThis.getName().equals(tempIn.getName())){ tempThis.updateAbs(tempIn); } } itIn=In.properties.iterator(); } } }
Java
package com.ecomdev.vpndialogxposed; import android.Manifest; import android.app.ListActivity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.*; import android.os.Bundle; import android.widget.AbsListView; import android.widget.ArrayAdapter; import android.widget.ListAdapter; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.*; /** * Created by arne on 06.10.13. */ public class AllowedVPNsChooser extends ListActivity { public static final String ALLOWED_APPS = "allowedApps"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Collection<VpnApp> vpnApps = getVpnAppList(); ListAdapter la = new ArrayAdapter<VpnApp>(this, android.R.layout.simple_list_item_multiple_choice, vpnApps.toArray(new VpnApp[vpnApps.size()])); setListAdapter(la); setContentView(R.layout.vpnapplayout); getListView().setChoiceMode(AbsListView.CHOICE_MODE_MULTIPLE); Collection<String> allowedapps = getAllowedApps(); for(int i=0; i < vpnApps.size(); i++) { VpnApp va= (VpnApp) getListView().getItemAtPosition(i); boolean allowed = allowedapps.contains(va.mPkg); getListView().setItemChecked(i,allowed); } } private Collection<String> getAllowedApps(){ SharedPreferences prefs = getPreferences(MODE_WORLD_READABLE); HashSet<String> defaultapps = new HashSet<String>(); defaultapps.add("com.ecomdev.openvpn"); return prefs.getStringSet(ALLOWED_APPS,defaultapps ); } private void saveAllowedApps(Set<String> allowedApps) { SharedPreferences prefs = getPreferences(MODE_WORLD_READABLE); prefs.edit().putStringSet(ALLOWED_APPS,allowedApps) .putInt("random",new Random().nextInt()).apply(); } @Override protected void onStop() { super.onStop(); HashSet<String> allowedPkgs= new HashSet<String>(); for(int i=0;i < getListView().getChildCount();i++) { if(getListView().getCheckedItemPositions().get(i)) { allowedPkgs.add(((VpnApp)getListView().getItemAtPosition(i)).mPkg); } } saveAllowedApps(allowedPkgs); } private Collection<VpnApp> getVpnAppList() { PackageManager pm = getPackageManager(); Intent vpnOpen = new Intent(); vpnOpen.setAction("android.net.VpnService"); Vector<VpnApp> vpnApps = new Vector<VpnApp>(); // Hack but should work for(PackageInfo pkg : pm.getInstalledPackages(PackageManager.GET_SERVICES)) { if (pkg.services != null) { for(ServiceInfo serviceInfo:pkg.services) { if(Manifest.permission.BIND_VPN_SERVICE.equals(serviceInfo.permission)) vpnApps.add(new VpnApp(pkg.applicationInfo.loadLabel(pm), pkg.packageName)); } } } /* public abstract List<ResolveInfo> queryIntentServicesAsUser(Intent intent, int flags, int userId); */ /* This does not work ... */ /* Class<?>[] queryIntentServicesAsUserSignature = {Intent.class, int.class, int.class}; try { Method queryIntentServicesAsUser = pm.getClass().getMethod("queryIntentServicesAsUser", queryIntentServicesAsUserSignature); List<ApplicationInfo> installedApps = pm.getInstalledApplications(0); for (ApplicationInfo app : installedApps) { List<ResolveInfo> apps; if (app.packageName.equals(getPackageName())) { apps = pm.queryIntentServices(vpnOpen, 0); } else { apps = (List<ResolveInfo>) queryIntentServicesAsUser.invoke(pm, vpnOpen, 0, app.uid); } for (ResolveInfo ri : apps) { vpnApps.add(new VpnApp(ri.toString())); } } } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } */ return vpnApps; } static class VpnApp { private final String mPkg; private CharSequence mName; public VpnApp(CharSequence name, String pkg) { mName = name; mPkg = pkg; } @Override public String toString() { return mName.toString(); } } }
Java
package com.ecomdev.vpndialogxposed; import android.app.Activity; import android.content.Context; import android.os.IBinder; import android.widget.Toast; import de.robv.android.xposed.IXposedHookLoadPackage; import de.robv.android.xposed.XC_MethodHook; import de.robv.android.xposed.XposedBridge; import de.robv.android.xposed.XposedHelpers; import de.robv.android.xposed.XSharedPreferences; import de.robv.android.xposed.callbacks.XC_LoadPackage.LoadPackageParam; import de.robv.android.xposed.IXposedHookZygoteInit; import java.lang.reflect.Method; import java.util.HashSet; import java.util.Set; public class VpnDialogPatcher implements IXposedHookLoadPackage, IXposedHookZygoteInit { public static final String MY_PACKAGE_NAME = AllowedVPNsChooser.class.getPackage().getName(); private static XSharedPreferences pref; @Override public void initZygote(StartupParam startupParam) throws Throwable { pref = new XSharedPreferences(MY_PACKAGE_NAME, "AllowedVPNsChooser"); } @Override public void handleLoadPackage(LoadPackageParam lpparam) throws Throwable { if (!lpparam.packageName.equals("com.android.vpndialogs")) return; XposedBridge.log("Got VPN Dialog"); XposedHelpers.findAndHookMethod("com.android.vpndialogs.ConfirmDialog", lpparam.classLoader, "onResume", new XC_MethodHook() { @Override protected void afterHookedMethod(MethodHookParam param) throws Throwable { // IConnectivityManager mService = IConnectivityManager.Stub.asInterface( // ServiceManager.getService(Context.CONNECTIVITY_SERVICE)); try { /*Class servicemanager = Class.forName("android.os.ServiceManager"); Method getService = servicemanager.getMethod("getService",String.class); IConnectivityManager mService = IConnectivityManager.Stub.asInterface( (IBinder) getService.invoke(servicemanager, Context.CONNECTIVITY_SERVICE)); */ Object mService = XposedHelpers.getObjectField(param.thisObject, "mService"); String mPackage = ((Activity) param.thisObject).getCallingPackage(); // App is already allowed do nothing /*if (mService.prepareVpn(mPackage, null)) { return; }*/ Class<?>[] prepareVPNsignature = {String.class, String.class}; if((Boolean) XposedHelpers.callMethod(mService,"prepareVpn",prepareVPNsignature, mPackage,(String)null)) return; HashSet<String> developmentApp = new HashSet<String>(); developmentApp.add("com.ecomdev.openvpn"); // developmentApp.add("com.ecomdev.nothingset"); pref.reload(); Set<String> allowedApps = pref.getStringSet("allowedApps",developmentApp); //Toast.makeText((Context)param.thisObject, "Allowed apps: " + allowedApps, Toast.LENGTH_LONG).show(); if (allowedApps.contains(mPackage)) { //mService.prepareVpn(null, mPackage); XposedHelpers.callMethod(mService,"prepareVpn",prepareVPNsignature, (String)null,mPackage); ((Activity) param.thisObject).setResult(Activity.RESULT_OK); Toast.makeText((Context)param.thisObject,"Allowed VpnService app: " + mPackage,Toast.LENGTH_LONG).show(); ((Activity) param.thisObject).finish(); } } catch (Exception e) { e.printStackTrace(); } } }); } }
Java
package org.spongycastle.util.io.pem; public interface PemObjectGenerator { PemObject generate() throws PemGenerationException; }
Java
package org.spongycastle.util.io.pem; import java.io.IOException; @SuppressWarnings("serial") public class PemGenerationException extends IOException { private Throwable cause; public PemGenerationException(String message, Throwable cause) { super(message); this.cause = cause; } public PemGenerationException(String message) { super(message); } public Throwable getCause() { return cause; } }
Java
package org.spongycastle.util.io.pem; import java.util.ArrayList; import java.util.Collections; import java.util.List; @SuppressWarnings("all") public class PemObject implements PemObjectGenerator { private static final List EMPTY_LIST = Collections.unmodifiableList(new ArrayList()); private String type; private List headers; private byte[] content; /** * Generic constructor for object without headers. * * @param type pem object type. * @param content the binary content of the object. */ public PemObject(String type, byte[] content) { this(type, EMPTY_LIST, content); } /** * Generic constructor for object with headers. * * @param type pem object type. * @param headers a list of PemHeader objects. * @param content the binary content of the object. */ public PemObject(String type, List headers, byte[] content) { this.type = type; this.headers = Collections.unmodifiableList(headers); this.content = content; } public String getType() { return type; } public List getHeaders() { return headers; } public byte[] getContent() { return content; } public PemObject generate() throws PemGenerationException { return this; } }
Java
package org.spongycastle.util.io.pem; import java.io.BufferedReader; import java.io.IOException; import java.io.Reader; import java.util.ArrayList; import java.util.List; import org.spongycastle.util.encoders.Base64; public class PemReader extends BufferedReader { private static final String BEGIN = "-----BEGIN "; private static final String END = "-----END "; public PemReader(Reader reader) { super(reader); } public PemObject readPemObject() throws IOException { String line = readLine(); while (line != null && !line.startsWith(BEGIN)) { line = readLine(); } if (line != null) { line = line.substring(BEGIN.length()); int index = line.indexOf('-'); String type = line.substring(0, index); if (index > 0) { return loadObject(type); } } return null; } private PemObject loadObject(String type) throws IOException { String line; String endMarker = END + type; StringBuffer buf = new StringBuffer(); List headers = new ArrayList(); while ((line = readLine()) != null) { if (line.indexOf(":") >= 0) { int index = line.indexOf(':'); String hdr = line.substring(0, index); String value = line.substring(index + 1).trim(); headers.add(new PemHeader(hdr, value)); continue; } if (line.indexOf(endMarker) != -1) { break; } buf.append(line.trim()); } if (line == null) { throw new IOException(endMarker + " not found"); } return new PemObject(type, headers, Base64.decode(buf.toString())); } }
Java
package org.spongycastle.util.io.pem; import java.io.BufferedWriter; import java.io.IOException; import java.io.Writer; import java.util.Iterator; import org.spongycastle.util.encoders.Base64; /** * A generic PEM writer, based on RFC 1421 */ @SuppressWarnings("all") public class PemWriter extends BufferedWriter { private static final int LINE_LENGTH = 64; private final int nlLength; private char[] buf = new char[LINE_LENGTH]; /** * Base constructor. * * @param out output stream to use. */ public PemWriter(Writer out) { super(out); String nl = System.getProperty("line.separator"); if (nl != null) { nlLength = nl.length(); } else { nlLength = 2; } } /** * Return the number of bytes or characters required to contain the * passed in object if it is PEM encoded. * * @param obj pem object to be output * @return an estimate of the number of bytes */ public int getOutputSize(PemObject obj) { // BEGIN and END boundaries. int size = (2 * (obj.getType().length() + 10 + nlLength)) + 6 + 4; if (!obj.getHeaders().isEmpty()) { for (Iterator it = obj.getHeaders().iterator(); it.hasNext();) { PemHeader hdr = (PemHeader)it.next(); size += hdr.getName().length() + ": ".length() + hdr.getValue().length() + nlLength; } size += nlLength; } // base64 encoding int dataLen = ((obj.getContent().length + 2) / 3) * 4; size += dataLen + (((dataLen + LINE_LENGTH - 1) / LINE_LENGTH) * nlLength); return size; } public void writeObject(PemObjectGenerator objGen) throws IOException { PemObject obj = objGen.generate(); writePreEncapsulationBoundary(obj.getType()); if (!obj.getHeaders().isEmpty()) { for (Iterator it = obj.getHeaders().iterator(); it.hasNext();) { PemHeader hdr = (PemHeader)it.next(); this.write(hdr.getName()); this.write(": "); this.write(hdr.getValue()); this.newLine(); } this.newLine(); } writeEncoded(obj.getContent()); writePostEncapsulationBoundary(obj.getType()); } private void writeEncoded(byte[] bytes) throws IOException { bytes = Base64.encode(bytes); for (int i = 0; i < bytes.length; i += buf.length) { int index = 0; while (index != buf.length) { if ((i + index) >= bytes.length) { break; } buf[index] = (char)bytes[i + index]; index++; } this.write(buf, 0, index); this.newLine(); } } private void writePreEncapsulationBoundary( String type) throws IOException { this.write("-----BEGIN " + type + "-----"); this.newLine(); } private void writePostEncapsulationBoundary( String type) throws IOException { this.write("-----END " + type + "-----"); this.newLine(); } }
Java
package org.spongycastle.util.io.pem; public class PemHeader { private String name; private String value; public PemHeader(String name, String value) { this.name = name; this.value = value; } public String getName() { return name; } public String getValue() { return value; } public int hashCode() { return getHashCode(this.name) + 31 * getHashCode(this.value); } public boolean equals(Object o) { if (!(o instanceof PemHeader)) { return false; } PemHeader other = (PemHeader)o; return other == this || (isEqual(this.name, other.name) && isEqual(this.value, other.value)); } private int getHashCode(String s) { if (s == null) { return 1; } return s.hashCode(); } private boolean isEqual(String s1, String s2) { if (s1 == s2) { return true; } if (s1 == null || s2 == null) { return false; } return s1.equals(s2); } }
Java
package org.spongycastle.util.encoders; import java.io.IOException; import java.io.OutputStream; /** * Encode and decode byte arrays (typically from binary to 7-bit ASCII * encodings). */ public interface Encoder { int encode(byte[] data, int off, int length, OutputStream out) throws IOException; int decode(byte[] data, int off, int length, OutputStream out) throws IOException; int decode(String data, OutputStream out) throws IOException; }
Java
package org.spongycastle.util.encoders; import java.io.IOException; import java.io.OutputStream; public class Base64Encoder implements Encoder { protected final byte[] encodingTable = { (byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G', (byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N', (byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U', (byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z', (byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g', (byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n', (byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u', (byte)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z', (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5', (byte)'6', (byte)'7', (byte)'8', (byte)'9', (byte)'+', (byte)'/' }; protected byte padding = (byte)'='; /* * set up the decoding table. */ protected final byte[] decodingTable = new byte[128]; protected void initialiseDecodingTable() { for (int i = 0; i < encodingTable.length; i++) { decodingTable[encodingTable[i]] = (byte)i; } } public Base64Encoder() { initialiseDecodingTable(); } /** * encode the input data producing a base 64 output stream. * * @return the number of bytes produced. */ public int encode( byte[] data, int off, int length, OutputStream out) throws IOException { int modulus = length % 3; int dataLength = (length - modulus); int a1, a2, a3; for (int i = off; i < off + dataLength; i += 3) { a1 = data[i] & 0xff; a2 = data[i + 1] & 0xff; a3 = data[i + 2] & 0xff; out.write(encodingTable[(a1 >>> 2) & 0x3f]); out.write(encodingTable[((a1 << 4) | (a2 >>> 4)) & 0x3f]); out.write(encodingTable[((a2 << 2) | (a3 >>> 6)) & 0x3f]); out.write(encodingTable[a3 & 0x3f]); } /* * process the tail end. */ int b1, b2, b3; int d1, d2; switch (modulus) { case 0: /* nothing left to do */ break; case 1: d1 = data[off + dataLength] & 0xff; b1 = (d1 >>> 2) & 0x3f; b2 = (d1 << 4) & 0x3f; out.write(encodingTable[b1]); out.write(encodingTable[b2]); out.write(padding); out.write(padding); break; case 2: d1 = data[off + dataLength] & 0xff; d2 = data[off + dataLength + 1] & 0xff; b1 = (d1 >>> 2) & 0x3f; b2 = ((d1 << 4) | (d2 >>> 4)) & 0x3f; b3 = (d2 << 2) & 0x3f; out.write(encodingTable[b1]); out.write(encodingTable[b2]); out.write(encodingTable[b3]); out.write(padding); break; } return (dataLength / 3) * 4 + ((modulus == 0) ? 0 : 4); } private boolean ignore( char c) { return (c == '\n' || c =='\r' || c == '\t' || c == ' '); } /** * decode the base 64 encoded byte data writing it to the given output stream, * whitespace characters will be ignored. * * @return the number of bytes produced. */ public int decode( byte[] data, int off, int length, OutputStream out) throws IOException { byte b1, b2, b3, b4; int outLen = 0; int end = off + length; while (end > off) { if (!ignore((char)data[end - 1])) { break; } end--; } int i = off; int finish = end - 4; i = nextI(data, i, finish); while (i < finish) { b1 = decodingTable[data[i++]]; i = nextI(data, i, finish); b2 = decodingTable[data[i++]]; i = nextI(data, i, finish); b3 = decodingTable[data[i++]]; i = nextI(data, i, finish); b4 = decodingTable[data[i++]]; out.write((b1 << 2) | (b2 >> 4)); out.write((b2 << 4) | (b3 >> 2)); out.write((b3 << 6) | b4); outLen += 3; i = nextI(data, i, finish); } outLen += decodeLastBlock(out, (char)data[end - 4], (char)data[end - 3], (char)data[end - 2], (char)data[end - 1]); return outLen; } private int nextI(byte[] data, int i, int finish) { while ((i < finish) && ignore((char)data[i])) { i++; } return i; } /** * decode the base 64 encoded String data writing it to the given output stream, * whitespace characters will be ignored. * * @return the number of bytes produced. */ public int decode( String data, OutputStream out) throws IOException { byte b1, b2, b3, b4; int length = 0; int end = data.length(); while (end > 0) { if (!ignore(data.charAt(end - 1))) { break; } end--; } int i = 0; int finish = end - 4; i = nextI(data, i, finish); while (i < finish) { b1 = decodingTable[data.charAt(i++)]; i = nextI(data, i, finish); b2 = decodingTable[data.charAt(i++)]; i = nextI(data, i, finish); b3 = decodingTable[data.charAt(i++)]; i = nextI(data, i, finish); b4 = decodingTable[data.charAt(i++)]; out.write((b1 << 2) | (b2 >> 4)); out.write((b2 << 4) | (b3 >> 2)); out.write((b3 << 6) | b4); length += 3; i = nextI(data, i, finish); } length += decodeLastBlock(out, data.charAt(end - 4), data.charAt(end - 3), data.charAt(end - 2), data.charAt(end - 1)); return length; } private int decodeLastBlock(OutputStream out, char c1, char c2, char c3, char c4) throws IOException { byte b1, b2, b3, b4; if (c3 == padding) { b1 = decodingTable[c1]; b2 = decodingTable[c2]; out.write((b1 << 2) | (b2 >> 4)); return 1; } else if (c4 == padding) { b1 = decodingTable[c1]; b2 = decodingTable[c2]; b3 = decodingTable[c3]; out.write((b1 << 2) | (b2 >> 4)); out.write((b2 << 4) | (b3 >> 2)); return 2; } else { b1 = decodingTable[c1]; b2 = decodingTable[c2]; b3 = decodingTable[c3]; b4 = decodingTable[c4]; out.write((b1 << 2) | (b2 >> 4)); out.write((b2 << 4) | (b3 >> 2)); out.write((b3 << 6) | b4); return 3; } } private int nextI(String data, int i, int finish) { while ((i < finish) && ignore(data.charAt(i))) { i++; } return i; } }
Java
package org.spongycastle.util.encoders; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; public class Base64 { private static final Encoder encoder = new Base64Encoder(); /** * encode the input data producing a base 64 encoded byte array. * * @return a byte array containing the base 64 encoded data. */ public static byte[] encode( byte[] data) { int len = (data.length + 2) / 3 * 4; ByteArrayOutputStream bOut = new ByteArrayOutputStream(len); try { encoder.encode(data, 0, data.length, bOut); } catch (IOException e) { throw new RuntimeException("exception encoding base64 string: " + e); } return bOut.toByteArray(); } /** * Encode the byte data to base 64 writing it to the given output stream. * * @return the number of bytes produced. */ public static int encode( byte[] data, OutputStream out) throws IOException { return encoder.encode(data, 0, data.length, out); } /** * Encode the byte data to base 64 writing it to the given output stream. * * @return the number of bytes produced. */ public static int encode( byte[] data, int off, int length, OutputStream out) throws IOException { return encoder.encode(data, off, length, out); } /** * decode the base 64 encoded input data. It is assumed the input data is valid. * * @return a byte array representing the decoded data. */ public static byte[] decode( byte[] data) { int len = data.length / 4 * 3; ByteArrayOutputStream bOut = new ByteArrayOutputStream(len); try { encoder.decode(data, 0, data.length, bOut); } catch (IOException e) { throw new RuntimeException("exception decoding base64 string: " + e); } return bOut.toByteArray(); } /** * decode the base 64 encoded String data - whitespace will be ignored. * * @return a byte array representing the decoded data. */ public static byte[] decode( String data) { int len = data.length() / 4 * 3; ByteArrayOutputStream bOut = new ByteArrayOutputStream(len); try { encoder.decode(data, bOut); } catch (IOException e) { throw new RuntimeException("exception decoding base64 string: " + e); } return bOut.toByteArray(); } /** * decode the base 64 encoded String data writing it to the given output stream, * whitespace characters will be ignored. * * @return the number of bytes produced. */ public static int decode( String data, OutputStream out) throws IOException { return encoder.decode(data, out); } }
Java
package com.ecomdev.openvpn.activities; import java.io.*; import java.util.*; import android.app.Activity; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.app.ListActivity; import android.content.ActivityNotFoundException; import android.content.Intent; import android.content.res.AssetManager; import android.os.Bundle; import android.os.Environment; import android.security.KeyChain; import android.security.KeyChainAliasCallback; import android.util.Base64; import android.view.*; import android.widget.ArrayAdapter; import android.widget.CheckBox; import android.widget.LinearLayout; import com.ecomdev.openvpn.R; import com.ecomdev.openvpn.VpnProfile; import com.ecomdev.openvpn.core.ConfigParser; import com.ecomdev.openvpn.core.ConfigParser.ConfigParseError; import com.ecomdev.openvpn.core.ProfileManager; import com.ecomdev.openvpn.fragments.Utils; import com.ecomdev.openvpn.views.FileSelectLayout; import junit.framework.Assert; import static com.ecomdev.openvpn.views.FileSelectLayout.*; public class ConfigConverter extends ListActivity implements FileSelectCallback { public static final String IMPORT_PROFILE = "com.ecomdev.openvpn.IMPORT_PROFILE"; private static final int RESULT_INSTALLPKCS12 = 7; private static final int CHOOSE_FILE_OFFSET = 1000; public static final String VPNPROFILE = "vpnProfile"; private VpnProfile mResult; private transient ArrayAdapter<String> mArrayAdapter; private transient List<String> mPathsegments; private String mAliasName=null; private Map<Utils.FileType, FileSelectLayout> fileSelectMap = new HashMap<Utils.FileType, FileSelectLayout>(); @Override public boolean onOptionsItemSelected(MenuItem item) { if(item.getItemId()==R.id.cancel){ setResult(Activity.RESULT_CANCELED); finish(); } else if(item.getItemId()==R.id.ok) { if(mResult==null) { log("Importing the config had error, cannot save it"); return true; } Intent in = installPKCS12(); if(in != null) startActivityForResult(in, RESULT_INSTALLPKCS12); else saveProfile(); return true; } return super.onOptionsItemSelected(item); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); if(mResult!=null) outState.putSerializable(VPNPROFILE,mResult); outState.putString("mAliasName", mAliasName); String[] logentries = new String[mArrayAdapter.getCount()]; for(int i =0; i < mArrayAdapter.getCount();i++){ logentries[i] = mArrayAdapter.getItem(i); } outState.putStringArray("logentries", logentries); int[] fileselects = new int[fileSelectMap.size()]; int k=0; for (Utils.FileType key :fileSelectMap.keySet()){ fileselects[k]=key.getValue(); k++; } outState.putIntArray("fileselects",fileselects); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent result) { if (requestCode == RESULT_INSTALLPKCS12 && resultCode == Activity.RESULT_OK) { showCertDialog(); } if (resultCode == Activity.RESULT_OK && requestCode >= CHOOSE_FILE_OFFSET) { Utils.FileType type = Utils.FileType.getFileTypeByValue(requestCode - CHOOSE_FILE_OFFSET); FileSelectLayout fs = fileSelectMap.get(type); fs.parseResponse(result, this); String data = fs.getData(); switch (type){ case USERPW_FILE: ConfigParser.useEmbbedUserAuth(mResult, data); break; case PKCS12: mResult.mPKCS12Filename = data; break; case TLS_AUTH_FILE: mResult.mTLSAuthFilename = data; break; case CA_CERTIFICATE: mResult.mCaFilename = data; break; case CLIENT_CERTIFICATE: mResult.mClientCertFilename = data; break; case KEYFILE: mResult.mClientKeyFilename = data; break; default: Assert.fail(); } } super.onActivityResult(requestCode, resultCode, result); } private void saveProfile() { Intent result = new Intent(); ProfileManager vpl = ProfileManager.getInstance(this); vpl.addProfile(mResult); vpl.saveProfile(this, mResult); vpl.saveProfileList(this); result.putExtra(VpnProfile.EXTRA_PROFILEUUID,mResult.getUUID().toString()); setResult(Activity.RESULT_OK, result); finish(); } public void showCertDialog () { try { KeyChain.choosePrivateKeyAlias(this, new KeyChainAliasCallback() { public void alias(String alias) { // Credential alias selected. Remember the alias selection for future use. mResult.mAlias=alias; saveProfile(); } }, new String[] {"RSA"}, // List of acceptable key types. null for any null, // issuer, null for any mResult.mServerName, // host name of server requesting the cert, null if unavailable -1, // port of server requesting the cert, -1 if unavailable mAliasName); // alias to preselect, null if unavailable } catch (ActivityNotFoundException anf) { Builder ab = new AlertDialog.Builder(this); ab.setTitle(R.string.broken_image_cert_title); ab.setMessage(R.string.broken_image_cert); ab.setPositiveButton(android.R.string.ok, null); ab.show(); } } private Intent installPKCS12() { if(!((CheckBox)findViewById(R.id.importpkcs12)).isChecked()) { setAuthTypeToEmbeddedPKCS12(); return null; } String pkcs12datastr = mResult.mPKCS12Filename; if(pkcs12datastr!=null && pkcs12datastr.startsWith(VpnProfile.INLINE_TAG)) { Intent inkeyintent = KeyChain.createInstallIntent(); pkcs12datastr= pkcs12datastr.substring(VpnProfile.INLINE_TAG.length()); byte[] pkcs12data = Base64.decode(pkcs12datastr, Base64.DEFAULT); inkeyintent.putExtra(KeyChain.EXTRA_PKCS12,pkcs12data ); if(mAliasName.equals("")) mAliasName=null; if(mAliasName!=null){ inkeyintent.putExtra(KeyChain.EXTRA_NAME, mAliasName); } return inkeyintent; } return null; } private void setAuthTypeToEmbeddedPKCS12() { if(mResult.mPKCS12Filename!=null && mResult.mPKCS12Filename.startsWith(VpnProfile.INLINE_TAG)) { if(mResult.mAuthenticationType==VpnProfile.TYPE_USERPASS_KEYSTORE) mResult.mAuthenticationType=VpnProfile.TYPE_USERPASS_PKCS12; if(mResult.mAuthenticationType==VpnProfile.TYPE_KEYSTORE) mResult.mAuthenticationType=VpnProfile.TYPE_PKCS12; } } private String getUniqueProfileName(String possibleName) { int i=0; ProfileManager vpl = ProfileManager.getInstance(this); String newname = possibleName; // Default to if(mResult.mName!=null && !ConfigParser.CONVERTED_PROFILE.equals(mResult.mName)) newname=mResult.mName; while(newname==null || vpl.getProfileByName(newname)!=null) { i++; if(i==1) newname = getString(R.string.converted_profile); else newname = getString(R.string.converted_profile_i,i); } return newname; } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.import_menu, menu); return true; } private String embedFile(String filename, Utils.FileType type) { if(filename==null) return null; // Already embedded, nothing to do if(filename.startsWith(VpnProfile.INLINE_TAG)) return filename; File possibleFile = findFile(filename, type); if(possibleFile==null) return filename; else return readFileContent(possibleFile,type == Utils.FileType.PKCS12); } private File findFile(String filename, Utils.FileType fileType) { File foundfile =findFileRaw(filename); if (foundfile==null && filename!=null && !filename.equals("")) { log(R.string.import_could_not_open,filename); addFileSelectDialog(fileType); } return foundfile; } private void addFileSelectDialog(Utils.FileType type) { int titleRes = 0; String value=null; switch (type) { case KEYFILE: titleRes = R.string.client_key_title; if (mResult!=null) value = mResult.mClientKeyFilename; break; case CLIENT_CERTIFICATE: titleRes = R.string.client_certificate_title; if (mResult!=null) value = mResult.mClientCertFilename; break; case CA_CERTIFICATE: titleRes = R.string.ca_title; if (mResult!=null) value = mResult.mCaFilename; break; case TLS_AUTH_FILE: titleRes = R.string.tls_auth_file; if (mResult!=null) value = mResult.mTLSAuthFilename; break; case PKCS12: titleRes = R.string.client_pkcs12_title; if (mResult!=null) value = mResult.mPKCS12Filename; break; case USERPW_FILE: titleRes = R.string.userpw_file; return; } boolean isCert = type == Utils.FileType.CA_CERTIFICATE || type == Utils.FileType.CLIENT_CERTIFICATE; FileSelectLayout fl = new FileSelectLayout(this,getString(titleRes), isCert); fileSelectMap.put(type, fl); fl.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); ((LinearLayout) findViewById(R.id.config_convert_root)).addView(fl, 1); fl.setData(value,this); int i = getFileLayoutOffset(type); fl.setCaller(this, i, type); } private int getFileLayoutOffset(Utils.FileType type) { return CHOOSE_FILE_OFFSET + type.getValue(); } private File findFileRaw(String filename) { if(filename == null || filename.equals("")) return null; // Try diffent path relative to /mnt/sdcard File sdcard = Environment.getExternalStorageDirectory(); File root = new File("/"); HashSet<File> dirlist = new HashSet<File>(); for(int i=mPathsegments.size()-1;i >=0 ;i--){ String path = ""; for (int j = 0;j<=i;j++) { path += "/" + mPathsegments.get(j); } // Do a little hackish dance for the Android File Importer // /document/primary:ovpn/openvpn-imt.conf if (path.indexOf(':')!=-1) { String possibleDir = path.substring(path.indexOf(':')+1,path.length()); possibleDir = possibleDir.substring(0,possibleDir.lastIndexOf('/')); dirlist.add(new File(sdcard,possibleDir)); } dirlist.add(new File(path)); } dirlist.add(sdcard); dirlist.add(root); String[] fileparts = filename.split("/"); for(File rootdir:dirlist){ String suffix=""; for(int i=fileparts.length-1; i >=0;i--) { if(i==fileparts.length-1) suffix = fileparts[i]; else suffix = fileparts[i] + "/" + suffix; File possibleFile = new File(rootdir,suffix); if(!possibleFile.canRead()) continue; // read the file inline return possibleFile; } } return null; } String readFileContent(File possibleFile, boolean base64encode) { byte [] filedata; try { filedata = readBytesFromFile(possibleFile); } catch (IOException e) { log(e.getLocalizedMessage()); return null; } String data; if(base64encode) { data = Base64.encodeToString(filedata, Base64.DEFAULT); } else { data = new String(filedata); } return VpnProfile.INLINE_TAG + data; } private byte[] readBytesFromFile(File file) throws IOException { InputStream input = new FileInputStream(file); long len= file.length(); if (len > VpnProfile.MAX_EMBED_FILE_SIZE) throw new IOException("File size of file to import too large."); // Create the byte array to hold the data byte[] bytes = new byte[(int) len]; // Read in the bytes int offset = 0; int bytesRead = 0; while (offset < bytes.length && (bytesRead=input.read(bytes, offset, bytes.length-offset)) >= 0) { offset += bytesRead; } input.close(); return bytes; } void embedFiles() { // This where I would like to have a c++ style // void embedFile(std::string & option) if (mResult.mPKCS12Filename!=null) { File pkcs12file = findFileRaw(mResult.mPKCS12Filename); if(pkcs12file!=null) { mAliasName = pkcs12file.getName().replace(".p12", ""); } else { mAliasName = "Imported PKCS12"; } } mResult.mCaFilename = embedFile(mResult.mCaFilename, Utils.FileType.CA_CERTIFICATE); mResult.mClientCertFilename = embedFile(mResult.mClientCertFilename, Utils.FileType.CLIENT_CERTIFICATE); mResult.mClientKeyFilename = embedFile(mResult.mClientKeyFilename, Utils.FileType.KEYFILE); mResult.mTLSAuthFilename = embedFile(mResult.mTLSAuthFilename, Utils.FileType.TLS_AUTH_FILE); mResult.mPKCS12Filename = embedFile(mResult.mPKCS12Filename, Utils.FileType.PKCS12); if(mResult.mUsername == null && mResult.mPassword != null ){ String data =embedFile(mResult.mPassword, Utils.FileType.USERPW_FILE); ConfigParser.useEmbbedUserAuth(mResult, data); } } @Override protected void onCreate(Bundle savedInstanceState) { setContentView(R.layout.config_converter); mArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1); getListView().setAdapter(mArrayAdapter); super.onCreate(savedInstanceState); if (savedInstanceState !=null && savedInstanceState.containsKey(VPNPROFILE)) { mResult = (VpnProfile) savedInstanceState.getSerializable(VPNPROFILE); mAliasName = savedInstanceState.getString("mAliasName"); mArrayAdapter.addAll(savedInstanceState.getStringArray("logentries")); for (int k: savedInstanceState.getIntArray("fileselects")) { addFileSelectDialog(Utils.FileType.getFileTypeByValue(k)); } return; } final android.content.Intent intent = getIntent (); if (intent != null ) { final android.net.Uri data = intent.getData (); if (data != null) { //log(R.string.import_experimental); //log(R.string.importing_config,data.toString()); try { InputStream is = getAssets().open(data.toString() + ".ovpn"); doImport(is, data.toString()); saveProfile(); } catch (FileNotFoundException e) { log(R.string.import_content_resolve_error); } catch (IOException e) { log(R.string.import_content_resolve_error); } } // We parsed the intent, relay on saved instance for restoring setIntent(null); } } @Override protected void onStart() { super.onStart(); } private void log(String logmessage) { mArrayAdapter.add(logmessage); } private void doImport(InputStream is, String newName) { ConfigParser cp = new ConfigParser(); try { InputStreamReader isr = new InputStreamReader(is); cp.parseConfig(isr); VpnProfile vp = cp.convertProfile(); mResult = vp; embedFiles(); //displayWarnings(); mResult.mName = getUniqueProfileName(newName); //log(R.string.import_done); return; } catch (IOException e) { log(R.string.error_reading_config_file); log(e.getLocalizedMessage()); } catch (ConfigParseError e) { log(R.string.error_reading_config_file); log(e.getLocalizedMessage()); } mResult=null; } private void displayWarnings() { if(mResult.mUseCustomConfig) { log(R.string.import_warning_custom_options); String copt = mResult.mCustomConfigOptions; if(copt.startsWith("#")) { int until = copt.indexOf('\n'); copt = copt.substring(until+1); } log(copt); } if(mResult.mAuthenticationType==VpnProfile.TYPE_KEYSTORE || mResult.mAuthenticationType == VpnProfile.TYPE_USERPASS_KEYSTORE) { findViewById(R.id.importpkcs12).setVisibility(View.VISIBLE); } } private void log(int ressourceId, Object... formatArgs) { log(getString(ressourceId,formatArgs)); } }
Java
package com.ecomdev.openvpn.activities; import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import com.ecomdev.openvpn.R; import com.ecomdev.openvpn.fragments.LogFragment; /** * Created by arne on 13.10.13. */ public class LogWindow extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.log_window); getActionBar().setDisplayHomeAsUpEnabled(true); if (savedInstanceState == null) { getFragmentManager().beginTransaction() .add(R.id.container, new LogFragment()) .commit(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.demo_menu, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { return super.onOptionsItemSelected(item); } }
Java
package com.ecomdev.openvpn.activities; import java.util.List; import android.annotation.TargetApi; import android.app.AlertDialog; import android.app.Fragment; import android.content.DialogInterface; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.preference.PreferenceActivity; import android.preference.PreferenceFragment; import android.view.Menu; import android.view.MenuItem; import com.ecomdev.openvpn.R; import com.ecomdev.openvpn.VpnProfile; import com.ecomdev.openvpn.core.ProfileManager; import com.ecomdev.openvpn.fragments.Settings_Authentication; import com.ecomdev.openvpn.fragments.Settings_Basic; import com.ecomdev.openvpn.fragments.Settings_IP; import com.ecomdev.openvpn.fragments.Settings_Obscure; import com.ecomdev.openvpn.fragments.Settings_Routing; import com.ecomdev.openvpn.fragments.ShowConfigFragment; import com.ecomdev.openvpn.fragments.VPNProfileList; public class VPNPreferences extends PreferenceActivity { static final Class validFragments[] = new Class[] { Settings_Authentication.class, Settings_Basic.class, Settings_IP.class, Settings_Obscure.class, Settings_Routing.class, ShowConfigFragment.class }; private String mProfileUUID; private VpnProfile mProfile; public VPNPreferences() { super(); } @TargetApi(Build.VERSION_CODES.KITKAT) @Override protected boolean isValidFragment(String fragmentName) { for (Class c: validFragments) if (c.getName().equals(fragmentName)) return true; return false; } @Override protected void onStop() { super.onStop(); } @Override protected void onSaveInstanceState(Bundle outState) { outState.putString(getIntent().getStringExtra(getPackageName() + ".profileUUID"),mProfileUUID); super.onSaveInstanceState(outState); } @Override protected void onResume() { super.onResume(); Intent intent = getIntent(); if(intent!=null) { String profileUUID = intent.getStringExtra(getPackageName() + ".profileUUID"); if(profileUUID==null) { Bundle initialArguments = getIntent().getBundleExtra(EXTRA_SHOW_FRAGMENT_ARGUMENTS); profileUUID = initialArguments.getString(getPackageName() + ".profileUUID"); } if(profileUUID!=null){ mProfileUUID = profileUUID; mProfile = ProfileManager.get(this,mProfileUUID); } } // When a profile is deleted from a category fragment in hadset mod we need to finish // this activity as well when returning if (mProfile==null || mProfile.profileDleted) { setResult(VPNProfileList.RESULT_VPN_DELETED); finish(); } } @Override protected void onCreate(Bundle savedInstanceState) { mProfileUUID = getIntent().getStringExtra(getPackageName() + ".profileUUID"); if(savedInstanceState!=null){ String savedUUID = savedInstanceState.getString(getPackageName() + ".profileUUID"); if(savedUUID!=null) mProfileUUID=savedUUID; } mProfile = ProfileManager.get(this,mProfileUUID); if(mProfile!=null) { setTitle(getString(R.string.edit_profile_title, mProfile.getName())); } super.onCreate(savedInstanceState); } @Override public void onBuildHeaders(List<Header> target) { loadHeadersFromResource(R.xml.vpn_headers, target); for (Header header : target) { if(header.fragmentArguments==null) header.fragmentArguments = new Bundle(); header.fragmentArguments.putString(getPackageName() + ".profileUUID",mProfileUUID); } } @Override public void onBackPressed() { setResult(RESULT_OK, getIntent()); super.onBackPressed(); } @Override public boolean onOptionsItemSelected(MenuItem item) { if(item.getItemId() == R.id.remove_vpn) askProfileRemoval(); return super.onOptionsItemSelected(item); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.vpnpreferences_menu, menu); return super.onCreateOptionsMenu(menu); } private void askProfileRemoval() { AlertDialog.Builder dialog = new AlertDialog.Builder(this); dialog.setTitle("Confirm deletion"); dialog.setMessage(getString(R.string.remove_vpn_query, mProfile.mName)); dialog.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { removeProfile(mProfile); } }); dialog.setNegativeButton(android.R.string.no,null); dialog.create().show(); } protected void removeProfile(VpnProfile profile) { ProfileManager.getInstance(this).removeProfile(this,profile); setResult(VPNProfileList.RESULT_VPN_DELETED); finish(); } }
Java
package com.ecomdev.openvpn.activities; import android.app.ListActivity; import android.content.Intent; import android.os.Bundle; import android.os.Parcelable; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; import com.ecomdev.openvpn.LaunchVPN; import com.ecomdev.openvpn.R; import com.ecomdev.openvpn.VpnProfile; import com.ecomdev.openvpn.core.ProfileManager; import java.util.Collection; import java.util.Vector; /** * This Activity actually handles two stages of a launcher shortcut's life cycle. * * 1. Your application offers to provide shortcuts to the launcher. When * the user installs a shortcut, an activity within your application * generates the actual shortcut and returns it to the launcher, where it * is shown to the user as an icon. * * 2. Any time the user clicks on an installed shortcut, an intent is sent. * Typically this would then be handled as necessary by an activity within * your application. * * We handle stage 1 (creating a shortcut) by simply sending back the information (in the form * of an {@link android.content.Intent} that the launcher will use to create the shortcut. * * You can also implement this in an interactive way, by having your activity actually present * UI for the user to select the specific nature of the shortcut, such as a contact, picture, URL, * media item, or action. * * We handle stage 2 (responding to a shortcut) in this sample by simply displaying the contents * of the incoming {@link android.content.Intent}. * * In a real application, you would probably use the shortcut intent to display specific content * or start a particular operation. */ public class CreateShortcuts extends ListActivity implements OnItemClickListener { private static final int START_VPN_PROFILE= 70; private ProfileManager mPM; private VpnProfile mSelectedProfile; @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); mPM =ProfileManager.getInstance(this); } @Override protected void onStart() { super.onStart(); // Resolve the intent createListView(); } private void createListView() { ListView lv = getListView(); //lv.setTextFilterEnabled(true); Collection<VpnProfile> vpnList = mPM.getProfiles(); Vector<String> vpnNames=new Vector<String>(); for (VpnProfile vpnProfile : vpnList) { vpnNames.add(vpnProfile.mName); } ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,vpnNames); lv.setAdapter(adapter); lv.setOnItemClickListener(this); } /** * This function creates a shortcut and returns it to the caller. There are actually two * intents that you will send back. * * The first intent serves as a container for the shortcut and is returned to the launcher by * setResult(). This intent must contain three fields: * * <ul> * <li>{@link android.content.Intent#EXTRA_SHORTCUT_INTENT} The shortcut intent.</li> * <li>{@link android.content.Intent#EXTRA_SHORTCUT_NAME} The text that will be displayed with * the shortcut.</li> * <li>{@link android.content.Intent#EXTRA_SHORTCUT_ICON} The shortcut's icon, if provided as a * bitmap, <i>or</i> {@link android.content.Intent#EXTRA_SHORTCUT_ICON_RESOURCE} if provided as * a drawable resource.</li> * </ul> * * If you use a simple drawable resource, note that you must wrapper it using * {@link android.content.Intent.ShortcutIconResource}, as shown below. This is required so * that the launcher can access resources that are stored in your application's .apk file. If * you return a bitmap, such as a thumbnail, you can simply put the bitmap into the extras * bundle using {@link android.content.Intent#EXTRA_SHORTCUT_ICON}. * * The shortcut intent can be any intent that you wish the launcher to send, when the user * clicks on the shortcut. Typically this will be {@link android.content.Intent#ACTION_VIEW} * with an appropriate Uri for your content, but any Intent will work here as long as it * triggers the desired action within your Activity. * @param profile */ private void setupShortcut(VpnProfile profile) { // First, set up the shortcut intent. For this example, we simply create an intent that // will bring us directly back to this activity. A more typical implementation would use a // data Uri in order to display a more specific result, or a custom action in order to // launch a specific operation. Intent shortcutIntent = new Intent(Intent.ACTION_MAIN); shortcutIntent.setClass(this, LaunchVPN.class); shortcutIntent.putExtra(LaunchVPN.EXTRA_KEY,profile.getUUID().toString()); // Then, set up the container intent (the response to the caller) Intent intent = new Intent(); intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent); intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, profile.getName()); Parcelable iconResource = Intent.ShortcutIconResource.fromContext( this, R.drawable.icon); intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconResource); // Now, return the result to the launcher setResult(RESULT_OK, intent); } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { String profileName = ((TextView) view).getText().toString(); VpnProfile profile = mPM.getProfileByName(profileName); setupShortcut(profile); finish(); } }
Java
package com.ecomdev.openvpn.activities; import android.app.Activity; import android.app.AlertDialog; import android.content.*; import android.os.IBinder; import com.ecomdev.openvpn.R; import com.ecomdev.openvpn.core.OpenVpnService; import com.ecomdev.openvpn.core.ProfileManager; /** * Created by arne on 13.10.13. */ public class DisconnectVPN extends Activity implements DialogInterface.OnClickListener{ protected OpenVpnService mService; private ServiceConnection mConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName className, IBinder service) { // We've bound to LocalService, cast the IBinder and get LocalService instance OpenVpnService.LocalBinder binder = (OpenVpnService.LocalBinder) service; mService = binder.getService(); } @Override public void onServiceDisconnected(ComponentName arg0) { mService =null; } }; @Override protected void onResume() { super.onResume(); Intent intent = new Intent(this, OpenVpnService.class); intent.setAction(OpenVpnService.START_SERVICE); bindService(intent, mConnection, Context.BIND_AUTO_CREATE); showDisconnectDialog(); } @Override protected void onStop() { super.onStop(); unbindService(mConnection); } // if (getIntent() !=null && OpenVpnService.DISCONNECT_VPN.equals(getIntent().getAction())) // setIntent(null); /* @Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); setIntent(intent); } */ private void showDisconnectDialog() { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(R.string.title_cancel); builder.setMessage(R.string.cancel_connection_query); builder.setNegativeButton(android.R.string.no, this); builder.setPositiveButton(android.R.string.yes,this); builder.show(); } @Override public void onClick(DialogInterface dialog, int which) { if (which == DialogInterface.BUTTON_POSITIVE) { ProfileManager.setConntectedVpnProfileDisconnected(this); if (mService != null && mService.getManagement() != null) mService.getManagement().stopVPN(); } finish(); } }
Java
package com.ecomdev.openvpn.activities; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import android.app.ActionBar; import android.app.ActionBar.Tab; import android.app.Activity; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.app.Fragment; import android.app.FragmentTransaction; import android.content.Intent; import android.os.Bundle; import android.os.Environment; import android.util.Base64; import com.ecomdev.openvpn.R; import com.ecomdev.openvpn.VpnProfile; import com.ecomdev.openvpn.fragments.FileSelectionFragment; import com.ecomdev.openvpn.fragments.InlineFileTab; public class FileSelect extends Activity { public static final String RESULT_DATA = "RESULT_PATH"; public static final String START_DATA = "START_DATA"; public static final String WINDOW_TITLE = "WINDOW_TILE"; public static final String NO_INLINE_SELECTION = "com.ecomdev.openvpn.NO_INLINE_SELECTION"; public static final String SHOW_CLEAR_BUTTON = "com.ecomdev.openvpn.SHOW_CLEAR_BUTTON"; public static final String DO_BASE64_ENCODE = "com.ecomdev.openvpn.BASE64ENCODE"; private FileSelectionFragment mFSFragment; private InlineFileTab mInlineFragment; private String mData; private Tab inlineFileTab; private Tab fileExplorerTab; private boolean mNoInline; private boolean mShowClear; private boolean mBase64Encode; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.file_dialog); mData = getIntent().getStringExtra(START_DATA); if(mData==null) mData=Environment.getExternalStorageDirectory().getPath(); String title = getIntent().getStringExtra(WINDOW_TITLE); int titleId = getIntent().getIntExtra(WINDOW_TITLE, 0); if(titleId!=0) title =getString(titleId); if(title!=null) setTitle(title); mNoInline = getIntent().getBooleanExtra(NO_INLINE_SELECTION, false); mShowClear = getIntent().getBooleanExtra(SHOW_CLEAR_BUTTON, false); mBase64Encode = getIntent().getBooleanExtra(DO_BASE64_ENCODE, false); ActionBar bar = getActionBar(); bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); fileExplorerTab = bar.newTab().setText(R.string.file_explorer_tab); inlineFileTab = bar.newTab().setText(R.string.inline_file_tab); mFSFragment = new FileSelectionFragment(); fileExplorerTab.setTabListener(new MyTabsListener<FileSelectionFragment>(this, mFSFragment)); bar.addTab(fileExplorerTab); if(!mNoInline) { mInlineFragment = new InlineFileTab(); inlineFileTab.setTabListener(new MyTabsListener<InlineFileTab>(this, mInlineFragment)); bar.addTab(inlineFileTab); } else { mFSFragment.setNoInLine(); } } public boolean showClear() { if(mData == null || mData.equals("")) return false; else return mShowClear; } protected class MyTabsListener<T extends Fragment> implements ActionBar.TabListener { private Fragment mFragment; private boolean mAdded=false; public MyTabsListener( Activity activity, Fragment fragment){ this.mFragment = fragment; } public void onTabSelected(Tab tab, FragmentTransaction ft) { // Check if the fragment is already initialized if (!mAdded) { // If not, instantiate and add it to the activity ft.add(android.R.id.content, mFragment); mAdded =true; } else { // If it exists, simply attach it in order to show it ft.attach(mFragment); } } @Override public void onTabUnselected(Tab tab, FragmentTransaction ft) { ft.detach(mFragment); } @Override public void onTabReselected(Tab tab, FragmentTransaction ft) { } } public void importFile(String path) { File ifile = new File(path); Exception fe = null; try { String data = ""; byte[] filedata = readBytesFromFile(ifile) ; if(mBase64Encode) data += Base64.encodeToString(filedata, Base64.DEFAULT); else data += new String(filedata); mData =data; /* mInlineFragment.setData(data); getActionBar().selectTab(inlineFileTab); */ saveInlineData(data); } catch (FileNotFoundException e) { fe = e; } catch (IOException e) { fe =e; } if(fe!=null) { Builder ab = new AlertDialog.Builder(this); ab.setTitle(R.string.error_importing_file); ab.setMessage(getString(R.string.import_error_message) + "\n" + fe.getLocalizedMessage()); ab.setPositiveButton(android.R.string.ok, null); ab.show(); } } static private byte[] readBytesFromFile(File file) throws IOException { InputStream input = new FileInputStream(file); long len= file.length(); if (len > VpnProfile.MAX_EMBED_FILE_SIZE) throw new IOException("selected file size too big to embed into profile"); // Create the byte array to hold the data byte[] bytes = new byte[(int) len]; // Read in the bytes int offset = 0; int bytesRead = 0; while (offset < bytes.length && (bytesRead=input.read(bytes, offset, bytes.length-offset)) >= 0) { offset += bytesRead; } input.close(); return bytes; } public void setFile(String path) { Intent intent = new Intent(); intent.putExtra(RESULT_DATA, path); setResult(Activity.RESULT_OK,intent); finish(); } public String getSelectPath() { if(!mData.startsWith(VpnProfile.INLINE_TAG)) return mData; else return Environment.getExternalStorageDirectory().getPath(); } public CharSequence getInlineData() { if(mData.startsWith(VpnProfile.INLINE_TAG)) return mData.substring(VpnProfile.INLINE_TAG.length()); else return ""; } public void clearData() { Intent intent = new Intent(); intent.putExtra(RESULT_DATA, (String)null); setResult(Activity.RESULT_OK,intent); finish(); } public void saveInlineData(String string) { Intent intent = new Intent(); intent.putExtra(RESULT_DATA,VpnProfile.INLINE_TAG + string); setResult(Activity.RESULT_OK,intent); finish(); } }
Java
package com.ecomdev.openvpn.activities; import android.app.ActionBar; import android.app.ActionBar.Tab; import android.app.Activity; import android.app.Fragment; import android.app.FragmentTransaction; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.content.SharedPreferences; import android.os.IBinder; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.TextView; import com.ecomdev.openvpn.Constants; import com.ecomdev.openvpn.DemoService; import com.ecomdev.openvpn.R; import com.ecomdev.openvpn.core.OpenVpnService; import com.ecomdev.openvpn.core.ProfileManager; import com.ecomdev.openvpn.fragments.*; public class MainActivity extends Activity implements DemoService.UpdateTimeListener { private MenuItem mDemoTimeMenuItem; protected OpenVpnService mService; private ServiceConnection mConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName className, IBinder service) { // We've bound to LocalService, cast the IBinder and get LocalService instance OpenVpnService.LocalBinder binder = (OpenVpnService.LocalBinder) service; mService = binder.getService(); ProfileManager.setConntectedVpnProfileDisconnected(MainActivity.this); if (mService != null && mService.getManagement() != null) { mService.getManagement().stopVPN(); } unbindService(mConnection); } @Override public void onServiceDisconnected(ComponentName arg0) { mService =null; } }; protected void onCreate(android.os.Bundle savedInstanceState) { super.onCreate(savedInstanceState); ActionBar bar = getActionBar(); bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); Tab vpnListTab = bar.newTab().setText(R.string.vpn_list_title); //Tab generalTab = bar.newTab().setText(R.string.generalsettings); //Tab faqtab = bar.newTab().setText(R.string.faq); Tab abouttab = bar.newTab().setText(R.string.about); vpnListTab.setTabListener(new TabListener<VPNProfileList>("profiles", VPNProfileList.class)); //generalTab.setTabListener(new TabListener<GeneralSettings>("settings", GeneralSettings.class)); //faqtab.setTabListener(new TabListener<FaqFragment>("faq", FaqFragment.class)); abouttab.setTabListener(new TabListener<AboutFragment>("about", AboutFragment.class)); bar.addTab(vpnListTab); //bar.addTab(generalTab); //bar.addTab(faqtab); bar.addTab(abouttab); if (false) { Tab logtab = bar.newTab().setText("Log"); logtab.setTabListener(new TabListener<LogFragment>("log", LogFragment.class)); bar.addTab(logtab); } if(SendDumpFragment.getLastestDump(this)!=null) { Tab sendDump = bar.newTab().setText(R.string.crashdump); sendDump.setTabListener(new TabListener<SendDumpFragment>("crashdump",SendDumpFragment.class)); bar.addTab(sendDump); } startDemoService(); } private void startDemoService() { } @Override public void updateDemoHours() { View actionView = mDemoTimeMenuItem.getActionView(); TextView timeView = (TextView) actionView.findViewById(R.id.demoTime); SharedPreferences preferences = getSharedPreferences(Constants.sMAIN_SHARED_PREFERENCE, MODE_PRIVATE); int defaultTime = getResources().getInteger(R.integer.demoHours); timeView.setText(preferences.getInt(Constants.sPREF_LEFT_HOURS, defaultTime) + "h"); } @Override public void timeOut() { Intent intent = new Intent(this, OpenVpnService.class); intent.setAction(OpenVpnService.START_SERVICE); bindService(intent, mConnection, Context.BIND_AUTO_CREATE); } protected class TabListener<T extends Fragment> implements ActionBar.TabListener { private Fragment mFragment; private String mTag; private Class<T> mClass; public TabListener(String tag, Class<T> clz) { mTag = tag; mClass = clz; // Check to see if we already have a fragment for this tab, probably // from a previously saved state. If so, deactivate it, because our // initial state is that a tab isn't shown. mFragment = getFragmentManager().findFragmentByTag(mTag); if (mFragment != null && !mFragment.isDetached()) { FragmentTransaction ft = getFragmentManager().beginTransaction(); ft.detach(mFragment); ft.commit(); } } public void onTabSelected(Tab tab, FragmentTransaction ft) { if (mFragment == null) { mFragment = Fragment.instantiate(MainActivity.this, mClass.getName()); ft.add(android.R.id.content, mFragment, mTag); } else { ft.attach(mFragment); } } public void onTabUnselected(Tab tab, FragmentTransaction ft) { if (mFragment != null) { ft.detach(mFragment); } } @Override public void onTabReselected(Tab tab, FragmentTransaction ft) { } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); System.out.println(data); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.demo_menu, menu); mDemoTimeMenuItem = menu.findItem(R.id.menuDemoTime); return super.onCreateOptionsMenu(menu); } }
Java
package com.ecomdev.openvpn.api; import java.util.HashSet; import java.util.Set; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.preference.PreferenceManager; public class ExternalAppDatabase { Context mContext; public ExternalAppDatabase(Context c) { mContext =c; } private final String PREFERENCES_KEY = "PREFERENCES_KEY"; boolean isAllowed(String packagename) { Set<String> allowedapps = getExtAppList(); return allowedapps.contains(packagename); } public Set<String> getExtAppList() { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext); return prefs.getStringSet(PREFERENCES_KEY, new HashSet<String>()); } void addApp(String packagename) { Set<String> allowedapps = getExtAppList(); allowedapps.add(packagename); saveExtAppList(allowedapps); } private void saveExtAppList( Set<String> allowedapps) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext); Editor prefedit = prefs.edit(); prefedit.putStringSet(PREFERENCES_KEY, allowedapps); prefedit.apply(); } public void clearAllApiApps() { saveExtAppList(new HashSet<String>()); } public void removeApp(String packagename) { Set<String> allowedapps = getExtAppList(); allowedapps.remove(packagename); saveExtAppList(allowedapps); } }
Java
package com.ecomdev.openvpn.api; import android.app.Activity; import android.content.Intent; import android.net.VpnService; public class GrantPermissionsActivity extends Activity { private static final int VPN_PREPARE = 0; @Override protected void onStart() { super.onStart(); Intent i= VpnService.prepare(this); if(i==null) onActivityResult(VPN_PREPARE, RESULT_OK, null); else startActivityForResult(i, VPN_PREPARE); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); setResult(resultCode); finish(); } }
Java
package com.ecomdev.openvpn.api; import android.os.RemoteException; public class SecurityRemoteException extends RemoteException { /** * */ private static final long serialVersionUID = 1L; }
Java
/* * Copyright (C) 2011 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ecomdev.openvpn.api; import android.app.Activity; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.content.DialogInterface; import android.content.DialogInterface.OnShowListener; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.CompoundButton; import android.widget.ImageView; import android.widget.TextView; import com.ecomdev.openvpn.R; public class ConfirmDialog extends Activity implements CompoundButton.OnCheckedChangeListener, DialogInterface.OnClickListener { private static final String TAG = "OpenVPNVpnConfirm"; private String mPackage; private Button mButton; private AlertDialog mAlert; @Override protected void onResume() { super.onResume(); try { mPackage = getCallingPackage(); if (mPackage==null) { finish(); return; } PackageManager pm = getPackageManager(); ApplicationInfo app = pm.getApplicationInfo(mPackage, 0); View view = View.inflate(this, R.layout.api_confirm, null); ((ImageView) view.findViewById(R.id.icon)).setImageDrawable(app.loadIcon(pm)); ((TextView) view.findViewById(R.id.prompt)).setText( getString(R.string.prompt, app.loadLabel(pm), getString(R.string.app))); ((CompoundButton) view.findViewById(R.id.check)).setOnCheckedChangeListener(this); Builder builder = new AlertDialog.Builder(this); builder.setView(view); builder.setIconAttribute(android.R.attr.alertDialogIcon); builder.setTitle(android.R.string.dialog_alert_title); builder.setPositiveButton(android.R.string.ok,this); builder.setNegativeButton(android.R.string.cancel,this); mAlert = builder.create(); mAlert.setCanceledOnTouchOutside(false); mAlert.setOnShowListener (new OnShowListener() { @Override public void onShow(DialogInterface dialog) { mButton = mAlert.getButton(DialogInterface.BUTTON_POSITIVE); mButton.setEnabled(false); } }); //setCloseOnTouchOutside(false); mAlert.show(); } catch (Exception e) { Log.e(TAG, "onResume", e); finish(); } } @Override public void onBackPressed() { setResult(RESULT_CANCELED); finish(); } @Override public void onCheckedChanged(CompoundButton button, boolean checked) { mButton.setEnabled(checked); } @Override public void onClick(DialogInterface dialog, int which) { if (which == DialogInterface.BUTTON_POSITIVE) { ExternalAppDatabase extapps = new ExternalAppDatabase(this); extapps.addApp(mPackage); setResult(RESULT_OK); finish(); } if (which == DialogInterface.BUTTON_NEGATIVE) { setResult(RESULT_CANCELED); finish(); } } }
Java