code
stringlengths
3
1.18M
language
stringclasses
1 value
package org.anddev.andengine.engine.handler.collision; import org.anddev.andengine.entity.shape.IShape; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 12:05:39 - 11.03.2010 */ public interface ICollisionCallback { // =========================================================== // Final Fields // =========================================================== // =========================================================== // Methods // =========================================================== /** * @param pCheckShape * @param pTargetShape * @return <code>true</code> to proceed, <code>false</code> to stop further collosion-checks. */ public boolean onCollision(final IShape pCheckShape, final IShape pTargetShape); }
Java
package org.anddev.andengine.engine.handler; import org.anddev.andengine.entity.IEntity; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 14:00:25 - 24.12.2010 */ public abstract class BaseEntityUpdateHandler implements IUpdateHandler { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private final IEntity mEntity; // =========================================================== // Constructors // =========================================================== public BaseEntityUpdateHandler(final IEntity pEntity) { this.mEntity = pEntity; } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== protected abstract void onUpdate(final float pSecondsElapsed, final IEntity pEntity); @Override public final void onUpdate(final float pSecondsElapsed) { this.onUpdate(pSecondsElapsed, this.mEntity); } @Override public void reset() { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.engine.handler.physics; import org.anddev.andengine.engine.handler.BaseEntityUpdateHandler; import org.anddev.andengine.entity.IEntity; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 13:53:07 - 24.12.2010 */ public class PhysicsHandler extends BaseEntityUpdateHandler { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private boolean mEnabled = true; protected float mAccelerationX = 0; protected float mAccelerationY = 0; protected float mVelocityX = 0; protected float mVelocityY = 0; protected float mAngularVelocity = 0; // =========================================================== // Constructors // =========================================================== public PhysicsHandler(final IEntity pEntity) { super(pEntity); } // =========================================================== // Getter & Setter // =========================================================== public boolean isEnabled() { return this.mEnabled; } public void setEnabled(final boolean pEnabled) { this.mEnabled = pEnabled; } public float getVelocityX() { return this.mVelocityX; } public float getVelocityY() { return this.mVelocityY; } public void setVelocityX(final float pVelocityX) { this.mVelocityX = pVelocityX; } public void setVelocityY(final float pVelocityY) { this.mVelocityY = pVelocityY; } public void setVelocity(final float pVelocity) { this.mVelocityX = pVelocity; this.mVelocityY = pVelocity; } public void setVelocity(final float pVelocityX, final float pVelocityY) { this.mVelocityX = pVelocityX; this.mVelocityY = pVelocityY; } public float getAccelerationX() { return this.mAccelerationX; } public float getAccelerationY() { return this.mAccelerationY; } public void setAccelerationX(final float pAccelerationX) { this.mAccelerationX = pAccelerationX; } public void setAccelerationY(final float pAccelerationY) { this.mAccelerationY = pAccelerationY; } public void setAcceleration(final float pAccelerationX, final float pAccelerationY) { this.mAccelerationX = pAccelerationX; this.mAccelerationY = pAccelerationY; } public void setAcceleration(final float pAcceleration) { this.mAccelerationX = pAcceleration; this.mAccelerationY = pAcceleration; } public void accelerate(final float pAccelerationX, final float pAccelerationY) { this.mAccelerationX += pAccelerationX; this.mAccelerationY += pAccelerationY; } public float getAngularVelocity() { return this.mAngularVelocity; } public void setAngularVelocity(final float pAngularVelocity) { this.mAngularVelocity = pAngularVelocity; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override protected void onUpdate(final float pSecondsElapsed, final IEntity pEntity) { if(this.mEnabled) { /* Apply linear acceleration. */ final float accelerationX = this.mAccelerationX; final float accelerationY = this.mAccelerationY; if(accelerationX != 0 || accelerationY != 0) { this.mVelocityX += accelerationX * pSecondsElapsed; this.mVelocityY += accelerationY * pSecondsElapsed; } /* Apply angular velocity. */ final float angularVelocity = this.mAngularVelocity; if(angularVelocity != 0) { pEntity.setRotation(pEntity.getRotation() + angularVelocity * pSecondsElapsed); } /* Apply linear velocity. */ final float velocityX = this.mVelocityX; final float velocityY = this.mVelocityY; if(velocityX != 0 || velocityY != 0) { pEntity.setPosition(pEntity.getX() + velocityX * pSecondsElapsed, pEntity.getY() + velocityY * pSecondsElapsed); } } } @Override public void reset() { this.mAccelerationX = 0; this.mAccelerationY = 0; this.mVelocityX = 0; this.mVelocityY = 0; this.mAngularVelocity = 0; } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.engine; import javax.microedition.khronos.opengles.GL10; import javax.microedition.khronos.opengles.GL11; import org.anddev.andengine.audio.music.MusicFactory; import org.anddev.andengine.audio.music.MusicManager; import org.anddev.andengine.audio.sound.SoundFactory; import org.anddev.andengine.audio.sound.SoundManager; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.handler.IUpdateHandler; import org.anddev.andengine.engine.handler.UpdateHandlerList; import org.anddev.andengine.engine.handler.runnable.RunnableHandler; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.input.touch.TouchEvent; import org.anddev.andengine.input.touch.controller.ITouchController; import org.anddev.andengine.input.touch.controller.ITouchController.ITouchEventCallback; import org.anddev.andengine.input.touch.controller.SingleTouchControler; import org.anddev.andengine.opengl.buffer.BufferObjectManager; import org.anddev.andengine.opengl.font.FontFactory; import org.anddev.andengine.opengl.font.FontManager; import org.anddev.andengine.opengl.texture.TextureManager; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.util.GLHelper; import org.anddev.andengine.sensor.SensorDelay; import org.anddev.andengine.sensor.accelerometer.AccelerometerData; import org.anddev.andengine.sensor.accelerometer.AccelerometerSensorOptions; import org.anddev.andengine.sensor.accelerometer.IAccelerometerListener; import org.anddev.andengine.sensor.location.ILocationListener; import org.anddev.andengine.sensor.location.LocationProviderStatus; import org.anddev.andengine.sensor.location.LocationSensorOptions; import org.anddev.andengine.sensor.orientation.IOrientationListener; import org.anddev.andengine.sensor.orientation.OrientationData; import org.anddev.andengine.sensor.orientation.OrientationSensorOptions; import org.anddev.andengine.util.Debug; import org.anddev.andengine.util.constants.TimeConstants; import android.content.Context; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.location.LocationProvider; import android.os.Bundle; import android.os.Vibrator; import android.view.Display; import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; import android.view.WindowManager; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 12:21:31 - 08.03.2010 */ public class Engine implements SensorEventListener, OnTouchListener, ITouchEventCallback, TimeConstants, LocationListener { // =========================================================== // Constants // =========================================================== private static final SensorDelay SENSORDELAY_DEFAULT = SensorDelay.GAME; private static final int UPDATEHANDLERS_CAPACITY_DEFAULT = 32; // =========================================================== // Fields // =========================================================== private boolean mRunning = false; private long mLastTick = -1; private float mSecondsElapsedTotal = 0; private final State mThreadLocker = new State(); private final UpdateThread mUpdateThread = new UpdateThread(); private final RunnableHandler mUpdateThreadRunnableHandler = new RunnableHandler(); private final EngineOptions mEngineOptions; protected final Camera mCamera; private ITouchController mTouchController; private SoundManager mSoundManager; private MusicManager mMusicManager; private final TextureManager mTextureManager = new TextureManager(); private final BufferObjectManager mBufferObjectManager = new BufferObjectManager(); private final FontManager mFontManager = new FontManager(); protected Scene mScene; private Vibrator mVibrator; private ILocationListener mLocationListener; private Location mLocation; private IAccelerometerListener mAccelerometerListener; private AccelerometerData mAccelerometerData; private IOrientationListener mOrientationListener; private OrientationData mOrientationData; private final UpdateHandlerList mUpdateHandlers = new UpdateHandlerList(UPDATEHANDLERS_CAPACITY_DEFAULT); protected int mSurfaceWidth = 1; // 1 to prevent accidental DIV/0 protected int mSurfaceHeight = 1; // 1 to prevent accidental DIV/0 private boolean mIsMethodTracing; // =========================================================== // Constructors // =========================================================== public Engine(final EngineOptions pEngineOptions) { BitmapTextureAtlasTextureRegionFactory.reset(); SoundFactory.reset(); MusicFactory.reset(); FontFactory.reset(); BufferObjectManager.setActiveInstance(this.mBufferObjectManager); this.mEngineOptions = pEngineOptions; this.setTouchController(new SingleTouchControler()); this.mCamera = pEngineOptions.getCamera(); if(this.mEngineOptions.needsSound()) { this.mSoundManager = new SoundManager(); } if(this.mEngineOptions.needsMusic()) { this.mMusicManager = new MusicManager(); } this.mUpdateThread.start(); } // =========================================================== // Getter & Setter // =========================================================== public boolean isRunning() { return this.mRunning; } public synchronized void start() { if(!this.mRunning) { this.mLastTick = System.nanoTime(); this.mRunning = true; } } public synchronized void stop() { if(this.mRunning) { this.mRunning = false; } } public Scene getScene() { return this.mScene; } public void setScene(final Scene pScene) { this.mScene = pScene; } public EngineOptions getEngineOptions() { return this.mEngineOptions; } public Camera getCamera() { return this.mCamera; } public float getSecondsElapsedTotal() { return this.mSecondsElapsedTotal; } public void setSurfaceSize(final int pSurfaceWidth, final int pSurfaceHeight) { // Debug.w("SurfaceView size changed to (width x height): " + pSurfaceWidth + " x " + pSurfaceHeight, new Exception()); this.mSurfaceWidth = pSurfaceWidth; this.mSurfaceHeight = pSurfaceHeight; this.onUpdateCameraSurface(); } protected void onUpdateCameraSurface() { this.mCamera.setSurfaceSize(0, 0, this.mSurfaceWidth, this.mSurfaceHeight); } public int getSurfaceWidth() { return this.mSurfaceWidth; } public int getSurfaceHeight() { return this.mSurfaceHeight; } public ITouchController getTouchController() { return this.mTouchController; } public void setTouchController(final ITouchController pTouchController) { this.mTouchController = pTouchController; this.mTouchController.applyTouchOptions(this.mEngineOptions.getTouchOptions()); this.mTouchController.setTouchEventCallback(this); } public AccelerometerData getAccelerometerData() { return this.mAccelerometerData; } public OrientationData getOrientationData() { return this.mOrientationData; } public SoundManager getSoundManager() throws IllegalStateException { if(this.mSoundManager != null) { return this.mSoundManager; } else { throw new IllegalStateException("To enable the SoundManager, check the EngineOptions!"); } } public MusicManager getMusicManager() throws IllegalStateException { if(this.mMusicManager != null) { return this.mMusicManager; } else { throw new IllegalStateException("To enable the MusicManager, check the EngineOptions!"); } } public TextureManager getTextureManager() { return this.mTextureManager; } public FontManager getFontManager() { return this.mFontManager; } public void clearUpdateHandlers() { this.mUpdateHandlers.clear(); } public void registerUpdateHandler(final IUpdateHandler pUpdateHandler) { this.mUpdateHandlers.add(pUpdateHandler); } public void unregisterUpdateHandler(final IUpdateHandler pUpdateHandler) { this.mUpdateHandlers.remove(pUpdateHandler); } public boolean isMethodTracing() { return this.mIsMethodTracing; } public void startMethodTracing(final String pTraceFileName) { if(!this.mIsMethodTracing) { this.mIsMethodTracing = true; android.os.Debug.startMethodTracing(pTraceFileName); } } public void stopMethodTracing() { if(this.mIsMethodTracing) { android.os.Debug.stopMethodTracing(); this.mIsMethodTracing = false; } } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public void onAccuracyChanged(final Sensor pSensor, final int pAccuracy) { if(this.mRunning) { switch(pSensor.getType()) { case Sensor.TYPE_ACCELEROMETER: if(this.mAccelerometerData != null) { this.mAccelerometerData.setAccuracy(pAccuracy); this.mAccelerometerListener.onAccelerometerChanged(this.mAccelerometerData); } else if(this.mOrientationData != null) { this.mOrientationData.setAccelerometerAccuracy(pAccuracy); this.mOrientationListener.onOrientationChanged(this.mOrientationData); } break; case Sensor.TYPE_MAGNETIC_FIELD: this.mOrientationData.setMagneticFieldAccuracy(pAccuracy); this.mOrientationListener.onOrientationChanged(this.mOrientationData); break; } } } @Override public void onSensorChanged(final SensorEvent pEvent) { if(this.mRunning) { switch(pEvent.sensor.getType()) { case Sensor.TYPE_ACCELEROMETER: if(this.mAccelerometerData != null) { this.mAccelerometerData.setValues(pEvent.values); this.mAccelerometerListener.onAccelerometerChanged(this.mAccelerometerData); } else if(this.mOrientationData != null) { this.mOrientationData.setAccelerometerValues(pEvent.values); this.mOrientationListener.onOrientationChanged(this.mOrientationData); } break; case Sensor.TYPE_MAGNETIC_FIELD: this.mOrientationData.setMagneticFieldValues(pEvent.values); this.mOrientationListener.onOrientationChanged(this.mOrientationData); break; } } } @Override public void onLocationChanged(final Location pLocation) { if(this.mLocation == null) { this.mLocation = pLocation; } else { if(pLocation == null) { this.mLocationListener.onLocationLost(); } else { this.mLocation = pLocation; this.mLocationListener.onLocationChanged(pLocation); } } } @Override public void onProviderDisabled(final String pProvider) { this.mLocationListener.onLocationProviderDisabled(); } @Override public void onProviderEnabled(final String pProvider) { this.mLocationListener.onLocationProviderEnabled(); } @Override public void onStatusChanged(final String pProvider, final int pStatus, final Bundle pExtras) { switch(pStatus) { case LocationProvider.AVAILABLE: this.mLocationListener.onLocationProviderStatusChanged(LocationProviderStatus.AVAILABLE, pExtras); break; case LocationProvider.OUT_OF_SERVICE: this.mLocationListener.onLocationProviderStatusChanged(LocationProviderStatus.OUT_OF_SERVICE, pExtras); break; case LocationProvider.TEMPORARILY_UNAVAILABLE: this.mLocationListener.onLocationProviderStatusChanged(LocationProviderStatus.TEMPORARILY_UNAVAILABLE, pExtras); break; } } @Override public boolean onTouch(final View pView, final MotionEvent pSurfaceMotionEvent) { if(this.mRunning) { final boolean handled = this.mTouchController.onHandleMotionEvent(pSurfaceMotionEvent); try { /* * As a human cannot interact 1000x per second, we pause the * UI-Thread for a little. */ Thread.sleep(20); // TODO Maybe this can be removed, when TouchEvents are handled on the UpdateThread! } catch (final InterruptedException e) { Debug.e(e); } return handled; } else { return false; } } @Override public boolean onTouchEvent(final TouchEvent pSurfaceTouchEvent) { /* * Let the engine determine which scene and camera this event should be * handled by. */ final Scene scene = this.getSceneFromSurfaceTouchEvent(pSurfaceTouchEvent); final Camera camera = this.getCameraFromSurfaceTouchEvent(pSurfaceTouchEvent); this.convertSurfaceToSceneTouchEvent(camera, pSurfaceTouchEvent); if(this.onTouchHUD(camera, pSurfaceTouchEvent)) { return true; } else { /* If HUD didn't handle it, Scene may handle it. */ return this.onTouchScene(scene, pSurfaceTouchEvent); } } protected boolean onTouchHUD(final Camera pCamera, final TouchEvent pSceneTouchEvent) { if(pCamera.hasHUD()) { return pCamera.getHUD().onSceneTouchEvent(pSceneTouchEvent); } else { return false; } } protected boolean onTouchScene(final Scene pScene, final TouchEvent pSceneTouchEvent) { if(pScene != null) { return pScene.onSceneTouchEvent(pSceneTouchEvent); } else { return false; } } // =========================================================== // Methods // =========================================================== public void runOnUpdateThread(final Runnable pRunnable) { this.mUpdateThreadRunnableHandler.postRunnable(pRunnable); } public void interruptUpdateThread(){ this.mUpdateThread.interrupt(); } public void onResume() { // TODO GLHelper.reset(pGL); ? this.mTextureManager.reloadTextures(); this.mFontManager.reloadFonts(); BufferObjectManager.setActiveInstance(this.mBufferObjectManager); this.mBufferObjectManager.reloadBufferObjects(); } public void onPause() { } protected Camera getCameraFromSurfaceTouchEvent(@SuppressWarnings("unused") final TouchEvent pTouchEvent) { return this.getCamera(); } protected Scene getSceneFromSurfaceTouchEvent(@SuppressWarnings("unused") final TouchEvent pTouchEvent) { return this.mScene; } protected void convertSurfaceToSceneTouchEvent(final Camera pCamera, final TouchEvent pSurfaceTouchEvent) { pCamera.convertSurfaceToSceneTouchEvent(pSurfaceTouchEvent, this.mSurfaceWidth, this.mSurfaceHeight); } public void onLoadComplete(final Scene pScene) { this.setScene(pScene); } void onTickUpdate() throws InterruptedException { if(this.mRunning) { final long secondsElapsed = this.getNanosecondsElapsed(); this.onUpdate(secondsElapsed); this.yieldDraw(); } else { this.yieldDraw(); Thread.sleep(16); } } private void yieldDraw() throws InterruptedException { final State threadLocker = this.mThreadLocker; threadLocker.notifyCanDraw(); threadLocker.waitUntilCanUpdate(); } protected void onUpdate(final long pNanosecondsElapsed) throws InterruptedException { final float pSecondsElapsed = (float)pNanosecondsElapsed / TimeConstants.NANOSECONDSPERSECOND; this.mSecondsElapsedTotal += pSecondsElapsed; this.mLastTick += pNanosecondsElapsed; this.mTouchController.onUpdate(pSecondsElapsed); this.updateUpdateHandlers(pSecondsElapsed); this.onUpdateScene(pSecondsElapsed); } protected void onUpdateScene(final float pSecondsElapsed) { if(this.mScene != null) { this.mScene.onUpdate(pSecondsElapsed); } } protected void updateUpdateHandlers(final float pSecondsElapsed) { this.mUpdateThreadRunnableHandler.onUpdate(pSecondsElapsed); this.mUpdateHandlers.onUpdate(pSecondsElapsed); this.getCamera().onUpdate(pSecondsElapsed); } public void onDrawFrame(final GL10 pGL) throws InterruptedException { final State threadLocker = this.mThreadLocker; threadLocker.waitUntilCanDraw(); this.mTextureManager.updateTextures(pGL); this.mFontManager.updateFonts(pGL); if(GLHelper.EXTENSIONS_VERTEXBUFFEROBJECTS) { this.mBufferObjectManager.updateBufferObjects((GL11) pGL); } this.onDrawScene(pGL); threadLocker.notifyCanUpdate(); } protected void onDrawScene(final GL10 pGL) { final Camera camera = this.getCamera(); this.mScene.onDraw(pGL, camera); camera.onDrawHUD(pGL); } private long getNanosecondsElapsed() { final long now = System.nanoTime(); return this.calculateNanosecondsElapsed(now, this.mLastTick); } protected long calculateNanosecondsElapsed(final long pNow, final long pLastTick) { return pNow - pLastTick; } public boolean enableVibrator(final Context pContext) { this.mVibrator = (Vibrator) pContext.getSystemService(Context.VIBRATOR_SERVICE); return this.mVibrator != null; } public void vibrate(final long pMilliseconds) throws IllegalStateException { if(this.mVibrator != null) { this.mVibrator.vibrate(pMilliseconds); } else { throw new IllegalStateException("You need to enable the Vibrator before you can use it!"); } } public void vibrate(final long[] pPattern, final int pRepeat) throws IllegalStateException { if(this.mVibrator != null) { this.mVibrator.vibrate(pPattern, pRepeat); } else { throw new IllegalStateException("You need to enable the Vibrator before you can use it!"); } } public void enableLocationSensor(final Context pContext, final ILocationListener pLocationListener, final LocationSensorOptions pLocationSensorOptions) { this.mLocationListener = pLocationListener; final LocationManager locationManager = (LocationManager) pContext.getSystemService(Context.LOCATION_SERVICE); final String locationProvider = locationManager.getBestProvider(pLocationSensorOptions, pLocationSensorOptions.isEnabledOnly()); // TODO locationProvider can be null, in that case return false. Successful case should return true. locationManager.requestLocationUpdates(locationProvider, pLocationSensorOptions.getMinimumTriggerTime(), pLocationSensorOptions.getMinimumTriggerDistance(), this); this.onLocationChanged(locationManager.getLastKnownLocation(locationProvider)); } public void disableLocationSensor(final Context pContext) { final LocationManager locationManager = (LocationManager) pContext.getSystemService(Context.LOCATION_SERVICE); locationManager.removeUpdates(this); } /** * @see {@link Engine#enableAccelerometerSensor(Context, IAccelerometerListener, AccelerometerSensorOptions)} */ public boolean enableAccelerometerSensor(final Context pContext, final IAccelerometerListener pAccelerometerListener) { return this.enableAccelerometerSensor(pContext, pAccelerometerListener, new AccelerometerSensorOptions(SENSORDELAY_DEFAULT)); } /** * @return <code>true</code> when the sensor was successfully enabled, <code>false</code> otherwise. */ public boolean enableAccelerometerSensor(final Context pContext, final IAccelerometerListener pAccelerometerListener, final AccelerometerSensorOptions pAccelerometerSensorOptions) { final SensorManager sensorManager = (SensorManager) pContext.getSystemService(Context.SENSOR_SERVICE); if(this.isSensorSupported(sensorManager, Sensor.TYPE_ACCELEROMETER)) { this.mAccelerometerListener = pAccelerometerListener; if(this.mAccelerometerData == null) { final Display display = ((WindowManager) pContext.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); final int displayRotation = display.getOrientation(); this.mAccelerometerData = new AccelerometerData(displayRotation); } this.registerSelfAsSensorListener(sensorManager, Sensor.TYPE_ACCELEROMETER, pAccelerometerSensorOptions.getSensorDelay()); return true; } else { return false; } } /** * @return <code>true</code> when the sensor was successfully disabled, <code>false</code> otherwise. */ public boolean disableAccelerometerSensor(final Context pContext) { final SensorManager sensorManager = (SensorManager) pContext.getSystemService(Context.SENSOR_SERVICE); if(this.isSensorSupported(sensorManager, Sensor.TYPE_ACCELEROMETER)) { this.unregisterSelfAsSensorListener(sensorManager, Sensor.TYPE_ACCELEROMETER); return true; } else { return false; } } /** * @see {@link Engine#enableOrientationSensor(Context, IOrientationListener, OrientationSensorOptions)} */ public boolean enableOrientationSensor(final Context pContext, final IOrientationListener pOrientationListener) { return this.enableOrientationSensor(pContext, pOrientationListener, new OrientationSensorOptions(SENSORDELAY_DEFAULT)); } /** * @return <code>true</code> when the sensor was successfully enabled, <code>false</code> otherwise. */ public boolean enableOrientationSensor(final Context pContext, final IOrientationListener pOrientationListener, final OrientationSensorOptions pOrientationSensorOptions) { final SensorManager sensorManager = (SensorManager) pContext.getSystemService(Context.SENSOR_SERVICE); if(this.isSensorSupported(sensorManager, Sensor.TYPE_ACCELEROMETER) && this.isSensorSupported(sensorManager, Sensor.TYPE_MAGNETIC_FIELD)) { this.mOrientationListener = pOrientationListener; if(this.mOrientationData == null) { final Display display = ((WindowManager) pContext.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); final int displayRotation = display.getOrientation(); this.mOrientationData = new OrientationData(displayRotation); } this.registerSelfAsSensorListener(sensorManager, Sensor.TYPE_ACCELEROMETER, pOrientationSensorOptions.getSensorDelay()); this.registerSelfAsSensorListener(sensorManager, Sensor.TYPE_MAGNETIC_FIELD, pOrientationSensorOptions.getSensorDelay()); return true; } else { return false; } } /** * @return <code>true</code> when the sensor was successfully disabled, <code>false</code> otherwise. */ public boolean disableOrientationSensor(final Context pContext) { final SensorManager sensorManager = (SensorManager) pContext.getSystemService(Context.SENSOR_SERVICE); if(this.isSensorSupported(sensorManager, Sensor.TYPE_ACCELEROMETER) && this.isSensorSupported(sensorManager, Sensor.TYPE_MAGNETIC_FIELD)) { this.unregisterSelfAsSensorListener(sensorManager, Sensor.TYPE_ACCELEROMETER); this.unregisterSelfAsSensorListener(sensorManager, Sensor.TYPE_MAGNETIC_FIELD); return true; } else { return false; } } private boolean isSensorSupported(final SensorManager pSensorManager, final int pType) { return pSensorManager.getSensorList(pType).size() > 0; } private void registerSelfAsSensorListener(final SensorManager pSensorManager, final int pType, final SensorDelay pSensorDelay) { final Sensor sensor = pSensorManager.getSensorList(pType).get(0); pSensorManager.registerListener(this, sensor, pSensorDelay.getDelay()); } private void unregisterSelfAsSensorListener(final SensorManager pSensorManager, final int pType) { final Sensor sensor = pSensorManager.getSensorList(pType).get(0); pSensorManager.unregisterListener(this, sensor); } // =========================================================== // Inner and Anonymous Classes // =========================================================== private class UpdateThread extends Thread { public UpdateThread() { super("UpdateThread"); } @Override public void run() { android.os.Process.setThreadPriority(Engine.this.mEngineOptions.getUpdateThreadPriority()); try { while(true) { Engine.this.onTickUpdate(); } } catch (final InterruptedException e) { Debug.d("UpdateThread interrupted. Don't worry - this Exception is most likely expected!", e); this.interrupt(); } } } private static class State { boolean mDrawing = false; public synchronized void notifyCanDraw() { // Debug.d(">>> notifyCanDraw"); this.mDrawing = true; this.notifyAll(); // Debug.d("<<< notifyCanDraw"); } public synchronized void notifyCanUpdate() { // Debug.d(">>> notifyCanUpdate"); this.mDrawing = false; this.notifyAll(); // Debug.d("<<< notifyCanUpdate"); } public synchronized void waitUntilCanDraw() throws InterruptedException { // Debug.d(">>> waitUntilCanDraw"); while(!this.mDrawing) { this.wait(); } // Debug.d("<<< waitUntilCanDraw"); } public synchronized void waitUntilCanUpdate() throws InterruptedException { // Debug.d(">>> waitUntilCanUpdate"); while(this.mDrawing) { this.wait(); } // Debug.d("<<< waitUntilCanUpdate"); } } }
Java
package org.anddev.andengine.engine; import javax.microedition.khronos.opengles.GL10; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.input.touch.TouchEvent; import org.anddev.andengine.opengl.util.GLHelper; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 22:28:34 - 27.03.2010 */ public class SingleSceneSplitScreenEngine extends Engine { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private final Camera mSecondCamera; // =========================================================== // Constructors // =========================================================== public SingleSceneSplitScreenEngine(final EngineOptions pEngineOptions, final Camera pSecondCamera) { super(pEngineOptions); this.mSecondCamera = pSecondCamera; } // =========================================================== // Getter & Setter // =========================================================== @Deprecated @Override public Camera getCamera() { return super.mCamera; } public Camera getFirstCamera() { return super.mCamera; } public Camera getSecondCamera() { return this.mSecondCamera; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override protected void onDrawScene(final GL10 pGL) { final Camera firstCamera = this.getFirstCamera(); final Camera secondCamera = this.getSecondCamera(); final int surfaceWidth = this.mSurfaceWidth; final int surfaceWidthHalf = surfaceWidth >> 1; final int surfaceHeight = this.mSurfaceHeight; GLHelper.enableScissorTest(pGL); /* First Screen. With first camera, on the left half of the screens width. */ { pGL.glScissor(0, 0, surfaceWidthHalf, surfaceHeight); pGL.glViewport(0, 0, surfaceWidthHalf, surfaceHeight); super.mScene.onDraw(pGL, firstCamera); firstCamera.onDrawHUD(pGL); } /* Second Screen. With second camera, on the right half of the screens width. */ { pGL.glScissor(surfaceWidthHalf, 0, surfaceWidthHalf, surfaceHeight); pGL.glViewport(surfaceWidthHalf, 0, surfaceWidthHalf, surfaceHeight); super.mScene.onDraw(pGL, secondCamera); secondCamera.onDrawHUD(pGL); } GLHelper.disableScissorTest(pGL); } @Override protected Camera getCameraFromSurfaceTouchEvent(final TouchEvent pTouchEvent) { if(pTouchEvent.getX() <= this.mSurfaceWidth >> 1) { return this.getFirstCamera(); } else { return this.getSecondCamera(); } } @Override protected void convertSurfaceToSceneTouchEvent(final Camera pCamera, final TouchEvent pSurfaceTouchEvent) { final int surfaceWidthHalf = this.mSurfaceWidth >> 1; if(pCamera == this.getFirstCamera()) { pCamera.convertSurfaceToSceneTouchEvent(pSurfaceTouchEvent, surfaceWidthHalf, this.mSurfaceHeight); } else { pSurfaceTouchEvent.offset(-surfaceWidthHalf, 0); pCamera.convertSurfaceToSceneTouchEvent(pSurfaceTouchEvent, surfaceWidthHalf, this.mSurfaceHeight); } } @Override protected void updateUpdateHandlers(final float pSecondsElapsed) { super.updateUpdateHandlers(pSecondsElapsed); this.getSecondCamera().onUpdate(pSecondsElapsed); } @Override protected void onUpdateCameraSurface() { final int surfaceWidth = this.mSurfaceWidth; final int surfaceWidthHalf = surfaceWidth >> 1; this.getFirstCamera().setSurfaceSize(0, 0, surfaceWidthHalf, this.mSurfaceHeight); this.getSecondCamera().setSurfaceSize(surfaceWidthHalf, 0, surfaceWidthHalf, this.mSurfaceHeight); } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.engine; import org.anddev.andengine.engine.options.EngineOptions; /** * A subclass of {@link Engine} that tries to achieve a specific amount of updates per second. * When the time since the last update is bigger long the steplength, additional updates are executed. * * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 10:17:47 - 02.08.2010 */ public class FixedStepEngine extends Engine { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private final long mStepLength; private long mSecondsElapsedAccumulator; // =========================================================== // Constructors // =========================================================== public FixedStepEngine(final EngineOptions pEngineOptions, final int pStepsPerSecond) { super(pEngineOptions); this.mStepLength = NANOSECONDSPERSECOND / pStepsPerSecond; } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public void onUpdate(final long pNanosecondsElapsed) throws InterruptedException { this.mSecondsElapsedAccumulator += pNanosecondsElapsed; final long stepLength = this.mStepLength; while(this.mSecondsElapsedAccumulator >= stepLength) { super.onUpdate(stepLength); this.mSecondsElapsedAccumulator -= stepLength; } } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.engine.options; import android.os.PowerManager; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 19:45:23 - 10.07.2010 */ public enum WakeLockOptions { // =========================================================== // Elements // =========================================================== /** Screen is on at full brightness. Keyboard backlight is on at full brightness. Requires <b>WAKE_LOCK</b> permission! */ BRIGHT(PowerManager.FULL_WAKE_LOCK), /** Screen is on at full brightness. Keyboard backlight will be allowed to go off. Requires <b>WAKE_LOCK</b> permission!*/ SCREEN_BRIGHT(PowerManager.SCREEN_BRIGHT_WAKE_LOCK), /** Screen is on but may be dimmed. Keyboard backlight will be allowed to go off. Requires <b>WAKE_LOCK</b> permission!*/ SCREEN_DIM(PowerManager.SCREEN_DIM_WAKE_LOCK), /** Screen is on at full brightness. Does <b>not</b> require <b>WAKE_LOCK</b> permission! */ SCREEN_ON(-1); // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private final int mFlag; // =========================================================== // Constructors // =========================================================== private WakeLockOptions(final int pFlag) { this.mFlag = pFlag; } // =========================================================== // Getter & Setter // =========================================================== public int getFlag() { return this.mFlag; } // =========================================================== // Methods from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.engine.options; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 13:01:40 - 02.07.2010 */ public class RenderOptions { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private boolean mDisableExtensionVertexBufferObjects = false; private boolean mDisableExtensionDrawTexture = false; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== /** * <u><b>Default:</b></u> <code>false</code> */ public boolean isDisableExtensionVertexBufferObjects() { return this.mDisableExtensionVertexBufferObjects; } public RenderOptions enableExtensionVertexBufferObjects() { return this.setDisableExtensionVertexBufferObjects(false); } public RenderOptions disableExtensionVertexBufferObjects() { return this.setDisableExtensionVertexBufferObjects(true); } public RenderOptions setDisableExtensionVertexBufferObjects(final boolean pDisableExtensionVertexBufferObjects) { this.mDisableExtensionVertexBufferObjects = pDisableExtensionVertexBufferObjects; return this; } /** * <u><b>Default:</b></u> <code>false</code> */ public boolean isDisableExtensionDrawTexture() { return this.mDisableExtensionDrawTexture; } public RenderOptions enableExtensionDrawTexture() { return this.setDisableExtensionDrawTexture(false); } public RenderOptions disableExtensionDrawTexture() { return this.setDisableExtensionDrawTexture(true); } public RenderOptions setDisableExtensionDrawTexture(final boolean pDisableExtensionDrawTexture) { this.mDisableExtensionDrawTexture = pDisableExtensionDrawTexture; return this; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.engine.options; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.resolutionpolicy.IResolutionPolicy; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 15:59:52 - 09.03.2010 */ public class EngineOptions { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private final boolean mFullscreen; private final ScreenOrientation mScreenOrientation; private final IResolutionPolicy mResolutionPolicy; private final Camera mCamera; private final TouchOptions mTouchOptions = new TouchOptions(); private final RenderOptions mRenderOptions = new RenderOptions(); private boolean mNeedsSound; private boolean mNeedsMusic; private WakeLockOptions mWakeLockOptions = WakeLockOptions.SCREEN_BRIGHT; private int mUpdateThreadPriority = android.os.Process.THREAD_PRIORITY_DEFAULT;; // =========================================================== // Constructors // =========================================================== public EngineOptions(final boolean pFullscreen, final ScreenOrientation pScreenOrientation, final IResolutionPolicy pResolutionPolicy, final Camera pCamera) { this.mFullscreen = pFullscreen; this.mScreenOrientation = pScreenOrientation; this.mResolutionPolicy = pResolutionPolicy; this.mCamera = pCamera; } // =========================================================== // Getter & Setter // =========================================================== public TouchOptions getTouchOptions() { return this.mTouchOptions; } public RenderOptions getRenderOptions() { return this.mRenderOptions; } public boolean isFullscreen() { return this.mFullscreen; } public ScreenOrientation getScreenOrientation() { return this.mScreenOrientation; } public IResolutionPolicy getResolutionPolicy() { return this.mResolutionPolicy; } public Camera getCamera() { return this.mCamera; } public int getUpdateThreadPriority() { return this.mUpdateThreadPriority; } /** * @param pUpdateThreadPriority Use constants from: {@link android.os.Process}. */ public void setUpdateThreadPriority(final int pUpdateThreadPriority) { this.mUpdateThreadPriority = pUpdateThreadPriority; } public boolean needsSound() { return this.mNeedsSound; } public EngineOptions setNeedsSound(final boolean pNeedsSound) { this.mNeedsSound = pNeedsSound; return this; } public boolean needsMusic() { return this.mNeedsMusic; } public EngineOptions setNeedsMusic(final boolean pNeedsMusic) { this.mNeedsMusic = pNeedsMusic; return this; } public WakeLockOptions getWakeLockOptions() { return this.mWakeLockOptions; } public EngineOptions setWakeLockOptions(final WakeLockOptions pWakeLockOptions) { this.mWakeLockOptions = pWakeLockOptions; return this; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== public static enum ScreenOrientation { // =========================================================== // Elements // =========================================================== LANDSCAPE, PORTRAIT; } }
Java
package org.anddev.andengine.engine.options.resolutionpolicy; import org.anddev.andengine.opengl.view.RenderSurfaceView; import android.view.View.MeasureSpec; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 11:23:00 - 29.03.2010 */ public class RatioResolutionPolicy extends BaseResolutionPolicy { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private final float mRatio; // =========================================================== // Constructors // =========================================================== public RatioResolutionPolicy(final float pRatio) { this.mRatio = pRatio; } public RatioResolutionPolicy(final float pWidthRatio, final float pHeightRatio) { this.mRatio = pWidthRatio / pHeightRatio; } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public void onMeasure(final RenderSurfaceView pRenderSurfaceView, final int pWidthMeasureSpec, final int pHeightMeasureSpec) { BaseResolutionPolicy.throwOnNotMeasureSpecEXACTLY(pWidthMeasureSpec, pHeightMeasureSpec); final int specWidth = MeasureSpec.getSize(pWidthMeasureSpec); final int specHeight = MeasureSpec.getSize(pHeightMeasureSpec); final float desiredRatio = this.mRatio; final float realRatio = (float)specWidth / specHeight; int measuredWidth; int measuredHeight; if(realRatio < desiredRatio) { measuredWidth = specWidth; measuredHeight = Math.round(measuredWidth / desiredRatio); } else { measuredHeight = specHeight; measuredWidth = Math.round(measuredHeight * desiredRatio); } pRenderSurfaceView.setMeasuredDimensionProxy(measuredWidth, measuredHeight); } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.engine.options.resolutionpolicy; import org.anddev.andengine.opengl.view.RenderSurfaceView; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 11:23:00 - 29.03.2010 */ public class FixedResolutionPolicy extends BaseResolutionPolicy { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private final int mWidth; private final int mHeight; // =========================================================== // Constructors // =========================================================== public FixedResolutionPolicy(final int pWidth, final int pHeight) { this.mWidth = pWidth; this.mHeight = pHeight; } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public void onMeasure(final RenderSurfaceView pRenderSurfaceView, final int pWidthMeasureSpec, final int pHeightMeasureSpec) { pRenderSurfaceView.setMeasuredDimensionProxy(this.mWidth, this.mHeight); } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.engine.options.resolutionpolicy; import org.anddev.andengine.opengl.view.RenderSurfaceView; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 11:02:35 - 29.03.2010 */ public interface IResolutionPolicy { // =========================================================== // Constants // =========================================================== // =========================================================== // Methods // =========================================================== public void onMeasure(final RenderSurfaceView pRenderSurfaceView, final int pWidthMeasureSpec, final int pHeightMeasureSpec); }
Java
package org.anddev.andengine.engine.options.resolutionpolicy; import org.anddev.andengine.opengl.view.RenderSurfaceView; import android.view.View.MeasureSpec; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 11:23:00 - 29.03.2010 */ public class RelativeResolutionPolicy extends BaseResolutionPolicy { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private final float mWidthScale; private final float mHeightScale; // =========================================================== // Constructors // =========================================================== public RelativeResolutionPolicy(final float pScale) { this(pScale, pScale); } public RelativeResolutionPolicy(final float pWidthScale, final float pHeightScale) { this.mWidthScale = pWidthScale; this.mHeightScale = pHeightScale; } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public void onMeasure(final RenderSurfaceView pRenderSurfaceView, final int pWidthMeasureSpec, final int pHeightMeasureSpec) { BaseResolutionPolicy.throwOnNotMeasureSpecEXACTLY(pWidthMeasureSpec, pHeightMeasureSpec); final int measuredWidth = (int)(MeasureSpec.getSize(pWidthMeasureSpec) * this.mWidthScale); final int measuredHeight = (int)(MeasureSpec.getSize(pHeightMeasureSpec) * this.mHeightScale); pRenderSurfaceView.setMeasuredDimensionProxy(measuredWidth, measuredHeight); } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.engine.options.resolutionpolicy; import org.anddev.andengine.opengl.view.RenderSurfaceView; import android.view.View.MeasureSpec; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 11:22:48 - 29.03.2010 */ public class FillResolutionPolicy extends BaseResolutionPolicy { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public void onMeasure(final RenderSurfaceView pRenderSurfaceView, final int pWidthMeasureSpec, final int pHeightMeasureSpec) { BaseResolutionPolicy.throwOnNotMeasureSpecEXACTLY(pWidthMeasureSpec, pHeightMeasureSpec); final int measuredWidth = MeasureSpec.getSize(pWidthMeasureSpec); final int measuredHeight = MeasureSpec.getSize(pHeightMeasureSpec); pRenderSurfaceView.setMeasuredDimensionProxy(measuredWidth, measuredHeight); } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.engine.options.resolutionpolicy; import android.view.View.MeasureSpec; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 22:46:43 - 06.10.2010 */ public abstract class BaseResolutionPolicy implements IResolutionPolicy { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== protected static void throwOnNotMeasureSpecEXACTLY(final int pWidthMeasureSpec, final int pHeightMeasureSpec) { final int specWidthMode = MeasureSpec.getMode(pWidthMeasureSpec); final int specHeightMode = MeasureSpec.getMode(pHeightMeasureSpec); if (specWidthMode != MeasureSpec.EXACTLY || specHeightMode != MeasureSpec.EXACTLY) { throw new IllegalStateException("This IResolutionPolicy requires MeasureSpec.EXACTLY ! That means "); } } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.engine.options; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 16:03:09 - 08.09.2010 */ public class TouchOptions { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private boolean mRunOnUpdateThread; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== public TouchOptions enableRunOnUpdateThread() { return this.setRunOnUpdateThread(true); } public TouchOptions disableRunOnUpdateThread() { return this.setRunOnUpdateThread(false); } public TouchOptions setRunOnUpdateThread(final boolean pRunOnUpdateThread) { this.mRunOnUpdateThread = pRunOnUpdateThread; return this; } /** * <u><b>Default:</b></u> <code>true</code> */ public boolean isRunOnUpdateThread() { return this.mRunOnUpdateThread; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.opengl.buffer; import javax.microedition.khronos.opengles.GL11; import org.anddev.andengine.opengl.util.FastFloatBuffer; import org.anddev.andengine.opengl.util.GLHelper; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 14:22:56 - 07.04.2010 */ public abstract class BufferObject { // =========================================================== // Constants // =========================================================== private static final int[] HARDWAREBUFFERID_FETCHER = new int[1]; // =========================================================== // Fields // =========================================================== protected final int[] mBufferData; private final int mDrawType; protected final FastFloatBuffer mFloatBuffer; private int mHardwareBufferID = -1; private boolean mLoadedToHardware; private boolean mHardwareBufferNeedsUpdate = true; private boolean mManaged; // =========================================================== // Constructors // =========================================================== /** * @param pCapacity * @param pDrawType * @param pManaged when passing <code>true</code> this {@link BufferObject} loads itself to the active {@link BufferObjectManager}. <b><u>WARNING:</u></b> When passing <code>false</code> one needs to take care of that by oneself! */ public BufferObject(final int pCapacity, final int pDrawType, final boolean pManaged) { this.mDrawType = pDrawType; this.mManaged = pManaged; this.mBufferData = new int[pCapacity]; this.mFloatBuffer = new FastFloatBuffer(pCapacity); if(pManaged) { this.loadToActiveBufferObjectManager(); } } // =========================================================== // Getter & Setter // =========================================================== public boolean isManaged() { return this.mManaged; } public void setManaged(final boolean pManaged) { this.mManaged = pManaged; } public FastFloatBuffer getFloatBuffer() { return this.mFloatBuffer; } public int getHardwareBufferID() { return this.mHardwareBufferID; } public boolean isLoadedToHardware() { return this.mLoadedToHardware; } void setLoadedToHardware(final boolean pLoadedToHardware) { this.mLoadedToHardware = pLoadedToHardware; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== public void setHardwareBufferNeedsUpdate(){ this.mHardwareBufferNeedsUpdate = true; } // =========================================================== // Methods // =========================================================== public void selectOnHardware(final GL11 pGL11) { final int hardwareBufferID = this.mHardwareBufferID; if(hardwareBufferID == -1) { return; } GLHelper.bindBuffer(pGL11, hardwareBufferID); // TODO Does this always need to be bound, or are just for buffers of the same 'type'(texture/vertex)? if(this.mHardwareBufferNeedsUpdate) { this.mHardwareBufferNeedsUpdate = false; synchronized(this) { GLHelper.bufferData(pGL11, this.mFloatBuffer.mByteBuffer, this.mDrawType); } } } public void loadToActiveBufferObjectManager() { BufferObjectManager.getActiveInstance().loadBufferObject(this); } public void unloadFromActiveBufferObjectManager() { BufferObjectManager.getActiveInstance().unloadBufferObject(this); } public void loadToHardware(final GL11 pGL11) { this.mHardwareBufferID = this.generateHardwareBufferID(pGL11); this.mLoadedToHardware = true; } public void unloadFromHardware(final GL11 pGL11) { this.deleteBufferOnHardware(pGL11); this.mHardwareBufferID = -1; this.mLoadedToHardware = false; } private void deleteBufferOnHardware(final GL11 pGL11) { GLHelper.deleteBuffer(pGL11, this.mHardwareBufferID); } private int generateHardwareBufferID(final GL11 pGL11) { pGL11.glGenBuffers(1, HARDWAREBUFFERID_FETCHER, 0); return HARDWAREBUFFERID_FETCHER[0]; } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.opengl.buffer; import java.util.ArrayList; import java.util.HashSet; import javax.microedition.khronos.opengles.GL11; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 17:48:46 - 08.03.2010 */ public class BufferObjectManager { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private static final HashSet<BufferObject> mBufferObjectsManaged = new HashSet<BufferObject>(); private static final ArrayList<BufferObject> mBufferObjectsLoaded = new ArrayList<BufferObject>(); private static final ArrayList<BufferObject> mBufferObjectsToBeLoaded = new ArrayList<BufferObject>(); private static final ArrayList<BufferObject> mBufferObjectsToBeUnloaded = new ArrayList<BufferObject>(); private static BufferObjectManager mActiveInstance = null; // =========================================================== // Constructors // =========================================================== public static BufferObjectManager getActiveInstance() { return BufferObjectManager.mActiveInstance; } public static void setActiveInstance(final BufferObjectManager pActiveInstance) { BufferObjectManager.mActiveInstance = pActiveInstance; } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== public synchronized void clear() { BufferObjectManager.mBufferObjectsToBeLoaded.clear(); BufferObjectManager.mBufferObjectsLoaded.clear(); BufferObjectManager.mBufferObjectsManaged.clear(); } public synchronized void loadBufferObject(final BufferObject pBufferObject) { if(pBufferObject == null) { return; } if(BufferObjectManager.mBufferObjectsManaged.contains(pBufferObject)) { /* Just make sure it doesn't get deleted. */ BufferObjectManager.mBufferObjectsToBeUnloaded.remove(pBufferObject); } else { BufferObjectManager.mBufferObjectsManaged.add(pBufferObject); BufferObjectManager.mBufferObjectsToBeLoaded.add(pBufferObject); } } public synchronized void unloadBufferObject(final BufferObject pBufferObject) { if(pBufferObject == null) { return; } if(BufferObjectManager.mBufferObjectsManaged.contains(pBufferObject)) { if(BufferObjectManager.mBufferObjectsLoaded.contains(pBufferObject)) { BufferObjectManager.mBufferObjectsToBeUnloaded.add(pBufferObject); } else if(BufferObjectManager.mBufferObjectsToBeLoaded.remove(pBufferObject)) { BufferObjectManager.mBufferObjectsManaged.remove(pBufferObject); } } } public void loadBufferObjects(final BufferObject... pBufferObjects) { for(int i = pBufferObjects.length - 1; i >= 0; i--) { this.loadBufferObject(pBufferObjects[i]); } } public void unloadBufferObjects(final BufferObject... pBufferObjects) { for(int i = pBufferObjects.length - 1; i >= 0; i--) { this.unloadBufferObject(pBufferObjects[i]); } } public synchronized void reloadBufferObjects() { final ArrayList<BufferObject> loadedBufferObjects = BufferObjectManager.mBufferObjectsLoaded; for(int i = loadedBufferObjects.size() - 1; i >= 0; i--) { loadedBufferObjects.get(i).setLoadedToHardware(false); } BufferObjectManager.mBufferObjectsToBeLoaded.addAll(loadedBufferObjects); loadedBufferObjects.clear(); } public synchronized void updateBufferObjects(final GL11 pGL11) { final HashSet<BufferObject> bufferObjectsManaged = BufferObjectManager.mBufferObjectsManaged; final ArrayList<BufferObject> bufferObjectsLoaded = BufferObjectManager.mBufferObjectsLoaded; final ArrayList<BufferObject> bufferObjectsToBeLoaded = BufferObjectManager.mBufferObjectsToBeLoaded; final ArrayList<BufferObject> bufferObjectsToBeUnloaded = BufferObjectManager.mBufferObjectsToBeUnloaded; /* First load pending BufferObjects. */ final int bufferObjectToBeLoadedCount = bufferObjectsToBeLoaded.size(); if(bufferObjectToBeLoadedCount > 0) { for(int i = bufferObjectToBeLoadedCount - 1; i >= 0; i--) { final BufferObject bufferObjectToBeLoaded = bufferObjectsToBeLoaded.get(i); if(!bufferObjectToBeLoaded.isLoadedToHardware()) { bufferObjectToBeLoaded.loadToHardware(pGL11); bufferObjectToBeLoaded.setHardwareBufferNeedsUpdate(); } bufferObjectsLoaded.add(bufferObjectToBeLoaded); } bufferObjectsToBeLoaded.clear(); } /* Then unload pending BufferObjects. */ final int bufferObjectsToBeUnloadedCount = bufferObjectsToBeUnloaded.size(); if(bufferObjectsToBeUnloadedCount > 0){ for(int i = bufferObjectsToBeUnloadedCount - 1; i >= 0; i--){ final BufferObject bufferObjectToBeUnloaded = bufferObjectsToBeUnloaded.remove(i); if(bufferObjectToBeUnloaded.isLoadedToHardware()){ bufferObjectToBeUnloaded.unloadFromHardware(pGL11); } bufferObjectsLoaded.remove(bufferObjectToBeUnloaded); bufferObjectsManaged.remove(bufferObjectToBeUnloaded); } } } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.opengl; import javax.microedition.khronos.opengles.GL10; import org.anddev.andengine.engine.camera.Camera; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 10:50:58 - 08.08.2010 */ public interface IDrawable { // =========================================================== // Final Fields // =========================================================== // =========================================================== // Methods // =========================================================== public void onDraw(final GL10 pGL, final Camera pCamera); }
Java
package org.anddev.andengine.opengl.view; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.opengles.GL10; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.opengl.util.GLHelper; import org.anddev.andengine.util.Debug; import android.content.Context; import android.util.AttributeSet; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 11:57:29 - 08.03.2010 */ public class RenderSurfaceView extends GLSurfaceView { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private Renderer mRenderer; // =========================================================== // Constructors // =========================================================== public RenderSurfaceView(final Context pContext) { super(pContext); } public RenderSurfaceView(final Context pContext, final AttributeSet pAttrs) { super(pContext, pAttrs); } public void setRenderer(final Engine pEngine) { this.setOnTouchListener(pEngine); this.mRenderer = new Renderer(pEngine); this.setRenderer(this.mRenderer); } /** * @see android.view.View#measure(int, int) */ @Override protected void onMeasure(final int pWidthMeasureSpec, final int pHeightMeasureSpec) { this.mRenderer.mEngine.getEngineOptions().getResolutionPolicy().onMeasure(this, pWidthMeasureSpec, pHeightMeasureSpec); } public void setMeasuredDimensionProxy(final int pMeasuredWidth, final int pMeasuredHeight) { this.setMeasuredDimension(pMeasuredWidth, pMeasuredHeight); } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 11:45:59 - 08.03.2010 */ public static class Renderer implements GLSurfaceView.Renderer { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private final Engine mEngine; // =========================================================== // Constructors // =========================================================== public Renderer(final Engine pEngine) { this.mEngine = pEngine; } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public void onSurfaceChanged(final GL10 pGL, final int pWidth, final int pHeight) { Debug.d("onSurfaceChanged: pWidth=" + pWidth + " pHeight=" + pHeight); this.mEngine.setSurfaceSize(pWidth, pHeight); pGL.glViewport(0, 0, pWidth, pHeight); pGL.glLoadIdentity(); } @Override public void onSurfaceCreated(final GL10 pGL, final EGLConfig pConfig) { Debug.d("onSurfaceCreated"); GLHelper.reset(pGL); GLHelper.setPerspectiveCorrectionHintFastest(pGL); // pGL.glEnable(GL10.GL_POLYGON_SMOOTH); // pGL.glHint(GL10.GL_POLYGON_SMOOTH_HINT, GL10.GL_NICEST); // pGL.glEnable(GL10.GL_LINE_SMOOTH); // pGL.glHint(GL10.GL_LINE_SMOOTH_HINT, GL10.GL_NICEST); // pGL.glEnable(GL10.GL_POINT_SMOOTH); // pGL.glHint(GL10.GL_POINT_SMOOTH_HINT, GL10.GL_NICEST); GLHelper.setShadeModelFlat(pGL); GLHelper.disableLightning(pGL); GLHelper.disableDither(pGL); GLHelper.disableDepthTest(pGL); GLHelper.disableMultisample(pGL); GLHelper.enableBlend(pGL); GLHelper.enableTextures(pGL); GLHelper.enableTexCoordArray(pGL); GLHelper.enableVertexArray(pGL); GLHelper.enableCulling(pGL); pGL.glFrontFace(GL10.GL_CCW); pGL.glCullFace(GL10.GL_BACK); GLHelper.enableExtensions(pGL, this.mEngine.getEngineOptions().getRenderOptions()); } @Override public void onDrawFrame(final GL10 pGL) { try { this.mEngine.onDrawFrame(pGL); } catch (final InterruptedException e) { Debug.e("GLThread interrupted!", e); } } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== } }
Java
package org.anddev.andengine.opengl.view; import javax.microedition.khronos.egl.EGL10; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.egl.EGLDisplay; /** * An interface for choosing an EGLConfig configuration from a list of * potential configurations. * <p> * This interface must be implemented by clients wishing to call * {@link GLSurfaceView#setEGLConfigChooser(EGLConfigChooser)} * * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 20:53:49 - 28.06.2010 */ public interface EGLConfigChooser { // =========================================================== // Final Fields // =========================================================== // =========================================================== // Methods // =========================================================== /** * Choose a configuration from the list. Implementors typically * implement this method by calling {@link EGL10#eglChooseConfig} and * iterating through the results. Please consult the EGL specification * available from The Khronos Group to learn how to call * eglChooseConfig. * * @param pEGL the EGL10 for the current display. * @param pEGLDisplay the current display. * @return the chosen configuration. */ public EGLConfig chooseConfig(final EGL10 pEGL, final EGLDisplay pEGLDisplay); }
Java
/** * */ package org.anddev.andengine.opengl.view; import javax.microedition.khronos.egl.EGL10; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.egl.EGLDisplay; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 20:42:29 - 28.06.2010 */ abstract class BaseConfigChooser implements EGLConfigChooser { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== protected final int[] mConfigSpec; // =========================================================== // Constructors // =========================================================== public BaseConfigChooser(final int[] pConfigSpec) { this.mConfigSpec = pConfigSpec; } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== abstract EGLConfig chooseConfig(final EGL10 pEGL, final EGLDisplay pEGLDisplay, final EGLConfig[] pEGLConfigs); @Override public EGLConfig chooseConfig(final EGL10 pEGL, final EGLDisplay pEGLDisplay) { final int[] num_config = new int[1]; pEGL.eglChooseConfig(pEGLDisplay, this.mConfigSpec, null, 0, num_config); final int numConfigs = num_config[0]; if(numConfigs <= 0) { throw new IllegalArgumentException("No configs match configSpec"); } final EGLConfig[] configs = new EGLConfig[numConfigs]; pEGL.eglChooseConfig(pEGLDisplay, this.mConfigSpec, configs, numConfigs, num_config); final EGLConfig config = this.chooseConfig(pEGL, pEGLDisplay, configs); if(config == null) { throw new IllegalArgumentException("No config chosen"); } return config; } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.opengl.view; import javax.microedition.khronos.opengles.GL; /** * An interface used to wrap a GL interface. * <p> * Typically used for implementing debugging and tracing on top of the default * GL interface. You would typically use this by creating your own class that * implemented all the GL methods by delegating to another GL instance. Then you * could add your own behavior before or after calling the delegate. All the * GLWrapper would do was instantiate and return the wrapper GL instance: * * <pre class="prettyprint"> * class MyGLWrapper implements GLWrapper { * GL wrap(GL gl) { * return new MyGLImplementation(gl); * } * static class MyGLImplementation implements GL,GL10,GL11,... { * ... * } * } * </pre> * * @see #setGLWrapper(GLWrapper) * * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 20:53:38 - 28.06.2010 */ public interface GLWrapper { // =========================================================== // Final Fields // =========================================================== // =========================================================== // Methods // =========================================================== /** * Wraps a gl interface in another gl interface. * * @param pGL a GL interface that is to be wrapped. * @return either the input argument or another GL object that wraps the * input argument. */ public GL wrap(final GL pGL); }
Java
package org.anddev.andengine.opengl.view; import javax.microedition.khronos.egl.EGL10; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.egl.EGLDisplay; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 20:54:06 - 28.06.2010 */ public class ComponentSizeChooser extends BaseConfigChooser { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private final int[] mValue; // Subclasses can adjust these values: protected int mRedSize; protected int mGreenSize; protected int mBlueSize; protected int mAlphaSize; protected int mDepthSize; protected int mStencilSize; // =========================================================== // Constructors // =========================================================== public ComponentSizeChooser(final int pRedSize, final int pGreenSize, final int pBlueSize, final int pAlphaSize, final int pDepthSize, final int pStencilSize) { super(new int[] { EGL10.EGL_RED_SIZE, pRedSize, EGL10.EGL_GREEN_SIZE, pGreenSize, EGL10.EGL_BLUE_SIZE, pBlueSize, EGL10.EGL_ALPHA_SIZE, pAlphaSize, EGL10.EGL_DEPTH_SIZE, pDepthSize, EGL10.EGL_STENCIL_SIZE, pStencilSize, EGL10.EGL_NONE }); this.mValue = new int[1]; this.mRedSize = pRedSize; this.mGreenSize = pGreenSize; this.mBlueSize = pBlueSize; this.mAlphaSize = pAlphaSize; this.mDepthSize = pDepthSize; this.mStencilSize = pStencilSize; } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public EGLConfig chooseConfig(final EGL10 pEGL, final EGLDisplay pEGLDisplay, final EGLConfig[] pEGLConfigs) { EGLConfig closestConfig = null; int closestDistance = 1000; for(final EGLConfig config : pEGLConfigs) { final int r = this.findConfigAttrib(pEGL, pEGLDisplay, config, EGL10.EGL_RED_SIZE, 0); final int g = this.findConfigAttrib(pEGL, pEGLDisplay, config, EGL10.EGL_GREEN_SIZE, 0); final int b = this.findConfigAttrib(pEGL, pEGLDisplay, config, EGL10.EGL_BLUE_SIZE, 0); final int a = this.findConfigAttrib(pEGL, pEGLDisplay, config, EGL10.EGL_ALPHA_SIZE, 0); final int d = this.findConfigAttrib(pEGL, pEGLDisplay, config, EGL10.EGL_DEPTH_SIZE, 0); final int s = this.findConfigAttrib(pEGL, pEGLDisplay, config, EGL10.EGL_STENCIL_SIZE, 0); final int distance = Math.abs(r - this.mRedSize) + Math.abs(g - this.mGreenSize) + Math.abs(b - this.mBlueSize) + Math.abs(a - this.mAlphaSize) + Math.abs(d - this.mDepthSize) + Math.abs(s - this.mStencilSize); if(distance < closestDistance) { closestDistance = distance; closestConfig = config; } } return closestConfig; } // =========================================================== // Methods // =========================================================== private int findConfigAttrib(final EGL10 pEGL, final EGLDisplay pEGLDisplay, final EGLConfig pEGLConfig, final int pAttribute, final int pDefaultValue) { if(pEGL.eglGetConfigAttrib(pEGLDisplay, pEGLConfig, pAttribute, this.mValue)) { return this.mValue[0]; } return pDefaultValue; } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.opengl.view; /** * This class will choose a supported surface as close to RGB565 as * possible, with or without a depth buffer. * * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 20:53:29 - 28.06.2010 */ class SimpleEGLConfigChooser extends ComponentSizeChooser { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== public SimpleEGLConfigChooser(final boolean pWithDepthBuffer) { super(4, 4, 4, 0, pWithDepthBuffer ? 16 : 0, 0); // Adjust target values. This way we'll accept a 4444 or // 555 buffer if there'MAGIC_CONSTANT no 565 buffer available. this.mRedSize = 5; this.mGreenSize = 6; this.mBlueSize = 5; } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
// ############################################################ // ############################################################ // // This class is a replacement for the original GLSurfaceView, due to issue: // http://code.google.com/p/android/issues/detail?id=2828 // // Reason: Two sequential Activities using a GLSurfaceView leads to a deadlock in the GLThread! // // ############################################################ // ############################################################ package org.anddev.andengine.opengl.view; import java.util.ArrayList; import java.util.concurrent.Semaphore; import javax.microedition.khronos.egl.EGL10; import javax.microedition.khronos.egl.EGL11; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.egl.EGLContext; import javax.microedition.khronos.egl.EGLDisplay; import javax.microedition.khronos.egl.EGLSurface; import javax.microedition.khronos.opengles.GL; import javax.microedition.khronos.opengles.GL10; import android.content.Context; import android.util.AttributeSet; import android.view.SurfaceHolder; import android.view.SurfaceView; /** * An implementation of SurfaceView that uses the dedicated surface for * displaying OpenGL rendering. * <p> * A GLSurfaceView provides the following features: * <p> * <ul> * <li>Manages a surface, which is a special piece of memory that can be * composited into the Android view system. * <li>Manages an EGL display, which enables OpenGL to render into a surface. * <li>Accepts a user-provided Renderer object that does the actual rendering. * <li>Renders on a dedicated thread to decouple rendering performance from the * UI thread. * <li>Supports both on-demand and continuous rendering. * <li>Optionally wraps, traces, and/or error-checks the renderer'MAGIC_CONSTANT OpenGL * calls. * </ul> * * <h3>Using GLSurfaceView</h3> * <p> * Typically you use GLSurfaceView by subclassing it and overriding one or more * of the View system input event methods. If your application does not need to * override event methods then GLSurfaceView can be used as-is. For the most * part GLSurfaceView behavior is customized by calling "set" methods rather * than by subclassing. For example, unlike a regular View, drawing is delegated * to a separate Renderer object which is registered with the GLSurfaceView * using the {@link #setRenderer(Renderer)} call. * <p> * <h3>Initializing GLSurfaceView</h3> * All you have to do to initialize a GLSurfaceView is call * {@link #setRenderer(Renderer)}. However, if desired, you can modify the * default behavior of GLSurfaceView by calling one or more of these methods * before calling setRenderer: * <ul> * <li>{@link #setDebugFlags(int)} * <li>{@link #setEGLConfigChooser(boolean)} * <li>{@link #setEGLConfigChooser(EGLConfigChooser)} * <li>{@link #setEGLConfigChooser(int, int, int, int, int, int)} * <li>{@link #setGLWrapper(GLWrapper)} * </ul> * <p> * <h4>Choosing an EGL Configuration</h4> * A given Android device may support multiple possible types of drawing * surfaces. The available surfaces may differ in how may channels of data are * present, as well as how many bits are allocated to each channel. Therefore, * the first thing GLSurfaceView has to do when starting to render is choose * what type of surface to use. * <p> * By default GLSurfaceView chooses an available surface that'MAGIC_CONSTANT closest to a * 16-bit R5G6B5 surface with a 16-bit depth buffer and no stencil. If you would * prefer a different surface (for example, if you do not need a depth buffer) * you can override the default behavior by calling one of the * setEGLConfigChooser methods. * <p> * <h4>Debug Behavior</h4> * You can optionally modify the behavior of GLSurfaceView by calling one or * more of the debugging methods {@link #setDebugFlags(int)}, and * {@link #setGLWrapper}. These methods may be called before and/or after * setRenderer, but typically they are called before setRenderer so that they * take effect immediately. * <p> * <h4>Setting a Renderer</h4> * Finally, you must call {@link #setRenderer} to register a {@link Renderer}. * The renderer is responsible for doing the actual OpenGL rendering. * <p> * <h3>Rendering Mode</h3> * Once the renderer is set, you can control whether the renderer draws * continuously or on-demand by calling {@link #setRenderMode}. The default is * continuous rendering. * <p> * <h3>Activity Life-cycle</h3> * A GLSurfaceView must be notified when the activity is paused and resumed. * GLSurfaceView clients are required to call {@link #onPause()} when the * activity pauses and {@link #onResume()} when the activity resumes. These * calls allow GLSurfaceView to pause and resume the rendering thread, and also * allow GLSurfaceView to release and recreate the OpenGL display. * <p> * <h3>Handling events</h3> * <p> * To handle an event you will typically subclass GLSurfaceView and override the * appropriate method, just as you would with any other View. However, when * handling the event, you may need to communicate with the Renderer object * that'MAGIC_CONSTANT running in the rendering thread. You can do this using any standard * Java cross-thread communication mechanism. In addition, one relatively easy * way to communicate with your renderer is to call * {@link #queueEvent(Runnable)}. For example: * * <pre class="prettyprint"> * class MyGLSurfaceView extends GLSurfaceView { * * private MyRenderer mMyRenderer; * * public void start() { * mMyRenderer = ...; * setRenderer(mMyRenderer); * } * * public boolean onKeyDown(int keyCode, KeyEvent event) { * if(keyCode == KeyEvent.KEYCODE_DPAD_CENTER) { * queueEvent(new Runnable() { * // This method will be called on the rendering * // thread: * public void run() { * mMyRenderer.handleDpadCenter(); * } * }); * return true; * } * return super.onKeyDown(keyCode, event); * } * } * </pre> * */ public class GLSurfaceView extends SurfaceView implements SurfaceHolder.Callback { // =========================================================== // Constants // =========================================================== /** * The renderer only renders when the surface is created, or when * {@link #requestRender} is called. * * @see #getRenderMode() * @see #setRenderMode(int) */ public final static int RENDERMODE_WHEN_DIRTY = 0; /** * The renderer is called continuously to re-render the scene. * * @see #getRenderMode() * @see #setRenderMode(int) * @see #requestRender() */ public final static int RENDERMODE_CONTINUOUSLY = 1; /** * Check glError() after every GL call and throw an exception if glError * indicates that an error has occurred. This can be used to help track down * which OpenGL ES call is causing an error. * * @see #getDebugFlags * @see #setDebugFlags */ public final static int DEBUG_CHECK_GL_ERROR = 1; /** * Log GL calls to the system log at "verbose" level with tag * "GLSurfaceView". * * @see #getDebugFlags * @see #setDebugFlags */ public final static int DEBUG_LOG_GL_CALLS = 2; private static final Semaphore sEglSemaphore = new Semaphore(1); // =========================================================== // Fields // =========================================================== private GLThread mGLThread; private EGLConfigChooser mEGLConfigChooser; private GLWrapper mGLWrapper; private int mDebugFlags; private int mRenderMode; private Renderer mRenderer; private int mSurfaceWidth; private int mSurfaceHeight; private boolean mHasSurface; // =========================================================== // Constructors // =========================================================== /** * Standard View constructor. In order to render something, you must call * {@link #setRenderer} to register a renderer. */ public GLSurfaceView(final Context context) { super(context); this.init(); } /** * Standard View constructor. In order to render something, you must call * {@link #setRenderer} to register a renderer. */ public GLSurfaceView(final Context context, final AttributeSet attrs) { super(context, attrs); this.init(); } private void init() { // Install a SurfaceHolder.Callback so we get notified when the // underlying surface is created and destroyed final SurfaceHolder holder = this.getHolder(); holder.addCallback(this); holder.setType(SurfaceHolder.SURFACE_TYPE_GPU); this.mRenderMode = RENDERMODE_CONTINUOUSLY; } // =========================================================== // Getter & Setter // =========================================================== /** * Set the glWrapper. If the glWrapper is not null, its * {@link GLWrapper#wrap(GL)} method is called whenever a surface is * created. A GLWrapper can be used to wrap the GL object that'MAGIC_CONSTANT passed to * the renderer. Wrapping a GL object enables examining and modifying the * behavior of the GL calls made by the renderer. * <p> * Wrapping is typically used for debugging purposes. * <p> * The default value is null. * * @param glWrapper * the new GLWrapper */ public void setGLWrapper(final GLWrapper glWrapper) { this.mGLWrapper = glWrapper; } /** * Set the debug flags to a new value. The value is constructed by * OR-together zero or more of the DEBUG_CHECK_* constants. The debug flags * take effect whenever a surface is created. The default value is zero. * * @param debugFlags * the new debug flags * @see #DEBUG_CHECK_GL_ERROR * @see #DEBUG_LOG_GL_CALLS */ public void setDebugFlags(final int debugFlags) { this.mDebugFlags = debugFlags; } /** * Get the current value of the debug flags. * * @return the current value of the debug flags. */ public int getDebugFlags() { return this.mDebugFlags; } /** * Set the renderer associated with this view. Also starts the thread that * will call the renderer, which in turn causes the rendering to start. * <p> * This method should be called once and only once in the life-cycle of a * GLSurfaceView. * <p> * The following GLSurfaceView methods can only be called <em>before</em> * setRenderer is called: * <ul> * <li>{@link #setEGLConfigChooser(boolean)} * <li>{@link #setEGLConfigChooser(EGLConfigChooser)} * <li>{@link #setEGLConfigChooser(int, int, int, int, int, int)} * </ul> * <p> * The following GLSurfaceView methods can only be called <em>after</em> * setRenderer is called: * <ul> * <li>{@link #getRenderMode()} * <li>{@link #onPause()} * <li>{@link #onResume()} * <li>{@link #queueEvent(Runnable)} * <li>{@link #requestRender()} * <li>{@link #setRenderMode(int)} * </ul> * * @param renderer * the renderer to use to perform OpenGL drawing. */ public void setRenderer(final Renderer renderer) { if(this.mRenderer != null) { throw new IllegalStateException("setRenderer has already been called for this instance."); } this.mRenderer = renderer; } /** * Install a custom EGLConfigChooser. * <p> * If this method is called, it must be called before * {@link #setRenderer(Renderer)} is called. * <p> * If no setEGLConfigChooser method is called, then by default the view will * choose a config as close to 16-bit RGB as possible, with a depth buffer * as close to 16 bits as possible. * * @param configChooser */ public void setEGLConfigChooser(final EGLConfigChooser configChooser) { if(this.mRenderer != null) { throw new IllegalStateException("setRenderer has already been called for this instance."); } this.mEGLConfigChooser = configChooser; } /** * Install a config chooser which will choose a config as close to 16-bit * RGB as possible, with or without an optional depth buffer as close to * 16-bits as possible. * <p> * If this method is called, it must be called before * {@link #setRenderer(Renderer)} is called. * <p> * If no setEGLConfigChooser method is called, then by default the view will * choose a config as close to 16-bit RGB as possible, with a depth buffer * as close to 16 bits as possible. * * @param needDepth */ public void setEGLConfigChooser(final boolean needDepth) { this.setEGLConfigChooser(new SimpleEGLConfigChooser(needDepth)); } /** * Install a config chooser which will choose a config with at least the * specified component sizes, and as close to the specified component sizes * as possible. * <p> * If this method is called, it must be called before * {@link #setRenderer(Renderer)} is called. * <p> * If no setEGLConfigChooser method is called, then by default the view will * choose a config as close to 16-bit RGB as possible, with a depth buffer * as close to 16 bits as possible. * */ public void setEGLConfigChooser(final int redSize, final int greenSize, final int blueSize, final int alphaSize, final int depthSize, final int stencilSize) { this.setEGLConfigChooser(new ComponentSizeChooser(redSize, greenSize, blueSize, alphaSize, depthSize, stencilSize)); } /** * Set the rendering mode. When renderMode is RENDERMODE_CONTINUOUSLY, the * renderer is called repeatedly to re-render the scene. When renderMode is * RENDERMODE_WHEN_DIRTY, the renderer only rendered when the surface is * created, or when {@link #requestRender} is called. Defaults to * RENDERMODE_CONTINUOUSLY. * <p> * Using RENDERMODE_WHEN_DIRTY can improve battery life and overall system * performance by allowing the GPU and CPU to idle when the view does not * need to be updated. * <p> * This method can only be called after {@link #setRenderer(Renderer)} * * @param renderMode * one of the RENDERMODE_X constants * @see #RENDERMODE_CONTINUOUSLY * @see #RENDERMODE_WHEN_DIRTY */ public void setRenderMode(final int renderMode) { this.mRenderMode = renderMode; if(this.mGLThread != null) { this.mGLThread.setRenderMode(renderMode); } } /** * Get the current rendering mode. May be called from any thread. Must not * be called before a renderer has been set. * * @return the current rendering mode. * @see #RENDERMODE_CONTINUOUSLY * @see #RENDERMODE_WHEN_DIRTY */ public int getRenderMode() { return this.mRenderMode; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== /** * Request that the renderer render a frame. This method is typically used * when the render mode has been set to {@link #RENDERMODE_WHEN_DIRTY}, so * that frames are only rendered on demand. May be called from any thread. * Must be called after onResume() and before onPause(). */ public void requestRender() { this.mGLThread.requestRender(); } /** * This method is part of the SurfaceHolder.Callback interface, and is not * normally called or subclassed by clients of GLSurfaceView. */ @Override public void surfaceCreated(final SurfaceHolder holder) { if(this.mGLThread != null) { this.mGLThread.surfaceCreated(); } this.mHasSurface = true; } /** * This method is part of the SurfaceHolder.Callback interface, and is not * normally called or subclassed by clients of GLSurfaceView. */ @Override public void surfaceDestroyed(final SurfaceHolder holder) { // Surface will be destroyed when we return if(this.mGLThread != null) { this.mGLThread.surfaceDestroyed(); } this.mHasSurface = false; } /** * This method is part of the SurfaceHolder.Callback interface, and is not * normally called or subclassed by clients of GLSurfaceView. */ @Override public void surfaceChanged(final SurfaceHolder holder, final int format, final int w, final int h) { if(this.mGLThread != null) { this.mGLThread.onWindowResize(w, h); } this.mSurfaceWidth = w; this.mSurfaceHeight = h; } /** * Inform the view that the activity is paused. The owner of this view must * call this method when the activity is paused. Calling this method will * pause the rendering thread. Must not be called before a renderer has been * set. */ public void onPause() { this.mGLThread.onPause(); this.mGLThread.requestExitAndWait(); this.mGLThread = null; } /** * Inform the view that the activity is resumed. The owner of this view must * call this method when the activity is resumed. Calling this method will * recreate the OpenGL display and resume the rendering thread. Must not be * called before a renderer has been set. */ public void onResume() { if(this.mEGLConfigChooser == null) { this.mEGLConfigChooser = new SimpleEGLConfigChooser(true); } this.mGLThread = new GLThread(this.mRenderer); this.mGLThread.start(); this.mGLThread.setRenderMode(this.mRenderMode); if(this.mHasSurface) { this.mGLThread.surfaceCreated(); } if(this.mSurfaceWidth > 0 && this.mSurfaceHeight > 0) { this.mGLThread.onWindowResize(this.mSurfaceWidth, this.mSurfaceHeight); } this.mGLThread.onResume(); } /** * Queue a runnable to be run on the GL rendering thread. This can be used * to communicate with the Renderer on the rendering thread. Must be called * after onResume() and before onPause(). * * @param r * the runnable to be run on the GL rendering thread. */ public void queueEvent(final Runnable r) { if(this.mGLThread != null) { this.mGLThread.queueEvent(r); } } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== /** * A generic GL Thread. Takes care of initializing EGL and GL. Delegates to * a Renderer instance to do the actual drawing. Can be configured to render * continuously or on request. * */ class GLThread extends Thread { GLThread(final Renderer renderer) { super(); this.mDone = false; this.mWidth = 0; this.mHeight = 0; this.mRequestRender = true; this.mRenderMode = RENDERMODE_CONTINUOUSLY; this.mRenderer = renderer; this.mSizeChanged = true; this.setName("GLThread"); } @Override public void run() { /* * When the android framework launches a second instance of an * activity, the new instance'MAGIC_CONSTANT onCreate() method may be called * before the first instance returns from onDestroy(). * * This semaphore ensures that only one instance at a time accesses * EGL. */ try { try { sEglSemaphore.acquire(); } catch (final InterruptedException e) { return; } this.guardedRun(); } catch (final InterruptedException e) { // fall thru and exit normally } finally { sEglSemaphore.release(); } } private void guardedRun() throws InterruptedException { this.mEglHelper = new EglHelper(); this.mEglHelper.start(); GL10 gl = null; boolean tellRendererSurfaceCreated = true; boolean tellRendererSurfaceChanged = true; /* * This is our main activity thread'MAGIC_CONSTANT loop, we go until asked to * quit. */ while(!this.mDone) { /* * Update the asynchronous state (window size) */ int w, h; boolean changed; boolean needStart = false; synchronized (this) { Runnable r; while((r = this.getEvent()) != null) { r.run(); } if(this.mPaused) { this.mEglHelper.finish(); needStart = true; } while(this.needToWait()) { this.wait(); } if(this.mDone) { break; } changed = this.mSizeChanged; w = this.mWidth; h = this.mHeight; this.mSizeChanged = false; this.mRequestRender = false; } if(needStart) { this.mEglHelper.start(); tellRendererSurfaceCreated = true; changed = true; } if(changed) { gl = (GL10) this.mEglHelper.createSurface(GLSurfaceView.this.getHolder()); tellRendererSurfaceChanged = true; } if(tellRendererSurfaceCreated) { this.mRenderer.onSurfaceCreated(gl, this.mEglHelper.mEglConfig); tellRendererSurfaceCreated = false; } if(tellRendererSurfaceChanged) { this.mRenderer.onSurfaceChanged(gl, w, h); tellRendererSurfaceChanged = false; } if((w > 0) && (h > 0)) { /* draw a frame here */ this.mRenderer.onDrawFrame(gl); /* * Once we're done with GL, we need to call swapBuffers() to * instruct the system to display the rendered frame */ this.mEglHelper.swap(); } } /* * clean-up everything... */ this.mEglHelper.finish(); } private boolean needToWait() { if(this.mDone) { return false; } if(this.mPaused || (!this.mHasSurface)) { return true; } if((this.mWidth > 0) && (this.mHeight > 0) && (this.mRequestRender || (this.mRenderMode == RENDERMODE_CONTINUOUSLY))) { return false; } return true; } public void setRenderMode(final int renderMode) { if(!((RENDERMODE_WHEN_DIRTY <= renderMode) && (renderMode <= RENDERMODE_CONTINUOUSLY))) { throw new IllegalArgumentException("renderMode"); } synchronized (this) { this.mRenderMode = renderMode; if(renderMode == RENDERMODE_CONTINUOUSLY) { this.notify(); } } } public int getRenderMode() { synchronized (this) { return this.mRenderMode; } } public void requestRender() { synchronized (this) { this.mRequestRender = true; this.notify(); } } public void surfaceCreated() { synchronized (this) { this.mHasSurface = true; this.notify(); } } public void surfaceDestroyed() { synchronized (this) { this.mHasSurface = false; this.notify(); } } public void onPause() { synchronized (this) { this.mPaused = true; } } public void onResume() { synchronized (this) { this.mPaused = false; this.notify(); } } public void onWindowResize(final int w, final int h) { synchronized (this) { this.mWidth = w; this.mHeight = h; this.mSizeChanged = true; this.notify(); } } public void requestExitAndWait() { // don't call this from GLThread thread or it is a guaranteed // deadlock! synchronized (this) { this.mDone = true; this.notify(); } try { this.join(); } catch (final InterruptedException ex) { Thread.currentThread().interrupt(); } } /** * Queue an "event" to be run on the GL rendering thread. * * @param r * the runnable to be run on the GL rendering thread. */ public void queueEvent(final Runnable r) { synchronized (this) { this.mEventQueue.add(r); } } private Runnable getEvent() { synchronized (this) { if(this.mEventQueue.size() > 0) { return this.mEventQueue.remove(0); } } return null; } private boolean mDone; private boolean mPaused; private boolean mHasSurface; private int mWidth; private int mHeight; private int mRenderMode; private boolean mRequestRender; private final Renderer mRenderer; private final ArrayList<Runnable> mEventQueue = new ArrayList<Runnable>(); private EglHelper mEglHelper; private boolean mSizeChanged; } /** * An EGL helper class. */ class EglHelper { public EglHelper() { } /** * Initialize EGL for a given configuration spec. * * @param configSpec */ public void start() { /* * Get an EGL instance */ this.mEgl = (EGL10) EGLContext.getEGL(); /* * Get to the default display. */ this.mEglDisplay = this.mEgl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY); /* * We can now initialize EGL for that display */ final int[] version = new int[2]; this.mEgl.eglInitialize(this.mEglDisplay, version); this.mEglConfig = GLSurfaceView.this.mEGLConfigChooser.chooseConfig(this.mEgl, this.mEglDisplay); /* * Create an OpenGL ES context. This must be done only once, an * OpenGL context is a somewhat heavy object. */ this.mEglContext = this.mEgl.eglCreateContext(this.mEglDisplay, this.mEglConfig, EGL10.EGL_NO_CONTEXT, null); this.mEglSurface = null; } /* * React to the creation of a new surface by creating and returning an * OpenGL interface that renders to that surface. */ public GL createSurface(final SurfaceHolder holder) { /* * The window size has changed, so we need to create a new surface. */ if(this.mEglSurface != null) { /* * Unbind and destroy the old EGL surface, if there is one. */ this.mEgl.eglMakeCurrent(this.mEglDisplay, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_CONTEXT); this.mEgl.eglDestroySurface(this.mEglDisplay, this.mEglSurface); } /* * Create an EGL surface we can render into. */ this.mEglSurface = this.mEgl.eglCreateWindowSurface(this.mEglDisplay, this.mEglConfig, holder, null); /* * Before we can issue GL commands, we need to make sure the context * is current and bound to a surface. */ this.mEgl.eglMakeCurrent(this.mEglDisplay, this.mEglSurface, this.mEglSurface, this.mEglContext); GL gl = this.mEglContext.getGL(); if(GLSurfaceView.this.mGLWrapper != null) { gl = GLSurfaceView.this.mGLWrapper.wrap(gl); } /* Debugging disabled */ /* * if ((mDebugFlags & (DEBUG_CHECK_GL_ERROR | DEBUG_LOG_GL_CALLS))!= * 0) { int configFlags = 0; Writer log = null; if ((mDebugFlags & * DEBUG_CHECK_GL_ERROR) != 0) { configFlags |= * GLDebugHelper.CONFIG_CHECK_GL_ERROR; } if ((mDebugFlags & * DEBUG_LOG_GL_CALLS) != 0) { log = new LogWriter(); } gl = * GLDebugHelper.wrap(gl, configFlags, log); } */ return gl; } /** * Display the current render surface. * * @return false if the context has been lost. */ public boolean swap() { this.mEgl.eglSwapBuffers(this.mEglDisplay, this.mEglSurface); /* * Always check for EGL_CONTEXT_LOST, which means the context and * all associated data were lost (For instance because the device * went to sleep). We need to sleep until we get a new surface. */ return this.mEgl.eglGetError() != EGL11.EGL_CONTEXT_LOST; } public void finish() { if(this.mEglSurface != null) { this.mEgl.eglMakeCurrent(this.mEglDisplay, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_CONTEXT); this.mEgl.eglDestroySurface(this.mEglDisplay, this.mEglSurface); this.mEglSurface = null; } if(this.mEglContext != null) { this.mEgl.eglDestroyContext(this.mEglDisplay, this.mEglContext); this.mEglContext = null; } if(this.mEglDisplay != null) { this.mEgl.eglTerminate(this.mEglDisplay); this.mEglDisplay = null; } } EGL10 mEgl; EGLDisplay mEglDisplay; EGLSurface mEglSurface; EGLConfig mEglConfig; EGLContext mEglContext; } /** * A generic renderer interface. * <p> * The renderer is responsible for making OpenGL calls to render a frame. * <p> * GLSurfaceView clients typically create their own classes that implement * this interface, and then call {@link GLSurfaceView#setRenderer} to * register the renderer with the GLSurfaceView. * <p> * <h3>Threading</h3> * The renderer will be called on a separate thread, so that rendering * performance is decoupled from the UI thread. Clients typically need to * communicate with the renderer from the UI thread, because that'MAGIC_CONSTANT where * input events are received. Clients can communicate using any of the * standard Java techniques for cross-thread communication, or they can use * the {@link GLSurfaceView#queueEvent(Runnable)} convenience method. * <p> * <h3>EGL Context Lost</h3> * There are situations where the EGL rendering context will be lost. This * typically happens when device wakes up after going to sleep. When the EGL * context is lost, all OpenGL resources (such as textures) that are * associated with that context will be automatically deleted. In order to * keep rendering correctly, a renderer must recreate any lost resources * that it still needs. The {@link #onSurfaceCreated(GL10, EGLConfig)} * method is a convenient place to do this. * * * @see #setRenderer(Renderer) */ public interface Renderer { /** * Called when the surface is created or recreated. * <p> * Called when the rendering thread starts and whenever the EGL context * is lost. The context will typically be lost when the Android device * awakes after going to sleep. * <p> * Since this method is called at the beginning of rendering, as well as * every time the EGL context is lost, this method is a convenient place * to put code to create resources that need to be created when the * rendering starts, and that need to be recreated when the EGL context * is lost. Textures are an example of a resource that you might want to * create here. * <p> * Note that when the EGL context is lost, all OpenGL resources * associated with that context will be automatically deleted. You do * not need to call the corresponding "glDelete" methods such as * glDeleteTextures to manually delete these lost resources. * <p> * * @param gl * the GL interface. Use <code>instanceof</code> to test if * the interface supports GL11 or higher interfaces. * @param config * the EGLConfig of the created surface. Can be used to * create matching pbuffers. */ void onSurfaceCreated(GL10 gl, EGLConfig config); /** * Called when the surface changed size. * <p> * Called after the surface is created and whenever the OpenGL ES * surface size changes. * <p> * Typically you will set your viewport here. If your camera is fixed * then you could also set your projection matrix here: * * <pre class="prettyprint"> * void onSurfaceChanged(GL10 gl, int width, int height) { * gl.glViewport(0, 0, width, height); * // for a fixed camera, set the projection too * float ratio = (float) width / height; * gl.glMatrixMode(GL10.GL_PROJECTION); * gl.glLoadIdentity(); * gl.glFrustumf(-ratio, ratio, -1, 1, 1, 10); * } * </pre> * * @param gl * the GL interface. Use <code>instanceof</code> to test if * the interface supports GL11 or higher interfaces. * @param width * @param height */ void onSurfaceChanged(GL10 gl, int width, int height); /** * Called to draw the current frame. * <p> * This method is responsible for drawing the current frame. * <p> * The implementation of this method typically looks like this: * * <pre class="prettyprint"> * void onDrawFrame(GL10 gl) { * gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT); * //... other gl calls to render the scene ... * } * </pre> * * @param gl * the GL interface. Use <code>instanceof</code> to test if * the interface supports GL11 or higher interfaces. */ void onDrawFrame(GL10 gl); } }
Java
/** * */ package org.anddev.andengine.opengl.view; import java.io.Writer; import android.util.Log; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 20:42:02 - 28.06.2010 */ class LogWriter extends Writer { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private final StringBuilder mBuilder = new StringBuilder(); // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public void close() { this.flushBuilder(); } @Override public void flush() { this.flushBuilder(); } @Override public void write(final char[] buf, final int offset, final int count) { for(int i = 0; i < count; i++) { final char c = buf[offset + i]; if(c == '\n') { this.flushBuilder(); } else { this.mBuilder.append(c); } } } // =========================================================== // Methods // =========================================================== private void flushBuilder() { if(this.mBuilder.length() > 0) { Log.v("GLSurfaceView", this.mBuilder.toString()); this.mBuilder.delete(0, this.mBuilder.length()); } } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.opengl.util; import java.nio.Buffer; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.IntBuffer; import javax.microedition.khronos.opengles.GL10; import javax.microedition.khronos.opengles.GL11; import org.anddev.andengine.engine.options.RenderOptions; import org.anddev.andengine.opengl.texture.Texture.PixelFormat; import org.anddev.andengine.util.Debug; import android.graphics.Bitmap; import android.opengl.GLException; import android.opengl.GLUtils; import android.os.Build; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 18:00:43 - 08.03.2010 */ public class GLHelper { // =========================================================== // Constants // =========================================================== public static final int BYTES_PER_FLOAT = 4; public static final int BYTES_PER_PIXEL_RGBA = 4; private static final boolean IS_LITTLE_ENDIAN = (ByteOrder.nativeOrder() == ByteOrder.LITTLE_ENDIAN); private static final int[] HARDWARETEXTUREID_CONTAINER = new int[1]; private static final int[] HARDWAREBUFFERID_CONTAINER = new int[1]; // =========================================================== // Fields // =========================================================== private static int sCurrentHardwareBufferID = -1; private static int sCurrentHardwareTextureID = -1; private static int sCurrentMatrix = -1; private static int sCurrentSourceBlendMode = -1; private static int sCurrentDestinationBlendMode = -1; private static FastFloatBuffer sCurrentVertexFloatBuffer = null; private static FastFloatBuffer sCurrentTextureFloatBuffer = null; private static boolean sEnableDither = true; private static boolean sEnableLightning = true; private static boolean sEnableDepthTest = true; private static boolean sEnableMultisample = true; private static boolean sEnableScissorTest = false; private static boolean sEnableBlend = false; private static boolean sEnableCulling = false; private static boolean sEnableTextures = false; private static boolean sEnableTexCoordArray = false; private static boolean sEnableVertexArray = false; private static float sLineWidth = 1; private static float sRed = -1; private static float sGreen = -1; private static float sBlue = -1; private static float sAlpha = -1; public static boolean EXTENSIONS_VERTEXBUFFEROBJECTS = false; public static boolean EXTENSIONS_DRAWTEXTURE = false; public static boolean EXTENSIONS_TEXTURE_NON_POWER_OF_TWO = false; // =========================================================== // Methods // =========================================================== public static void reset(final GL10 pGL) { GLHelper.sCurrentHardwareBufferID = -1; GLHelper.sCurrentHardwareTextureID = -1; GLHelper.sCurrentMatrix = -1; GLHelper.sCurrentSourceBlendMode = -1; GLHelper.sCurrentDestinationBlendMode = -1; GLHelper.sCurrentVertexFloatBuffer = null; GLHelper.sCurrentTextureFloatBuffer = null; GLHelper.enableDither(pGL); GLHelper.enableLightning(pGL); GLHelper.enableDepthTest(pGL); GLHelper.enableMultisample(pGL); GLHelper.disableBlend(pGL); GLHelper.disableCulling(pGL); GLHelper.disableTextures(pGL); GLHelper.disableTexCoordArray(pGL); GLHelper.disableVertexArray(pGL); GLHelper.sLineWidth = 1; GLHelper.sRed = -1; GLHelper.sGreen = -1; GLHelper.sBlue = -1; GLHelper.sAlpha = -1; GLHelper.EXTENSIONS_VERTEXBUFFEROBJECTS = false; GLHelper.EXTENSIONS_DRAWTEXTURE = false; GLHelper.EXTENSIONS_TEXTURE_NON_POWER_OF_TWO = false; } public static void enableExtensions(final GL10 pGL, final RenderOptions pRenderOptions) { final String version = pGL.glGetString(GL10.GL_VERSION); final String renderer = pGL.glGetString(GL10.GL_RENDERER); final String extensions = pGL.glGetString(GL10.GL_EXTENSIONS); Debug.d("RENDERER: " + renderer); Debug.d("VERSION: " + version); Debug.d("EXTENSIONS: " + extensions); final boolean isOpenGL10 = version.contains("1.0"); final boolean isOpenGL2X = version.contains("2."); final boolean isSoftwareRenderer = renderer.contains("PixelFlinger"); final boolean isVBOCapable = extensions.contains("_vertex_buffer_object"); final boolean isDrawTextureCapable = extensions.contains("draw_texture"); final boolean isTextureNonPowerOfTwoCapable = extensions.contains("texture_npot"); GLHelper.EXTENSIONS_VERTEXBUFFEROBJECTS = !pRenderOptions.isDisableExtensionVertexBufferObjects() && !isSoftwareRenderer && (isVBOCapable || !isOpenGL10); GLHelper.EXTENSIONS_DRAWTEXTURE = !pRenderOptions.isDisableExtensionVertexBufferObjects() && (isDrawTextureCapable || !isOpenGL10); GLHelper.EXTENSIONS_TEXTURE_NON_POWER_OF_TWO = isTextureNonPowerOfTwoCapable || isOpenGL2X; GLHelper.hackBrokenDevices(); Debug.d("EXTENSIONS_VERXTEXBUFFEROBJECTS = " + GLHelper.EXTENSIONS_VERTEXBUFFEROBJECTS); Debug.d("EXTENSIONS_DRAWTEXTURE = " + GLHelper.EXTENSIONS_DRAWTEXTURE); } private static void hackBrokenDevices() { if (Build.PRODUCT.contains("morrison")) { // This is the Motorola Cliq. This device LIES and says it supports // VBOs, which it actually does not (or, more likely, the extensions string // is correct and the GL JNI glue is broken). GLHelper.EXTENSIONS_VERTEXBUFFEROBJECTS = false; // TODO: if Motorola fixes this, I should switch to using the fingerprint // (blur/morrison/morrison/morrison:1.5/CUPCAKE/091007:user/ota-rel-keys,release-keys) // instead of the product name so that newer versions use VBOs } } public static void setColor(final GL10 pGL, final float pRed, final float pGreen, final float pBlue, final float pAlpha) { if(pAlpha != GLHelper.sAlpha || pRed != GLHelper.sRed || pGreen != GLHelper.sGreen || pBlue != GLHelper.sBlue) { GLHelper.sAlpha = pAlpha; GLHelper.sRed = pRed; GLHelper.sGreen = pGreen; GLHelper.sBlue = pBlue; pGL.glColor4f(pRed, pGreen, pBlue, pAlpha); } } public static void enableVertexArray(final GL10 pGL) { if(!GLHelper.sEnableVertexArray) { GLHelper.sEnableVertexArray = true; pGL.glEnableClientState(GL10.GL_VERTEX_ARRAY); } } public static void disableVertexArray(final GL10 pGL) { if(GLHelper.sEnableVertexArray) { GLHelper.sEnableVertexArray = false; pGL.glDisableClientState(GL10.GL_VERTEX_ARRAY); } } public static void enableTexCoordArray(final GL10 pGL) { if(!GLHelper.sEnableTexCoordArray) { GLHelper.sEnableTexCoordArray = true; pGL.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY); } } public static void disableTexCoordArray(final GL10 pGL) { if(GLHelper.sEnableTexCoordArray) { GLHelper.sEnableTexCoordArray = false; pGL.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY); } } public static void enableScissorTest(final GL10 pGL) { if(!GLHelper.sEnableScissorTest) { GLHelper.sEnableScissorTest = true; pGL.glEnable(GL10.GL_SCISSOR_TEST); } } public static void disableScissorTest(final GL10 pGL) { if(GLHelper.sEnableScissorTest) { GLHelper.sEnableScissorTest = false; pGL.glDisable(GL10.GL_SCISSOR_TEST); } } public static void enableBlend(final GL10 pGL) { if(!GLHelper.sEnableBlend) { GLHelper.sEnableBlend = true; pGL.glEnable(GL10.GL_BLEND); } } public static void disableBlend(final GL10 pGL) { if(GLHelper.sEnableBlend) { GLHelper.sEnableBlend = false; pGL.glDisable(GL10.GL_BLEND); } } public static void enableCulling(final GL10 pGL) { if(!GLHelper.sEnableCulling) { GLHelper.sEnableCulling = true; pGL.glEnable(GL10.GL_CULL_FACE); } } public static void disableCulling(final GL10 pGL) { if(GLHelper.sEnableCulling) { GLHelper.sEnableCulling = false; pGL.glDisable(GL10.GL_CULL_FACE); } } public static void enableTextures(final GL10 pGL) { if(!GLHelper.sEnableTextures) { GLHelper.sEnableTextures = true; pGL.glEnable(GL10.GL_TEXTURE_2D); } } public static void disableTextures(final GL10 pGL) { if(GLHelper.sEnableTextures) { GLHelper.sEnableTextures = false; pGL.glDisable(GL10.GL_TEXTURE_2D); } } public static void enableLightning(final GL10 pGL) { if(!GLHelper.sEnableLightning) { GLHelper.sEnableLightning = true; pGL.glEnable(GL10.GL_LIGHTING); } } public static void disableLightning(final GL10 pGL) { if(GLHelper.sEnableLightning) { GLHelper.sEnableLightning = false; pGL.glDisable(GL10.GL_LIGHTING); } } public static void enableDither(final GL10 pGL) { if(!GLHelper.sEnableDither) { GLHelper.sEnableDither = true; pGL.glEnable(GL10.GL_DITHER); } } public static void disableDither(final GL10 pGL) { if(GLHelper.sEnableDither) { GLHelper.sEnableDither = false; pGL.glDisable(GL10.GL_DITHER); } } public static void enableDepthTest(final GL10 pGL) { if(!GLHelper.sEnableDepthTest) { GLHelper.sEnableDepthTest = true; pGL.glEnable(GL10.GL_DEPTH_TEST); } } public static void disableDepthTest(final GL10 pGL) { if(GLHelper.sEnableDepthTest) { GLHelper.sEnableDepthTest = false; pGL.glDisable(GL10.GL_DEPTH_TEST); } } public static void enableMultisample(final GL10 pGL) { if(!GLHelper.sEnableMultisample) { GLHelper.sEnableMultisample = true; pGL.glEnable(GL10.GL_MULTISAMPLE); } } public static void disableMultisample(final GL10 pGL) { if(GLHelper.sEnableMultisample) { GLHelper.sEnableMultisample = false; pGL.glDisable(GL10.GL_MULTISAMPLE); } } public static void bindBuffer(final GL11 pGL11, final int pHardwareBufferID) { /* Reduce unnecessary buffer switching calls. */ if(GLHelper.sCurrentHardwareBufferID != pHardwareBufferID) { GLHelper.sCurrentHardwareBufferID = pHardwareBufferID; pGL11.glBindBuffer(GL11.GL_ARRAY_BUFFER, pHardwareBufferID); } } public static void deleteBuffer(final GL11 pGL11, final int pHardwareBufferID) { GLHelper.HARDWAREBUFFERID_CONTAINER[0] = pHardwareBufferID; pGL11.glDeleteBuffers(1, GLHelper.HARDWAREBUFFERID_CONTAINER, 0); } /** * @see {@link GLHelper#forceBindTexture(GL10, int)} * @param pGL * @param pHardwareTextureID */ public static void bindTexture(final GL10 pGL, final int pHardwareTextureID) { /* Reduce unnecessary texture switching calls. */ if(GLHelper.sCurrentHardwareTextureID != pHardwareTextureID) { GLHelper.sCurrentHardwareTextureID = pHardwareTextureID; pGL.glBindTexture(GL10.GL_TEXTURE_2D, pHardwareTextureID); } } /** * @see {@link GLHelper#bindTexture(GL10, int)} * @param pGL * @param pHardwareTextureID */ public static void forceBindTexture(final GL10 pGL, final int pHardwareTextureID) { GLHelper.sCurrentHardwareTextureID = pHardwareTextureID; pGL.glBindTexture(GL10.GL_TEXTURE_2D, pHardwareTextureID); } public static void deleteTexture(final GL10 pGL, final int pHardwareTextureID) { GLHelper.HARDWARETEXTUREID_CONTAINER[0] = pHardwareTextureID; pGL.glDeleteTextures(1, GLHelper.HARDWARETEXTUREID_CONTAINER, 0); } public static void texCoordPointer(final GL10 pGL, final FastFloatBuffer pTextureFloatBuffer) { if(GLHelper.sCurrentTextureFloatBuffer != pTextureFloatBuffer) { GLHelper.sCurrentTextureFloatBuffer = pTextureFloatBuffer; pGL.glTexCoordPointer(2, GL10.GL_FLOAT, 0, pTextureFloatBuffer.mByteBuffer); } } public static void texCoordZeroPointer(final GL11 pGL11) { pGL11.glTexCoordPointer(2, GL10.GL_FLOAT, 0, 0); } public static void vertexPointer(final GL10 pGL, final FastFloatBuffer pVertexFloatBuffer) { if(GLHelper.sCurrentVertexFloatBuffer != pVertexFloatBuffer) { GLHelper.sCurrentVertexFloatBuffer = pVertexFloatBuffer; pGL.glVertexPointer(2, GL10.GL_FLOAT, 0, pVertexFloatBuffer.mByteBuffer); } } public static void vertexZeroPointer(final GL11 pGL11) { pGL11.glVertexPointer(2, GL10.GL_FLOAT, 0, 0); } public static void blendFunction(final GL10 pGL, final int pSourceBlendMode, final int pDestinationBlendMode) { if(GLHelper.sCurrentSourceBlendMode != pSourceBlendMode || GLHelper.sCurrentDestinationBlendMode != pDestinationBlendMode) { GLHelper.sCurrentSourceBlendMode = pSourceBlendMode; GLHelper.sCurrentDestinationBlendMode = pDestinationBlendMode; pGL.glBlendFunc(pSourceBlendMode, pDestinationBlendMode); } } public static void lineWidth(final GL10 pGL, final float pLineWidth) { if(GLHelper.sLineWidth != pLineWidth) { GLHelper.sLineWidth = pLineWidth; pGL.glLineWidth(pLineWidth); } } public static void switchToModelViewMatrix(final GL10 pGL) { /* Reduce unnecessary matrix switching calls. */ if(GLHelper.sCurrentMatrix != GL10.GL_MODELVIEW) { GLHelper.sCurrentMatrix = GL10.GL_MODELVIEW; pGL.glMatrixMode(GL10.GL_MODELVIEW); } } public static void switchToProjectionMatrix(final GL10 pGL) { /* Reduce unnecessary matrix switching calls. */ if(GLHelper.sCurrentMatrix != GL10.GL_PROJECTION) { GLHelper.sCurrentMatrix = GL10.GL_PROJECTION; pGL.glMatrixMode(GL10.GL_PROJECTION); } } public static void setProjectionIdentityMatrix(final GL10 pGL) { GLHelper.switchToProjectionMatrix(pGL); pGL.glLoadIdentity(); } public static void setModelViewIdentityMatrix(final GL10 pGL) { GLHelper.switchToModelViewMatrix(pGL); pGL.glLoadIdentity(); } public static void setShadeModelFlat(final GL10 pGL) { pGL.glShadeModel(GL10.GL_FLAT); } public static void setPerspectiveCorrectionHintFastest(final GL10 pGL) { pGL.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, GL10.GL_FASTEST); } public static void bufferData(final GL11 pGL11, final ByteBuffer pByteBuffer, final int pUsage) { pGL11.glBufferData(GL11.GL_ARRAY_BUFFER, pByteBuffer.capacity(), pByteBuffer, pUsage); } /** * <b>Note:</b> does not pre-multiply the alpha channel!</br> * Except that difference, same as: {@link GLUtils#texSubImage2D(int, int, int, int, Bitmap, int, int)}</br> * </br> * See topic: '<a href="http://groups.google.com/group/android-developers/browse_thread/thread/baa6c33e63f82fca">PNG loading that doesn't premultiply alpha?</a>' * @param pBorder */ public static void glTexImage2D(final GL10 pGL, final int pTarget, final int pLevel, final Bitmap pBitmap, final int pBorder, final PixelFormat pPixelFormat) { final Buffer pixelBuffer = GLHelper.getPixels(pBitmap, pPixelFormat); pGL.glTexImage2D(pTarget, pLevel, pPixelFormat.getGLFormat(), pBitmap.getWidth(), pBitmap.getHeight(), pBorder, pPixelFormat.getGLFormat(), pPixelFormat.getGLType(), pixelBuffer); } /** * <b>Note:</b> does not pre-multiply the alpha channel!</br> * Except that difference, same as: {@link GLUtils#texSubImage2D(int, int, int, int, Bitmap, int, int)}</br> * </br> * See topic: '<a href="http://groups.google.com/group/android-developers/browse_thread/thread/baa6c33e63f82fca">PNG loading that doesn't premultiply alpha?</a>' */ public static void glTexSubImage2D(final GL10 pGL, final int pTarget, final int pLevel, final int pXOffset, final int pYOffset, final Bitmap pBitmap, final PixelFormat pPixelFormat) { final Buffer pixelBuffer = GLHelper.getPixels(pBitmap, pPixelFormat); pGL.glTexSubImage2D(pTarget, pLevel, pXOffset, pYOffset, pBitmap.getWidth(), pBitmap.getHeight(), pPixelFormat.getGLFormat(), pPixelFormat.getGLType(), pixelBuffer); } private static Buffer getPixels(final Bitmap pBitmap, final PixelFormat pPixelFormat) { final int[] pixelsARGB_8888 = GLHelper.getPixelsARGB_8888(pBitmap); switch(pPixelFormat) { case RGB_565: return ByteBuffer.wrap(GLHelper.convertARGB_8888toRGB_565(pixelsARGB_8888)); case RGBA_8888: return IntBuffer.wrap(GLHelper.convertARGB_8888toRGBA_8888(pixelsARGB_8888)); case RGBA_4444: return ByteBuffer.wrap(GLHelper.convertARGB_8888toARGB_4444(pixelsARGB_8888)); case A_8: return ByteBuffer.wrap(GLHelper.convertARGB_8888toA_8(pixelsARGB_8888)); default: throw new IllegalArgumentException("Unexpected " + PixelFormat.class.getSimpleName() + ": '" + pPixelFormat + "'."); } } private static int[] convertARGB_8888toRGBA_8888(final int[] pPixelsARGB_8888) { if(GLHelper.IS_LITTLE_ENDIAN) { for(int i = pPixelsARGB_8888.length - 1; i >= 0; i--) { final int pixel = pPixelsARGB_8888[i]; /* ARGB to ABGR */ pPixelsARGB_8888[i] = pixel & 0xFF00FF00 | (pixel & 0x000000FF) << 16 | (pixel & 0x00FF0000) >> 16; } } else { for(int i = pPixelsARGB_8888.length - 1; i >= 0; i--) { final int pixel = pPixelsARGB_8888[i]; /* ARGB to RGBA */ pPixelsARGB_8888[i] = (pixel & 0x00FFFFFF) << 8 | (pixel & 0xFF000000) >> 24; } } return pPixelsARGB_8888; } private static byte[] convertARGB_8888toRGB_565(final int[] pPixelsARGB_8888) { final byte[] pixelsRGB_565 = new byte[pPixelsARGB_8888.length * 2]; if(GLHelper.IS_LITTLE_ENDIAN) { for(int i = pPixelsARGB_8888.length - 1, j = pixelsRGB_565.length - 1; i >= 0; i--) { final int pixel = pPixelsARGB_8888[i]; final int red = ((pixel >> 16) & 0xFF); final int green = ((pixel >> 8) & 0xFF); final int blue = ((pixel) & 0xFF); /* Byte1: [R1 R2 R3 R4 R5 G1 G2 G3] * Byte2: [G4 G5 G6 B1 B2 B3 B4 B5] */ pixelsRGB_565[j--] = (byte)((red & 0xF8) | (green >> 5)); pixelsRGB_565[j--] = (byte)(((green << 3) & 0xE0) | (blue >> 3)); } } else { for(int i = pPixelsARGB_8888.length - 1, j = pixelsRGB_565.length - 1; i >= 0; i--) { final int pixel = pPixelsARGB_8888[i]; final int red = ((pixel >> 16) & 0xFF); final int green = ((pixel >> 8) & 0xFF); final int blue = ((pixel) & 0xFF); /* Byte2: [G4 G5 G6 B1 B2 B3 B4 B5] * Byte1: [R1 R2 R3 R4 R5 G1 G2 G3]*/ pixelsRGB_565[j--] = (byte)(((green << 3) & 0xE0) | (blue >> 3)); pixelsRGB_565[j--] = (byte)((red & 0xF8) | (green >> 5)); } } return pixelsRGB_565; } private static byte[] convertARGB_8888toARGB_4444(final int[] pPixelsARGB_8888) { final byte[] pixelsARGB_4444 = new byte[pPixelsARGB_8888.length * 2]; if(GLHelper.IS_LITTLE_ENDIAN) { for(int i = pPixelsARGB_8888.length - 1, j = pixelsARGB_4444.length - 1; i >= 0; i--) { final int pixel = pPixelsARGB_8888[i]; final int alpha = ((pixel >> 28) & 0x0F); final int red = ((pixel >> 16) & 0xF0); final int green = ((pixel >> 8) & 0xF0); final int blue = ((pixel) & 0x0F); /* Byte1: [A1 A2 A3 A4 R1 R2 R3 R4] * Byte2: [G1 G2 G3 G4 G2 G2 G3 G4] */ pixelsARGB_4444[j--] = (byte)(alpha | red); pixelsARGB_4444[j--] = (byte)(green | blue); } } else { for(int i = pPixelsARGB_8888.length - 1, j = pixelsARGB_4444.length - 1; i >= 0; i--) { final int pixel = pPixelsARGB_8888[i]; final int alpha = ((pixel >> 28) & 0x0F); final int red = ((pixel >> 16) & 0xF0); final int green = ((pixel >> 8) & 0xF0); final int blue = ((pixel) & 0x0F); /* Byte2: [G1 G2 G3 G4 G2 G2 G3 G4] * Byte1: [A1 A2 A3 A4 R1 R2 R3 R4] */ pixelsARGB_4444[j--] = (byte)(green | blue); pixelsARGB_4444[j--] = (byte)(alpha | red); } } return pixelsARGB_4444; } private static byte[] convertARGB_8888toA_8(final int[] pPixelsARGB_8888) { final byte[] pixelsA_8 = new byte[pPixelsARGB_8888.length]; if(GLHelper.IS_LITTLE_ENDIAN) { for(int i = pPixelsARGB_8888.length - 1; i >= 0; i--) { pixelsA_8[i] = (byte) (pPixelsARGB_8888[i] >> 24); } } else { for(int i = pPixelsARGB_8888.length - 1; i >= 0; i--) { pixelsA_8[i] = (byte) (pPixelsARGB_8888[i] & 0xFF); } } return pixelsA_8; } public static int[] getPixelsARGB_8888(final Bitmap pBitmap) { final int w = pBitmap.getWidth(); final int h = pBitmap.getHeight(); final int[] pixelsARGB_8888 = new int[w * h]; pBitmap.getPixels(pixelsARGB_8888, 0, w, 0, 0, w, h); return pixelsARGB_8888; } public static void checkGLError(final GL10 pGL) throws GLException { // TODO Use more often! final int err = pGL.glGetError(); if (err != GL10.GL_NO_ERROR) { throw new GLException(err); } } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.opengl.util; import static org.anddev.andengine.opengl.util.GLHelper.BYTES_PER_FLOAT; import java.lang.ref.SoftReference; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.FloatBuffer; import java.nio.IntBuffer; /** * Convenient work-around for poor {@link FloatBuffer#put(float[])} performance. * This should become unnecessary in gingerbread, * @see <a href="http://code.google.com/p/android/issues/detail?id=11078">Issue 11078</a> * * @author ryanm */ public class FastFloatBuffer { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== /** * Use a {@link SoftReference} so that the array can be collected if * necessary */ private static SoftReference<int[]> sWeakIntArray = new SoftReference<int[]>(new int[0]); /** * Underlying data - give this to OpenGL */ public final ByteBuffer mByteBuffer; private final FloatBuffer mFloatBuffer; private final IntBuffer mIntBuffer; // =========================================================== // Constructors // =========================================================== /** * Constructs a new direct native-ordered buffer */ public FastFloatBuffer(final int pCapacity) { this.mByteBuffer = ByteBuffer.allocateDirect((pCapacity * BYTES_PER_FLOAT)).order(ByteOrder.nativeOrder()); this.mFloatBuffer = this.mByteBuffer.asFloatBuffer(); this.mIntBuffer = this.mByteBuffer.asIntBuffer(); } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== /** * See {@link FloatBuffer#flip()} */ public void flip() { this.mByteBuffer.flip(); this.mFloatBuffer.flip(); this.mIntBuffer.flip(); } /** * See {@link FloatBuffer#put(float)} */ public void put(final float f) { final ByteBuffer byteBuffer = this.mByteBuffer; final IntBuffer intBuffer = this.mIntBuffer; byteBuffer.position(byteBuffer.position() + BYTES_PER_FLOAT); this.mFloatBuffer.put(f); intBuffer.position(intBuffer.position() + 1); } /** * It'MAGIC_CONSTANT like {@link FloatBuffer#put(float[])}, but about 10 times faster */ public void put(final float[] data) { final int length = data.length; int[] ia = sWeakIntArray.get(); if(ia == null || ia.length < length) { ia = new int[length]; sWeakIntArray = new SoftReference<int[]>(ia); } for(int i = 0; i < length; i++) { ia[i] = Float.floatToRawIntBits(data[i]); } final ByteBuffer byteBuffer = this.mByteBuffer; byteBuffer.position(byteBuffer.position() + BYTES_PER_FLOAT * length); final FloatBuffer floatBuffer = this.mFloatBuffer; floatBuffer.position(floatBuffer.position() + length); this.mIntBuffer.put(ia, 0, length); } /** * For use with pre-converted data. This is 50x faster than * {@link #put(float[])}, and 500x faster than * {@link FloatBuffer#put(float[])}, so if you've got float[] data that * won't change, {@link #convert(float...)} it to an int[] once and use this * method to put it in the buffer * * @param data floats that have been converted with {@link Float#floatToIntBits(float)} */ public void put(final int[] data) { final ByteBuffer byteBuffer = this.mByteBuffer; byteBuffer.position(byteBuffer.position() + BYTES_PER_FLOAT * data.length); final FloatBuffer floatBuffer = this.mFloatBuffer; floatBuffer.position(floatBuffer.position() + data.length); this.mIntBuffer.put(data, 0, data.length); } /** * Converts float data to a format that can be quickly added to the buffer * with {@link #put(int[])} * * @param data * @return the int-formatted data */ public static int[] convert(final float ... data) { final int length = data.length; final int[] id = new int[length]; for(int i = 0; i < length; i++) { id[i] = Float.floatToRawIntBits(data[i]); } return id; } /** * See {@link FloatBuffer#put(FloatBuffer)} */ public void put(final FastFloatBuffer b) { final ByteBuffer byteBuffer = this.mByteBuffer; byteBuffer.put(b.mByteBuffer); this.mFloatBuffer.position(byteBuffer.position() >> 2); this.mIntBuffer.position(byteBuffer.position() >> 2); } /** * @return See {@link FloatBuffer#capacity()} */ public int capacity() { return this.mFloatBuffer.capacity(); } /** * @return See {@link FloatBuffer#position()} */ public int position() { return this.mFloatBuffer.position(); } /** * See {@link FloatBuffer#position(int)} */ public void position(final int p) { this.mByteBuffer.position(p * BYTES_PER_FLOAT); this.mFloatBuffer.position(p); this.mIntBuffer.position(p); } /** * @return See {@link FloatBuffer#slice()} */ public FloatBuffer slice() { return this.mFloatBuffer.slice(); } /** * @return See {@link FloatBuffer#remaining()} */ public int remaining() { return this.mFloatBuffer.remaining(); } /** * @return See {@link FloatBuffer#limit()} */ public int limit() { return this.mFloatBuffer.limit(); } /** * See {@link FloatBuffer#clear()} */ public void clear() { this.mByteBuffer.clear(); this.mFloatBuffer.clear(); this.mIntBuffer.clear(); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.opengl.vertex; import org.anddev.andengine.opengl.util.FastFloatBuffer; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 13:07:25 - 13.03.2010 */ public class RectangleVertexBuffer extends VertexBuffer { // =========================================================== // Constants // =========================================================== public static final int VERTICES_PER_RECTANGLE = 4; private static final int FLOAT_TO_RAW_INT_BITS_ZERO = Float.floatToRawIntBits(0); // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== public RectangleVertexBuffer(final int pDrawType, final boolean pManaged) { super(2 * VERTICES_PER_RECTANGLE, pDrawType, pManaged); } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== public synchronized void update(final float pWidth, final float pHeight) { final int x = FLOAT_TO_RAW_INT_BITS_ZERO; final int y = FLOAT_TO_RAW_INT_BITS_ZERO; final int x2 = Float.floatToRawIntBits(pWidth); final int y2 = Float.floatToRawIntBits(pHeight); final int[] bufferData = this.mBufferData; bufferData[0] = x; bufferData[1] = y; bufferData[2] = x; bufferData[3] = y2; bufferData[4] = x2; bufferData[5] = y; bufferData[6] = x2; bufferData[7] = y2; final FastFloatBuffer buffer = this.getFloatBuffer(); buffer.position(0); buffer.put(bufferData); buffer.position(0); super.setHardwareBufferNeedsUpdate(); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.opengl.vertex; import org.anddev.andengine.opengl.buffer.BufferObject; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 12:16:18 - 09.03.2010 */ public abstract class VertexBuffer extends BufferObject { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== public VertexBuffer(final int pCapacity, final int pDrawType, final boolean pManaged) { super(pCapacity, pDrawType, pManaged); } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.opengl.vertex; import org.anddev.andengine.opengl.util.FastFloatBuffer; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 13:07:25 - 13.03.2010 */ public class LineVertexBuffer extends VertexBuffer { // =========================================================== // Constants // =========================================================== public static final int VERTICES_PER_LINE = 2; // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== public LineVertexBuffer(final int pDrawType, final boolean pManaged) { super(2 * VERTICES_PER_LINE, pDrawType, pManaged); } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== public synchronized void update(final float pX1, final float pY1, final float pX2, final float pY2) { final int[] bufferData = this.mBufferData; bufferData[0] = Float.floatToRawIntBits(pX1); bufferData[1] = Float.floatToRawIntBits(pY1); bufferData[2] = Float.floatToRawIntBits(pX2); bufferData[3] = Float.floatToRawIntBits(pY2); final FastFloatBuffer buffer = this.mFloatBuffer; buffer.position(0); buffer.put(bufferData); buffer.position(0); super.setHardwareBufferNeedsUpdate(); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.opengl.vertex; import org.anddev.andengine.opengl.font.Font; import org.anddev.andengine.opengl.font.Letter; import org.anddev.andengine.opengl.util.FastFloatBuffer; import org.anddev.andengine.util.HorizontalAlign; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 18:05:08 - 07.04.2010 */ public class TextVertexBuffer extends VertexBuffer { // =========================================================== // Constants // =========================================================== public static final int VERTICES_PER_CHARACTER = 6; // =========================================================== // Fields // =========================================================== private final HorizontalAlign mHorizontalAlign; // =========================================================== // Constructors // =========================================================== public TextVertexBuffer(final int pCharacterCount, final HorizontalAlign pHorizontalAlign, final int pDrawType, final boolean pManaged) { super(2 * VERTICES_PER_CHARACTER * pCharacterCount, pDrawType, pManaged); this.mHorizontalAlign = pHorizontalAlign; } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== public synchronized void update(final Font font, final int pMaximumLineWidth, final int[] pWidths, final String[] pLines) { final int[] bufferData = this.mBufferData; int i = 0; final int lineHeight = font.getLineHeight(); final int lineCount = pLines.length; for (int lineIndex = 0; lineIndex < lineCount; lineIndex++) { final String line = pLines[lineIndex]; int lineX; switch(this.mHorizontalAlign) { case RIGHT: lineX = pMaximumLineWidth - pWidths[lineIndex]; break; case CENTER: lineX = (pMaximumLineWidth - pWidths[lineIndex]) >> 1; break; case LEFT: default: lineX = 0; } final int lineY = lineIndex * (font.getLineHeight() + font.getLineGap()); final int lineYBits = Float.floatToRawIntBits(lineY); final int lineLength = line.length(); for (int letterIndex = 0; letterIndex < lineLength; letterIndex++) { final Letter letter = font.getLetter(line.charAt(letterIndex)); final int lineY2 = lineY + lineHeight; final int lineX2 = lineX + letter.mWidth; final int lineXBits = Float.floatToRawIntBits(lineX); final int lineX2Bits = Float.floatToRawIntBits(lineX2); final int lineY2Bits = Float.floatToRawIntBits(lineY2); bufferData[i++] = lineXBits; bufferData[i++] = lineYBits; bufferData[i++] = lineXBits; bufferData[i++] = lineY2Bits; bufferData[i++] = lineX2Bits; bufferData[i++] = lineY2Bits; bufferData[i++] = lineX2Bits; bufferData[i++] = lineY2Bits; bufferData[i++] = lineX2Bits; bufferData[i++] = lineYBits; bufferData[i++] = lineXBits; bufferData[i++] = lineYBits; lineX += letter.mAdvance; } } final FastFloatBuffer vertexFloatBuffer = this.mFloatBuffer; vertexFloatBuffer.position(0); vertexFloatBuffer.put(bufferData); vertexFloatBuffer.position(0); super.setHardwareBufferNeedsUpdate(); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.opengl.vertex; import org.anddev.andengine.opengl.util.FastFloatBuffer; import org.anddev.andengine.util.Transformation; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 11:53:48 - 14.06.2011 */ public class SpriteBatchVertexBuffer extends VertexBuffer { // =========================================================== // Constants // =========================================================== public static final int VERTICES_PER_RECTANGLE = 6; private static final float[] VERTICES_TMP = new float[8]; private static final Transformation TRANSFORATION_TMP = new Transformation(); // =========================================================== // Fields // =========================================================== protected int mIndex; // =========================================================== // Constructors // =========================================================== public SpriteBatchVertexBuffer(final int pCapacity, final int pDrawType, final boolean pManaged) { super(pCapacity * 2 * VERTICES_PER_RECTANGLE, pDrawType, pManaged); } // =========================================================== // Getter & Setter // =========================================================== public int getIndex() { return this.mIndex; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== public void setIndex(final int pIndex) { this.mIndex = pIndex; } /** * @param pX * @param pY * @param pWidth * @param pHeight * @param pRotation around the center (pWidth * 0.5f, pHeight * 0.5f) */ public void add(final float pX, final float pY, final float pWidth, final float pHeight, final float pRotation) { final float widthHalf = pWidth * 0.5f; final float heightHalf = pHeight * 0.5f; TRANSFORATION_TMP.setToIdentity(); TRANSFORATION_TMP.postTranslate(-widthHalf, -heightHalf); TRANSFORATION_TMP.postRotate(pRotation); TRANSFORATION_TMP.postTranslate(widthHalf, heightHalf); TRANSFORATION_TMP.postTranslate(pX, pY); this.add(pWidth, pHeight, TRANSFORATION_TMP); } /** * @param pX * @param pY * @param pWidth * @param pHeight * @param pRotation around the center (pWidth * 0.5f, pHeight * 0.5f) * @param pScaleX around the center (pWidth * 0.5f, pHeight * 0.5f) * @param pScaleY around the center (pWidth * 0.5f, pHeight * 0.5f) */ public void add(final float pX, final float pY, final float pWidth, final float pHeight, final float pScaleX, final float pScaleY) { final float widthHalf = pWidth * 0.5f; final float heightHalf = pHeight * 0.5f; TRANSFORATION_TMP.setToIdentity(); TRANSFORATION_TMP.postTranslate(-widthHalf, -heightHalf); TRANSFORATION_TMP.postScale(pScaleX, pScaleY); TRANSFORATION_TMP.postTranslate(widthHalf, heightHalf); TRANSFORATION_TMP.postTranslate(pX, pY); this.add(pWidth, pHeight, TRANSFORATION_TMP); } /** * @param pX * @param pY * @param pWidth * @param pHeight * @param pRotation around the center (pWidth * 0.5f, pHeight * 0.5f) * @param pScaleX around the center (pWidth * 0.5f, pHeight * 0.5f) * @param pScaleY around the center (pWidth * 0.5f, pHeight * 0.5f) */ public void add(final float pX, final float pY, final float pWidth, final float pHeight, final float pRotation, final float pScaleX, final float pScaleY) { final float widthHalf = pWidth * 0.5f; final float heightHalf = pHeight * 0.5f; TRANSFORATION_TMP.setToIdentity(); TRANSFORATION_TMP.postTranslate(-widthHalf, -heightHalf); TRANSFORATION_TMP.postScale(pScaleX, pScaleY); TRANSFORATION_TMP.postRotate(pRotation); TRANSFORATION_TMP.postTranslate(widthHalf, heightHalf); TRANSFORATION_TMP.postTranslate(pX, pY); this.add(pWidth, pHeight, TRANSFORATION_TMP); } /** * * @param pX * @param pY * @param pWidth * @param pHeight * @param pTransformation */ public void add(final float pWidth, final float pHeight, final Transformation pTransformation) { VERTICES_TMP[0] = 0; VERTICES_TMP[1] = 0; VERTICES_TMP[2] = 0; VERTICES_TMP[3] = pHeight; VERTICES_TMP[4] = pWidth; VERTICES_TMP[5] = 0; VERTICES_TMP[6] = pWidth; VERTICES_TMP[7] = pHeight; pTransformation.transform(VERTICES_TMP); this.addInner(VERTICES_TMP[0], VERTICES_TMP[1], VERTICES_TMP[2], VERTICES_TMP[3], VERTICES_TMP[4], VERTICES_TMP[5], VERTICES_TMP[6], VERTICES_TMP[7]); } public void add(final float pX, final float pY, final float pWidth, final float pHeight) { this.addInner(pX, pY, pX + pWidth, pY + pHeight); } /** * 1-+ * |X| * +-2 */ public void addInner(final float pX1, final float pY1, final float pX2, final float pY2) { final int x1 = Float.floatToRawIntBits(pX1); final int y1 = Float.floatToRawIntBits(pY1); final int x2 = Float.floatToRawIntBits(pX2); final int y2 = Float.floatToRawIntBits(pY2); final int[] bufferData = this.mBufferData; int index = this.mIndex; bufferData[index++] = x1; bufferData[index++] = y1; bufferData[index++] = x1; bufferData[index++] = y2; bufferData[index++] = x2; bufferData[index++] = y1; bufferData[index++] = x2; bufferData[index++] = y1; bufferData[index++] = x1; bufferData[index++] = y2; bufferData[index++] = x2; bufferData[index++] = y2; this.mIndex = index; } /** * 1-3 * |X| * 2-4 */ public void addInner(final float pX1, final float pY1, final float pX2, final float pY2, final float pX3, final float pY3, final float pX4, final float pY4) { final int x1 = Float.floatToRawIntBits(pX1); final int y1 = Float.floatToRawIntBits(pY1); final int x2 = Float.floatToRawIntBits(pX2); final int y2 = Float.floatToRawIntBits(pY2); final int x3 = Float.floatToRawIntBits(pX3); final int y3 = Float.floatToRawIntBits(pY3); final int x4 = Float.floatToRawIntBits(pX4); final int y4 = Float.floatToRawIntBits(pY4); final int[] bufferData = this.mBufferData; int index = this.mIndex; bufferData[index++] = x1; bufferData[index++] = y1; bufferData[index++] = x2; bufferData[index++] = y2; bufferData[index++] = x3; bufferData[index++] = y3; bufferData[index++] = x3; bufferData[index++] = y3; bufferData[index++] = x2; bufferData[index++] = y2; bufferData[index++] = x4; bufferData[index++] = y4; this.mIndex = index; } public void submit() { final FastFloatBuffer buffer = this.mFloatBuffer; buffer.position(0); buffer.put(this.mBufferData); buffer.position(0); super.setHardwareBufferNeedsUpdate(); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.opengl.font; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 10:29:21 - 03.04.2010 */ class Size { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private float mWidth; private float mHeight; // =========================================================== // Constructors // =========================================================== public Size() { this(0, 0); } public Size(final float pWidth, final float pHeight) { this.setWidth(pWidth); this.setHeight(pHeight); } // =========================================================== // Getter & Setter // =========================================================== public void setWidth(final float width) { this.mWidth = width; } public float getWidth() { return this.mWidth; } public void setHeight(final float height) { this.mHeight = height; } public float getHeight() { return this.mHeight; } public void set(final int pWidth, final int pHeight) { this.setWidth(pWidth); this.setHeight(pHeight); } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.opengl.font; import org.anddev.andengine.opengl.texture.ITexture; import android.graphics.Paint; import android.graphics.Paint.Style; import android.graphics.Typeface; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 10:39:33 - 03.04.2010 */ public class StrokeFont extends Font { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private final Paint mStrokePaint; private final boolean mStrokeOnly; // =========================================================== // Constructors // =========================================================== public StrokeFont(final ITexture pTexture, final Typeface pTypeface, final float pSize, final boolean pAntiAlias, final int pColor, final float pStrokeWidth, final int pStrokeColor) { this(pTexture, pTypeface, pSize, pAntiAlias, pColor, pStrokeWidth, pStrokeColor, false); } public StrokeFont(final ITexture pTexture, final Typeface pTypeface, final float pSize, final boolean pAntiAlias, final int pColor, final float pStrokeWidth, final int pStrokeColor, final boolean pStrokeOnly) { super(pTexture, pTypeface, pSize, pAntiAlias, pColor); this.mStrokePaint = new Paint(); this.mStrokePaint.setTypeface(pTypeface); this.mStrokePaint.setStyle(Style.STROKE); this.mStrokePaint.setStrokeWidth(pStrokeWidth); this.mStrokePaint.setColor(pStrokeColor); this.mStrokePaint.setTextSize(pSize); this.mStrokePaint.setAntiAlias(pAntiAlias); this.mStrokeOnly = pStrokeOnly; } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override protected void drawCharacterString(final String pCharacterAsString) { if(!this.mStrokeOnly) { super.drawCharacterString(pCharacterAsString); } this.mCanvas.drawText(pCharacterAsString, LETTER_LEFT_OFFSET, -this.mFontMetrics.ascent, this.mStrokePaint); } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.opengl.font; import org.anddev.andengine.opengl.texture.ITexture; import android.content.Context; import android.graphics.Typeface; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 17:17:28 - 16.06.2010 */ public class FontFactory { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private static String sAssetBasePath = ""; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== /** * @param pAssetBasePath must end with '<code>/</code>' or have <code>.length() == 0</code>. */ public static void setAssetBasePath(final String pAssetBasePath) { if(pAssetBasePath.endsWith("/") || pAssetBasePath.length() == 0) { FontFactory.sAssetBasePath = pAssetBasePath; } else { throw new IllegalStateException("pAssetBasePath must end with '/' or be lenght zero."); } } public static void reset() { FontFactory.setAssetBasePath(""); } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== public static Font create(final ITexture pTexture, final Typeface pTypeface, final float pSize, final boolean pAntiAlias, final int pColor) { return new Font(pTexture, pTypeface, pSize, pAntiAlias, pColor); } public static StrokeFont createStroke(final ITexture pTexture, final Typeface pTypeface, final float pSize, final boolean pAntiAlias, final int pColor, final float pStrokeWidth, final int pStrokeColor) { return new StrokeFont(pTexture, pTypeface, pSize, pAntiAlias, pColor, pStrokeWidth, pStrokeColor); } public static StrokeFont createStroke(final ITexture pTexture, final Typeface pTypeface, final float pSize, final boolean pAntiAlias, final int pColor, final float pStrokeWidth, final int pStrokeColor, final boolean pStrokeOnly) { return new StrokeFont(pTexture, pTypeface, pSize, pAntiAlias, pColor, pStrokeWidth, pStrokeColor, pStrokeOnly); } public static Font createFromAsset(final ITexture pTexture, final Context pContext, final String pAssetPath, final float pSize, final boolean pAntiAlias, final int pColor) { return new Font(pTexture, Typeface.createFromAsset(pContext.getAssets(), FontFactory.sAssetBasePath + pAssetPath), pSize, pAntiAlias, pColor); } public static StrokeFont createStrokeFromAsset(final ITexture pTexture, final Context pContext, final String pAssetPath, final float pSize, final boolean pAntiAlias, final int pColor, final float pStrokeWidth, final int pStrokeColor) { return new StrokeFont(pTexture, Typeface.createFromAsset(pContext.getAssets(), FontFactory.sAssetBasePath + pAssetPath), pSize, pAntiAlias, pColor, pStrokeWidth, pStrokeColor); } public static StrokeFont createStrokeFromAsset(final ITexture pTexture, final Context pContext, final String pAssetPath, final float pSize, final boolean pAntiAlias, final int pColor, final float pStrokeWidth, final int pStrokeColor, final boolean pStrokeOnly) { return new StrokeFont(pTexture, Typeface.createFromAsset(pContext.getAssets(), FontFactory.sAssetBasePath + pAssetPath), pSize, pAntiAlias, pColor, pStrokeWidth, pStrokeColor, pStrokeOnly); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
/** * */ package org.anddev.andengine.opengl.font; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 10:30:22 - 03.04.2010 */ public class Letter { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== public final int mAdvance; public final int mWidth; public final int mHeight; public final float mTextureX; public final float mTextureY; public final float mTextureWidth; public final float mTextureHeight; public final char mCharacter; // =========================================================== // Constructors // =========================================================== Letter(final char pCharacter, final int pAdvance, final int pWidth, final int pHeight, final float pTextureX, final float pTextureY, final float pTextureWidth, final float pTextureHeight) { this.mCharacter = pCharacter; this.mAdvance = pAdvance; this.mWidth = pWidth; this.mHeight = pHeight; this.mTextureX = pTextureX; this.mTextureY = pTextureY; this.mTextureWidth = pTextureWidth; this.mTextureHeight = pTextureHeight; } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + this.mCharacter; return result; } @Override public boolean equals(final Object obj) { if(this == obj) { return true; } if(obj == null) { return false; } if(this.getClass() != obj.getClass()) { return false; } final Letter other = (Letter) obj; if(this.mCharacter != other.mCharacter) { return false; } return true; } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.opengl.font; import java.util.ArrayList; import javax.microedition.khronos.opengles.GL10; import org.anddev.andengine.opengl.texture.ITexture; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Paint.FontMetrics; import android.graphics.Paint.Style; import android.graphics.Rect; import android.graphics.Typeface; import android.opengl.GLUtils; import android.util.FloatMath; import android.util.SparseArray; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 10:39:33 - 03.04.2010 */ public class Font { // =========================================================== // Constants // =========================================================== protected static final float LETTER_LEFT_OFFSET = 0; protected static final int LETTER_EXTRA_WIDTH = 10; protected final static int PADDING = 1; // =========================================================== // Fields // =========================================================== private final ITexture mTexture; private final float mTextureWidth; private final float mTextureHeight; private int mCurrentTextureX = 0; private int mCurrentTextureY = 0; private final SparseArray<Letter> mManagedCharacterToLetterMap = new SparseArray<Letter>(); private final ArrayList<Letter> mLettersPendingToBeDrawnToTexture = new ArrayList<Letter>(); protected final Paint mPaint; private final Paint mBackgroundPaint; protected final FontMetrics mFontMetrics; private final int mLineHeight; private final int mLineGap; private final Size mCreateLetterTemporarySize = new Size(); private final Rect mGetLetterBitmapTemporaryRect = new Rect(); private final Rect mGetStringWidthTemporaryRect = new Rect(); private final Rect mGetLetterBoundsTemporaryRect = new Rect(); private final float[] mTemporaryTextWidthFetchers = new float[1]; protected final Canvas mCanvas = new Canvas(); // =========================================================== // Constructors // =========================================================== public Font(final ITexture pTexture, final Typeface pTypeface, final float pSize, final boolean pAntiAlias, final int pColor) { this.mTexture = pTexture; this.mTextureWidth = pTexture.getWidth(); this.mTextureHeight = pTexture.getHeight(); this.mPaint = new Paint(); this.mPaint.setTypeface(pTypeface); this.mPaint.setColor(pColor); this.mPaint.setTextSize(pSize); this.mPaint.setAntiAlias(pAntiAlias); this.mBackgroundPaint = new Paint(); this.mBackgroundPaint.setColor(Color.TRANSPARENT); this.mBackgroundPaint.setStyle(Style.FILL); this.mFontMetrics = this.mPaint.getFontMetrics(); this.mLineHeight = (int) FloatMath.ceil(Math.abs(this.mFontMetrics.ascent) + Math.abs(this.mFontMetrics.descent)) + (PADDING * 2); this.mLineGap = (int) (FloatMath.ceil(this.mFontMetrics.leading)); } // =========================================================== // Getter & Setter // =========================================================== public int getLineGap() { return this.mLineGap; } public int getLineHeight() { return this.mLineHeight; } public ITexture getTexture() { return this.mTexture; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== public synchronized void reload() { final ArrayList<Letter> lettersPendingToBeDrawnToTexture = this.mLettersPendingToBeDrawnToTexture; final SparseArray<Letter> managedCharacterToLetterMap = this.mManagedCharacterToLetterMap; /* Make all letters redraw to the texture. */ for(int i = managedCharacterToLetterMap.size() - 1; i >= 0; i--) { lettersPendingToBeDrawnToTexture.add(managedCharacterToLetterMap.valueAt(i)); } } private int getLetterAdvance(final char pCharacter) { this.mPaint.getTextWidths(String.valueOf(pCharacter), this.mTemporaryTextWidthFetchers); return (int) (FloatMath.ceil(this.mTemporaryTextWidthFetchers[0])); } private Bitmap getLetterBitmap(final char pCharacter) { final Rect getLetterBitmapTemporaryRect = this.mGetLetterBitmapTemporaryRect; final String characterAsString = String.valueOf(pCharacter); this.mPaint.getTextBounds(characterAsString, 0, 1, getLetterBitmapTemporaryRect); getLetterBitmapTemporaryRect.right += PADDING * 2; final int lineHeight = this.getLineHeight(); final Bitmap bitmap = Bitmap.createBitmap(getLetterBitmapTemporaryRect.width() == 0 ? 1 + (2 * PADDING) : getLetterBitmapTemporaryRect.width() + LETTER_EXTRA_WIDTH, lineHeight, Bitmap.Config.ARGB_8888); this.mCanvas.setBitmap(bitmap); /* Make background transparent. */ this.mCanvas.drawRect(0, 0, bitmap.getWidth(), bitmap.getHeight(), this.mBackgroundPaint); /* Actually draw the character. */ this.drawCharacterString(characterAsString); return bitmap; } protected void drawCharacterString(final String pCharacterAsString) { this.mCanvas.drawText(pCharacterAsString, LETTER_LEFT_OFFSET + PADDING, -this.mFontMetrics.ascent + PADDING, this.mPaint); } public int getStringWidth(final String pText) { this.mPaint.getTextBounds(pText, 0, pText.length(), this.mGetStringWidthTemporaryRect); return this.mGetStringWidthTemporaryRect.width(); } private void getLetterBounds(final char pCharacter, final Size pSize) { this.mPaint.getTextBounds(String.valueOf(pCharacter), 0, 1, this.mGetLetterBoundsTemporaryRect); pSize.set(this.mGetLetterBoundsTemporaryRect.width() + LETTER_EXTRA_WIDTH + (2 * PADDING), this.getLineHeight()); } public void prepareLetters(final char ... pCharacters) { for(final char character : pCharacters) { this.getLetter(character); } } public synchronized Letter getLetter(final char pCharacter) { final SparseArray<Letter> managedCharacterToLetterMap = this.mManagedCharacterToLetterMap; Letter letter = managedCharacterToLetterMap.get(pCharacter); if (letter == null) { letter = this.createLetter(pCharacter); this.mLettersPendingToBeDrawnToTexture.add(letter); managedCharacterToLetterMap.put(pCharacter, letter); } return letter; } private Letter createLetter(final char pCharacter) { final float textureWidth = this.mTextureWidth; final float textureHeight = this.mTextureHeight; final Size createLetterTemporarySize = this.mCreateLetterTemporarySize; this.getLetterBounds(pCharacter, createLetterTemporarySize); final float letterWidth = createLetterTemporarySize.getWidth(); final float letterHeight = createLetterTemporarySize.getHeight(); if (this.mCurrentTextureX + letterWidth >= textureWidth) { this.mCurrentTextureX = 0; this.mCurrentTextureY += this.getLineGap() + this.getLineHeight(); } final float letterTextureX = this.mCurrentTextureX / textureWidth; final float letterTextureY = this.mCurrentTextureY / textureHeight; final float letterTextureWidth = letterWidth / textureWidth; final float letterTextureHeight = letterHeight / textureHeight; final Letter letter = new Letter(pCharacter, this.getLetterAdvance(pCharacter), (int)letterWidth, (int)letterHeight, letterTextureX, letterTextureY, letterTextureWidth, letterTextureHeight); this.mCurrentTextureX += letterWidth; return letter; } public synchronized void update(final GL10 pGL) { final ArrayList<Letter> lettersPendingToBeDrawnToTexture = this.mLettersPendingToBeDrawnToTexture; if(lettersPendingToBeDrawnToTexture.size() > 0) { this.mTexture.bind(pGL); final float textureWidth = this.mTextureWidth; final float textureHeight = this.mTextureHeight; for(int i = lettersPendingToBeDrawnToTexture.size() - 1; i >= 0; i--) { final Letter letter = lettersPendingToBeDrawnToTexture.get(i); final Bitmap bitmap = this.getLetterBitmap(letter.mCharacter); // TODO What about premultiplyalpha of the textureOptions? GLUtils.texSubImage2D(GL10.GL_TEXTURE_2D, 0, (int)(letter.mTextureX * textureWidth), (int)(letter.mTextureY * textureHeight), bitmap); bitmap.recycle(); } lettersPendingToBeDrawnToTexture.clear(); System.gc(); } } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.opengl.font; import org.anddev.andengine.util.Library; import android.util.SparseArray; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 11:52:26 - 20.08.2010 */ public class FontLibrary extends Library<Font> { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== public FontLibrary() { super(); } public FontLibrary(final int pInitialCapacity) { super(pInitialCapacity); } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== void loadFonts(final FontManager pFontManager) { final SparseArray<Font> items = this.mItems; for(int i = items.size() - 1; i >= 0; i--) { final Font font = items.valueAt(i); if(font != null) { pFontManager.loadFont(font); } } } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.opengl.font; import java.util.ArrayList; import javax.microedition.khronos.opengles.GL10; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 17:48:46 - 08.03.2010 */ public class FontManager { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private final ArrayList<Font> mFontsManaged = new ArrayList<Font>(); // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== public synchronized void clear() { this.mFontsManaged.clear(); } public synchronized void loadFont(final Font pFont) { if(pFont == null) { throw new IllegalArgumentException("pFont must not be null!"); } this.mFontsManaged.add(pFont); } public synchronized void loadFonts(final FontLibrary pFontLibrary) { pFontLibrary.loadFonts(this); } public void loadFonts(final Font ... pFonts) { for(int i = pFonts.length - 1; i >= 0; i--) { this.loadFont(pFonts[i]); } } public synchronized void updateFonts(final GL10 pGL) { final ArrayList<Font> fonts = this.mFontsManaged; final int fontCount = fonts.size(); if(fontCount > 0){ for(int i = fontCount - 1; i >= 0; i--){ fonts.get(i).update(pGL); } } } public synchronized void reloadFonts() { final ArrayList<Font> managedFonts = this.mFontsManaged; for(int i = managedFonts.size() - 1; i >= 0; i--) { managedFonts.get(i).reload(); } } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.opengl.texture; import javax.microedition.khronos.opengles.GL10; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 13:00:09 - 05.04.2010 */ public class TextureOptions { // =========================================================== // Constants // =========================================================== public static final TextureOptions NEAREST = new TextureOptions(GL10.GL_NEAREST, GL10.GL_NEAREST, GL10.GL_CLAMP_TO_EDGE, GL10.GL_CLAMP_TO_EDGE, false); public static final TextureOptions BILINEAR = new TextureOptions(GL10.GL_LINEAR, GL10.GL_LINEAR, GL10.GL_CLAMP_TO_EDGE, GL10.GL_CLAMP_TO_EDGE, false); public static final TextureOptions REPEATING_NEAREST = new TextureOptions(GL10.GL_NEAREST, GL10.GL_NEAREST, GL10.GL_REPEAT, GL10.GL_REPEAT, false); public static final TextureOptions REPEATING_BILINEAR = new TextureOptions(GL10.GL_LINEAR, GL10.GL_LINEAR, GL10.GL_REPEAT, GL10.GL_REPEAT, false); public static final TextureOptions NEAREST_PREMULTIPLYALPHA = new TextureOptions(GL10.GL_NEAREST, GL10.GL_NEAREST, GL10.GL_CLAMP_TO_EDGE, GL10.GL_CLAMP_TO_EDGE, true); public static final TextureOptions BILINEAR_PREMULTIPLYALPHA = new TextureOptions(GL10.GL_LINEAR, GL10.GL_LINEAR, GL10.GL_CLAMP_TO_EDGE, GL10.GL_CLAMP_TO_EDGE, true); public static final TextureOptions REPEATING_NEAREST_PREMULTIPLYALPHA = new TextureOptions(GL10.GL_NEAREST, GL10.GL_NEAREST, GL10.GL_REPEAT, GL10.GL_REPEAT, true); public static final TextureOptions REPEATING_BILINEAR_PREMULTIPLYALPHA = new TextureOptions(GL10.GL_LINEAR, GL10.GL_LINEAR, GL10.GL_REPEAT, GL10.GL_REPEAT, true); public static final TextureOptions DEFAULT = TextureOptions.NEAREST_PREMULTIPLYALPHA; // =========================================================== // Fields // =========================================================== public final int mMagFilter; public final int mMinFilter; public final float mWrapT; public final float mWrapS; public final boolean mPreMultipyAlpha; // =========================================================== // Constructors // =========================================================== public TextureOptions(final int pMinFilter, final int pMagFilter, final int pWrapT, final int pWrapS, final boolean pPreMultiplyAlpha) { this.mMinFilter = pMinFilter; this.mMagFilter = pMagFilter; this.mWrapT = pWrapT; this.mWrapS = pWrapS; this.mPreMultipyAlpha = pPreMultiplyAlpha; } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== public void apply(final GL10 pGL) { pGL.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, this.mMinFilter); pGL.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, this.mMagFilter); pGL.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, this.mWrapS); pGL.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, this.mWrapT); pGL.glTexEnvf(GL10.GL_TEXTURE_ENV, GL10.GL_TEXTURE_ENV_MODE, GL10.GL_MODULATE); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.opengl.texture.compressed.pvr; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.nio.ByteOrder; import javax.microedition.khronos.opengles.GL10; import org.anddev.andengine.opengl.texture.Texture; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.util.ArrayUtils; import org.anddev.andengine.util.ByteBufferOutputStream; import org.anddev.andengine.util.Debug; import org.anddev.andengine.util.MathUtils; import org.anddev.andengine.util.StreamUtils; import org.anddev.andengine.util.constants.DataConstants; /** * [16:32:42] Ricardo Quesada: "quick tip for PVR + NPOT + RGBA4444 textures: Don't forget to pack the bytes: glPixelStorei(GL_UNPACK_ALIGNMENT,1);" * * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 16:18:10 - 13.07.2011 * @see https://github.com/cocos2d/cocos2d-iphone/blob/develop/cocos2d/CCTexturePVR.m */ public abstract class PVRTexture extends Texture { // =========================================================== // Constants // =========================================================== public static final int FLAG_MIPMAP = (1<<8); // has mip map levels public static final int FLAG_TWIDDLE = (1<<9); // is twiddled public static final int FLAG_BUMPMAP = (1<<10); // has normals encoded for a bump map public static final int FLAG_TILING = (1<<11); // is bordered for tiled pvr public static final int FLAG_CUBEMAP = (1<<12); // is a cubemap/skybox public static final int FLAG_FALSEMIPCOL = (1<<13); // are there false colored MIP levels public static final int FLAG_VOLUME = (1<<14); // is this a volume texture public static final int FLAG_ALPHA = (1<<15); // v2.1 is there transparency info in the texture public static final int FLAG_VERTICALFLIP = (1<<16); // v2.1 is the texture vertically flipped // =========================================================== // Fields // =========================================================== private final PVRTextureHeader mPVRTextureHeader; // =========================================================== // Constructors // =========================================================== public PVRTexture(final PVRTextureFormat pPVRTextureFormat) throws IllegalArgumentException, IOException { this(pPVRTextureFormat, TextureOptions.DEFAULT, null); } public PVRTexture(final PVRTextureFormat pPVRTextureFormat, final ITextureStateListener pTextureStateListener) throws IllegalArgumentException, IOException { this(pPVRTextureFormat, TextureOptions.DEFAULT, pTextureStateListener); } public PVRTexture(final PVRTextureFormat pPVRTextureFormat, final TextureOptions pTextureOptions) throws IllegalArgumentException, IOException { this(pPVRTextureFormat, pTextureOptions, null); } public PVRTexture(final PVRTextureFormat pPVRTextureFormat, final TextureOptions pTextureOptions, final ITextureStateListener pTextureStateListener) throws IllegalArgumentException, IOException { super(pPVRTextureFormat.getPixelFormat(), pTextureOptions, pTextureStateListener); InputStream inputStream = null; try { inputStream = this.getInputStream(); this.mPVRTextureHeader = new PVRTextureHeader(StreamUtils.streamToBytes(inputStream, PVRTextureHeader.SIZE)); } finally { StreamUtils.close(inputStream); } if(!MathUtils.isPowerOfTwo(this.getWidth()) || !MathUtils.isPowerOfTwo(this.getHeight())) { // TODO GLHelper.EXTENSIONS_NON_POWER_OF_TWO throw new IllegalArgumentException("mWidth and mHeight must be a power of 2!"); } if(this.mPVRTextureHeader.getPVRTextureFormat().getPixelFormat() != pPVRTextureFormat.getPixelFormat()) { throw new IllegalArgumentException("Other PVRTextureFormat: '" + this.mPVRTextureHeader.getPVRTextureFormat().getPixelFormat() + "' found than expected: '" + pPVRTextureFormat.getPixelFormat() + "'."); } if(this.mPVRTextureHeader.getPVRTextureFormat().isCompressed()) { // TODO && ! GLHELPER_EXTENSION_PVRTC] ) { throw new IllegalArgumentException("Invalid PVRTextureFormat: '" + this.mPVRTextureHeader.getPVRTextureFormat() + "'."); } this.mUpdateOnHardwareNeeded = true; } // =========================================================== // Getter & Setter // =========================================================== @Override public int getWidth() { return this.mPVRTextureHeader.getWidth(); } @Override public int getHeight() { return this.mPVRTextureHeader.getHeight(); } public PVRTextureHeader getPVRTextureHeader() { return this.mPVRTextureHeader; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== protected abstract InputStream onGetInputStream() throws IOException; protected InputStream getInputStream() throws IOException { return this.onGetInputStream(); } @Override protected void generateHardwareTextureID(final GL10 pGL) { // // TODO // if(this.mMipMapCount > 0) { pGL.glPixelStorei(GL10.GL_UNPACK_ALIGNMENT, 1); // } super.generateHardwareTextureID(pGL); } @Override protected void writeTextureToHardware(final GL10 pGL) throws IOException { final ByteBuffer pvrDataBuffer = this.getPVRDataBuffer(); int width = this.getWidth(); int height = this.getHeight(); final int dataLength = this.mPVRTextureHeader.getDataLength(); final int glFormat = this.mPixelFormat.getGLFormat(); final int glType = this.mPixelFormat.getGLType(); final int bytesPerPixel = this.mPVRTextureHeader.getBitsPerPixel() / DataConstants.BITS_PER_BYTE; /* Calculate the data size for each texture level and respect the minimum number of blocks. */ int mipmapLevel = 0; int currentPixelDataOffset = 0; while (currentPixelDataOffset < dataLength) { final int currentPixelDataSize = width * height * bytesPerPixel; if (mipmapLevel > 0 && (width != height || MathUtils.nextPowerOfTwo(width) != width)) { Debug.w(String.format("Mipmap level '%u' is not squared. Width: '%u', height: '%u'. Texture won't render correctly.", mipmapLevel, width, height)); } pvrDataBuffer.position(PVRTextureHeader.SIZE + currentPixelDataOffset); pvrDataBuffer.limit(PVRTextureHeader.SIZE + currentPixelDataOffset + currentPixelDataSize); ByteBuffer pixelBuffer = pvrDataBuffer.slice(); pGL.glTexImage2D(GL10.GL_TEXTURE_2D, mipmapLevel, glFormat, width, height, 0, glFormat, glType, pixelBuffer); currentPixelDataOffset += currentPixelDataSize; /* Prepare next mipmap level. */ width = Math.max(width >> 1, 1); height = Math.max(height >> 1, 1); mipmapLevel++; } } // =========================================================== // Methods // =========================================================== protected ByteBuffer getPVRDataBuffer() throws IOException { final InputStream inputStream = this.getInputStream(); try { final ByteBufferOutputStream os = new ByteBufferOutputStream(DataConstants.BYTES_PER_KILOBYTE, DataConstants.BYTES_PER_MEGABYTE / 2); StreamUtils.copy(inputStream, os); return os.toByteBuffer(); } finally { StreamUtils.close(inputStream); } } // =========================================================== // Inner and Anonymous Classes // =========================================================== public static class PVRTextureHeader { // =========================================================== // Constants // =========================================================== public static final byte[] MAGIC_IDENTIFIER = { (byte)'P', (byte)'V', (byte)'R', (byte)'!' }; public static final int SIZE = 13 * DataConstants.BYTES_PER_INT; private static final int FORMAT_FLAG_MASK = 0x0FF; // =========================================================== // Fields // =========================================================== private final ByteBuffer mDataByteBuffer; private final PVRTextureFormat mPVRTextureFormat; // =========================================================== // Constructors // =========================================================== public PVRTextureHeader(final byte[] pData) { this.mDataByteBuffer = ByteBuffer.wrap(pData); this.mDataByteBuffer.rewind(); this.mDataByteBuffer.order(ByteOrder.LITTLE_ENDIAN); /* Check magic bytes. */ if(!ArrayUtils.equals(pData, 11 * DataConstants.BYTES_PER_INT, PVRTextureHeader.MAGIC_IDENTIFIER, 0, PVRTextureHeader.MAGIC_IDENTIFIER.length)) { throw new IllegalArgumentException("Invalid " + this.getClass().getSimpleName() + "!"); } this.mPVRTextureFormat = PVRTextureFormat.fromID(this.getFlags() & PVRTextureHeader.FORMAT_FLAG_MASK); } // =========================================================== // Getter & Setter // =========================================================== public PVRTextureFormat getPVRTextureFormat() { return this.mPVRTextureFormat; } public int headerLength() { return this.mDataByteBuffer.getInt(0 * DataConstants.BYTES_PER_INT); // TODO Constants } public int getHeight() { return this.mDataByteBuffer.getInt(1 * DataConstants.BYTES_PER_INT); } public int getWidth() { return this.mDataByteBuffer.getInt(2 * DataConstants.BYTES_PER_INT); } public int getNumMipmaps() { return this.mDataByteBuffer.getInt(3 * DataConstants.BYTES_PER_INT); } public int getFlags() { return this.mDataByteBuffer.getInt(4 * DataConstants.BYTES_PER_INT); } public int getDataLength() { return this.mDataByteBuffer.getInt(5 * DataConstants.BYTES_PER_INT); } public int getBitsPerPixel() { return this.mDataByteBuffer.getInt(6 * DataConstants.BYTES_PER_INT); } public int getBitmaskRed() { return this.mDataByteBuffer.getInt(7 * DataConstants.BYTES_PER_INT); } public int getBitmaskGreen() { return this.mDataByteBuffer.getInt(8 * DataConstants.BYTES_PER_INT); } public int getBitmaskBlue() { return this.mDataByteBuffer.getInt(9 * DataConstants.BYTES_PER_INT); } public int getBitmaskAlpha() { return this.mDataByteBuffer.getInt(10 * DataConstants.BYTES_PER_INT); } public boolean hasAlpha() { return this.getBitmaskAlpha() != 0; } public int getPVRTag() { return this.mDataByteBuffer.getInt(11 * DataConstants.BYTES_PER_INT); } public int numSurfs() { return this.mDataByteBuffer.getInt(12 * DataConstants.BYTES_PER_INT); } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== } public static enum PVRTextureFormat { // =========================================================== // Elements // =========================================================== RGBA_4444(0x10, false, PixelFormat.RGBA_4444), RGBA_5551(0x11, false, PixelFormat.RGBA_5551), RGBA_8888(0x12, false, PixelFormat.RGBA_8888), RGB_565(0x13, false, PixelFormat.RGB_565), // RGB_555( 0x14, ...), // RGB_888( 0x15, ...), I_8(0x16, false, PixelFormat.I_8), AI_88(0x17, false, PixelFormat.AI_88), // PVRTC_2(0x18, GL10.GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG, true, TextureFormat.???), // PVRTC_4(0x19, GL10.GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG, true, TextureFormat.???), // BGRA_8888(0x1A, GL10.GL_RGBA, TextureFormat.???), A_8(0x1B, false, PixelFormat.A_8); // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private final int mID; private final boolean mCompressed; private final PixelFormat mPixelFormat; // =========================================================== // Constructors // =========================================================== private PVRTextureFormat(final int pID, final boolean pCompressed, final PixelFormat pPixelFormat) { this.mID = pID; this.mCompressed = pCompressed; this.mPixelFormat = pPixelFormat; } public static PVRTextureFormat fromID(final int pID) { final PVRTextureFormat[] pvrTextureFormats = PVRTextureFormat.values(); final int pvrTextureFormatCount = pvrTextureFormats.length; for(int i = 0; i < pvrTextureFormatCount; i++) { final PVRTextureFormat pvrTextureFormat = pvrTextureFormats[i]; if(pvrTextureFormat.mID == pID) { return pvrTextureFormat; } } throw new IllegalArgumentException("Unexpected " + PVRTextureFormat.class.getSimpleName() + "-ID: '" + pID + "'."); } public static PVRTextureFormat fromPixelFormat(final PixelFormat pPixelFormat) throws IllegalArgumentException { switch(pPixelFormat) { case RGBA_8888: return PVRTextureFormat.RGBA_8888; case RGBA_4444: return PVRTextureFormat.RGBA_4444; case RGB_565: return PVRTextureFormat.RGB_565; default: throw new IllegalArgumentException("Unsupported " + PixelFormat.class.getName() + ": '" + pPixelFormat + "'."); } } // =========================================================== // Getter & Setter // =========================================================== public int getID() { return this.mID; } public boolean isCompressed() { return this.mCompressed; } public PixelFormat getPixelFormat() { return this.mPixelFormat; } // =========================================================== // Methods from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== } }
Java
package org.anddev.andengine.opengl.texture.compressed.pvr; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.zip.GZIPInputStream; import java.util.zip.Inflater; import java.util.zip.InflaterInputStream; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.util.ArrayUtils; import org.anddev.andengine.util.StreamUtils; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 14:17:23 - 27.07.2011 */ public abstract class PVRCCZTexture extends PVRTexture { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private CCZHeader mCCZHeader; // =========================================================== // Constructors // =========================================================== public PVRCCZTexture(final PVRTextureFormat pPVRTextureFormat) throws IllegalArgumentException, IOException { super(pPVRTextureFormat); } public PVRCCZTexture(final PVRTextureFormat pPVRTextureFormat, final ITextureStateListener pTextureStateListener) throws IllegalArgumentException, IOException { super(pPVRTextureFormat, pTextureStateListener); } public PVRCCZTexture(final PVRTextureFormat pPVRTextureFormat, final TextureOptions pTextureOptions) throws IllegalArgumentException, IOException { super(pPVRTextureFormat, pTextureOptions); } public PVRCCZTexture(final PVRTextureFormat pPVRTextureFormat, final TextureOptions pTextureOptions, final ITextureStateListener pTextureStateListener) throws IllegalArgumentException, IOException { super(pPVRTextureFormat, pTextureOptions, pTextureStateListener); } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override protected final InputStream getInputStream() throws IOException { final InputStream inputStream = this.onGetInputStream(); this.mCCZHeader = new CCZHeader(StreamUtils.streamToBytes(inputStream, CCZHeader.SIZE)); return this.mCCZHeader.getCCZCompressionFormat().wrap(inputStream); } @Override protected ByteBuffer getPVRDataBuffer() throws IOException { final InputStream inputStream = this.getInputStream(); try { final byte[] data = new byte[this.mCCZHeader.getUncompressedSize()]; StreamUtils.copy(inputStream, data); return ByteBuffer.wrap(data); } finally { StreamUtils.close(inputStream); } } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== public static class CCZHeader { // =========================================================== // Constants // =========================================================== public static final byte[] MAGIC_IDENTIFIER = { (byte)'C', (byte)'C', (byte)'Z', (byte)'!' }; public static final int SIZE = 16; // =========================================================== // Fields // =========================================================== private final ByteBuffer mDataByteBuffer; private final CCZCompressionFormat mCCZCompressionFormat; // =========================================================== // Constructors // =========================================================== public CCZHeader(final byte[] pData) { this.mDataByteBuffer = ByteBuffer.wrap(pData); this.mDataByteBuffer.rewind(); this.mDataByteBuffer.order(ByteOrder.BIG_ENDIAN); /* Check magic bytes. */ if(!ArrayUtils.equals(pData, 0, CCZHeader.MAGIC_IDENTIFIER, 0, CCZHeader.MAGIC_IDENTIFIER.length)) { throw new IllegalArgumentException("Invalid " + this.getClass().getSimpleName() + "!"); } // TODO Check the version? this.mCCZCompressionFormat = CCZCompressionFormat.fromID(this.getCCZCompressionFormatID()); } // =========================================================== // Getter & Setter // =========================================================== private short getCCZCompressionFormatID() { return this.mDataByteBuffer.getShort(4); } public CCZCompressionFormat getCCZCompressionFormat() { return this.mCCZCompressionFormat; } public short getVersion() { return this.mDataByteBuffer.getShort(6); } public int getUserdata() { return this.mDataByteBuffer.getInt(8); } public int getUncompressedSize() { return this.mDataByteBuffer.getInt(12); } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== } public static enum CCZCompressionFormat { // =========================================================== // Elements // =========================================================== ZLIB((short)0), BZIP2((short)1), GZIP((short)2), NONE((short)3); // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private final short mID; // =========================================================== // Constructors // =========================================================== private CCZCompressionFormat(final short pID) { this.mID = pID; } public InputStream wrap(final InputStream pInputStream) throws IOException { switch(this) { case GZIP: return new GZIPInputStream(pInputStream); case ZLIB: return new InflaterInputStream(pInputStream, new Inflater()); case NONE: case BZIP2: default: throw new IllegalArgumentException("Unexpected " + CCZCompressionFormat.class.getSimpleName() + ": '" + this + "'."); } } public static CCZCompressionFormat fromID(final short pID) { final CCZCompressionFormat[] cczCompressionFormats = CCZCompressionFormat.values(); final int cczCompressionFormatCount = cczCompressionFormats.length; for(int i = 0; i < cczCompressionFormatCount; i++) { final CCZCompressionFormat cczCompressionFormat = cczCompressionFormats[i]; if(cczCompressionFormat.mID == pID) { return cczCompressionFormat; } } throw new IllegalArgumentException("Unexpected " + CCZCompressionFormat.class.getSimpleName() + "-ID: '" + pID + "'."); } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== } }
Java
package org.anddev.andengine.opengl.texture.compressed.pvr; import java.io.IOException; import java.util.zip.GZIPInputStream; import org.anddev.andengine.opengl.texture.TextureOptions; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 14:31:23 - 15.07.2011 */ public abstract class PVRGZTexture extends PVRTexture { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== public PVRGZTexture(final PVRTextureFormat pPVRTextureFormat) throws IllegalArgumentException, IOException { super(pPVRTextureFormat); } public PVRGZTexture(final PVRTextureFormat pPVRTextureFormat, final ITextureStateListener pTextureStateListener) throws IllegalArgumentException, IOException { super(pPVRTextureFormat, pTextureStateListener); } public PVRGZTexture(final PVRTextureFormat pPVRTextureFormat, final TextureOptions pTextureOptions) throws IllegalArgumentException, IOException { super(pPVRTextureFormat, pTextureOptions); } public PVRGZTexture(final PVRTextureFormat pPVRTextureFormat, final TextureOptions pTextureOptions, final ITextureStateListener pTextureStateListener) throws IllegalArgumentException, IOException { super(pPVRTextureFormat, pTextureOptions, pTextureStateListener); } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override protected GZIPInputStream getInputStream() throws IOException { return new GZIPInputStream(this.onGetInputStream()); } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.opengl.texture.compressed.etc1; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.nio.ByteOrder; import javax.microedition.khronos.opengles.GL10; import org.anddev.andengine.opengl.texture.Texture; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.util.StreamUtils; import android.opengl.ETC1; import android.opengl.ETC1Util; /** * TODO if(!SystemUtils.isAndroidVersionOrHigher(Build.VERSION_CODES.FROYO)) --> Meaningful Exception! * * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 15:32:01 - 13.07.2011 */ public abstract class ETC1Texture extends Texture { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private ETC1TextureHeader mETC1TextureHeader; // =========================================================== // Constructors // =========================================================== public ETC1Texture() throws IOException { this(TextureOptions.DEFAULT, null); } public ETC1Texture(final ITextureStateListener pTextureStateListener) throws IOException { this(TextureOptions.DEFAULT, pTextureStateListener); } public ETC1Texture(final TextureOptions pTextureOptions) throws IOException { this(pTextureOptions, null); } public ETC1Texture(final TextureOptions pTextureOptions, final ITextureStateListener pTextureStateListener) throws IOException { super(PixelFormat.RGB_565, pTextureOptions, pTextureStateListener); InputStream inputStream = null; try { inputStream = this.getInputStream(); this.mETC1TextureHeader = new ETC1TextureHeader(StreamUtils.streamToBytes(inputStream, ETC1.ETC_PKM_HEADER_SIZE)); } finally { StreamUtils.close(inputStream); } } // =========================================================== // Getter & Setter // =========================================================== @Override public int getWidth() { return this.mETC1TextureHeader.getWidth(); } @Override public int getHeight() { return this.mETC1TextureHeader.getHeight(); } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== protected abstract InputStream getInputStream() throws IOException; @Override protected void writeTextureToHardware(final GL10 pGL) throws IOException { final InputStream inputStream = this.getInputStream(); ETC1Util.loadTexture(GL10.GL_TEXTURE_2D, 0, 0, this.mPixelFormat.getGLFormat(), this.mPixelFormat.getGLType(), inputStream); } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== public static class ETC1TextureHeader { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private final ByteBuffer mDataByteBuffer; private final int mWidth; private final int mHeight; // =========================================================== // Constructors // =========================================================== public ETC1TextureHeader(final byte[] pData) { if(pData.length != ETC1.ETC_PKM_HEADER_SIZE) { throw new IllegalArgumentException("Invalid " + this.getClass().getSimpleName() + "!"); } this.mDataByteBuffer = ByteBuffer.allocateDirect(ETC1.ETC_PKM_HEADER_SIZE).order(ByteOrder.nativeOrder()); this.mDataByteBuffer.put(pData, 0, ETC1.ETC_PKM_HEADER_SIZE); this.mDataByteBuffer.position(0); if (!ETC1.isValid(this.mDataByteBuffer)) { throw new IllegalArgumentException("Invalid " + this.getClass().getSimpleName() + "!"); } this.mWidth = ETC1.getWidth(this.mDataByteBuffer); this.mHeight = ETC1.getHeight(this.mDataByteBuffer); } // =========================================================== // Getter & Setter // =========================================================== public int getWidth() { return this.mWidth; } public int getHeight() { return this.mHeight; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== } }
Java
package org.anddev.andengine.opengl.texture.buffer; import org.anddev.andengine.opengl.buffer.BufferObject; import org.anddev.andengine.opengl.font.Font; import org.anddev.andengine.opengl.font.Letter; import org.anddev.andengine.opengl.util.FastFloatBuffer; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 11:05:56 - 03.04.2010 */ public class TextTextureBuffer extends BufferObject { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== public TextTextureBuffer(final int pCapacity, final int pDrawType, final boolean pManaged) { super(pCapacity, pDrawType, pManaged); } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== public synchronized void update(final Font pFont, final String[] pLines) { final FastFloatBuffer textureFloatBuffer = this.getFloatBuffer(); textureFloatBuffer.position(0); final Font font = pFont; final String[] lines = pLines; final int lineCount = lines.length; for (int i = 0; i < lineCount; i++) { final String line = lines[i]; final int lineLength = line.length(); for (int j = 0; j < lineLength; j++) { final Letter letter = font.getLetter(line.charAt(j)); final float letterTextureX = letter.mTextureX; final float letterTextureY = letter.mTextureY; final float letterTextureX2 = letterTextureX + letter.mTextureWidth; final float letterTextureY2 = letterTextureY + letter.mTextureHeight; textureFloatBuffer.put(letterTextureX); textureFloatBuffer.put(letterTextureY); textureFloatBuffer.put(letterTextureX); textureFloatBuffer.put(letterTextureY2); textureFloatBuffer.put(letterTextureX2); textureFloatBuffer.put(letterTextureY2); textureFloatBuffer.put(letterTextureX2); textureFloatBuffer.put(letterTextureY2); textureFloatBuffer.put(letterTextureX2); textureFloatBuffer.put(letterTextureY); textureFloatBuffer.put(letterTextureX); textureFloatBuffer.put(letterTextureY); } } textureFloatBuffer.position(0); this.setHardwareBufferNeedsUpdate(); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.opengl.texture; import java.io.IOException; import java.util.ArrayList; import java.util.HashSet; import javax.microedition.khronos.opengles.GL10; import org.anddev.andengine.util.Debug; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 17:48:46 - 08.03.2010 */ public class TextureManager { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private final HashSet<ITexture> mTexturesManaged = new HashSet<ITexture>(); private final ArrayList<ITexture> mTexturesLoaded = new ArrayList<ITexture>(); private final ArrayList<ITexture> mTexturesToBeLoaded = new ArrayList<ITexture>(); private final ArrayList<ITexture> mTexturesToBeUnloaded = new ArrayList<ITexture>(); // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== protected synchronized void clear() { this.mTexturesToBeLoaded.clear(); this.mTexturesLoaded.clear(); this.mTexturesManaged.clear(); } /** * @param pTexture the {@link ITexture} to be loaded before the very next frame is drawn (Or prevent it from being unloaded then). * @return <code>true</code> when the {@link ITexture} was previously not managed by this {@link TextureManager}, <code>false</code> if it was already managed. */ public synchronized boolean loadTexture(final ITexture pTexture) { if(this.mTexturesManaged.contains(pTexture)) { /* Just make sure it doesn't get deleted. */ this.mTexturesToBeUnloaded.remove(pTexture); return false; } else { this.mTexturesManaged.add(pTexture); this.mTexturesToBeLoaded.add(pTexture); return true; } } /** * @param pTexture the {@link ITexture} to be unloaded before the very next frame is drawn (Or prevent it from being loaded then). * @return <code>true</code> when the {@link ITexture} was already managed by this {@link TextureManager}, <code>false</code> if it was not managed. */ public synchronized boolean unloadTexture(final ITexture pTexture) { if(this.mTexturesManaged.contains(pTexture)) { /* If the Texture is loaded, unload it. * If the Texture is about to be loaded, stop it from being loaded. */ if(this.mTexturesLoaded.contains(pTexture)){ this.mTexturesToBeUnloaded.add(pTexture); } else if(this.mTexturesToBeLoaded.remove(pTexture)){ this.mTexturesManaged.remove(pTexture); } return true; } else { return false; } } public void loadTextures(final ITexture ... pTextures) { for(int i = pTextures.length - 1; i >= 0; i--) { this.loadTexture(pTextures[i]); } } public void unloadTextures(final ITexture ... pTextures) { for(int i = pTextures.length - 1; i >= 0; i--) { this.unloadTexture(pTextures[i]); } } public synchronized void reloadTextures() { final HashSet<ITexture> managedTextures = this.mTexturesManaged; for(final ITexture texture : managedTextures) { // TODO Can the use of the iterator be avoided somehow? texture.setLoadedToHardware(false); } this.mTexturesToBeLoaded.addAll(this.mTexturesLoaded); // TODO Check if addAll uses iterator internally! this.mTexturesLoaded.clear(); this.mTexturesManaged.removeAll(this.mTexturesToBeUnloaded); // TODO Check if removeAll uses iterator internally! this.mTexturesToBeUnloaded.clear(); } public synchronized void updateTextures(final GL10 pGL) { final HashSet<ITexture> texturesManaged = this.mTexturesManaged; final ArrayList<ITexture> texturesLoaded = this.mTexturesLoaded; final ArrayList<ITexture> texturesToBeLoaded = this.mTexturesToBeLoaded; final ArrayList<ITexture> texturesToBeUnloaded = this.mTexturesToBeUnloaded; /* First reload Textures that need to be updated. */ final int textursLoadedCount = texturesLoaded.size(); if(textursLoadedCount > 0){ for(int i = textursLoadedCount - 1; i >= 0; i--){ final ITexture textureToBeReloaded = texturesLoaded.get(i); if(textureToBeReloaded.isUpdateOnHardwareNeeded()){ try { textureToBeReloaded.reloadToHardware(pGL); } catch(IOException e) { Debug.e(e); } } } } /* Then load pending Textures. */ final int texturesToBeLoadedCount = texturesToBeLoaded.size(); if(texturesToBeLoadedCount > 0){ for(int i = texturesToBeLoadedCount - 1; i >= 0; i--){ final ITexture textureToBeLoaded = texturesToBeLoaded.remove(i); if(!textureToBeLoaded.isLoadedToHardware()){ try { textureToBeLoaded.loadToHardware(pGL); } catch(IOException e) { Debug.e(e); } } texturesLoaded.add(textureToBeLoaded); } } /* Then unload pending Textures. */ final int texturesToBeUnloadedCount = texturesToBeUnloaded.size(); if(texturesToBeUnloadedCount > 0){ for(int i = texturesToBeUnloadedCount - 1; i >= 0; i--){ final ITexture textureToBeUnloaded = texturesToBeUnloaded.remove(i); if(textureToBeUnloaded.isLoadedToHardware()){ textureToBeUnloaded.unloadFromHardware(pGL); } texturesLoaded.remove(textureToBeUnloaded); texturesManaged.remove(textureToBeUnloaded); } } /* Finally invoke the GC if anything has changed. */ if(texturesToBeLoadedCount > 0 || texturesToBeUnloadedCount > 0){ System.gc(); } } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.opengl.texture.region.buffer; import org.anddev.andengine.opengl.buffer.BufferObject; import org.anddev.andengine.opengl.texture.ITexture; import org.anddev.andengine.opengl.texture.region.BaseTextureRegion; import org.anddev.andengine.opengl.util.FastFloatBuffer; import org.anddev.andengine.opengl.vertex.SpriteBatchVertexBuffer; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 12:32:14 - 14.06.2011 */ public class SpriteBatchTextureRegionBuffer extends BufferObject { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== protected int mIndex; // =========================================================== // Constructors // =========================================================== public SpriteBatchTextureRegionBuffer(final int pCapacity, final int pDrawType, final boolean pManaged) { super(pCapacity * 2 * SpriteBatchVertexBuffer.VERTICES_PER_RECTANGLE, pDrawType, pManaged); } // =========================================================== // Getter & Setter // =========================================================== public int getIndex() { return this.mIndex; } public void setIndex(final int pIndex) { this.mIndex = pIndex; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== public void add(final BaseTextureRegion pTextureRegion) { final ITexture texture = pTextureRegion.getTexture(); if(texture == null) { // TODO Check really needed? return; } final int x1 = Float.floatToRawIntBits(pTextureRegion.getTextureCoordinateX1()); final int y1 = Float.floatToRawIntBits(pTextureRegion.getTextureCoordinateY1()); final int x2 = Float.floatToRawIntBits(pTextureRegion.getTextureCoordinateX2()); final int y2 = Float.floatToRawIntBits(pTextureRegion.getTextureCoordinateY2()); final int[] bufferData = this.mBufferData; int index = this.mIndex; bufferData[index++] = x1; bufferData[index++] = y1; bufferData[index++] = x1; bufferData[index++] = y2; bufferData[index++] = x2; bufferData[index++] = y1; bufferData[index++] = x2; bufferData[index++] = y1; bufferData[index++] = x1; bufferData[index++] = y2; bufferData[index++] = x2; bufferData[index++] = y2; this.mIndex = index; } public void submit() { final FastFloatBuffer buffer = this.mFloatBuffer; buffer.position(0); buffer.put(this.mBufferData); buffer.position(0); super.setHardwareBufferNeedsUpdate(); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.opengl.texture.region.buffer; import static org.anddev.andengine.opengl.vertex.RectangleVertexBuffer.VERTICES_PER_RECTANGLE; import org.anddev.andengine.opengl.buffer.BufferObject; import org.anddev.andengine.opengl.texture.ITexture; import org.anddev.andengine.opengl.texture.region.BaseTextureRegion; import org.anddev.andengine.opengl.util.FastFloatBuffer; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 19:05:50 - 09.03.2010 */ public class TextureRegionBuffer extends BufferObject { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== protected final BaseTextureRegion mTextureRegion; private boolean mFlippedVertical; private boolean mFlippedHorizontal; // =========================================================== // Constructors // =========================================================== public TextureRegionBuffer(final BaseTextureRegion pBaseTextureRegion, final int pDrawType, final boolean pManaged) { super(2 * VERTICES_PER_RECTANGLE, pDrawType, pManaged); this.mTextureRegion = pBaseTextureRegion; } // =========================================================== // Getter & Setter // =========================================================== public BaseTextureRegion getTextureRegion() { return this.mTextureRegion; } public boolean isFlippedHorizontal() { return this.mFlippedHorizontal; } public void setFlippedHorizontal(final boolean pFlippedHorizontal) { if(this.mFlippedHorizontal != pFlippedHorizontal) { this.mFlippedHorizontal = pFlippedHorizontal; this.update(); } } public boolean isFlippedVertical() { return this.mFlippedVertical; } public void setFlippedVertical(final boolean pFlippedVertical) { if(this.mFlippedVertical != pFlippedVertical) { this.mFlippedVertical = pFlippedVertical; this.update(); } } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== public synchronized void update() { final BaseTextureRegion textureRegion = this.mTextureRegion; final int x1 = Float.floatToRawIntBits(textureRegion.getTextureCoordinateX1()); final int y1 = Float.floatToRawIntBits(textureRegion.getTextureCoordinateY1()); final int x2 = Float.floatToRawIntBits(textureRegion.getTextureCoordinateX2()); final int y2 = Float.floatToRawIntBits(textureRegion.getTextureCoordinateY2()); final int[] bufferData = this.mBufferData; if(this.mFlippedVertical) { if(this.mFlippedHorizontal) { bufferData[0] = x2; bufferData[1] = y2; bufferData[2] = x2; bufferData[3] = y1; bufferData[4] = x1; bufferData[5] = y2; bufferData[6] = x1; bufferData[7] = y1; } else { bufferData[0] = x1; bufferData[1] = y2; bufferData[2] = x1; bufferData[3] = y1; bufferData[4] = x2; bufferData[5] = y2; bufferData[6] = x2; bufferData[7] = y1; } } else { if(this.mFlippedHorizontal) { bufferData[0] = x2; bufferData[1] = y1; bufferData[2] = x2; bufferData[3] = y2; bufferData[4] = x1; bufferData[5] = y1; bufferData[6] = x1; bufferData[7] = y2; } else { bufferData[0] = x1; bufferData[1] = y1; bufferData[2] = x1; bufferData[3] = y2; bufferData[4] = x2; bufferData[5] = y1; bufferData[6] = x2; bufferData[7] = y2; } } final FastFloatBuffer buffer = this.mFloatBuffer; buffer.position(0); buffer.put(bufferData); buffer.position(0); super.setHardwareBufferNeedsUpdate(); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.opengl.texture.region; import org.anddev.andengine.util.Library; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 11:52:26 - 20.08.2010 */ public class TextureRegionLibrary extends Library<BaseTextureRegion> { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== public TextureRegionLibrary(final int pInitialCapacity) { super(pInitialCapacity); } // =========================================================== // Getter & Setter // =========================================================== @Override public TextureRegion get(final int pID) { return (TextureRegion) super.get(pID); } public TiledTextureRegion getTiled(final int pID) { return (TiledTextureRegion) this.mItems.get(pID); } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.opengl.texture.region; import org.anddev.andengine.opengl.texture.ITexture; import org.anddev.andengine.opengl.texture.atlas.ITextureAtlas; import org.anddev.andengine.opengl.texture.source.ITextureAtlasSource; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 18:15:14 - 09.03.2010 */ public class TextureRegionFactory { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== public static TextureRegion extractFromTexture(final ITexture pTexture, final int pTexturePositionX, final int pTexturePositionY, final int pWidth, final int pHeight, final boolean pTextureRegionBufferManaged) { final TextureRegion textureRegion = new TextureRegion(pTexture, pTexturePositionX, pTexturePositionY, pWidth, pHeight); textureRegion.setTextureRegionBufferManaged(pTextureRegionBufferManaged); return textureRegion; } public static <T extends ITextureAtlasSource> TextureRegion createFromSource(final ITextureAtlas<T> pTextureAtlas, final T pTextureAtlasSource, final int pTexturePositionX, final int pTexturePositionY, final boolean pCreateTextureRegionBuffersManaged) { final TextureRegion textureRegion = new TextureRegion(pTextureAtlas, pTexturePositionX, pTexturePositionY, pTextureAtlasSource.getWidth(), pTextureAtlasSource.getHeight()); pTextureAtlas.addTextureAtlasSource(pTextureAtlasSource, textureRegion.getTexturePositionX(), textureRegion.getTexturePositionY()); textureRegion.setTextureRegionBufferManaged(pCreateTextureRegionBuffersManaged); return textureRegion; } public static <T extends ITextureAtlasSource> TiledTextureRegion createTiledFromSource(final ITextureAtlas<T> pTextureAtlas, final T pTextureAtlasSource, final int pTexturePositionX, final int pTexturePositionY, final int pTileColumns, final int pTileRows, final boolean pCreateTextureRegionBuffersManaged) { final TiledTextureRegion tiledTextureRegion = new TiledTextureRegion(pTextureAtlas, pTexturePositionX, pTexturePositionY, pTextureAtlasSource.getWidth(), pTextureAtlasSource.getHeight(), pTileColumns, pTileRows); pTextureAtlas.addTextureAtlasSource(pTextureAtlasSource, tiledTextureRegion.getTexturePositionX(), tiledTextureRegion.getTexturePositionY()); tiledTextureRegion.setTextureRegionBufferManaged(pCreateTextureRegionBuffersManaged); return tiledTextureRegion; } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.opengl.texture.region; import org.anddev.andengine.opengl.texture.ITexture; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 18:14:42 - 09.03.2010 */ public class TiledTextureRegion extends BaseTextureRegion { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private final int mTileColumns; private final int mTileRows; private int mCurrentTileColumn; private int mCurrentTileRow; private final int mTileCount; // =========================================================== // Constructors // =========================================================== public TiledTextureRegion(final ITexture pTexture, final int pTexturePositionX, final int pTexturePositionY, final int pWidth, final int pHeight, final int pTileColumns, final int pTileRows) { super(pTexture, pTexturePositionX, pTexturePositionY, pWidth, pHeight); this.mTileColumns = pTileColumns; this.mTileRows = pTileRows; this.mTileCount = this.mTileColumns * this.mTileRows; this.mCurrentTileColumn = 0; this.mCurrentTileRow = 0; this.initTextureBuffer(); } @Override protected void initTextureBuffer() { if(this.mTileRows != 0 && this.mTileColumns != 0) { super.initTextureBuffer(); } } // =========================================================== // Getter & Setter // =========================================================== public int getTileCount() { return this.mTileCount; } public int getTileWidth() { return super.getWidth() / this.mTileColumns; } public int getTileHeight() { return super.getHeight() / this.mTileRows; } public int getCurrentTileColumn() { return this.mCurrentTileColumn; } public int getCurrentTileRow() { return this.mCurrentTileRow; } public int getCurrentTileIndex() { return this.mCurrentTileRow * this.mTileColumns + this.mCurrentTileColumn; } public void setCurrentTileIndex(final int pTileColumn, final int pTileRow) { if(pTileColumn != this.mCurrentTileColumn || pTileRow != this.mCurrentTileRow) { this.mCurrentTileColumn = pTileColumn; this.mCurrentTileRow = pTileRow; super.updateTextureRegionBuffer(); } } public void setCurrentTileIndex(final int pTileIndex) { if(pTileIndex < this.mTileCount) { final int tileColumns = this.mTileColumns; this.setCurrentTileIndex(pTileIndex % tileColumns, pTileIndex / tileColumns); } } public int getTexturePositionOfCurrentTileX() { return super.getTexturePositionX() + this.mCurrentTileColumn * this.getTileWidth(); } public int getTexturePositionOfCurrentTileY() { return super.getTexturePositionY() + this.mCurrentTileRow * this.getTileHeight(); } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public TiledTextureRegion deepCopy() { final TiledTextureRegion deepCopy = new TiledTextureRegion(this.mTexture, this.getTexturePositionX(), this.getTexturePositionY(), this.getWidth(), this.getHeight(), this.mTileColumns, this.mTileRows); deepCopy.setCurrentTileIndex(this.mCurrentTileColumn, this.mCurrentTileRow); return deepCopy; } @Override public float getTextureCoordinateX1() { return (float)this.getTexturePositionOfCurrentTileX() / this.mTexture.getWidth(); } @Override public float getTextureCoordinateY1() { return (float)this.getTexturePositionOfCurrentTileY() / this.mTexture.getHeight(); } @Override public float getTextureCoordinateX2() { return (float)(this.getTexturePositionOfCurrentTileX() + this.getTileWidth()) / this.mTexture.getWidth(); } @Override public float getTextureCoordinateY2() { return (float)(this.getTexturePositionOfCurrentTileY() + this.getTileHeight()) / this.mTexture.getHeight(); } // =========================================================== // Methods // =========================================================== public void nextTile() { final int tileIndex = (this.getCurrentTileIndex() + 1) % this.getTileCount(); this.setCurrentTileIndex(tileIndex); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.opengl.texture.region; import org.anddev.andengine.opengl.texture.ITexture; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 14:29:59 - 08.03.2010 */ public class TextureRegion extends BaseTextureRegion { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== public TextureRegion(final ITexture pTexture, final int pTexturePositionX, final int pTexturePositionY, final int pWidth, final int pHeight) { super(pTexture, pTexturePositionX, pTexturePositionY, pWidth, pHeight); } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public TextureRegion deepCopy() { return new TextureRegion(this.mTexture, this.mTexturePositionX, this.mTexturePositionY, this.mWidth, this.mHeight); } @Override public float getTextureCoordinateX1() { return (float) this.mTexturePositionX / this.mTexture.getWidth(); } @Override public float getTextureCoordinateY1() { return (float) this.mTexturePositionY / this.mTexture.getHeight(); } @Override public float getTextureCoordinateX2() { return (float) (this.mTexturePositionX + this.mWidth) / this.mTexture.getWidth(); } @Override public float getTextureCoordinateY2() { return (float) (this.mTexturePositionY + this.mHeight) / this.mTexture.getHeight(); } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.opengl.texture.region; import javax.microedition.khronos.opengles.GL10; import javax.microedition.khronos.opengles.GL11; import org.anddev.andengine.opengl.buffer.BufferObjectManager; import org.anddev.andengine.opengl.texture.ITexture; import org.anddev.andengine.opengl.texture.region.buffer.TextureRegionBuffer; import org.anddev.andengine.opengl.util.GLHelper; import org.anddev.andengine.util.modifier.IModifier.DeepCopyNotSupportedException; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 14:29:59 - 08.03.2010 */ public abstract class BaseTextureRegion { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== protected final ITexture mTexture; protected final TextureRegionBuffer mTextureRegionBuffer; protected int mWidth; protected int mHeight; protected int mTexturePositionX; protected int mTexturePositionY; // =========================================================== // Constructors // =========================================================== public BaseTextureRegion(final ITexture pTexture, final int pTexturePositionX, final int pTexturePositionY, final int pWidth, final int pHeight) { this.mTexture = pTexture; this.mTexturePositionX = pTexturePositionX; this.mTexturePositionY = pTexturePositionY; this.mWidth = pWidth; this.mHeight = pHeight; this.mTextureRegionBuffer = new TextureRegionBuffer(this, GL11.GL_STATIC_DRAW, true); this.initTextureBuffer(); } protected void initTextureBuffer() { this.updateTextureRegionBuffer(); } protected abstract BaseTextureRegion deepCopy() throws DeepCopyNotSupportedException; // =========================================================== // Getter & Setter // =========================================================== public int getWidth() { return this.mWidth; } public int getHeight() { return this.mHeight; } public void setWidth(final int pWidth) { this.mWidth = pWidth; this.updateTextureRegionBuffer(); } public void setHeight(final int pHeight) { this.mHeight = pHeight; this.updateTextureRegionBuffer(); } public void setTexturePosition(final int pTexturePositionX, final int pTexturePositionY) { this.mTexturePositionX = pTexturePositionX; this.mTexturePositionY = pTexturePositionY; this.updateTextureRegionBuffer(); } public int getTexturePositionX() { return this.mTexturePositionX; } public int getTexturePositionY() { return this.mTexturePositionY; } public ITexture getTexture() { return this.mTexture; } public TextureRegionBuffer getTextureBuffer() { return this.mTextureRegionBuffer; } public boolean isFlippedHorizontal() { return this.mTextureRegionBuffer.isFlippedHorizontal(); } public void setFlippedHorizontal(final boolean pFlippedHorizontal) { this.mTextureRegionBuffer.setFlippedHorizontal(pFlippedHorizontal); } public boolean isFlippedVertical() { return this.mTextureRegionBuffer.isFlippedVertical(); } public void setFlippedVertical(final boolean pFlippedVertical) { this.mTextureRegionBuffer.setFlippedVertical(pFlippedVertical); } public boolean isTextureRegionBufferManaged() { return this.mTextureRegionBuffer.isManaged(); } /** * @param pVertexBufferManaged when passing <code>true</code> this {@link BaseTextureRegion} will make its {@link TextureRegionBuffer} unload itself from the active {@link BufferObjectManager}, when this {@link BaseTextureRegion} is finalized/garbage-collected.<b><u>WARNING:</u></b> When passing <code>false</code> one needs to take care of that by oneself! */ public void setTextureRegionBufferManaged(final boolean pTextureRegionBufferManaged) { this.mTextureRegionBuffer.setManaged(pTextureRegionBufferManaged); } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== public abstract float getTextureCoordinateX1(); public abstract float getTextureCoordinateY1(); public abstract float getTextureCoordinateX2(); public abstract float getTextureCoordinateY2(); // =========================================================== // Methods // =========================================================== protected void updateTextureRegionBuffer() { this.mTextureRegionBuffer.update(); } public void onApply(final GL10 pGL) { this.mTexture.bind(pGL); if(GLHelper.EXTENSIONS_VERTEXBUFFEROBJECTS) { final GL11 gl11 = (GL11)pGL; this.mTextureRegionBuffer.selectOnHardware(gl11); GLHelper.texCoordZeroPointer(gl11); } else { GLHelper.texCoordPointer(pGL, this.mTextureRegionBuffer.getFloatBuffer()); } } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.opengl.texture.source; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 13:55:12 - 12.07.2011 */ public abstract class BaseTextureAtlasSource implements ITextureAtlasSource { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== protected int mTexturePositionX; protected int mTexturePositionY; // =========================================================== // Constructors // =========================================================== public BaseTextureAtlasSource(final int pTexturePositionX, final int pTexturePositionY) { this.mTexturePositionX = pTexturePositionX; this.mTexturePositionY = pTexturePositionY; } // =========================================================== // Getter & Setter // =========================================================== @Override public int getTexturePositionX() { return this.mTexturePositionX; } @Override public int getTexturePositionY() { return this.mTexturePositionY; } @Override public void setTexturePositionX(final int pTexturePositionX) { this.mTexturePositionX = pTexturePositionX; } @Override public void setTexturePositionY(final int pTexturePositionY) { this.mTexturePositionY = pTexturePositionY; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public String toString() { return this.getClass().getSimpleName() + "( " + this.getWidth() + "x" + this.getHeight() + " @ "+ this.mTexturePositionX + "/" + this.mTexturePositionY + " )"; } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.opengl.texture.source; import org.anddev.andengine.util.modifier.IModifier.DeepCopyNotSupportedException; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 11:46:56 - 12.07.2011 */ public interface ITextureAtlasSource { // =========================================================== // Final Fields // =========================================================== // =========================================================== // Methods // =========================================================== public int getTexturePositionX(); public int getTexturePositionY(); public void setTexturePositionX(final int pTexturePositionX); public void setTexturePositionY(final int pTexturePositionY); public int getWidth(); public int getHeight(); public ITextureAtlasSource deepCopy() throws DeepCopyNotSupportedException; }
Java
package org.anddev.andengine.opengl.texture.atlas; import java.util.ArrayList; import org.anddev.andengine.opengl.texture.Texture; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.source.ITextureAtlasSource; import org.anddev.andengine.util.MathUtils; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 14:22:55 - 14.07.2011 */ public abstract class TextureAtlas<T extends ITextureAtlasSource> extends Texture implements ITextureAtlas<T> { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== protected final int mWidth; protected final int mHeight; protected final ArrayList<T> mTextureAtlasSources = new ArrayList<T>(); // =========================================================== // Constructors // =========================================================== public TextureAtlas(final int pWidth, final int pHeight, final PixelFormat pPixelFormat, final TextureOptions pTextureOptions, final ITextureAtlasStateListener<T> pTextureAtlasStateListener) { super(pPixelFormat, pTextureOptions, pTextureAtlasStateListener); if(!MathUtils.isPowerOfTwo(pWidth) || !MathUtils.isPowerOfTwo(pHeight)) { // TODO GLHelper.EXTENSIONS_NON_POWER_OF_TWO throw new IllegalArgumentException("pWidth and pHeight must be a power of 2!"); } this.mWidth = pWidth; this.mHeight = pHeight; } // =========================================================== // Getter & Setter // =========================================================== @Override public int getWidth() { return this.mWidth; } @Override public int getHeight() { return this.mHeight; } @SuppressWarnings("unchecked") @Override public ITextureAtlasStateListener<T> getTextureStateListener() { return (ITextureAtlasStateListener<T>) super.getTextureStateListener(); } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public void addTextureAtlasSource(final T pTextureAtlasSource, final int pTexturePositionX, final int pTexturePositionY) throws IllegalArgumentException { this.checkTextureAtlasSourcePosition(pTextureAtlasSource, pTexturePositionX, pTexturePositionY); pTextureAtlasSource.setTexturePositionX(pTexturePositionX); pTextureAtlasSource.setTexturePositionY(pTexturePositionY); this.mTextureAtlasSources.add(pTextureAtlasSource); this.mUpdateOnHardwareNeeded = true; } @Override public void removeTextureAtlasSource(final T pTextureAtlasSource, final int pTexturePositionX, final int pTexturePositionY) { final ArrayList<T> textureSources = this.mTextureAtlasSources; for(int i = textureSources.size() - 1; i >= 0; i--) { final T textureSource = textureSources.get(i); if(textureSource == pTextureAtlasSource && textureSource.getTexturePositionX() == pTexturePositionX && textureSource.getTexturePositionY() == pTexturePositionY) { textureSources.remove(i); this.mUpdateOnHardwareNeeded = true; return; } } } @Override public void clearTextureAtlasSources() { this.mTextureAtlasSources.clear(); this.mUpdateOnHardwareNeeded = true; } // =========================================================== // Methods // =========================================================== private void checkTextureAtlasSourcePosition(final T pTextureAtlasSource, final int pTexturePositionX, final int pTexturePositionY) throws IllegalArgumentException { if(pTexturePositionX < 0) { throw new IllegalArgumentException("Illegal negative pTexturePositionX supplied: '" + pTexturePositionX + "'"); } else if(pTexturePositionY < 0) { throw new IllegalArgumentException("Illegal negative pTexturePositionY supplied: '" + pTexturePositionY + "'"); } else if(pTexturePositionX + pTextureAtlasSource.getWidth() > this.getWidth() || pTexturePositionY + pTextureAtlasSource.getHeight() > this.getHeight()) { throw new IllegalArgumentException("Supplied pTextureAtlasSource must not exceed bounds of Texture."); } } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.opengl.texture.atlas; import org.anddev.andengine.opengl.texture.ITexture; import org.anddev.andengine.opengl.texture.source.ITextureAtlasSource; import org.anddev.andengine.util.Debug; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 14:24:29 - 14.07.2011 */ public interface ITextureAtlas<T extends ITextureAtlasSource> extends ITexture { // =========================================================== // Final Fields // =========================================================== // =========================================================== // Methods // =========================================================== public void addTextureAtlasSource(final T pTextureAtlasSource, final int pTexturePositionX, final int pTexturePositionY) throws IllegalArgumentException; public void removeTextureAtlasSource(final T pTextureAtlasSource, final int pTexturePositionX, final int pTexturePositionY); public void clearTextureAtlasSources(); @Override public ITextureAtlasStateListener<T> getTextureStateListener(); // =========================================================== // Inner and Anonymous Classes // =========================================================== public static interface ITextureAtlasStateListener<T extends ITextureAtlasSource> extends ITextureStateListener { // =========================================================== // Final Fields // =========================================================== // =========================================================== // Methods // =========================================================== public void onTextureAtlasSourceLoadExeption(final ITextureAtlas<T> pTextureAtlas, final T pTextureAtlasSource, final Throwable pThrowable); // =========================================================== // Inner and Anonymous Classes // =========================================================== public static class TextureAtlasStateAdapter<T extends ITextureAtlasSource> implements ITextureAtlasStateListener<T> { @Override public void onLoadedToHardware(final ITexture pTexture) { } @Override public void onTextureAtlasSourceLoadExeption(final ITextureAtlas<T> pTextureAtlas, final T pTextureAtlasSource, final Throwable pThrowable) { } @Override public void onUnloadedFromHardware(final ITexture pTexture) { } } public static class DebugTextureAtlasStateListener<T extends ITextureAtlasSource> implements ITextureAtlasStateListener<T> { @Override public void onLoadedToHardware(final ITexture pTexture) { Debug.d("Texture loaded: " + pTexture.toString()); } @Override public void onTextureAtlasSourceLoadExeption(final ITextureAtlas<T> pTextureAtlas, final T pTextureAtlasSource, final Throwable pThrowable) { Debug.e("Exception loading TextureAtlasSource. TextureAtlas: " + pTextureAtlas.toString() + " TextureAtlasSource: " + pTextureAtlasSource.toString(), pThrowable); } @Override public void onUnloadedFromHardware(final ITexture pTexture) { Debug.d("Texture unloaded: " + pTexture.toString()); } } } }
Java
package org.anddev.andengine.opengl.texture.atlas.buildable; import java.io.IOException; import java.util.ArrayList; import javax.microedition.khronos.opengles.GL10; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.ITextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BuildableBitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.buildable.builder.ITextureBuilder; import org.anddev.andengine.opengl.texture.atlas.buildable.builder.ITextureBuilder.TextureAtlasSourcePackingException; import org.anddev.andengine.opengl.texture.source.ITextureAtlasSource; import org.anddev.andengine.util.Callback; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 21:26:38 - 12.08.2010 */ public class BuildableTextureAtlas<T extends ITextureAtlasSource, A extends ITextureAtlas<T>> implements ITextureAtlas<T> { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private final A mTextureAtlas; private final ArrayList<TextureAtlasSourceWithWithLocationCallback<T>> mTextureAtlasSourcesToPlace = new ArrayList<TextureAtlasSourceWithWithLocationCallback<T>>(); // =========================================================== // Constructors // =========================================================== public BuildableTextureAtlas(final A pTextureAtlas) { this.mTextureAtlas = pTextureAtlas; } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public int getWidth() { return this.mTextureAtlas.getWidth(); } @Override public int getHeight() { return this.mTextureAtlas.getHeight(); } @Override public int getHardwareTextureID() { return this.mTextureAtlas.getHardwareTextureID(); } @Override public boolean isLoadedToHardware() { return this.mTextureAtlas.isLoadedToHardware(); } @Override public void setLoadedToHardware(final boolean pLoadedToHardware) { this.mTextureAtlas.setLoadedToHardware(pLoadedToHardware); } @Override public boolean isUpdateOnHardwareNeeded() { return this.mTextureAtlas.isUpdateOnHardwareNeeded(); } @Override public void setUpdateOnHardwareNeeded(final boolean pUpdateOnHardwareNeeded) { this.mTextureAtlas.setUpdateOnHardwareNeeded(pUpdateOnHardwareNeeded); } @Override public void loadToHardware(final GL10 pGL) throws IOException { this.mTextureAtlas.loadToHardware(pGL); } @Override public void unloadFromHardware(final GL10 pGL) { this.mTextureAtlas.unloadFromHardware(pGL); } @Override public void reloadToHardware(final GL10 pGL) throws IOException { this.mTextureAtlas.reloadToHardware(pGL); } @Override public void bind(final GL10 pGL) { this.mTextureAtlas.bind(pGL); } @Override public TextureOptions getTextureOptions() { return this.mTextureAtlas.getTextureOptions(); } /** * Most likely this is not the method you'd want to be using, as the {@link ITextureAtlasSource} won't get packed through this. * @deprecated Use {@link BuildableTextureAtlas#addTextureAtlasSource(ITextureAtlasSource)} instead. */ @Deprecated @Override public void addTextureAtlasSource(final T pTextureAtlasSource, final int pTexturePositionX, final int pTexturePositionY) { this.mTextureAtlas.addTextureAtlasSource(pTextureAtlasSource, pTexturePositionX, pTexturePositionY); } @Override public void removeTextureAtlasSource(final T pTextureAtlasSource, final int pTexturePositionX, final int pTexturePositionY) { this.mTextureAtlas.removeTextureAtlasSource(pTextureAtlasSource, pTexturePositionX, pTexturePositionY); } @Override public void clearTextureAtlasSources() { this.mTextureAtlas.clearTextureAtlasSources(); this.mTextureAtlasSourcesToPlace.clear(); } @Override public boolean hasTextureStateListener() { return this.mTextureAtlas.hasTextureStateListener(); } @Override public ITextureAtlasStateListener<T> getTextureStateListener() { return this.mTextureAtlas.getTextureStateListener(); } // =========================================================== // Methods // =========================================================== /** * When all {@link ITextureAtlasSource}MAGIC_CONSTANT are added you have to call {@link BuildableBitmapTextureAtlas#build(ITextureBuilder)}. * @param pTextureAtlasSource to be added. * @param pTextureRegion */ public void addTextureAtlasSource(final T pTextureAtlasSource, final Callback<T> pCallback) { this.mTextureAtlasSourcesToPlace.add(new TextureAtlasSourceWithWithLocationCallback<T>(pTextureAtlasSource, pCallback)); } /** * Removes a {@link ITextureAtlasSource} before {@link BuildableBitmapTextureAtlas#build(ITextureBuilder)} is called. * @param pBitmapTextureAtlasSource to be removed. */ public void removeTextureAtlasSource(final ITextureAtlasSource pTextureAtlasSource) { final ArrayList<TextureAtlasSourceWithWithLocationCallback<T>> textureSources = this.mTextureAtlasSourcesToPlace; for(int i = textureSources.size() - 1; i >= 0; i--) { final TextureAtlasSourceWithWithLocationCallback<T> textureSource = textureSources.get(i); if(textureSource.mTextureAtlasSource == pTextureAtlasSource) { textureSources.remove(i); this.mTextureAtlas.setUpdateOnHardwareNeeded(true); return; } } } /** * May draw over already added {@link ITextureAtlasSource}MAGIC_CONSTANT. * * @param pTextureAtlasSourcePackingAlgorithm the {@link ITextureBuilder} to use for packing the {@link ITextureAtlasSource} in this {@link BuildableBitmapTextureAtlas}. * @throws TextureAtlasSourcePackingException i.e. when the {@link ITextureAtlasSource}MAGIC_CONSTANT didn't fit into this {@link BuildableBitmapTextureAtlas}. */ public void build(final ITextureBuilder<T, A> pTextureAtlasSourcePackingAlgorithm) throws TextureAtlasSourcePackingException { pTextureAtlasSourcePackingAlgorithm.pack(this.mTextureAtlas, this.mTextureAtlasSourcesToPlace); this.mTextureAtlasSourcesToPlace.clear(); this.mTextureAtlas.setUpdateOnHardwareNeeded(true); } // =========================================================== // Inner and Anonymous Classes // =========================================================== public static class TextureAtlasSourceWithWithLocationCallback<T extends ITextureAtlasSource> { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private final T mTextureAtlasSource; private final Callback<T> mCallback; // =========================================================== // Constructors // =========================================================== public TextureAtlasSourceWithWithLocationCallback(final T pTextureAtlasSource, final Callback<T> pCallback) { this.mTextureAtlasSource = pTextureAtlasSource; this.mCallback = pCallback; } // =========================================================== // Getter & Setter // =========================================================== public Callback<T> getCallback() { return this.mCallback; } public T getTextureAtlasSource() { return this.mTextureAtlasSource; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== } }
Java
package org.anddev.andengine.opengl.texture.atlas.buildable; import org.anddev.andengine.opengl.texture.atlas.ITextureAtlas; import org.anddev.andengine.opengl.texture.region.TextureRegion; import org.anddev.andengine.opengl.texture.region.TiledTextureRegion; import org.anddev.andengine.opengl.texture.source.ITextureAtlasSource; import org.anddev.andengine.util.Callback; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 16:42:08 - 12.07.2011 */ public class BuildableTextureAtlasTextureRegionFactory { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== // =========================================================== // Methods using BuildableBitmapTexture // =========================================================== // =========================================================== // Methods // =========================================================== public static <T extends ITextureAtlasSource, A extends ITextureAtlas<T>> TextureRegion createFromSource(final BuildableTextureAtlas<T, A> pBuildableTextureAtlas, final T pTextureAtlasSource, final boolean pTextureRegionBufferManaged) { final TextureRegion textureRegion = new TextureRegion(pBuildableTextureAtlas, 0, 0, pTextureAtlasSource.getWidth(), pTextureAtlasSource.getHeight()); pBuildableTextureAtlas.addTextureAtlasSource(pTextureAtlasSource, new Callback<T>() { @Override public void onCallback(final T pCallbackValue) { textureRegion.setTexturePosition(pCallbackValue.getTexturePositionX(), pCallbackValue.getTexturePositionY()); } }); textureRegion.setTextureRegionBufferManaged(pTextureRegionBufferManaged); return textureRegion; } public static <T extends ITextureAtlasSource, A extends ITextureAtlas<T>> TiledTextureRegion createTiledFromSource(final BuildableTextureAtlas<T, A> pBuildableTextureAtlas, final T pTextureAtlasSource, final int pTileColumns, final int pTileRows, final boolean pTextureRegionBufferManaged) { final TiledTextureRegion tiledTextureRegion = new TiledTextureRegion(pBuildableTextureAtlas, 0, 0, pTextureAtlasSource.getWidth(), pTextureAtlasSource.getHeight(), pTileColumns, pTileRows); pBuildableTextureAtlas.addTextureAtlasSource(pTextureAtlasSource, new Callback<T>() { @Override public void onCallback(final T pCallbackValue) { tiledTextureRegion.setTexturePosition(pCallbackValue.getTexturePositionX(), pCallbackValue.getTexturePositionY()); } }); tiledTextureRegion.setTextureRegionBufferManaged(pTextureRegionBufferManaged); return tiledTextureRegion; } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.opengl.texture.atlas.buildable.builder; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import org.anddev.andengine.opengl.texture.atlas.ITextureAtlas; import org.anddev.andengine.opengl.texture.atlas.buildable.BuildableTextureAtlas.TextureAtlasSourceWithWithLocationCallback; import org.anddev.andengine.opengl.texture.source.ITextureAtlasSource; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @author Jim Scott (BlackPawn) * @since 16:03:01 - 12.08.2010 * @see http://www.blackpawn.com/texts/lightmaps/default.html */ public class BlackPawnTextureBuilder<T extends ITextureAtlasSource, A extends ITextureAtlas<T>> implements ITextureBuilder<T, A> { // =========================================================== // Constants // =========================================================== private static final Comparator<TextureAtlasSourceWithWithLocationCallback<?>> TEXTURESOURCE_COMPARATOR = new Comparator<TextureAtlasSourceWithWithLocationCallback<?>>() { @Override public int compare(final TextureAtlasSourceWithWithLocationCallback<?> pTextureAtlasSourceWithWithLocationCallbackA, final TextureAtlasSourceWithWithLocationCallback<?> pTextureAtlasSourceWithWithLocationCallbackB) { final int deltaWidth = pTextureAtlasSourceWithWithLocationCallbackB.getTextureAtlasSource().getWidth() - pTextureAtlasSourceWithWithLocationCallbackA.getTextureAtlasSource().getWidth(); if(deltaWidth != 0) { return deltaWidth; } else { return pTextureAtlasSourceWithWithLocationCallbackB.getTextureAtlasSource().getHeight() - pTextureAtlasSourceWithWithLocationCallbackA.getTextureAtlasSource().getHeight(); } } }; // =========================================================== // Fields // =========================================================== private final int mTextureAtlasSourceSpacing; // =========================================================== // Constructors // =========================================================== public BlackPawnTextureBuilder(final int pTextureAtlasSourceSpacing) { this.mTextureAtlasSourceSpacing = pTextureAtlasSourceSpacing; } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public void pack(final A pTextureAtlas, final ArrayList<TextureAtlasSourceWithWithLocationCallback<T>> pTextureAtlasSourcesWithLocationCallback) throws TextureAtlasSourcePackingException { Collections.sort(pTextureAtlasSourcesWithLocationCallback, TEXTURESOURCE_COMPARATOR); final Node root = new Node(new Rect(0, 0, pTextureAtlas.getWidth(), pTextureAtlas.getHeight())); final int textureSourceCount = pTextureAtlasSourcesWithLocationCallback.size(); for(int i = 0; i < textureSourceCount; i++) { final TextureAtlasSourceWithWithLocationCallback<T> textureSourceWithLocationCallback = pTextureAtlasSourcesWithLocationCallback.get(i); final T textureSource = textureSourceWithLocationCallback.getTextureAtlasSource(); final Node inserted = root.insert(textureSource, pTextureAtlas.getWidth(), pTextureAtlas.getHeight(), this.mTextureAtlasSourceSpacing); if(inserted == null) { throw new TextureAtlasSourcePackingException("Could not pack: " + textureSource.toString()); } pTextureAtlas.addTextureAtlasSource(textureSource, inserted.mRect.mLeft, inserted.mRect.mTop); textureSourceWithLocationCallback.getCallback().onCallback(textureSource); } } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== protected static class Rect { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private final int mLeft; private final int mTop; private final int mWidth; private final int mHeight; // =========================================================== // Constructors // =========================================================== public Rect(final int pLeft, final int pTop, final int pWidth, final int pHeight) { this.mLeft = pLeft; this.mTop = pTop; this.mWidth = pWidth; this.mHeight = pHeight; } // =========================================================== // Getter & Setter // =========================================================== public int getWidth() { return this.mWidth; } public int getHeight() { return this.mHeight; } public int getLeft() { return this.mLeft; } public int getTop() { return this.mTop; } public int getRight() { return this.mLeft + this.mWidth; } public int getBottom() { return this.mTop + this.mHeight; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public String toString() { return "@: " + this.mLeft + "/" + this.mTop + " * " + this.mWidth + "x" + this.mHeight; } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== } protected static class Node { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private Node mChildA; private Node mChildB; private final Rect mRect; private ITextureAtlasSource mTextureAtlasSource; // =========================================================== // Constructors // =========================================================== public Node(final int pLeft, final int pTop, final int pWidth, final int pHeight) { this(new Rect(pLeft, pTop, pWidth, pHeight)); } public Node(final Rect pRect) { this.mRect = pRect; } // =========================================================== // Getter & Setter // =========================================================== public Rect getRect() { return this.mRect; } public Node getChildA() { return this.mChildA; } public Node getChildB() { return this.mChildB; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== public Node insert(final ITextureAtlasSource pTextureAtlasSource, final int pTextureWidth, final int pTextureHeight, final int pTextureSpacing) throws IllegalArgumentException { if(this.mChildA != null && this.mChildB != null) { final Node newNode = this.mChildA.insert(pTextureAtlasSource, pTextureWidth, pTextureHeight, pTextureSpacing); if(newNode != null){ return newNode; } else { return this.mChildB.insert(pTextureAtlasSource, pTextureWidth, pTextureHeight, pTextureSpacing); } } else { if(this.mTextureAtlasSource != null) { return null; } final int textureSourceWidth = pTextureAtlasSource.getWidth(); final int textureSourceHeight = pTextureAtlasSource.getHeight(); final int rectWidth = this.mRect.getWidth(); final int rectHeight = this.mRect.getHeight(); if(textureSourceWidth > rectWidth || textureSourceHeight > rectHeight) { return null; } final int textureSourceWidthWithSpacing = textureSourceWidth + pTextureSpacing; final int textureSourceHeightWithSpacing = textureSourceHeight + pTextureSpacing; final int rectLeft = this.mRect.getLeft(); final int rectTop = this.mRect.getTop(); final boolean fitToBottomWithoutSpacing = textureSourceHeight == rectHeight && rectTop + textureSourceHeight == pTextureHeight; final boolean fitToRightWithoutSpacing = textureSourceWidth == rectWidth && rectLeft + textureSourceWidth == pTextureWidth; if(textureSourceWidthWithSpacing == rectWidth){ if(textureSourceHeightWithSpacing == rectHeight) { /* Normal case with padding. */ this.mTextureAtlasSource = pTextureAtlasSource; return this; } else if(fitToBottomWithoutSpacing) { /* Bottom edge of the BitmapTexture. */ this.mTextureAtlasSource = pTextureAtlasSource; return this; } } if(fitToRightWithoutSpacing) { /* Right edge of the BitmapTexture. */ if(textureSourceHeightWithSpacing == rectHeight) { this.mTextureAtlasSource = pTextureAtlasSource; return this; } else if(fitToBottomWithoutSpacing) { /* Bottom edge of the BitmapTexture. */ this.mTextureAtlasSource = pTextureAtlasSource; return this; } else if(textureSourceHeightWithSpacing > rectHeight) { return null; } else { return this.createChildren(pTextureAtlasSource, pTextureWidth, pTextureHeight, pTextureSpacing, rectWidth - textureSourceWidth, rectHeight - textureSourceHeightWithSpacing); } } if(fitToBottomWithoutSpacing) { if(textureSourceWidthWithSpacing == rectWidth) { this.mTextureAtlasSource = pTextureAtlasSource; return this; } else if(textureSourceWidthWithSpacing > rectWidth) { return null; } else { return this.createChildren(pTextureAtlasSource, pTextureWidth, pTextureHeight, pTextureSpacing, rectWidth - textureSourceWidthWithSpacing, rectHeight - textureSourceHeight); } } else if(textureSourceWidthWithSpacing > rectWidth || textureSourceHeightWithSpacing > rectHeight) { return null; } else { return this.createChildren(pTextureAtlasSource, pTextureWidth, pTextureHeight, pTextureSpacing, rectWidth - textureSourceWidthWithSpacing, rectHeight - textureSourceHeightWithSpacing); } } } private Node createChildren(final ITextureAtlasSource pTextureAtlasSource, final int pTextureWidth, final int pTextureHeight, final int pTextureSpacing, final int pDeltaWidth, final int pDeltaHeight) { final Rect rect = this.mRect; if(pDeltaWidth >= pDeltaHeight) { /* Split using a vertical axis. */ this.mChildA = new Node( rect.getLeft(), rect.getTop(), pTextureAtlasSource.getWidth() + pTextureSpacing, rect.getHeight() ); this.mChildB = new Node( rect.getLeft() + (pTextureAtlasSource.getWidth() + pTextureSpacing), rect.getTop(), rect.getWidth() - (pTextureAtlasSource.getWidth() + pTextureSpacing), rect.getHeight() ); } else { /* Split using a horizontal axis. */ this.mChildA = new Node( rect.getLeft(), rect.getTop(), rect.getWidth(), pTextureAtlasSource.getHeight() + pTextureSpacing ); this.mChildB = new Node( rect.getLeft(), rect.getTop() + (pTextureAtlasSource.getHeight() + pTextureSpacing), rect.getWidth(), rect.getHeight() - (pTextureAtlasSource.getHeight() + pTextureSpacing) ); } return this.mChildA.insert(pTextureAtlasSource, pTextureWidth, pTextureHeight, pTextureSpacing); } // =========================================================== // Inner and Anonymous Classes // =========================================================== } }
Java
package org.anddev.andengine.opengl.texture.atlas.buildable.builder; import java.util.ArrayList; import org.anddev.andengine.opengl.texture.atlas.ITextureAtlas; import org.anddev.andengine.opengl.texture.atlas.buildable.BuildableTextureAtlas.TextureAtlasSourceWithWithLocationCallback; import org.anddev.andengine.opengl.texture.source.ITextureAtlasSource; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 15:59:14 - 12.08.2010 */ public interface ITextureBuilder<T extends ITextureAtlasSource, A extends ITextureAtlas<T>> { // =========================================================== // Final Fields // =========================================================== // =========================================================== // Methods // =========================================================== public void pack(final A pTextureAtlas, final ArrayList<TextureAtlasSourceWithWithLocationCallback<T>> pTextureAtlasSourcesWithLocationCallback) throws TextureAtlasSourcePackingException; // =========================================================== // Inner and Anonymous Classes // =========================================================== public static class TextureAtlasSourcePackingException extends Exception { // =========================================================== // Constants // =========================================================== private static final long serialVersionUID = 4700734424214372671L; // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== public TextureAtlasSourcePackingException(final String pMessage) { super(pMessage); } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== } }
Java
package org.anddev.andengine.opengl.texture.atlas.bitmap; import java.util.ArrayList; import javax.microedition.khronos.opengles.GL10; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.TextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.source.IBitmapTextureAtlasSource; import org.anddev.andengine.opengl.texture.bitmap.BitmapTexture.BitmapTextureFormat; import org.anddev.andengine.opengl.texture.source.ITextureAtlasSource; import org.anddev.andengine.opengl.util.GLHelper; import org.anddev.andengine.util.Debug; import android.graphics.Bitmap; import android.graphics.Bitmap.Config; import android.opengl.GLUtils; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 14:55:02 - 08.03.2010 */ public class BitmapTextureAtlas extends TextureAtlas<IBitmapTextureAtlasSource> { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private final BitmapTextureFormat mBitmapTextureFormat; // =========================================================== // Constructors // =========================================================== /** * Uses {@link BitmapTextureFormat#RGBA_8888}. * * @param pWidth must be a power of 2 (i.e. 32, 64, 128, 256, 512, 1024). * @param pHeight must be a power of 2 (i.e. 32, 64, 128, 256, 512, 1024). */ public BitmapTextureAtlas(final int pWidth, final int pHeight) { this(pWidth, pHeight, BitmapTextureFormat.RGBA_8888); } /** * @param pWidth must be a power of 2 (i.e. 32, 64, 128, 256, 512, 1024). * @param pHeight must be a power of 2 (i.e. 32, 64, 128, 256, 512, 1024). * @param pBitmapTextureFormat use {@link BitmapTextureFormat#RGBA_8888} for {@link BitmapTextureAtlas}MAGIC_CONSTANT with transparency and {@link BitmapTextureFormat#RGB_565} for {@link BitmapTextureAtlas}MAGIC_CONSTANT without transparency. */ public BitmapTextureAtlas(final int pWidth, final int pHeight, final BitmapTextureFormat pBitmapTextureFormat) { this(pWidth, pHeight, pBitmapTextureFormat, TextureOptions.DEFAULT, null); } /** * Uses {@link BitmapTextureFormat#RGBA_8888}. * * @param pWidth must be a power of 2 (i.e. 32, 64, 128, 256, 512, 1024). * @param pHeight must be a power of 2 (i.e. 32, 64, 128, 256, 512, 1024). * @param pTextureStateListener to be informed when this {@link BitmapTextureAtlas} is loaded, unloaded or a {@link ITextureAtlasSource} failed to load. */ public BitmapTextureAtlas(final int pWidth, final int pHeight, final ITextureAtlasStateListener<IBitmapTextureAtlasSource> pTextureAtlasStateListener) { this(pWidth, pHeight, BitmapTextureFormat.RGBA_8888, TextureOptions.DEFAULT, pTextureAtlasStateListener); } /** * @param pWidth must be a power of 2 (i.e. 32, 64, 128, 256, 512, 1024). * @param pHeight must be a power of 2 (i.e. 32, 64, 128, 256, 512, 1024). * @param pBitmapTextureFormat use {@link BitmapTextureFormat#RGBA_8888} for {@link BitmapTextureAtlas}MAGIC_CONSTANT with transparency and {@link BitmapTextureFormat#RGB_565} for {@link BitmapTextureAtlas}MAGIC_CONSTANT without transparency. * @param pTextureAtlasStateListener to be informed when this {@link BitmapTextureAtlas} is loaded, unloaded or a {@link ITextureAtlasSource} failed to load. */ public BitmapTextureAtlas(final int pWidth, final int pHeight, final BitmapTextureFormat pBitmapTextureFormat, final ITextureAtlasStateListener<IBitmapTextureAtlasSource> pTextureAtlasStateListener) { this(pWidth, pHeight, pBitmapTextureFormat, TextureOptions.DEFAULT, pTextureAtlasStateListener); } /** * Uses {@link BitmapTextureFormat#RGBA_8888}. * * @param pWidth must be a power of 2 (i.e. 32, 64, 128, 256, 512, 1024). * @param pHeight must be a power of 2 (i.e. 32, 64, 128, 256, 512, 1024). * @param pTextureOptions the (quality) settings of the BitmapTexture. */ public BitmapTextureAtlas(final int pWidth, final int pHeight, final TextureOptions pTextureOptions) throws IllegalArgumentException { this(pWidth, pHeight, BitmapTextureFormat.RGBA_8888, pTextureOptions, null); } /** * @param pWidth must be a power of 2 (i.e. 32, 64, 128, 256, 512, 1024). * @param pHeight must be a power of 2 (i.e. 32, 64, 128, 256, 512, 1024). * @param pBitmapTextureFormat use {@link BitmapTextureFormat#RGBA_8888} for {@link BitmapTextureAtlas}MAGIC_CONSTANT with transparency and {@link BitmapTextureFormat#RGB_565} for {@link BitmapTextureAtlas}MAGIC_CONSTANT without transparency. * @param pTextureOptions the (quality) settings of the BitmapTexture. */ public BitmapTextureAtlas(final int pWidth, final int pHeight, final BitmapTextureFormat pBitmapTextureFormat, final TextureOptions pTextureOptions) throws IllegalArgumentException { this(pWidth, pHeight, pBitmapTextureFormat, pTextureOptions, null); } /** * Uses {@link BitmapTextureFormat#RGBA_8888}. * * @param pWidth must be a power of 2 (i.e. 32, 64, 128, 256, 512, 1024). * @param pHeight must be a power of 2 (i.e. 32, 64, 128, 256, 512, 1024). * @param pTextureOptions the (quality) settings of the BitmapTexture. * @param pTextureAtlasStateListener to be informed when this {@link BitmapTextureAtlas} is loaded, unloaded or a {@link ITextureAtlasSource} failed to load. */ public BitmapTextureAtlas(final int pWidth, final int pHeight, final TextureOptions pTextureOptions, final ITextureAtlasStateListener<IBitmapTextureAtlasSource> pTextureAtlasStateListener) throws IllegalArgumentException { this(pWidth, pHeight, BitmapTextureFormat.RGBA_8888, pTextureOptions, pTextureAtlasStateListener); } /** * @param pWidth must be a power of 2 (i.e. 32, 64, 128, 256, 512, 1024). * @param pHeight must be a power of 2 (i.e. 32, 64, 128, 256, 512, 1024). * @param pBitmapTextureFormat use {@link BitmapTextureFormat#RGBA_8888} for {@link BitmapTextureAtlas}MAGIC_CONSTANT with transparency and {@link BitmapTextureFormat#RGB_565} for {@link BitmapTextureAtlas}MAGIC_CONSTANT without transparency. * @param pTextureOptions the (quality) settings of the BitmapTexture. * @param pTextureAtlasStateListener to be informed when this {@link BitmapTextureAtlas} is loaded, unloaded or a {@link ITextureAtlasSource} failed to load. */ public BitmapTextureAtlas(final int pWidth, final int pHeight, final BitmapTextureFormat pBitmapTextureFormat, final TextureOptions pTextureOptions, final ITextureAtlasStateListener<IBitmapTextureAtlasSource> pTextureAtlasStateListener) throws IllegalArgumentException { super(pWidth, pHeight, pBitmapTextureFormat.getPixelFormat(), pTextureOptions, pTextureAtlasStateListener); this.mBitmapTextureFormat = pBitmapTextureFormat; } // =========================================================== // Getter & Setter // =========================================================== public BitmapTextureFormat getBitmapTextureFormat() { return this.mBitmapTextureFormat; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== @Override protected void writeTextureToHardware(final GL10 pGL) { final Config bitmapConfig = this.mBitmapTextureFormat.getBitmapConfig(); final int glFormat = this.mPixelFormat.getGLFormat(); final int glType = this.mPixelFormat.getGLType(); final boolean preMultipyAlpha = this.mTextureOptions.mPreMultipyAlpha; final ArrayList<IBitmapTextureAtlasSource> textureSources = this.mTextureAtlasSources; final int textureSourceCount = textureSources.size(); for(int j = 0; j < textureSourceCount; j++) { final IBitmapTextureAtlasSource bitmapTextureAtlasSource = textureSources.get(j); if(bitmapTextureAtlasSource != null) { final Bitmap bitmap = bitmapTextureAtlasSource.onLoadBitmap(bitmapConfig); try { if(bitmap == null) { throw new IllegalArgumentException(bitmapTextureAtlasSource.getClass().getSimpleName() + ": " + bitmapTextureAtlasSource.toString() + " returned a null Bitmap."); } if(preMultipyAlpha) { GLUtils.texSubImage2D(GL10.GL_TEXTURE_2D, 0, bitmapTextureAtlasSource.getTexturePositionX(), bitmapTextureAtlasSource.getTexturePositionY(), bitmap, glFormat, glType); } else { GLHelper.glTexSubImage2D(pGL, GL10.GL_TEXTURE_2D, 0, bitmapTextureAtlasSource.getTexturePositionX(), bitmapTextureAtlasSource.getTexturePositionY(), bitmap, this.mPixelFormat); } bitmap.recycle(); } catch (final IllegalArgumentException iae) { // TODO Load some static checkerboard or so to visualize that loading the texture has failed. //private Buffer createImage(final int width, final int height) { // final int stride = 3 * width; // final ByteBuffer image = ByteBuffer.allocateDirect(height * stride) // .order(ByteOrder.nativeOrder()); // // // Fill with a pretty "munching squares" pattern: // for (int t = 0; t < height; t++) { // final byte red = (byte) (255 - 2 * t); // final byte green = (byte) (2 * t); // final byte blue = 0; // for (int x = 0; x < width; x++) { // final int y = x ^ t; // image.position(stride * y + x * 3); // image.put(red); // image.put(green); // image.put(blue); // } // } // image.position(0); // return image; //} Debug.e("Error loading: " + bitmapTextureAtlasSource.toString(), iae); if(this.getTextureStateListener() != null) { this.getTextureStateListener().onTextureAtlasSourceLoadExeption(this, bitmapTextureAtlasSource, iae); } else { throw iae; } } } } } @Override protected void bindTextureOnHardware(final GL10 pGL) { super.bindTextureOnHardware(pGL); final PixelFormat pixelFormat = this.mBitmapTextureFormat.getPixelFormat(); final int glFormat = pixelFormat.getGLFormat(); final int glType = pixelFormat.getGLType(); pGL.glTexImage2D(GL10.GL_TEXTURE_2D, 0, glFormat, this.mWidth, this.mHeight, 0, glFormat, glType, null); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.opengl.texture.atlas.bitmap; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.source.IBitmapTextureAtlasSource; import org.anddev.andengine.opengl.texture.bitmap.BitmapTexture.BitmapTextureFormat; import org.anddev.andengine.opengl.texture.region.TextureRegion; import org.anddev.andengine.util.MathUtils; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 09:38:51 - 03.05.2010 */ public class BitmapTextureAtlasFactory { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== public static BitmapTextureAtlas createForTextureAtlasSourceSize(final BitmapTextureFormat pBitmapTextureFormat, final TextureRegion pTextureRegion) { return BitmapTextureAtlasFactory.createForTextureRegionSize(pBitmapTextureFormat, pTextureRegion, TextureOptions.DEFAULT); } public static BitmapTextureAtlas createForTextureRegionSize(final BitmapTextureFormat pBitmapTextureFormat, final TextureRegion pTextureRegion, final TextureOptions pTextureOptions) { final int textureRegionWidth = pTextureRegion.getWidth(); final int textureRegionHeight = pTextureRegion.getHeight(); return new BitmapTextureAtlas(MathUtils.nextPowerOfTwo(textureRegionWidth), MathUtils.nextPowerOfTwo(textureRegionHeight), pBitmapTextureFormat, pTextureOptions); } public static BitmapTextureAtlas createForTextureAtlasSourceSize(final BitmapTextureFormat pBitmapTextureFormat, final IBitmapTextureAtlasSource pBitmapTextureAtlasSource) { return BitmapTextureAtlasFactory.createForTextureAtlasSourceSize(pBitmapTextureFormat, pBitmapTextureAtlasSource, TextureOptions.DEFAULT); } public static BitmapTextureAtlas createForTextureAtlasSourceSize(final BitmapTextureFormat pBitmapTextureFormat, final IBitmapTextureAtlasSource pBitmapTextureAtlasSource, final TextureOptions pTextureOptions) { final int textureSourceWidth = pBitmapTextureAtlasSource.getWidth(); final int textureSourceHeight = pBitmapTextureAtlasSource.getHeight(); return new BitmapTextureAtlas(MathUtils.nextPowerOfTwo(textureSourceWidth), MathUtils.nextPowerOfTwo(textureSourceHeight), pBitmapTextureFormat, pTextureOptions); } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.opengl.texture.atlas.bitmap; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.source.IBitmapTextureAtlasSource; import org.anddev.andengine.opengl.texture.atlas.buildable.BuildableTextureAtlas; import org.anddev.andengine.opengl.texture.bitmap.BitmapTexture.BitmapTextureFormat; import org.anddev.andengine.opengl.texture.source.ITextureAtlasSource; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 15:51:46 - 12.07.2011 */ public class BuildableBitmapTextureAtlas extends BuildableTextureAtlas<IBitmapTextureAtlasSource, BitmapTextureAtlas> { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== /** * Uses {@link BitmapTextureFormat#RGBA_8888}. * * @param pWidth must be a power of 2 (i.e. 32, 64, 128, 256, 512, 1024). * @param pHeight must be a power of 2 (i.e. 32, 64, 128, 256, 512, 1024). */ public BuildableBitmapTextureAtlas(final int pWidth, final int pHeight) { this(pWidth, pHeight, BitmapTextureFormat.RGBA_8888); } /** * @param pWidth must be a power of 2 (i.e. 32, 64, 128, 256, 512, 1024). * @param pHeight must be a power of 2 (i.e. 32, 64, 128, 256, 512, 1024). * @param pBitmapTextureFormat use {@link BitmapTextureFormat#RGBA_8888} for {@link BitmapTextureAtlas}MAGIC_CONSTANT with transparency and {@link BitmapTextureFormat#RGB_565} for {@link BitmapTextureAtlas}MAGIC_CONSTANT without transparency. */ public BuildableBitmapTextureAtlas(final int pWidth, final int pHeight, final BitmapTextureFormat pBitmapTextureFormat) { this(pWidth, pHeight, pBitmapTextureFormat, TextureOptions.DEFAULT, null); } /** * Uses {@link BitmapTextureFormat#RGBA_8888}. * * @param pWidth must be a power of 2 (i.e. 32, 64, 128, 256, 512, 1024). * @param pHeight must be a power of 2 (i.e. 32, 64, 128, 256, 512, 1024). * @param pTextureStateListener to be informed when this {@link BitmapTextureAtlas} is loaded, unloaded or a {@link ITextureAtlasSource} failed to load. */ public BuildableBitmapTextureAtlas(final int pWidth, final int pHeight, final ITextureAtlasStateListener<IBitmapTextureAtlasSource> pTextureStateListener) { this(pWidth, pHeight, BitmapTextureFormat.RGBA_8888, TextureOptions.DEFAULT, pTextureStateListener); } /** * @param pWidth must be a power of 2 (i.e. 32, 64, 128, 256, 512, 1024). * @param pHeight must be a power of 2 (i.e. 32, 64, 128, 256, 512, 1024). * @param pBitmapTextureFormat use {@link BitmapTextureFormat#RGBA_8888} for {@link BitmapTextureAtlas}MAGIC_CONSTANT with transparency and {@link BitmapTextureFormat#RGB_565} for {@link BitmapTextureAtlas}MAGIC_CONSTANT without transparency. * @param pTextureStateListener to be informed when this {@link BitmapTextureAtlas} is loaded, unloaded or a {@link ITextureAtlasSource} failed to load. */ public BuildableBitmapTextureAtlas(final int pWidth, final int pHeight, final BitmapTextureFormat pBitmapTextureFormat, final ITextureAtlasStateListener<IBitmapTextureAtlasSource> pTextureStateListener) { this(pWidth, pHeight, pBitmapTextureFormat, TextureOptions.DEFAULT, pTextureStateListener); } /** * Uses {@link BitmapTextureFormat#RGBA_8888}. * * @param pWidth must be a power of 2 (i.e. 32, 64, 128, 256, 512, 1024). * @param pHeight must be a power of 2 (i.e. 32, 64, 128, 256, 512, 1024). * @param pTextureOptions the (quality) settings of the BitmapTexture. */ public BuildableBitmapTextureAtlas(final int pWidth, final int pHeight, final TextureOptions pTextureOptions) throws IllegalArgumentException { this(pWidth, pHeight, BitmapTextureFormat.RGBA_8888, pTextureOptions, null); } /** * @param pWidth must be a power of 2 (i.e. 32, 64, 128, 256, 512, 1024). * @param pHeight must be a power of 2 (i.e. 32, 64, 128, 256, 512, 1024). * @param pBitmapTextureFormat use {@link BitmapTextureFormat#RGBA_8888} for {@link BitmapTextureAtlas}MAGIC_CONSTANT with transparency and {@link BitmapTextureFormat#RGB_565} for {@link BitmapTextureAtlas}MAGIC_CONSTANT without transparency. * @param pTextureOptions the (quality) settings of the BitmapTexture. */ public BuildableBitmapTextureAtlas(final int pWidth, final int pHeight, final BitmapTextureFormat pBitmapTextureFormat, final TextureOptions pTextureOptions) throws IllegalArgumentException { this(pWidth, pHeight, pBitmapTextureFormat, pTextureOptions, null); } /** * Uses {@link BitmapTextureFormat#RGBA_8888}. * * @param pWidth must be a power of 2 (i.e. 32, 64, 128, 256, 512, 1024). * @param pHeight must be a power of 2 (i.e. 32, 64, 128, 256, 512, 1024). * @param pTextureOptions the (quality) settings of the BitmapTexture. * @param pTextureStateListener to be informed when this {@link BitmapTextureAtlas} is loaded, unloaded or a {@link ITextureAtlasSource} failed to load. */ public BuildableBitmapTextureAtlas(final int pWidth, final int pHeight, final TextureOptions pTextureOptions, final ITextureAtlasStateListener<IBitmapTextureAtlasSource> pTextureStateListener) throws IllegalArgumentException { this(pWidth, pHeight, BitmapTextureFormat.RGBA_8888, pTextureOptions, pTextureStateListener); } /** * @param pWidth must be a power of 2 (i.e. 32, 64, 128, 256, 512, 1024). * @param pHeight must be a power of 2 (i.e. 32, 64, 128, 256, 512, 1024). * @param pBitmapTextureFormat use {@link BitmapTextureFormat#RGBA_8888} for {@link BitmapTextureAtlas}MAGIC_CONSTANT with transparency and {@link BitmapTextureFormat#RGB_565} for {@link BitmapTextureAtlas}MAGIC_CONSTANT without transparency. * @param pTextureOptions the (quality) settings of the BitmapTexture. * @param pTextureStateListener to be informed when this {@link BitmapTextureAtlas} is loaded, unloaded or a {@link ITextureAtlasSource} failed to load. */ public BuildableBitmapTextureAtlas(final int pWidth, final int pHeight, final BitmapTextureFormat pBitmapTextureFormat, final TextureOptions pTextureOptions, final ITextureAtlasStateListener<IBitmapTextureAtlasSource> pTextureStateListener) throws IllegalArgumentException { super(new BitmapTextureAtlas(pWidth, pHeight, pBitmapTextureFormat, pTextureOptions, pTextureStateListener)); } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.opengl.texture.atlas.bitmap.source; import org.anddev.andengine.opengl.texture.source.BaseTextureAtlasSource; import org.anddev.andengine.util.Debug; import android.graphics.Bitmap; import android.graphics.Bitmap.Config; import android.graphics.Canvas; import android.graphics.Picture; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 12:52:58 - 21.05.2011 */ public abstract class PictureBitmapTextureAtlasSource extends BaseTextureAtlasSource implements IBitmapTextureAtlasSource { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== protected final Picture mPicture; protected final int mWidth; protected final int mHeight; // =========================================================== // Constructors // =========================================================== public PictureBitmapTextureAtlasSource(final Picture pPicture) { this(pPicture, 0, 0); } public PictureBitmapTextureAtlasSource(final Picture pPicture, final int pTexturePositionX, final int pTexturePositionY) { this(pPicture, pTexturePositionX, pTexturePositionY, pPicture.getWidth(), pPicture.getHeight()); } public PictureBitmapTextureAtlasSource(final Picture pPicture, final int pTexturePositionX, final int pTexturePositionY, final float pScale) { this(pPicture, pTexturePositionX, pTexturePositionY, Math.round(pPicture.getWidth() * pScale), Math.round(pPicture.getHeight() * pScale)); } public PictureBitmapTextureAtlasSource(final Picture pPicture, final int pTexturePositionX, final int pTexturePositionY, final int pWidth, final int pHeight) { super(pTexturePositionX, pTexturePositionY); this.mPicture = pPicture; this.mWidth = pWidth; this.mHeight = pHeight; } @Override public abstract PictureBitmapTextureAtlasSource deepCopy(); // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public int getWidth() { return this.mWidth; } @Override public int getHeight() { return this.mHeight; } @Override public Bitmap onLoadBitmap(final Config pBitmapConfig) { final Picture picture = this.mPicture; if(picture == null) { Debug.e("Failed loading Bitmap in PictureBitmapTextureAtlasSource."); return null; } final Bitmap bitmap = Bitmap.createBitmap(this.mWidth, this.mHeight, pBitmapConfig); final Canvas canvas = new Canvas(bitmap); final float scaleX = (float)this.mWidth / this.mPicture.getWidth(); final float scaleY = (float)this.mHeight / this.mPicture.getHeight(); canvas.scale(scaleX, scaleY, 0, 0); picture.draw(canvas); return bitmap; } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.opengl.texture.atlas.bitmap.source; import org.anddev.andengine.opengl.texture.source.ITextureAtlasSource; import android.graphics.Bitmap; import android.graphics.Bitmap.Config; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 12:08:52 - 09.03.2010 */ public interface IBitmapTextureAtlasSource extends ITextureAtlasSource { // =========================================================== // Final Fields // =========================================================== // =========================================================== // Methods // =========================================================== @Override public IBitmapTextureAtlasSource deepCopy(); public Bitmap onLoadBitmap(final Config pBitmapConfig); }
Java
package org.anddev.andengine.opengl.texture.atlas.bitmap.source; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import org.anddev.andengine.opengl.texture.source.BaseTextureAtlasSource; import org.anddev.andengine.util.Debug; import org.anddev.andengine.util.StreamUtils; import android.graphics.Bitmap; import android.graphics.Bitmap.Config; import android.graphics.BitmapFactory; /** * * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 16:39:22 - 10.08.2010 */ public class FileBitmapTextureAtlasSource extends BaseTextureAtlasSource implements IBitmapTextureAtlasSource { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private final int mWidth; private final int mHeight; private final File mFile; // =========================================================== // Constructors // =========================================================== public FileBitmapTextureAtlasSource(final File pFile) { this(pFile, 0, 0); } public FileBitmapTextureAtlasSource(final File pFile, final int pTexturePositionX, final int pTexturePositionY) { super(pTexturePositionX, pTexturePositionY); this.mFile = pFile; final BitmapFactory.Options decodeOptions = new BitmapFactory.Options(); decodeOptions.inJustDecodeBounds = true; InputStream in = null; try { in = new FileInputStream(pFile); BitmapFactory.decodeStream(in, null, decodeOptions); } catch (final IOException e) { Debug.e("Failed loading Bitmap in FileBitmapTextureAtlasSource. File: " + pFile, e); } finally { StreamUtils.close(in); } this.mWidth = decodeOptions.outWidth; this.mHeight = decodeOptions.outHeight; } FileBitmapTextureAtlasSource(final File pFile, final int pTexturePositionX, final int pTexturePositionY, final int pWidth, final int pHeight) { super(pTexturePositionX, pTexturePositionY); this.mFile = pFile; this.mWidth = pWidth; this.mHeight = pHeight; } @Override public FileBitmapTextureAtlasSource deepCopy() { return new FileBitmapTextureAtlasSource(this.mFile, this.mTexturePositionX, this.mTexturePositionY, this.mWidth, this.mHeight); } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public int getWidth() { return this.mWidth; } @Override public int getHeight() { return this.mHeight; } @Override public Bitmap onLoadBitmap(final Config pBitmapConfig) { final BitmapFactory.Options decodeOptions = new BitmapFactory.Options(); decodeOptions.inPreferredConfig = pBitmapConfig; InputStream in = null; try { in = new FileInputStream(this.mFile); return BitmapFactory.decodeStream(in, null, decodeOptions); } catch (final IOException e) { Debug.e("Failed loading Bitmap in " + this.getClass().getSimpleName() + ". File: " + this.mFile, e); return null; } finally { StreamUtils.close(in); } } @Override public String toString() { return this.getClass().getSimpleName() + "(" + this.mFile + ")"; } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.opengl.texture.atlas.bitmap.source; import org.anddev.andengine.opengl.texture.source.BaseTextureAtlasSource; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Bitmap.Config; import android.graphics.BitmapFactory; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 15:07:23 - 09.03.2010 */ public class ResourceBitmapTextureAtlasSource extends BaseTextureAtlasSource implements IBitmapTextureAtlasSource { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private final int mWidth; private final int mHeight; private final int mDrawableResourceID; private final Context mContext; // =========================================================== // Constructors // =========================================================== public ResourceBitmapTextureAtlasSource(final Context pContext, final int pDrawableResourceID) { this(pContext, pDrawableResourceID, 0, 0); } public ResourceBitmapTextureAtlasSource(final Context pContext, final int pDrawableResourceID, final int pTexturePositionX, final int pTexturePositionY) { super(pTexturePositionX, pTexturePositionY); this.mContext = pContext; this.mDrawableResourceID = pDrawableResourceID; final BitmapFactory.Options decodeOptions = new BitmapFactory.Options(); decodeOptions.inJustDecodeBounds = true; // decodeOptions.inScaled = false; // TODO Check how this behaves with drawable-""/nodpi/ldpi/mdpi/hdpi folders BitmapFactory.decodeResource(pContext.getResources(), pDrawableResourceID, decodeOptions); this.mWidth = decodeOptions.outWidth; this.mHeight = decodeOptions.outHeight; } protected ResourceBitmapTextureAtlasSource(final Context pContext, final int pDrawableResourceID, final int pTexturePositionX, final int pTexturePositionY, final int pWidth, final int pHeight) { super(pTexturePositionX, pTexturePositionY); this.mContext = pContext; this.mDrawableResourceID = pDrawableResourceID; this.mWidth = pWidth; this.mHeight = pHeight; } @Override public ResourceBitmapTextureAtlasSource deepCopy() { return new ResourceBitmapTextureAtlasSource(this.mContext, this.mDrawableResourceID, this.mTexturePositionX, this.mTexturePositionY, this.mWidth, this.mHeight); } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public int getWidth() { return this.mWidth; } @Override public int getHeight() { return this.mHeight; } @Override public Bitmap onLoadBitmap(final Config pBitmapConfig) { final BitmapFactory.Options decodeOptions = new BitmapFactory.Options(); decodeOptions.inPreferredConfig = pBitmapConfig; // decodeOptions.inScaled = false; // TODO Check how this behaves with drawable-""/nodpi/ldpi/mdpi/hdpi folders return BitmapFactory.decodeResource(this.mContext.getResources(), this.mDrawableResourceID, decodeOptions); } @Override public String toString() { return this.getClass().getSimpleName() + "(" + this.mDrawableResourceID + ")"; } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.opengl.texture.atlas.bitmap.source; import java.io.IOException; import java.io.InputStream; import org.anddev.andengine.opengl.texture.source.BaseTextureAtlasSource; import org.anddev.andengine.util.Debug; import org.anddev.andengine.util.StreamUtils; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Bitmap.Config; import android.graphics.BitmapFactory; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 12:07:52 - 09.03.2010 */ public class AssetBitmapTextureAtlasSource extends BaseTextureAtlasSource implements IBitmapTextureAtlasSource { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private final int mWidth; private final int mHeight; private final String mAssetPath; private final Context mContext; // =========================================================== // Constructors // =========================================================== public AssetBitmapTextureAtlasSource(final Context pContext, final String pAssetPath) { this(pContext, pAssetPath, 0, 0); } public AssetBitmapTextureAtlasSource(final Context pContext, final String pAssetPath, final int pTexturePositionX, final int pTexturePositionY) { super(pTexturePositionX, pTexturePositionY); this.mContext = pContext; this.mAssetPath = pAssetPath; final BitmapFactory.Options decodeOptions = new BitmapFactory.Options(); decodeOptions.inJustDecodeBounds = true; InputStream in = null; try { in = pContext.getAssets().open(pAssetPath); BitmapFactory.decodeStream(in, null, decodeOptions); } catch (final IOException e) { Debug.e("Failed loading Bitmap in AssetBitmapTextureAtlasSource. AssetPath: " + pAssetPath, e); } finally { StreamUtils.close(in); } this.mWidth = decodeOptions.outWidth; this.mHeight = decodeOptions.outHeight; } AssetBitmapTextureAtlasSource(final Context pContext, final String pAssetPath, final int pTexturePositionX, final int pTexturePositionY, final int pWidth, final int pHeight) { super(pTexturePositionX, pTexturePositionY); this.mContext = pContext; this.mAssetPath = pAssetPath; this.mWidth = pWidth; this.mHeight = pHeight; } @Override public AssetBitmapTextureAtlasSource deepCopy() { return new AssetBitmapTextureAtlasSource(this.mContext, this.mAssetPath, this.mTexturePositionX, this.mTexturePositionY, this.mWidth, this.mHeight); } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public int getWidth() { return this.mWidth; } @Override public int getHeight() { return this.mHeight; } @Override public Bitmap onLoadBitmap(final Config pBitmapConfig) { InputStream in = null; try { final BitmapFactory.Options decodeOptions = new BitmapFactory.Options(); decodeOptions.inPreferredConfig = pBitmapConfig; in = this.mContext.getAssets().open(this.mAssetPath); return BitmapFactory.decodeStream(in, null, decodeOptions); } catch (final IOException e) { Debug.e("Failed loading Bitmap in " + this.getClass().getSimpleName() + ". AssetPath: " + this.mAssetPath, e); return null; } finally { StreamUtils.close(in); } } @Override public String toString() { return this.getClass().getSimpleName() + "(" + this.mAssetPath + ")"; } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.opengl.texture.atlas.bitmap.source; import org.anddev.andengine.opengl.texture.source.BaseTextureAtlasSource; import android.graphics.Bitmap; import android.graphics.Bitmap.Config; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 20:20:36 - 08.08.2010 */ public class EmptyBitmapTextureAtlasSource extends BaseTextureAtlasSource implements IBitmapTextureAtlasSource { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private final int mWidth; private final int mHeight; // =========================================================== // Constructors // =========================================================== public EmptyBitmapTextureAtlasSource(final int pWidth, final int pHeight) { this(0, 0, pWidth, pHeight); } public EmptyBitmapTextureAtlasSource(final int pTexturePositionX, final int pTexturePositionY, final int pWidth, final int pHeight) { super(pTexturePositionX, pTexturePositionY); this.mWidth = pWidth; this.mHeight = pHeight; } @Override public EmptyBitmapTextureAtlasSource deepCopy() { return new EmptyBitmapTextureAtlasSource(this.mTexturePositionX, this.mTexturePositionY, this.mWidth, this.mHeight); } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public int getWidth() { return this.mWidth; } @Override public int getHeight() { return this.mHeight; } @Override public Bitmap onLoadBitmap(final Config pBitmapConfig) { return Bitmap.createBitmap(this.mWidth, this.mHeight, pBitmapConfig); } @Override public String toString() { return this.getClass().getSimpleName() + "(" + this.mWidth + " x " + this.mHeight + ")"; } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.opengl.texture.atlas.bitmap.source; import java.io.File; import org.anddev.andengine.util.FileUtils; import android.content.Context; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 10:03:19 - 30.05.2011 */ public class ExternalStorageFileBitmapTextureAtlasSource extends FileBitmapTextureAtlasSource { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== public ExternalStorageFileBitmapTextureAtlasSource(final Context pContext, final String pFilePath) { super(new File(FileUtils.getAbsolutePathOnExternalStorage(pContext, pFilePath))); } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.opengl.texture.atlas.bitmap.source; import java.io.File; import org.anddev.andengine.util.FileUtils; import android.content.Context; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 10:01:19 - 30.05.2011 */ public class InternalStorageFileBitmapTextureAtlasSource extends FileBitmapTextureAtlasSource { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== public InternalStorageFileBitmapTextureAtlasSource(final Context pContext, final String pFilePath) { super(new File(FileUtils.getAbsolutePathOnInternalStorage(pContext, pFilePath))); } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.opengl.texture.atlas.bitmap.source.decorator; import org.anddev.andengine.opengl.texture.atlas.bitmap.source.IBitmapTextureAtlasSource; import org.anddev.andengine.opengl.texture.atlas.bitmap.source.decorator.shape.IBitmapTextureAtlasSourceDecoratorShape; import android.graphics.Paint.Style; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 18:08:00 - 05.11.2010 */ public class FillBitmapTextureAtlasSourceDecorator extends BaseShapeBitmapTextureAtlasSourceDecorator { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== protected final int mFillColor; // =========================================================== // Constructors // =========================================================== public FillBitmapTextureAtlasSourceDecorator(final IBitmapTextureAtlasSource pBitmapTextureAtlasSource, final IBitmapTextureAtlasSourceDecoratorShape pBitmapTextureAtlasSourceDecoratorShape, final int pFillColor) { this(pBitmapTextureAtlasSource, pBitmapTextureAtlasSourceDecoratorShape, pFillColor, null); } public FillBitmapTextureAtlasSourceDecorator(final IBitmapTextureAtlasSource pBitmapTextureAtlasSource, final IBitmapTextureAtlasSourceDecoratorShape pBitmapTextureAtlasSourceDecoratorShape, final int pFillColor, final TextureAtlasSourceDecoratorOptions pTextureAtlasSourceDecoratorOptions) { super(pBitmapTextureAtlasSource, pBitmapTextureAtlasSourceDecoratorShape, pTextureAtlasSourceDecoratorOptions); this.mFillColor = pFillColor; this.mPaint.setStyle(Style.FILL); this.mPaint.setColor(pFillColor); } @Override public FillBitmapTextureAtlasSourceDecorator deepCopy() { return new FillBitmapTextureAtlasSourceDecorator(this.mBitmapTextureAtlasSource, this.mBitmapTextureAtlasSourceDecoratorShape, this.mFillColor, this.mTextureAtlasSourceDecoratorOptions); } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.opengl.texture.atlas.bitmap.source.decorator; import org.anddev.andengine.opengl.texture.atlas.bitmap.source.IBitmapTextureAtlasSource; import org.anddev.andengine.opengl.texture.atlas.bitmap.source.decorator.shape.IBitmapTextureAtlasSourceDecoratorShape; import android.graphics.LinearGradient; import android.graphics.Paint.Style; import android.graphics.Shader.TileMode; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 19:21:24 - 05.11.2010 */ public class LinearGradientFillBitmapTextureAtlasSourceDecorator extends BaseShapeBitmapTextureAtlasSourceDecorator { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== protected final LinearGradientDirection mLinearGradientDirection; protected final int[] mColors; protected final float[] mPositions; // =========================================================== // Constructors // =========================================================== public LinearGradientFillBitmapTextureAtlasSourceDecorator(final IBitmapTextureAtlasSource pBitmapTextureAtlasSource, final IBitmapTextureAtlasSourceDecoratorShape pBitmapTextureAtlasSourceDecoratorShape, final int pFromColor, final int pToColor, final LinearGradientDirection pLinearGradientDirection) { this(pBitmapTextureAtlasSource, pBitmapTextureAtlasSourceDecoratorShape, pFromColor, pToColor, pLinearGradientDirection, null); } public LinearGradientFillBitmapTextureAtlasSourceDecorator(final IBitmapTextureAtlasSource pBitmapTextureAtlasSource, final IBitmapTextureAtlasSourceDecoratorShape pBitmapTextureAtlasSourceDecoratorShape, final int pFromColor, final int pToColor, final LinearGradientDirection pLinearGradientDirection, final TextureAtlasSourceDecoratorOptions pTextureAtlasSourceDecoratorOptions) { this(pBitmapTextureAtlasSource, pBitmapTextureAtlasSourceDecoratorShape, new int[] { pFromColor, pToColor }, null, pLinearGradientDirection, pTextureAtlasSourceDecoratorOptions); } public LinearGradientFillBitmapTextureAtlasSourceDecorator(final IBitmapTextureAtlasSource pBitmapTextureAtlasSource, final IBitmapTextureAtlasSourceDecoratorShape pBitmapTextureAtlasSourceDecoratorShape, final int[] pColors, final float[] pPositions, final LinearGradientDirection pLinearGradientDirection) { this(pBitmapTextureAtlasSource, pBitmapTextureAtlasSourceDecoratorShape, pColors, pPositions, pLinearGradientDirection, null); } public LinearGradientFillBitmapTextureAtlasSourceDecorator(final IBitmapTextureAtlasSource pBitmapTextureAtlasSource, final IBitmapTextureAtlasSourceDecoratorShape pBitmapTextureAtlasSourceDecoratorShape, final int[] pColors, final float[] pPositions, final LinearGradientDirection pLinearGradientDirection, final TextureAtlasSourceDecoratorOptions pTextureAtlasSourceDecoratorOptions) { super(pBitmapTextureAtlasSource, pBitmapTextureAtlasSourceDecoratorShape, pTextureAtlasSourceDecoratorOptions); this.mColors = pColors; this.mPositions = pPositions; this.mLinearGradientDirection = pLinearGradientDirection; this.mPaint.setStyle(Style.FILL); final int right = pBitmapTextureAtlasSource.getWidth() - 1; final int bottom = pBitmapTextureAtlasSource.getHeight() - 1; final float fromX = pLinearGradientDirection.getFromX(right); final float fromY = pLinearGradientDirection.getFromY(bottom); final float toX = pLinearGradientDirection.getToX(right); final float toY = pLinearGradientDirection.getToY(bottom); this.mPaint.setShader(new LinearGradient(fromX, fromY, toX, toY, pColors, pPositions, TileMode.CLAMP)); } @Override public LinearGradientFillBitmapTextureAtlasSourceDecorator deepCopy() { return new LinearGradientFillBitmapTextureAtlasSourceDecorator(this.mBitmapTextureAtlasSource, this.mBitmapTextureAtlasSourceDecoratorShape, this.mColors, this.mPositions, this.mLinearGradientDirection, this.mTextureAtlasSourceDecoratorOptions); } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== public static enum LinearGradientDirection { // =========================================================== // Elements // =========================================================== LEFT_TO_RIGHT(1, 0, 0, 0), RIGHT_TO_LEFT(0, 0, 1, 0), BOTTOM_TO_TOP(0, 1, 0, 0), TOP_TO_BOTTOM(0, 0, 0, 1), TOPLEFT_TO_BOTTOMRIGHT(0, 0, 1, 1), BOTTOMRIGHT_TO_TOPLEFT(1, 1, 0, 0), TOPRIGHT_TO_BOTTOMLEFT(1, 0, 0, 1), BOTTOMLEFT_TO_TOPRIGHT(0, 1, 1, 0); // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private final int mFromX; private final int mFromY; private final int mToX; private final int mToY; // =========================================================== // Constructors // =========================================================== private LinearGradientDirection(final int pFromX, final int pFromY, final int pToX, final int pToY) { this.mFromX = pFromX; this.mFromY = pFromY; this.mToX = pToX; this.mToY = pToY; } // =========================================================== // Getter & Setter // =========================================================== final int getFromX(int pRight) { return this.mFromX * pRight; } final int getFromY(int pBottom) { return this.mFromY * pBottom; } final int getToX(int pRight) { return this.mToX * pRight; } final int getToY(int pBottom) { return this.mToY * pBottom; } // =========================================================== // Methods from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== } }
Java
package org.anddev.andengine.opengl.texture.atlas.bitmap.source.decorator; import org.anddev.andengine.opengl.texture.atlas.bitmap.source.IBitmapTextureAtlasSource; import org.anddev.andengine.opengl.texture.atlas.bitmap.source.decorator.shape.IBitmapTextureAtlasSourceDecoratorShape; import android.graphics.Paint.Style; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 18:07:55 - 05.11.2010 */ public class OutlineBitmapTextureAtlasSourceDecorator extends BaseShapeBitmapTextureAtlasSourceDecorator { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== protected final int mOutlineColor; // =========================================================== // Constructors // =========================================================== public OutlineBitmapTextureAtlasSourceDecorator(final IBitmapTextureAtlasSource pBitmapTextureAtlasSource, final IBitmapTextureAtlasSourceDecoratorShape pBitmapTextureAtlasSourceDecoratorShape, final int pOutlineColor) { this(pBitmapTextureAtlasSource, pBitmapTextureAtlasSourceDecoratorShape, pOutlineColor, null); } public OutlineBitmapTextureAtlasSourceDecorator(final IBitmapTextureAtlasSource pBitmapTextureAtlasSource, final IBitmapTextureAtlasSourceDecoratorShape pBitmapTextureAtlasSourceDecoratorShape, final int pOutlineColor, final TextureAtlasSourceDecoratorOptions pTextureAtlasSourceDecoratorOptions) { super(pBitmapTextureAtlasSource, pBitmapTextureAtlasSourceDecoratorShape, pTextureAtlasSourceDecoratorOptions); this.mOutlineColor = pOutlineColor; this.mPaint.setStyle(Style.STROKE); this.mPaint.setColor(pOutlineColor); } @Override public OutlineBitmapTextureAtlasSourceDecorator deepCopy() { return new OutlineBitmapTextureAtlasSourceDecorator(this.mBitmapTextureAtlasSource, this.mBitmapTextureAtlasSourceDecoratorShape, this.mOutlineColor, this.mTextureAtlasSourceDecoratorOptions); } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.opengl.texture.atlas.bitmap.source.decorator; import org.anddev.andengine.opengl.texture.atlas.bitmap.source.IBitmapTextureAtlasSource; import org.anddev.andengine.opengl.texture.source.BaseTextureAtlasSource; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Bitmap.Config; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 16:43:29 - 06.08.2010 */ public abstract class BaseBitmapTextureAtlasSourceDecorator extends BaseTextureAtlasSource implements IBitmapTextureAtlasSource { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== protected final IBitmapTextureAtlasSource mBitmapTextureAtlasSource; protected TextureAtlasSourceDecoratorOptions mTextureAtlasSourceDecoratorOptions; protected Paint mPaint = new Paint(); // =========================================================== // Constructors // =========================================================== public BaseBitmapTextureAtlasSourceDecorator(final IBitmapTextureAtlasSource pBitmapTextureAtlasSource) { this(pBitmapTextureAtlasSource, new TextureAtlasSourceDecoratorOptions()); } public BaseBitmapTextureAtlasSourceDecorator(final IBitmapTextureAtlasSource pBitmapTextureAtlasSource, final TextureAtlasSourceDecoratorOptions pTextureAtlasSourceDecoratorOptions) { super(pBitmapTextureAtlasSource.getTexturePositionX(), pBitmapTextureAtlasSource.getTexturePositionY()); this.mBitmapTextureAtlasSource = pBitmapTextureAtlasSource; this.mTextureAtlasSourceDecoratorOptions = (pTextureAtlasSourceDecoratorOptions == null) ? new TextureAtlasSourceDecoratorOptions() : pTextureAtlasSourceDecoratorOptions; this.mPaint.setAntiAlias(this.mTextureAtlasSourceDecoratorOptions.getAntiAliasing()); } @Override public abstract BaseBitmapTextureAtlasSourceDecorator deepCopy(); // =========================================================== // Getter & Setter // =========================================================== public Paint getPaint() { return this.mPaint; } public void setPaint(final Paint pPaint) { this.mPaint = pPaint; } public TextureAtlasSourceDecoratorOptions getTextureAtlasSourceDecoratorOptions() { return this.mTextureAtlasSourceDecoratorOptions; } public void setTextureAtlasSourceDecoratorOptions(final TextureAtlasSourceDecoratorOptions pTextureAtlasSourceDecoratorOptions) { this.mTextureAtlasSourceDecoratorOptions = pTextureAtlasSourceDecoratorOptions; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== protected abstract void onDecorateBitmap(final Canvas pCanvas); @Override public int getWidth() { return this.mBitmapTextureAtlasSource.getWidth(); } @Override public int getHeight() { return this.mBitmapTextureAtlasSource.getHeight(); } @Override public Bitmap onLoadBitmap(final Config pBitmapConfig) { final Bitmap bitmap = this.ensureLoadedBitmapIsMutable(this.mBitmapTextureAtlasSource.onLoadBitmap(pBitmapConfig)); final Canvas canvas = new Canvas(bitmap); this.onDecorateBitmap(canvas); return bitmap; } // =========================================================== // Methods // =========================================================== private Bitmap ensureLoadedBitmapIsMutable(final Bitmap pBitmap) { if(pBitmap.isMutable()) { return pBitmap; } else { final Bitmap mutableBitmap = pBitmap.copy(pBitmap.getConfig(), true); pBitmap.recycle(); return mutableBitmap; } } // =========================================================== // Inner and Anonymous Classes // =========================================================== public static class TextureAtlasSourceDecoratorOptions { // =========================================================== // Constants // =========================================================== public static final TextureAtlasSourceDecoratorOptions DEFAULT = new TextureAtlasSourceDecoratorOptions(); // =========================================================== // Fields // =========================================================== private float mInsetLeft = 0.25f; private float mInsetRight = 0.25f; private float mInsetTop = 0.25f; private float mInsetBottom = 0.25f; private boolean mAntiAliasing; // =========================================================== // Constructors // =========================================================== protected TextureAtlasSourceDecoratorOptions deepCopy() { final TextureAtlasSourceDecoratorOptions textureSourceDecoratorOptions = new TextureAtlasSourceDecoratorOptions(); textureSourceDecoratorOptions.setInsets(this.mInsetLeft, this.mInsetTop, this.mInsetRight, this.mInsetBottom); textureSourceDecoratorOptions.setAntiAliasing(this.mAntiAliasing); return textureSourceDecoratorOptions; } // =========================================================== // Getter & Setter // =========================================================== public boolean getAntiAliasing() { return this.mAntiAliasing; } public float getInsetLeft() { return this.mInsetLeft; } public float getInsetRight() { return this.mInsetRight; } public float getInsetTop() { return this.mInsetTop; } public float getInsetBottom() { return this.mInsetBottom; } public TextureAtlasSourceDecoratorOptions setAntiAliasing(final boolean pAntiAliasing) { this.mAntiAliasing = pAntiAliasing; return this; } public TextureAtlasSourceDecoratorOptions setInsetLeft(final float pInsetLeft) { this.mInsetLeft = pInsetLeft; return this; } public TextureAtlasSourceDecoratorOptions setInsetRight(final float pInsetRight) { this.mInsetRight = pInsetRight; return this; } public TextureAtlasSourceDecoratorOptions setInsetTop(final float pInsetTop) { this.mInsetTop = pInsetTop; return this; } public TextureAtlasSourceDecoratorOptions setInsetBottom(final float pInsetBottom) { this.mInsetBottom = pInsetBottom; return this; } public TextureAtlasSourceDecoratorOptions setInsets(final float pInsets) { return this.setInsets(pInsets, pInsets, pInsets, pInsets); } public TextureAtlasSourceDecoratorOptions setInsets(final float pInsetLeft, final float pInsetTop, final float pInsetRight, final float pInsetBottom) { this.mInsetLeft = pInsetLeft; this.mInsetTop = pInsetTop; this.mInsetRight = pInsetRight; this.mInsetBottom = pInsetBottom; return this; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== } }
Java
package org.anddev.andengine.opengl.texture.atlas.bitmap.source.decorator; import org.anddev.andengine.opengl.texture.atlas.bitmap.source.IBitmapTextureAtlasSource; import org.anddev.andengine.opengl.texture.atlas.bitmap.source.decorator.shape.IBitmapTextureAtlasSourceDecoratorShape; import org.anddev.andengine.util.ArrayUtils; import android.graphics.Paint.Style; import android.graphics.RadialGradient; import android.graphics.Shader.TileMode; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 19:21:24 - 05.11.2010 */ public class RadialGradientFillBitmapTextureAtlasSourceDecorator extends BaseShapeBitmapTextureAtlasSourceDecorator { // =========================================================== // Constants // =========================================================== private static final float[] POSITIONS_DEFAULT = new float[] { 0.0f, 1.0f }; // =========================================================== // Fields // =========================================================== protected final RadialGradientDirection mRadialGradientDirection; protected final int[] mColors; protected final float[] mPositions; // =========================================================== // Constructors // =========================================================== public RadialGradientFillBitmapTextureAtlasSourceDecorator(final IBitmapTextureAtlasSource pBitmapTextureAtlasSource, final IBitmapTextureAtlasSourceDecoratorShape pBitmapTextureAtlasSourceDecoratorShape, final int pFromColor, final int pToColor, final RadialGradientDirection pRadialGradientDirection) { this(pBitmapTextureAtlasSource, pBitmapTextureAtlasSourceDecoratorShape, pFromColor, pToColor, pRadialGradientDirection, null); } public RadialGradientFillBitmapTextureAtlasSourceDecorator(final IBitmapTextureAtlasSource pBitmapTextureAtlasSource, final IBitmapTextureAtlasSourceDecoratorShape pBitmapTextureAtlasSourceDecoratorShape, final int pFromColor, final int pToColor, final RadialGradientDirection pRadialGradientDirection, final TextureAtlasSourceDecoratorOptions pTextureAtlasSourceDecoratorOptions) { this(pBitmapTextureAtlasSource, pBitmapTextureAtlasSourceDecoratorShape, new int[] { pFromColor, pToColor }, POSITIONS_DEFAULT, pRadialGradientDirection, pTextureAtlasSourceDecoratorOptions); } public RadialGradientFillBitmapTextureAtlasSourceDecorator(final IBitmapTextureAtlasSource pBitmapTextureAtlasSource, final IBitmapTextureAtlasSourceDecoratorShape pBitmapTextureAtlasSourceDecoratorShape, final int[] pColors, final float[] pPositions, final RadialGradientDirection pRadialGradientDirection) { this(pBitmapTextureAtlasSource, pBitmapTextureAtlasSourceDecoratorShape, pColors, pPositions, pRadialGradientDirection, null); } public RadialGradientFillBitmapTextureAtlasSourceDecorator(final IBitmapTextureAtlasSource pBitmapTextureAtlasSource, final IBitmapTextureAtlasSourceDecoratorShape pBitmapTextureAtlasSourceDecoratorShape, final int[] pColors, final float[] pPositions, final RadialGradientDirection pRadialGradientDirection, final TextureAtlasSourceDecoratorOptions pTextureAtlasSourceDecoratorOptions) { super(pBitmapTextureAtlasSource, pBitmapTextureAtlasSourceDecoratorShape, pTextureAtlasSourceDecoratorOptions); this.mColors = pColors; this.mPositions = pPositions; this.mRadialGradientDirection = pRadialGradientDirection; this.mPaint.setStyle(Style.FILL); final int width = pBitmapTextureAtlasSource.getWidth(); final int height = pBitmapTextureAtlasSource.getHeight(); final float centerX = width * 0.5f; final float centerY = height * 0.5f; final float radius = Math.max(centerX, centerY); switch(pRadialGradientDirection) { case INSIDE_OUT: this.mPaint.setShader(new RadialGradient(centerX, centerY, radius, pColors, pPositions, TileMode.CLAMP)); break; case OUTSIDE_IN: ArrayUtils.reverse(pColors); this.mPaint.setShader(new RadialGradient(centerX, centerY, radius, pColors, pPositions, TileMode.CLAMP)); break; } } @Override public RadialGradientFillBitmapTextureAtlasSourceDecorator deepCopy() { return new RadialGradientFillBitmapTextureAtlasSourceDecorator(this.mBitmapTextureAtlasSource, this.mBitmapTextureAtlasSourceDecoratorShape, this.mColors, this.mPositions, this.mRadialGradientDirection, this.mTextureAtlasSourceDecoratorOptions); } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== public static enum RadialGradientDirection { // =========================================================== // Elements // =========================================================== INSIDE_OUT, OUTSIDE_IN; // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== } }
Java
package org.anddev.andengine.opengl.texture.atlas.bitmap.source.decorator.shape; import org.anddev.andengine.opengl.texture.atlas.bitmap.source.decorator.BaseBitmapTextureAtlasSourceDecorator.TextureAtlasSourceDecoratorOptions; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.RectF; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 12:50:09 - 04.01.2011 */ public class RoundedRectangleBitmapTextureAtlasSourceDecoratorShape implements IBitmapTextureAtlasSourceDecoratorShape { // =========================================================== // Constants // =========================================================== private static final float CORNER_RADIUS_DEFAULT = 1; // =========================================================== // Fields // =========================================================== private final RectF mRectF = new RectF(); private final float mCornerRadiusX; private final float mCornerRadiusY; private static RoundedRectangleBitmapTextureAtlasSourceDecoratorShape sDefaultInstance; // =========================================================== // Constructors // =========================================================== public RoundedRectangleBitmapTextureAtlasSourceDecoratorShape() { this(CORNER_RADIUS_DEFAULT, CORNER_RADIUS_DEFAULT); } public RoundedRectangleBitmapTextureAtlasSourceDecoratorShape(final float pCornerRadiusX, final float pCornerRadiusY) { this.mCornerRadiusX = pCornerRadiusX; this.mCornerRadiusY = pCornerRadiusY; } public static RoundedRectangleBitmapTextureAtlasSourceDecoratorShape getDefaultInstance() { if(sDefaultInstance == null) { sDefaultInstance = new RoundedRectangleBitmapTextureAtlasSourceDecoratorShape(); } return sDefaultInstance; } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public void onDecorateBitmap(final Canvas pCanvas, final Paint pPaint, final TextureAtlasSourceDecoratorOptions pDecoratorOptions) { final float left = pDecoratorOptions.getInsetLeft(); final float top = pDecoratorOptions.getInsetTop(); final float right = pCanvas.getWidth() - pDecoratorOptions.getInsetRight(); final float bottom = pCanvas.getHeight() - pDecoratorOptions.getInsetBottom(); this.mRectF.set(left, top, right, bottom); pCanvas.drawRoundRect(this.mRectF, this.mCornerRadiusX, this.mCornerRadiusY, pPaint); } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.opengl.texture.atlas.bitmap.source.decorator.shape; import org.anddev.andengine.opengl.texture.atlas.bitmap.source.decorator.BaseBitmapTextureAtlasSourceDecorator.TextureAtlasSourceDecoratorOptions; import android.graphics.Canvas; import android.graphics.Paint; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 12:53:13 - 04.01.2011 */ public class CircleBitmapTextureAtlasSourceDecoratorShape implements IBitmapTextureAtlasSourceDecoratorShape { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private static CircleBitmapTextureAtlasSourceDecoratorShape sDefaultInstance; // =========================================================== // Constructors // =========================================================== public CircleBitmapTextureAtlasSourceDecoratorShape() { } public static CircleBitmapTextureAtlasSourceDecoratorShape getDefaultInstance() { if(sDefaultInstance == null) { sDefaultInstance = new CircleBitmapTextureAtlasSourceDecoratorShape(); } return sDefaultInstance; } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public void onDecorateBitmap(final Canvas pCanvas, final Paint pPaint, final TextureAtlasSourceDecoratorOptions pDecoratorOptions) { final float width = pCanvas.getWidth() - pDecoratorOptions.getInsetLeft() - pDecoratorOptions.getInsetRight(); final float height = pCanvas.getHeight() - pDecoratorOptions.getInsetTop() - pDecoratorOptions.getInsetBottom(); final float centerX = (pCanvas.getWidth() + pDecoratorOptions.getInsetLeft() - pDecoratorOptions.getInsetRight()) * 0.5f; final float centerY = (pCanvas.getHeight() + pDecoratorOptions.getInsetTop() - pDecoratorOptions.getInsetBottom()) * 0.5f; final float radius = Math.min(width * 0.5f, height * 0.5f); pCanvas.drawCircle(centerX, centerY, radius, pPaint); } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.opengl.texture.atlas.bitmap.source.decorator.shape; import org.anddev.andengine.opengl.texture.atlas.bitmap.source.decorator.BaseBitmapTextureAtlasSourceDecorator.TextureAtlasSourceDecoratorOptions; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.RectF; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 12:52:55 - 04.01.2011 */ public class EllipseBitmapTextureAtlasSourceDecoratorShape implements IBitmapTextureAtlasSourceDecoratorShape { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private static EllipseBitmapTextureAtlasSourceDecoratorShape sDefaultInstance; private final RectF mRectF = new RectF(); // =========================================================== // Constructors // =========================================================== public EllipseBitmapTextureAtlasSourceDecoratorShape() { } public static EllipseBitmapTextureAtlasSourceDecoratorShape getDefaultInstance() { if(sDefaultInstance == null) { sDefaultInstance = new EllipseBitmapTextureAtlasSourceDecoratorShape(); } return sDefaultInstance; } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public void onDecorateBitmap(final Canvas pCanvas, final Paint pPaint, final TextureAtlasSourceDecoratorOptions pDecoratorOptions) { final float left = pDecoratorOptions.getInsetLeft(); final float top = pDecoratorOptions.getInsetTop(); final float right = pCanvas.getWidth() - pDecoratorOptions.getInsetRight(); final float bottom = pCanvas.getHeight() - pDecoratorOptions.getInsetBottom(); this.mRectF.set(left, top, right, bottom); pCanvas.drawOval(this.mRectF, pPaint); } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.opengl.texture.atlas.bitmap.source.decorator.shape; import org.anddev.andengine.opengl.texture.atlas.bitmap.source.decorator.BaseBitmapTextureAtlasSourceDecorator.TextureAtlasSourceDecoratorOptions; import android.graphics.Canvas; import android.graphics.Paint; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 12:47:40 - 04.01.2011 */ public interface IBitmapTextureAtlasSourceDecoratorShape { // =========================================================== // Constants // =========================================================== // =========================================================== // Methods // =========================================================== public void onDecorateBitmap(final Canvas pCanvas, final Paint pPaint, final TextureAtlasSourceDecoratorOptions pDecoratorOptions); }
Java
package org.anddev.andengine.opengl.texture.atlas.bitmap.source.decorator.shape; import org.anddev.andengine.opengl.texture.atlas.bitmap.source.decorator.BaseBitmapTextureAtlasSourceDecorator.TextureAtlasSourceDecoratorOptions; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.RectF; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 12:52:55 - 04.01.2011 */ public class ArcBitmapTextureAtlasSourceDecoratorShape implements IBitmapTextureAtlasSourceDecoratorShape { // =========================================================== // Constants // =========================================================== private static final float STARTANGLE_DEFAULT = 0; private static final float SWEEPANGLE_DEFAULT = 360; private static final boolean USECENTER_DEFAULT = true; // =========================================================== // Fields // =========================================================== private static ArcBitmapTextureAtlasSourceDecoratorShape sDefaultInstance; private final RectF mRectF = new RectF(); private final float mStartAngle; private final float mSweepAngle; private final boolean mUseCenter; // =========================================================== // Constructors // =========================================================== public ArcBitmapTextureAtlasSourceDecoratorShape() { this(STARTANGLE_DEFAULT, SWEEPANGLE_DEFAULT, USECENTER_DEFAULT); } public ArcBitmapTextureAtlasSourceDecoratorShape(final float pStartAngle, final float pSweepAngle, final boolean pUseCenter) { this.mStartAngle = pStartAngle; this.mSweepAngle = pSweepAngle; this.mUseCenter = pUseCenter; } @Deprecated public static ArcBitmapTextureAtlasSourceDecoratorShape getDefaultInstance() { if(sDefaultInstance == null) { sDefaultInstance = new ArcBitmapTextureAtlasSourceDecoratorShape(); } return sDefaultInstance; } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public void onDecorateBitmap(final Canvas pCanvas, final Paint pPaint, final TextureAtlasSourceDecoratorOptions pDecoratorOptions) { final float left = pDecoratorOptions.getInsetLeft(); final float top = pDecoratorOptions.getInsetTop(); final float right = pCanvas.getWidth() - pDecoratorOptions.getInsetRight(); final float bottom = pCanvas.getHeight() - pDecoratorOptions.getInsetBottom(); this.mRectF.set(left, top, right, bottom); pCanvas.drawArc(this.mRectF, this.mStartAngle, this.mSweepAngle, this.mUseCenter, pPaint); } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.opengl.texture.atlas.bitmap.source.decorator.shape; import org.anddev.andengine.opengl.texture.atlas.bitmap.source.decorator.BaseBitmapTextureAtlasSourceDecorator.TextureAtlasSourceDecoratorOptions; import android.graphics.Canvas; import android.graphics.Paint; public class RectangleBitmapTextureAtlasSourceDecoratorShape implements IBitmapTextureAtlasSourceDecoratorShape { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private static RectangleBitmapTextureAtlasSourceDecoratorShape sDefaultInstance; // =========================================================== // Constructors // =========================================================== public RectangleBitmapTextureAtlasSourceDecoratorShape() { } public static RectangleBitmapTextureAtlasSourceDecoratorShape getDefaultInstance() { if(sDefaultInstance == null) { sDefaultInstance = new RectangleBitmapTextureAtlasSourceDecoratorShape(); } return sDefaultInstance; } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public void onDecorateBitmap(final Canvas pCanvas, final Paint pPaint, final TextureAtlasSourceDecoratorOptions pDecoratorOptions) { final float left = pDecoratorOptions.getInsetLeft(); final float top = pDecoratorOptions.getInsetTop(); final float right = pCanvas.getWidth() - pDecoratorOptions.getInsetRight(); final float bottom = pCanvas.getHeight() - pDecoratorOptions.getInsetBottom(); pCanvas.drawRect(left, top, right, bottom, pPaint); } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== };
Java
package org.anddev.andengine.opengl.texture.atlas.bitmap.source.decorator; import org.anddev.andengine.opengl.texture.atlas.bitmap.source.IBitmapTextureAtlasSource; import org.anddev.andengine.opengl.texture.atlas.bitmap.source.decorator.shape.IBitmapTextureAtlasSourceDecoratorShape; import android.graphics.Color; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 22:16:41 - 06.08.2010 */ public class ColorKeyBitmapTextureAtlasSourceDecorator extends ColorSwapBitmapTextureAtlasSourceDecorator { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== public ColorKeyBitmapTextureAtlasSourceDecorator(final IBitmapTextureAtlasSource pBitmapTextureAtlasSource, final IBitmapTextureAtlasSourceDecoratorShape pBitmapTextureAtlasSourceDecoratorShape, final int pColorKeyColor) { super(pBitmapTextureAtlasSource, pBitmapTextureAtlasSourceDecoratorShape, pColorKeyColor, Color.TRANSPARENT); } public ColorKeyBitmapTextureAtlasSourceDecorator(final IBitmapTextureAtlasSource pBitmapTextureAtlasSource, final IBitmapTextureAtlasSourceDecoratorShape pBitmapTextureAtlasSourceDecoratorShape, final int pColorKeyColor, final TextureAtlasSourceDecoratorOptions pTextureAtlasSourceDecoratorOptions) { super(pBitmapTextureAtlasSource, pBitmapTextureAtlasSourceDecoratorShape, pColorKeyColor, Color.TRANSPARENT, pTextureAtlasSourceDecoratorOptions); } public ColorKeyBitmapTextureAtlasSourceDecorator(final IBitmapTextureAtlasSource pBitmapTextureAtlasSource, final IBitmapTextureAtlasSourceDecoratorShape pBitmapTextureAtlasSourceDecoratorShape, final int pColorKeyColor, final int pTolerance) { super(pBitmapTextureAtlasSource, pBitmapTextureAtlasSourceDecoratorShape, pColorKeyColor, Color.TRANSPARENT, pTolerance); } public ColorKeyBitmapTextureAtlasSourceDecorator(final IBitmapTextureAtlasSource pBitmapTextureAtlasSource, final IBitmapTextureAtlasSourceDecoratorShape pBitmapTextureAtlasSourceDecoratorShape, final int pColorKeyColor, final int pTolerance, final TextureAtlasSourceDecoratorOptions pTextureAtlasSourceDecoratorOptions) { super(pBitmapTextureAtlasSource, pBitmapTextureAtlasSourceDecoratorShape, pColorKeyColor, pTolerance, Color.TRANSPARENT, pTextureAtlasSourceDecoratorOptions); } @Override public ColorKeyBitmapTextureAtlasSourceDecorator deepCopy() { return new ColorKeyBitmapTextureAtlasSourceDecorator(this.mBitmapTextureAtlasSource, this.mBitmapTextureAtlasSourceDecoratorShape, this.mColorKeyColor, this.mTolerance, this.mTextureAtlasSourceDecoratorOptions); } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.opengl.texture.atlas.bitmap.source.decorator; import org.anddev.andengine.opengl.texture.atlas.bitmap.source.IBitmapTextureAtlasSource; import org.anddev.andengine.opengl.texture.atlas.bitmap.source.decorator.shape.IBitmapTextureAtlasSourceDecoratorShape; import android.graphics.AvoidXfermode; import android.graphics.AvoidXfermode.Mode; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 19:41:39 - 07.06.2011 */ public class ColorSwapBitmapTextureAtlasSourceDecorator extends BaseShapeBitmapTextureAtlasSourceDecorator { // =========================================================== // Constants // =========================================================== private static final int TOLERANCE_DEFAULT = 0; // =========================================================== // Fields // =========================================================== protected final int mColorKeyColor; protected final int mTolerance; protected final int mColorSwapColor; // =========================================================== // Constructors // =========================================================== public ColorSwapBitmapTextureAtlasSourceDecorator(final IBitmapTextureAtlasSource pBitmapTextureAtlasSource, final IBitmapTextureAtlasSourceDecoratorShape pBitmapTextureAtlasSourceDecoratorShape, final int pColorKeyColor, final int pColorSwapColor) { this(pBitmapTextureAtlasSource, pBitmapTextureAtlasSourceDecoratorShape, pColorKeyColor, TOLERANCE_DEFAULT, pColorSwapColor, null); } public ColorSwapBitmapTextureAtlasSourceDecorator(final IBitmapTextureAtlasSource pBitmapTextureAtlasSource, final IBitmapTextureAtlasSourceDecoratorShape pBitmapTextureAtlasSourceDecoratorShape, final int pColorKeyColor, final int pColorSwapColor, final TextureAtlasSourceDecoratorOptions pTextureAtlasSourceDecoratorOptions) { this(pBitmapTextureAtlasSource, pBitmapTextureAtlasSourceDecoratorShape, pColorKeyColor, TOLERANCE_DEFAULT, pColorSwapColor, pTextureAtlasSourceDecoratorOptions); } public ColorSwapBitmapTextureAtlasSourceDecorator(final IBitmapTextureAtlasSource pBitmapTextureAtlasSource, final IBitmapTextureAtlasSourceDecoratorShape pBitmapTextureAtlasSourceDecoratorShape, final int pColorKeyColor, final int pTolerance, final int pColorSwapColor) { this(pBitmapTextureAtlasSource, pBitmapTextureAtlasSourceDecoratorShape, pColorKeyColor, pTolerance, pColorSwapColor, null); } public ColorSwapBitmapTextureAtlasSourceDecorator(final IBitmapTextureAtlasSource pBitmapTextureAtlasSource, final IBitmapTextureAtlasSourceDecoratorShape pBitmapTextureAtlasSourceDecoratorShape, final int pColorKeyColor, final int pTolerance, final int pColorSwapColor, final TextureAtlasSourceDecoratorOptions pTextureAtlasSourceDecoratorOptions) { super(pBitmapTextureAtlasSource, pBitmapTextureAtlasSourceDecoratorShape, pTextureAtlasSourceDecoratorOptions); this.mColorKeyColor = pColorKeyColor; this.mTolerance = pTolerance; this.mColorSwapColor = pColorSwapColor; this.mPaint.setXfermode(new AvoidXfermode(pColorKeyColor, pTolerance, Mode.TARGET)); this.mPaint.setColor(pColorSwapColor); } @Override public ColorSwapBitmapTextureAtlasSourceDecorator deepCopy() { return new ColorSwapBitmapTextureAtlasSourceDecorator(this.mBitmapTextureAtlasSource, this.mBitmapTextureAtlasSourceDecoratorShape, this.mColorKeyColor, this.mTolerance, this.mColorSwapColor, this.mTextureAtlasSourceDecoratorOptions); } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.opengl.texture.atlas.bitmap.source.decorator; import org.anddev.andengine.opengl.texture.atlas.bitmap.source.IBitmapTextureAtlasSource; import org.anddev.andengine.opengl.texture.atlas.bitmap.source.decorator.shape.IBitmapTextureAtlasSourceDecoratorShape; import android.graphics.Canvas; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 20:09:41 - 05.11.2010 */ public abstract class BaseShapeBitmapTextureAtlasSourceDecorator extends BaseBitmapTextureAtlasSourceDecorator { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== protected final IBitmapTextureAtlasSourceDecoratorShape mBitmapTextureAtlasSourceDecoratorShape; // =========================================================== // Constructors // =========================================================== public BaseShapeBitmapTextureAtlasSourceDecorator(final IBitmapTextureAtlasSource pBitmapTextureAtlasSource, final IBitmapTextureAtlasSourceDecoratorShape pBitmapTextureAtlasSourceDecoratorShape, final TextureAtlasSourceDecoratorOptions pTextureAtlasSourceDecoratorOptions) { super(pBitmapTextureAtlasSource, pTextureAtlasSourceDecoratorOptions); this.mBitmapTextureAtlasSourceDecoratorShape = pBitmapTextureAtlasSourceDecoratorShape; } @Override public abstract BaseShapeBitmapTextureAtlasSourceDecorator deepCopy(); // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override protected void onDecorateBitmap(final Canvas pCanvas){ this.mBitmapTextureAtlasSourceDecoratorShape.onDecorateBitmap(pCanvas, this.mPaint, (this.mTextureAtlasSourceDecoratorOptions == null) ? TextureAtlasSourceDecoratorOptions.DEFAULT : this.mTextureAtlasSourceDecoratorOptions); } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.opengl.texture.atlas.bitmap; import org.anddev.andengine.opengl.texture.atlas.bitmap.source.AssetBitmapTextureAtlasSource; import org.anddev.andengine.opengl.texture.atlas.bitmap.source.IBitmapTextureAtlasSource; import org.anddev.andengine.opengl.texture.atlas.bitmap.source.ResourceBitmapTextureAtlasSource; import org.anddev.andengine.opengl.texture.atlas.buildable.BuildableTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TextureRegion; import org.anddev.andengine.opengl.texture.region.TextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TiledTextureRegion; import android.content.Context; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 18:15:14 - 09.03.2010 */ public class BitmapTextureAtlasTextureRegionFactory { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private static String sAssetBasePath = ""; private static boolean sCreateTextureRegionBuffersManaged; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== /** * @param pAssetBasePath must end with '<code>/</code>' or have <code>.length() == 0</code>. */ public static void setAssetBasePath(final String pAssetBasePath) { if(pAssetBasePath.endsWith("/") || pAssetBasePath.length() == 0) { BitmapTextureAtlasTextureRegionFactory.sAssetBasePath = pAssetBasePath; } else { throw new IllegalArgumentException("pAssetBasePath must end with '/' or be lenght zero."); } } public static void setCreateTextureRegionBuffersManaged(final boolean pCreateTextureRegionBuffersManaged) { BitmapTextureAtlasTextureRegionFactory.sCreateTextureRegionBuffersManaged = pCreateTextureRegionBuffersManaged; } public static void reset() { BitmapTextureAtlasTextureRegionFactory.setAssetBasePath(""); BitmapTextureAtlasTextureRegionFactory.setCreateTextureRegionBuffersManaged(false); } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== // =========================================================== // Methods using BitmapTexture // =========================================================== public static TextureRegion createFromAsset(final BitmapTextureAtlas pBitmapTextureAtlas, final Context pContext, final String pAssetPath, final int pTexturePositionX, final int pTexturePositionY) { final IBitmapTextureAtlasSource bitmapTextureAtlasSource = new AssetBitmapTextureAtlasSource(pContext, BitmapTextureAtlasTextureRegionFactory.sAssetBasePath + pAssetPath); return BitmapTextureAtlasTextureRegionFactory.createFromSource(pBitmapTextureAtlas, bitmapTextureAtlasSource, pTexturePositionX, pTexturePositionY); } public static TiledTextureRegion createTiledFromAsset(final BitmapTextureAtlas pBitmapTextureAtlas, final Context pContext, final String pAssetPath, final int pTexturePositionX, final int pTexturePositionY, final int pTileColumns, final int pTileRows) { final IBitmapTextureAtlasSource bitmapTextureAtlasSource = new AssetBitmapTextureAtlasSource(pContext, BitmapTextureAtlasTextureRegionFactory.sAssetBasePath + pAssetPath); return BitmapTextureAtlasTextureRegionFactory.createTiledFromSource(pBitmapTextureAtlas, bitmapTextureAtlasSource, pTexturePositionX, pTexturePositionY, pTileColumns, pTileRows); } public static TextureRegion createFromResource(final BitmapTextureAtlas pBitmapTextureAtlas, final Context pContext, final int pDrawableResourceID, final int pTexturePositionX, final int pTexturePositionY) { final IBitmapTextureAtlasSource bitmapTextureAtlasSource = new ResourceBitmapTextureAtlasSource(pContext, pDrawableResourceID); return BitmapTextureAtlasTextureRegionFactory.createFromSource(pBitmapTextureAtlas, bitmapTextureAtlasSource, pTexturePositionX, pTexturePositionY); } public static TiledTextureRegion createTiledFromResource(final BitmapTextureAtlas pBitmapTextureAtlas, final Context pContext, final int pDrawableResourceID, final int pTexturePositionX, final int pTexturePositionY, final int pTileColumns, final int pTileRows) { final IBitmapTextureAtlasSource bitmapTextureAtlasSource = new ResourceBitmapTextureAtlasSource(pContext, pDrawableResourceID); return BitmapTextureAtlasTextureRegionFactory.createTiledFromSource(pBitmapTextureAtlas, bitmapTextureAtlasSource, pTexturePositionX, pTexturePositionY, pTileColumns, pTileRows); } public static TextureRegion createFromSource(final BitmapTextureAtlas pBitmapTextureAtlas, final IBitmapTextureAtlasSource pBitmapTextureAtlasSource, final int pTexturePositionX, final int pTexturePositionY) { return TextureRegionFactory.createFromSource(pBitmapTextureAtlas, pBitmapTextureAtlasSource, pTexturePositionX, pTexturePositionY, sCreateTextureRegionBuffersManaged); } public static TiledTextureRegion createTiledFromSource(final BitmapTextureAtlas pBitmapTextureAtlas, final IBitmapTextureAtlasSource pBitmapTextureAtlasSource, final int pTexturePositionX, final int pTexturePositionY, final int pTileColumns, final int pTileRows) { return TextureRegionFactory.createTiledFromSource(pBitmapTextureAtlas, pBitmapTextureAtlasSource, pTexturePositionX, pTexturePositionY, pTileColumns, pTileRows, sCreateTextureRegionBuffersManaged); } // =========================================================== // Methods using BuildableTexture // =========================================================== public static TextureRegion createFromAsset(final BuildableBitmapTextureAtlas pBuildableBitmapTextureAtlas, final Context pContext, final String pAssetPath) { final IBitmapTextureAtlasSource bitmapTextureAtlasSource = new AssetBitmapTextureAtlasSource(pContext, BitmapTextureAtlasTextureRegionFactory.sAssetBasePath + pAssetPath); return BitmapTextureAtlasTextureRegionFactory.createFromSource(pBuildableBitmapTextureAtlas, bitmapTextureAtlasSource); } public static TiledTextureRegion createTiledFromAsset(final BuildableBitmapTextureAtlas pBuildableBitmapTextureAtlas, final Context pContext, final String pAssetPath, final int pTileColumns, final int pTileRows) { final IBitmapTextureAtlasSource bitmapTextureAtlasSource = new AssetBitmapTextureAtlasSource(pContext, BitmapTextureAtlasTextureRegionFactory.sAssetBasePath + pAssetPath); return BitmapTextureAtlasTextureRegionFactory.createTiledFromSource(pBuildableBitmapTextureAtlas, bitmapTextureAtlasSource, pTileColumns, pTileRows); } public static TextureRegion createFromResource(final BuildableBitmapTextureAtlas pBuildableBitmapTextureAtlas, final Context pContext, final int pDrawableResourceID) { final IBitmapTextureAtlasSource bitmapTextureAtlasSource = new ResourceBitmapTextureAtlasSource(pContext, pDrawableResourceID); return BitmapTextureAtlasTextureRegionFactory.createFromSource(pBuildableBitmapTextureAtlas, bitmapTextureAtlasSource); } public static TiledTextureRegion createTiledFromResource(final BuildableBitmapTextureAtlas pBuildableBitmapTextureAtlas, final Context pContext, final int pDrawableResourceID, final int pTileColumns, final int pTileRows) { final IBitmapTextureAtlasSource bitmapTextureAtlasSource = new ResourceBitmapTextureAtlasSource(pContext, pDrawableResourceID); return BitmapTextureAtlasTextureRegionFactory.createTiledFromSource(pBuildableBitmapTextureAtlas, bitmapTextureAtlasSource, pTileColumns, pTileRows); } public static TextureRegion createFromSource(final BuildableBitmapTextureAtlas pBuildableBitmapTextureAtlas, final IBitmapTextureAtlasSource pBitmapTextureAtlasSource) { return BuildableTextureAtlasTextureRegionFactory.createFromSource(pBuildableBitmapTextureAtlas, pBitmapTextureAtlasSource, sCreateTextureRegionBuffersManaged); } public static TiledTextureRegion createTiledFromSource(final BuildableBitmapTextureAtlas pBuildableBitmapTextureAtlas, final IBitmapTextureAtlasSource pBitmapTextureAtlasSource, final int pTileColumns, final int pTileRows) { return BuildableTextureAtlasTextureRegionFactory.createTiledFromSource(pBuildableBitmapTextureAtlas, pBitmapTextureAtlasSource, pTileColumns, pTileRows, sCreateTextureRegionBuffersManaged); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.opengl.texture; import java.io.IOException; import javax.microedition.khronos.opengles.GL10; import org.anddev.andengine.opengl.texture.source.ITextureAtlasSource; import org.anddev.andengine.util.Debug; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 15:01:03 - 11.07.2011 */ public interface ITexture { // =========================================================== // Constants // =========================================================== // =========================================================== // Methods // =========================================================== public int getWidth(); public int getHeight(); public int getHardwareTextureID(); public boolean isLoadedToHardware(); public void setLoadedToHardware(final boolean pLoadedToHardware); public boolean isUpdateOnHardwareNeeded(); public void setUpdateOnHardwareNeeded(final boolean pUpdateOnHardwareNeeded); public void loadToHardware(final GL10 pGL) throws IOException; public void unloadFromHardware(final GL10 pGL); public void reloadToHardware(final GL10 pGL) throws IOException; public void bind(final GL10 pGL); public TextureOptions getTextureOptions(); public boolean hasTextureStateListener(); public ITextureStateListener getTextureStateListener(); // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== public static interface ITextureStateListener { // =========================================================== // Final Fields // =========================================================== // =========================================================== // Methods // =========================================================== public void onLoadedToHardware(final ITexture pTexture); public void onUnloadedFromHardware(final ITexture pTexture); // =========================================================== // Inner and Anonymous Classes // =========================================================== public static class TextureStateAdapter<T extends ITextureAtlasSource> implements ITextureStateListener { @Override public void onLoadedToHardware(final ITexture pTexture) { } @Override public void onUnloadedFromHardware(final ITexture pTexture) { } } public static class DebugTextureStateListener<T extends ITextureAtlasSource> implements ITextureStateListener { @Override public void onLoadedToHardware(final ITexture pTexture) { Debug.d("Texture loaded: " + pTexture.toString()); } @Override public void onUnloadedFromHardware(final ITexture pTexture) { Debug.d("Texture unloaded: " + pTexture.toString()); } } } }
Java
package org.anddev.andengine.opengl.texture; import java.io.IOException; import javax.microedition.khronos.opengles.GL10; import org.anddev.andengine.opengl.texture.source.ITextureAtlasSource; import org.anddev.andengine.opengl.util.GLHelper; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 14:55:02 - 08.03.2010 */ public abstract class Texture implements ITexture { // =========================================================== // Constants // =========================================================== private static final int[] HARDWARETEXTUREID_FETCHER = new int[1]; // =========================================================== // Fields // =========================================================== protected final PixelFormat mPixelFormat; protected final TextureOptions mTextureOptions; protected int mHardwareTextureID = -1; protected boolean mLoadedToHardware; protected boolean mUpdateOnHardwareNeeded = false; protected final ITextureStateListener mTextureStateListener; // =========================================================== // Constructors // =========================================================== /** * @param pPixelFormat * @param pTextureOptions the (quality) settings of the Texture. * @param pTextureStateListener to be informed when this {@link Texture} is loaded, unloaded or a {@link ITextureAtlasSource} failed to load. */ public Texture(final PixelFormat pPixelFormat, final TextureOptions pTextureOptions, final ITextureStateListener pTextureStateListener) throws IllegalArgumentException { this.mPixelFormat = pPixelFormat; this.mTextureOptions = pTextureOptions; this.mTextureStateListener = pTextureStateListener; } // =========================================================== // Getter & Setter // =========================================================== @Override public int getHardwareTextureID() { return this.mHardwareTextureID; } @Override public boolean isLoadedToHardware() { return this.mLoadedToHardware; } @Override public void setLoadedToHardware(final boolean pLoadedToHardware) { this.mLoadedToHardware = pLoadedToHardware; } @Override public boolean isUpdateOnHardwareNeeded() { return this.mUpdateOnHardwareNeeded; } @Override public void setUpdateOnHardwareNeeded(final boolean pUpdateOnHardwareNeeded) { this.mUpdateOnHardwareNeeded = pUpdateOnHardwareNeeded; } public PixelFormat getPixelFormat() { return this.mPixelFormat; } @Override public TextureOptions getTextureOptions() { return this.mTextureOptions; } @Override public ITextureStateListener getTextureStateListener() { return this.mTextureStateListener; } @Override public boolean hasTextureStateListener() { return this.mTextureStateListener != null; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== protected abstract void writeTextureToHardware(final GL10 pGL) throws IOException; @Override public void loadToHardware(final GL10 pGL) throws IOException { GLHelper.enableTextures(pGL); this.generateHardwareTextureID(pGL); this.bindTextureOnHardware(pGL); this.applyTextureOptions(pGL); this.writeTextureToHardware(pGL); this.mUpdateOnHardwareNeeded = false; this.mLoadedToHardware = true; if(this.mTextureStateListener != null) { this.mTextureStateListener.onLoadedToHardware(this); } } @Override public void unloadFromHardware(final GL10 pGL) { GLHelper.enableTextures(pGL); this.deleteTextureOnHardware(pGL); this.mHardwareTextureID = -1; this.mLoadedToHardware = false; if(this.mTextureStateListener != null) { this.mTextureStateListener.onUnloadedFromHardware(this); } } @Override public void reloadToHardware(final GL10 pGL) throws IOException { this.unloadFromHardware(pGL); this.loadToHardware(pGL); } @Override public void bind(final GL10 pGL) { GLHelper.bindTexture(pGL, this.mHardwareTextureID); } // =========================================================== // Methods // =========================================================== protected void applyTextureOptions(final GL10 pGL) { this.mTextureOptions.apply(pGL); } protected void bindTextureOnHardware(final GL10 pGL) { GLHelper.forceBindTexture(pGL, this.mHardwareTextureID); } protected void deleteTextureOnHardware(final GL10 pGL) { GLHelper.deleteTexture(pGL, this.mHardwareTextureID); } protected void generateHardwareTextureID(final GL10 pGL) { pGL.glGenTextures(1, Texture.HARDWARETEXTUREID_FETCHER, 0); this.mHardwareTextureID = Texture.HARDWARETEXTUREID_FETCHER[0]; } // =========================================================== // Inner and Anonymous Classes // =========================================================== public enum PixelFormat { // =========================================================== // Elements // =========================================================== UNDEFINED(-1, -1, -1), RGBA_4444(GL10.GL_RGBA, GL10.GL_UNSIGNED_SHORT_4_4_4_4, 16), RGBA_5551(GL10.GL_RGBA, GL10.GL_UNSIGNED_SHORT_5_5_5_1, 16), RGBA_8888(GL10.GL_RGBA, GL10.GL_UNSIGNED_BYTE, 32), RGB_565(GL10.GL_RGB, GL10.GL_UNSIGNED_SHORT_5_6_5, 16), A_8(GL10.GL_ALPHA, GL10.GL_UNSIGNED_BYTE, 8), I_8(GL10.GL_LUMINANCE, GL10.GL_UNSIGNED_BYTE, 8), AI_88(GL10.GL_LUMINANCE_ALPHA, GL10.GL_UNSIGNED_BYTE, 16); // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private final int mGLFormat; private final int mGLType; private final int mBitsPerPixel; // =========================================================== // Constructors // =========================================================== private PixelFormat(final int pGLFormat, final int pGLType, final int pBitsPerPixel) { this.mGLFormat = pGLFormat; this.mGLType = pGLType; this.mBitsPerPixel = pBitsPerPixel; } // =========================================================== // Getter & Setter // =========================================================== public int getGLFormat() { return this.mGLFormat; } public int getGLType() { return this.mGLType; } public int getBitsPerPixel() { return this.mBitsPerPixel; } // =========================================================== // Methods from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== } }
Java
package org.anddev.andengine.opengl.texture.bitmap; import java.io.IOException; import java.io.InputStream; import javax.microedition.khronos.opengles.GL10; import org.anddev.andengine.opengl.texture.Texture; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.util.GLHelper; import org.anddev.andengine.util.MathUtils; import org.anddev.andengine.util.StreamUtils; import android.graphics.Bitmap; import android.graphics.Bitmap.Config; import android.graphics.BitmapFactory; import android.opengl.GLUtils; /** * (c) Zynga 2011 * * @author Nicolas Gramlich <ngramlich@zynga.com> * @since 16:16:25 - 30.07.2011 */ public abstract class BitmapTexture extends Texture { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private final int mWidth; private final int mHeight; private final BitmapTextureFormat mBitmapTextureFormat; // =========================================================== // Constructors // =========================================================== public BitmapTexture() throws IOException { this(BitmapTextureFormat.RGBA_8888, TextureOptions.DEFAULT, null); } public BitmapTexture(final BitmapTextureFormat pBitmapTextureFormat) throws IOException { this(pBitmapTextureFormat, TextureOptions.DEFAULT, null); } public BitmapTexture(final TextureOptions pTextureOptions) throws IOException { this(BitmapTextureFormat.RGBA_8888, pTextureOptions, null); } public BitmapTexture(final BitmapTextureFormat pBitmapTextureFormat, final TextureOptions pTextureOptions) throws IOException { this(pBitmapTextureFormat, pTextureOptions, null); } public BitmapTexture(final BitmapTextureFormat pBitmapTextureFormat, final TextureOptions pTextureOptions, final ITextureStateListener pTextureStateListener) throws IOException { super(pBitmapTextureFormat.getPixelFormat(), pTextureOptions, pTextureStateListener); this.mBitmapTextureFormat = pBitmapTextureFormat; final BitmapFactory.Options decodeOptions = new BitmapFactory.Options(); decodeOptions.inJustDecodeBounds = true; final InputStream in = null; try { BitmapFactory.decodeStream(this.onGetInputStream(), null, decodeOptions); } finally { StreamUtils.close(in); } this.mWidth = decodeOptions.outWidth; this.mHeight = decodeOptions.outHeight; if(!MathUtils.isPowerOfTwo(this.mWidth) || !MathUtils.isPowerOfTwo(this.mHeight)) { // TODO GLHelper.EXTENSIONS_NON_POWER_OF_TWO throw new IllegalArgumentException("pWidth and pHeight must be a power of 2!"); } } // =========================================================== // Getter & Setter // =========================================================== @Override public int getWidth() { return this.mWidth; } @Override public int getHeight() { return this.mHeight; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== protected abstract InputStream onGetInputStream() throws IOException; @Override protected void writeTextureToHardware(final GL10 pGL) throws IOException { final Config bitmapConfig = this.mBitmapTextureFormat.getBitmapConfig(); final boolean preMultipyAlpha = this.mTextureOptions.mPreMultipyAlpha; final BitmapFactory.Options decodeOptions = new BitmapFactory.Options(); decodeOptions.inPreferredConfig = bitmapConfig; final Bitmap bitmap = BitmapFactory.decodeStream(this.onGetInputStream(), null, decodeOptions); if(preMultipyAlpha) { GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0); } else { GLHelper.glTexImage2D(pGL, GL10.GL_TEXTURE_2D, 0, bitmap, 0, this.mPixelFormat); } bitmap.recycle(); } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== public static enum BitmapTextureFormat { // =========================================================== // Elements // =========================================================== RGBA_8888(Config.ARGB_8888, PixelFormat.RGBA_8888), RGB_565(Config.RGB_565, PixelFormat.RGB_565), RGBA_4444(Config.ARGB_4444, PixelFormat.RGBA_4444), // TODO A_8(Config.ALPHA_8, PixelFormat.A_8); // TODO // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private final Config mBitmapConfig; private final PixelFormat mPixelFormat; // =========================================================== // Constructors // =========================================================== private BitmapTextureFormat(final Config pBitmapConfig, final PixelFormat pPixelFormat) { this.mBitmapConfig = pBitmapConfig; this.mPixelFormat = pPixelFormat; } public static BitmapTextureFormat fromPixelFormat(final PixelFormat pPixelFormat) { switch(pPixelFormat) { case RGBA_8888: return RGBA_8888; case RGBA_4444: return RGBA_4444; case RGB_565: return RGB_565; case A_8: return A_8; default: throw new IllegalArgumentException("Unsupported " + PixelFormat.class.getName() + ": '" + pPixelFormat + "'."); } } // =========================================================== // Getter & Setter // =========================================================== public Config getBitmapConfig() { return this.mBitmapConfig; } public PixelFormat getPixelFormat() { return this.mPixelFormat; } // =========================================================== // Methods from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== } }
Java
package org.anddev.andengine.collision; import static org.anddev.andengine.util.constants.Constants.VERTEX_INDEX_X; import static org.anddev.andengine.util.constants.Constants.VERTEX_INDEX_Y; import org.anddev.andengine.entity.primitive.Line; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 19:27:22 - 17.07.2010 */ public class LineCollisionChecker extends ShapeCollisionChecker { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== public static boolean checkLineCollision(final float pX1, final float pY1, final float pX2, final float pY2, final float pX3, final float pY3, final float pX4, final float pY4) { return ((BaseCollisionChecker.relativeCCW(pX1, pY1, pX2, pY2, pX3, pY3) * BaseCollisionChecker.relativeCCW(pX1, pY1, pX2, pY2, pX4, pY4) <= 0) && (BaseCollisionChecker.relativeCCW(pX3, pY3, pX4, pY4, pX1, pY1) * BaseCollisionChecker.relativeCCW(pX3, pY3, pX4, pY4, pX2, pY2) <= 0)); } public static void fillVertices(final Line pLine, final float[] pVertices) { pVertices[0 + VERTEX_INDEX_X] = 0; pVertices[0 + VERTEX_INDEX_Y] = 0; pVertices[2 + VERTEX_INDEX_X] = pLine.getX2() - pLine.getX1(); pVertices[2 + VERTEX_INDEX_Y] = pLine.getY2() - pLine.getY1(); pLine.getLocalToSceneTransformation().transform(pVertices); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.collision; import static org.anddev.andengine.util.constants.Constants.VERTEX_INDEX_X; import static org.anddev.andengine.util.constants.Constants.VERTEX_INDEX_Y; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.entity.primitive.Line; import org.anddev.andengine.entity.shape.RectangularShape; import org.anddev.andengine.util.MathUtils; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 11:50:19 - 11.03.2010 */ public class RectangularShapeCollisionChecker extends ShapeCollisionChecker { // =========================================================== // Constants // =========================================================== private static final int RECTANGULARSHAPE_VERTEX_COUNT = 4; private static final int LINE_VERTEX_COUNT = 2; private static final float[] VERTICES_CONTAINS_TMP = new float[2 * RECTANGULARSHAPE_VERTEX_COUNT]; private static final float[] VERTICES_COLLISION_TMP_A = new float[2 * RECTANGULARSHAPE_VERTEX_COUNT]; private static final float[] VERTICES_COLLISION_TMP_B = new float[2 * RECTANGULARSHAPE_VERTEX_COUNT]; // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== public static boolean checkContains(final RectangularShape pRectangularShape, final float pX, final float pY) { RectangularShapeCollisionChecker.fillVertices(pRectangularShape, VERTICES_CONTAINS_TMP); return ShapeCollisionChecker.checkContains(VERTICES_CONTAINS_TMP, 2 * RECTANGULARSHAPE_VERTEX_COUNT, pX, pY); } public static boolean isVisible(final Camera pCamera, final RectangularShape pRectangularShape) { RectangularShapeCollisionChecker.fillVertices(pCamera, VERTICES_COLLISION_TMP_A); RectangularShapeCollisionChecker.fillVertices(pRectangularShape, VERTICES_COLLISION_TMP_B); return ShapeCollisionChecker.checkCollision(2 * RECTANGULARSHAPE_VERTEX_COUNT, VERTICES_COLLISION_TMP_A, 2 * RECTANGULARSHAPE_VERTEX_COUNT, VERTICES_COLLISION_TMP_B); } public static boolean isVisible(final Camera pCamera, final Line pLine) { RectangularShapeCollisionChecker.fillVertices(pCamera, VERTICES_COLLISION_TMP_A); LineCollisionChecker.fillVertices(pLine, VERTICES_COLLISION_TMP_B); return ShapeCollisionChecker.checkCollision(2 * RECTANGULARSHAPE_VERTEX_COUNT, VERTICES_COLLISION_TMP_A, 2 * LINE_VERTEX_COUNT, VERTICES_COLLISION_TMP_B); } public static boolean checkCollision(final RectangularShape pRectangularShapeA, final RectangularShape pRectangularShapeB) { RectangularShapeCollisionChecker.fillVertices(pRectangularShapeA, VERTICES_COLLISION_TMP_A); RectangularShapeCollisionChecker.fillVertices(pRectangularShapeB, VERTICES_COLLISION_TMP_B); return ShapeCollisionChecker.checkCollision(2 * RECTANGULARSHAPE_VERTEX_COUNT, VERTICES_COLLISION_TMP_A, 2 * RECTANGULARSHAPE_VERTEX_COUNT, VERTICES_COLLISION_TMP_B); } public static boolean checkCollision(final RectangularShape pRectangularShape, final Line pLine) { RectangularShapeCollisionChecker.fillVertices(pRectangularShape, VERTICES_COLLISION_TMP_A); LineCollisionChecker.fillVertices(pLine, VERTICES_COLLISION_TMP_B); return ShapeCollisionChecker.checkCollision(2 * RECTANGULARSHAPE_VERTEX_COUNT, VERTICES_COLLISION_TMP_A, 2 * LINE_VERTEX_COUNT, VERTICES_COLLISION_TMP_B); } public static void fillVertices(final RectangularShape pRectangularShape, final float[] pVertices) { final float left = 0; final float top = 0; final float right = pRectangularShape.getWidth(); final float bottom = pRectangularShape.getHeight(); pVertices[0 + VERTEX_INDEX_X] = left; pVertices[0 + VERTEX_INDEX_Y] = top; pVertices[2 + VERTEX_INDEX_X] = right; pVertices[2 + VERTEX_INDEX_Y] = top; pVertices[4 + VERTEX_INDEX_X] = right; pVertices[4 + VERTEX_INDEX_Y] = bottom; pVertices[6 + VERTEX_INDEX_X] = left; pVertices[6 + VERTEX_INDEX_Y] = bottom; pRectangularShape.getLocalToSceneTransformation().transform(pVertices); } private static void fillVertices(final Camera pCamera, final float[] pVertices) { pVertices[0 + VERTEX_INDEX_X] = pCamera.getMinX(); pVertices[0 + VERTEX_INDEX_Y] = pCamera.getMinY(); pVertices[2 + VERTEX_INDEX_X] = pCamera.getMaxX(); pVertices[2 + VERTEX_INDEX_Y] = pCamera.getMinY(); pVertices[4 + VERTEX_INDEX_X] = pCamera.getMaxX(); pVertices[4 + VERTEX_INDEX_Y] = pCamera.getMaxY(); pVertices[6 + VERTEX_INDEX_X] = pCamera.getMinX(); pVertices[6 + VERTEX_INDEX_Y] = pCamera.getMaxY(); MathUtils.rotateAroundCenter(pVertices, pCamera.getRotation(), pCamera.getCenterX(), pCamera.getCenterY()); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.collision; import org.anddev.andengine.util.constants.Constants; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 11:50:19 - 11.03.2010 */ public class ShapeCollisionChecker extends BaseCollisionChecker { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== public static boolean checkCollision(final int pVerticesALength, final float[] pVerticesA, final int pVerticesBLength, final float[] pVerticesB) { /* Check all the lines of A ... */ for(int a = pVerticesALength - 4; a >= 0; a -= 2) { /* ... against all lines in B. */ if(ShapeCollisionChecker.checkCollisionSub(a, a + 2, pVerticesA, pVerticesB, pVerticesBLength)){ return true; } } /* Also check the 'around the corner of the array' line of A against all lines in B. */ if(ShapeCollisionChecker.checkCollisionSub(pVerticesALength - 2, 0, pVerticesA, pVerticesB, pVerticesBLength)){ return true; } else { /* At last check if one polygon 'contains' the other one by checking * if one vertex of the one vertices is contained by all of the other vertices. */ if(ShapeCollisionChecker.checkContains(pVerticesA, pVerticesALength, pVerticesB[Constants.VERTEX_INDEX_X], pVerticesB[Constants.VERTEX_INDEX_Y])) { return true; } else if(ShapeCollisionChecker.checkContains(pVerticesB, pVerticesBLength, pVerticesA[Constants.VERTEX_INDEX_X], pVerticesA[Constants.VERTEX_INDEX_Y])) { return true; } else { return false; } } } /** * Checks line specified by pVerticesA[pVertexIndexA1] and pVerticesA[pVertexIndexA2] against all lines in pVerticesB. */ private static boolean checkCollisionSub(final int pVertexIndexA1, final int pVertexIndexA2, final float[] pVerticesA, final float[] pVerticesB, final int pVerticesBLength) { /* Check against all the lines of B. */ final float vertexA1X = pVerticesA[pVertexIndexA1 + Constants.VERTEX_INDEX_X]; final float vertexA1Y = pVerticesA[pVertexIndexA1 + Constants.VERTEX_INDEX_Y]; final float vertexA2X = pVerticesA[pVertexIndexA2 + Constants.VERTEX_INDEX_X]; final float vertexA2Y = pVerticesA[pVertexIndexA2 + Constants.VERTEX_INDEX_Y]; for(int b = pVerticesBLength - 4; b >= 0; b -= 2) { if(LineCollisionChecker.checkLineCollision(vertexA1X, vertexA1Y, vertexA2X, vertexA2Y, pVerticesB[b + Constants.VERTEX_INDEX_X], pVerticesB[b + Constants.VERTEX_INDEX_Y], pVerticesB[b + 2 + Constants.VERTEX_INDEX_X], pVerticesB[b + 2 + Constants.VERTEX_INDEX_Y])){ return true; } } /* Also check the 'around the corner of the array' line of B. */ if(LineCollisionChecker.checkLineCollision(vertexA1X, vertexA1Y, vertexA2X, vertexA2Y, pVerticesB[pVerticesBLength - 2], pVerticesB[pVerticesBLength - 1], pVerticesB[Constants.VERTEX_INDEX_X], pVerticesB[Constants.VERTEX_INDEX_Y])){ return true; } return false; } public static boolean checkContains(final float[] pVertices, final int pVerticesLength, final float pX, final float pY) { int edgeResultSum = 0; for(int i = pVerticesLength - 4; i >= 0; i -= 2) { final int edgeResult = BaseCollisionChecker.relativeCCW(pVertices[i], pVertices[i + 1], pVertices[i + 2], pVertices[i + 3], pX, pY); if(edgeResult == 0) { return true; } else { edgeResultSum += edgeResult; } } /* Also check the 'around the corner of the array' line. */ final int edgeResult = BaseCollisionChecker.relativeCCW(pVertices[pVerticesLength - 2], pVertices[pVerticesLength - 1], pVertices[Constants.VERTEX_INDEX_X], pVertices[Constants.VERTEX_INDEX_Y], pX, pY); if(edgeResult == 0){ return true; } else { edgeResultSum += edgeResult; } final int vertexCount = pVerticesLength / 2; /* Point is not on the edge, so check if the edge is on the same side(left or right) of all edges. */ return edgeResultSum == vertexCount || edgeResultSum == -vertexCount ; } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.collision; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 11:50:19 - 11.03.2010 */ public class BaseCollisionChecker { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== public static boolean checkAxisAlignedRectangleCollision(final float pLeftA, final float pTopA, final float pRightA, final float pBottomA, final float pLeftB, final float pTopB, final float pRightB, final float pBottomB) { return (pLeftA < pRightB && pLeftB < pRightA && pTopA < pBottomB && pTopB < pBottomA); } /** * Returns an indicator of where the specified point (PX,&nbsp;PY) lies with * respect to the line segment from (X1,&nbsp;Y1) to (X2,&nbsp;Y2). The * return value can be either 1, -1, or 0 and indicates in which direction * the specified line must pivot around its first endpoint, (X1,&nbsp;Y1), * in order to point at the specified point (PX,&nbsp;PY). * <p> * A return value of 1 indicates that the line segment must turn in the * direction that takes the positive X axis towards the negative Y axis. In * the default coordinate system used by Java 2D, this direction is * counterclockwise. * <p> * A return value of -1 indicates that the line segment must turn in the * direction that takes the positive X axis towards the positive Y axis. In * the default coordinate system, this direction is clockwise. * <p> * A return value of 0 indicates that the point lies exactly on the line * segment. Note that an indicator value of 0 is rare and not useful for * determining colinearity because of floating point rounding issues. * <p> * If the point is colinear with the line segment, but not between the * endpoints, then the value will be -1 if the point lies * "beyond (X1,&nbsp;Y1)" or 1 if the point lies "beyond (X2,&nbsp;Y2)". * * @param pX1 * ,&nbsp;Y1 the coordinates of the beginning of the specified * line segment * @param pX2 * ,&nbsp;Y2 the coordinates of the end of the specified line * segment * @param pPX * ,&nbsp;PY the coordinates of the specified point to be * compared with the specified line segment * @return an integer that indicates the position of the third specified * coordinates with respect to the line segment formed by the first * two specified coordinates. */ public static int relativeCCW(final float pX1, final float pY1, float pX2, float pY2, float pPX, float pPY) { pX2 -= pX1; pY2 -= pY1; pPX -= pX1; pPY -= pY1; float ccw = pPX * pY2 - pPY * pX2; if (ccw == 0.0f) { // The point is colinear, classify based on which side of // the segment the point falls on. We can calculate a // relative value using the projection of PX,PY onto the // segment - a negative value indicates the point projects // outside of the segment in the direction of the particular // endpoint used as the origin for the projection. ccw = pPX * pX2 + pPY * pY2; if (ccw > 0.0f) { // Reverse the projection to be relative to the original X2,Y2 // X2 and Y2 are simply negated. // PX and PY need to have (X2 - X1) or (Y2 - Y1) subtracted // from them (based on the original values) // Since we really want to get a positive answer when the // point is "beyond (X2,Y2)", then we want to calculate // the inverse anyway - thus we leave X2 & Y2 negated. pPX -= pX2; pPY -= pY2; ccw = pPX * pX2 + pPY * pY2; if (ccw < 0.0f) { ccw = 0.0f; } } } return (ccw < 0.0f) ? -1 : ((ccw > 0.0f) ? 1 : 0); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.entity.sprite.batch; import javax.microedition.khronos.opengles.GL10; import javax.microedition.khronos.opengles.GL11; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.entity.Entity; import org.anddev.andengine.entity.shape.Shape; import org.anddev.andengine.entity.sprite.BaseSprite; import org.anddev.andengine.opengl.texture.ITexture; import org.anddev.andengine.opengl.texture.region.BaseTextureRegion; import org.anddev.andengine.opengl.texture.region.buffer.SpriteBatchTextureRegionBuffer; import org.anddev.andengine.opengl.util.GLHelper; import org.anddev.andengine.opengl.vertex.SpriteBatchVertexBuffer; /** * TODO Texture could be semi-changeable, being resetting to null in end(...) * TODO Make use of pGL.glColorPointer(size, type, stride, pointer) which should allow individual color tinting. * * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 11:45:48 - 14.06.2011 */ public class SpriteBatch extends Entity { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== protected final ITexture mTexture; protected final int mCapacity; protected int mIndex; private int mVertices; private int mSourceBlendFunction; private int mDestinationBlendFunction; private final SpriteBatchVertexBuffer mSpriteBatchVertexBuffer; private final SpriteBatchTextureRegionBuffer mSpriteBatchTextureRegionBuffer; // =========================================================== // Constructors // =========================================================== public SpriteBatch(final ITexture pTexture, final int pCapacity) { this(pTexture, pCapacity, new SpriteBatchVertexBuffer(pCapacity, GL11.GL_STATIC_DRAW, true), new SpriteBatchTextureRegionBuffer(pCapacity, GL11.GL_STATIC_DRAW, true)); } public SpriteBatch(final ITexture pTexture, final int pCapacity, final SpriteBatchVertexBuffer pSpriteBatchVertexBuffer, final SpriteBatchTextureRegionBuffer pSpriteBatchTextureRegionBuffer) { this.mTexture = pTexture; this.mCapacity = pCapacity; this.mSpriteBatchVertexBuffer = pSpriteBatchVertexBuffer; this.mSpriteBatchTextureRegionBuffer = pSpriteBatchTextureRegionBuffer; this.initBlendFunction(); } // =========================================================== // Getter & Setter // =========================================================== public void setBlendFunction(final int pSourceBlendFunction, final int pDestinationBlendFunction) { this.mSourceBlendFunction = pSourceBlendFunction; this.mDestinationBlendFunction = pDestinationBlendFunction; } public int getIndex() { return this.mIndex; } public void setIndex(final int pIndex) { this.assertCapacity(pIndex); this.mIndex = pIndex; final int vertexIndex = pIndex * 2 * SpriteBatchVertexBuffer.VERTICES_PER_RECTANGLE; this.mSpriteBatchVertexBuffer.setIndex(vertexIndex); this.mSpriteBatchTextureRegionBuffer.setIndex(vertexIndex); } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override protected void doDraw(final GL10 pGL, final Camera pCamera) { this.onInitDraw(pGL); this.begin(pGL); this.onApplyVertices(pGL); this.onApplyTextureRegion(pGL); this.drawVertices(pGL, pCamera); this.end(pGL); } @Override public void reset() { super.reset(); this.initBlendFunction(); } @Override protected void finalize() throws Throwable { super.finalize(); if(this.mSpriteBatchVertexBuffer.isManaged()) { this.mSpriteBatchVertexBuffer.unloadFromActiveBufferObjectManager(); } if(this.mSpriteBatchTextureRegionBuffer.isManaged()) { this.mSpriteBatchTextureRegionBuffer.unloadFromActiveBufferObjectManager(); } } // =========================================================== // Methods // =========================================================== protected void begin(@SuppressWarnings("unused") final GL10 pGL) { // GLHelper.disableDepthMask(pGL); } protected void end(@SuppressWarnings("unused") final GL10 pGL) { // GLHelper.enableDepthMask(pGL); } /** * @see {@link SpriteBatchVertexBuffer#add(float, float, float, float)}. */ public void draw(final BaseTextureRegion pTextureRegion, final float pX, final float pY, final float pWidth, final float pHeight) { this.assertCapacity(); this.assertTexture(pTextureRegion); this.mSpriteBatchVertexBuffer.add(pX, pY, pWidth, pHeight); this.mSpriteBatchTextureRegionBuffer.add(pTextureRegion); this.mIndex++; } public void drawWithoutChecks(final BaseTextureRegion pTextureRegion, final float pX, final float pY, final float pWidth, final float pHeight) { this.mSpriteBatchVertexBuffer.add(pX, pY, pWidth, pHeight); this.mSpriteBatchTextureRegionBuffer.add(pTextureRegion); this.mIndex++; } /** * @see {@link SpriteBatchVertexBuffer#add(float, float, float, float, float)}. */ public void draw(final BaseTextureRegion pTextureRegion, final float pX, final float pY, final float pWidth, final float pHeight, final float pRotation) { this.assertCapacity(); this.assertTexture(pTextureRegion); this.mSpriteBatchVertexBuffer.add(pX, pY, pWidth, pHeight, pRotation); this.mSpriteBatchTextureRegionBuffer.add(pTextureRegion); this.mIndex++; } public void drawWithoutChecks(final BaseTextureRegion pTextureRegion, final float pX, final float pY, final float pWidth, final float pHeight, final float pRotation) { this.mSpriteBatchVertexBuffer.add(pX, pY, pWidth, pHeight, pRotation); this.mSpriteBatchTextureRegionBuffer.add(pTextureRegion); this.mIndex++; } /** * @see {@link SpriteBatchVertexBuffer#add(float, float, float, float, float, float)}. */ public void draw(final BaseTextureRegion pTextureRegion, final float pX, final float pY, final float pWidth, final float pHeight, final float pScaleX, final float pScaleY) { this.assertCapacity(); this.assertTexture(pTextureRegion); this.mSpriteBatchVertexBuffer.add(pX, pY, pWidth, pHeight, pScaleX, pScaleY); this.mSpriteBatchTextureRegionBuffer.add(pTextureRegion); this.mIndex++; } public void drawWithoutChecks(final BaseTextureRegion pTextureRegion, final float pX, final float pY, final float pWidth, final float pHeight, final float pScaleX, final float pScaleY) { this.mSpriteBatchVertexBuffer.add(pX, pY, pWidth, pHeight, pScaleX, pScaleY); this.mSpriteBatchTextureRegionBuffer.add(pTextureRegion); this.mIndex++; } /** * @see {@link SpriteBatchVertexBuffer#add(float, float, float, float, float, float, float)}. */ public void draw(final BaseTextureRegion pTextureRegion, final float pX, final float pY, final float pWidth, final float pHeight, final float pRotation, final float pScaleX, final float pScaleY) { this.assertCapacity(); this.assertTexture(pTextureRegion); this.mSpriteBatchVertexBuffer.add(pX, pY, pWidth, pHeight, pRotation, pScaleX, pScaleY); this.mSpriteBatchTextureRegionBuffer.add(pTextureRegion); this.mIndex++; } public void drawWithoutChecks(final BaseTextureRegion pTextureRegion, final float pX, final float pY, final float pWidth, final float pHeight, final float pRotation, final float pScaleX, final float pScaleY) { this.mSpriteBatchVertexBuffer.add(pX, pY, pWidth, pHeight, pRotation, pScaleX, pScaleY); this.mSpriteBatchTextureRegionBuffer.add(pTextureRegion); this.mIndex++; } /** * {@link SpriteBatchVertexBuffer#add(float, float, float, float, float, float, float, float)}. */ public void draw(final BaseTextureRegion pTextureRegion, final float pX1, final float pY1, final float pX2, final float pY2, final float pX3, final float pY3, final float pX4, final float pY4) { this.assertCapacity(); this.assertTexture(pTextureRegion); this.mSpriteBatchVertexBuffer.addInner(pX1, pY1, pX2, pY2, pX3, pY3, pX4, pY4); this.mSpriteBatchTextureRegionBuffer.add(pTextureRegion); this.mIndex++; } public void drawWithoutChecks(final BaseTextureRegion pTextureRegion, final float pX1, final float pY1, final float pX2, final float pY2, final float pX3, final float pY3, final float pX4, final float pY4) { this.mSpriteBatchVertexBuffer.addInner(pX1, pY1, pX2, pY2, pX3, pY3, pX4, pY4); this.mSpriteBatchTextureRegionBuffer.add(pTextureRegion); this.mIndex++; } /** * {@link SpriteBatchVertexBuffer#add(BaseSprite)}. */ public void draw(final BaseSprite pBaseSprite) { if(pBaseSprite.isVisible()) { this.assertCapacity(); final BaseTextureRegion textureRegion = pBaseSprite.getTextureRegion(); this.assertTexture(textureRegion); if(pBaseSprite.getRotation() == 0 && !pBaseSprite.isScaled()) { this.mSpriteBatchVertexBuffer.add(pBaseSprite.getX(), pBaseSprite.getY(), pBaseSprite.getWidth(), pBaseSprite.getHeight()); } else { this.mSpriteBatchVertexBuffer.add(pBaseSprite.getWidth(), pBaseSprite.getHeight(), pBaseSprite.getLocalToParentTransformation()); } this.mSpriteBatchTextureRegionBuffer.add(textureRegion); this.mIndex++; } } public void drawWithoutChecks(final BaseSprite pBaseSprite) { if(pBaseSprite.isVisible()) { final BaseTextureRegion textureRegion = pBaseSprite.getTextureRegion(); if(pBaseSprite.getRotation() == 0 && !pBaseSprite.isScaled()) { this.mSpriteBatchVertexBuffer.add(pBaseSprite.getX(), pBaseSprite.getY(), pBaseSprite.getWidth(), pBaseSprite.getHeight()); } else { this.mSpriteBatchVertexBuffer.add(pBaseSprite.getWidth(), pBaseSprite.getHeight(), pBaseSprite.getLocalToParentTransformation()); } this.mSpriteBatchTextureRegionBuffer.add(textureRegion); this.mIndex++; } } public void submit() { this.onSubmit(); } private void onSubmit() { this.mVertices = this.mIndex * SpriteBatchVertexBuffer.VERTICES_PER_RECTANGLE; this.mSpriteBatchVertexBuffer.submit(); this.mSpriteBatchTextureRegionBuffer.submit(); this.mIndex = 0; this.mSpriteBatchVertexBuffer.setIndex(0); this.mSpriteBatchTextureRegionBuffer.setIndex(0); } private void initBlendFunction() { if(this.mTexture.getTextureOptions().mPreMultipyAlpha) { this.setBlendFunction(Shape.BLENDFUNCTION_SOURCE_PREMULTIPLYALPHA_DEFAULT, Shape.BLENDFUNCTION_DESTINATION_PREMULTIPLYALPHA_DEFAULT); } } protected void onInitDraw(final GL10 pGL) { GLHelper.setColor(pGL, this.mRed, this.mGreen, this.mBlue, this.mAlpha); GLHelper.enableVertexArray(pGL); GLHelper.blendFunction(pGL, this.mSourceBlendFunction, this.mDestinationBlendFunction); GLHelper.enableTextures(pGL); GLHelper.enableTexCoordArray(pGL); } protected void onApplyVertices(final GL10 pGL) { if(GLHelper.EXTENSIONS_VERTEXBUFFEROBJECTS) { final GL11 gl11 = (GL11)pGL; this.mSpriteBatchVertexBuffer.selectOnHardware(gl11); GLHelper.vertexZeroPointer(gl11); } else { GLHelper.vertexPointer(pGL, this.mSpriteBatchVertexBuffer.getFloatBuffer()); } } private void onApplyTextureRegion(final GL10 pGL) { if(GLHelper.EXTENSIONS_VERTEXBUFFEROBJECTS) { final GL11 gl11 = (GL11)pGL; this.mSpriteBatchTextureRegionBuffer.selectOnHardware(gl11); this.mTexture.bind(pGL); GLHelper.texCoordZeroPointer(gl11); } else { this.mTexture.bind(pGL); GLHelper.texCoordPointer(pGL, this.mSpriteBatchTextureRegionBuffer.getFloatBuffer()); } } private void drawVertices(final GL10 pGL, @SuppressWarnings("unused") final Camera pCamera) { pGL.glDrawArrays(GL10.GL_TRIANGLES, 0, this.mVertices); } private void assertCapacity(final int pIndex) { if(pIndex >= this.mCapacity) { throw new IllegalStateException("This supplied pIndex: '" + pIndex + "' is exceeding the capacity: '" + this.mCapacity + "' of this SpriteBatch!"); } } private void assertCapacity() { if(this.mIndex == this.mCapacity) { throw new IllegalStateException("This SpriteBatch has already reached its capacity (" + this.mCapacity + ") !"); } } protected void assertTexture(final BaseTextureRegion pTextureRegion) { if(pTextureRegion.getTexture() != this.mTexture) { throw new IllegalArgumentException("The supplied Texture does match the Texture of this SpriteBatch!"); } } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.entity.sprite.batch; import javax.microedition.khronos.opengles.GL10; import org.anddev.andengine.opengl.texture.ITexture; import org.anddev.andengine.opengl.texture.region.buffer.SpriteBatchTextureRegionBuffer; import org.anddev.andengine.opengl.vertex.SpriteBatchVertexBuffer; /** * (c) Zynga 2011 * * @author Nicolas Gramlich <ngramlich@zynga.com> * @since 21:48:21 - 27.07.2011 */ public abstract class DynamicSpriteBatch extends SpriteBatch { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== public DynamicSpriteBatch(final ITexture pTexture, final int pCapacity) { super(pTexture, pCapacity); } public DynamicSpriteBatch(final ITexture pTexture, final int pCapacity, final SpriteBatchVertexBuffer pSpriteBatchVertexBuffer, final SpriteBatchTextureRegionBuffer pSpriteBatchTextureRegionBuffer) { super(pTexture, pCapacity, pSpriteBatchVertexBuffer, pSpriteBatchTextureRegionBuffer); } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== /** * @return <code>true</code> to submit, if you made any changes, or <code>false</code> otherwise. */ protected abstract boolean onUpdateSpriteBatch(); @Override protected void begin(final GL10 pGL) { super.begin(pGL); if(this.onUpdateSpriteBatch()) { this.submit(); } } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.entity.sprite.batch; import java.util.ArrayList; import org.anddev.andengine.entity.IEntity; import org.anddev.andengine.entity.sprite.BaseSprite; import org.anddev.andengine.opengl.texture.ITexture; import org.anddev.andengine.opengl.texture.region.buffer.SpriteBatchTextureRegionBuffer; import org.anddev.andengine.opengl.vertex.SpriteBatchVertexBuffer; import org.anddev.andengine.util.SmartList; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 12:10:35 - 15.06.2011 */ public class SpriteGroup extends DynamicSpriteBatch { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== public SpriteGroup(final ITexture pTexture, final int pCapacity) { super(pTexture, pCapacity); /* Make children not be drawn automatically, as we handle the drawing ourself. */ this.setChildrenVisible(false); } public SpriteGroup(final ITexture pTexture, final int pCapacity, final SpriteBatchVertexBuffer pSpriteBatchVertexBuffer, final SpriteBatchTextureRegionBuffer pSpriteBatchTextureRegionBuffer) { super(pTexture, pCapacity, pSpriteBatchVertexBuffer, pSpriteBatchTextureRegionBuffer); /* Make children not be drawn automatically, as we handle the drawing ourself. */ this.setChildrenVisible(false); } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== /** * Instead use {@link SpriteGroup#attachChild(BaseSprite)}. */ @Override @Deprecated public void attachChild(final IEntity pEntity) throws IllegalArgumentException { if(pEntity instanceof BaseSprite) { this.attachChild((BaseSprite)pEntity); } else { throw new IllegalArgumentException("A SpriteGroup can only handle children of type BaseSprite or subclasses of BaseSprite, like Sprite, TiledSprite or AnimatedSprite."); } } public void attachChild(final BaseSprite pBaseSprite) { this.assertCapacity(); this.assertTexture(pBaseSprite.getTextureRegion()); super.attachChild(pBaseSprite); } public void attachChildren(final ArrayList<? extends BaseSprite> pBaseSprites) { final int baseSpriteCount = pBaseSprites.size(); for(int i = 0; i < baseSpriteCount; i++) { this.attachChild(pBaseSprites.get(i)); } } @Override protected boolean onUpdateSpriteBatch() { final SmartList<IEntity> children = this.mChildren; if(children == null) { return false; } else { final int childCount = children.size(); for(int i = 0; i < childCount; i++) { super.drawWithoutChecks((BaseSprite)children.get(i)); } return true; } } // =========================================================== // Methods // =========================================================== private void assertCapacity() { if(this.getChildCount() >= this.mCapacity) { throw new IllegalStateException("This SpriteGroup has already reached its capacity (" + this.mCapacity + ") !"); } } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.entity.sprite; import javax.microedition.khronos.opengles.GL10; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.entity.primitive.BaseRectangle; import org.anddev.andengine.opengl.texture.region.BaseTextureRegion; import org.anddev.andengine.opengl.texture.region.buffer.TextureRegionBuffer; import org.anddev.andengine.opengl.util.GLHelper; import org.anddev.andengine.opengl.vertex.RectangleVertexBuffer; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 11:38:53 - 08.03.2010 */ public abstract class BaseSprite extends BaseRectangle { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== protected final BaseTextureRegion mTextureRegion; // =========================================================== // Constructors // =========================================================== public BaseSprite(final float pX, final float pY, final float pWidth, final float pHeight, final BaseTextureRegion pTextureRegion) { super(pX, pY, pWidth, pHeight); this.mTextureRegion = pTextureRegion; this.initBlendFunction(); } public BaseSprite(final float pX, final float pY, final float pWidth, final float pHeight, final BaseTextureRegion pTextureRegion, final RectangleVertexBuffer pRectangleVertexBuffer) { super(pX, pY, pWidth, pHeight, pRectangleVertexBuffer); this.mTextureRegion = pTextureRegion; this.initBlendFunction(); } // =========================================================== // Getter & Setter // =========================================================== public BaseTextureRegion getTextureRegion() { return this.mTextureRegion; } public void setFlippedHorizontal(final boolean pFlippedHorizontal) { this.mTextureRegion.setFlippedHorizontal(pFlippedHorizontal); } public void setFlippedVertical(final boolean pFlippedVertical) { this.mTextureRegion.setFlippedVertical(pFlippedVertical); } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public void reset() { super.reset(); this.initBlendFunction(); } @Override protected void onInitDraw(final GL10 pGL) { super.onInitDraw(pGL); GLHelper.enableTextures(pGL); GLHelper.enableTexCoordArray(pGL); } @Override protected void doDraw(final GL10 pGL, final Camera pCamera) { this.mTextureRegion.onApply(pGL); super.doDraw(pGL, pCamera); } @Override protected void finalize() throws Throwable { super.finalize(); final TextureRegionBuffer textureRegionBuffer = this.mTextureRegion.getTextureBuffer(); if(textureRegionBuffer.isManaged()) { textureRegionBuffer.unloadFromActiveBufferObjectManager(); } } // =========================================================== // Methods // =========================================================== private void initBlendFunction() { if(this.mTextureRegion.getTexture().getTextureOptions().mPreMultipyAlpha) { this.setBlendFunction(BLENDFUNCTION_SOURCE_PREMULTIPLYALPHA_DEFAULT, BLENDFUNCTION_DESTINATION_PREMULTIPLYALPHA_DEFAULT); } } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java