code
stringlengths
1
2.01M
repo_name
stringlengths
3
62
path
stringlengths
1
267
language
stringclasses
231 values
license
stringclasses
13 values
size
int64
1
2.01M
package org.anddev.andengine.examples; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.handler.timer.ITimerCallback; import org.anddev.andengine.engine.handler.timer.TimerHandler; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.text.ChangeableText; import org.anddev.andengine.entity.util.FPSCounter; import org.anddev.andengine.opengl.font.Font; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import android.graphics.Color; import android.graphics.Typeface; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 20:06:15 - 08.07.2010 */ public class ChangeableTextExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mFontTexture; private Font mFont; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override public void onLoadResources() { this.mFontTexture = new BitmapTextureAtlas(256, 256, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mFont = new Font(this.mFontTexture, Typeface.create(Typeface.DEFAULT, Typeface.BOLD), 48, true, Color.BLACK); this.mEngine.getTextureManager().loadTexture(this.mFontTexture); this.mEngine.getFontManager().loadFont(this.mFont); } @Override public Scene onLoadScene() { final FPSCounter fpsCounter = new FPSCounter(); this.mEngine.registerUpdateHandler(fpsCounter); final Scene scene = new Scene(); scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); final ChangeableText elapsedText = new ChangeableText(100, 160, this.mFont, "Seconds elapsed:", "Seconds elapsed: XXXXX".length()); final ChangeableText fpsText = new ChangeableText(250, 240, this.mFont, "FPS:", "FPS: XXXXX".length()); scene.attachChild(elapsedText); scene.attachChild(fpsText); scene.registerUpdateHandler(new TimerHandler(1 / 20.0f, true, new ITimerCallback() { @Override public void onTimePassed(final TimerHandler pTimerHandler) { elapsedText.setText("Seconds elapsed: " + ChangeableTextExample.this.mEngine.getSecondsElapsedTotal()); fpsText.setText("FPS: " + fpsCounter.getFPS()); } })); return scene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
12anyao-aaa
src/org/anddev/andengine/examples/ChangeableTextExample.java
Java
lgpl
4,074
package org.anddev.andengine.examples; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.sprite.Sprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.input.touch.TouchEvent; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TextureRegion; import android.widget.Toast; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 15:13:46 - 15.06.2010 */ public class TouchDragExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mBitmapTextureAtlas; private TextureRegion mFaceTextureRegion; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { Toast.makeText(this, "Touch & Drag the face!", Toast.LENGTH_LONG).show(); this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override public void onLoadResources() { this.mBitmapTextureAtlas = new BitmapTextureAtlas(32, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "gfx/face_box.png", 0, 0); this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); final int centerX = (CAMERA_WIDTH - this.mFaceTextureRegion.getWidth()) / 2; final int centerY = (CAMERA_HEIGHT - this.mFaceTextureRegion.getHeight()) / 2; final Sprite face = new Sprite(centerX, centerY, this.mFaceTextureRegion) { @Override public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final float pTouchAreaLocalX, final float pTouchAreaLocalY) { this.setPosition(pSceneTouchEvent.getX() - this.getWidth() / 2, pSceneTouchEvent.getY() - this.getHeight() / 2); return true; } }; face.setScale(4); scene.attachChild(face); scene.registerTouchArea(face); scene.setTouchAreaBindingEnabled(true); return scene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
12anyao-aaa
src/org/anddev/andengine/examples/TouchDragExample.java
Java
lgpl
4,108
package org.anddev.andengine.examples; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.primitive.Rectangle; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.Scene.IOnAreaTouchListener; import org.anddev.andengine.entity.scene.Scene.IOnSceneTouchListener; import org.anddev.andengine.entity.scene.Scene.ITouchArea; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.shape.IShape; import org.anddev.andengine.entity.shape.Shape; import org.anddev.andengine.entity.sprite.AnimatedSprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.extension.physics.box2d.PhysicsConnector; import org.anddev.andengine.extension.physics.box2d.PhysicsFactory; import org.anddev.andengine.extension.physics.box2d.PhysicsWorld; import org.anddev.andengine.extension.physics.box2d.util.Vector2Pool; import org.anddev.andengine.extension.physics.box2d.util.constants.PhysicsConstants; import org.anddev.andengine.input.touch.TouchEvent; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TiledTextureRegion; import org.anddev.andengine.sensor.accelerometer.AccelerometerData; import org.anddev.andengine.sensor.accelerometer.IAccelerometerListener; import org.anddev.andengine.util.Debug; import android.hardware.SensorManager; import android.widget.Toast; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.Body; import com.badlogic.gdx.physics.box2d.BodyDef; import com.badlogic.gdx.physics.box2d.BodyDef.BodyType; import com.badlogic.gdx.physics.box2d.FixtureDef; import com.badlogic.gdx.physics.box2d.joints.MouseJoint; import com.badlogic.gdx.physics.box2d.joints.MouseJointDef; /** * @author albrandroid * @author Nicolas Gramlich * @since 10:35:23 - 28.02.2011 */ public class PhysicsMouseJointExample extends BaseExample implements IAccelerometerListener, IOnSceneTouchListener, IOnAreaTouchListener { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; private static final FixtureDef FIXTURE_DEF = PhysicsFactory.createFixtureDef(1, 0.5f, 0.5f); // =========================================================== // Fields // =========================================================== private BitmapTextureAtlas mBitmapTextureAtlas; private TiledTextureRegion mBoxFaceTextureRegion; private TiledTextureRegion mCircleFaceTextureRegion; private Scene mScene; private PhysicsWorld mPhysicsWorld; private int mFaceCount = 0; private MouseJoint mMouseJointActive; private Body mGroundBody; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { Toast.makeText(this, "Touch the screen to add objects.", Toast.LENGTH_LONG).show(); final Camera camera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); final EngineOptions engineOptions = new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), camera); engineOptions.getTouchOptions().setRunOnUpdateThread(true); return new Engine(engineOptions); } @Override public void onLoadResources() { /* Textures. */ this.mBitmapTextureAtlas = new BitmapTextureAtlas(64, 64, TextureOptions.BILINEAR_PREMULTIPLYALPHA); BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); /* TextureRegions. */ this.mBoxFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "face_box_tiled.png", 0, 0, 2, 1); // 64x32 this.mCircleFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "face_circle_tiled.png", 0, 32, 2, 1); // 64x32 this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); this.mScene = new Scene(); this.mScene.setBackground(new ColorBackground(0, 0, 0)); this.mScene.setOnSceneTouchListener(this); this.mScene.setOnAreaTouchListener(this); this.mPhysicsWorld = new PhysicsWorld(new Vector2(0, SensorManager.GRAVITY_EARTH), false); this.mGroundBody = this.mPhysicsWorld.createBody(new BodyDef()); final Shape ground = new Rectangle(0, CAMERA_HEIGHT - 2, CAMERA_WIDTH, 2); final Shape roof = new Rectangle(0, 0, CAMERA_WIDTH, 2); final Shape left = new Rectangle(0, 0, 2, CAMERA_HEIGHT); final Shape right = new Rectangle(CAMERA_WIDTH - 2, 0, 2, CAMERA_HEIGHT); final FixtureDef wallFixtureDef = PhysicsFactory.createFixtureDef(0, 0.5f, 0.5f); PhysicsFactory.createBoxBody(this.mPhysicsWorld, ground, BodyType.StaticBody, wallFixtureDef); PhysicsFactory.createBoxBody(this.mPhysicsWorld, roof, BodyType.StaticBody, wallFixtureDef); PhysicsFactory.createBoxBody(this.mPhysicsWorld, left, BodyType.StaticBody, wallFixtureDef); PhysicsFactory.createBoxBody(this.mPhysicsWorld, right, BodyType.StaticBody, wallFixtureDef); this.mScene.attachChild(ground); this.mScene.attachChild(roof); this.mScene.attachChild(left); this.mScene.attachChild(right); this.mScene.registerUpdateHandler(this.mPhysicsWorld); return this.mScene; } @Override public void onLoadComplete() { this.mEngine.enableVibrator(this); } @Override public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) { if(this.mPhysicsWorld != null) { switch(pSceneTouchEvent.getAction()) { case TouchEvent.ACTION_DOWN: this.addFace(pSceneTouchEvent.getX(), pSceneTouchEvent.getY()); return true; case TouchEvent.ACTION_MOVE: if(this.mMouseJointActive != null) { final Vector2 vec = Vector2Pool.obtain(pSceneTouchEvent.getX() / PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT, pSceneTouchEvent.getY() / PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT); this.mMouseJointActive.setTarget(vec); Vector2Pool.recycle(vec); } return true; case TouchEvent.ACTION_UP: if(this.mMouseJointActive != null) { this.mPhysicsWorld.destroyJoint(this.mMouseJointActive); this.mMouseJointActive = null; } return true; } return false; } return false; } @Override public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final ITouchArea pTouchArea, final float pTouchAreaLocalX, final float pTouchAreaLocalY) { if(pSceneTouchEvent.isActionDown()) { final IShape face = (IShape) pTouchArea; /* * If we have a active MouseJoint, we are just moving it around * instead of creating a second one. */ if(this.mMouseJointActive == null) { this.mEngine.vibrate(100); this.mMouseJointActive = this.createMouseJoint(face, pTouchAreaLocalX, pTouchAreaLocalY); } return true; } return false; } @Override public void onAccelerometerChanged(final AccelerometerData pAccelerometerData) { final Vector2 gravity = Vector2Pool.obtain(pAccelerometerData.getX(), pAccelerometerData.getY()); this.mPhysicsWorld.setGravity(gravity); Vector2Pool.recycle(gravity); } @Override public void onResumeGame() { super.onResumeGame(); this.enableAccelerometerSensor(this); } @Override public void onPauseGame() { super.onPauseGame(); this.disableAccelerometerSensor(); } // =========================================================== // Methods // =========================================================== public MouseJoint createMouseJoint(final IShape pFace, final float pTouchAreaLocalX, final float pTouchAreaLocalY) { final Body body = (Body) pFace.getUserData(); final MouseJointDef mouseJointDef = new MouseJointDef(); final Vector2 localPoint = Vector2Pool.obtain((pTouchAreaLocalX - pFace.getWidth() * 0.5f) / PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT, (pTouchAreaLocalY - pFace.getHeight() * 0.5f) / PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT); this.mGroundBody.setTransform(localPoint, 0); mouseJointDef.bodyA = this.mGroundBody; mouseJointDef.bodyB = body; mouseJointDef.dampingRatio = 0.95f; mouseJointDef.frequencyHz = 30; mouseJointDef.maxForce = (200.0f * body.getMass()); mouseJointDef.collideConnected = true; mouseJointDef.target.set(body.getWorldPoint(localPoint)); Vector2Pool.recycle(localPoint); return (MouseJoint) this.mPhysicsWorld.createJoint(mouseJointDef); } private void addFace(final float pX, final float pY) { this.mFaceCount++; Debug.d("Faces: " + this.mFaceCount); final AnimatedSprite face; final Body body; if(this.mFaceCount % 2 == 0) { face = new AnimatedSprite(pX, pY, this.mBoxFaceTextureRegion); body = PhysicsFactory.createBoxBody(this.mPhysicsWorld, face, BodyType.DynamicBody, FIXTURE_DEF); } else { face = new AnimatedSprite(pX, pY, this.mCircleFaceTextureRegion); body = PhysicsFactory.createCircleBody(this.mPhysicsWorld, face, BodyType.DynamicBody, FIXTURE_DEF); } face.setUserData(body); face.animate(200); this.mScene.registerTouchArea(face); this.mScene.attachChild(face); this.mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(face, body, true, true)); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
12anyao-aaa
src/org/anddev/andengine/examples/PhysicsMouseJointExample.java
Java
lgpl
10,579
package org.anddev.andengine.examples.app.cityradar; import java.util.ArrayList; import java.util.HashMap; import javax.microedition.khronos.opengles.GL10; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.camera.hud.HUD; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.FillResolutionPolicy; import org.anddev.andengine.entity.IEntity; import org.anddev.andengine.entity.modifier.LoopEntityModifier; import org.anddev.andengine.entity.modifier.RotationModifier; import org.anddev.andengine.entity.primitive.Line; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.sprite.Sprite; import org.anddev.andengine.entity.text.Text; import org.anddev.andengine.examples.adt.cityradar.City; import org.anddev.andengine.opengl.font.Font; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.atlas.bitmap.BuildableBitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.source.IBitmapTextureAtlasSource; import org.anddev.andengine.opengl.texture.buildable.builder.BlackPawnTextureBuilder; import org.anddev.andengine.opengl.texture.buildable.builder.ITextureBuilder.TextureAtlasSourcePackingException; import org.anddev.andengine.opengl.texture.region.TextureRegion; 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.ui.activity.BaseGameActivity; import org.anddev.andengine.util.Debug; import org.anddev.andengine.util.MathUtils; import org.anddev.andengine.util.modifier.ease.EaseLinear; import android.graphics.Color; import android.graphics.Typeface; import android.location.Criteria; import android.location.Location; import android.location.LocationManager; import android.os.Bundle; public class CityRadarActivity extends BaseGameActivity implements IOrientationListener, ILocationListener { // =========================================================== // Constants // =========================================================== private static final boolean USE_MOCK_LOCATION = false; private static final boolean USE_ACTUAL_LOCATION = !USE_MOCK_LOCATION; private static final int CAMERA_WIDTH = 480; private static final int CAMERA_HEIGHT = 800; private static final int GRID_SIZE = 80; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BuildableBitmapTextureAtlas mBuildableBitmapTextureAtlas; private TextureRegion mRadarPointTextureRegion; private TextureRegion mRadarTextureRegion; private BitmapTextureAtlas mFontTexture; private Font mFont; private Location mUserLocation; private final ArrayList<City> mCities = new ArrayList<City>(); private final HashMap<City, Sprite> mCityToCitySpriteMap = new HashMap<City, Sprite>(); private final HashMap<City, Text> mCityToCityNameTextMap = new HashMap<City, Text>(); private Scene mScene; // =========================================================== // Constructors // =========================================================== public CityRadarActivity() { this.mCities.add(new City("London", 51.509, -0.118)); this.mCities.add(new City("New York", 40.713, -74.006)); // this.mCities.add(new City("Paris", 48.857, 2.352)); this.mCities.add(new City("Beijing", 39.929, 116.388)); this.mCities.add(new City("Sydney", -33.850, 151.200)); this.mCities.add(new City("Berlin", 52.518, 13.408)); this.mCities.add(new City("Rio", -22.908, -43.196)); this.mCities.add(new City("New Delhi", 28.636, 77.224)); this.mCities.add(new City("Cape Town", -33.926, 18.424)); this.mUserLocation = new Location(LocationManager.GPS_PROVIDER); if(USE_MOCK_LOCATION) { this.mUserLocation.setLatitude(51.518); this.mUserLocation.setLongitude(13.408); } } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public org.anddev.andengine.engine.Engine onLoadEngine() { this.mCamera = new Camera(0, 0, CityRadarActivity.CAMERA_WIDTH, CityRadarActivity.CAMERA_HEIGHT); return new org.anddev.andengine.engine.Engine(new EngineOptions(true, ScreenOrientation.PORTRAIT, new FillResolutionPolicy(), this.mCamera)); } @Override public void onLoadResources() { /* Init font. */ this.mFontTexture = new BitmapTextureAtlas(256, 256, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mFont = new Font(this.mFontTexture, Typeface.DEFAULT, 12, true, Color.WHITE); this.mEngine.getFontManager().loadFont(this.mFont); this.mEngine.getTextureManager().loadTexture(this.mFontTexture); /* Init TextureRegions. */ this.mBuildableBitmapTextureAtlas = new BuildableBitmapTextureAtlas(512, 256, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mRadarTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBuildableBitmapTextureAtlas, this, "gfx/radar.png"); this.mRadarPointTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBuildableBitmapTextureAtlas, this, "gfx/radarpoint.png"); try { this.mBuildableBitmapTextureAtlas.build(new BlackPawnTextureBuilder<IBitmapTextureAtlasSource, BitmapTextureAtlas>(1)); } catch (final TextureAtlasSourcePackingException e) { Debug.e(e); } this.mEngine.getTextureManager().loadTexture(this.mBuildableBitmapTextureAtlas); } @Override public Scene onLoadScene() { this.mScene = new Scene(); final HUD hud = new HUD(); this.mCamera.setHUD(hud); /* BACKGROUND */ this.initBackground(hud); /* CITIES */ this.initCitySprites(); return this.mScene; } private void initCitySprites() { final int cityCount = this.mCities.size(); for(int i = 0; i < cityCount; i++) { final City city = this.mCities.get(i); final Sprite citySprite = new Sprite(CityRadarActivity.CAMERA_WIDTH / 2, CityRadarActivity.CAMERA_HEIGHT / 2, this.mRadarPointTextureRegion); citySprite.setColor(0, 0.5f, 0, 1f); final Text cityNameText = new Text(CAMERA_WIDTH / 2, CAMERA_HEIGHT / 2, this.mFont, city.getName()) { @Override protected void onManagedDraw(final GL10 pGL, final Camera pCamera) { /* This ensures that the name of the city is always 'pointing down'. */ this.setRotation(-CityRadarActivity.this.mCamera.getRotation()); super.onManagedDraw(pGL, pCamera); } }; cityNameText.setRotationCenterY(- citySprite.getHeight() / 2); this.mCityToCityNameTextMap.put(city, cityNameText); this.mCityToCitySpriteMap.put(city, citySprite); this.mScene.attachChild(citySprite); this.mScene.attachChild(cityNameText); } } private void initBackground(final IEntity pEntity) { /* Vertical Grid lines. */ for(int i = CityRadarActivity.GRID_SIZE / 2; i < CityRadarActivity.CAMERA_WIDTH; i += CityRadarActivity.GRID_SIZE) { final Line line = new Line(i, 0, i, CityRadarActivity.CAMERA_HEIGHT); line.setColor(0, 0.5f, 0, 1f); pEntity.attachChild(line); } /* Horizontal Grid lines. */ for(int i = CityRadarActivity.GRID_SIZE / 2; i < CityRadarActivity.CAMERA_HEIGHT; i += CityRadarActivity.GRID_SIZE) { final Line line = new Line(0, i, CityRadarActivity.CAMERA_WIDTH, i); line.setColor(0, 0.5f, 0, 1f); pEntity.attachChild(line); } /* Vertical Grid lines. */ final Sprite radarSprite = new Sprite(CityRadarActivity.CAMERA_WIDTH / 2 - this.mRadarTextureRegion.getWidth(), CityRadarActivity.CAMERA_HEIGHT / 2 - this.mRadarTextureRegion.getHeight(), this.mRadarTextureRegion); radarSprite.setColor(0, 1f, 0, 1f); radarSprite.setRotationCenter(radarSprite.getWidth(), radarSprite.getHeight()); radarSprite.registerEntityModifier(new LoopEntityModifier(new RotationModifier(3, 0, 360, EaseLinear.getInstance()))); pEntity.attachChild(radarSprite); /* Title. */ final Text titleText = new Text(0, 0, this.mFont, "-- CityRadar --"); titleText.setPosition(CAMERA_WIDTH / 2 - titleText.getWidth() / 2, titleText.getHeight() + 35); titleText.setScale(2); titleText.setScaleCenterY(0); pEntity.attachChild(titleText); } @Override public void onLoadComplete() { this.refreshCitySprites(); } @Override protected void onResume() { super.onResume(); this.enableOrientationSensor(this); final LocationSensorOptions locationSensorOptions = new LocationSensorOptions(); locationSensorOptions.setAccuracy(Criteria.ACCURACY_COARSE); locationSensorOptions.setMinimumTriggerTime(0); locationSensorOptions.setMinimumTriggerDistance(0); this.enableLocationSensor(this, locationSensorOptions); } @Override protected void onPause() { super.onPause(); this.mEngine.disableOrientationSensor(this); this.mEngine.disableLocationSensor(this); } @Override public void onOrientationChanged(final OrientationData pOrientationData) { this.mCamera.setRotation(-pOrientationData.getYaw()); } @Override public void onLocationChanged(final Location pLocation) { if(USE_ACTUAL_LOCATION) { this.mUserLocation = pLocation; } this.refreshCitySprites(); } @Override public void onLocationLost() { } @Override public void onLocationProviderDisabled() { } @Override public void onLocationProviderEnabled() { } @Override public void onLocationProviderStatusChanged(final LocationProviderStatus pLocationProviderStatus, final Bundle pBundle) { } // =========================================================== // Methods // =========================================================== private void refreshCitySprites() { final double userLatitudeRad = MathUtils.degToRad((float) this.mUserLocation.getLatitude()); final double userLongitudeRad = MathUtils.degToRad((float) this.mUserLocation.getLongitude()); final int cityCount = this.mCities.size(); double maxDistance = Double.MIN_VALUE; /* Calculate the distances and bearings of the cities to the location of the user. */ for(int i = 0; i < cityCount; i++) { final City city = this.mCities.get(i); final double cityLatitudeRad = MathUtils.degToRad((float) city.getLatitude()); final double cityLongitudeRad = MathUtils.degToRad((float) city.getLongitude()); city.setDistanceToUser(GeoMath.calculateDistance(userLatitudeRad, userLongitudeRad, cityLatitudeRad, cityLongitudeRad)); city.setBearingToUser(GeoMath.calculateBearing(userLatitudeRad, userLongitudeRad, cityLatitudeRad, cityLongitudeRad)); maxDistance = Math.max(maxDistance, city.getDistanceToUser()); } /* Calculate a scaleRatio so that all cities are visible at all times. */ final double scaleRatio = (CityRadarActivity.CAMERA_WIDTH / 2) / maxDistance * 0.93f; for(int i = 0; i < cityCount; i++) { final City city = this.mCities.get(i); final Sprite citySprite = this.mCityToCitySpriteMap.get(city); final Text cityNameText = this.mCityToCityNameTextMap.get(city); final float bearingInRad = MathUtils.degToRad(90 - (float) city.getBearingToUser()); final float x = (float) (CityRadarActivity.CAMERA_WIDTH / 2 + city.getDistanceToUser() * scaleRatio * Math.cos(bearingInRad)); final float y = (float) (CityRadarActivity.CAMERA_HEIGHT / 2 - city.getDistanceToUser() * scaleRatio * Math.sin(bearingInRad)); citySprite.setPosition(x - citySprite.getWidth() / 2, y - citySprite.getHeight() / 2); final float textX = x - cityNameText.getWidth() / 2; final float textY = y + citySprite.getHeight() / 2; cityNameText.setPosition(textX, textY); } } // =========================================================== // Inner and Anonymous Classes // =========================================================== /** * Note: Formulas taken from <a href="http://www.movable-type.co.uk/scripts/latlong.html">here</a>. */ private static class GeoMath { // =========================================================== // Constants // =========================================================== private static final double RADIUS_EARTH_METERS = 6371000; // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== /** * @return the distance in meters. */ public static double calculateDistance(final double pLatitude1, final double pLongitude1, final double pLatitude2, final double pLongitude2) { return Math.acos(Math.sin(pLatitude1) * Math.sin(pLatitude2) + Math.cos(pLatitude1) * Math.cos(pLatitude2) * Math.cos(pLongitude2 - pLongitude1)) * RADIUS_EARTH_METERS; } /** * @return the bearing in degrees. */ public static double calculateBearing(final double pLatitude1, final double pLongitude1, final double pLatitude2, final double pLongitude2) { final double y = Math.sin(pLongitude2 - pLongitude1) * Math.cos(pLatitude2); final double x = Math.cos(pLatitude1) * Math.sin(pLatitude2) - Math.sin(pLatitude1) * Math.cos(pLatitude2) * Math.cos(pLongitude2 - pLongitude1); final float bearing = MathUtils.radToDeg((float) Math.atan2(y, x)); return (bearing + 360) % 360; } // =========================================================== // Inner and Anonymous Classes // =========================================================== } }
12anyao-aaa
src/org/anddev/andengine/examples/app/cityradar/CityRadarActivity.java
Java
lgpl
14,591
package org.anddev.andengine.examples; import java.io.IOException; import java.io.InputStream; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.SmoothCamera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.Scene.IOnSceneTouchListener; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.sprite.Sprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.examples.adt.ZoomState; import org.anddev.andengine.input.touch.TouchEvent; import org.anddev.andengine.opengl.texture.ITexture; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.compressed.pvr.PVRGZTexture; import org.anddev.andengine.opengl.texture.compressed.pvr.PVRTexture.PVRTextureFormat; import org.anddev.andengine.opengl.texture.region.TextureRegion; import org.anddev.andengine.opengl.texture.region.TextureRegionFactory; import org.anddev.andengine.util.Debug; import android.widget.Toast; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 13:54:51 - 13.07.2011 */ public class PVRGZTextureExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; // =========================================================== // Fields // =========================================================== private SmoothCamera mSmoothCamera; private ITexture mTexture; private TextureRegion mHouseTextureRegion; private ZoomState mZoomState = ZoomState.NONE; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { Toast.makeText(this, "Click the top half of the screen to zoom in or the bottom half to zoom out!", Toast.LENGTH_LONG); this.mSmoothCamera = new SmoothCamera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT, 0, 0, 0.1f) { @Override public void onUpdate(final float pSecondsElapsed) { switch (PVRGZTextureExample.this.mZoomState) { case IN: this.setZoomFactor(this.getZoomFactor() + 0.1f * pSecondsElapsed); break; case OUT: this.setZoomFactor(this.getZoomFactor() - 0.1f * pSecondsElapsed); break; } super.onUpdate(pSecondsElapsed); } }; return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mSmoothCamera)); } @Override public void onLoadResources() { try { this.mTexture = new PVRGZTexture(PVRTextureFormat.RGBA_8888, TextureOptions.BILINEAR) { @Override protected InputStream getInputStream() throws IOException { return PVRGZTextureExample.this.getResources().openRawResource(R.raw.house_pvrgz_argb_8888); } }; this.mHouseTextureRegion = TextureRegionFactory.extractFromTexture(this.mTexture, 0, 0, 512, 512, true); this.mEngine.getTextureManager().loadTextures(this.mTexture); } catch (final Throwable e) { Debug.e(e); } } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); final int centerX = (CAMERA_WIDTH - this.mHouseTextureRegion.getWidth()) / 2; final int centerY = (CAMERA_HEIGHT - this.mHouseTextureRegion.getHeight()) / 2; scene.attachChild(new Sprite(centerX, centerY, this.mHouseTextureRegion)); scene.setOnSceneTouchListener(new IOnSceneTouchListener() { @Override public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) { if (pSceneTouchEvent.isActionDown() || pSceneTouchEvent.isActionMove()) { if(pSceneTouchEvent.getY() < CAMERA_HEIGHT / 2) { PVRGZTextureExample.this.mZoomState = ZoomState.IN; } else { PVRGZTextureExample.this.mZoomState = ZoomState.OUT; } } else { PVRGZTextureExample.this.mZoomState = ZoomState.NONE; } return true; } }); return scene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
12anyao-aaa
src/org/anddev/andengine/examples/PVRGZTextureExample.java
Java
lgpl
5,314
package org.anddev.andengine.examples; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.SingleSceneSplitScreenEngine; import org.anddev.andengine.engine.camera.BoundCamera; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.primitive.Rectangle; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.Scene.IOnSceneTouchListener; import org.anddev.andengine.entity.shape.Shape; import org.anddev.andengine.entity.sprite.AnimatedSprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.extension.physics.box2d.PhysicsConnector; import org.anddev.andengine.extension.physics.box2d.PhysicsFactory; import org.anddev.andengine.extension.physics.box2d.PhysicsWorld; import org.anddev.andengine.extension.physics.box2d.util.Vector2Pool; import org.anddev.andengine.input.touch.TouchEvent; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TiledTextureRegion; import org.anddev.andengine.sensor.accelerometer.AccelerometerData; import org.anddev.andengine.sensor.accelerometer.IAccelerometerListener; import android.hardware.SensorManager; import android.widget.Toast; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.Body; import com.badlogic.gdx.physics.box2d.BodyDef.BodyType; import com.badlogic.gdx.physics.box2d.FixtureDef; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 18:47:08 - 19.03.2010 */ public class SplitScreenExample extends BaseExample implements IAccelerometerListener, IOnSceneTouchListener { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 400; private static final int CAMERA_HEIGHT = 480; // =========================================================== // Fields // =========================================================== private Camera mCamera; private Camera mChaseCamera; private BitmapTextureAtlas mBitmapTextureAtlas; private TiledTextureRegion mBoxFaceTextureRegion; private Scene mScene; private PhysicsWorld mPhysicsWorld; private int mFaceCount; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { Toast.makeText(this, "Touch the screen to add boxes.", Toast.LENGTH_LONG).show(); this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); this.mChaseCamera = new BoundCamera(0, 0, CAMERA_WIDTH / 2, CAMERA_HEIGHT / 2, 0, CAMERA_WIDTH, 0, CAMERA_HEIGHT); final EngineOptions engineOptions = new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH * 2, CAMERA_HEIGHT), this.mCamera); engineOptions.getTouchOptions().setRunOnUpdateThread(true); return new SingleSceneSplitScreenEngine(engineOptions, this.mChaseCamera); } @Override public void onLoadResources() { this.mBitmapTextureAtlas = new BitmapTextureAtlas(64, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mBoxFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "gfx/face_box_tiled.png", 0, 0, 2, 1); // 64x32 this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); this.mScene = new Scene(); this.mScene.setOnSceneTouchListener(this); this.mPhysicsWorld = new PhysicsWorld(new Vector2(0, SensorManager.GRAVITY_EARTH), false); final Shape ground = new Rectangle(0, CAMERA_HEIGHT - 2, CAMERA_WIDTH, 2); final Shape roof = new Rectangle(0, 0, CAMERA_WIDTH, 2); final Shape left = new Rectangle(0, 0, 2, CAMERA_HEIGHT); final Shape right = new Rectangle(CAMERA_WIDTH - 2, 0, 2, CAMERA_HEIGHT); final FixtureDef wallFixtureDef = PhysicsFactory.createFixtureDef(0, 0.5f, 0.5f); PhysicsFactory.createBoxBody(this.mPhysicsWorld, ground, BodyType.StaticBody, wallFixtureDef); PhysicsFactory.createBoxBody(this.mPhysicsWorld, roof, BodyType.StaticBody, wallFixtureDef); PhysicsFactory.createBoxBody(this.mPhysicsWorld, left, BodyType.StaticBody, wallFixtureDef); PhysicsFactory.createBoxBody(this.mPhysicsWorld, right, BodyType.StaticBody, wallFixtureDef); this.mScene.attachChild(ground); this.mScene.attachChild(roof); this.mScene.attachChild(left); this.mScene.attachChild(right); this.mScene.registerUpdateHandler(this.mPhysicsWorld); return this.mScene; } @Override public void onLoadComplete() { } @Override public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) { if(this.mPhysicsWorld != null) { if(pSceneTouchEvent.isActionDown()) { this.addFace(pSceneTouchEvent.getX(), pSceneTouchEvent.getY()); return true; } } return false; } @Override public void onAccelerometerChanged(final AccelerometerData pAccelerometerData) { final Vector2 gravity = Vector2Pool.obtain(pAccelerometerData.getX(), pAccelerometerData.getY()); this.mPhysicsWorld.setGravity(gravity); Vector2Pool.recycle(gravity); } @Override public void onResumeGame() { super.onResumeGame(); this.enableAccelerometerSensor(this); } @Override public void onPauseGame() { super.onPauseGame(); this.disableAccelerometerSensor(); } // =========================================================== // Methods // =========================================================== private void addFace(final float pX, final float pY) { final FixtureDef objectFixtureDef = PhysicsFactory.createFixtureDef(1, 0.5f, 0.5f); final AnimatedSprite face = new AnimatedSprite(pX, pY, this.mBoxFaceTextureRegion).animate(100); final Body body = PhysicsFactory.createBoxBody(this.mPhysicsWorld, face, BodyType.DynamicBody, objectFixtureDef); this.mScene.attachChild(face); this.mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(face, body, true, true)); if(this.mFaceCount == 0){ this.mChaseCamera.setChaseEntity(face); } this.mFaceCount++; } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
12anyao-aaa
src/org/anddev/andengine/examples/SplitScreenExample.java
Java
lgpl
7,288
package org.anddev.andengine.examples; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.IEntity; import org.anddev.andengine.entity.modifier.IEntityModifier.IEntityModifierListener; import org.anddev.andengine.entity.modifier.ParallelEntityModifier; import org.anddev.andengine.entity.modifier.RotationByModifier; import org.anddev.andengine.entity.modifier.RotationModifier; import org.anddev.andengine.entity.modifier.ScaleModifier; import org.anddev.andengine.entity.modifier.SequenceEntityModifier; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.sprite.AnimatedSprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TiledTextureRegion; import org.anddev.andengine.util.modifier.IModifier; import android.widget.Toast; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 21:42:39 - 06.07.2010 */ public class EntityModifierIrregularExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mBitmapTextureAtlas; private TiledTextureRegion mFaceTextureRegion; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { Toast.makeText(this, "Shapes can have variable rotation and scale centers.", Toast.LENGTH_LONG).show(); this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override public void onLoadResources() { this.mBitmapTextureAtlas = new BitmapTextureAtlas(64, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "gfx/face_box_tiled.png", 0, 0, 2, 1); this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); final int centerX = (CAMERA_WIDTH - this.mFaceTextureRegion.getWidth()) / 2; final int centerY = (CAMERA_HEIGHT - this.mFaceTextureRegion.getHeight()) / 2; final AnimatedSprite face1 = new AnimatedSprite(centerX - 100, centerY, this.mFaceTextureRegion); face1.setRotationCenter(0, 0); face1.setScaleCenter(0, 0); face1.animate(100); final AnimatedSprite face2 = new AnimatedSprite(centerX + 100, centerY, this.mFaceTextureRegion); face2.animate(100); final SequenceEntityModifier entityModifier = new SequenceEntityModifier( new IEntityModifierListener() { @Override public void onModifierStarted(final IModifier<IEntity> pModifier, final IEntity pItem) { EntityModifierIrregularExample.this.runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(EntityModifierIrregularExample.this, "Sequence started.", Toast.LENGTH_LONG).show(); } }); } @Override public void onModifierFinished(final IModifier<IEntity> pEntityModifier, final IEntity pEntity) { EntityModifierIrregularExample.this.runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(EntityModifierIrregularExample.this, "Sequence finished.", Toast.LENGTH_LONG).show(); } }); } }, new ScaleModifier(2, 1.0f, 0.75f, 1.0f, 2.0f), new ScaleModifier(2, 0.75f, 2.0f, 2.0f, 1.25f), new ParallelEntityModifier( new ScaleModifier(3, 2.0f, 5.0f, 1.25f, 5.0f), new RotationByModifier(3, 180) ), new ParallelEntityModifier( new ScaleModifier(3, 5, 1), new RotationModifier(3, 180, 0) ) ); face1.registerEntityModifier(entityModifier); face2.registerEntityModifier(entityModifier.clone()); scene.attachChild(face1); scene.attachChild(face2); /* Create some not-modified sprites, that act as fixed references to the modified ones. */ final AnimatedSprite face1Reference = new AnimatedSprite(centerX - 100, centerY, this.mFaceTextureRegion); final AnimatedSprite face2Reference = new AnimatedSprite(centerX + 100, centerY, this.mFaceTextureRegion); scene.attachChild(face1Reference); scene.attachChild(face2Reference); return scene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
12anyao-aaa
src/org/anddev/andengine/examples/EntityModifierIrregularExample.java
Java
lgpl
6,259
package org.anddev.andengine.examples; import java.io.IOException; import java.io.InputStream; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.SmoothCamera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.Scene.IOnSceneTouchListener; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.sprite.Sprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.examples.adt.ZoomState; import org.anddev.andengine.input.touch.TouchEvent; import org.anddev.andengine.opengl.texture.ITexture; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.compressed.pvr.PVRCCZTexture; import org.anddev.andengine.opengl.texture.compressed.pvr.PVRTexture.PVRTextureFormat; import org.anddev.andengine.opengl.texture.region.TextureRegion; import org.anddev.andengine.opengl.texture.region.TextureRegionFactory; import org.anddev.andengine.util.Debug; import android.widget.Toast; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 15:31:11 - 27.07.2011 */ public class PVRCCZTextureExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; // =========================================================== // Fields // =========================================================== private SmoothCamera mSmoothCamera; private ITexture mTexture; private TextureRegion mHouseTextureRegion; private ZoomState mZoomState = ZoomState.NONE; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { Toast.makeText(this, "Click the top half of the screen to zoom in or the bottom half to zoom out!", Toast.LENGTH_LONG); this.mSmoothCamera = new SmoothCamera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT, 0, 0, 0.1f) { @Override public void onUpdate(final float pSecondsElapsed) { switch (PVRCCZTextureExample.this.mZoomState) { case IN: this.setZoomFactor(this.getZoomFactor() + 0.1f * pSecondsElapsed); break; case OUT: this.setZoomFactor(this.getZoomFactor() - 0.1f * pSecondsElapsed); break; } super.onUpdate(pSecondsElapsed); } }; return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mSmoothCamera)); } @Override public void onLoadResources() { try { this.mTexture = new PVRCCZTexture(PVRTextureFormat.RGBA_8888, TextureOptions.BILINEAR) { @Override protected InputStream getInputStream() throws IOException { return PVRCCZTextureExample.this.getResources().openRawResource(R.raw.house_pvrccz_argb_8888); } }; this.mHouseTextureRegion = TextureRegionFactory.extractFromTexture(this.mTexture, 0, 0, 512, 512, true); this.mEngine.getTextureManager().loadTextures(this.mTexture); } catch (final Throwable e) { Debug.e(e); } } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); final int centerX = (CAMERA_WIDTH - this.mHouseTextureRegion.getWidth()) / 2; final int centerY = (CAMERA_HEIGHT - this.mHouseTextureRegion.getHeight()) / 2; scene.attachChild(new Sprite(centerX, centerY, this.mHouseTextureRegion)); scene.setOnSceneTouchListener(new IOnSceneTouchListener() { @Override public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) { if (pSceneTouchEvent.isActionDown() || pSceneTouchEvent.isActionMove()) { if(pSceneTouchEvent.getY() < CAMERA_HEIGHT / 2) { PVRCCZTextureExample.this.mZoomState = ZoomState.IN; } else { PVRCCZTextureExample.this.mZoomState = ZoomState.OUT; } } else { PVRCCZTextureExample.this.mZoomState = ZoomState.NONE; } return true; } }); return scene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
12anyao-aaa
src/org/anddev/andengine/examples/PVRCCZTextureExample.java
Java
lgpl
5,323
package org.anddev.andengine.examples; import org.anddev.andengine.ui.activity.BaseGameActivity; import android.view.Menu; import android.view.MenuItem; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 22:10:28 - 11.04.2010 */ public abstract class BaseExample extends BaseGameActivity { // =========================================================== // Constants // =========================================================== private static final int MENU_TRACE = Menu.FIRST; // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public boolean onCreateOptionsMenu(final Menu pMenu) { pMenu.add(Menu.NONE, MENU_TRACE, Menu.NONE, "Start Method Tracing"); return super.onCreateOptionsMenu(pMenu); } @Override public boolean onPrepareOptionsMenu(final Menu pMenu) { pMenu.findItem(MENU_TRACE).setTitle(this.mEngine.isMethodTracing() ? "Stop Method Tracing" : "Start Method Tracing"); return super.onPrepareOptionsMenu(pMenu); } @Override public boolean onMenuItemSelected(final int pFeatureId, final MenuItem pItem) { switch(pItem.getItemId()) { case MENU_TRACE: if(this.mEngine.isMethodTracing()) { this.mEngine.stopMethodTracing(); } else { this.mEngine.startMethodTracing("AndEngine_" + System.currentTimeMillis() + ".trace"); } return true; default: return super.onMenuItemSelected(pFeatureId, pItem); } } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
12anyao-aaa
src/org/anddev/andengine/examples/BaseExample.java
Java
lgpl
2,366
package org.anddev.andengine.examples; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.primitive.Rectangle; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.Scene.IOnSceneTouchListener; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.shape.Shape; import org.anddev.andengine.entity.sprite.AnimatedSprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.extension.physics.box2d.PhysicsConnector; import org.anddev.andengine.extension.physics.box2d.PhysicsFactory; import org.anddev.andengine.extension.physics.box2d.PhysicsWorld; import org.anddev.andengine.extension.physics.box2d.util.Vector2Pool; import org.anddev.andengine.input.touch.TouchEvent; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TiledTextureRegion; import org.anddev.andengine.sensor.accelerometer.AccelerometerData; import org.anddev.andengine.sensor.accelerometer.IAccelerometerListener; import org.anddev.andengine.util.Debug; import android.hardware.SensorManager; import android.widget.Toast; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.Body; import com.badlogic.gdx.physics.box2d.BodyDef.BodyType; import com.badlogic.gdx.physics.box2d.FixtureDef; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 14:33:38 - 03.10.2010 */ public class PhysicsCollisionFilteringExample extends BaseExample implements IAccelerometerListener, IOnSceneTouchListener { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; /* The categories. */ public static final short CATEGORYBIT_WALL = 1; public static final short CATEGORYBIT_BOX = 2; public static final short CATEGORYBIT_CIRCLE = 4; /* And what should collide with what. */ public static final short MASKBITS_WALL = CATEGORYBIT_WALL + CATEGORYBIT_BOX + CATEGORYBIT_CIRCLE; public static final short MASKBITS_BOX = CATEGORYBIT_WALL + CATEGORYBIT_BOX; // Missing: CATEGORYBIT_CIRCLE public static final short MASKBITS_CIRCLE = CATEGORYBIT_WALL + CATEGORYBIT_CIRCLE; // Missing: CATEGORYBIT_BOX public static final FixtureDef WALL_FIXTURE_DEF = PhysicsFactory.createFixtureDef(0, 0.5f, 0.5f, false, CATEGORYBIT_WALL, MASKBITS_WALL, (short)0); public static final FixtureDef BOX_FIXTURE_DEF = PhysicsFactory.createFixtureDef(1, 0.5f, 0.5f, false, CATEGORYBIT_BOX, MASKBITS_BOX, (short)0); public static final FixtureDef CIRCLE_FIXTURE_DEF = PhysicsFactory.createFixtureDef(1, 0.5f, 0.5f, false, CATEGORYBIT_CIRCLE, MASKBITS_CIRCLE, (short)0); // =========================================================== // Fields // =========================================================== private BitmapTextureAtlas mBitmapTextureAtlas; private TiledTextureRegion mBoxFaceTextureRegion; private TiledTextureRegion mCircleFaceTextureRegion; private Scene mScene; private PhysicsWorld mPhysicsWorld; private int mFaceCount = 0; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { Toast.makeText(this, "Touch the screen to add objects.", Toast.LENGTH_LONG).show(); Toast.makeText(this, "Boxes will only collide with boxes.\nCircles will only collide with circles.", Toast.LENGTH_LONG).show(); final Camera camera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); final EngineOptions engineOptions = new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), camera); engineOptions.getTouchOptions().setRunOnUpdateThread(true); return new Engine(engineOptions); } @Override public void onLoadResources() { /* Textures. */ this.mBitmapTextureAtlas = new BitmapTextureAtlas(64, 64, TextureOptions.BILINEAR_PREMULTIPLYALPHA); BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); /* TextureRegions. */ this.mBoxFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "face_box_tiled.png", 0, 0, 2, 1); // 64x32 this.mCircleFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "face_circle_tiled.png", 0, 32, 2, 1); // 64x32 this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); this.mScene = new Scene(); this.mScene.setBackground(new ColorBackground(0, 0, 0)); this.mScene.setOnSceneTouchListener(this); this.mPhysicsWorld = new PhysicsWorld(new Vector2(0, SensorManager.GRAVITY_EARTH), false); final Shape ground = new Rectangle(0, CAMERA_HEIGHT - 2, CAMERA_WIDTH, 2); final Shape roof = new Rectangle(0, 0, CAMERA_WIDTH, 2); final Shape left = new Rectangle(0, 0, 2, CAMERA_HEIGHT); final Shape right = new Rectangle(CAMERA_WIDTH - 2, 0, 2, CAMERA_HEIGHT); PhysicsFactory.createBoxBody(this.mPhysicsWorld, ground, BodyType.StaticBody, WALL_FIXTURE_DEF); PhysicsFactory.createBoxBody(this.mPhysicsWorld, roof, BodyType.StaticBody, WALL_FIXTURE_DEF); PhysicsFactory.createBoxBody(this.mPhysicsWorld, left, BodyType.StaticBody, WALL_FIXTURE_DEF); PhysicsFactory.createBoxBody(this.mPhysicsWorld, right, BodyType.StaticBody, WALL_FIXTURE_DEF); this.mScene.attachChild(ground); this.mScene.attachChild(roof); this.mScene.attachChild(left); this.mScene.attachChild(right); this.mScene.registerUpdateHandler(this.mPhysicsWorld); return this.mScene; } @Override public void onLoadComplete() { } @Override public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) { if(this.mPhysicsWorld != null) { if(pSceneTouchEvent.isActionDown()) { this.addFace(pSceneTouchEvent.getX(), pSceneTouchEvent.getY()); return true; } } return false; } @Override public void onAccelerometerChanged(final AccelerometerData pAccelerometerData) { final Vector2 gravity = Vector2Pool.obtain(pAccelerometerData.getX(), pAccelerometerData.getY()); this.mPhysicsWorld.setGravity(gravity); Vector2Pool.recycle(gravity); } @Override public void onResumeGame() { super.onResumeGame(); this.enableAccelerometerSensor(this); } @Override public void onPauseGame() { super.onPauseGame(); this.disableAccelerometerSensor(); } // =========================================================== // Methods // =========================================================== private void addFace(final float pX, final float pY) { this.mFaceCount++; Debug.d("Faces: " + this.mFaceCount); final AnimatedSprite face; final Body body; if(this.mFaceCount % 2 == 0) { face = new AnimatedSprite(pX, pY, this.mBoxFaceTextureRegion); body = PhysicsFactory.createBoxBody(this.mPhysicsWorld, face, BodyType.DynamicBody, BOX_FIXTURE_DEF); } else { face = new AnimatedSprite(pX, pY, this.mCircleFaceTextureRegion); body = PhysicsFactory.createCircleBody(this.mPhysicsWorld, face, BodyType.DynamicBody, CIRCLE_FIXTURE_DEF); } face.animate(200); this.mScene.attachChild(face); this.mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(face, body, true, true)); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
12anyao-aaa
src/org/anddev/andengine/examples/PhysicsCollisionFilteringExample.java
Java
lgpl
8,668
package org.anddev.andengine.examples; import java.io.IOException; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.sprite.AnimatedSprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.level.LevelLoader; import org.anddev.andengine.level.LevelLoader.IEntityLoader; import org.anddev.andengine.level.util.constants.LevelConstants; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TiledTextureRegion; import org.anddev.andengine.util.Debug; import org.anddev.andengine.util.SAXUtils; import org.xml.sax.Attributes; import android.widget.Toast; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 17:16:10 - 11.10.2010 */ public class LevelLoaderExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 480; private static final int CAMERA_HEIGHT = 320; private static final String TAG_ENTITY = "entity"; private static final String TAG_ENTITY_ATTRIBUTE_X = "x"; private static final String TAG_ENTITY_ATTRIBUTE_Y = "y"; private static final String TAG_ENTITY_ATTRIBUTE_WIDTH = "width"; private static final String TAG_ENTITY_ATTRIBUTE_HEIGHT = "height"; private static final String TAG_ENTITY_ATTRIBUTE_TYPE = "type"; private static final Object TAG_ENTITY_ATTRIBUTE_TYPE_VALUE_BOX = "box"; private static final Object TAG_ENTITY_ATTRIBUTE_TYPE_VALUE_CIRCLE = "circle"; private static final Object TAG_ENTITY_ATTRIBUTE_TYPE_VALUE_TRIANGLE = "triangle"; private static final Object TAG_ENTITY_ATTRIBUTE_TYPE_VALUE_HEXAGON = "hexagon"; // =========================================================== // Fields // =========================================================== private BitmapTextureAtlas mBitmapTextureAtlas; private TiledTextureRegion mBoxFaceTextureRegion; private TiledTextureRegion mCircleFaceTextureRegion; private TiledTextureRegion mTriangleFaceTextureRegion; private TiledTextureRegion mHexagonFaceTextureRegion; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { Toast.makeText(this, "Loading level...", Toast.LENGTH_SHORT).show(); final Camera camera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), camera)); } @Override public void onLoadResources() { /* Textures. */ this.mBitmapTextureAtlas = new BitmapTextureAtlas(64, 128, TextureOptions.BILINEAR_PREMULTIPLYALPHA); BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); /* TextureRegions. */ this.mBoxFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "face_box_tiled.png", 0, 0, 2, 1); // 64x32 this.mCircleFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "face_circle_tiled.png", 0, 32, 2, 1); // 64x32 this.mTriangleFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "face_triangle_tiled.png", 0, 64, 2, 1); // 64x32 this.mHexagonFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "face_hexagon_tiled.png", 0, 96, 2, 1); // 64x32 this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); scene.setBackground(new ColorBackground(0, 0, 0)); final LevelLoader levelLoader = new LevelLoader(); levelLoader.setAssetBasePath("level/"); levelLoader.registerEntityLoader(LevelConstants.TAG_LEVEL, new IEntityLoader() { @Override public void onLoadEntity(final String pEntityName, final Attributes pAttributes) { final int width = SAXUtils.getIntAttributeOrThrow(pAttributes, LevelConstants.TAG_LEVEL_ATTRIBUTE_WIDTH); final int height = SAXUtils.getIntAttributeOrThrow(pAttributes, LevelConstants.TAG_LEVEL_ATTRIBUTE_HEIGHT); Toast.makeText(LevelLoaderExample.this, "Loaded level with width=" + width + " and height=" + height + ".", Toast.LENGTH_LONG).show(); } }); levelLoader.registerEntityLoader(TAG_ENTITY, new IEntityLoader() { @Override public void onLoadEntity(final String pEntityName, final Attributes pAttributes) { final int x = SAXUtils.getIntAttributeOrThrow(pAttributes, TAG_ENTITY_ATTRIBUTE_X); final int y = SAXUtils.getIntAttributeOrThrow(pAttributes, TAG_ENTITY_ATTRIBUTE_Y); final int width = SAXUtils.getIntAttributeOrThrow(pAttributes, TAG_ENTITY_ATTRIBUTE_WIDTH); final int height = SAXUtils.getIntAttributeOrThrow(pAttributes, TAG_ENTITY_ATTRIBUTE_HEIGHT); final String type = SAXUtils.getAttributeOrThrow(pAttributes, TAG_ENTITY_ATTRIBUTE_TYPE); LevelLoaderExample.this.addFace(scene, x, y, width, height, type); } }); try { levelLoader.loadLevelFromAsset(this, "example.lvl"); } catch (final IOException e) { Debug.e(e); } return scene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== private void addFace(final Scene pScene, final float pX, final float pY, final int pWidth, final int pHeight, final String pType) { final AnimatedSprite face; if(pType.equals(TAG_ENTITY_ATTRIBUTE_TYPE_VALUE_BOX)) { face = new AnimatedSprite(pX, pY, pWidth, pHeight, this.mBoxFaceTextureRegion); } else if(pType.equals(TAG_ENTITY_ATTRIBUTE_TYPE_VALUE_CIRCLE)) { face = new AnimatedSprite(pX, pY, pWidth, pHeight, this.mCircleFaceTextureRegion); } else if(pType.equals(TAG_ENTITY_ATTRIBUTE_TYPE_VALUE_TRIANGLE)) { face = new AnimatedSprite(pX, pY, pWidth, pHeight, this.mTriangleFaceTextureRegion); } else if(pType.equals(TAG_ENTITY_ATTRIBUTE_TYPE_VALUE_HEXAGON)) { face = new AnimatedSprite(pX, pY, pWidth, pHeight, this.mHexagonFaceTextureRegion); } else { throw new IllegalArgumentException(); } face.animate(200); pScene.attachChild(face); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
12anyao-aaa
src/org/anddev/andengine/examples/LevelLoaderExample.java
Java
lgpl
7,655
package org.anddev.andengine.examples.benchmark; import javax.microedition.khronos.opengles.GL10; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.particle.ParticleSystem; import org.anddev.andengine.entity.particle.emitter.PointParticleEmitter; import org.anddev.andengine.entity.particle.initializer.AccelerationInitializer; import org.anddev.andengine.entity.particle.initializer.ColorInitializer; import org.anddev.andengine.entity.particle.initializer.RotationInitializer; import org.anddev.andengine.entity.particle.initializer.VelocityInitializer; import org.anddev.andengine.entity.particle.modifier.AlphaModifier; import org.anddev.andengine.entity.particle.modifier.ColorModifier; import org.anddev.andengine.entity.particle.modifier.ExpireModifier; import org.anddev.andengine.entity.particle.modifier.ScaleModifier; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TextureRegion; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 09:27:21 - 29.06.2010 */ public class ParticleSystemBenchmark extends BaseBenchmark { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 480; private static final int CAMERA_HEIGHT = 320; private static final float RATE_MIN = 15; private static final float RATE_MAX = 20; private static final int PARTICLES_MAX = 200; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mBitmapTextureAtlas; private TextureRegion mParticleTextureRegion; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override protected int getBenchmarkID() { return PARTICLESYSTEMBENCHMARK_ID; } @Override protected float getBenchmarkStartOffset() { return 5; } @Override protected float getBenchmarkDuration() { return 15; } @Override public Engine onLoadEngine() { this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override public void onLoadResources() { this.mBitmapTextureAtlas = new BitmapTextureAtlas(32, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mParticleTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "gfx/particle_fire.png", 0, 0); this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { final Scene scene = new Scene(); scene.setBackground(new ColorBackground(0.0f, 0.0f, 0.0f)); /* LowerLeft to LowerRight Particle System. */ { final ParticleSystem particleSystem = new ParticleSystem(new PointParticleEmitter(-32, CAMERA_HEIGHT - 32), RATE_MIN, RATE_MAX, PARTICLES_MAX, this.mParticleTextureRegion); particleSystem.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE); particleSystem.addParticleInitializer(new VelocityInitializer(35, 45, 0, -10)); particleSystem.addParticleInitializer(new AccelerationInitializer(5, -11)); particleSystem.addParticleInitializer(new RotationInitializer(0.0f, 360.0f)); particleSystem.addParticleInitializer(new ColorInitializer(1.0f, 1.0f, 0.0f)); particleSystem.addParticleModifier(new ScaleModifier(0.5f, 2.0f, 0, 5)); particleSystem.addParticleModifier(new ExpireModifier(6.5f)); particleSystem.addParticleModifier(new ColorModifier(1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 2.5f, 5.5f)); particleSystem.addParticleModifier(new AlphaModifier(1.0f, 0.0f, 2.5f, 6.5f)); scene.attachChild(particleSystem); } /* LowerRight to LowerLeft Particle System. */ { final ParticleSystem particleSystem = new ParticleSystem(new PointParticleEmitter(CAMERA_WIDTH, CAMERA_HEIGHT - 32), RATE_MIN, RATE_MAX, PARTICLES_MAX, this.mParticleTextureRegion); particleSystem.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE); particleSystem.addParticleInitializer(new VelocityInitializer(-35, -45, 0, -10)); particleSystem.addParticleInitializer(new AccelerationInitializer(-5, -11)); particleSystem.addParticleInitializer(new RotationInitializer(0.0f, 360.0f)); particleSystem.addParticleInitializer(new ColorInitializer(0.0f, 1.0f, 0.0f)); particleSystem.addParticleModifier(new ScaleModifier(0.5f, 2.0f, 0, 5)); particleSystem.addParticleModifier(new ExpireModifier(6.5f)); particleSystem.addParticleModifier(new ColorModifier(0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 2.5f, 5.5f)); particleSystem.addParticleModifier(new AlphaModifier(1.0f, 0.0f, 2.5f, 6.5f)); scene.attachChild(particleSystem); } /* UpperLeft to UpperRight Particle System. */ { final ParticleSystem particleSystem = new ParticleSystem(new PointParticleEmitter(-32, 0), RATE_MIN, RATE_MAX, PARTICLES_MAX, this.mParticleTextureRegion); particleSystem.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE); particleSystem.addParticleInitializer(new VelocityInitializer(35, 45, 0, 10)); particleSystem.addParticleInitializer(new AccelerationInitializer(5, 11)); particleSystem.addParticleInitializer(new RotationInitializer(0.0f, 360.0f)); particleSystem.addParticleInitializer(new ColorInitializer(0.0f, 0.0f, 1.0f)); particleSystem.addParticleModifier(new ScaleModifier(0.5f, 2.0f, 0, 5)); particleSystem.addParticleModifier(new ExpireModifier(6.5f)); particleSystem.addParticleModifier(new ColorModifier(0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 2.5f, 5.5f)); particleSystem.addParticleModifier(new AlphaModifier(1.0f, 0.0f, 2.5f, 6.5f)); scene.attachChild(particleSystem); } /* UpperRight to UpperLeft Particle System. */ { final ParticleSystem particleSystem = new ParticleSystem(new PointParticleEmitter(CAMERA_WIDTH, 0), RATE_MIN, RATE_MAX, PARTICLES_MAX, this.mParticleTextureRegion); particleSystem.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE); particleSystem.addParticleInitializer(new VelocityInitializer(-35, -45, 0, 10)); particleSystem.addParticleInitializer(new AccelerationInitializer(-5, 12)); particleSystem.addParticleInitializer(new RotationInitializer(0.0f, 360.0f)); particleSystem.addParticleInitializer(new ColorInitializer(1.0f, 0.0f, 0.0f)); particleSystem.addParticleModifier(new ScaleModifier(0.5f, 2.0f, 0, 5)); particleSystem.addParticleModifier(new ExpireModifier(6.5f)); particleSystem.addParticleModifier(new ColorModifier(1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 2.5f, 5.5f)); particleSystem.addParticleModifier(new AlphaModifier(1.0f, 0.0f, 2.5f, 6.5f)); scene.attachChild(particleSystem); } return scene; } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
12anyao-aaa
src/org/anddev/andengine/examples/benchmark/ParticleSystemBenchmark.java
Java
lgpl
8,298
package org.anddev.andengine.examples.benchmark; import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.concurrent.Callable; import org.anddev.andengine.engine.handler.timer.ITimerCallback; import org.anddev.andengine.engine.handler.timer.TimerHandler; import org.anddev.andengine.entity.util.FPSCounter; import org.anddev.andengine.examples.R; import org.anddev.andengine.opengl.util.GLHelper; import org.anddev.andengine.ui.activity.BaseGameActivity; import org.anddev.andengine.util.Callback; import org.anddev.andengine.util.Debug; import org.anddev.andengine.util.StreamUtils; import org.anddev.andengine.util.SystemUtils; import org.anddev.andengine.util.SystemUtils.SystemUtilsException; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import android.app.AlertDialog; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.os.Build; import android.telephony.TelephonyManager; import android.util.DisplayMetrics; import android.widget.Toast; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 10:38:36 - 27.06.2010 */ public abstract class BaseBenchmark extends BaseGameActivity { // =========================================================== // Constants // =========================================================== /* Initializing the Random generator produces a comparable result over different versions. */ private static final long RANDOM_SEED = 1234567890; private static final int DIALOG_SHOW_RESULT = 1; private static final String SUBMIT_URL = "http://www.andengine.org/sys/benchmark/submit.php"; protected static final int ANIMATIONBENCHMARK_ID = 0; protected static final int PARTICLESYSTEMBENCHMARK_ID = ANIMATIONBENCHMARK_ID + 1; protected static final int PHYSICSBENCHMARK_ID = PARTICLESYSTEMBENCHMARK_ID + 1; protected static final int ENTITYMODIFIERBENCHMARK_ID = PHYSICSBENCHMARK_ID + 1; protected static final int SPRITEBENCHMARK_ID = ENTITYMODIFIERBENCHMARK_ID + 1; protected static final int TICKERTEXTBENCHMARK_ID = SPRITEBENCHMARK_ID + 1; // =========================================================== // Fields // =========================================================== private float mFPS; protected final Random mRandom = new Random(RANDOM_SEED); // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // ===========================================================; protected void showResult(final float pFPS) { this.mFPS = pFPS; this.runOnUiThread(new Runnable() { @Override public void run() { BaseBenchmark.this.showDialog(DIALOG_SHOW_RESULT); } }); } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== protected abstract int getBenchmarkID(); protected abstract float getBenchmarkDuration(); protected abstract float getBenchmarkStartOffset(); @Override public void onLoadComplete() { this.mEngine.registerUpdateHandler(new TimerHandler(this.getBenchmarkStartOffset(), new ITimerCallback() { @Override public void onTimePassed(final TimerHandler pTimerHandler) { BaseBenchmark.this.mEngine.unregisterUpdateHandler(pTimerHandler); System.gc(); BaseBenchmark.this.setUpBenchmarkHandling(); } })); } protected void setUpBenchmarkHandling() { final FPSCounter fpsCounter = new FPSCounter(); this.mEngine.registerUpdateHandler(fpsCounter); this.mEngine.registerUpdateHandler(new TimerHandler(this.getBenchmarkDuration(), new ITimerCallback() { @Override public void onTimePassed(final TimerHandler pTimerHandler) { BaseBenchmark.this.showResult(fpsCounter.getFPS()); } })); } @Override protected Dialog onCreateDialog(final int pID) { switch(pID) { case DIALOG_SHOW_RESULT: return new AlertDialog.Builder(this) .setTitle(this.getClass().getSimpleName()) .setMessage(String.format("Result: %.2f FPS", this.mFPS)) .setPositiveButton("Submit (Please!)", new OnClickListener() { @Override public void onClick(final DialogInterface pDialog, final int pWhich) { BaseBenchmark.this.submitResults(); } }) .setNegativeButton(android.R.string.cancel, new OnClickListener() { @Override public void onClick(final DialogInterface pDialog, final int pWhich) { BaseBenchmark.this.finish(); } }) .create(); default: return super.onCreateDialog(pID); } } // =========================================================== // Methods // =========================================================== private void submitResults() { this.doAsync(R.string.dialog_benchmark_submit_title, R.string.dialog_benchmark_submit_message, new Callable<Boolean>() { @Override public Boolean call() throws Exception { // Create a new HttpClient and Post Header final HttpClient httpClient = new DefaultHttpClient(); final HttpPost httpPost = new HttpPost(SUBMIT_URL); // Add your data final List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(18); nameValuePairs.add(new BasicNameValuePair("benchmark_id", String.valueOf(BaseBenchmark.this.getBenchmarkID()))); nameValuePairs.add(new BasicNameValuePair("benchmark_versionname", BaseBenchmark.getVersionName(BaseBenchmark.this))); nameValuePairs.add(new BasicNameValuePair("benchmark_versioncode", String.valueOf(BaseBenchmark.getVersionCode(BaseBenchmark.this)))); nameValuePairs.add(new BasicNameValuePair("benchmark_fps", String.valueOf(BaseBenchmark.this.mFPS).replace(",", "."))); nameValuePairs.add(new BasicNameValuePair("device_model", Build.MODEL)); nameValuePairs.add(new BasicNameValuePair("device_android_version", Build.VERSION.RELEASE)); nameValuePairs.add(new BasicNameValuePair("device_sdk_version", String.valueOf(Build.VERSION.SDK_INT))); nameValuePairs.add(new BasicNameValuePair("device_manufacturer", Build.MANUFACTURER)); nameValuePairs.add(new BasicNameValuePair("device_brand", Build.BRAND)); nameValuePairs.add(new BasicNameValuePair("device_build_id", Build.ID)); nameValuePairs.add(new BasicNameValuePair("device_build", Build.DISPLAY)); nameValuePairs.add(new BasicNameValuePair("device_device", Build.DEVICE)); nameValuePairs.add(new BasicNameValuePair("device_product", Build.PRODUCT)); nameValuePairs.add(new BasicNameValuePair("device_cpuabi", Build.CPU_ABI)); nameValuePairs.add(new BasicNameValuePair("device_board", Build.BOARD)); nameValuePairs.add(new BasicNameValuePair("device_fingerprint", Build.FINGERPRINT)); nameValuePairs.add(new BasicNameValuePair("benchmark_extension_vbo", GLHelper.EXTENSIONS_VERTEXBUFFEROBJECTS ? "1" : "0")); nameValuePairs.add(new BasicNameValuePair("benchmark_extension_drawtexture", GLHelper.EXTENSIONS_DRAWTEXTURE ? "1" : "0")); final TelephonyManager telephonyManager = (TelephonyManager)BaseBenchmark.this.getSystemService(Context.TELEPHONY_SERVICE); nameValuePairs.add(new BasicNameValuePair("device_imei", telephonyManager.getDeviceId())); final DisplayMetrics displayMetrics = new DisplayMetrics(); BaseBenchmark.this.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics); nameValuePairs.add(new BasicNameValuePair("device_displaymetrics_widthpixels", String.valueOf(displayMetrics.widthPixels))); nameValuePairs.add(new BasicNameValuePair("device_displaymetrics_heightpixels", String.valueOf(displayMetrics.heightPixels))); nameValuePairs.add(new BasicNameValuePair("device_displaymetrics_xdpi", String.valueOf(displayMetrics.xdpi))); nameValuePairs.add(new BasicNameValuePair("device_displaymetrics_ydpi", String.valueOf(displayMetrics.ydpi))); try{ final float bogoMips = SystemUtils.getCPUBogoMips(); nameValuePairs.add(new BasicNameValuePair("device_cpuinfo_bogomips", String.valueOf(bogoMips))); }catch(IllegalStateException e) { Debug.e(e); } try{ final float memoryTotal = SystemUtils.getMemoryTotal(); final float memoryFree = SystemUtils.getMemoryFree(); nameValuePairs.add(new BasicNameValuePair("device_memoryinfo_total", String.valueOf(memoryTotal))); nameValuePairs.add(new BasicNameValuePair("device_memoryinfo_free", String.valueOf(memoryFree))); }catch(IllegalStateException e) { Debug.e(e); } try{ final int cpuFrequencyCurrent = SystemUtils.getCPUFrequencyCurrent(); final int cpuFrequencyMax = SystemUtils.getCPUFrequencyMax(); nameValuePairs.add(new BasicNameValuePair("device_cpuinfo_frequency_current", String.valueOf(cpuFrequencyCurrent))); nameValuePairs.add(new BasicNameValuePair("device_cpuinfo_frequency_max", String.valueOf(cpuFrequencyMax))); }catch(SystemUtilsException e) { Debug.e(e); } httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); // Execute HTTP Post Request final HttpResponse response = httpClient.execute(httpPost); final int statusCode = response.getStatusLine().getStatusCode(); Debug.d(StreamUtils.readFully(response.getEntity().getContent())); if(statusCode == HttpStatus.SC_OK) { return true; } else { throw new RuntimeException(); } } }, new Callback<Boolean>() { @Override public void onCallback(final Boolean pCallbackValue) { BaseBenchmark.this.runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(BaseBenchmark.this, "Success", Toast.LENGTH_LONG).show(); BaseBenchmark.this.finish(); } }); } }, new Callback<Exception>() { @Override public void onCallback(final Exception pException) { Debug.e(pException); Toast.makeText(BaseBenchmark.this, "Exception occurred: " + pException.getClass().getSimpleName(), Toast.LENGTH_SHORT).show(); BaseBenchmark.this.finish(); } }); } public static String getVersionName(final Context ctx) { try { final PackageInfo pi = ctx.getPackageManager().getPackageInfo(ctx.getPackageName(), 0); return pi.versionName; } catch (final PackageManager.NameNotFoundException e) { Debug.e("Package name not found", e); return "?"; } } public static int getVersionCode(final Context ctx) { try { final PackageInfo pi = ctx.getPackageManager().getPackageInfo(ctx.getPackageName(), 0); return pi.versionCode; } catch (final PackageManager.NameNotFoundException e) { Debug.e("Package name not found", e); return -1; } } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
12anyao-aaa
src/org/anddev/andengine/examples/benchmark/BaseBenchmark.java
Java
lgpl
11,638
package org.anddev.andengine.examples.benchmark; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.handler.timer.ITimerCallback; import org.anddev.andengine.engine.handler.timer.TimerHandler; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.primitive.Rectangle; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.Scene.IOnSceneTouchListener; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.shape.Shape; import org.anddev.andengine.entity.sprite.AnimatedSprite; import org.anddev.andengine.extension.physics.box2d.PhysicsConnector; import org.anddev.andengine.extension.physics.box2d.PhysicsFactory; import org.anddev.andengine.extension.physics.box2d.PhysicsWorld; import org.anddev.andengine.extension.physics.box2d.util.Vector2Pool; import org.anddev.andengine.extension.physics.box2d.util.constants.PhysicsConstants; import org.anddev.andengine.input.touch.TouchEvent; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TiledTextureRegion; import android.hardware.SensorManager; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.Body; import com.badlogic.gdx.physics.box2d.BodyDef.BodyType; import com.badlogic.gdx.physics.box2d.FixtureDef; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 18:47:08 - 19.03.2010 */ public class PhysicsBenchmark extends BaseBenchmark implements IOnSceneTouchListener { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; private static final int COUNT_HORIZONTAL = 17; private static final int COUNT_VERTICAL = 15; // =========================================================== // Fields // =========================================================== private BitmapTextureAtlas mBitmapTextureAtlas; private TiledTextureRegion mBoxFaceTextureRegion; private TiledTextureRegion mCircleFaceTextureRegion; private Scene mScene; private PhysicsWorld mPhysicsWorld; private int mFaceCount = 0; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override protected int getBenchmarkID() { return PHYSICSBENCHMARK_ID; } @Override protected float getBenchmarkStartOffset() { return 2; } @Override protected float getBenchmarkDuration() { return 20; } @Override public Engine onLoadEngine() { final Camera camera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), camera)); } @Override public void onLoadResources() { this.mBitmapTextureAtlas = new BitmapTextureAtlas(64, 64, TextureOptions.BILINEAR_PREMULTIPLYALPHA); BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mBoxFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "face_box_tiled.png", 0, 0, 2, 1); // 64x32 this.mCircleFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "face_circle_tiled.png", 0, 32, 2, 1); // 64x32 this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { this.mScene = new Scene(); this.mScene.setBackground(new ColorBackground(0, 0, 0)); this.mScene.setOnSceneTouchListener(this); this.mPhysicsWorld = new PhysicsWorld(new Vector2(0, 2 * SensorManager.GRAVITY_EARTH / PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT), false); final Shape ground = new Rectangle(0, CAMERA_HEIGHT - 2, CAMERA_WIDTH, 2); final Shape roof = new Rectangle(0, 0, CAMERA_WIDTH, 2); final Shape left = new Rectangle(0, 0, 2, CAMERA_HEIGHT); final Shape right = new Rectangle(CAMERA_WIDTH - 2, 0, 2, CAMERA_HEIGHT); final FixtureDef wallFixtureDef = PhysicsFactory.createFixtureDef(0, 0.5f, 0.5f); PhysicsFactory.createBoxBody(this.mPhysicsWorld, ground, BodyType.StaticBody, wallFixtureDef); PhysicsFactory.createBoxBody(this.mPhysicsWorld, roof, BodyType.StaticBody, wallFixtureDef); PhysicsFactory.createBoxBody(this.mPhysicsWorld, left, BodyType.StaticBody, wallFixtureDef); PhysicsFactory.createBoxBody(this.mPhysicsWorld, right, BodyType.StaticBody, wallFixtureDef); this.mScene.attachChild(ground); this.mScene.attachChild(roof); this.mScene.attachChild(left); this.mScene.attachChild(right); for(int x = 1; x < COUNT_HORIZONTAL; x++) { for(int y = 1; y < COUNT_VERTICAL; y++) { final float pX = (((float)CAMERA_WIDTH) / COUNT_HORIZONTAL) * x + y; final float pY = (((float)CAMERA_HEIGHT) / COUNT_VERTICAL) * y; this.addFace(this.mScene, pX - 16, pY - 16); } } this.mScene.registerUpdateHandler(new TimerHandler(2, new ITimerCallback() { @Override public void onTimePassed(final TimerHandler pTimerHandler) { PhysicsBenchmark.this.mScene.unregisterUpdateHandler(pTimerHandler); PhysicsBenchmark.this.mScene.registerUpdateHandler(PhysicsBenchmark.this.mPhysicsWorld); PhysicsBenchmark.this.mScene.registerUpdateHandler(new TimerHandler(10, new ITimerCallback() { @Override public void onTimePassed(final TimerHandler pTimerHandler) { final Vector2 gravity = Vector2Pool.obtain(0, -SensorManager.GRAVITY_EARTH / 32); PhysicsBenchmark.this.mPhysicsWorld.setGravity(gravity); Vector2Pool.recycle(gravity); } })); } })); return this.mScene; } @Override public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) { if(this.mPhysicsWorld != null) { if(pSceneTouchEvent.isActionDown()) { this.addFace(pScene, pSceneTouchEvent.getX(), pSceneTouchEvent.getY()); return true; } } return false; } // =========================================================== // Methods // =========================================================== private void addFace(final Scene pScene, final float pX, final float pY) { this.mFaceCount++; final AnimatedSprite face; final Body body; final FixtureDef objectFixtureDef = PhysicsFactory.createFixtureDef(1, 0.5f, 0.5f); if(this.mFaceCount % 2 == 0) { face = new AnimatedSprite(pX, pY, this.mBoxFaceTextureRegion); body = PhysicsFactory.createBoxBody(this.mPhysicsWorld, face, BodyType.DynamicBody, objectFixtureDef); } else { face = new AnimatedSprite(pX, pY, this.mCircleFaceTextureRegion); body = PhysicsFactory.createCircleBody(this.mPhysicsWorld, face, BodyType.DynamicBody, objectFixtureDef); } pScene.attachChild(face); this.mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(face, body, true, true)); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
12anyao-aaa
src/org/anddev/andengine/examples/benchmark/PhysicsBenchmark.java
Java
lgpl
8,076
package org.anddev.andengine.examples.benchmark; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.text.Text; import org.anddev.andengine.entity.text.TickerText; import org.anddev.andengine.opengl.font.Font; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.util.HorizontalAlign; import android.graphics.Color; import android.graphics.Typeface; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 21:00:56 - 28.06.2010 */ public class TickerTextBenchmark extends BaseBenchmark { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; private static final int TEXT_COUNT = 200; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mFontTexture; private Font mFont; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override protected int getBenchmarkID() { return TICKERTEXTBENCHMARK_ID; } @Override protected float getBenchmarkStartOffset() { return 2; } @Override protected float getBenchmarkDuration() { return 10; } @Override public Engine onLoadEngine() { this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override public void onLoadResources() { this.mFontTexture = new BitmapTextureAtlas(256, 256, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mFont = new Font(this.mFontTexture, Typeface.create(Typeface.DEFAULT, Typeface.BOLD), 22, true, Color.WHITE); this.mEngine.getTextureManager().loadTexture(this.mFontTexture); this.mEngine.getFontManager().loadFont(this.mFont); } @Override public Scene onLoadScene() { final Scene scene = new Scene(); scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); for(int i = 0; i < TEXT_COUNT; i++) { final Text text = new TickerText(this.mRandom.nextInt(30), this.mRandom.nextFloat() * (CAMERA_HEIGHT - 20), this.mFont, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", HorizontalAlign.CENTER, 5 + 5 * this.mRandom.nextFloat()); text.setColor(this.mRandom.nextFloat(), this.mRandom.nextFloat(), this.mRandom.nextFloat()); scene.attachChild(text); } return scene; } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
12anyao-aaa
src/org/anddev/andengine/examples/benchmark/TickerTextBenchmark.java
Java
lgpl
3,883
package org.anddev.andengine.examples.benchmark; import javax.microedition.khronos.opengles.GL10; import javax.microedition.khronos.opengles.GL11; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.sprite.Sprite; import org.anddev.andengine.entity.sprite.batch.SpriteBatch; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TextureRegion; import org.anddev.andengine.opengl.vertex.RectangleVertexBuffer; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 10:34:22 - 27.06.2010 */ public class SpriteBenchmark extends BaseBenchmark { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; private static final int SPRITE_COUNT = 1000; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mBitmapTextureAtlas; private TextureRegion mFaceTextureRegion; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override protected int getBenchmarkID() { return SPRITEBENCHMARK_ID; } @Override protected float getBenchmarkStartOffset() { return 2; } @Override protected float getBenchmarkDuration() { return 10; } @Override public Engine onLoadEngine() { this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override public void onLoadResources() { this.mBitmapTextureAtlas = new BitmapTextureAtlas(32, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "gfx/face_box.png", 0, 0); this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { final Scene scene = new Scene(); scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); // this.drawUsingSprites(scene); // this.drawUsingSpritesWithSharedVertexBuffer(scene); this.drawUsingSpriteBatch(scene); return scene; } // =========================================================== // Methods // =========================================================== private void drawUsingSprites(final Scene scene) { for(int i = 0; i < SPRITE_COUNT; i++) { final Sprite face = new Sprite(this.mRandom.nextFloat() * (CAMERA_WIDTH - 32), this.mRandom.nextFloat() * (CAMERA_HEIGHT - 32), this.mFaceTextureRegion); face.setBlendFunction(GL10.GL_ONE, GL10.GL_ONE_MINUS_SRC_ALPHA); face.setIgnoreUpdate(true); scene.attachChild(face); } } private void drawUsingSpritesWithSharedVertexBuffer(final Scene scene) { /* As we are creating quite a lot of the same Sprites, we can let them share a VertexBuffer to significantly increase performance. */ final RectangleVertexBuffer sharedVertexBuffer = new RectangleVertexBuffer(GL11.GL_STATIC_DRAW, true); sharedVertexBuffer.update(this.mFaceTextureRegion.getWidth(), this.mFaceTextureRegion.getHeight()); for(int i = 0; i < SPRITE_COUNT; i++) { final Sprite face = new Sprite(this.mRandom.nextFloat() * (CAMERA_WIDTH - 32), this.mRandom.nextFloat() * (CAMERA_HEIGHT - 32), this.mFaceTextureRegion, sharedVertexBuffer); face.setBlendFunction(GL10.GL_ONE, GL10.GL_ONE_MINUS_SRC_ALPHA); face.setIgnoreUpdate(true); scene.attachChild(face); } } private void drawUsingSpriteBatch(final Scene scene) { final int width = this.mFaceTextureRegion.getWidth(); final int height = this.mFaceTextureRegion.getHeight(); final SpriteBatch spriteBatch = new SpriteBatch(this.mBitmapTextureAtlas, SPRITE_COUNT); spriteBatch.setBlendFunction(GL10.GL_ONE, GL10.GL_ONE_MINUS_SRC_ALPHA); for(int i = 0; i < SPRITE_COUNT; i++) { final float x = this.mRandom.nextFloat() * (CAMERA_WIDTH - 32); final float y = this.mRandom.nextFloat() * (CAMERA_HEIGHT - 32); spriteBatch.draw(this.mFaceTextureRegion, x, y, width, height); } spriteBatch.submit(); scene.attachChild(spriteBatch); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
12anyao-aaa
src/org/anddev/andengine/examples/benchmark/SpriteBenchmark.java
Java
lgpl
5,624
package org.anddev.andengine.examples.benchmark; import javax.microedition.khronos.opengles.GL11; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.modifier.AlphaModifier; import org.anddev.andengine.entity.modifier.DelayModifier; import org.anddev.andengine.entity.modifier.IEntityModifier; import org.anddev.andengine.entity.modifier.ParallelEntityModifier; import org.anddev.andengine.entity.modifier.RotationByModifier; import org.anddev.andengine.entity.modifier.RotationModifier; import org.anddev.andengine.entity.modifier.ScaleModifier; import org.anddev.andengine.entity.modifier.SequenceEntityModifier; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.sprite.Sprite; import org.anddev.andengine.entity.sprite.batch.SpriteGroup; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TextureRegion; import org.anddev.andengine.opengl.vertex.RectangleVertexBuffer; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 20:24:17 - 27.06.2010 */ public class EntityModifierBenchmark extends BaseBenchmark { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; private static final int SPRITE_COUNT = 1000; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mBitmapTextureAtlas; private TextureRegion mFaceTextureRegion; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override protected int getBenchmarkID() { return ENTITYMODIFIERBENCHMARK_ID; } @Override protected float getBenchmarkStartOffset() { return 2; } @Override protected float getBenchmarkDuration() { return 10; } @Override public Engine onLoadEngine() { this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override public void onLoadResources() { this.mBitmapTextureAtlas = new BitmapTextureAtlas(32, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "gfx/face_box.png", 0, 0); this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { final Scene scene = new Scene(); scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); // this.drawUsingSprites(scene); // this.drawUsingSpritesWithSharedVertexBuffer(scene); this.drawUsingSpriteBatch(scene); return scene; } // =========================================================== // Methods // =========================================================== private void drawUsingSprites(final Scene pScene) { final IEntityModifier faceEntityModifier = new SequenceEntityModifier( new RotationByModifier(2, 90), new AlphaModifier(1.5f, 1, 0), new AlphaModifier(1.5f, 0, 1), new ScaleModifier(2.5f, 1, 0.5f), new DelayModifier(0.5f), new ParallelEntityModifier( new ScaleModifier(2f, 0.5f, 5), new RotationByModifier(2, 90) ), new ParallelEntityModifier( new ScaleModifier(2f, 5, 1), new RotationModifier(2f, 180, 0) ) ); for(int i = 0; i < SPRITE_COUNT; i++) { final Sprite face = new Sprite((CAMERA_WIDTH - 32) * this.mRandom.nextFloat(), (CAMERA_HEIGHT - 32) * this.mRandom.nextFloat(), this.mFaceTextureRegion); face.registerEntityModifier(faceEntityModifier.clone()); pScene.attachChild(face); } } private void drawUsingSpritesWithSharedVertexBuffer(final Scene pScene) { final IEntityModifier faceEntityModifier = new SequenceEntityModifier( new RotationByModifier(2, 90), new AlphaModifier(1.5f, 1, 0), new AlphaModifier(1.5f, 0, 1), new ScaleModifier(2.5f, 1, 0.5f), new DelayModifier(0.5f), new ParallelEntityModifier( new ScaleModifier(2f, 0.5f, 5), new RotationByModifier(2, 90) ), new ParallelEntityModifier( new ScaleModifier(2f, 5, 1), new RotationModifier(2f, 180, 0) ) ); /* As we are creating quite a lot of the same Sprites, we can let them share a VertexBuffer to significantly increase performance. */ final RectangleVertexBuffer sharedVertexBuffer = new RectangleVertexBuffer(GL11.GL_DYNAMIC_DRAW, true); sharedVertexBuffer.update(this.mFaceTextureRegion.getWidth(), this.mFaceTextureRegion.getHeight()); for(int i = 0; i < SPRITE_COUNT; i++) { final Sprite face = new Sprite((CAMERA_WIDTH - 32) * this.mRandom.nextFloat(), (CAMERA_HEIGHT - 32) * this.mRandom.nextFloat(), this.mFaceTextureRegion, sharedVertexBuffer); face.registerEntityModifier(faceEntityModifier.clone()); pScene.attachChild(face); } } private void drawUsingSpriteBatch(final Scene pScene) { final IEntityModifier faceEntityModifier = new SequenceEntityModifier( new RotationByModifier(2, 90), // new AlphaModifier(1.5f, 1, 0), // new AlphaModifier(1.5f, 0, 1), new DelayModifier(1.5f + 1.5f), new ScaleModifier(2.5f, 1, 0.5f), new DelayModifier(0.5f), new ParallelEntityModifier( new ScaleModifier(2f, 0.5f, 5), new RotationByModifier(2, 90) ), new ParallelEntityModifier( new ScaleModifier(2f, 5, 1), new RotationModifier(2f, 180, 0) ) ); final IEntityModifier spriteBatchEntityModifier = new SequenceEntityModifier( new DelayModifier(2), new AlphaModifier(1.5f, 1, 0), new AlphaModifier(1.5f, 0, 1) ); final SpriteGroup spriteGroup = new SpriteGroup(this.mBitmapTextureAtlas, SPRITE_COUNT); for(int i = 0; i < SPRITE_COUNT; i++) { final Sprite face = new Sprite((CAMERA_WIDTH - 32) * this.mRandom.nextFloat(), (CAMERA_HEIGHT - 32) * this.mRandom.nextFloat(), this.mFaceTextureRegion); face.registerEntityModifier(faceEntityModifier.clone()); spriteGroup.attachChild(face); } spriteGroup.registerEntityModifier(spriteBatchEntityModifier); pScene.attachChild(spriteGroup); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
12anyao-aaa
src/org/anddev/andengine/examples/benchmark/EntityModifierBenchmark.java
Java
lgpl
7,642
package org.anddev.andengine.examples.benchmark; import javax.microedition.khronos.opengles.GL11; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.sprite.AnimatedSprite; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TiledTextureRegion; import org.anddev.andengine.opengl.vertex.RectangleVertexBuffer; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 11:28:45 - 28.06.2010 */ public class AnimationBenchmark extends BaseBenchmark { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; private static final int SPRITE_COUNT = 150; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mBitmapTextureAtlas; private TiledTextureRegion mSnapdragonTextureRegion; private TiledTextureRegion mHelicopterTextureRegion; private TiledTextureRegion mBananaTextureRegion; private TiledTextureRegion mFaceTextureRegion; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override protected int getBenchmarkID() { return ANIMATIONBENCHMARK_ID; } @Override protected float getBenchmarkStartOffset() { return 2; } @Override protected float getBenchmarkDuration() { return 10; } @Override public Engine onLoadEngine() { this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); final EngineOptions engineOptions = new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera); engineOptions.getRenderOptions().disableExtensionVertexBufferObjects(); return new Engine(engineOptions); } @Override public void onLoadResources() { this.mBitmapTextureAtlas = new BitmapTextureAtlas(512, 256, TextureOptions.BILINEAR_PREMULTIPLYALPHA); BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mSnapdragonTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "snapdragon_tiled.png", 0, 0, 4, 3); this.mHelicopterTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "helicopter_tiled.png", 400, 0, 2, 2); this.mBananaTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "banana_tiled.png", 0, 180, 4, 2); this.mFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "face_box_tiled.png", 132, 180, 2, 1); this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { final Scene scene = new Scene(); scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); /* As we are creating quite a lot of the same Sprites, we can let them share a VertexBuffer to significantly increase performance. */ final RectangleVertexBuffer faceSharedVertexBuffer = new RectangleVertexBuffer(GL11.GL_DYNAMIC_DRAW, true); faceSharedVertexBuffer.update(this.mFaceTextureRegion.getTileWidth(), this.mFaceTextureRegion.getTileHeight()); final RectangleVertexBuffer helicopterSharedVertexBuffer = new RectangleVertexBuffer(GL11.GL_DYNAMIC_DRAW, true); helicopterSharedVertexBuffer.update(this.mHelicopterTextureRegion.getTileWidth(), this.mHelicopterTextureRegion.getTileHeight()); final RectangleVertexBuffer snapdragonSharedVertexBuffer = new RectangleVertexBuffer(GL11.GL_DYNAMIC_DRAW, true); snapdragonSharedVertexBuffer.update(this.mSnapdragonTextureRegion.getTileWidth(), this.mSnapdragonTextureRegion.getTileHeight()); final RectangleVertexBuffer bananaSharedVertexBuffer = new RectangleVertexBuffer(GL11.GL_DYNAMIC_DRAW, true); bananaSharedVertexBuffer.update(this.mBananaTextureRegion.getTileWidth(), this.mBananaTextureRegion.getTileHeight()); for(int i = 0; i < SPRITE_COUNT; i++) { /* Quickly twinkling face. */ final AnimatedSprite face = new AnimatedSprite(this.mRandom.nextFloat() * (CAMERA_WIDTH - 32), this.mRandom.nextFloat() * (CAMERA_HEIGHT - 32), this.mFaceTextureRegion.clone(), faceSharedVertexBuffer); face.animate(50 + this.mRandom.nextInt(100)); scene.attachChild(face); /* Continuously flying helicopter. */ final AnimatedSprite helicopter = new AnimatedSprite(this.mRandom.nextFloat() * (CAMERA_WIDTH - 48), this.mRandom.nextFloat() * (CAMERA_HEIGHT - 48), this.mHelicopterTextureRegion.clone(), helicopterSharedVertexBuffer); helicopter.animate(new long[] { 50 + this.mRandom.nextInt(100), 50 + this.mRandom.nextInt(100) }, 1, 2, true); scene.attachChild(helicopter); /* Snapdragon. */ final AnimatedSprite snapdragon = new AnimatedSprite(this.mRandom.nextFloat() * (CAMERA_WIDTH - 100), this.mRandom.nextFloat() * (CAMERA_HEIGHT - 60), this.mSnapdragonTextureRegion.clone(), snapdragonSharedVertexBuffer); snapdragon.animate(50 + this.mRandom.nextInt(100)); scene.attachChild(snapdragon); /* Funny banana. */ final AnimatedSprite banana = new AnimatedSprite(this.mRandom.nextFloat() * (CAMERA_WIDTH - 32), this.mRandom.nextFloat() * (CAMERA_HEIGHT - 32), this.mBananaTextureRegion.clone(), bananaSharedVertexBuffer); banana.animate(50 + this.mRandom.nextInt(100)); scene.attachChild(banana); } return scene; } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
12anyao-aaa
src/org/anddev/andengine/examples/benchmark/AnimationBenchmark.java
Java
lgpl
6,985
package org.anddev.andengine.examples; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.sprite.Sprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.atlas.bitmap.source.AssetBitmapTextureAtlasSource; import org.anddev.andengine.opengl.texture.atlas.bitmap.source.decorator.ColorKeyBitmapTextureAtlasSourceDecorator; import org.anddev.andengine.opengl.texture.atlas.bitmap.source.decorator.shape.RectangleBitmapTextureAtlasSourceDecoratorShape; import org.anddev.andengine.opengl.texture.region.TextureRegion; import android.graphics.Color; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 11:54:51 - 03.04.2010 */ public class ColorKeyTextureSourceDecoratorExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 480; private static final int CAMERA_HEIGHT = 320; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mBitmapTextureAtlas; private TextureRegion mChromaticCircleTextureRegion; private TextureRegion mChromaticCircleColorKeyedTextureRegion; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override public void onLoadResources() { this.mBitmapTextureAtlas = new BitmapTextureAtlas(256, 128, TextureOptions.BILINEAR_PREMULTIPLYALPHA); /* The actual AssetTextureSource. */ final AssetBitmapTextureAtlasSource baseTextureSource = new AssetBitmapTextureAtlasSource(this, "gfx/chromatic_circle.png"); this.mChromaticCircleTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromSource(this.mBitmapTextureAtlas, baseTextureSource, 0, 0); /* We will remove both the red and the green segment of the chromatic circle, * by nesting two ColorKeyTextureSourceDecorators around the actual baseTextureSource. */ final int colorKeyRed = Color.rgb(255, 0, 51); // Red segment final int colorKeyGreen = Color.rgb(0, 179, 0); // Green segment final ColorKeyBitmapTextureAtlasSourceDecorator colorKeyBitmapTextureAtlasSource = new ColorKeyBitmapTextureAtlasSourceDecorator(new ColorKeyBitmapTextureAtlasSourceDecorator(baseTextureSource, RectangleBitmapTextureAtlasSourceDecoratorShape.getDefaultInstance(), colorKeyRed), RectangleBitmapTextureAtlasSourceDecoratorShape.getDefaultInstance(), colorKeyGreen); this.mChromaticCircleColorKeyedTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromSource(this.mBitmapTextureAtlas, colorKeyBitmapTextureAtlasSource, 128, 0); this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); final int centerX = (CAMERA_WIDTH - this.mChromaticCircleTextureRegion.getWidth()) / 2; final int centerY = (CAMERA_HEIGHT - this.mChromaticCircleTextureRegion.getHeight()) / 2; final Sprite chromaticCircle = new Sprite(centerX - 80, centerY, this.mChromaticCircleTextureRegion); final Sprite chromaticCircleColorKeyed = new Sprite(centerX + 80, centerY, this.mChromaticCircleColorKeyedTextureRegion); scene.attachChild(chromaticCircle); scene.attachChild(chromaticCircleColorKeyed); return scene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
12anyao-aaa
src/org/anddev/andengine/examples/ColorKeyTextureSourceDecoratorExample.java
Java
lgpl
5,160
package org.anddev.andengine.examples; import java.util.HashMap; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.sprite.Sprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.examples.adt.card.Card; import org.anddev.andengine.extension.input.touch.controller.MultiTouch; import org.anddev.andengine.extension.input.touch.controller.MultiTouchController; import org.anddev.andengine.extension.input.touch.exception.MultiTouchException; import org.anddev.andengine.input.touch.TouchEvent; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TextureRegion; import org.anddev.andengine.opengl.texture.region.TextureRegionFactory; import android.widget.Toast; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 18:20:40 - 18.06.2010 */ public class MultiTouchExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mCardDeckTexture; private Scene mScene; private HashMap<Card, TextureRegion> mCardTotextureRegionMap; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); final Engine engine = new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); try { if(MultiTouch.isSupported(this)) { engine.setTouchController(new MultiTouchController()); if(MultiTouch.isSupportedDistinct(this)) { Toast.makeText(this, "MultiTouch detected --> Drag multiple Sprites with multiple fingers!", Toast.LENGTH_LONG).show(); } else { Toast.makeText(this, "MultiTouch detected --> Drag multiple Sprites with multiple fingers!\n\n(Your device might have problems to distinguish between separate fingers.)", Toast.LENGTH_LONG).show(); } } else { Toast.makeText(this, "Sorry your device does NOT support MultiTouch!\n\n(Falling back to SingleTouch.)", Toast.LENGTH_LONG).show(); } } catch (final MultiTouchException e) { Toast.makeText(this, "Sorry your Android Version does NOT support MultiTouch!\n\n(Falling back to SingleTouch.)", Toast.LENGTH_LONG).show(); } return engine; } @Override public void onLoadResources() { this.mCardDeckTexture = new BitmapTextureAtlas(1024, 512, TextureOptions.BILINEAR_PREMULTIPLYALPHA); BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mCardDeckTexture, this, "gfx/carddeck_tiled.png", 0, 0); this.mCardTotextureRegionMap = new HashMap<Card, TextureRegion>(); /* Extract the TextureRegion of each card in the whole deck. */ for(final Card card : Card.values()) { final TextureRegion cardTextureRegion = TextureRegionFactory.extractFromTexture(this.mCardDeckTexture, card.getTexturePositionX(), card.getTexturePositionY(), Card.CARD_WIDTH, Card.CARD_HEIGHT, true); this.mCardTotextureRegionMap.put(card, cardTextureRegion); } this.mEngine.getTextureManager().loadTexture(this.mCardDeckTexture); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); this.mScene = new Scene(); this.mScene.setOnAreaTouchTraversalFrontToBack(); this.addCard(Card.CLUB_ACE, 200, 100); this.addCard(Card.HEART_ACE, 200, 260); this.addCard(Card.DIAMOND_ACE, 440, 100); this.addCard(Card.SPADE_ACE, 440, 260); this.mScene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); this.mScene.setTouchAreaBindingEnabled(true); return this.mScene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== private void addCard(final Card pCard, final int pX, final int pY) { final Sprite sprite = new Sprite(pX, pY, this.mCardTotextureRegionMap.get(pCard)) { boolean mGrabbed = false; @Override public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final float pTouchAreaLocalX, final float pTouchAreaLocalY) { switch(pSceneTouchEvent.getAction()) { case TouchEvent.ACTION_DOWN: this.setScale(1.25f); this.mGrabbed = true; break; case TouchEvent.ACTION_MOVE: if(this.mGrabbed) { this.setPosition(pSceneTouchEvent.getX() - Card.CARD_WIDTH / 2, pSceneTouchEvent.getY() - Card.CARD_HEIGHT / 2); } break; case TouchEvent.ACTION_UP: if(this.mGrabbed) { this.mGrabbed = false; this.setScale(1.0f); } break; } return true; } }; this.mScene.attachChild(sprite); this.mScene.registerTouchArea(sprite); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
12anyao-aaa
src/org/anddev/andengine/examples/MultiTouchExample.java
Java
lgpl
6,380
package org.anddev.andengine.examples; import javax.microedition.khronos.opengles.GL10; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.particle.ParticleSystem; import org.anddev.andengine.entity.particle.emitter.CircleOutlineParticleEmitter; import org.anddev.andengine.entity.particle.initializer.AlphaInitializer; import org.anddev.andengine.entity.particle.initializer.ColorInitializer; import org.anddev.andengine.entity.particle.initializer.RotationInitializer; import org.anddev.andengine.entity.particle.initializer.VelocityInitializer; import org.anddev.andengine.entity.particle.modifier.AlphaModifier; import org.anddev.andengine.entity.particle.modifier.ColorModifier; import org.anddev.andengine.entity.particle.modifier.ExpireModifier; import org.anddev.andengine.entity.particle.modifier.ScaleModifier; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.Scene.IOnSceneTouchListener; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.input.touch.TouchEvent; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TextureRegion; import android.widget.Toast; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 11:54:51 - 03.04.2010 */ public class ParticleSystemSimpleExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mBitmapTextureAtlas; private TextureRegion mParticleTextureRegion; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { Toast.makeText(this, "Touch the screen to move the particlesystem.", Toast.LENGTH_LONG).show(); this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override public void onLoadResources() { this.mBitmapTextureAtlas = new BitmapTextureAtlas(32, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mParticleTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "gfx/particle_point.png", 0, 0); this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); final CircleOutlineParticleEmitter particleEmitter = new CircleOutlineParticleEmitter(CAMERA_WIDTH * 0.5f, CAMERA_HEIGHT * 0.5f + 20, 80); final ParticleSystem particleSystem = new ParticleSystem(particleEmitter, 60, 60, 360, this.mParticleTextureRegion); scene.setOnSceneTouchListener(new IOnSceneTouchListener() { @Override public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) { particleEmitter.setCenter(pSceneTouchEvent.getX(), pSceneTouchEvent.getY()); return true; } }); particleSystem.addParticleInitializer(new ColorInitializer(1, 0, 0)); particleSystem.addParticleInitializer(new AlphaInitializer(0)); particleSystem.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE); particleSystem.addParticleInitializer(new VelocityInitializer(-2, 2, -20, -10)); particleSystem.addParticleInitializer(new RotationInitializer(0.0f, 360.0f)); particleSystem.addParticleModifier(new ScaleModifier(1.0f, 2.0f, 0, 5)); particleSystem.addParticleModifier(new ColorModifier(1, 1, 0, 0.5f, 0, 0, 0, 3)); particleSystem.addParticleModifier(new ColorModifier(1, 1, 0.5f, 1, 0, 1, 4, 6)); particleSystem.addParticleModifier(new AlphaModifier(0, 1, 0, 1)); particleSystem.addParticleModifier(new AlphaModifier(1, 0, 5, 6)); particleSystem.addParticleModifier(new ExpireModifier(6, 6)); scene.attachChild(particleSystem); return scene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
12anyao-aaa
src/org/anddev/andengine/examples/ParticleSystemSimpleExample.java
Java
lgpl
5,570
package org.anddev.andengine.examples; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.Scene.IOnSceneTouchListener; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.sprite.Sprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.input.touch.TouchEvent; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TextureRegion; import org.anddev.andengine.util.pool.RunnablePoolItem; import org.anddev.andengine.util.pool.RunnablePoolUpdateHandler; import android.widget.Toast; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 14:56:22 - 15.06.2011 */ public class RunnablePoolUpdateHandlerExample extends BaseExample implements IOnSceneTouchListener { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; private static final int FACE_COUNT = 2; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mBitmapTextureAtlas; private TextureRegion mFaceTextureRegion; private int mTargetFaceIndex = 0; private final Sprite[] mFaces = new Sprite[FACE_COUNT]; private final RunnablePoolUpdateHandler<FaceRotateRunnablePoolItem> mFaceRotateRunnablePoolUpdateHandler = new RunnablePoolUpdateHandler<FaceRotateRunnablePoolItem>() { @Override protected FaceRotateRunnablePoolItem onAllocatePoolItem() { return new FaceRotateRunnablePoolItem(); } }; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { Toast.makeText(this, "Touch the screen to rotate the sprites using RunnablePoolItems.", Toast.LENGTH_LONG).show(); this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override public void onLoadResources() { this.mBitmapTextureAtlas = new BitmapTextureAtlas(32, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "gfx/face_box.png", 0, 0); this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); scene.registerUpdateHandler(this.mFaceRotateRunnablePoolUpdateHandler); /* Calculate the coordinates for the face, so its centered on the camera. */ final int centerX = (CAMERA_WIDTH - this.mFaceTextureRegion.getWidth()) / 2; final int centerY = (CAMERA_HEIGHT - this.mFaceTextureRegion.getHeight()) / 2; this.mFaces[0] = new Sprite(centerX - 50, centerY, this.mFaceTextureRegion); this.mFaces[1] = new Sprite(centerX + 50, centerY, this.mFaceTextureRegion); scene.attachChild(this.mFaces[0]); scene.attachChild(this.mFaces[1]); scene.setOnSceneTouchListener(this); return scene; } @Override public void onLoadComplete() { } @Override public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) { if(pSceneTouchEvent.isActionDown()) { this.mTargetFaceIndex = (this.mTargetFaceIndex + 1) % FACE_COUNT; final FaceRotateRunnablePoolItem faceRotateRunnablePoolItem = this.mFaceRotateRunnablePoolUpdateHandler.obtainPoolItem(); faceRotateRunnablePoolItem.setTargetFace(this.mFaces[this.mTargetFaceIndex]); this.mFaceRotateRunnablePoolUpdateHandler.postPoolItem(faceRotateRunnablePoolItem); } return true; } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== public class FaceRotateRunnablePoolItem extends RunnablePoolItem { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private Sprite mTargetFace; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== public void setTargetFace(final Sprite pTargetFace) { this.mTargetFace = pTargetFace; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public void run() { this.mTargetFace.setRotation(this.mTargetFace.getRotation() + 45); } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== } }
12anyao-aaa
src/org/anddev/andengine/examples/RunnablePoolUpdateHandlerExample.java
Java
lgpl
6,738
package org.anddev.andengine.examples; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.IEntity; import org.anddev.andengine.entity.modifier.LoopEntityModifier; import org.anddev.andengine.entity.modifier.PathModifier; import org.anddev.andengine.entity.modifier.PathModifier.IPathModifierListener; import org.anddev.andengine.entity.modifier.PathModifier.Path; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.background.RepeatingSpriteBackground; import org.anddev.andengine.entity.sprite.AnimatedSprite; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.atlas.bitmap.source.AssetBitmapTextureAtlasSource; import org.anddev.andengine.opengl.texture.region.TiledTextureRegion; import org.anddev.andengine.util.Debug; import org.anddev.andengine.util.modifier.ease.EaseSineInOut; import android.widget.Toast; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 11:54:51 - 03.04.2010 */ public class PathModifierExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; // =========================================================== // Fields // =========================================================== private Camera mCamera; private RepeatingSpriteBackground mGrassBackground; private BitmapTextureAtlas mBitmapTextureAtlas; private TiledTextureRegion mPlayerTextureRegion; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { Toast.makeText(this, "You move my sprite right round, right round...", Toast.LENGTH_LONG).show(); this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override public void onLoadResources() { this.mBitmapTextureAtlas = new BitmapTextureAtlas(128, 128, TextureOptions.DEFAULT); this.mPlayerTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "gfx/player.png", 0, 0, 3, 4); this.mGrassBackground = new RepeatingSpriteBackground(CAMERA_WIDTH, CAMERA_HEIGHT, this.mEngine.getTextureManager(), new AssetBitmapTextureAtlasSource(this, "gfx/background_grass.png")); this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { // this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); scene.setBackground(this.mGrassBackground); /* Create the face and add it to the scene. */ final AnimatedSprite player = new AnimatedSprite(10, 10, 48, 64, this.mPlayerTextureRegion); final Path path = new Path(5).to(10, 10).to(10, CAMERA_HEIGHT - 74).to(CAMERA_WIDTH - 58, CAMERA_HEIGHT - 74).to(CAMERA_WIDTH - 58, 10).to(10, 10); /* Add the proper animation when a waypoint of the path is passed. */ player.registerEntityModifier(new LoopEntityModifier(new PathModifier(30, path, null, new IPathModifierListener() { @Override public void onPathStarted(final PathModifier pPathModifier, final IEntity pEntity) { Debug.d("onPathStarted"); } @Override public void onPathWaypointStarted(final PathModifier pPathModifier, final IEntity pEntity, final int pWaypointIndex) { Debug.d("onPathWaypointStarted: " + pWaypointIndex); switch(pWaypointIndex) { case 0: player.animate(new long[]{200, 200, 200}, 6, 8, true); break; case 1: player.animate(new long[]{200, 200, 200}, 3, 5, true); break; case 2: player.animate(new long[]{200, 200, 200}, 0, 2, true); break; case 3: player.animate(new long[]{200, 200, 200}, 9, 11, true); break; } } @Override public void onPathWaypointFinished(final PathModifier pPathModifier, final IEntity pEntity, final int pWaypointIndex) { Debug.d("onPathWaypointFinished: " + pWaypointIndex); } @Override public void onPathFinished(final PathModifier pPathModifier, final IEntity pEntity) { Debug.d("onPathFinished"); } }, EaseSineInOut.getInstance()))); scene.attachChild(player); return scene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
12anyao-aaa
src/org/anddev/andengine/examples/PathModifierExample.java
Java
lgpl
5,787
package org.anddev.andengine.examples; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.Scene.IOnSceneTouchListener; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.sprite.AnimatedSprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.input.touch.TouchEvent; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TiledTextureRegion; import android.widget.Toast; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 12:14:22 - 30.06.2010 */ public class UpdateTextureExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 480; private static final int CAMERA_HEIGHT = 320; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mBitmapTextureAtlas; private TiledTextureRegion mFaceTextureRegion; private boolean mToggleBox = true; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { Toast.makeText(this, "Touch the screen to update (redraw) an existing BitmapTextureAtlas with every touch!", Toast.LENGTH_LONG).show(); this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override public void onLoadResources() { this.mBitmapTextureAtlas = new BitmapTextureAtlas(64, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "gfx/face_box_tiled.png", 0, 0, 2, 1); this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); /* Calculate the coordinates for the face, so its centered on the camera. */ final int x = (CAMERA_WIDTH - this.mFaceTextureRegion.getTileWidth()) / 2; final int y = (CAMERA_HEIGHT - this.mFaceTextureRegion.getTileHeight()) / 2; /* Create the face and add it to the scene. */ final AnimatedSprite face = new AnimatedSprite(x, y, this.mFaceTextureRegion); face.animate(100); scene.attachChild(face); scene.setOnSceneTouchListener(new IOnSceneTouchListener() { @Override public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) { if(pSceneTouchEvent.isActionDown()) { UpdateTextureExample.this.toggle(); } return true; } }); return scene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== private void toggle() { this.mBitmapTextureAtlas.clearTextureAtlasSources(); this.mToggleBox = !this.mToggleBox; BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, this.mToggleBox ? "gfx/face_box_tiled.png" : "gfx/face_circle_tiled.png", 0, 0, 2, 1); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
12anyao-aaa
src/org/anddev/andengine/examples/UpdateTextureExample.java
Java
lgpl
4,687
package org.anddev.andengine.examples; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.primitive.Rectangle; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.Scene.IOnSceneTouchListener; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.shape.Shape; import org.anddev.andengine.entity.sprite.AnimatedSprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.extension.physics.box2d.PhysicsConnector; import org.anddev.andengine.extension.physics.box2d.PhysicsFactory; import org.anddev.andengine.extension.physics.box2d.PhysicsWorld; import org.anddev.andengine.extension.physics.box2d.util.Vector2Pool; import org.anddev.andengine.input.touch.TouchEvent; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TiledTextureRegion; import org.anddev.andengine.sensor.accelerometer.AccelerometerData; import org.anddev.andengine.sensor.accelerometer.IAccelerometerListener; import org.anddev.andengine.util.Debug; import org.anddev.andengine.util.MathUtils; import android.hardware.SensorManager; import android.widget.Toast; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.Body; import com.badlogic.gdx.physics.box2d.BodyDef.BodyType; import com.badlogic.gdx.physics.box2d.FixtureDef; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 18:47:08 - 19.03.2010 */ public class BasePhysicsJointExample extends BaseExample implements IAccelerometerListener, IOnSceneTouchListener { // =========================================================== // Constants // =========================================================== protected static final int CAMERA_WIDTH = 720; protected static final int CAMERA_HEIGHT = 480; // =========================================================== // Fields // =========================================================== private BitmapTextureAtlas mBitmapTextureAtlas; private Scene mScene; protected TiledTextureRegion mBoxFaceTextureRegion; protected TiledTextureRegion mCircleFaceTextureRegion; protected PhysicsWorld mPhysicsWorld; private int mFaceCount = 0; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { Toast.makeText(this, "Touch the screen to add objects.", Toast.LENGTH_LONG).show(); final Camera camera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); final EngineOptions engineOptions = new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), camera); engineOptions.getTouchOptions().setRunOnUpdateThread(true); return new Engine(engineOptions); } @Override public void onLoadResources() { this.mBitmapTextureAtlas = new BitmapTextureAtlas(64, 64, TextureOptions.BILINEAR_PREMULTIPLYALPHA); BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mBoxFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "face_box_tiled.png", 0, 0, 2, 1); // 64x32 this.mCircleFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "face_circle_tiled.png", 0, 32, 2, 1); // 64x32 this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); this.mScene = new Scene(); this.mScene.setBackground(new ColorBackground(0, 0, 0)); this.mScene.setOnSceneTouchListener(this); this.mPhysicsWorld = new PhysicsWorld(new Vector2(0, SensorManager.GRAVITY_EARTH), false); final Shape ground = new Rectangle(0, CAMERA_HEIGHT - 2, CAMERA_WIDTH, 2); final Shape roof = new Rectangle(0, 0, CAMERA_WIDTH, 2); final Shape left = new Rectangle(0, 0, 2, CAMERA_HEIGHT); final Shape right = new Rectangle(CAMERA_WIDTH - 2, 0, 2, CAMERA_HEIGHT); final FixtureDef wallFixtureDef = PhysicsFactory.createFixtureDef(0, 0.5f, 0.5f); PhysicsFactory.createBoxBody(this.mPhysicsWorld, ground, BodyType.StaticBody, wallFixtureDef); PhysicsFactory.createBoxBody(this.mPhysicsWorld, roof, BodyType.StaticBody, wallFixtureDef); PhysicsFactory.createBoxBody(this.mPhysicsWorld, left, BodyType.StaticBody, wallFixtureDef); PhysicsFactory.createBoxBody(this.mPhysicsWorld, right, BodyType.StaticBody, wallFixtureDef); this.mScene.attachChild(ground); this.mScene.attachChild(roof); this.mScene.attachChild(left); this.mScene.attachChild(right); this.mScene.registerUpdateHandler(this.mPhysicsWorld); return this.mScene; } @Override public void onLoadComplete() { } @Override public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) { if(this.mPhysicsWorld != null) { if(pSceneTouchEvent.isActionDown()) { this.addFace(pSceneTouchEvent.getX(), pSceneTouchEvent.getY()); return true; } } return false; } @Override public void onAccelerometerChanged(final AccelerometerData pAccelerometerData) { final Vector2 gravity = Vector2Pool.obtain(pAccelerometerData.getX(), pAccelerometerData.getY()); this.mPhysicsWorld.setGravity(gravity); Vector2Pool.recycle(gravity); } @Override public void onResumeGame() { super.onResumeGame(); this.enableAccelerometerSensor(this); } @Override public void onPauseGame() { super.onPauseGame(); this.disableAccelerometerSensor(); } // =========================================================== // Methods // =========================================================== private void addFace(final float pX, final float pY) { this.mFaceCount++; Debug.d("Faces: " + this.mFaceCount); final AnimatedSprite face; final Body body; final FixtureDef objectFixtureDef = PhysicsFactory.createFixtureDef(1, 0.5f, 0.5f); if(this.mFaceCount % 2 == 0) { face = new AnimatedSprite(pX, pY, this.mCircleFaceTextureRegion); face.setScale(MathUtils.random(0.5f, 1.25f)); body = PhysicsFactory.createCircleBody(this.mPhysicsWorld, face, BodyType.DynamicBody, objectFixtureDef); } else { face = new AnimatedSprite(pX, pY, this.mBoxFaceTextureRegion); face.setScale(MathUtils.random(0.5f, 1.25f)); body = PhysicsFactory.createBoxBody(this.mPhysicsWorld, face, BodyType.DynamicBody, objectFixtureDef); } face.animate(200); this.mScene.attachChild(face); this.mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(face, body, true, true)); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
12anyao-aaa
src/org/anddev/andengine/examples/BasePhysicsJointExample.java
Java
lgpl
7,803
package org.anddev.andengine.examples; import org.anddev.andengine.entity.primitive.Line; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.sprite.AnimatedSprite; import org.anddev.andengine.extension.physics.box2d.PhysicsConnector; import org.anddev.andengine.extension.physics.box2d.PhysicsFactory; import org.anddev.andengine.extension.physics.box2d.util.constants.PhysicsConstants; import android.widget.Toast; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.Body; import com.badlogic.gdx.physics.box2d.BodyDef.BodyType; import com.badlogic.gdx.physics.box2d.FixtureDef; import com.badlogic.gdx.physics.box2d.joints.RevoluteJointDef; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 18:47:08 - 19.03.2010 */ public class PhysicsRevoluteJointExample extends BasePhysicsJointExample { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Scene onLoadScene() { final Scene scene = super.onLoadScene(); this.initJoints(scene); Toast.makeText(this, "In this example, the revolute joints have their motor enabled.", Toast.LENGTH_LONG).show(); return scene; } // =========================================================== // Methods // =========================================================== private void initJoints(final Scene pScene) { final int centerX = CAMERA_WIDTH / 2; final int centerY = CAMERA_HEIGHT / 2; final int spriteWidth = this.mBoxFaceTextureRegion.getTileWidth(); final int spriteHeight = this.mBoxFaceTextureRegion.getTileHeight(); final FixtureDef objectFixtureDef = PhysicsFactory.createFixtureDef(10, 0.2f, 0.5f); for(int i = 0; i < 3; i++) { final float anchorFaceX = centerX - spriteWidth * 0.5f + 220 * (i - 1); final float anchorFaceY = centerY - spriteHeight * 0.5f; final AnimatedSprite anchorFace = new AnimatedSprite(anchorFaceX, anchorFaceY, this.mBoxFaceTextureRegion); final Body anchorBody = PhysicsFactory.createBoxBody(this.mPhysicsWorld, anchorFace, BodyType.StaticBody, objectFixtureDef); final AnimatedSprite movingFace = new AnimatedSprite(anchorFaceX, anchorFaceY + 90, this.mCircleFaceTextureRegion); final Body movingBody = PhysicsFactory.createCircleBody(this.mPhysicsWorld, movingFace, BodyType.DynamicBody, objectFixtureDef); anchorFace.animate(200); anchorFace.animate(200); final Line connectionLine = new Line(anchorFaceX + spriteWidth / 2, anchorFaceY + spriteHeight / 2, anchorFaceX + spriteWidth / 2, anchorFaceY + spriteHeight / 2); pScene.attachChild(connectionLine); pScene.attachChild(anchorFace); pScene.attachChild(movingFace); this.mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(anchorFace, anchorBody, true, true){ @Override public void onUpdate(final float pSecondsElapsed) { super.onUpdate(pSecondsElapsed); final Vector2 movingBodyWorldCenter = movingBody.getWorldCenter(); connectionLine.setPosition(connectionLine.getX1(), connectionLine.getY1(), movingBodyWorldCenter.x * PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT, movingBodyWorldCenter.y * PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT); } }); this.mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(movingFace, movingBody, true, true)); final RevoluteJointDef revoluteJointDef = new RevoluteJointDef(); revoluteJointDef.initialize(anchorBody, movingBody, anchorBody.getWorldCenter()); revoluteJointDef.enableMotor = true; revoluteJointDef.motorSpeed = 10; revoluteJointDef.maxMotorTorque = 200; this.mPhysicsWorld.createJoint(revoluteJointDef); } } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
12anyao-aaa
src/org/anddev/andengine/examples/PhysicsRevoluteJointExample.java
Java
lgpl
4,632
package org.anddev.andengine.examples; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.sprite.AnimatedSprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TiledTextureRegion; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 11:54:51 - 03.04.2010 */ public class AnimatedSpritesExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 480; private static final int CAMERA_HEIGHT = 320; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mBitmapTextureAtlas; private TiledTextureRegion mSnapdragonTextureRegion; private TiledTextureRegion mHelicopterTextureRegion; private TiledTextureRegion mBananaTextureRegion; private TiledTextureRegion mFaceTextureRegion; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override public void onLoadResources() { this.mBitmapTextureAtlas = new BitmapTextureAtlas(512, 256, TextureOptions.BILINEAR); BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mSnapdragonTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "snapdragon_tiled.png", 0, 0, 4, 3); this.mHelicopterTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "helicopter_tiled.png", 400, 0, 2, 2); this.mBananaTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "banana_tiled.png", 0, 180, 4, 2); this.mFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "face_box_tiled.png", 132, 180, 2, 1); this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); /* Quickly twinkling face. */ final AnimatedSprite face = new AnimatedSprite(100, 50, this.mFaceTextureRegion); face.animate(100); scene.attachChild(face); /* Continuously flying helicopter. */ final AnimatedSprite helicopter = new AnimatedSprite(320, 50, this.mHelicopterTextureRegion); helicopter.animate(new long[] { 100, 100 }, 1, 2, true); scene.attachChild(helicopter); /* Snapdragon. */ final AnimatedSprite snapdragon = new AnimatedSprite(300, 200, this.mSnapdragonTextureRegion); snapdragon.animate(100); scene.attachChild(snapdragon); /* Funny banana. */ final AnimatedSprite banana = new AnimatedSprite(100, 220, this.mBananaTextureRegion); banana.animate(100); scene.attachChild(banana); return scene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
12anyao-aaa
src/org/anddev/andengine/examples/AnimatedSpritesExample.java
Java
lgpl
4,790
package org.anddev.andengine.examples; import javax.microedition.khronos.opengles.GL10; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.particle.ParticleSystem; import org.anddev.andengine.entity.particle.emitter.PointParticleEmitter; import org.anddev.andengine.entity.particle.initializer.AccelerationInitializer; import org.anddev.andengine.entity.particle.initializer.ColorInitializer; import org.anddev.andengine.entity.particle.initializer.RotationInitializer; import org.anddev.andengine.entity.particle.initializer.VelocityInitializer; import org.anddev.andengine.entity.particle.modifier.AlphaModifier; import org.anddev.andengine.entity.particle.modifier.ColorModifier; import org.anddev.andengine.entity.particle.modifier.ExpireModifier; import org.anddev.andengine.entity.particle.modifier.ScaleModifier; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TextureRegion; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 11:54:51 - 03.04.2010 */ public class ParticleSystemCoolExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 480; private static final int CAMERA_HEIGHT = 320; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mBitmapTextureAtlas; private TextureRegion mParticleTextureRegion; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override public void onLoadResources() { this.mBitmapTextureAtlas = new BitmapTextureAtlas(32, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mParticleTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "gfx/particle_fire.png", 0, 0); this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); scene.setBackground(new ColorBackground(0.0f, 0.0f, 0.0f)); /* Left to right Particle System. */ { final ParticleSystem particleSystem = new ParticleSystem(new PointParticleEmitter(0, CAMERA_HEIGHT), 6, 10, 200, this.mParticleTextureRegion); particleSystem.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE); particleSystem.addParticleInitializer(new VelocityInitializer(15, 22, -60, -90)); particleSystem.addParticleInitializer(new AccelerationInitializer(5, 15)); particleSystem.addParticleInitializer(new RotationInitializer(0.0f, 360.0f)); particleSystem.addParticleInitializer(new ColorInitializer(1.0f, 0.0f, 0.0f)); particleSystem.addParticleModifier(new ScaleModifier(0.5f, 2.0f, 0, 5)); particleSystem.addParticleModifier(new ExpireModifier(11.5f)); particleSystem.addParticleModifier(new AlphaModifier(1.0f, 0.0f, 2.5f, 3.5f)); particleSystem.addParticleModifier(new AlphaModifier(0.0f, 1.0f, 3.5f, 4.5f)); particleSystem.addParticleModifier(new ColorModifier(1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 11.5f)); particleSystem.addParticleModifier(new AlphaModifier(1.0f, 0.0f, 4.5f, 11.5f)); scene.attachChild(particleSystem); } /* Right to left Particle System. */ { final ParticleSystem particleSystem = new ParticleSystem(new PointParticleEmitter(CAMERA_WIDTH - 32, CAMERA_HEIGHT), 8, 12, 200, this.mParticleTextureRegion); particleSystem.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE); particleSystem.addParticleInitializer(new VelocityInitializer(-15, -22, -60, -90)); particleSystem.addParticleInitializer(new AccelerationInitializer(-5, 15)); particleSystem.addParticleInitializer(new RotationInitializer(0.0f, 360.0f)); particleSystem.addParticleInitializer(new ColorInitializer(0.0f, 0.0f, 1.0f)); particleSystem.addParticleModifier(new ScaleModifier(0.5f, 2.0f, 0, 5)); particleSystem.addParticleModifier(new ExpireModifier(11.5f)); particleSystem.addParticleModifier(new AlphaModifier(1.0f, 0.0f, 2.5f, 3.5f)); particleSystem.addParticleModifier(new AlphaModifier(0.0f, 1.0f, 3.5f, 4.5f)); particleSystem.addParticleModifier(new ColorModifier(0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 11.5f)); particleSystem.addParticleModifier(new AlphaModifier(1.0f, 0.0f, 4.5f, 11.5f)); scene.attachChild(particleSystem); } return scene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
12anyao-aaa
src/org/anddev/andengine/examples/ParticleSystemCoolExample.java
Java
lgpl
6,335
package org.anddev.andengine.examples; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.text.Text; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.opengl.font.Font; import org.anddev.andengine.opengl.font.StrokeFont; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import android.graphics.Color; import android.graphics.Typeface; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 22:49:43 - 26.07.2010 */ public class StrokeFontExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; private static final int FONT_SIZE = 48; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mFontTexture; private BitmapTextureAtlas mStrokeFontTexture; private BitmapTextureAtlas mStrokeOnlyFontTexture; private Font mFont; private StrokeFont mStrokeFont; private StrokeFont mStrokeOnlyFont; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override public void onLoadResources() { this.mFontTexture = new BitmapTextureAtlas(256, 256, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mStrokeFontTexture = new BitmapTextureAtlas(256, 256, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mStrokeOnlyFontTexture = new BitmapTextureAtlas(256, 256, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mFont = new Font(this.mFontTexture, Typeface.create(Typeface.DEFAULT, Typeface.BOLD), FONT_SIZE, true, Color.BLACK); this.mStrokeFont = new StrokeFont(this.mStrokeFontTexture, Typeface.create(Typeface.DEFAULT, Typeface.BOLD), FONT_SIZE, true, Color.BLACK, 2, Color.WHITE); this.mStrokeOnlyFont = new StrokeFont(this.mStrokeOnlyFontTexture, Typeface.create(Typeface.DEFAULT, Typeface.BOLD), FONT_SIZE, true, Color.BLACK, 2, Color.WHITE, true); this.mEngine.getTextureManager().loadTextures(this.mFontTexture, this.mStrokeFontTexture, this.mStrokeOnlyFontTexture); this.mEngine.getFontManager().loadFonts(this.mFont, this.mStrokeFont, this.mStrokeOnlyFont); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); final Text textNormal = new Text(100, 100, this.mFont, "Just some normal Text."); final Text textStroke = new Text(100, 200, this.mStrokeFont, "Text with fill and stroke."); final Text textStrokeOnly = new Text(100, 300, this.mStrokeOnlyFont, "Text with stroke only."); scene.attachChild(textNormal); scene.attachChild(textStroke); scene.attachChild(textStrokeOnly); return scene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
12anyao-aaa
src/org/anddev/andengine/examples/StrokeFontExample.java
Java
lgpl
4,540
package org.anddev.andengine.examples; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.primitive.Rectangle; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.Scene.IOnAreaTouchListener; import org.anddev.andengine.entity.scene.Scene.IOnSceneTouchListener; import org.anddev.andengine.entity.scene.Scene.ITouchArea; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.shape.Shape; import org.anddev.andengine.entity.sprite.AnimatedSprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.extension.physics.box2d.PhysicsConnector; import org.anddev.andengine.extension.physics.box2d.PhysicsFactory; import org.anddev.andengine.extension.physics.box2d.PhysicsWorld; import org.anddev.andengine.extension.physics.box2d.util.Vector2Pool; import org.anddev.andengine.input.touch.TouchEvent; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TiledTextureRegion; import org.anddev.andengine.sensor.accelerometer.AccelerometerData; import org.anddev.andengine.sensor.accelerometer.IAccelerometerListener; import android.hardware.SensorManager; import android.widget.Toast; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.Body; import com.badlogic.gdx.physics.box2d.BodyDef.BodyType; import com.badlogic.gdx.physics.box2d.FixtureDef; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 21:18:08 - 27.06.2010 */ public class PhysicsJumpExample extends BaseExample implements IAccelerometerListener, IOnSceneTouchListener, IOnAreaTouchListener { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 360; private static final int CAMERA_HEIGHT = 240; // =========================================================== // Fields // =========================================================== private BitmapTextureAtlas mBitmapTextureAtlas; private TiledTextureRegion mBoxFaceTextureRegion; private TiledTextureRegion mCircleFaceTextureRegion; private int mFaceCount = 0; private PhysicsWorld mPhysicsWorld; private float mGravityX; private float mGravityY; private Scene mScene; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { Toast.makeText(this, "Touch the screen to add objects. Touch an object to shoot it up into the air.", Toast.LENGTH_LONG).show(); final Camera camera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); final EngineOptions engineOptions = new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), camera); engineOptions.getTouchOptions().setRunOnUpdateThread(true); return new Engine(engineOptions); } @Override public void onLoadResources() { this.mBitmapTextureAtlas = new BitmapTextureAtlas(64, 64, TextureOptions.BILINEAR_PREMULTIPLYALPHA); BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mBoxFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "face_box_tiled.png", 0, 0, 2, 1); // 64x32 this.mCircleFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "face_circle_tiled.png", 0, 32, 2, 1); // 64x32 this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); this.mPhysicsWorld = new PhysicsWorld(new Vector2(0, SensorManager.GRAVITY_EARTH), false); this.mScene = new Scene(); this.mScene.setBackground(new ColorBackground(0, 0, 0)); this.mScene.setOnSceneTouchListener(this); final Shape ground = new Rectangle(0, CAMERA_HEIGHT - 2, CAMERA_WIDTH, 2); final Shape roof = new Rectangle(0, 0, CAMERA_WIDTH, 2); final Shape left = new Rectangle(0, 0, 2, CAMERA_HEIGHT); final Shape right = new Rectangle(CAMERA_WIDTH - 2, 0, 2, CAMERA_HEIGHT); final FixtureDef wallFixtureDef = PhysicsFactory.createFixtureDef(0, 0.5f, 0.5f); PhysicsFactory.createBoxBody(this.mPhysicsWorld, ground, BodyType.StaticBody, wallFixtureDef); PhysicsFactory.createBoxBody(this.mPhysicsWorld, roof, BodyType.StaticBody, wallFixtureDef); PhysicsFactory.createBoxBody(this.mPhysicsWorld, left, BodyType.StaticBody, wallFixtureDef); PhysicsFactory.createBoxBody(this.mPhysicsWorld, right, BodyType.StaticBody, wallFixtureDef); this.mScene.attachChild(ground); this.mScene.attachChild(roof); this.mScene.attachChild(left); this.mScene.attachChild(right); this.mScene.registerUpdateHandler(this.mPhysicsWorld); this.mScene.setOnAreaTouchListener(this); return this.mScene; } @Override public boolean onAreaTouched( final TouchEvent pSceneTouchEvent, final ITouchArea pTouchArea,final float pTouchAreaLocalX, final float pTouchAreaLocalY) { if(pSceneTouchEvent.isActionDown()) { final AnimatedSprite face = (AnimatedSprite) pTouchArea; this.jumpFace(face); return true; } return false; } @Override public void onLoadComplete() { } @Override public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) { if(this.mPhysicsWorld != null) { if(pSceneTouchEvent.isActionDown()) { this.addFace(pSceneTouchEvent.getX(), pSceneTouchEvent.getY()); return true; } } return false; } @Override public void onAccelerometerChanged(final AccelerometerData pAccelerometerData) { this.mGravityX = pAccelerometerData.getX(); this.mGravityY = pAccelerometerData.getY(); final Vector2 gravity = Vector2Pool.obtain(this.mGravityX, this.mGravityY); this.mPhysicsWorld.setGravity(gravity); Vector2Pool.recycle(gravity); } @Override public void onResumeGame() { super.onResumeGame(); this.enableAccelerometerSensor(this); } @Override public void onPauseGame() { super.onPauseGame(); this.disableAccelerometerSensor(); } // =========================================================== // Methods // =========================================================== private void addFace(final float pX, final float pY) { this.mFaceCount++; final AnimatedSprite face; final Body body; final FixtureDef objectFixtureDef = PhysicsFactory.createFixtureDef(1, 0.5f, 0.5f); if(this.mFaceCount % 2 == 1){ face = new AnimatedSprite(pX, pY, this.mBoxFaceTextureRegion); body = PhysicsFactory.createBoxBody(this.mPhysicsWorld, face, BodyType.DynamicBody, objectFixtureDef); } else { face = new AnimatedSprite(pX, pY, this.mCircleFaceTextureRegion); body = PhysicsFactory.createCircleBody(this.mPhysicsWorld, face, BodyType.DynamicBody, objectFixtureDef); } this.mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(face, body, true, true)); face.animate(new long[]{200,200}, 0, 1, true); face.setUserData(body); this.mScene.registerTouchArea(face); this.mScene.attachChild(face); } private void jumpFace(final AnimatedSprite face) { final Body faceBody = (Body)face.getUserData(); final Vector2 velocity = Vector2Pool.obtain(this.mGravityX * -50, this.mGravityY * -50); faceBody.setLinearVelocity(velocity); Vector2Pool.recycle(velocity); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
12anyao-aaa
src/org/anddev/andengine/examples/PhysicsJumpExample.java
Java
lgpl
8,649
package org.anddev.andengine.examples; import java.io.IOException; import java.io.InputStream; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.SmoothCamera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.Scene.IOnSceneTouchListener; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.sprite.Sprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.examples.adt.ZoomState; import org.anddev.andengine.input.touch.TouchEvent; import org.anddev.andengine.opengl.texture.ITexture; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.compressed.etc1.ETC1Texture; import org.anddev.andengine.opengl.texture.region.TextureRegion; import org.anddev.andengine.opengl.texture.region.TextureRegionFactory; import org.anddev.andengine.util.Debug; import android.widget.Toast; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 11:54:51 - 03.04.2010 */ public class ETC1TextureExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; // =========================================================== // Fields // =========================================================== private SmoothCamera mSmoothCamera; private ITexture mTexture; private TextureRegion mHouseTextureRegion; private ZoomState mZoomState = ZoomState.NONE; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { Toast.makeText(this, "Click the top half of the screen to zoom in or the bottom half to zoom out!", Toast.LENGTH_LONG); this.mSmoothCamera = new SmoothCamera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT, 0, 0, 0.1f) { @Override public void onUpdate(final float pSecondsElapsed) { switch (ETC1TextureExample.this.mZoomState) { case IN: this.setZoomFactor(this.getZoomFactor() + 0.1f * pSecondsElapsed); break; case OUT: this.setZoomFactor(this.getZoomFactor() - 0.1f * pSecondsElapsed); break; } super.onUpdate(pSecondsElapsed); } }; return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mSmoothCamera)); } @Override public void onLoadResources() { try { this.mTexture = new ETC1Texture(TextureOptions.BILINEAR) { @Override protected InputStream getInputStream() throws IOException { return ETC1TextureExample.this.getResources().openRawResource(R.raw.house_etc1); } }; this.mHouseTextureRegion = TextureRegionFactory.extractFromTexture(this.mTexture, 0, 0, 512, 512, true); this.mEngine.getTextureManager().loadTextures(this.mTexture); } catch (final Throwable e) { Debug.e(e); } } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); final int centerX = (CAMERA_WIDTH - this.mHouseTextureRegion.getWidth()) / 2; final int centerY = (CAMERA_HEIGHT - this.mHouseTextureRegion.getHeight()) / 2; scene.attachChild(new Sprite(centerX, centerY, this.mHouseTextureRegion)); scene.setOnSceneTouchListener(new IOnSceneTouchListener() { @Override public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) { if (pSceneTouchEvent.isActionDown() || pSceneTouchEvent.isActionMove()) { if(pSceneTouchEvent.getY() < CAMERA_HEIGHT / 2) { ETC1TextureExample.this.mZoomState = ZoomState.IN; } else { ETC1TextureExample.this.mZoomState = ZoomState.OUT; } } else { ETC1TextureExample.this.mZoomState = ZoomState.NONE; } return true; } }); return scene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
12anyao-aaa
src/org/anddev/andengine/examples/ETC1TextureExample.java
Java
lgpl
5,180
package org.anddev.andengine.examples; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.text.Text; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.opengl.font.Font; import org.anddev.andengine.opengl.font.FontFactory; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import android.graphics.Color; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 11:54:51 - 03.04.2010 */ public class CustomFontExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; private static final int FONT_SIZE = 48; // =========================================================== // Fields // =========================================================== private Camera mCamera; private Font mDroidFont; private Font mPlokFont; private Font mNeverwinterNightsFont; private Font mUnrealTournamenFont; private Font mKingdomOfHeartsFont; private BitmapTextureAtlas mDroidFontTexture; private BitmapTextureAtlas mPlokFontTexture; private BitmapTextureAtlas mNeverwinterNightsFontTexture; private BitmapTextureAtlas mUnrealTournamentFontTexture; private BitmapTextureAtlas mKingdomOfHeartsFontTexture; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override public void onLoadResources() { /* The custom fonts. */ this.mDroidFontTexture = new BitmapTextureAtlas(256, 256, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mKingdomOfHeartsFontTexture = new BitmapTextureAtlas(256, 256, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mNeverwinterNightsFontTexture = new BitmapTextureAtlas(256, 256, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mPlokFontTexture = new BitmapTextureAtlas(256, 256, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mUnrealTournamentFontTexture = new BitmapTextureAtlas(256, 256, TextureOptions.BILINEAR_PREMULTIPLYALPHA); FontFactory.setAssetBasePath("font/"); this.mDroidFont = FontFactory.createFromAsset(this.mDroidFontTexture, this, "Droid.ttf", FONT_SIZE, true, Color.BLACK); this.mKingdomOfHeartsFont = FontFactory.createFromAsset(this.mKingdomOfHeartsFontTexture, this, "KingdomOfHearts.ttf", FONT_SIZE + 20, true, Color.BLACK); this.mNeverwinterNightsFont = FontFactory.createFromAsset(this.mNeverwinterNightsFontTexture, this, "NeverwinterNights.ttf", FONT_SIZE, true, Color.BLACK); this.mPlokFont = FontFactory.createFromAsset(this.mPlokFontTexture, this, "Plok.ttf", FONT_SIZE, true, Color.BLACK); this.mUnrealTournamenFont = FontFactory.createFromAsset(this.mUnrealTournamentFontTexture, this, "UnrealTournament.ttf", FONT_SIZE, true, Color.BLACK); this.mEngine.getTextureManager().loadTextures(this.mDroidFontTexture, this.mKingdomOfHeartsFontTexture, this.mNeverwinterNightsFontTexture, this.mPlokFontTexture, this.mUnrealTournamentFontTexture); this.mEngine.getFontManager().loadFonts(this.mDroidFont, this.mKingdomOfHeartsFont, this.mNeverwinterNightsFont, this.mPlokFont, this.mUnrealTournamenFont); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); scene.attachChild(new Text(230, 30, this.mDroidFont, "Droid Font")); scene.attachChild(new Text(160, 120, this.mKingdomOfHeartsFont, "Kingdom Of Hearts Font")); scene.attachChild(new Text(110, 210, this.mNeverwinterNightsFont, "Neverwinter Nights Font")); scene.attachChild(new Text(140, 300, this.mPlokFont, "Plok Font")); scene.attachChild(new Text(25, 390, this.mUnrealTournamenFont, "Unreal Tournament Font")); return scene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
12anyao-aaa
src/org/anddev/andengine/examples/CustomFontExample.java
Java
lgpl
5,459
package org.anddev.andengine.examples; import javax.microedition.khronos.opengles.GL10; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.camera.hud.controls.AnalogOnScreenControl; import org.anddev.andengine.engine.camera.hud.controls.AnalogOnScreenControl.IAnalogOnScreenControlListener; import org.anddev.andengine.engine.camera.hud.controls.BaseOnScreenControl; import org.anddev.andengine.engine.handler.IUpdateHandler; import org.anddev.andengine.engine.handler.physics.PhysicsHandler; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.modifier.LoopEntityModifier; import org.anddev.andengine.entity.modifier.ParallelEntityModifier; import org.anddev.andengine.entity.modifier.RotationModifier; import org.anddev.andengine.entity.modifier.ScaleModifier; import org.anddev.andengine.entity.modifier.SequenceEntityModifier; import org.anddev.andengine.entity.primitive.Line; import org.anddev.andengine.entity.primitive.Rectangle; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.sprite.Sprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.extension.input.touch.controller.MultiTouch; import org.anddev.andengine.extension.input.touch.controller.MultiTouchController; import org.anddev.andengine.extension.input.touch.exception.MultiTouchException; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TextureRegion; import org.anddev.andengine.util.MathUtils; import android.widget.Toast; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 00:06:23 - 11.07.2010 */ public class CollisionDetectionExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 480; private static final int CAMERA_HEIGHT = 320; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mBitmapTextureAtlas; private TextureRegion mFaceTextureRegion; private BitmapTextureAtlas mOnScreenControlTexture; private TextureRegion mOnScreenControlBaseTextureRegion; private TextureRegion mOnScreenControlKnobTextureRegion; private boolean mPlaceOnScreenControlsAtDifferentVerticalLocations = false; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); final Engine engine = new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); try { if(MultiTouch.isSupported(this)) { engine.setTouchController(new MultiTouchController()); if(MultiTouch.isSupportedDistinct(this)) { Toast.makeText(this, "MultiTouch detected --> Both controls will work properly!", Toast.LENGTH_SHORT).show(); } else { this.mPlaceOnScreenControlsAtDifferentVerticalLocations = true; Toast.makeText(this, "MultiTouch detected, but your device has problems distinguishing between fingers.\n\nControls are placed at different vertical locations.", Toast.LENGTH_LONG).show(); } } else { Toast.makeText(this, "Sorry your device does NOT support MultiTouch!\n\n(Falling back to SingleTouch.)\n\nControls are placed at different vertical locations.", Toast.LENGTH_LONG).show(); } } catch (final MultiTouchException e) { Toast.makeText(this, "Sorry your Android Version does NOT support MultiTouch!\n\n(Falling back to SingleTouch.)\n\nControls are placed at different vertical locations.", Toast.LENGTH_LONG).show(); } return engine; } @Override public void onLoadResources() { BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mBitmapTextureAtlas = new BitmapTextureAtlas(32, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "face_box.png", 0, 0); this.mOnScreenControlTexture = new BitmapTextureAtlas(256, 128, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mOnScreenControlBaseTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mOnScreenControlTexture, this, "onscreen_control_base.png", 0, 0); this.mOnScreenControlKnobTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mOnScreenControlTexture, this, "onscreen_control_knob.png", 128, 0); this.mEngine.getTextureManager().loadTextures(this.mBitmapTextureAtlas, this.mOnScreenControlTexture); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); final int centerX = (CAMERA_WIDTH - this.mFaceTextureRegion.getWidth()) / 2; final int centerY = (CAMERA_HEIGHT - this.mFaceTextureRegion.getHeight()) / 2; final LoopEntityModifier entityModifier = new LoopEntityModifier(new ParallelEntityModifier(new RotationModifier(6, 0, 360), new SequenceEntityModifier(new ScaleModifier(3, 1, 1.5f), new ScaleModifier(3, 1.5f, 1)))); /* Create A spinning rectangle and a line. */ final Rectangle centerRectangle = new Rectangle(centerX - 50, centerY - 16, 32, 32); centerRectangle.registerEntityModifier(entityModifier); scene.attachChild(centerRectangle); final Line line = new Line(centerX + 50 - 16, centerY, centerX + 50 + 16, centerY); line.registerEntityModifier(entityModifier.clone()); scene.attachChild(line); final Sprite face = new Sprite(centerX, centerY + 42, this.mFaceTextureRegion); final PhysicsHandler physicsHandler = new PhysicsHandler(face); face.registerUpdateHandler(physicsHandler); scene.attachChild(face); /* Velocity control (left). */ final int x1 = 0; final int y1 = CAMERA_HEIGHT - this.mOnScreenControlBaseTextureRegion.getHeight(); final AnalogOnScreenControl velocityOnScreenControl = new AnalogOnScreenControl(x1, y1, this.mCamera, this.mOnScreenControlBaseTextureRegion, this.mOnScreenControlKnobTextureRegion, 0.1f, new IAnalogOnScreenControlListener() { @Override public void onControlChange(final BaseOnScreenControl pBaseOnScreenControl, final float pValueX, final float pValueY) { physicsHandler.setVelocity(pValueX * 100, pValueY * 100); } @Override public void onControlClick(final AnalogOnScreenControl pAnalogOnScreenControl) { /* Nothing. */ } }); velocityOnScreenControl.getControlBase().setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); velocityOnScreenControl.getControlBase().setAlpha(0.5f); scene.setChildScene(velocityOnScreenControl); /* Rotation control (right). */ final int y2 = (this.mPlaceOnScreenControlsAtDifferentVerticalLocations) ? 0 : y1; final int x2 = CAMERA_WIDTH - this.mOnScreenControlBaseTextureRegion.getWidth(); final AnalogOnScreenControl rotationOnScreenControl = new AnalogOnScreenControl(x2, y2, this.mCamera, this.mOnScreenControlBaseTextureRegion, this.mOnScreenControlKnobTextureRegion, 0.1f, new IAnalogOnScreenControlListener() { @Override public void onControlChange(final BaseOnScreenControl pBaseOnScreenControl, final float pValueX, final float pValueY) { if(pValueX == x1 && pValueY == x1) { face.setRotation(x1); } else { face.setRotation(MathUtils.radToDeg((float)Math.atan2(pValueX, -pValueY))); } } @Override public void onControlClick(final AnalogOnScreenControl pAnalogOnScreenControl) { /* Nothing. */ } }); rotationOnScreenControl.getControlBase().setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); rotationOnScreenControl.getControlBase().setAlpha(0.5f); velocityOnScreenControl.setChildScene(rotationOnScreenControl); /* The actual collision-checking. */ scene.registerUpdateHandler(new IUpdateHandler() { @Override public void reset() { } @Override public void onUpdate(final float pSecondsElapsed) { if(centerRectangle.collidesWith(face)) { centerRectangle.setColor(1, 0, 0); } else { centerRectangle.setColor(0, 1, 0); } if(line.collidesWith(face)){ line.setColor(1, 0, 0); } else { line.setColor(0, 1, 0); } if(!mCamera.isRectangularShapeVisible(face)) { centerRectangle.setColor(1, 0, 1); } } }); return scene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
12anyao-aaa
src/org/anddev/andengine/examples/CollisionDetectionExample.java
Java
lgpl
10,051
package org.anddev.andengine.examples; import java.io.IOException; import org.anddev.andengine.audio.music.Music; import org.anddev.andengine.audio.music.MusicFactory; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.Scene.IOnAreaTouchListener; import org.anddev.andengine.entity.scene.Scene.ITouchArea; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.sprite.Sprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.input.touch.TouchEvent; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TextureRegion; import org.anddev.andengine.util.Debug; import android.widget.Toast; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 15:51:47 - 13.06.2010 */ public class MusicExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; // =========================================================== // Fields // =========================================================== private BitmapTextureAtlas mBitmapTextureAtlas; private TextureRegion mNotesTextureRegion; private Music mMusic; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { Toast.makeText(this, "Touch the notes to hear some Music.", Toast.LENGTH_LONG).show(); final Camera camera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), camera).setNeedsMusic(true)); } @Override public void onLoadResources() { this.mBitmapTextureAtlas = new BitmapTextureAtlas(128, 128, TextureOptions.BILINEAR_PREMULTIPLYALPHA); BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mNotesTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "notes.png", 0, 0); MusicFactory.setAssetBasePath("mfx/"); try { this.mMusic = MusicFactory.createMusicFromAsset(this.mEngine.getMusicManager(), this, "wagner_the_ride_of_the_valkyries.ogg"); this.mMusic.setLooping(true); } catch (final IOException e) { Debug.e(e); } this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); final int x = (CAMERA_WIDTH - this.mNotesTextureRegion.getWidth()) / 2; final int y = (CAMERA_HEIGHT - this.mNotesTextureRegion.getHeight()) / 2; final Sprite notes = new Sprite(x, y, this.mNotesTextureRegion); scene.attachChild(notes); scene.registerTouchArea(notes); scene.setOnAreaTouchListener(new IOnAreaTouchListener() { @Override public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final ITouchArea pTouchArea, final float pTouchAreaLocalX, final float pTouchAreaLocalY) { if(pSceneTouchEvent.isActionDown()) { if(MusicExample.this.mMusic.isPlaying()) { MusicExample.this.mMusic.pause(); } else { MusicExample.this.mMusic.play(); } } return true; } }); return scene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
12anyao-aaa
src/org/anddev/andengine/examples/MusicExample.java
Java
lgpl
4,881
package org.anddev.andengine.examples; import javax.microedition.khronos.opengles.GL10; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.camera.hud.controls.AnalogOnScreenControl; import org.anddev.andengine.engine.camera.hud.controls.AnalogOnScreenControl.IAnalogOnScreenControlListener; import org.anddev.andengine.engine.camera.hud.controls.BaseOnScreenControl; import org.anddev.andengine.engine.handler.physics.PhysicsHandler; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.sprite.Sprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.extension.input.touch.controller.MultiTouch; import org.anddev.andengine.extension.input.touch.controller.MultiTouchController; import org.anddev.andengine.extension.input.touch.exception.MultiTouchException; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TextureRegion; import org.anddev.andengine.util.MathUtils; import android.widget.Toast; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 00:06:23 - 11.07.2010 */ public class AnalogOnScreenControlsExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 480; private static final int CAMERA_HEIGHT = 320; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mBitmapTextureAtlas; private TextureRegion mFaceTextureRegion; private BitmapTextureAtlas mOnScreenControlTexture; private TextureRegion mOnScreenControlBaseTextureRegion; private TextureRegion mOnScreenControlKnobTextureRegion; private boolean mPlaceOnScreenControlsAtDifferentVerticalLocations = false; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); final Engine engine = new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); try { if(MultiTouch.isSupported(this)) { engine.setTouchController(new MultiTouchController()); if(MultiTouch.isSupportedDistinct(this)) { Toast.makeText(this, "MultiTouch detected --> Both controls will work properly!", Toast.LENGTH_LONG).show(); } else { this.mPlaceOnScreenControlsAtDifferentVerticalLocations = true; Toast.makeText(this, "MultiTouch detected, but your device has problems distinguishing between fingers.\n\nControls are placed at different vertical locations.", Toast.LENGTH_LONG).show(); } } else { Toast.makeText(this, "Sorry your device does NOT support MultiTouch!\n\n(Falling back to SingleTouch.)\n\nControls are placed at different vertical locations.", Toast.LENGTH_LONG).show(); } } catch (final MultiTouchException e) { Toast.makeText(this, "Sorry your Android Version does NOT support MultiTouch!\n\n(Falling back to SingleTouch.)\n\nControls are placed at different vertical locations.", Toast.LENGTH_LONG).show(); } return engine; } @Override public void onLoadResources() { BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mBitmapTextureAtlas = new BitmapTextureAtlas(32, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "face_box.png", 0, 0); this.mOnScreenControlTexture = new BitmapTextureAtlas(256, 128, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mOnScreenControlBaseTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mOnScreenControlTexture, this, "onscreen_control_base.png", 0, 0); this.mOnScreenControlKnobTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mOnScreenControlTexture, this, "onscreen_control_knob.png", 128, 0); this.mEngine.getTextureManager().loadTextures(this.mBitmapTextureAtlas, this.mOnScreenControlTexture); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); final int centerX = (CAMERA_WIDTH - this.mFaceTextureRegion.getWidth()) / 2; final int centerY = (CAMERA_HEIGHT - this.mFaceTextureRegion.getHeight()) / 2; final Sprite face = new Sprite(centerX, centerY, this.mFaceTextureRegion); final PhysicsHandler physicsHandler = new PhysicsHandler(face); face.registerUpdateHandler(physicsHandler); scene.attachChild(face); /* Velocity control (left). */ final int x1 = 0; final int y1 = CAMERA_HEIGHT - this.mOnScreenControlBaseTextureRegion.getHeight(); final AnalogOnScreenControl velocityOnScreenControl = new AnalogOnScreenControl(x1, y1, this.mCamera, this.mOnScreenControlBaseTextureRegion, this.mOnScreenControlKnobTextureRegion, 0.1f, new IAnalogOnScreenControlListener() { @Override public void onControlChange(final BaseOnScreenControl pBaseOnScreenControl, final float pValueX, final float pValueY) { physicsHandler.setVelocity(pValueX * 100, pValueY * 100); } @Override public void onControlClick(final AnalogOnScreenControl pAnalogOnScreenControl) { /* Nothing. */ } }); velocityOnScreenControl.getControlBase().setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); velocityOnScreenControl.getControlBase().setAlpha(0.5f); scene.setChildScene(velocityOnScreenControl); /* Rotation control (right). */ final int y2 = (this.mPlaceOnScreenControlsAtDifferentVerticalLocations) ? 0 : y1; final int x2 = CAMERA_WIDTH - this.mOnScreenControlBaseTextureRegion.getWidth(); final AnalogOnScreenControl rotationOnScreenControl = new AnalogOnScreenControl(x2, y2, this.mCamera, this.mOnScreenControlBaseTextureRegion, this.mOnScreenControlKnobTextureRegion, 0.1f, new IAnalogOnScreenControlListener() { @Override public void onControlChange(final BaseOnScreenControl pBaseOnScreenControl, final float pValueX, final float pValueY) { if(pValueX == x1 && pValueY == x1) { face.setRotation(x1); } else { face.setRotation(MathUtils.radToDeg((float)Math.atan2(pValueX, -pValueY))); } } @Override public void onControlClick(final AnalogOnScreenControl pAnalogOnScreenControl) { /* Nothing. */ } }); rotationOnScreenControl.getControlBase().setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); rotationOnScreenControl.getControlBase().setAlpha(0.5f); velocityOnScreenControl.setChildScene(rotationOnScreenControl); return scene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
12anyao-aaa
src/org/anddev/andengine/examples/AnalogOnScreenControlsExample.java
Java
lgpl
8,315
#!/usr/bin/env php <?php require_once 'lib/spark/spark_source.php'; require_once 'lib/spark/spark_cli.php'; // define a source $sources = array(); if ($fh = @fopen(dirname(__FILE__) . '/lib/spark/sources', 'r')) { while ($line = fgets($fh)) { $line = trim($line); if ($line && $line[0] != '#') $sources[] = new Spark_source($line); } fclose($fh); } if (count($sources) == 0) { $default_source = 'sparks.oconf.org'; Spark_utils::warning("No sources found, using $default_source"); $sources[] = new Spark_source($default_source); } // take commands $cli = new Spark_CLI($sources); $cmd = $argc > 1 ? $argv[1] : null; $args = $argc > 2 ? array_slice($argv, 2) : array(); $cli->execute($cmd, $args);
101-code
tools/spark
PHP
gpl3
746
<?php class Install_test extends Spark_test_case { function test_install_with_version() { $clines = $this->capture_buffer_lines(function($cli) { $cli->execute('install', array('-v1.0', 'example-spark')); }); $success = (bool) (strpos(end($clines), chr(27) . '[1;36m[ SPARK ]' . chr(27) . '[0m Spark installed') === 0); Spark_utils::remove_full_directory(SPARK_PATH . '/example-spark'); $this->assertEquals(true, $success); } function test_install_without_version() { $clines = $this->capture_buffer_lines(function($cli) { $cli->execute('install', array('example-spark')); }); $success = (bool) (strpos(end($clines), chr(27) . '[1;36m[ SPARK ]' . chr(27) . '[0m Spark installed') === 0); Spark_utils::remove_full_directory(SPARK_PATH . '/example-spark'); $this->assertEquals(true, $success); } function test_install_with_invalid_spark() { $clines = $this->capture_buffer_lines(function($cli) { $cli->execute('install', array('jjks7878erHjhsjdkksj')); }); $success = (bool) (strpos(end($clines), chr(27) . '[1;31m[ ERROR ]' . chr(27) . '[0m Unable to find spark') === 0); Spark_utils::remove_full_directory(SPARK_PATH . '/example-spark'); $this->assertEquals(true, $success); } function test_install_with_invalid_spark_version() { $clines = $this->capture_buffer_lines(function($cli) { $cli->execute('install', array('v9.4', 'example-spark')); }); $success = (bool) (strpos(reset($clines), chr(27) . '[1;31m[ ERROR ]' . chr(27) . '[0m Uh-oh!') === 0); Spark_utils::remove_full_directory(SPARK_PATH . '/example-spark'); $this->assertEquals(true, $success); } }
101-code
tools/test/install_test.php
PHP
gpl3
1,821
<?php class Search_test extends Spark_test_case { function test_search() { $clines = $this->capture_buffer_lines(function($cli) { $cli->execute('search', array('markdown')); }); // Less than ideal, I know $this->assertEquals(array("\033[33mmarkdown\033[0m - A markdown helper for easy parsing of markdown"), $clines); } }
101-code
tools/test/search_test.php
PHP
gpl3
381
<?php class Version_test extends Spark_test_case { function test_version() { $clines = $this->capture_buffer_lines(function($cli) { $cli->execute('version'); }); $this->assertEquals(array(SPARK_VERSION), $clines); } function test_sources() { $clines = $this->capture_buffer_lines(function($cli) { $cli->execute('sources'); }); $this->assertEquals($this->source_names, $clines); } function test_bad_command() { $clines = $this->capture_buffer_lines(function($cli) { $cli->execute('fake'); }); $this->assertEquals(array(chr(27) . '[1;31m[ ERROR ]' . chr(27) . '[0m Uh-oh!', chr(27) . '[1;31m[ ERROR ]' . chr(27) . '[0m Unknown action: fake'), $clines); } function test_search_empty() { $clines = $this->capture_buffer_lines(function($cli) { $cli->execute('search', array('nothing_found_here')); }); $this->assertEquals(array(), $clines); } }
101-code
tools/test/version_test.php
PHP
gpl3
1,039
<?php class Remove_test extends Spark_test_case { function test_remove_with_version() { // Test install with a version specified $clines = $this->capture_buffer_lines(function($cli) { $cli->execute('install', array('-v1.0', 'example-spark')); // Spark needs installed first $cli->execute('remove', array('-v1.0', 'example-spark')); }); $success = (bool) (strpos(end($clines), chr(27) . '[1;36m[ SPARK ]' . chr(27) . '[0m Spark removed') === 0 && ! is_dir(SPARK_PATH.'/example-spark')); $this->assertEquals(true, $success); Spark_utils::remove_full_directory(SPARK_PATH . '/example-spark'); } function test_remove_without_flags() { $clines = $this->capture_buffer_lines(function($cli) { $cli->execute('install', array('-v1.0', 'example-spark')); // Spark needs installed first $cli->execute('remove', array('example-spark')); }); $success = (bool) (strpos(end($clines), chr(27) . '[1;31m[ ERROR ]' . chr(27) . '[0m Please specify') === 0 && is_dir(SPARK_PATH.'/example-spark')); $this->assertEquals(true, $success); Spark_utils::remove_full_directory(SPARK_PATH . '/example-spark'); } function test_remove_with_f_flag() { $clines = $this->capture_buffer_lines(function($cli) { $cli->execute('install', array('-v1.0', 'example-spark')); // Spark needs installed first $cli->execute('remove', array('-f', 'example-spark')); }); $success = (bool) (strpos(end($clines), chr(27) . '[1;36m[ SPARK ]' . chr(27) . '[0m Spark removed') === 0 && ! is_dir(SPARK_PATH.'/example-spark')); $this->assertEquals(true, $success); Spark_utils::remove_full_directory(SPARK_PATH . '/example-spark'); } function test_remove_with_invalid_version() { $clines = $this->capture_buffer_lines(function($cli) { $cli->execute('install', array('-v1.0', 'example-spark')); // Spark needs installed first $cli->execute('remove', array('-v9.4', 'example-spark')); }); $success = (bool) (strpos(end($clines), chr(27) . '[1;36m[ SPARK ]' . chr(27) . '[0m Looks like that spark isn\'t installed') === 0 && is_dir(SPARK_PATH.'/example-spark')); $this->assertEquals(true, $success); Spark_utils::remove_full_directory(SPARK_PATH . '/example-spark'); } }
101-code
tools/test/remove_test.php
PHP
gpl3
2,434
<?php define('SPARK_PATH', __DIR__ . '/test-sparks'); require __DIR__ . '/../../lib/spark/spark_cli.php'; class Spark_test_case extends PHPUnit_Framework_TestCase { function setUp() { $this->source_names[] = 'getsparks.org'; $this->sources = array_map(function($n) { return new Spark_source($n); }, $this->source_names); $this->cli = new Spark_CLI($this->sources); } function tearDown() { if (is_dir(SPARK_PATH . '/example-spark')) { Spark_utils::remove_full_directory(SPARK_PATH . '/example-spark'); } } protected function capture_buffer_lines($func) { ob_start(); $func($this->cli); $t = ob_get_contents(); ob_end_clean(); if ($t == '') return array(); // empty return explode("\n", substr($t, 0, count($t) - 2)); } }
101-code
tools/test/lib/bootstrap.php
PHP
gpl3
887
<?php class Spark_exception extends Exception { }
101-code
tools/lib/spark/spark_exception.php
PHP
gpl3
52
<?php require_once dirname(__FILE__) . '/spark_utils.php'; require_once dirname(__FILE__) . '/spark_exception.php'; require_once dirname(__FILE__) . '/spark_source.php'; define('SPARK_VERSION', '0.0.7'); ! defined('SPARK_PATH') AND define('SPARK_PATH', './sparks'); class Spark_CLI { private static $commands = array( 'help' => 'help', 'install' => 'install', 'list' => 'lister', 'reinstall' => 'reinstall', 'remove' => 'remove', 'search' => 'search', 'sources' => 'sources', 'upgrade-system' => 'upgrade_system', 'version' => 'version', '' => 'index' // default action ); function __construct($spark_sources) { $this->spark_sources = $spark_sources; } function execute($command, $args = array()) { if (!array_key_exists($command, self::$commands)) { $this->failtown("Unknown action: $command"); return; } try { $method = self::$commands[$command]; $this->$method($args); } catch (Exception $ex) { return $this->failtown($ex->getMessage()); } } private function index($args) { Spark_utils::line('Spark (v' . SPARK_VERSION . ')'); Spark_utils::line('For help: `php tools/spark help`'); } private function upgrade_system() { $tool_dir = dirname(__FILE__) . '/../../'; $tool_dir = realpath($tool_dir); // Get version data $source = $this->spark_sources[0]; if (!$source) throw new Spark_exception('No sources listed - unsure how to upgrade'); if ($source->outdated()) // We have an acceptable version { Spark_utils::warning('Spark manager is already up to date'); return; } // Build a spark and download it $data = null; $data->name = 'Spark Manager'; $data->archive_url = $source->version_data->spark_manager_download_url; $zip_spark = new Zip_spark($data); $zip_spark->retrieve(); // Download the new version // Remove the lib directory and the spark unlink($tool_dir . '/spark'); Spark_utils::remove_full_directory($tool_dir . '/lib'); // Link up the new version Spark_utils::full_move($zip_spark->temp_path . '/lib', $tool_dir . '/lib'); @rename($zip_spark->temp_path . '/spark', $tool_dir . '/spark'); @`chmod u+x {$tool_dir}/spark`; // Tell the user the story of what just happened Spark_utils::notice('Spark manager has been upgraded to ' . $source->version . '!'); } // list the installed sparks private function lister() { if (!is_dir(SPARK_PATH)) return; // no directory yet foreach(scandir(SPARK_PATH) as $item) { if (!is_dir(SPARK_PATH . "/$item") || $item[0] == '.') continue; foreach (scandir(SPARK_PATH . "/$item") as $ver) { if (!is_dir(SPARK_PATH . "/$item/$ver") || $ver[0] == '.') continue; Spark_utils::line("$item ($ver)"); } } } private function version() { Spark_utils::line(SPARK_VERSION); } private function help() { Spark_utils::line('install # Install a spark'); Spark_utils::line('reinstall # Reinstall a spark'); Spark_utils::line('remove # Remove a spark'); Spark_utils::line('list # List installed sparks'); Spark_utils::line('search # Search for a spark'); Spark_utils::line('sources # Display the spark source URL(s)'); Spark_utils::line('upgrade-system # Update Sparks Manager to latest version (does not upgrade any of your installed sparks)'); Spark_utils::line('version # Display the installed spark version'); Spark_utils::line('help # Print This message'); } private function search($args) { $term = implode($args, ' '); foreach($this->spark_sources as $source) { $results = $source->search($term); foreach ($results as $result) { $result_line = "\033[33m$result->name\033[0m - $result->summary"; // only show the source information if there are multiple sources if (count($this->spark_sources) > 1) $result_line .= " (source: $source->url)"; Spark_utils::line($result_line); } } } private function sources() { foreach($this->spark_sources as $source) { Spark_utils::line($source->get_url()); } } private function failtown($error_message) { Spark_utils::error('Uh-oh!'); Spark_utils::error($error_message); } private function remove($args) { list($flats, $flags) = $this->prep_args($args); if (count($flats) != 1) { return $this->failtown('Which spark do you want to remove?'); } $spark_name = $flats[0]; $version = array_key_exists('v', $flags) ? $flags['v'] : null; // figure out what to remove and make sure its isntalled $dir_to_remove = SPARK_PATH . ($version == null ? "/$spark_name" : "/$spark_name/$version"); if (!file_exists($dir_to_remove)) { return Spark_utils::warning('Looks like that spark isn\'t installed'); } if ($version == null && !array_key_exists('f', $flags)) { throw new Spark_exception("Please specify a version of remove all with -f"); } Spark_utils::notice("Removing $spark_name (" . ($version ? $version : 'ALL') . ") from $dir_to_remove"); if (Spark_utils::remove_full_directory($dir_to_remove, true)) { Spark_utils::notice('Spark removed successfully!'); } else { Spark_utils::warning('Looks like that spark isn\'t installed'); } // attempt to clean up - will not remove unless empty @rmdir(SPARK_PATH . "/$spark_name"); } private function install($args) { list($flats, $flags) = $this->prep_args($args); if (count($flats) != 1) { return $this->failtown('format: `spark install -v1.0.0 name`'); } $spark_name = $flats[0]; $version = array_key_exists('v', $flags) ? $flags['v'] : 'HEAD'; // retrieve the spark details foreach ($this->spark_sources as $source) { Spark_utils::notice("Retrieving spark detail from " . $source->get_url()); $spark = $source->get_spark_detail($spark_name, $version); if ($spark != null) break; } // did we find the details? if ($spark == null) { throw new Spark_exception("Unable to find spark: $spark_name ($version) in any sources"); } // verify the spark, and put out warnings if needed $spark->verify(); // retrieve the spark Spark_utils::notice("From Downtown! Retrieving spark from " . $spark->location_detail()); $spark->retrieve(); // Install it $spark->install(); Spark_utils::notice('Spark installed to ' . $spark->installed_path() . ' - You\'re on fire!'); } private function reinstall($args) { list($flats, $flags) = $this->prep_args($args); if (count($flats) != 1) { return $this->failtown('format: `spark reinstall -v1.0.0 name`'); } $spark_name = $flats[0]; $version = array_key_exists('v', $flags) ? $flags['v'] : null; if ($version == null && !array_key_exists('f', $flags)) { throw new Spark_exception("Please specify a version to reinstall, or use -f to remove all versions and install latest."); } $this->remove($args); $this->install($args); } /** * Prepares the command line arguments for use. * * Usage: * list($flats, $flags) = $this->prep_args($args); * * @param array the arguments array * @return array the flats and flags */ private function prep_args($args) { $flats = array(); $flags = array(); foreach($args as $arg) { preg_match('/^(\-?[a-zA-Z])([^\s]*)$/', $arg, $matches); if (count($matches) != 3) continue; $matches[0][0] == '-' ? $flags[$matches[1][1]] = $matches[2] : $flats[] = $matches[0]; } return array($flats, $flags); } }
101-code
tools/lib/spark/spark_cli.php
PHP
gpl3
8,735
<?php class Git_spark extends Spark_type { function __construct($data) { if (!self::git_installed()) { throw new Spark_exception('You have to have git to install this spark.'); } parent::__construct($data); $this->tag = $this->tag; } static function get_spark($data) { if (self::git_installed()) { return new Git_spark($data); } else { Spark_utils::warning('Git not found - reverting to archived copy'); return new Zip_spark($data); } } private static function git_installed() { return !!`git`; } function location_detail() { return "Git repository at $this->base_location"; } function retrieve() { // check out the right tag `git clone $this->base_location $this->temp_path`; `cd $this->temp_path; git checkout $this->tag -b $this->temp_token`; // remove the git directory Spark_utils::remove_full_directory("$this->temp_path/.git"); if (!file_exists($this->temp_path)) { throw new Spark_exception('Failed to retrieve the spark ;('); } return true; } }
101-code
tools/lib/spark/spark_types/git_spark.php
PHP
gpl3
1,258
<?php class Mercurial_spark extends Spark_type { function __construct($data) { parent::__construct($data); $this->tag = $this->tag; } static function get_spark($data) { if (self::hg_installed()) { return new Mercurial_spark($data); } else { Spark_utils::warning('Mercurial not found - reverting to archived copy'); return new Zip_spark($data); } } private static function hg_installed() { return !!`hg`; } function location_detail() { return "Mercurial repository at $this->base_location"; } function retrieve() { `hg clone -r$this->tag $this->base_location $this->temp_path`; // remove the mercurial directory Spark_utils::remove_full_directory("$this->temp_path/.hg"); if (!file_exists($this->temp_path)) { throw new Spark_exception('Failed to retrieve the spark ;('); } return true; } }
101-code
tools/lib/spark/spark_types/hg_spark.php
PHP
gpl3
1,042
<?php class Zip_spark extends Spark_type { function __construct($data) { parent::__construct($data); $this->temp_file = $this->temp_path . '.zip'; $this->archive_url = property_exists($this->data, 'archive_url') ? $this->data->archive_url : null; } function location_detail() { return "ZIP archive at $this->archive_url"; } private static function unzip_installed() { return !!`unzip`; } function retrieve() { file_put_contents($this->temp_file, file_get_contents($this->archive_url)); // Try a few ways to unzip if (class_exists('ZipArchive')) { $zip = new ZipArchive; $zip->open($this->temp_file); $zip->extractTo($this->temp_path); $zip->close(); } else { if (!self::unzip_installed()) { throw new Spark_exception('You have to install PECL ZipArchive or `unzip` to install this spark.'); } `unzip $this->temp_file -d $this->temp_path`; } if (!file_exists($this->temp_path)) { throw new Spark_exception('Failed to retrieve the spark ;('); } return true; } }
101-code
tools/lib/spark/spark_types/zip_spark.php
PHP
gpl3
1,277
<?php // backward compatibility if ( !function_exists('sys_get_temp_dir')) { function sys_get_temp_dir() { if ($temp = getenv('TMP')) return $temp; if ($temp = getenv('TEMP')) return $temp; if ($temp = getenv('TMPDIR')) return $temp; $temp = tempnam(__FILE__, ''); if (file_exists($temp)) { unlink($temp); return dirname($temp); } return '/tmp'; // the best we can do } } class Spark_utils { private static $buffer = false; private static $lines = array(); static function get_lines() { return self::$lines; } static function buffer() { self::$buffer = true; } static function full_move($src, $dst) { $dir = opendir($src); @mkdir($dst); while(false !== ($file = readdir($dir))) { if (($file != '.') && ($file != '..')) { if (is_dir($src . '/' . $file)) { self::full_move($src . '/' . $file,$dst . '/' . $file); } else { rename($src . '/' . $file,$dst . '/' . $file); } } } closedir($dir); } static function remove_full_directory($dir, $vocally = false) { if (is_dir($dir)) { $objects = scandir($dir); foreach ($objects as $object) { if ($object != '.' && $object != '..') { if (filetype($dir . '/' . $object) == "dir") { self::remove_full_directory($dir . '/' . $object, $vocally); } else { if ($vocally) self::notice("Removing $dir/$object"); unlink($dir . '/' . $object); } } } reset($objects); return rmdir($dir); } } static function notice($msg) { self::line($msg, 'SPARK', '[1;36m'); } static function error($msg) { self::line($msg, 'ERROR', '[1;31m'); } static function warning($msg) { self::line($msg, 'WARNING', '[1;33m'); } static function line($msg = '', $s = null, $color = null) { foreach(explode("\n", $msg) as $line) { if (self::$buffer) { self::$lines[] = $line; } else { echo !$s ? "$line\n" : chr(27) . $color . "[ $s ]" . chr(27) . "[0m" . " $line\n"; } } } }
101-code
tools/lib/spark/spark_utils.php
PHP
gpl3
2,671
<?php class Spark_type { function __construct($data) { $this->data = $data; $this->name = $this->data->name; $this->spark_id = property_exists($this->data, 'id') ? $this->data->id : null; $this->version = property_exists($this->data, 'version') ? $this->data->version : null; $this->tag = property_exists($this->data, 'tag') ? $this->data->tag : $this->version; $this->base_location = property_exists($this->data, 'base_location') ? $this->data->base_location : null; // Load the dependencies $this->dependencies = property_exists($this->data, 'dependencies') ? $this->data->dependencies : array(); // Assign other data we don't have foreach ($this->data as $k=>$v) { if (!property_exists($this, $k)) $this->$k = $v; } // used internally $this->temp_token = 'spark-' . $this->spark_id . '-' . time(); $this->temp_path = sys_get_temp_dir() . '/' . $this->temp_token; } final function installed_path() { return $this->installed_path; } function location_detail() { } function retrieve() { } function install() { foreach ($this->dependencies as $dependency) { if ($dependency->is_direct) { $this->install_dependency($dependency); } } @mkdir(SPARK_PATH); // Two steps for windows @mkdir(SPARK_PATH . "/$this->name"); Spark_utils::full_move($this->temp_path, $this->installation_path); Spark_utils::remove_full_directory($this->temp_path); $this->installed_path = $this->installation_path; } private function recurseMove($src,$dst) { $dir = opendir($src); @mkdir($dst); while(false !== ( $file = readdir($dir)) ) { if (( $file != '.' ) && ( $file != '..' )) { if ( is_dir($src . '/' . $file) ) { $this->recurseMove($src . '/' . $file,$dst . '/' . $file); } else { rename($src . '/' . $file,$dst . '/' . $file); } } } closedir($dir); } private function rrmdir($dir) { if (is_dir($dir)) { $files = scandir($dir); foreach ($files as $file) { if ($file != "." && $file != "..") { if (is_dir($dir . "/" . $file)) { $this->rrmdir($dir . "/" . $file); } else { unlink($dir . "/" . $file); } } } reset($files); rmdir($dir); } } function install_dependency($dependency_data) { // Get the spark object $spark = null; if ($dependency_data->repository_type == 'hg') $spark = Mercurial_spark::get_spark($dependency_data); else if ($dependency_data->repository_type == 'git') $spark = Git_spark::get_spark($dependency_data); else if ($dependency_data->repository_type == 'zip') $spark = new Zip_spark($dependency_data); else throw new Exception('Unknown repository type: ' . $dependency_data->repository_type); // Install the spark if ($spark->verify(false)) { // if not installed, install $spark->retrieve(); $spark->install(); Spark_utils::notice("Installed dependency: $spark->name to " . $spark->installed_path()); } else { Spark_utils::warning("Dependency $spark->name is already installed."); } } function verify($break_on_already_installed = true) { // see if this is deactivated if ($this->data->is_deactivated) { $msg = 'Woah there - it seems the spark you want has been deactivated'; if ($this->data->spark_home) $msg .= "\nLook for different versions at: " . $this->data->spark_home; throw new Spark_exception($msg); } // see if this is unsupported if ($this->data->is_unsupported) { Spark_utils::warning('This spark is no longer supported.'); Spark_utils::warning('You can keep using it, or look for an alternate'); } // tell the user if its already installed and throw an error $this->installation_path = SPARK_PATH . "/$this->name/$this->version"; if (is_dir($this->installation_path)) { if ($break_on_already_installed) { throw new Spark_exception("Already installed. Try `php tools/spark reinstall $this->name`"); } return false; } else { return true; } } }
101-code
tools/lib/spark/spark_type.php
PHP
gpl3
4,875
<?php require_once 'spark_type.php'; require_once 'spark_types/git_spark.php'; require_once 'spark_types/hg_spark.php'; require_once 'spark_types/zip_spark.php'; class Spark_source { public $url; public $version_data; public $version; function __construct($url) { $this->url = $url; $this->version_data = json_decode(@file_get_contents("http://$this->url/api/system/latest")); $this->version = $this->version_data->spark_manager; $this->warn_if_outdated(); } function get_url() { return $this->url; } // get details on an individual spark function get_spark_detail($spark_name, $version = 'HEAD') { $json_data = @file_get_contents("http://$this->url/api/packages/$spark_name/versions/$version/spec"); if (!$json_data) return null; // no such spark here $data = json_decode($json_data); // if we don't succeed - throw an error if ($data == null || !$data->success) { $message = "Error retrieving spark detail from source: $this->url"; if ($data != null) $message .= " ($data->message)"; throw new Spark_exception($message); } // Get the detail for this spark return $this->get_spark($data->spec); } // get details on multiple sparks by search term function search($term) { $json_data = @file_get_contents("http://$this->url/api/packages/search?q=" . urlencode($term)); $data = json_decode($json_data); // if the data isn't around of success is false, return a warning for this source if ($data == null || !$data->success) { $message = "Error searching source: $this->url"; if ($data != null) $message .= " ($data->message)"; Spark_utils::warning($message); return array(); } // Get sparks for each one $results = array(); foreach($data->results as $data) { $results[] = $this->get_spark($data); } return $results; } private function warn_if_outdated() { if ($this->outdated()) { Spark_utils::warning("Your installed version of spark is outdated (current version: " . $this->outdated() . " / latest: " . $this->version . ")"); Spark_utils::warning("To upgrade now, use `php tools/spark upgrade-system`"); } } function outdated() { // Get the version for this source if (!$this->version) return; // no version found // Split versions list($self_major, $self_minor, $self_patch) = explode('.', SPARK_VERSION); list($source_major, $source_minor, $source_patch) = explode('.', $this->version); // Compare if ($self_major < $source_major || $self_major == $source_major && $self_minor < $source_minor || $self_major == $source_major && $self_minor == $source_minor && $self_patch < $source_patch) { return SPARK_VERSION; } } private function get_spark($data) { if ($data->repository_type == 'hg') return Mercurial_spark::get_spark($data); else if ($data->repository_type == 'git') return Git_spark::get_spark($data); else if ($data->repository_type == 'zip') return new Zip_spark($data); else throw new Exception('Unknown repository type: ' . $data->repository_type); } }
101-code
tools/lib/spark/spark_source.php
PHP
gpl3
3,475
::selection{ background-color: #E13300; color: white; } ::moz-selection{ background-color: #E13300; color: white; } ::webkit-selection{ background-color: #E13300; color: white; } body { background-color: #fff; margin: 40px; font: 13px/20px normal Helvetica, Arial, sans-serif; color: #4F5155; } a { color: #003399; background-color: transparent; font-weight: normal; } h1 { color: #444; background-color: transparent; border-bottom: 1px solid #D0D0D0; font-size: 19px; font-weight: normal; margin: 0 0 14px 0; padding: 14px 15px 10px 15px; } code { font-family: Consolas, Monaco, Courier New, Courier, monospace; font-size: 12px; background-color: #f9f9f9; border: 1px solid #D0D0D0; color: #002166; display: block; margin: 14px 0 14px 0; padding: 12px 10px 12px 10px; } #body{ margin: 0 15px 0 15px; } p.footer{ text-align: right; font-size: 11px; border-top: 1px solid #D0D0D0; line-height: 32px; padding: 0 10px 0 10px; margin: 20px 0 0 0; } #container{ margin: 10px; border: 1px solid #D0D0D0; -webkit-box-shadow: 0 0 8px #D0D0D0; }
101-code
public/css/style.css
CSS
gpl3
1,121
<?php $lang['upload_userfile_not_set'] = "Unable to find a post variable called userfile."; $lang['upload_file_exceeds_limit'] = "The uploaded file exceeds the maximum allowed size in your PHP configuration file."; $lang['upload_file_exceeds_form_limit'] = "The uploaded file exceeds the maximum size allowed by the submission form."; $lang['upload_file_partial'] = "The file was only partially uploaded."; $lang['upload_no_temp_directory'] = "The temporary folder is missing."; $lang['upload_unable_to_write_file'] = "The file could not be written to disk."; $lang['upload_stopped_by_extension'] = "The file upload was stopped by extension."; $lang['upload_no_file_selected'] = "You did not select a file to upload."; $lang['upload_invalid_filetype'] = "The filetype you are attempting to upload is not allowed."; $lang['upload_invalid_filesize'] = "The file you are attempting to upload is larger than the permitted size."; $lang['upload_invalid_dimensions'] = "The image you are attempting to upload exceedes the maximum height or width."; $lang['upload_destination_error'] = "A problem was encountered while attempting to move the uploaded file to the final destination."; $lang['upload_no_filepath'] = "The upload path does not appear to be valid."; $lang['upload_no_file_types'] = "You have not specified any allowed file types."; $lang['upload_bad_filename'] = "The file name you submitted already exists on the server."; $lang['upload_not_writable'] = "The upload destination folder does not appear to be writable."; /* End of file upload_lang.php */ /* Location: ./system/language/english/upload_lang.php */
101-code
system/language/english/upload_lang.php
PHP
gpl3
1,619
<?php $lang['cal_su'] = "Su"; $lang['cal_mo'] = "Mo"; $lang['cal_tu'] = "Tu"; $lang['cal_we'] = "We"; $lang['cal_th'] = "Th"; $lang['cal_fr'] = "Fr"; $lang['cal_sa'] = "Sa"; $lang['cal_sun'] = "Sun"; $lang['cal_mon'] = "Mon"; $lang['cal_tue'] = "Tue"; $lang['cal_wed'] = "Wed"; $lang['cal_thu'] = "Thu"; $lang['cal_fri'] = "Fri"; $lang['cal_sat'] = "Sat"; $lang['cal_sunday'] = "Sunday"; $lang['cal_monday'] = "Monday"; $lang['cal_tuesday'] = "Tuesday"; $lang['cal_wednesday'] = "Wednesday"; $lang['cal_thursday'] = "Thursday"; $lang['cal_friday'] = "Friday"; $lang['cal_saturday'] = "Saturday"; $lang['cal_jan'] = "Jan"; $lang['cal_feb'] = "Feb"; $lang['cal_mar'] = "Mar"; $lang['cal_apr'] = "Apr"; $lang['cal_may'] = "May"; $lang['cal_jun'] = "Jun"; $lang['cal_jul'] = "Jul"; $lang['cal_aug'] = "Aug"; $lang['cal_sep'] = "Sep"; $lang['cal_oct'] = "Oct"; $lang['cal_nov'] = "Nov"; $lang['cal_dec'] = "Dec"; $lang['cal_january'] = "January"; $lang['cal_february'] = "February"; $lang['cal_march'] = "March"; $lang['cal_april'] = "April"; $lang['cal_mayl'] = "May"; $lang['cal_june'] = "June"; $lang['cal_july'] = "July"; $lang['cal_august'] = "August"; $lang['cal_september'] = "September"; $lang['cal_october'] = "October"; $lang['cal_november'] = "November"; $lang['cal_december'] = "December"; /* End of file calendar_lang.php */ /* Location: ./system/language/english/calendar_lang.php */
101-code
system/language/english/calendar_lang.php
PHP
gpl3
1,437
<?php $lang['db_invalid_connection_str'] = 'Unable to determine the database settings based on the connection string you submitted.'; $lang['db_unable_to_connect'] = 'Unable to connect to your database server using the provided settings.'; $lang['db_unable_to_select'] = 'Unable to select the specified database: %s'; $lang['db_unable_to_create'] = 'Unable to create the specified database: %s'; $lang['db_invalid_query'] = 'The query you submitted is not valid.'; $lang['db_must_set_table'] = 'You must set the database table to be used with your query.'; $lang['db_must_use_set'] = 'You must use the "set" method to update an entry.'; $lang['db_must_use_index'] = 'You must specify an index to match on for batch updates.'; $lang['db_batch_missing_index'] = 'One or more rows submitted for batch updating is missing the specified index.'; $lang['db_must_use_where'] = 'Updates are not allowed unless they contain a "where" clause.'; $lang['db_del_must_use_where'] = 'Deletes are not allowed unless they contain a "where" or "like" clause.'; $lang['db_field_param_missing'] = 'To fetch fields requires the name of the table as a parameter.'; $lang['db_unsupported_function'] = 'This feature is not available for the database you are using.'; $lang['db_transaction_failure'] = 'Transaction failure: Rollback performed.'; $lang['db_unable_to_drop'] = 'Unable to drop the specified database.'; $lang['db_unsuported_feature'] = 'Unsupported feature of the database platform you are using.'; $lang['db_unsuported_compression'] = 'The file compression format you chose is not supported by your server.'; $lang['db_filepath_error'] = 'Unable to write data to the file path you have submitted.'; $lang['db_invalid_cache_path'] = 'The cache path you submitted is not valid or writable.'; $lang['db_table_name_required'] = 'A table name is required for that operation.'; $lang['db_column_name_required'] = 'A column name is required for that operation.'; $lang['db_column_definition_required'] = 'A column definition is required for that operation.'; $lang['db_unable_to_set_charset'] = 'Unable to set client connection character set: %s'; $lang['db_error_heading'] = 'A Database Error Occurred'; /* End of file db_lang.php */ /* Location: ./system/language/english/db_lang.php */
101-code
system/language/english/db_lang.php
PHP
gpl3
2,273
<?php $lang['date_year'] = "Year"; $lang['date_years'] = "Years"; $lang['date_month'] = "Month"; $lang['date_months'] = "Months"; $lang['date_week'] = "Week"; $lang['date_weeks'] = "Weeks"; $lang['date_day'] = "Day"; $lang['date_days'] = "Days"; $lang['date_hour'] = "Hour"; $lang['date_hours'] = "Hours"; $lang['date_minute'] = "Minute"; $lang['date_minutes'] = "Minutes"; $lang['date_second'] = "Second"; $lang['date_seconds'] = "Seconds"; $lang['UM12'] = '(UTC -12:00) Baker/Howland Island'; $lang['UM11'] = '(UTC -11:00) Samoa Time Zone, Niue'; $lang['UM10'] = '(UTC -10:00) Hawaii-Aleutian Standard Time, Cook Islands, Tahiti'; $lang['UM95'] = '(UTC -9:30) Marquesas Islands'; $lang['UM9'] = '(UTC -9:00) Alaska Standard Time, Gambier Islands'; $lang['UM8'] = '(UTC -8:00) Pacific Standard Time, Clipperton Island'; $lang['UM7'] = '(UTC -7:00) Mountain Standard Time'; $lang['UM6'] = '(UTC -6:00) Central Standard Time'; $lang['UM5'] = '(UTC -5:00) Eastern Standard Time, Western Caribbean Standard Time'; $lang['UM45'] = '(UTC -4:30) Venezuelan Standard Time'; $lang['UM4'] = '(UTC -4:00) Atlantic Standard Time, Eastern Caribbean Standard Time'; $lang['UM35'] = '(UTC -3:30) Newfoundland Standard Time'; $lang['UM3'] = '(UTC -3:00) Argentina, Brazil, French Guiana, Uruguay'; $lang['UM2'] = '(UTC -2:00) South Georgia/South Sandwich Islands'; $lang['UM1'] = '(UTC -1:00) Azores, Cape Verde Islands'; $lang['UTC'] = '(UTC) Greenwich Mean Time, Western European Time'; $lang['UP1'] = '(UTC +1:00) Central European Time, West Africa Time'; $lang['UP2'] = '(UTC +2:00) Central Africa Time, Eastern European Time, Kaliningrad Time'; $lang['UP3'] = '(UTC +3:00) Moscow Time, East Africa Time'; $lang['UP35'] = '(UTC +3:30) Iran Standard Time'; $lang['UP4'] = '(UTC +4:00) Azerbaijan Standard Time, Samara Time'; $lang['UP45'] = '(UTC +4:30) Afghanistan'; $lang['UP5'] = '(UTC +5:00) Pakistan Standard Time, Yekaterinburg Time'; $lang['UP55'] = '(UTC +5:30) Indian Standard Time, Sri Lanka Time'; $lang['UP575'] = '(UTC +5:45) Nepal Time'; $lang['UP6'] = '(UTC +6:00) Bangladesh Standard Time, Bhutan Time, Omsk Time'; $lang['UP65'] = '(UTC +6:30) Cocos Islands, Myanmar'; $lang['UP7'] = '(UTC +7:00) Krasnoyarsk Time, Cambodia, Laos, Thailand, Vietnam'; $lang['UP8'] = '(UTC +8:00) Australian Western Standard Time, Beijing Time, Irkutsk Time'; $lang['UP875'] = '(UTC +8:45) Australian Central Western Standard Time'; $lang['UP9'] = '(UTC +9:00) Japan Standard Time, Korea Standard Time, Yakutsk Time'; $lang['UP95'] = '(UTC +9:30) Australian Central Standard Time'; $lang['UP10'] = '(UTC +10:00) Australian Eastern Standard Time, Vladivostok Time'; $lang['UP105'] = '(UTC +10:30) Lord Howe Island'; $lang['UP11'] = '(UTC +11:00) Magadan Time, Solomon Islands, Vanuatu'; $lang['UP115'] = '(UTC +11:30) Norfolk Island'; $lang['UP12'] = '(UTC +12:00) Fiji, Gilbert Islands, Kamchatka Time, New Zealand Standard Time'; $lang['UP1275'] = '(UTC +12:45) Chatham Islands Standard Time'; $lang['UP13'] = '(UTC +13:00) Phoenix Islands Time, Tonga'; $lang['UP14'] = '(UTC +14:00) Line Islands'; /* End of file date_lang.php */ /* Location: ./system/language/english/date_lang.php */
101-code
system/language/english/date_lang.php
PHP
gpl3
3,177
<?php $lang['ut_test_name'] = 'Test Name'; $lang['ut_test_datatype'] = 'Test Datatype'; $lang['ut_res_datatype'] = 'Expected Datatype'; $lang['ut_result'] = 'Result'; $lang['ut_undefined'] = 'Undefined Test Name'; $lang['ut_file'] = 'File Name'; $lang['ut_line'] = 'Line Number'; $lang['ut_passed'] = 'Passed'; $lang['ut_failed'] = 'Failed'; $lang['ut_boolean'] = 'Boolean'; $lang['ut_integer'] = 'Integer'; $lang['ut_float'] = 'Float'; $lang['ut_double'] = 'Float'; // can be the same as float $lang['ut_string'] = 'String'; $lang['ut_array'] = 'Array'; $lang['ut_object'] = 'Object'; $lang['ut_resource'] = 'Resource'; $lang['ut_null'] = 'Null'; $lang['ut_notes'] = 'Notes'; /* End of file unit_test_lang.php */ /* Location: ./system/language/english/unit_test_lang.php */
101-code
system/language/english/unit_test_lang.php
PHP
gpl3
808
<?php $lang['email_must_be_array'] = "The email validation method must be passed an array."; $lang['email_invalid_address'] = "Invalid email address: %s"; $lang['email_attachment_missing'] = "Unable to locate the following email attachment: %s"; $lang['email_attachment_unreadable'] = "Unable to open this attachment: %s"; $lang['email_no_recipients'] = "You must include recipients: To, Cc, or Bcc"; $lang['email_send_failure_phpmail'] = "Unable to send email using PHP mail(). Your server might not be configured to send mail using this method."; $lang['email_send_failure_sendmail'] = "Unable to send email using PHP Sendmail. Your server might not be configured to send mail using this method."; $lang['email_send_failure_smtp'] = "Unable to send email using PHP SMTP. Your server might not be configured to send mail using this method."; $lang['email_sent'] = "Your message has been successfully sent using the following protocol: %s"; $lang['email_no_socket'] = "Unable to open a socket to Sendmail. Please check settings."; $lang['email_no_hostname'] = "You did not specify a SMTP hostname."; $lang['email_smtp_error'] = "The following SMTP error was encountered: %s"; $lang['email_no_smtp_unpw'] = "Error: You must assign a SMTP username and password."; $lang['email_failed_smtp_login'] = "Failed to send AUTH LOGIN command. Error: %s"; $lang['email_smtp_auth_un'] = "Failed to authenticate username. Error: %s"; $lang['email_smtp_auth_pw'] = "Failed to authenticate password. Error: %s"; $lang['email_smtp_data_failure'] = "Unable to send data: %s"; $lang['email_exit_status'] = "Exit status code: %s"; /* End of file email_lang.php */ /* Location: ./system/language/english/email_lang.php */
101-code
system/language/english/email_lang.php
PHP
gpl3
1,707
<?php $lang['required'] = "The %s field is required."; $lang['isset'] = "The %s field must have a value."; $lang['valid_email'] = "The %s field must contain a valid email address."; $lang['valid_emails'] = "The %s field must contain all valid email addresses."; $lang['valid_url'] = "The %s field must contain a valid URL."; $lang['valid_ip'] = "The %s field must contain a valid IP."; $lang['min_length'] = "The %s field must be at least %s characters in length."; $lang['max_length'] = "The %s field can not exceed %s characters in length."; $lang['exact_length'] = "The %s field must be exactly %s characters in length."; $lang['alpha'] = "The %s field may only contain alphabetical characters."; $lang['alpha_numeric'] = "The %s field may only contain alpha-numeric characters."; $lang['alpha_dash'] = "The %s field may only contain alpha-numeric characters, underscores, and dashes."; $lang['numeric'] = "The %s field must contain only numbers."; $lang['is_numeric'] = "The %s field must contain only numeric characters."; $lang['integer'] = "The %s field must contain an integer."; $lang['regex_match'] = "The %s field is not in the correct format."; $lang['matches'] = "The %s field does not match the %s field."; $lang['is_unique'] = "The %s field must contain a unique value."; $lang['is_natural'] = "The %s field must contain only positive numbers."; $lang['is_natural_no_zero'] = "The %s field must contain a number greater than zero."; $lang['decimal'] = "The %s field must contain a decimal number."; $lang['less_than'] = "The %s field must contain a number less than %s."; $lang['greater_than'] = "The %s field must contain a number greater than %s."; /* End of file form_validation_lang.php */ /* Location: ./system/language/english/form_validation_lang.php */
101-code
system/language/english/form_validation_lang.php
PHP
gpl3
1,819
<?php $lang['migration_none_found'] = "No migrations were found."; $lang['migration_not_found'] = "This migration could not be found."; $lang['migration_multiple_version'] = "This are multiple migrations with the same version number: %d."; $lang['migration_class_doesnt_exist'] = "The migration class \"%s\" could not be found."; $lang['migration_missing_up_method'] = "The migration class \"%s\" is missing an 'up' method."; $lang['migration_missing_down_method'] = "The migration class \"%s\" is missing an 'up' method."; $lang['migration_invalid_filename'] = "Migration \"%s\" has an invalid filename."; /* End of file migration_lang.php */ /* Location: ./system/language/english/migration_lang.php */
101-code
system/language/english/migration_lang.php
PHP
gpl3
713
<?php $lang['imglib_source_image_required'] = "You must specify a source image in your preferences."; $lang['imglib_gd_required'] = "The GD image library is required for this feature."; $lang['imglib_gd_required_for_props'] = "Your server must support the GD image library in order to determine the image properties."; $lang['imglib_unsupported_imagecreate'] = "Your server does not support the GD function required to process this type of image."; $lang['imglib_gif_not_supported'] = "GIF images are often not supported due to licensing restrictions. You may have to use JPG or PNG images instead."; $lang['imglib_jpg_not_supported'] = "JPG images are not supported."; $lang['imglib_png_not_supported'] = "PNG images are not supported."; $lang['imglib_jpg_or_png_required'] = "The image resize protocol specified in your preferences only works with JPEG or PNG image types."; $lang['imglib_copy_error'] = "An error was encountered while attempting to replace the file. Please make sure your file directory is writable."; $lang['imglib_rotate_unsupported'] = "Image rotation does not appear to be supported by your server."; $lang['imglib_libpath_invalid'] = "The path to your image library is not correct. Please set the correct path in your image preferences."; $lang['imglib_image_process_failed'] = "Image processing failed. Please verify that your server supports the chosen protocol and that the path to your image library is correct."; $lang['imglib_rotation_angle_required'] = "An angle of rotation is required to rotate the image."; $lang['imglib_writing_failed_gif'] = "GIF image."; $lang['imglib_invalid_path'] = "The path to the image is not correct."; $lang['imglib_copy_failed'] = "The image copy routine failed."; $lang['imglib_missing_font'] = "Unable to find a font to use."; $lang['imglib_save_failed'] = "Unable to save the image. Please make sure the image and file directory are writable."; /* End of file imglib_lang.php */ /* Location: ./system/language/english/imglib_lang.php */
101-code
system/language/english/imglib_lang.php
PHP
gpl3
2,011
<?php $lang['ftp_no_connection'] = "Unable to locate a valid connection ID. Please make sure you are connected before peforming any file routines."; $lang['ftp_unable_to_connect'] = "Unable to connect to your FTP server using the supplied hostname."; $lang['ftp_unable_to_login'] = "Unable to login to your FTP server. Please check your username and password."; $lang['ftp_unable_to_makdir'] = "Unable to create the directory you have specified."; $lang['ftp_unable_to_changedir'] = "Unable to change directories."; $lang['ftp_unable_to_chmod'] = "Unable to set file permissions. Please check your path. Note: This feature is only available in PHP 5 or higher."; $lang['ftp_unable_to_upload'] = "Unable to upload the specified file. Please check your path."; $lang['ftp_unable_to_download'] = "Unable to download the specified file. Please check your path."; $lang['ftp_no_source_file'] = "Unable to locate the source file. Please check your path."; $lang['ftp_unable_to_rename'] = "Unable to rename the file."; $lang['ftp_unable_to_delete'] = "Unable to delete the file."; $lang['ftp_unable_to_move'] = "Unable to move the file. Please make sure the destination directory exists."; /* End of file ftp_lang.php */ /* Location: ./system/language/english/ftp_lang.php */
101-code
system/language/english/ftp_lang.php
PHP
gpl3
1,285
<?php $lang['terabyte_abbr'] = "TB"; $lang['gigabyte_abbr'] = "GB"; $lang['megabyte_abbr'] = "MB"; $lang['kilobyte_abbr'] = "KB"; $lang['bytes'] = "Bytes"; /* End of file number_lang.php */ /* Location: ./system/language/english/number_lang.php */
101-code
system/language/english/number_lang.php
PHP
gpl3
249
<html> <head> <title>403 Forbidden</title> </head> <body> <p>Directory access is forbidden.</p> </body> </html>
101-code
system/language/english/index.html
HTML
gpl3
114
<?php $lang['profiler_database'] = 'DATABASE'; $lang['profiler_controller_info'] = 'CLASS/METHOD'; $lang['profiler_benchmarks'] = 'BENCHMARKS'; $lang['profiler_queries'] = 'QUERIES'; $lang['profiler_get_data'] = 'GET DATA'; $lang['profiler_post_data'] = 'POST DATA'; $lang['profiler_uri_string'] = 'URI STRING'; $lang['profiler_memory_usage'] = 'MEMORY USAGE'; $lang['profiler_config'] = 'CONFIG VARIABLES'; $lang['profiler_session_data'] = 'SESSION DATA'; $lang['profiler_headers'] = 'HTTP HEADERS'; $lang['profiler_no_db'] = 'Database driver is not currently loaded'; $lang['profiler_no_queries'] = 'No queries were run'; $lang['profiler_no_post'] = 'No POST data exists'; $lang['profiler_no_get'] = 'No GET data exists'; $lang['profiler_no_uri'] = 'No URI data exists'; $lang['profiler_no_memory'] = 'Memory Usage Unavailable'; $lang['profiler_no_profiles'] = 'No Profile data - all Profiler sections have been disabled.'; $lang['profiler_section_hide'] = 'Hide'; $lang['profiler_section_show'] = 'Show'; /* End of file profiler_lang.php */ /* Location: ./system/language/english/profiler_lang.php */
101-code
system/language/english/profiler_lang.php
PHP
gpl3
1,117
<html> <head> <title>403 Forbidden</title> </head> <body> <p>Directory access is forbidden.</p> </body> </html>
101-code
system/language/index.html
HTML
gpl3
114
<html> <head> <title>403 Forbidden</title> </head> <body> <p>Directory access is forbidden.</p> </body> </html>
101-code
system/fonts/index.html
HTML
gpl3
114
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // ------------------------------------------------------------------------ /** * CodeIgniter Download Helpers * * @package CodeIgniter * @subpackage Helpers * @category Helpers * @author ExpressionEngine Dev Team * @link http://codeigniter.com/user_guide/helpers/download_helper.html */ // ------------------------------------------------------------------------ /** * Force Download * * Generates headers that force a download to happen * * @access public * @param string filename * @param mixed the data to be downloaded * @return void */ if ( ! function_exists('force_download')) { function force_download($filename = '', $data = '') { if ($filename == '' OR $data == '') { return FALSE; } // Try to determine if the filename includes a file extension. // We need it in order to set the MIME type if (FALSE === strpos($filename, '.')) { return FALSE; } // Grab the file extension $x = explode('.', $filename); $extension = end($x); // Load the mime types if (defined('ENVIRONMENT') AND is_file(APPPATH.'config/'.ENVIRONMENT.'/mimes.php')) { include(APPPATH.'config/'.ENVIRONMENT.'/mimes.php'); } elseif (is_file(APPPATH.'config/mimes.php')) { include(APPPATH.'config/mimes.php'); } // Set a default mime if we can't find it if ( ! isset($mimes[$extension])) { $mime = 'application/octet-stream'; } else { $mime = (is_array($mimes[$extension])) ? $mimes[$extension][0] : $mimes[$extension]; } // Generate the server headers if (strpos($_SERVER['HTTP_USER_AGENT'], "MSIE") !== FALSE) { header('Content-Type: "'.$mime.'"'); header('Content-Disposition: attachment; filename="'.$filename.'"'); header('Expires: 0'); header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); header("Content-Transfer-Encoding: binary"); header('Pragma: public'); header("Content-Length: ".strlen($data)); } else { header('Content-Type: "'.$mime.'"'); header('Content-Disposition: attachment; filename="'.$filename.'"'); header("Content-Transfer-Encoding: binary"); header('Expires: 0'); header('Pragma: no-cache'); header("Content-Length: ".strlen($data)); } exit($data); } } /* End of file download_helper.php */ /* Location: ./system/helpers/download_helper.php */
101-code
system/helpers/download_helper.php
PHP
gpl3
2,747
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // ------------------------------------------------------------------------ /** * CodeIgniter Directory Helpers * * @package CodeIgniter * @subpackage Helpers * @category Helpers * @author ExpressionEngine Dev Team * @link http://codeigniter.com/user_guide/helpers/directory_helper.html */ // ------------------------------------------------------------------------ /** * Create a Directory Map * * Reads the specified directory and builds an array * representation of it. Sub-folders contained with the * directory will be mapped as well. * * @access public * @param string path to source * @param int depth of directories to traverse (0 = fully recursive, 1 = current dir, etc) * @return array */ if ( ! function_exists('directory_map')) { function directory_map($source_dir, $directory_depth = 0, $hidden = FALSE) { if ($fp = @opendir($source_dir)) { $filedata = array(); $new_depth = $directory_depth - 1; $source_dir = rtrim($source_dir, DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR; while (FALSE !== ($file = readdir($fp))) { // Remove '.', '..', and hidden files [optional] if ( ! trim($file, '.') OR ($hidden == FALSE && $file[0] == '.')) { continue; } if (($directory_depth < 1 OR $new_depth > 0) && @is_dir($source_dir.$file)) { $filedata[$file] = directory_map($source_dir.$file.DIRECTORY_SEPARATOR, $new_depth, $hidden); } else { $filedata[] = $file; } } closedir($fp); return $filedata; } return FALSE; } } /* End of file directory_helper.php */ /* Location: ./system/helpers/directory_helper.php */
101-code
system/helpers/directory_helper.php
PHP
gpl3
2,062
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // ------------------------------------------------------------------------ /** * CodeIgniter Path Helpers * * @package CodeIgniter * @subpackage Helpers * @category Helpers * @author ExpressionEngine Dev Team * @link http://codeigniter.com/user_guide/helpers/xml_helper.html */ // ------------------------------------------------------------------------ /** * Set Realpath * * @access public * @param string * @param bool checks to see if the path exists * @return string */ if ( ! function_exists('set_realpath')) { function set_realpath($path, $check_existance = FALSE) { // Security check to make sure the path is NOT a URL. No remote file inclusion! if (preg_match("#^(http:\/\/|https:\/\/|www\.|ftp|[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})#i", $path)) { show_error('The path you submitted must be a local server path, not a URL'); } // Resolve the path if (function_exists('realpath') AND @realpath($path) !== FALSE) { $path = realpath($path).'/'; } // Add a trailing slash $path = preg_replace("#([^/])/*$#", "\\1/", $path); // Make sure the path exists if ($check_existance == TRUE) { if ( ! is_dir($path)) { show_error('Not a valid path: '.$path); } } return $path; } } /* End of file path_helper.php */ /* Location: ./system/helpers/path_helper.php */
101-code
system/helpers/path_helper.php
PHP
gpl3
1,779
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // ------------------------------------------------------------------------ /** * CodeIgniter Email Helpers * * @package CodeIgniter * @subpackage Helpers * @category Helpers * @author ExpressionEngine Dev Team * @link http://codeigniter.com/user_guide/helpers/email_helper.html */ // ------------------------------------------------------------------------ /** * Validate email address * * @access public * @return bool */ if ( ! function_exists('valid_email')) { function valid_email($address) { return ( ! preg_match("/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/ix", $address)) ? FALSE : TRUE; } } // ------------------------------------------------------------------------ /** * Send an email * * @access public * @return bool */ if ( ! function_exists('send_email')) { function send_email($recipient, $subject = 'Test email', $message = 'Hello World') { return mail($recipient, $subject, $message); } } /* End of file email_helper.php */ /* Location: ./system/helpers/email_helper.php */
101-code
system/helpers/email_helper.php
PHP
gpl3
1,483
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // ------------------------------------------------------------------------ /** * CodeIgniter Date Helpers * * @package CodeIgniter * @subpackage Helpers * @category Helpers * @author ExpressionEngine Dev Team * @link http://codeigniter.com/user_guide/helpers/date_helper.html */ // ------------------------------------------------------------------------ /** * Get "now" time * * Returns time() or its GMT equivalent based on the config file preference * * @access public * @return integer */ if ( ! function_exists('now')) { function now() { $CI =& get_instance(); if (strtolower($CI->config->item('time_reference')) == 'gmt') { $now = time(); $system_time = mktime(gmdate("H", $now), gmdate("i", $now), gmdate("s", $now), gmdate("m", $now), gmdate("d", $now), gmdate("Y", $now)); if (strlen($system_time) < 10) { $system_time = time(); log_message('error', 'The Date class could not set a proper GMT timestamp so the local time() value was used.'); } return $system_time; } else { return time(); } } } // ------------------------------------------------------------------------ /** * Convert MySQL Style Datecodes * * This function is identical to PHPs date() function, * except that it allows date codes to be formatted using * the MySQL style, where each code letter is preceded * with a percent sign: %Y %m %d etc... * * The benefit of doing dates this way is that you don't * have to worry about escaping your text letters that * match the date codes. * * @access public * @param string * @param integer * @return integer */ if ( ! function_exists('mdate')) { function mdate($datestr = '', $time = '') { if ($datestr == '') return ''; if ($time == '') $time = now(); $datestr = str_replace('%\\', '', preg_replace("/([a-z]+?){1}/i", "\\\\\\1", $datestr)); return date($datestr, $time); } } // ------------------------------------------------------------------------ /** * Standard Date * * Returns a date formatted according to the submitted standard. * * @access public * @param string the chosen format * @param integer Unix timestamp * @return string */ if ( ! function_exists('standard_date')) { function standard_date($fmt = 'DATE_RFC822', $time = '') { $formats = array( 'DATE_ATOM' => '%Y-%m-%dT%H:%i:%s%Q', 'DATE_COOKIE' => '%l, %d-%M-%y %H:%i:%s UTC', 'DATE_ISO8601' => '%Y-%m-%dT%H:%i:%s%Q', 'DATE_RFC822' => '%D, %d %M %y %H:%i:%s %O', 'DATE_RFC850' => '%l, %d-%M-%y %H:%i:%s UTC', 'DATE_RFC1036' => '%D, %d %M %y %H:%i:%s %O', 'DATE_RFC1123' => '%D, %d %M %Y %H:%i:%s %O', 'DATE_RSS' => '%D, %d %M %Y %H:%i:%s %O', 'DATE_W3C' => '%Y-%m-%dT%H:%i:%s%Q' ); if ( ! isset($formats[$fmt])) { return FALSE; } return mdate($formats[$fmt], $time); } } // ------------------------------------------------------------------------ /** * Timespan * * Returns a span of seconds in this format: * 10 days 14 hours 36 minutes 47 seconds * * @access public * @param integer a number of seconds * @param integer Unix timestamp * @return integer */ if ( ! function_exists('timespan')) { function timespan($seconds = 1, $time = '') { $CI =& get_instance(); $CI->lang->load('date'); if ( ! is_numeric($seconds)) { $seconds = 1; } if ( ! is_numeric($time)) { $time = time(); } if ($time <= $seconds) { $seconds = 1; } else { $seconds = $time - $seconds; } $str = ''; $years = floor($seconds / 31536000); if ($years > 0) { $str .= $years.' '.$CI->lang->line((($years > 1) ? 'date_years' : 'date_year')).', '; } $seconds -= $years * 31536000; $months = floor($seconds / 2628000); if ($years > 0 OR $months > 0) { if ($months > 0) { $str .= $months.' '.$CI->lang->line((($months > 1) ? 'date_months' : 'date_month')).', '; } $seconds -= $months * 2628000; } $weeks = floor($seconds / 604800); if ($years > 0 OR $months > 0 OR $weeks > 0) { if ($weeks > 0) { $str .= $weeks.' '.$CI->lang->line((($weeks > 1) ? 'date_weeks' : 'date_week')).', '; } $seconds -= $weeks * 604800; } $days = floor($seconds / 86400); if ($months > 0 OR $weeks > 0 OR $days > 0) { if ($days > 0) { $str .= $days.' '.$CI->lang->line((($days > 1) ? 'date_days' : 'date_day')).', '; } $seconds -= $days * 86400; } $hours = floor($seconds / 3600); if ($days > 0 OR $hours > 0) { if ($hours > 0) { $str .= $hours.' '.$CI->lang->line((($hours > 1) ? 'date_hours' : 'date_hour')).', '; } $seconds -= $hours * 3600; } $minutes = floor($seconds / 60); if ($days > 0 OR $hours > 0 OR $minutes > 0) { if ($minutes > 0) { $str .= $minutes.' '.$CI->lang->line((($minutes > 1) ? 'date_minutes' : 'date_minute')).', '; } $seconds -= $minutes * 60; } if ($str == '') { $str .= $seconds.' '.$CI->lang->line((($seconds > 1) ? 'date_seconds' : 'date_second')).', '; } return substr(trim($str), 0, -1); } } // ------------------------------------------------------------------------ /** * Number of days in a month * * Takes a month/year as input and returns the number of days * for the given month/year. Takes leap years into consideration. * * @access public * @param integer a numeric month * @param integer a numeric year * @return integer */ if ( ! function_exists('days_in_month')) { function days_in_month($month = 0, $year = '') { if ($month < 1 OR $month > 12) { return 0; } if ( ! is_numeric($year) OR strlen($year) != 4) { $year = date('Y'); } if ($month == 2) { if ($year % 400 == 0 OR ($year % 4 == 0 AND $year % 100 != 0)) { return 29; } } $days_in_month = array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31); return $days_in_month[$month - 1]; } } // ------------------------------------------------------------------------ /** * Converts a local Unix timestamp to GMT * * @access public * @param integer Unix timestamp * @return integer */ if ( ! function_exists('local_to_gmt')) { function local_to_gmt($time = '') { if ($time == '') $time = time(); return mktime( gmdate("H", $time), gmdate("i", $time), gmdate("s", $time), gmdate("m", $time), gmdate("d", $time), gmdate("Y", $time)); } } // ------------------------------------------------------------------------ /** * Converts GMT time to a localized value * * Takes a Unix timestamp (in GMT) as input, and returns * at the local value based on the timezone and DST setting * submitted * * @access public * @param integer Unix timestamp * @param string timezone * @param bool whether DST is active * @return integer */ if ( ! function_exists('gmt_to_local')) { function gmt_to_local($time = '', $timezone = 'UTC', $dst = FALSE) { if ($time == '') { return now(); } $time += timezones($timezone) * 3600; if ($dst == TRUE) { $time += 3600; } return $time; } } // ------------------------------------------------------------------------ /** * Converts a MySQL Timestamp to Unix * * @access public * @param integer Unix timestamp * @return integer */ if ( ! function_exists('mysql_to_unix')) { function mysql_to_unix($time = '') { // We'll remove certain characters for backward compatibility // since the formatting changed with MySQL 4.1 // YYYY-MM-DD HH:MM:SS $time = str_replace('-', '', $time); $time = str_replace(':', '', $time); $time = str_replace(' ', '', $time); // YYYYMMDDHHMMSS return mktime( substr($time, 8, 2), substr($time, 10, 2), substr($time, 12, 2), substr($time, 4, 2), substr($time, 6, 2), substr($time, 0, 4) ); } } // ------------------------------------------------------------------------ /** * Unix to "Human" * * Formats Unix timestamp to the following prototype: 2006-08-21 11:35 PM * * @access public * @param integer Unix timestamp * @param bool whether to show seconds * @param string format: us or euro * @return string */ if ( ! function_exists('unix_to_human')) { function unix_to_human($time = '', $seconds = FALSE, $fmt = 'us') { $r = date('Y', $time).'-'.date('m', $time).'-'.date('d', $time).' '; if ($fmt == 'us') { $r .= date('h', $time).':'.date('i', $time); } else { $r .= date('H', $time).':'.date('i', $time); } if ($seconds) { $r .= ':'.date('s', $time); } if ($fmt == 'us') { $r .= ' '.date('A', $time); } return $r; } } // ------------------------------------------------------------------------ /** * Convert "human" date to GMT * * Reverses the above process * * @access public * @param string format: us or euro * @return integer */ if ( ! function_exists('human_to_unix')) { function human_to_unix($datestr = '') { if ($datestr == '') { return FALSE; } $datestr = trim($datestr); $datestr = preg_replace("/\040+/", ' ', $datestr); if ( ! preg_match('/^[0-9]{2,4}\-[0-9]{1,2}\-[0-9]{1,2}\s[0-9]{1,2}:[0-9]{1,2}(?::[0-9]{1,2})?(?:\s[AP]M)?$/i', $datestr)) { return FALSE; } $split = explode(' ', $datestr); $ex = explode("-", $split['0']); $year = (strlen($ex['0']) == 2) ? '20'.$ex['0'] : $ex['0']; $month = (strlen($ex['1']) == 1) ? '0'.$ex['1'] : $ex['1']; $day = (strlen($ex['2']) == 1) ? '0'.$ex['2'] : $ex['2']; $ex = explode(":", $split['1']); $hour = (strlen($ex['0']) == 1) ? '0'.$ex['0'] : $ex['0']; $min = (strlen($ex['1']) == 1) ? '0'.$ex['1'] : $ex['1']; if (isset($ex['2']) && preg_match('/[0-9]{1,2}/', $ex['2'])) { $sec = (strlen($ex['2']) == 1) ? '0'.$ex['2'] : $ex['2']; } else { // Unless specified, seconds get set to zero. $sec = '00'; } if (isset($split['2'])) { $ampm = strtolower($split['2']); if (substr($ampm, 0, 1) == 'p' AND $hour < 12) $hour = $hour + 12; if (substr($ampm, 0, 1) == 'a' AND $hour == 12) $hour = '00'; if (strlen($hour) == 1) $hour = '0'.$hour; } return mktime($hour, $min, $sec, $month, $day, $year); } } // ------------------------------------------------------------------------ /** * Timezone Menu * * Generates a drop-down menu of timezones. * * @access public * @param string timezone * @param string classname * @param string menu name * @return string */ if ( ! function_exists('timezone_menu')) { function timezone_menu($default = 'UTC', $class = "", $name = 'timezones') { $CI =& get_instance(); $CI->lang->load('date'); if ($default == 'GMT') $default = 'UTC'; $menu = '<select name="'.$name.'"'; if ($class != '') { $menu .= ' class="'.$class.'"'; } $menu .= ">\n"; foreach (timezones() as $key => $val) { $selected = ($default == $key) ? " selected='selected'" : ''; $menu .= "<option value='{$key}'{$selected}>".$CI->lang->line($key)."</option>\n"; } $menu .= "</select>"; return $menu; } } // ------------------------------------------------------------------------ /** * Timezones * * Returns an array of timezones. This is a helper function * for various other ones in this library * * @access public * @param string timezone * @return string */ if ( ! function_exists('timezones')) { function timezones($tz = '') { // Note: Don't change the order of these even though // some items appear to be in the wrong order $zones = array( 'UM12' => -12, 'UM11' => -11, 'UM10' => -10, 'UM95' => -9.5, 'UM9' => -9, 'UM8' => -8, 'UM7' => -7, 'UM6' => -6, 'UM5' => -5, 'UM45' => -4.5, 'UM4' => -4, 'UM35' => -3.5, 'UM3' => -3, 'UM2' => -2, 'UM1' => -1, 'UTC' => 0, 'UP1' => +1, 'UP2' => +2, 'UP3' => +3, 'UP35' => +3.5, 'UP4' => +4, 'UP45' => +4.5, 'UP5' => +5, 'UP55' => +5.5, 'UP575' => +5.75, 'UP6' => +6, 'UP65' => +6.5, 'UP7' => +7, 'UP8' => +8, 'UP875' => +8.75, 'UP9' => +9, 'UP95' => +9.5, 'UP10' => +10, 'UP105' => +10.5, 'UP11' => +11, 'UP115' => +11.5, 'UP12' => +12, 'UP1275' => +12.75, 'UP13' => +13, 'UP14' => +14 ); if ($tz == '') { return $zones; } if ($tz == 'GMT') $tz = 'UTC'; return ( ! isset($zones[$tz])) ? 0 : $zones[$tz]; } } /* End of file date_helper.php */ /* Location: ./system/helpers/date_helper.php */
101-code
system/helpers/date_helper.php
PHP
gpl3
12,971
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // ------------------------------------------------------------------------ /** * CodeIgniter URL Helpers * * @package CodeIgniter * @subpackage Helpers * @category Helpers * @author ExpressionEngine Dev Team * @link http://codeigniter.com/user_guide/helpers/url_helper.html */ // ------------------------------------------------------------------------ /** * Site URL * * Create a local URL based on your basepath. Segments can be passed via the * first parameter either as a string or an array. * * @access public * @param string * @return string */ if ( ! function_exists('site_url')) { function site_url($uri = '') { $CI =& get_instance(); return $CI->config->site_url($uri); } } // ------------------------------------------------------------------------ /** * Base URL * * Create a local URL based on your basepath. * Segments can be passed in as a string or an array, same as site_url * or a URL to a file can be passed in, e.g. to an image file. * * @access public * @param string * @return string */ if ( ! function_exists('base_url')) { function base_url($uri = '') { $CI =& get_instance(); return $CI->config->base_url($uri); } } // ------------------------------------------------------------------------ /** * Current URL * * Returns the full URL (including segments) of the page where this * function is placed * * @access public * @return string */ if ( ! function_exists('current_url')) { function current_url() { $CI =& get_instance(); return $CI->config->site_url($CI->uri->uri_string()); } } // ------------------------------------------------------------------------ /** * URL String * * Returns the URI segments. * * @access public * @return string */ if ( ! function_exists('uri_string')) { function uri_string() { $CI =& get_instance(); return $CI->uri->uri_string(); } } // ------------------------------------------------------------------------ /** * Index page * * Returns the "index_page" from your config file * * @access public * @return string */ if ( ! function_exists('index_page')) { function index_page() { $CI =& get_instance(); return $CI->config->item('index_page'); } } // ------------------------------------------------------------------------ /** * Anchor Link * * Creates an anchor based on the local URL. * * @access public * @param string the URL * @param string the link title * @param mixed any attributes * @return string */ if ( ! function_exists('anchor')) { function anchor($uri = '', $title = '', $attributes = '') { $title = (string) $title; if ( ! is_array($uri)) { $site_url = ( ! preg_match('!^\w+://! i', $uri)) ? site_url($uri) : $uri; } else { $site_url = site_url($uri); } if ($title == '') { $title = $site_url; } if ($attributes != '') { $attributes = _parse_attributes($attributes); } return '<a href="'.$site_url.'"'.$attributes.'>'.$title.'</a>'; } } // ------------------------------------------------------------------------ /** * Anchor Link - Pop-up version * * Creates an anchor based on the local URL. The link * opens a new window based on the attributes specified. * * @access public * @param string the URL * @param string the link title * @param mixed any attributes * @return string */ if ( ! function_exists('anchor_popup')) { function anchor_popup($uri = '', $title = '', $attributes = FALSE) { $title = (string) $title; $site_url = ( ! preg_match('!^\w+://! i', $uri)) ? site_url($uri) : $uri; if ($title == '') { $title = $site_url; } if ($attributes === FALSE) { return "<a href='javascript:void(0);' onclick=\"window.open('".$site_url."', '_blank');\">".$title."</a>"; } if ( ! is_array($attributes)) { $attributes = array(); } foreach (array('width' => '800', 'height' => '600', 'scrollbars' => 'yes', 'status' => 'yes', 'resizable' => 'yes', 'screenx' => '0', 'screeny' => '0', ) as $key => $val) { $atts[$key] = ( ! isset($attributes[$key])) ? $val : $attributes[$key]; unset($attributes[$key]); } if ($attributes != '') { $attributes = _parse_attributes($attributes); } return "<a href='javascript:void(0);' onclick=\"window.open('".$site_url."', '_blank', '"._parse_attributes($atts, TRUE)."');\"$attributes>".$title."</a>"; } } // ------------------------------------------------------------------------ /** * Mailto Link * * @access public * @param string the email address * @param string the link title * @param mixed any attributes * @return string */ if ( ! function_exists('mailto')) { function mailto($email, $title = '', $attributes = '') { $title = (string) $title; if ($title == "") { $title = $email; } $attributes = _parse_attributes($attributes); return '<a href="mailto:'.$email.'"'.$attributes.'>'.$title.'</a>'; } } // ------------------------------------------------------------------------ /** * Encoded Mailto Link * * Create a spam-protected mailto link written in Javascript * * @access public * @param string the email address * @param string the link title * @param mixed any attributes * @return string */ if ( ! function_exists('safe_mailto')) { function safe_mailto($email, $title = '', $attributes = '') { $title = (string) $title; if ($title == "") { $title = $email; } for ($i = 0; $i < 16; $i++) { $x[] = substr('<a href="mailto:', $i, 1); } for ($i = 0; $i < strlen($email); $i++) { $x[] = "|".ord(substr($email, $i, 1)); } $x[] = '"'; if ($attributes != '') { if (is_array($attributes)) { foreach ($attributes as $key => $val) { $x[] = ' '.$key.'="'; for ($i = 0; $i < strlen($val); $i++) { $x[] = "|".ord(substr($val, $i, 1)); } $x[] = '"'; } } else { for ($i = 0; $i < strlen($attributes); $i++) { $x[] = substr($attributes, $i, 1); } } } $x[] = '>'; $temp = array(); for ($i = 0; $i < strlen($title); $i++) { $ordinal = ord($title[$i]); if ($ordinal < 128) { $x[] = "|".$ordinal; } else { if (count($temp) == 0) { $count = ($ordinal < 224) ? 2 : 3; } $temp[] = $ordinal; if (count($temp) == $count) { $number = ($count == 3) ? (($temp['0'] % 16) * 4096) + (($temp['1'] % 64) * 64) + ($temp['2'] % 64) : (($temp['0'] % 32) * 64) + ($temp['1'] % 64); $x[] = "|".$number; $count = 1; $temp = array(); } } } $x[] = '<'; $x[] = '/'; $x[] = 'a'; $x[] = '>'; $x = array_reverse($x); ob_start(); ?><script type="text/javascript"> //<![CDATA[ var l=new Array(); <?php $i = 0; foreach ($x as $val){ ?>l[<?php echo $i++; ?>]='<?php echo $val; ?>';<?php } ?> for (var i = l.length-1; i >= 0; i=i-1){ if (l[i].substring(0, 1) == '|') document.write("&#"+unescape(l[i].substring(1))+";"); else document.write(unescape(l[i]));} //]]> </script><?php $buffer = ob_get_contents(); ob_end_clean(); return $buffer; } } // ------------------------------------------------------------------------ /** * Auto-linker * * Automatically links URL and Email addresses. * Note: There's a bit of extra code here to deal with * URLs or emails that end in a period. We'll strip these * off and add them after the link. * * @access public * @param string the string * @param string the type: email, url, or both * @param bool whether to create pop-up links * @return string */ if ( ! function_exists('auto_link')) { function auto_link($str, $type = 'both', $popup = FALSE) { if ($type != 'email') { if (preg_match_all("#(^|\s|\()((http(s?)://)|(www\.))(\w+[^\s\)\<]+)#i", $str, $matches)) { $pop = ($popup == TRUE) ? " target=\"_blank\" " : ""; for ($i = 0; $i < count($matches['0']); $i++) { $period = ''; if (preg_match("|\.$|", $matches['6'][$i])) { $period = '.'; $matches['6'][$i] = substr($matches['6'][$i], 0, -1); } $str = str_replace($matches['0'][$i], $matches['1'][$i].'<a href="http'. $matches['4'][$i].'://'. $matches['5'][$i]. $matches['6'][$i].'"'.$pop.'>http'. $matches['4'][$i].'://'. $matches['5'][$i]. $matches['6'][$i].'</a>'. $period, $str); } } } if ($type != 'url') { if (preg_match_all("/([a-zA-Z0-9_\.\-\+]+)@([a-zA-Z0-9\-]+)\.([a-zA-Z0-9\-\.]*)/i", $str, $matches)) { for ($i = 0; $i < count($matches['0']); $i++) { $period = ''; if (preg_match("|\.$|", $matches['3'][$i])) { $period = '.'; $matches['3'][$i] = substr($matches['3'][$i], 0, -1); } $str = str_replace($matches['0'][$i], safe_mailto($matches['1'][$i].'@'.$matches['2'][$i].'.'.$matches['3'][$i]).$period, $str); } } } return $str; } } // ------------------------------------------------------------------------ /** * Prep URL * * Simply adds the http:// part if no scheme is included * * @access public * @param string the URL * @return string */ if ( ! function_exists('prep_url')) { function prep_url($str = '') { if ($str == 'http://' OR $str == '') { return ''; } $url = parse_url($str); if ( ! $url OR ! isset($url['scheme'])) { $str = 'http://'.$str; } return $str; } } // ------------------------------------------------------------------------ /** * Create URL Title * * Takes a "title" string as input and creates a * human-friendly URL string with either a dash * or an underscore as the word separator. * * @access public * @param string the string * @param string the separator: dash, or underscore * @return string */ if ( ! function_exists('url_title')) { function url_title($str, $separator = 'dash', $lowercase = FALSE) { if ($separator == 'dash') { $search = '_'; $replace = '-'; } else { $search = '-'; $replace = '_'; } $trans = array( '&\#\d+?;' => '', '&\S+?;' => '', '\s+' => $replace, '[^a-z0-9\-\._]' => '', $replace.'+' => $replace, $replace.'$' => $replace, '^'.$replace => $replace, '\.+$' => '' ); $str = strip_tags($str); foreach ($trans as $key => $val) { $str = preg_replace("#".$key."#i", $val, $str); } if ($lowercase === TRUE) { $str = strtolower($str); } return trim(stripslashes($str)); } } // ------------------------------------------------------------------------ /** * Header Redirect * * Header redirect in two flavors * For very fine grained control over headers, you could use the Output * Library's set_header() function. * * @access public * @param string the URL * @param string the method: location or redirect * @return string */ if ( ! function_exists('redirect')) { function redirect($uri = '', $method = 'location', $http_response_code = 302) { if ( ! preg_match('#^https?://#i', $uri)) { $uri = site_url($uri); } switch($method) { case 'refresh' : header("Refresh:0;url=".$uri); break; default : header("Location: ".$uri, TRUE, $http_response_code); break; } exit; } } // ------------------------------------------------------------------------ /** * Parse out the attributes * * Some of the functions use this * * @access private * @param array * @param bool * @return string */ if ( ! function_exists('_parse_attributes')) { function _parse_attributes($attributes, $javascript = FALSE) { if (is_string($attributes)) { return ($attributes != '') ? ' '.$attributes : ''; } $att = ''; foreach ($attributes as $key => $val) { if ($javascript == TRUE) { $att .= $key . '=' . $val . ','; } else { $att .= ' ' . $key . '="' . $val . '"'; } } if ($javascript == TRUE AND $att != '') { $att = substr($att, 0, -1); } return $att; } } /* End of file url_helper.php */ /* Location: ./system/helpers/url_helper.php */
101-code
system/helpers/url_helper.php
PHP
gpl3
12,435
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // ------------------------------------------------------------------------ /** * CodeIgniter Language Helpers * * @package CodeIgniter * @subpackage Helpers * @category Helpers * @author ExpressionEngine Dev Team * @link http://codeigniter.com/user_guide/helpers/language_helper.html */ // ------------------------------------------------------------------------ /** * Lang * * Fetches a language variable and optionally outputs a form label * * @access public * @param string the language line * @param string the id of the form element * @return string */ if ( ! function_exists('lang')) { function lang($line, $id = '') { $CI =& get_instance(); $line = $CI->lang->line($line); if ($id != '') { $line = '<label for="'.$id.'">'.$line."</label>"; } return $line; } } // ------------------------------------------------------------------------ /* End of file language_helper.php */ /* Location: ./system/helpers/language_helper.php */
101-code
system/helpers/language_helper.php
PHP
gpl3
1,409
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // ------------------------------------------------------------------------ /** * CodeIgniter Typography Helpers * * @package CodeIgniter * @subpackage Helpers * @category Helpers * @author ExpressionEngine Dev Team * @link http://codeigniter.com/user_guide/helpers/typography_helper.html */ // ------------------------------------------------------------------------ /** * Convert newlines to HTML line breaks except within PRE tags * * @access public * @param string * @return string */ if ( ! function_exists('nl2br_except_pre')) { function nl2br_except_pre($str) { $CI =& get_instance(); $CI->load->library('typography'); return $CI->typography->nl2br_except_pre($str); } } // ------------------------------------------------------------------------ /** * Auto Typography Wrapper Function * * * @access public * @param string * @param bool whether to allow javascript event handlers * @param bool whether to reduce multiple instances of double newlines to two * @return string */ if ( ! function_exists('auto_typography')) { function auto_typography($str, $strip_js_event_handlers = TRUE, $reduce_linebreaks = FALSE) { $CI =& get_instance(); $CI->load->library('typography'); return $CI->typography->auto_typography($str, $strip_js_event_handlers, $reduce_linebreaks); } } // -------------------------------------------------------------------- /** * HTML Entities Decode * * This function is a replacement for html_entity_decode() * * @access public * @param string * @return string */ if ( ! function_exists('entity_decode')) { function entity_decode($str, $charset='UTF-8') { global $SEC; return $SEC->entity_decode($str, $charset); } } /* End of file typography_helper.php */ /* Location: ./system/helpers/typography_helper.php */
101-code
system/helpers/typography_helper.php
PHP
gpl3
2,239
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // ------------------------------------------------------------------------ /** * CodeIgniter Cookie Helpers * * @package CodeIgniter * @subpackage Helpers * @category Helpers * @author ExpressionEngine Dev Team * @link http://codeigniter.com/user_guide/helpers/cookie_helper.html */ // ------------------------------------------------------------------------ /** * Set cookie * * Accepts six parameter, or you can submit an associative * array in the first parameter containing all the values. * * @access public * @param mixed * @param string the value of the cookie * @param string the number of seconds until expiration * @param string the cookie domain. Usually: .yourdomain.com * @param string the cookie path * @param string the cookie prefix * @return void */ if ( ! function_exists('set_cookie')) { function set_cookie($name = '', $value = '', $expire = '', $domain = '', $path = '/', $prefix = '', $secure = FALSE) { // Set the config file options $CI =& get_instance(); $CI->input->set_cookie($name, $value, $expire, $domain, $path, $prefix, $secure); } } // -------------------------------------------------------------------- /** * Fetch an item from the COOKIE array * * @access public * @param string * @param bool * @return mixed */ if ( ! function_exists('get_cookie')) { function get_cookie($index = '', $xss_clean = FALSE) { $CI =& get_instance(); $prefix = ''; if ( ! isset($_COOKIE[$index]) && config_item('cookie_prefix') != '') { $prefix = config_item('cookie_prefix'); } return $CI->input->cookie($prefix.$index, $xss_clean); } } // -------------------------------------------------------------------- /** * Delete a COOKIE * * @param mixed * @param string the cookie domain. Usually: .yourdomain.com * @param string the cookie path * @param string the cookie prefix * @return void */ if ( ! function_exists('delete_cookie')) { function delete_cookie($name = '', $domain = '', $path = '/', $prefix = '') { set_cookie($name, '', '', $domain, $path, $prefix); } } /* End of file cookie_helper.php */ /* Location: ./system/helpers/cookie_helper.php */
101-code
system/helpers/cookie_helper.php
PHP
gpl3
2,591
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // ------------------------------------------------------------------------ /** * CodeIgniter String Helpers * * @package CodeIgniter * @subpackage Helpers * @category Helpers * @author ExpressionEngine Dev Team * @link http://codeigniter.com/user_guide/helpers/string_helper.html */ // ------------------------------------------------------------------------ /** * Trim Slashes * * Removes any leading/trailing slashes from a string: * * /this/that/theother/ * * becomes: * * this/that/theother * * @access public * @param string * @return string */ if ( ! function_exists('trim_slashes')) { function trim_slashes($str) { return trim($str, '/'); } } // ------------------------------------------------------------------------ /** * Strip Slashes * * Removes slashes contained in a string or in an array * * @access public * @param mixed string or array * @return mixed string or array */ if ( ! function_exists('strip_slashes')) { function strip_slashes($str) { if (is_array($str)) { foreach ($str as $key => $val) { $str[$key] = strip_slashes($val); } } else { $str = stripslashes($str); } return $str; } } // ------------------------------------------------------------------------ /** * Strip Quotes * * Removes single and double quotes from a string * * @access public * @param string * @return string */ if ( ! function_exists('strip_quotes')) { function strip_quotes($str) { return str_replace(array('"', "'"), '', $str); } } // ------------------------------------------------------------------------ /** * Quotes to Entities * * Converts single and double quotes to entities * * @access public * @param string * @return string */ if ( ! function_exists('quotes_to_entities')) { function quotes_to_entities($str) { return str_replace(array("\'","\"","'",'"'), array("&#39;","&quot;","&#39;","&quot;"), $str); } } // ------------------------------------------------------------------------ /** * Reduce Double Slashes * * Converts double slashes in a string to a single slash, * except those found in http:// * * http://www.some-site.com//index.php * * becomes: * * http://www.some-site.com/index.php * * @access public * @param string * @return string */ if ( ! function_exists('reduce_double_slashes')) { function reduce_double_slashes($str) { return preg_replace("#(^|[^:])//+#", "\\1/", $str); } } // ------------------------------------------------------------------------ /** * Reduce Multiples * * Reduces multiple instances of a particular character. Example: * * Fred, Bill,, Joe, Jimmy * * becomes: * * Fred, Bill, Joe, Jimmy * * @access public * @param string * @param string the character you wish to reduce * @param bool TRUE/FALSE - whether to trim the character from the beginning/end * @return string */ if ( ! function_exists('reduce_multiples')) { function reduce_multiples($str, $character = ',', $trim = FALSE) { $str = preg_replace('#'.preg_quote($character, '#').'{2,}#', $character, $str); if ($trim === TRUE) { $str = trim($str, $character); } return $str; } } // ------------------------------------------------------------------------ /** * Create a Random String * * Useful for generating passwords or hashes. * * @access public * @param string type of random string. basic, alpha, alunum, numeric, nozero, unique, md5, encrypt and sha1 * @param integer number of characters * @return string */ if ( ! function_exists('random_string')) { function random_string($type = 'alnum', $len = 8) { switch($type) { case 'basic' : return mt_rand(); break; case 'alnum' : case 'numeric' : case 'nozero' : case 'alpha' : switch ($type) { case 'alpha' : $pool = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; break; case 'alnum' : $pool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; break; case 'numeric' : $pool = '0123456789'; break; case 'nozero' : $pool = '123456789'; break; } $str = ''; for ($i=0; $i < $len; $i++) { $str .= substr($pool, mt_rand(0, strlen($pool) -1), 1); } return $str; break; case 'unique' : case 'md5' : return md5(uniqid(mt_rand())); break; case 'encrypt' : case 'sha1' : $CI =& get_instance(); $CI->load->helper('security'); return do_hash(uniqid(mt_rand(), TRUE), 'sha1'); break; } } } // ------------------------------------------------------------------------ /** * Add's _1 to a string or increment the ending number to allow _2, _3, etc * * @param string $str required * @param string $separator What should the duplicate number be appended with * @param string $first Which number should be used for the first dupe increment * @return string */ function increment_string($str, $separator = '_', $first = 1) { preg_match('/(.+)'.$separator.'([0-9]+)$/', $str, $match); return isset($match[2]) ? $match[1].$separator.($match[2] + 1) : $str.$separator.$first; } // ------------------------------------------------------------------------ /** * Alternator * * Allows strings to be alternated. See docs... * * @access public * @param string (as many parameters as needed) * @return string */ if ( ! function_exists('alternator')) { function alternator() { static $i; if (func_num_args() == 0) { $i = 0; return ''; } $args = func_get_args(); return $args[($i++ % count($args))]; } } // ------------------------------------------------------------------------ /** * Repeater function * * @access public * @param string * @param integer number of repeats * @return string */ if ( ! function_exists('repeater')) { function repeater($data, $num = 1) { return (($num > 0) ? str_repeat($data, $num) : ''); } } /* End of file string_helper.php */ /* Location: ./system/helpers/string_helper.php */
101-code
system/helpers/string_helper.php
PHP
gpl3
6,433
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // ------------------------------------------------------------------------ /** * CodeIgniter Inflector Helpers * * @package CodeIgniter * @subpackage Helpers * @category Helpers * @author ExpressionEngine Dev Team * @link http://codeigniter.com/user_guide/helpers/directory_helper.html */ // -------------------------------------------------------------------- /** * Singular * * Takes a plural word and makes it singular * * @access public * @param string * @return str */ if ( ! function_exists('singular')) { function singular($str) { $result = strval($str); $singular_rules = array( '/(matr)ices$/' => '\1ix', '/(vert|ind)ices$/' => '\1ex', '/^(ox)en/' => '\1', '/(alias)es$/' => '\1', '/([octop|vir])i$/' => '\1us', '/(cris|ax|test)es$/' => '\1is', '/(shoe)s$/' => '\1', '/(o)es$/' => '\1', '/(bus|campus)es$/' => '\1', '/([m|l])ice$/' => '\1ouse', '/(x|ch|ss|sh)es$/' => '\1', '/(m)ovies$/' => '\1\2ovie', '/(s)eries$/' => '\1\2eries', '/([^aeiouy]|qu)ies$/' => '\1y', '/([lr])ves$/' => '\1f', '/(tive)s$/' => '\1', '/(hive)s$/' => '\1', '/([^f])ves$/' => '\1fe', '/(^analy)ses$/' => '\1sis', '/((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)ses$/' => '\1\2sis', '/([ti])a$/' => '\1um', '/(p)eople$/' => '\1\2erson', '/(m)en$/' => '\1an', '/(s)tatuses$/' => '\1\2tatus', '/(c)hildren$/' => '\1\2hild', '/(n)ews$/' => '\1\2ews', '/([^u])s$/' => '\1', ); foreach ($singular_rules as $rule => $replacement) { if (preg_match($rule, $result)) { $result = preg_replace($rule, $replacement, $result); break; } } return $result; } } // -------------------------------------------------------------------- /** * Plural * * Takes a singular word and makes it plural * * @access public * @param string * @param bool * @return str */ if ( ! function_exists('plural')) { function plural($str, $force = FALSE) { $result = strval($str); $plural_rules = array( '/^(ox)$/' => '\1\2en', // ox '/([m|l])ouse$/' => '\1ice', // mouse, louse '/(matr|vert|ind)ix|ex$/' => '\1ices', // matrix, vertex, index '/(x|ch|ss|sh)$/' => '\1es', // search, switch, fix, box, process, address '/([^aeiouy]|qu)y$/' => '\1ies', // query, ability, agency '/(hive)$/' => '\1s', // archive, hive '/(?:([^f])fe|([lr])f)$/' => '\1\2ves', // half, safe, wife '/sis$/' => 'ses', // basis, diagnosis '/([ti])um$/' => '\1a', // datum, medium '/(p)erson$/' => '\1eople', // person, salesperson '/(m)an$/' => '\1en', // man, woman, spokesman '/(c)hild$/' => '\1hildren', // child '/(buffal|tomat)o$/' => '\1\2oes', // buffalo, tomato '/(bu|campu)s$/' => '\1\2ses', // bus, campus '/(alias|status|virus)/' => '\1es', // alias '/(octop)us$/' => '\1i', // octopus '/(ax|cris|test)is$/' => '\1es', // axis, crisis '/s$/' => 's', // no change (compatibility) '/$/' => 's', ); foreach ($plural_rules as $rule => $replacement) { if (preg_match($rule, $result)) { $result = preg_replace($rule, $replacement, $result); break; } } return $result; } } // -------------------------------------------------------------------- /** * Camelize * * Takes multiple words separated by spaces or underscores and camelizes them * * @access public * @param string * @return str */ if ( ! function_exists('camelize')) { function camelize($str) { $str = 'x'.strtolower(trim($str)); $str = ucwords(preg_replace('/[\s_]+/', ' ', $str)); return substr(str_replace(' ', '', $str), 1); } } // -------------------------------------------------------------------- /** * Underscore * * Takes multiple words separated by spaces and underscores them * * @access public * @param string * @return str */ if ( ! function_exists('underscore')) { function underscore($str) { return preg_replace('/[\s]+/', '_', strtolower(trim($str))); } } // -------------------------------------------------------------------- /** * Humanize * * Takes multiple words separated by underscores and changes them to spaces * * @access public * @param string * @return str */ if ( ! function_exists('humanize')) { function humanize($str) { return ucwords(preg_replace('/[_]+/', ' ', strtolower(trim($str)))); } } /* End of file inflector_helper.php */ /* Location: ./system/helpers/inflector_helper.php */
101-code
system/helpers/inflector_helper.php
PHP
gpl3
5,367
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // ------------------------------------------------------------------------ /** * CodeIgniter Security Helpers * * @package CodeIgniter * @subpackage Helpers * @category Helpers * @author ExpressionEngine Dev Team * @link http://codeigniter.com/user_guide/helpers/security_helper.html */ // ------------------------------------------------------------------------ /** * XSS Filtering * * @access public * @param string * @param bool whether or not the content is an image file * @return string */ if ( ! function_exists('xss_clean')) { function xss_clean($str, $is_image = FALSE) { $CI =& get_instance(); return $CI->security->xss_clean($str, $is_image); } } // ------------------------------------------------------------------------ /** * Sanitize Filename * * @access public * @param string * @return string */ if ( ! function_exists('sanitize_filename')) { function sanitize_filename($filename) { $CI =& get_instance(); return $CI->security->sanitize_filename($filename); } } // -------------------------------------------------------------------- /** * Hash encode a string * * @access public * @param string * @return string */ if ( ! function_exists('do_hash')) { function do_hash($str, $type = 'sha1') { if ($type == 'sha1') { return sha1($str); } else { return md5($str); } } } // ------------------------------------------------------------------------ /** * Strip Image Tags * * @access public * @param string * @return string */ if ( ! function_exists('strip_image_tags')) { function strip_image_tags($str) { $str = preg_replace("#<img\s+.*?src\s*=\s*[\"'](.+?)[\"'].*?\>#", "\\1", $str); $str = preg_replace("#<img\s+.*?src\s*=\s*(.+?).*?\>#", "\\1", $str); return $str; } } // ------------------------------------------------------------------------ /** * Convert PHP tags to entities * * @access public * @param string * @return string */ if ( ! function_exists('encode_php_tags')) { function encode_php_tags($str) { return str_replace(array('<?php', '<?PHP', '<?', '?>'), array('&lt;?php', '&lt;?PHP', '&lt;?', '?&gt;'), $str); } } /* End of file security_helper.php */ /* Location: ./system/helpers/security_helper.php */
101-code
system/helpers/security_helper.php
PHP
gpl3
2,675
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // ------------------------------------------------------------------------ /** * CodeIgniter Form Helpers * * @package CodeIgniter * @subpackage Helpers * @category Helpers * @author ExpressionEngine Dev Team * @link http://codeigniter.com/user_guide/helpers/form_helper.html */ // ------------------------------------------------------------------------ /** * Form Declaration * * Creates the opening portion of the form. * * @access public * @param string the URI segments of the form destination * @param array a key/value pair of attributes * @param array a key/value pair hidden data * @return string */ if ( ! function_exists('form_open')) { function form_open($action = '', $attributes = '', $hidden = array()) { $CI =& get_instance(); if ($attributes == '') { $attributes = 'method="post"'; } // If an action is not a full URL then turn it into one if ($action && strpos($action, '://') === FALSE) { $action = $CI->config->site_url($action); } // If no action is provided then set to the current url $action OR $action = $CI->config->site_url($CI->uri->uri_string()); $form = '<form action="'.$action.'"'; $form .= _attributes_to_string($attributes, TRUE); $form .= '>'; // Add CSRF field if enabled, but leave it out for GET requests and requests to external websites if ($CI->config->item('csrf_protection') === TRUE AND ! (strpos($action, $CI->config->site_url()) === FALSE OR strpos($form, 'method="get"'))) { $hidden[$CI->security->get_csrf_token_name()] = $CI->security->get_csrf_hash(); } if (is_array($hidden) AND count($hidden) > 0) { $form .= sprintf("<div style=\"display:none\">%s</div>", form_hidden($hidden)); } return $form; } } // ------------------------------------------------------------------------ /** * Form Declaration - Multipart type * * Creates the opening portion of the form, but with "multipart/form-data". * * @access public * @param string the URI segments of the form destination * @param array a key/value pair of attributes * @param array a key/value pair hidden data * @return string */ if ( ! function_exists('form_open_multipart')) { function form_open_multipart($action = '', $attributes = array(), $hidden = array()) { if (is_string($attributes)) { $attributes .= ' enctype="multipart/form-data"'; } else { $attributes['enctype'] = 'multipart/form-data'; } return form_open($action, $attributes, $hidden); } } // ------------------------------------------------------------------------ /** * Hidden Input Field * * Generates hidden fields. You can pass a simple key/value string or an associative * array with multiple values. * * @access public * @param mixed * @param string * @return string */ if ( ! function_exists('form_hidden')) { function form_hidden($name, $value = '', $recursing = FALSE) { static $form; if ($recursing === FALSE) { $form = "\n"; } if (is_array($name)) { foreach ($name as $key => $val) { form_hidden($key, $val, TRUE); } return $form; } if ( ! is_array($value)) { $form .= '<input type="hidden" name="'.$name.'" value="'.form_prep($value, $name).'" />'."\n"; } else { foreach ($value as $k => $v) { $k = (is_int($k)) ? '' : $k; form_hidden($name.'['.$k.']', $v, TRUE); } } return $form; } } // ------------------------------------------------------------------------ /** * Text Input Field * * @access public * @param mixed * @param string * @param string * @return string */ if ( ! function_exists('form_input')) { function form_input($data = '', $value = '', $extra = '') { $defaults = array('type' => 'text', 'name' => (( ! is_array($data)) ? $data : ''), 'value' => $value); return "<input "._parse_form_attributes($data, $defaults).$extra." />"; } } // ------------------------------------------------------------------------ /** * Password Field * * Identical to the input function but adds the "password" type * * @access public * @param mixed * @param string * @param string * @return string */ if ( ! function_exists('form_password')) { function form_password($data = '', $value = '', $extra = '') { if ( ! is_array($data)) { $data = array('name' => $data); } $data['type'] = 'password'; return form_input($data, $value, $extra); } } // ------------------------------------------------------------------------ /** * Upload Field * * Identical to the input function but adds the "file" type * * @access public * @param mixed * @param string * @param string * @return string */ if ( ! function_exists('form_upload')) { function form_upload($data = '', $value = '', $extra = '') { if ( ! is_array($data)) { $data = array('name' => $data); } $data['type'] = 'file'; return form_input($data, $value, $extra); } } // ------------------------------------------------------------------------ /** * Textarea field * * @access public * @param mixed * @param string * @param string * @return string */ if ( ! function_exists('form_textarea')) { function form_textarea($data = '', $value = '', $extra = '') { $defaults = array('name' => (( ! is_array($data)) ? $data : ''), 'cols' => '40', 'rows' => '10'); if ( ! is_array($data) OR ! isset($data['value'])) { $val = $value; } else { $val = $data['value']; unset($data['value']); // textareas don't use the value attribute } $name = (is_array($data)) ? $data['name'] : $data; return "<textarea "._parse_form_attributes($data, $defaults).$extra.">".form_prep($val, $name)."</textarea>"; } } // ------------------------------------------------------------------------ /** * Multi-select menu * * @access public * @param string * @param array * @param mixed * @param string * @return type */ if ( ! function_exists('form_multiselect')) { function form_multiselect($name = '', $options = array(), $selected = array(), $extra = '') { if ( ! strpos($extra, 'multiple')) { $extra .= ' multiple="multiple"'; } return form_dropdown($name, $options, $selected, $extra); } } // -------------------------------------------------------------------- /** * Drop-down Menu * * @access public * @param string * @param array * @param string * @param string * @return string */ if ( ! function_exists('form_dropdown')) { function form_dropdown($name = '', $options = array(), $selected = array(), $extra = '') { if ( ! is_array($selected)) { $selected = array($selected); } // If no selected state was submitted we will attempt to set it automatically if (count($selected) === 0) { // If the form name appears in the $_POST array we have a winner! if (isset($_POST[$name])) { $selected = array($_POST[$name]); } } if ($extra != '') $extra = ' '.$extra; $multiple = (count($selected) > 1 && strpos($extra, 'multiple') === FALSE) ? ' multiple="multiple"' : ''; $form = '<select name="'.$name.'"'.$extra.$multiple.">\n"; foreach ($options as $key => $val) { $key = (string) $key; if (is_array($val) && ! empty($val)) { $form .= '<optgroup label="'.$key.'">'."\n"; foreach ($val as $optgroup_key => $optgroup_val) { $sel = (in_array($optgroup_key, $selected)) ? ' selected="selected"' : ''; $form .= '<option value="'.$optgroup_key.'"'.$sel.'>'.(string) $optgroup_val."</option>\n"; } $form .= '</optgroup>'."\n"; } else { $sel = (in_array($key, $selected)) ? ' selected="selected"' : ''; $form .= '<option value="'.$key.'"'.$sel.'>'.(string) $val."</option>\n"; } } $form .= '</select>'; return $form; } } // ------------------------------------------------------------------------ /** * Checkbox Field * * @access public * @param mixed * @param string * @param bool * @param string * @return string */ if ( ! function_exists('form_checkbox')) { function form_checkbox($data = '', $value = '', $checked = FALSE, $extra = '') { $defaults = array('type' => 'checkbox', 'name' => (( ! is_array($data)) ? $data : ''), 'value' => $value); if (is_array($data) AND array_key_exists('checked', $data)) { $checked = $data['checked']; if ($checked == FALSE) { unset($data['checked']); } else { $data['checked'] = 'checked'; } } if ($checked == TRUE) { $defaults['checked'] = 'checked'; } else { unset($defaults['checked']); } return "<input "._parse_form_attributes($data, $defaults).$extra." />"; } } // ------------------------------------------------------------------------ /** * Radio Button * * @access public * @param mixed * @param string * @param bool * @param string * @return string */ if ( ! function_exists('form_radio')) { function form_radio($data = '', $value = '', $checked = FALSE, $extra = '') { if ( ! is_array($data)) { $data = array('name' => $data); } $data['type'] = 'radio'; return form_checkbox($data, $value, $checked, $extra); } } // ------------------------------------------------------------------------ /** * Submit Button * * @access public * @param mixed * @param string * @param string * @return string */ if ( ! function_exists('form_submit')) { function form_submit($data = '', $value = '', $extra = '') { $defaults = array('type' => 'submit', 'name' => (( ! is_array($data)) ? $data : ''), 'value' => $value); return "<input "._parse_form_attributes($data, $defaults).$extra." />"; } } // ------------------------------------------------------------------------ /** * Reset Button * * @access public * @param mixed * @param string * @param string * @return string */ if ( ! function_exists('form_reset')) { function form_reset($data = '', $value = '', $extra = '') { $defaults = array('type' => 'reset', 'name' => (( ! is_array($data)) ? $data : ''), 'value' => $value); return "<input "._parse_form_attributes($data, $defaults).$extra." />"; } } // ------------------------------------------------------------------------ /** * Form Button * * @access public * @param mixed * @param string * @param string * @return string */ if ( ! function_exists('form_button')) { function form_button($data = '', $content = '', $extra = '') { $defaults = array('name' => (( ! is_array($data)) ? $data : ''), 'type' => 'button'); if ( is_array($data) AND isset($data['content'])) { $content = $data['content']; unset($data['content']); // content is not an attribute } return "<button "._parse_form_attributes($data, $defaults).$extra.">".$content."</button>"; } } // ------------------------------------------------------------------------ /** * Form Label Tag * * @access public * @param string The text to appear onscreen * @param string The id the label applies to * @param string Additional attributes * @return string */ if ( ! function_exists('form_label')) { function form_label($label_text = '', $id = '', $attributes = array()) { $label = '<label'; if ($id != '') { $label .= " for=\"$id\""; } if (is_array($attributes) AND count($attributes) > 0) { foreach ($attributes as $key => $val) { $label .= ' '.$key.'="'.$val.'"'; } } $label .= ">$label_text</label>"; return $label; } } // ------------------------------------------------------------------------ /** * Fieldset Tag * * Used to produce <fieldset><legend>text</legend>. To close fieldset * use form_fieldset_close() * * @access public * @param string The legend text * @param string Additional attributes * @return string */ if ( ! function_exists('form_fieldset')) { function form_fieldset($legend_text = '', $attributes = array()) { $fieldset = "<fieldset"; $fieldset .= _attributes_to_string($attributes, FALSE); $fieldset .= ">\n"; if ($legend_text != '') { $fieldset .= "<legend>$legend_text</legend>\n"; } return $fieldset; } } // ------------------------------------------------------------------------ /** * Fieldset Close Tag * * @access public * @param string * @return string */ if ( ! function_exists('form_fieldset_close')) { function form_fieldset_close($extra = '') { return "</fieldset>".$extra; } } // ------------------------------------------------------------------------ /** * Form Close Tag * * @access public * @param string * @return string */ if ( ! function_exists('form_close')) { function form_close($extra = '') { return "</form>".$extra; } } // ------------------------------------------------------------------------ /** * Form Prep * * Formats text so that it can be safely placed in a form field in the event it has HTML tags. * * @access public * @param string * @return string */ if ( ! function_exists('form_prep')) { function form_prep($str = '', $field_name = '') { static $prepped_fields = array(); // if the field name is an array we do this recursively if (is_array($str)) { foreach ($str as $key => $val) { $str[$key] = form_prep($val); } return $str; } if ($str === '') { return ''; } // we've already prepped a field with this name // @todo need to figure out a way to namespace this so // that we know the *exact* field and not just one with // the same name if (isset($prepped_fields[$field_name])) { return $str; } $str = htmlspecialchars($str); // In case htmlspecialchars misses these. $str = str_replace(array("'", '"'), array("&#39;", "&quot;"), $str); if ($field_name != '') { $prepped_fields[$field_name] = $field_name; } return $str; } } // ------------------------------------------------------------------------ /** * Form Value * * Grabs a value from the POST array for the specified field so you can * re-populate an input field or textarea. If Form Validation * is active it retrieves the info from the validation class * * @access public * @param string * @return mixed */ if ( ! function_exists('set_value')) { function set_value($field = '', $default = '') { if (FALSE === ($OBJ =& _get_validation_object())) { if ( ! isset($_POST[$field])) { return $default; } return form_prep($_POST[$field], $field); } return form_prep($OBJ->set_value($field, $default), $field); } } // ------------------------------------------------------------------------ /** * Set Select * * Let's you set the selected value of a <select> menu via data in the POST array. * If Form Validation is active it retrieves the info from the validation class * * @access public * @param string * @param string * @param bool * @return string */ if ( ! function_exists('set_select')) { function set_select($field = '', $value = '', $default = FALSE) { $OBJ =& _get_validation_object(); if ($OBJ === FALSE) { if ( ! isset($_POST[$field])) { if (count($_POST) === 0 AND $default == TRUE) { return ' selected="selected"'; } return ''; } $field = $_POST[$field]; if (is_array($field)) { if ( ! in_array($value, $field)) { return ''; } } else { if (($field == '' OR $value == '') OR ($field != $value)) { return ''; } } return ' selected="selected"'; } return $OBJ->set_select($field, $value, $default); } } // ------------------------------------------------------------------------ /** * Set Checkbox * * Let's you set the selected value of a checkbox via the value in the POST array. * If Form Validation is active it retrieves the info from the validation class * * @access public * @param string * @param string * @param bool * @return string */ if ( ! function_exists('set_checkbox')) { function set_checkbox($field = '', $value = '', $default = FALSE) { $OBJ =& _get_validation_object(); if ($OBJ === FALSE) { if ( ! isset($_POST[$field])) { if (count($_POST) === 0 AND $default == TRUE) { return ' checked="checked"'; } return ''; } $field = $_POST[$field]; if (is_array($field)) { if ( ! in_array($value, $field)) { return ''; } } else { if (($field == '' OR $value == '') OR ($field != $value)) { return ''; } } return ' checked="checked"'; } return $OBJ->set_checkbox($field, $value, $default); } } // ------------------------------------------------------------------------ /** * Set Radio * * Let's you set the selected value of a radio field via info in the POST array. * If Form Validation is active it retrieves the info from the validation class * * @access public * @param string * @param string * @param bool * @return string */ if ( ! function_exists('set_radio')) { function set_radio($field = '', $value = '', $default = FALSE) { $OBJ =& _get_validation_object(); if ($OBJ === FALSE) { if ( ! isset($_POST[$field])) { if (count($_POST) === 0 AND $default == TRUE) { return ' checked="checked"'; } return ''; } $field = $_POST[$field]; if (is_array($field)) { if ( ! in_array($value, $field)) { return ''; } } else { if (($field == '' OR $value == '') OR ($field != $value)) { return ''; } } return ' checked="checked"'; } return $OBJ->set_radio($field, $value, $default); } } // ------------------------------------------------------------------------ /** * Form Error * * Returns the error for a specific form field. This is a helper for the * form validation class. * * @access public * @param string * @param string * @param string * @return string */ if ( ! function_exists('form_error')) { function form_error($field = '', $prefix = '', $suffix = '') { if (FALSE === ($OBJ =& _get_validation_object())) { return ''; } return $OBJ->error($field, $prefix, $suffix); } } // ------------------------------------------------------------------------ /** * Validation Error String * * Returns all the errors associated with a form submission. This is a helper * function for the form validation class. * * @access public * @param string * @param string * @return string */ if ( ! function_exists('validation_errors')) { function validation_errors($prefix = '', $suffix = '') { if (FALSE === ($OBJ =& _get_validation_object())) { return ''; } return $OBJ->error_string($prefix, $suffix); } } // ------------------------------------------------------------------------ /** * Parse the form attributes * * Helper function used by some of the form helpers * * @access private * @param array * @param array * @return string */ if ( ! function_exists('_parse_form_attributes')) { function _parse_form_attributes($attributes, $default) { if (is_array($attributes)) { foreach ($default as $key => $val) { if (isset($attributes[$key])) { $default[$key] = $attributes[$key]; unset($attributes[$key]); } } if (count($attributes) > 0) { $default = array_merge($default, $attributes); } } $att = ''; foreach ($default as $key => $val) { if ($key == 'value') { $val = form_prep($val, $default['name']); } $att .= $key . '="' . $val . '" '; } return $att; } } // ------------------------------------------------------------------------ /** * Attributes To String * * Helper function used by some of the form helpers * * @access private * @param mixed * @param bool * @return string */ if ( ! function_exists('_attributes_to_string')) { function _attributes_to_string($attributes, $formtag = FALSE) { if (is_string($attributes) AND strlen($attributes) > 0) { if ($formtag == TRUE AND strpos($attributes, 'method=') === FALSE) { $attributes .= ' method="post"'; } if ($formtag == TRUE AND strpos($attributes, 'accept-charset=') === FALSE) { $attributes .= ' accept-charset="'.strtolower(config_item('charset')).'"'; } return ' '.$attributes; } if (is_object($attributes) AND count($attributes) > 0) { $attributes = (array)$attributes; } if (is_array($attributes) AND count($attributes) > 0) { $atts = ''; if ( ! isset($attributes['method']) AND $formtag === TRUE) { $atts .= ' method="post"'; } if ( ! isset($attributes['accept-charset']) AND $formtag === TRUE) { $atts .= ' accept-charset="'.strtolower(config_item('charset')).'"'; } foreach ($attributes as $key => $val) { $atts .= ' '.$key.'="'.$val.'"'; } return $atts; } } } // ------------------------------------------------------------------------ /** * Validation Object * * Determines what the form validation class was instantiated as, fetches * the object and returns it. * * @access private * @return mixed */ if ( ! function_exists('_get_validation_object')) { function &_get_validation_object() { $CI =& get_instance(); // We set this as a variable since we're returning by reference. $return = FALSE; if (FALSE !== ($object = $CI->load->is_loaded('form_validation'))) { if ( ! isset($CI->$object) OR ! is_object($CI->$object)) { return $return; } return $CI->$object; } return $return; } } /* End of file form_helper.php */ /* Location: ./system/helpers/form_helper.php */
101-code
system/helpers/form_helper.php
PHP
gpl3
21,772
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // ------------------------------------------------------------------------ /** * CodeIgniter CAPTCHA Helper * * @package CodeIgniter * @subpackage Helpers * @category Helpers * @author ExpressionEngine Dev Team * @link http://codeigniter.com/user_guide/helpers/xml_helper.html */ // ------------------------------------------------------------------------ /** * Create CAPTCHA * * @access public * @param array array of data for the CAPTCHA * @param string path to create the image in * @param string URL to the CAPTCHA image folder * @param string server path to font * @return string */ if ( ! function_exists('create_captcha')) { function create_captcha($data = '', $img_path = '', $img_url = '', $font_path = '') { $defaults = array('word' => '', 'img_path' => '', 'img_url' => '', 'img_width' => '150', 'img_height' => '30', 'font_path' => '', 'expiration' => 7200); foreach ($defaults as $key => $val) { if ( ! is_array($data)) { if ( ! isset($$key) OR $$key == '') { $$key = $val; } } else { $$key = ( ! isset($data[$key])) ? $val : $data[$key]; } } if ($img_path == '' OR $img_url == '') { return FALSE; } if ( ! @is_dir($img_path)) { return FALSE; } if ( ! is_writable($img_path)) { return FALSE; } if ( ! extension_loaded('gd')) { return FALSE; } // ----------------------------------- // Remove old images // ----------------------------------- list($usec, $sec) = explode(" ", microtime()); $now = ((float)$usec + (float)$sec); $current_dir = @opendir($img_path); while ($filename = @readdir($current_dir)) { if ($filename != "." and $filename != ".." and $filename != "index.html") { $name = str_replace(".jpg", "", $filename); if (($name + $expiration) < $now) { @unlink($img_path.$filename); } } } @closedir($current_dir); // ----------------------------------- // Do we have a "word" yet? // ----------------------------------- if ($word == '') { $pool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; $str = ''; for ($i = 0; $i < 8; $i++) { $str .= substr($pool, mt_rand(0, strlen($pool) -1), 1); } $word = $str; } // ----------------------------------- // Determine angle and position // ----------------------------------- $length = strlen($word); $angle = ($length >= 6) ? rand(-($length-6), ($length-6)) : 0; $x_axis = rand(6, (360/$length)-16); $y_axis = ($angle >= 0 ) ? rand($img_height, $img_width) : rand(6, $img_height); // ----------------------------------- // Create image // ----------------------------------- // PHP.net recommends imagecreatetruecolor(), but it isn't always available if (function_exists('imagecreatetruecolor')) { $im = imagecreatetruecolor($img_width, $img_height); } else { $im = imagecreate($img_width, $img_height); } // ----------------------------------- // Assign colors // ----------------------------------- $bg_color = imagecolorallocate ($im, 255, 255, 255); $border_color = imagecolorallocate ($im, 153, 102, 102); $text_color = imagecolorallocate ($im, 204, 153, 153); $grid_color = imagecolorallocate($im, 255, 182, 182); $shadow_color = imagecolorallocate($im, 255, 240, 240); // ----------------------------------- // Create the rectangle // ----------------------------------- ImageFilledRectangle($im, 0, 0, $img_width, $img_height, $bg_color); // ----------------------------------- // Create the spiral pattern // ----------------------------------- $theta = 1; $thetac = 7; $radius = 16; $circles = 20; $points = 32; for ($i = 0; $i < ($circles * $points) - 1; $i++) { $theta = $theta + $thetac; $rad = $radius * ($i / $points ); $x = ($rad * cos($theta)) + $x_axis; $y = ($rad * sin($theta)) + $y_axis; $theta = $theta + $thetac; $rad1 = $radius * (($i + 1) / $points); $x1 = ($rad1 * cos($theta)) + $x_axis; $y1 = ($rad1 * sin($theta )) + $y_axis; imageline($im, $x, $y, $x1, $y1, $grid_color); $theta = $theta - $thetac; } // ----------------------------------- // Write the text // ----------------------------------- $use_font = ($font_path != '' AND file_exists($font_path) AND function_exists('imagettftext')) ? TRUE : FALSE; if ($use_font == FALSE) { $font_size = 5; $x = rand(0, $img_width/($length/3)); $y = 0; } else { $font_size = 16; $x = rand(0, $img_width/($length/1.5)); $y = $font_size+2; } for ($i = 0; $i < strlen($word); $i++) { if ($use_font == FALSE) { $y = rand(0 , $img_height/2); imagestring($im, $font_size, $x, $y, substr($word, $i, 1), $text_color); $x += ($font_size*2); } else { $y = rand($img_height/2, $img_height-3); imagettftext($im, $font_size, $angle, $x, $y, $text_color, $font_path, substr($word, $i, 1)); $x += $font_size; } } // ----------------------------------- // Create the border // ----------------------------------- imagerectangle($im, 0, 0, $img_width-1, $img_height-1, $border_color); // ----------------------------------- // Generate the image // ----------------------------------- $img_name = $now.'.jpg'; ImageJPEG($im, $img_path.$img_name); $img = "<img src=\"$img_url$img_name\" width=\"$img_width\" height=\"$img_height\" style=\"border:0;\" alt=\" \" />"; ImageDestroy($im); return array('word' => $word, 'time' => $now, 'image' => $img); } } // ------------------------------------------------------------------------ /* End of file captcha_helper.php */ /* Location: ./system/heleprs/captcha_helper.php */
101-code
system/helpers/captcha_helper.php
PHP
gpl3
6,169
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // ------------------------------------------------------------------------ /** * CodeIgniter Text Helpers * * @package CodeIgniter * @subpackage Helpers * @category Helpers * @author ExpressionEngine Dev Team * @link http://codeigniter.com/user_guide/helpers/text_helper.html */ // ------------------------------------------------------------------------ /** * Word Limiter * * Limits a string to X number of words. * * @access public * @param string * @param integer * @param string the end character. Usually an ellipsis * @return string */ if ( ! function_exists('word_limiter')) { function word_limiter($str, $limit = 100, $end_char = '&#8230;') { if (trim($str) == '') { return $str; } preg_match('/^\s*+(?:\S++\s*+){1,'.(int) $limit.'}/', $str, $matches); if (strlen($str) == strlen($matches[0])) { $end_char = ''; } return rtrim($matches[0]).$end_char; } } // ------------------------------------------------------------------------ /** * Character Limiter * * Limits the string based on the character count. Preserves complete words * so the character count may not be exactly as specified. * * @access public * @param string * @param integer * @param string the end character. Usually an ellipsis * @return string */ if ( ! function_exists('character_limiter')) { function character_limiter($str, $n = 500, $end_char = '&#8230;') { if (strlen($str) < $n) { return $str; } $str = preg_replace("/\s+/", ' ', str_replace(array("\r\n", "\r", "\n"), ' ', $str)); if (strlen($str) <= $n) { return $str; } $out = ""; foreach (explode(' ', trim($str)) as $val) { $out .= $val.' '; if (strlen($out) >= $n) { $out = trim($out); return (strlen($out) == strlen($str)) ? $out : $out.$end_char; } } } } // ------------------------------------------------------------------------ /** * High ASCII to Entities * * Converts High ascii text and MS Word special characters to character entities * * @access public * @param string * @return string */ if ( ! function_exists('ascii_to_entities')) { function ascii_to_entities($str) { $count = 1; $out = ''; $temp = array(); for ($i = 0, $s = strlen($str); $i < $s; $i++) { $ordinal = ord($str[$i]); if ($ordinal < 128) { /* If the $temp array has a value but we have moved on, then it seems only fair that we output that entity and restart $temp before continuing. -Paul */ if (count($temp) == 1) { $out .= '&#'.array_shift($temp).';'; $count = 1; } $out .= $str[$i]; } else { if (count($temp) == 0) { $count = ($ordinal < 224) ? 2 : 3; } $temp[] = $ordinal; if (count($temp) == $count) { $number = ($count == 3) ? (($temp['0'] % 16) * 4096) + (($temp['1'] % 64) * 64) + ($temp['2'] % 64) : (($temp['0'] % 32) * 64) + ($temp['1'] % 64); $out .= '&#'.$number.';'; $count = 1; $temp = array(); } } } return $out; } } // ------------------------------------------------------------------------ /** * Entities to ASCII * * Converts character entities back to ASCII * * @access public * @param string * @param bool * @return string */ if ( ! function_exists('entities_to_ascii')) { function entities_to_ascii($str, $all = TRUE) { if (preg_match_all('/\&#(\d+)\;/', $str, $matches)) { for ($i = 0, $s = count($matches['0']); $i < $s; $i++) { $digits = $matches['1'][$i]; $out = ''; if ($digits < 128) { $out .= chr($digits); } elseif ($digits < 2048) { $out .= chr(192 + (($digits - ($digits % 64)) / 64)); $out .= chr(128 + ($digits % 64)); } else { $out .= chr(224 + (($digits - ($digits % 4096)) / 4096)); $out .= chr(128 + ((($digits % 4096) - ($digits % 64)) / 64)); $out .= chr(128 + ($digits % 64)); } $str = str_replace($matches['0'][$i], $out, $str); } } if ($all) { $str = str_replace(array("&amp;", "&lt;", "&gt;", "&quot;", "&apos;", "&#45;"), array("&","<",">","\"", "'", "-"), $str); } return $str; } } // ------------------------------------------------------------------------ /** * Word Censoring Function * * Supply a string and an array of disallowed words and any * matched words will be converted to #### or to the replacement * word you've submitted. * * @access public * @param string the text string * @param string the array of censoered words * @param string the optional replacement value * @return string */ if ( ! function_exists('word_censor')) { function word_censor($str, $censored, $replacement = '') { if ( ! is_array($censored)) { return $str; } $str = ' '.$str.' '; // \w, \b and a few others do not match on a unicode character // set for performance reasons. As a result words like über // will not match on a word boundary. Instead, we'll assume that // a bad word will be bookeneded by any of these characters. $delim = '[-_\'\"`(){}<>\[\]|!?@#%&,.:;^~*+=\/ 0-9\n\r\t]'; foreach ($censored as $badword) { if ($replacement != '') { $str = preg_replace("/({$delim})(".str_replace('\*', '\w*?', preg_quote($badword, '/')).")({$delim})/i", "\\1{$replacement}\\3", $str); } else { $str = preg_replace("/({$delim})(".str_replace('\*', '\w*?', preg_quote($badword, '/')).")({$delim})/ie", "'\\1'.str_repeat('#', strlen('\\2')).'\\3'", $str); } } return trim($str); } } // ------------------------------------------------------------------------ /** * Code Highlighter * * Colorizes code strings * * @access public * @param string the text string * @return string */ if ( ! function_exists('highlight_code')) { function highlight_code($str) { // The highlight string function encodes and highlights // brackets so we need them to start raw $str = str_replace(array('&lt;', '&gt;'), array('<', '>'), $str); // Replace any existing PHP tags to temporary markers so they don't accidentally // break the string out of PHP, and thus, thwart the highlighting. $str = str_replace(array('<?', '?>', '<%', '%>', '\\', '</script>'), array('phptagopen', 'phptagclose', 'asptagopen', 'asptagclose', 'backslashtmp', 'scriptclose'), $str); // The highlight_string function requires that the text be surrounded // by PHP tags, which we will remove later $str = '<?php '.$str.' ?>'; // <? // All the magic happens here, baby! $str = highlight_string($str, TRUE); // Prior to PHP 5, the highligh function used icky <font> tags // so we'll replace them with <span> tags. if (abs(PHP_VERSION) < 5) { $str = str_replace(array('<font ', '</font>'), array('<span ', '</span>'), $str); $str = preg_replace('#color="(.*?)"#', 'style="color: \\1"', $str); } // Remove our artificially added PHP, and the syntax highlighting that came with it $str = preg_replace('/<span style="color: #([A-Z0-9]+)">&lt;\?php(&nbsp;| )/i', '<span style="color: #$1">', $str); $str = preg_replace('/(<span style="color: #[A-Z0-9]+">.*?)\?&gt;<\/span>\n<\/span>\n<\/code>/is', "$1</span>\n</span>\n</code>", $str); $str = preg_replace('/<span style="color: #[A-Z0-9]+"\><\/span>/i', '', $str); // Replace our markers back to PHP tags. $str = str_replace(array('phptagopen', 'phptagclose', 'asptagopen', 'asptagclose', 'backslashtmp', 'scriptclose'), array('&lt;?', '?&gt;', '&lt;%', '%&gt;', '\\', '&lt;/script&gt;'), $str); return $str; } } // ------------------------------------------------------------------------ /** * Phrase Highlighter * * Highlights a phrase within a text string * * @access public * @param string the text string * @param string the phrase you'd like to highlight * @param string the openging tag to precede the phrase with * @param string the closing tag to end the phrase with * @return string */ if ( ! function_exists('highlight_phrase')) { function highlight_phrase($str, $phrase, $tag_open = '<strong>', $tag_close = '</strong>') { if ($str == '') { return ''; } if ($phrase != '') { return preg_replace('/('.preg_quote($phrase, '/').')/i', $tag_open."\\1".$tag_close, $str); } return $str; } } // ------------------------------------------------------------------------ /** * Convert Accented Foreign Characters to ASCII * * @access public * @param string the text string * @return string */ if ( ! function_exists('convert_accented_characters')) { function convert_accented_characters($str) { if (defined('ENVIRONMENT') AND is_file(APPPATH.'config/'.ENVIRONMENT.'/foreign_chars.php')) { include(APPPATH.'config/'.ENVIRONMENT.'/foreign_chars.php'); } elseif (is_file(APPPATH.'config/foreign_chars.php')) { include(APPPATH.'config/foreign_chars.php'); } if ( ! isset($foreign_characters)) { return $str; } return preg_replace(array_keys($foreign_characters), array_values($foreign_characters), $str); } } // ------------------------------------------------------------------------ /** * Word Wrap * * Wraps text at the specified character. Maintains the integrity of words. * Anything placed between {unwrap}{/unwrap} will not be word wrapped, nor * will URLs. * * @access public * @param string the text string * @param integer the number of characters to wrap at * @return string */ if ( ! function_exists('word_wrap')) { function word_wrap($str, $charlim = '76') { // Se the character limit if ( ! is_numeric($charlim)) $charlim = 76; // Reduce multiple spaces $str = preg_replace("| +|", " ", $str); // Standardize newlines if (strpos($str, "\r") !== FALSE) { $str = str_replace(array("\r\n", "\r"), "\n", $str); } // If the current word is surrounded by {unwrap} tags we'll // strip the entire chunk and replace it with a marker. $unwrap = array(); if (preg_match_all("|(\{unwrap\}.+?\{/unwrap\})|s", $str, $matches)) { for ($i = 0; $i < count($matches['0']); $i++) { $unwrap[] = $matches['1'][$i]; $str = str_replace($matches['1'][$i], "{{unwrapped".$i."}}", $str); } } // Use PHP's native function to do the initial wordwrap. // We set the cut flag to FALSE so that any individual words that are // too long get left alone. In the next step we'll deal with them. $str = wordwrap($str, $charlim, "\n", FALSE); // Split the string into individual lines of text and cycle through them $output = ""; foreach (explode("\n", $str) as $line) { // Is the line within the allowed character count? // If so we'll join it to the output and continue if (strlen($line) <= $charlim) { $output .= $line."\n"; continue; } $temp = ''; while ((strlen($line)) > $charlim) { // If the over-length word is a URL we won't wrap it if (preg_match("!\[url.+\]|://|wwww.!", $line)) { break; } // Trim the word down $temp .= substr($line, 0, $charlim-1); $line = substr($line, $charlim-1); } // If $temp contains data it means we had to split up an over-length // word into smaller chunks so we'll add it back to our current line if ($temp != '') { $output .= $temp."\n".$line; } else { $output .= $line; } $output .= "\n"; } // Put our markers back if (count($unwrap) > 0) { foreach ($unwrap as $key => $val) { $output = str_replace("{{unwrapped".$key."}}", $val, $output); } } // Remove the unwrap tags $output = str_replace(array('{unwrap}', '{/unwrap}'), '', $output); return $output; } } // ------------------------------------------------------------------------ /** * Ellipsize String * * This function will strip tags from a string, split it at its max_length and ellipsize * * @param string string to ellipsize * @param integer max length of string * @param mixed int (1|0) or float, .5, .2, etc for position to split * @param string ellipsis ; Default '...' * @return string ellipsized string */ if ( ! function_exists('ellipsize')) { function ellipsize($str, $max_length, $position = 1, $ellipsis = '&hellip;') { // Strip tags $str = trim(strip_tags($str)); // Is the string long enough to ellipsize? if (strlen($str) <= $max_length) { return $str; } $beg = substr($str, 0, floor($max_length * $position)); $position = ($position > 1) ? 1 : $position; if ($position === 1) { $end = substr($str, 0, -($max_length - strlen($beg))); } else { $end = substr($str, -($max_length - strlen($beg))); } return $beg.$ellipsis.$end; } } /* End of file text_helper.php */ /* Location: ./system/helpers/text_helper.php */
101-code
system/helpers/text_helper.php
PHP
gpl3
13,134
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // ------------------------------------------------------------------------ /** * CodeIgniter Array Helpers * * @package CodeIgniter * @subpackage Helpers * @category Helpers * @author ExpressionEngine Dev Team * @link http://codeigniter.com/user_guide/helpers/array_helper.html */ // ------------------------------------------------------------------------ /** * Element * * Lets you determine whether an array index is set and whether it has a value. * If the element is empty it returns FALSE (or whatever you specify as the default value.) * * @access public * @param string * @param array * @param mixed * @return mixed depends on what the array contains */ if ( ! function_exists('element')) { function element($item, $array, $default = FALSE) { if ( ! isset($array[$item]) OR $array[$item] == "") { return $default; } return $array[$item]; } } // ------------------------------------------------------------------------ /** * Random Element - Takes an array as input and returns a random element * * @access public * @param array * @return mixed depends on what the array contains */ if ( ! function_exists('random_element')) { function random_element($array) { if ( ! is_array($array)) { return $array; } return $array[array_rand($array)]; } } // -------------------------------------------------------------------- /** * Elements * * Returns only the array items specified. Will return a default value if * it is not set. * * @access public * @param array * @param array * @param mixed * @return mixed depends on what the array contains */ if ( ! function_exists('elements')) { function elements($items, $array, $default = FALSE) { $return = array(); if ( ! is_array($items)) { $items = array($items); } foreach ($items as $item) { if (isset($array[$item])) { $return[$item] = $array[$item]; } else { $return[$item] = $default; } } return $return; } } /* End of file array_helper.php */ /* Location: ./system/helpers/array_helper.php */
101-code
system/helpers/array_helper.php
PHP
gpl3
2,509
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // ------------------------------------------------------------------------ /** * CodeIgniter HTML Helpers * * @package CodeIgniter * @subpackage Helpers * @category Helpers * @author ExpressionEngine Dev Team * @link http://codeigniter.com/user_guide/helpers/html_helper.html */ // ------------------------------------------------------------------------ /** * Heading * * Generates an HTML heading tag. First param is the data. * Second param is the size of the heading tag. * * @access public * @param string * @param integer * @return string */ if ( ! function_exists('heading')) { function heading($data = '', $h = '1', $attributes = '') { $attributes = ($attributes != '') ? ' '.$attributes : $attributes; return "<h".$h.$attributes.">".$data."</h".$h.">"; } } // ------------------------------------------------------------------------ /** * Unordered List * * Generates an HTML unordered list from an single or multi-dimensional array. * * @access public * @param array * @param mixed * @return string */ if ( ! function_exists('ul')) { function ul($list, $attributes = '') { return _list('ul', $list, $attributes); } } // ------------------------------------------------------------------------ /** * Ordered List * * Generates an HTML ordered list from an single or multi-dimensional array. * * @access public * @param array * @param mixed * @return string */ if ( ! function_exists('ol')) { function ol($list, $attributes = '') { return _list('ol', $list, $attributes); } } // ------------------------------------------------------------------------ /** * Generates the list * * Generates an HTML ordered list from an single or multi-dimensional array. * * @access private * @param string * @param mixed * @param mixed * @param integer * @return string */ if ( ! function_exists('_list')) { function _list($type = 'ul', $list, $attributes = '', $depth = 0) { // If an array wasn't submitted there's nothing to do... if ( ! is_array($list)) { return $list; } // Set the indentation based on the depth $out = str_repeat(" ", $depth); // Were any attributes submitted? If so generate a string if (is_array($attributes)) { $atts = ''; foreach ($attributes as $key => $val) { $atts .= ' ' . $key . '="' . $val . '"'; } $attributes = $atts; } elseif (is_string($attributes) AND strlen($attributes) > 0) { $attributes = ' '. $attributes; } // Write the opening list tag $out .= "<".$type.$attributes.">\n"; // Cycle through the list elements. If an array is // encountered we will recursively call _list() static $_last_list_item = ''; foreach ($list as $key => $val) { $_last_list_item = $key; $out .= str_repeat(" ", $depth + 2); $out .= "<li>"; if ( ! is_array($val)) { $out .= $val; } else { $out .= $_last_list_item."\n"; $out .= _list($type, $val, '', $depth + 4); $out .= str_repeat(" ", $depth + 2); } $out .= "</li>\n"; } // Set the indentation for the closing tag $out .= str_repeat(" ", $depth); // Write the closing list tag $out .= "</".$type.">\n"; return $out; } } // ------------------------------------------------------------------------ /** * Generates HTML BR tags based on number supplied * * @access public * @param integer * @return string */ if ( ! function_exists('br')) { function br($num = 1) { return str_repeat("<br />", $num); } } // ------------------------------------------------------------------------ /** * Image * * Generates an <img /> element * * @access public * @param mixed * @return string */ if ( ! function_exists('img')) { function img($src = '', $index_page = FALSE) { if ( ! is_array($src) ) { $src = array('src' => $src); } // If there is no alt attribute defined, set it to an empty string if ( ! isset($src['alt'])) { $src['alt'] = ''; } $img = '<img'; foreach ($src as $k=>$v) { if ($k == 'src' AND strpos($v, '://') === FALSE) { $CI =& get_instance(); if ($index_page === TRUE) { $img .= ' src="'.$CI->config->site_url($v).'"'; } else { $img .= ' src="'.$CI->config->slash_item('base_url').$v.'"'; } } else { $img .= " $k=\"$v\""; } } $img .= '/>'; return $img; } } // ------------------------------------------------------------------------ /** * Doctype * * Generates a page document type declaration * * Valid options are xhtml-11, xhtml-strict, xhtml-trans, xhtml-frame, * html4-strict, html4-trans, and html4-frame. Values are saved in the * doctypes config file. * * @access public * @param string type The doctype to be generated * @return string */ if ( ! function_exists('doctype')) { function doctype($type = 'xhtml1-strict') { global $_doctypes; if ( ! is_array($_doctypes)) { if (defined('ENVIRONMENT') AND is_file(APPPATH.'config/'.ENVIRONMENT.'/doctypes.php')) { include(APPPATH.'config/'.ENVIRONMENT.'/doctypes.php'); } elseif (is_file(APPPATH.'config/doctypes.php')) { include(APPPATH.'config/doctypes.php'); } if ( ! is_array($_doctypes)) { return FALSE; } } if (isset($_doctypes[$type])) { return $_doctypes[$type]; } else { return FALSE; } } } // ------------------------------------------------------------------------ /** * Link * * Generates link to a CSS file * * @access public * @param mixed stylesheet hrefs or an array * @param string rel * @param string type * @param string title * @param string media * @param boolean should index_page be added to the css path * @return string */ if ( ! function_exists('link_tag')) { function link_tag($href = '', $rel = 'stylesheet', $type = 'text/css', $title = '', $media = '', $index_page = FALSE) { $CI =& get_instance(); $link = '<link '; if (is_array($href)) { foreach ($href as $k=>$v) { if ($k == 'href' AND strpos($v, '://') === FALSE) { if ($index_page === TRUE) { $link .= 'href="'.$CI->config->site_url($v).'" '; } else { $link .= 'href="'.$CI->config->slash_item('base_url').$v.'" '; } } else { $link .= "$k=\"$v\" "; } } $link .= "/>"; } else { if ( strpos($href, '://') !== FALSE) { $link .= 'href="'.$href.'" '; } elseif ($index_page === TRUE) { $link .= 'href="'.$CI->config->site_url($href).'" '; } else { $link .= 'href="'.$CI->config->slash_item('base_url').$href.'" '; } $link .= 'rel="'.$rel.'" type="'.$type.'" '; if ($media != '') { $link .= 'media="'.$media.'" '; } if ($title != '') { $link .= 'title="'.$title.'" '; } $link .= '/>'; } return $link; } } // ------------------------------------------------------------------------ /** * Generates meta tags from an array of key/values * * @access public * @param array * @return string */ if ( ! function_exists('meta')) { function meta($name = '', $content = '', $type = 'name', $newline = "\n") { // Since we allow the data to be passes as a string, a simple array // or a multidimensional one, we need to do a little prepping. if ( ! is_array($name)) { $name = array(array('name' => $name, 'content' => $content, 'type' => $type, 'newline' => $newline)); } else { // Turn single array into multidimensional if (isset($name['name'])) { $name = array($name); } } $str = ''; foreach ($name as $meta) { $type = ( ! isset($meta['type']) OR $meta['type'] == 'name') ? 'name' : 'http-equiv'; $name = ( ! isset($meta['name'])) ? '' : $meta['name']; $content = ( ! isset($meta['content'])) ? '' : $meta['content']; $newline = ( ! isset($meta['newline'])) ? "\n" : $meta['newline']; $str .= '<meta '.$type.'="'.$name.'" content="'.$content.'" />'.$newline; } return $str; } } // ------------------------------------------------------------------------ /** * Generates non-breaking space entities based on number supplied * * @access public * @param integer * @return string */ if ( ! function_exists('nbs')) { function nbs($num = 1) { return str_repeat("&nbsp;", $num); } } /* End of file html_helper.php */ /* Location: ./system/helpers/html_helper.php */
101-code
system/helpers/html_helper.php
PHP
gpl3
8,796
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // ------------------------------------------------------------------------ /** * CodeIgniter XML Helpers * * @package CodeIgniter * @subpackage Helpers * @category Helpers * @author ExpressionEngine Dev Team * @link http://codeigniter.com/user_guide/helpers/xml_helper.html */ // ------------------------------------------------------------------------ /** * Convert Reserved XML characters to Entities * * @access public * @param string * @return string */ if ( ! function_exists('xml_convert')) { function xml_convert($str, $protect_all = FALSE) { $temp = '__TEMP_AMPERSANDS__'; // Replace entities to temporary markers so that // ampersands won't get messed up $str = preg_replace("/&#(\d+);/", "$temp\\1;", $str); if ($protect_all === TRUE) { $str = preg_replace("/&(\w+);/", "$temp\\1;", $str); } $str = str_replace(array("&","<",">","\"", "'", "-"), array("&amp;", "&lt;", "&gt;", "&quot;", "&apos;", "&#45;"), $str); // Decode the temp markers back to entities $str = preg_replace("/$temp(\d+);/","&#\\1;",$str); if ($protect_all === TRUE) { $str = preg_replace("/$temp(\w+);/","&\\1;", $str); } return $str; } } // ------------------------------------------------------------------------ /* End of file xml_helper.php */ /* Location: ./system/helpers/xml_helper.php */
101-code
system/helpers/xml_helper.php
PHP
gpl3
1,788
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // ------------------------------------------------------------------------ /** * CodeIgniter Number Helpers * * @package CodeIgniter * @subpackage Helpers * @category Helpers * @author ExpressionEngine Dev Team * @link http://codeigniter.com/user_guide/helpers/number_helper.html */ // ------------------------------------------------------------------------ /** * Formats a numbers as bytes, based on size, and adds the appropriate suffix * * @access public * @param mixed // will be cast as int * @return string */ if ( ! function_exists('byte_format')) { function byte_format($num, $precision = 1) { $CI =& get_instance(); $CI->lang->load('number'); if ($num >= 1000000000000) { $num = round($num / 1099511627776, $precision); $unit = $CI->lang->line('terabyte_abbr'); } elseif ($num >= 1000000000) { $num = round($num / 1073741824, $precision); $unit = $CI->lang->line('gigabyte_abbr'); } elseif ($num >= 1000000) { $num = round($num / 1048576, $precision); $unit = $CI->lang->line('megabyte_abbr'); } elseif ($num >= 1000) { $num = round($num / 1024, $precision); $unit = $CI->lang->line('kilobyte_abbr'); } else { $unit = $CI->lang->line('bytes'); return number_format($num).' '.$unit; } return number_format($num, $precision).' '.$unit; } } /* End of file number_helper.php */ /* Location: ./system/helpers/number_helper.php */
101-code
system/helpers/number_helper.php
PHP
gpl3
1,859
<html> <head> <title>403 Forbidden</title> </head> <body> <p>Directory access is forbidden.</p> </body> </html>
101-code
system/helpers/index.html
HTML
gpl3
114
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // ------------------------------------------------------------------------ /** * CodeIgniter Smiley Helpers * * @package CodeIgniter * @subpackage Helpers * @category Helpers * @author ExpressionEngine Dev Team * @link http://codeigniter.com/user_guide/helpers/smiley_helper.html */ // ------------------------------------------------------------------------ /** * Smiley Javascript * * Returns the javascript required for the smiley insertion. Optionally takes * an array of aliases to loosely couple the smiley array to the view. * * @access public * @param mixed alias name or array of alias->field_id pairs * @param string field_id if alias name was passed in * @return array */ if ( ! function_exists('smiley_js')) { function smiley_js($alias = '', $field_id = '', $inline = TRUE) { static $do_setup = TRUE; $r = ''; if ($alias != '' && ! is_array($alias)) { $alias = array($alias => $field_id); } if ($do_setup === TRUE) { $do_setup = FALSE; $m = array(); if (is_array($alias)) { foreach ($alias as $name => $id) { $m[] = '"'.$name.'" : "'.$id.'"'; } } $m = '{'.implode(',', $m).'}'; $r .= <<<EOF var smiley_map = {$m}; function insert_smiley(smiley, field_id) { var el = document.getElementById(field_id), newStart; if ( ! el && smiley_map[field_id]) { el = document.getElementById(smiley_map[field_id]); if ( ! el) return false; } el.focus(); smiley = " " + smiley; if ('selectionStart' in el) { newStart = el.selectionStart + smiley.length; el.value = el.value.substr(0, el.selectionStart) + smiley + el.value.substr(el.selectionEnd, el.value.length); el.setSelectionRange(newStart, newStart); } else if (document.selection) { document.selection.createRange().text = smiley; } } EOF; } else { if (is_array($alias)) { foreach ($alias as $name => $id) { $r .= 'smiley_map["'.$name.'"] = "'.$id.'";'."\n"; } } } if ($inline) { return '<script type="text/javascript" charset="utf-8">/*<![CDATA[ */'.$r.'// ]]></script>'; } else { return $r; } } } // ------------------------------------------------------------------------ /** * Get Clickable Smileys * * Returns an array of image tag links that can be clicked to be inserted * into a form field. * * @access public * @param string the URL to the folder containing the smiley images * @return array */ if ( ! function_exists('get_clickable_smileys')) { function get_clickable_smileys($image_url, $alias = '', $smileys = NULL) { // For backward compatibility with js_insert_smiley if (is_array($alias)) { $smileys = $alias; } if ( ! is_array($smileys)) { if (FALSE === ($smileys = _get_smiley_array())) { return $smileys; } } // Add a trailing slash to the file path if needed $image_url = rtrim($image_url, '/').'/'; $used = array(); foreach ($smileys as $key => $val) { // Keep duplicates from being used, which can happen if the // mapping array contains multiple identical replacements. For example: // :-) and :) might be replaced with the same image so both smileys // will be in the array. if (isset($used[$smileys[$key][0]])) { continue; } $link[] = "<a href=\"javascript:void(0);\" onclick=\"insert_smiley('".$key."', '".$alias."')\"><img src=\"".$image_url.$smileys[$key][0]."\" width=\"".$smileys[$key][1]."\" height=\"".$smileys[$key][2]."\" alt=\"".$smileys[$key][3]."\" style=\"border:0;\" /></a>"; $used[$smileys[$key][0]] = TRUE; } return $link; } } // ------------------------------------------------------------------------ /** * Parse Smileys * * Takes a string as input and swaps any contained smileys for the actual image * * @access public * @param string the text to be parsed * @param string the URL to the folder containing the smiley images * @return string */ if ( ! function_exists('parse_smileys')) { function parse_smileys($str = '', $image_url = '', $smileys = NULL) { if ($image_url == '') { return $str; } if ( ! is_array($smileys)) { if (FALSE === ($smileys = _get_smiley_array())) { return $str; } } // Add a trailing slash to the file path if needed $image_url = preg_replace("/(.+?)\/*$/", "\\1/", $image_url); foreach ($smileys as $key => $val) { $str = str_replace($key, "<img src=\"".$image_url.$smileys[$key][0]."\" width=\"".$smileys[$key][1]."\" height=\"".$smileys[$key][2]."\" alt=\"".$smileys[$key][3]."\" style=\"border:0;\" />", $str); } return $str; } } // ------------------------------------------------------------------------ /** * Get Smiley Array * * Fetches the config/smiley.php file * * @access private * @return mixed */ if ( ! function_exists('_get_smiley_array')) { function _get_smiley_array() { if (defined('ENVIRONMENT') AND file_exists(APPPATH.'config/'.ENVIRONMENT.'/smileys.php')) { include(APPPATH.'config/'.ENVIRONMENT.'/smileys.php'); } elseif (file_exists(APPPATH.'config/smileys.php')) { include(APPPATH.'config/smileys.php'); } if (isset($smileys) AND is_array($smileys)) { return $smileys; } return FALSE; } } // ------------------------------------------------------------------------ /** * JS Insert Smiley * * Generates the javascript function needed to insert smileys into a form field * * DEPRECATED as of version 1.7.2, use smiley_js instead * * @access public * @param string form name * @param string field name * @return string */ if ( ! function_exists('js_insert_smiley')) { function js_insert_smiley($form_name = '', $form_field = '') { return <<<EOF <script type="text/javascript"> function insert_smiley(smiley) { document.{$form_name}.{$form_field}.value += " " + smiley; } </script> EOF; } } /* End of file smiley_helper.php */ /* Location: ./system/helpers/smiley_helper.php */
101-code
system/helpers/smiley_helper.php
PHP
gpl3
6,466
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // ------------------------------------------------------------------------ /** * CodeIgniter File Helpers * * @package CodeIgniter * @subpackage Helpers * @category Helpers * @author ExpressionEngine Dev Team * @link http://codeigniter.com/user_guide/helpers/file_helpers.html */ // ------------------------------------------------------------------------ /** * Read File * * Opens the file specfied in the path and returns it as a string. * * @access public * @param string path to file * @return string */ if ( ! function_exists('read_file')) { function read_file($file) { if ( ! file_exists($file)) { return FALSE; } if (function_exists('file_get_contents')) { return file_get_contents($file); } if ( ! $fp = @fopen($file, FOPEN_READ)) { return FALSE; } flock($fp, LOCK_SH); $data = ''; if (filesize($file) > 0) { $data =& fread($fp, filesize($file)); } flock($fp, LOCK_UN); fclose($fp); return $data; } } // ------------------------------------------------------------------------ /** * Write File * * Writes data to the file specified in the path. * Creates a new file if non-existent. * * @access public * @param string path to file * @param string file data * @return bool */ if ( ! function_exists('write_file')) { function write_file($path, $data, $mode = FOPEN_WRITE_CREATE_DESTRUCTIVE) { if ( ! $fp = @fopen($path, $mode)) { return FALSE; } flock($fp, LOCK_EX); fwrite($fp, $data); flock($fp, LOCK_UN); fclose($fp); return TRUE; } } // ------------------------------------------------------------------------ /** * Delete Files * * Deletes all files contained in the supplied directory path. * Files must be writable or owned by the system in order to be deleted. * If the second parameter is set to TRUE, any directories contained * within the supplied base directory will be nuked as well. * * @access public * @param string path to file * @param bool whether to delete any directories found in the path * @return bool */ if ( ! function_exists('delete_files')) { function delete_files($path, $del_dir = FALSE, $level = 0) { // Trim the trailing slash $path = rtrim($path, DIRECTORY_SEPARATOR); if ( ! $current_dir = @opendir($path)) { return FALSE; } while (FALSE !== ($filename = @readdir($current_dir))) { if ($filename != "." and $filename != "..") { if (is_dir($path.DIRECTORY_SEPARATOR.$filename)) { // Ignore empty folders if (substr($filename, 0, 1) != '.') { delete_files($path.DIRECTORY_SEPARATOR.$filename, $del_dir, $level + 1); } } else { unlink($path.DIRECTORY_SEPARATOR.$filename); } } } @closedir($current_dir); if ($del_dir == TRUE AND $level > 0) { return @rmdir($path); } return TRUE; } } // ------------------------------------------------------------------------ /** * Get Filenames * * Reads the specified directory and builds an array containing the filenames. * Any sub-folders contained within the specified path are read as well. * * @access public * @param string path to source * @param bool whether to include the path as part of the filename * @param bool internal variable to determine recursion status - do not use in calls * @return array */ if ( ! function_exists('get_filenames')) { function get_filenames($source_dir, $include_path = FALSE, $_recursion = FALSE) { static $_filedata = array(); if ($fp = @opendir($source_dir)) { // reset the array and make sure $source_dir has a trailing slash on the initial call if ($_recursion === FALSE) { $_filedata = array(); $source_dir = rtrim(realpath($source_dir), DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR; } while (FALSE !== ($file = readdir($fp))) { if (@is_dir($source_dir.$file) && strncmp($file, '.', 1) !== 0) { get_filenames($source_dir.$file.DIRECTORY_SEPARATOR, $include_path, TRUE); } elseif (strncmp($file, '.', 1) !== 0) { $_filedata[] = ($include_path == TRUE) ? $source_dir.$file : $file; } } return $_filedata; } else { return FALSE; } } } // -------------------------------------------------------------------- /** * Get Directory File Information * * Reads the specified directory and builds an array containing the filenames, * filesize, dates, and permissions * * Any sub-folders contained within the specified path are read as well. * * @access public * @param string path to source * @param bool Look only at the top level directory specified? * @param bool internal variable to determine recursion status - do not use in calls * @return array */ if ( ! function_exists('get_dir_file_info')) { function get_dir_file_info($source_dir, $top_level_only = TRUE, $_recursion = FALSE) { static $_filedata = array(); $relative_path = $source_dir; if ($fp = @opendir($source_dir)) { // reset the array and make sure $source_dir has a trailing slash on the initial call if ($_recursion === FALSE) { $_filedata = array(); $source_dir = rtrim(realpath($source_dir), DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR; } // foreach (scandir($source_dir, 1) as $file) // In addition to being PHP5+, scandir() is simply not as fast while (FALSE !== ($file = readdir($fp))) { if (@is_dir($source_dir.$file) AND strncmp($file, '.', 1) !== 0 AND $top_level_only === FALSE) { get_dir_file_info($source_dir.$file.DIRECTORY_SEPARATOR, $top_level_only, TRUE); } elseif (strncmp($file, '.', 1) !== 0) { $_filedata[$file] = get_file_info($source_dir.$file); $_filedata[$file]['relative_path'] = $relative_path; } } return $_filedata; } else { return FALSE; } } } // -------------------------------------------------------------------- /** * Get File Info * * Given a file and path, returns the name, path, size, date modified * Second parameter allows you to explicitly declare what information you want returned * Options are: name, server_path, size, date, readable, writable, executable, fileperms * Returns FALSE if the file cannot be found. * * @access public * @param string path to file * @param mixed array or comma separated string of information returned * @return array */ if ( ! function_exists('get_file_info')) { function get_file_info($file, $returned_values = array('name', 'server_path', 'size', 'date')) { if ( ! file_exists($file)) { return FALSE; } if (is_string($returned_values)) { $returned_values = explode(',', $returned_values); } foreach ($returned_values as $key) { switch ($key) { case 'name': $fileinfo['name'] = substr(strrchr($file, DIRECTORY_SEPARATOR), 1); break; case 'server_path': $fileinfo['server_path'] = $file; break; case 'size': $fileinfo['size'] = filesize($file); break; case 'date': $fileinfo['date'] = filemtime($file); break; case 'readable': $fileinfo['readable'] = is_readable($file); break; case 'writable': // There are known problems using is_weritable on IIS. It may not be reliable - consider fileperms() $fileinfo['writable'] = is_writable($file); break; case 'executable': $fileinfo['executable'] = is_executable($file); break; case 'fileperms': $fileinfo['fileperms'] = fileperms($file); break; } } return $fileinfo; } } // -------------------------------------------------------------------- /** * Get Mime by Extension * * Translates a file extension into a mime type based on config/mimes.php. * Returns FALSE if it can't determine the type, or open the mime config file * * Note: this is NOT an accurate way of determining file mime types, and is here strictly as a convenience * It should NOT be trusted, and should certainly NOT be used for security * * @access public * @param string path to file * @return mixed */ if ( ! function_exists('get_mime_by_extension')) { function get_mime_by_extension($file) { $extension = strtolower(substr(strrchr($file, '.'), 1)); global $mimes; if ( ! is_array($mimes)) { if (defined('ENVIRONMENT') AND is_file(APPPATH.'config/'.ENVIRONMENT.'/mimes.php')) { include(APPPATH.'config/'.ENVIRONMENT.'/mimes.php'); } elseif (is_file(APPPATH.'config/mimes.php')) { include(APPPATH.'config/mimes.php'); } if ( ! is_array($mimes)) { return FALSE; } } if (array_key_exists($extension, $mimes)) { if (is_array($mimes[$extension])) { // Multiple mime types, just give the first one return current($mimes[$extension]); } else { return $mimes[$extension]; } } else { return FALSE; } } } // -------------------------------------------------------------------- /** * Symbolic Permissions * * Takes a numeric value representing a file's permissions and returns * standard symbolic notation representing that value * * @access public * @param int * @return string */ if ( ! function_exists('symbolic_permissions')) { function symbolic_permissions($perms) { if (($perms & 0xC000) == 0xC000) { $symbolic = 's'; // Socket } elseif (($perms & 0xA000) == 0xA000) { $symbolic = 'l'; // Symbolic Link } elseif (($perms & 0x8000) == 0x8000) { $symbolic = '-'; // Regular } elseif (($perms & 0x6000) == 0x6000) { $symbolic = 'b'; // Block special } elseif (($perms & 0x4000) == 0x4000) { $symbolic = 'd'; // Directory } elseif (($perms & 0x2000) == 0x2000) { $symbolic = 'c'; // Character special } elseif (($perms & 0x1000) == 0x1000) { $symbolic = 'p'; // FIFO pipe } else { $symbolic = 'u'; // Unknown } // Owner $symbolic .= (($perms & 0x0100) ? 'r' : '-'); $symbolic .= (($perms & 0x0080) ? 'w' : '-'); $symbolic .= (($perms & 0x0040) ? (($perms & 0x0800) ? 's' : 'x' ) : (($perms & 0x0800) ? 'S' : '-')); // Group $symbolic .= (($perms & 0x0020) ? 'r' : '-'); $symbolic .= (($perms & 0x0010) ? 'w' : '-'); $symbolic .= (($perms & 0x0008) ? (($perms & 0x0400) ? 's' : 'x' ) : (($perms & 0x0400) ? 'S' : '-')); // World $symbolic .= (($perms & 0x0004) ? 'r' : '-'); $symbolic .= (($perms & 0x0002) ? 'w' : '-'); $symbolic .= (($perms & 0x0001) ? (($perms & 0x0200) ? 't' : 'x' ) : (($perms & 0x0200) ? 'T' : '-')); return $symbolic; } } // -------------------------------------------------------------------- /** * Octal Permissions * * Takes a numeric value representing a file's permissions and returns * a three character string representing the file's octal permissions * * @access public * @param int * @return string */ if ( ! function_exists('octal_permissions')) { function octal_permissions($perms) { return substr(sprintf('%o', $perms), -3); } } /* End of file file_helper.php */ /* Location: ./system/helpers/file_helper.php */
101-code
system/helpers/file_helper.php
PHP
gpl3
11,384
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // ------------------------------------------------------------------------ /** * Database Cache Class * * @category Database * @author ExpressionEngine Dev Team * @link http://codeigniter.com/user_guide/database/ */ class CI_DB_Cache { var $CI; var $db; // allows passing of db object so that multiple database connections and returned db objects can be supported /** * Constructor * * Grabs the CI super object instance so we can access it. * */ function __construct(&$db) { // Assign the main CI object to $this->CI // and load the file helper since we use it a lot $this->CI =& get_instance(); $this->db =& $db; $this->CI->load->helper('file'); } // -------------------------------------------------------------------- /** * Set Cache Directory Path * * @access public * @param string the path to the cache directory * @return bool */ function check_path($path = '') { if ($path == '') { if ($this->db->cachedir == '') { return $this->db->cache_off(); } $path = $this->db->cachedir; } // Add a trailing slash to the path if needed $path = preg_replace("/(.+?)\/*$/", "\\1/", $path); if ( ! is_dir($path) OR ! is_really_writable($path)) { // If the path is wrong we'll turn off caching return $this->db->cache_off(); } $this->db->cachedir = $path; return TRUE; } // -------------------------------------------------------------------- /** * Retrieve a cached query * * The URI being requested will become the name of the cache sub-folder. * An MD5 hash of the SQL statement will become the cache file name * * @access public * @return string */ function read($sql) { if ( ! $this->check_path()) { return $this->db->cache_off(); } $segment_one = ($this->CI->uri->segment(1) == FALSE) ? 'default' : $this->CI->uri->segment(1); $segment_two = ($this->CI->uri->segment(2) == FALSE) ? 'index' : $this->CI->uri->segment(2); $filepath = $this->db->cachedir.$segment_one.'+'.$segment_two.'/'.md5($sql); if (FALSE === ($cachedata = read_file($filepath))) { return FALSE; } return unserialize($cachedata); } // -------------------------------------------------------------------- /** * Write a query to a cache file * * @access public * @return bool */ function write($sql, $object) { if ( ! $this->check_path()) { return $this->db->cache_off(); } $segment_one = ($this->CI->uri->segment(1) == FALSE) ? 'default' : $this->CI->uri->segment(1); $segment_two = ($this->CI->uri->segment(2) == FALSE) ? 'index' : $this->CI->uri->segment(2); $dir_path = $this->db->cachedir.$segment_one.'+'.$segment_two.'/'; $filename = md5($sql); if ( ! @is_dir($dir_path)) { if ( ! @mkdir($dir_path, DIR_WRITE_MODE)) { return FALSE; } @chmod($dir_path, DIR_WRITE_MODE); } if (write_file($dir_path.$filename, serialize($object)) === FALSE) { return FALSE; } @chmod($dir_path.$filename, FILE_WRITE_MODE); return TRUE; } // -------------------------------------------------------------------- /** * Delete cache files within a particular directory * * @access public * @return bool */ function delete($segment_one = '', $segment_two = '') { if ($segment_one == '') { $segment_one = ($this->CI->uri->segment(1) == FALSE) ? 'default' : $this->CI->uri->segment(1); } if ($segment_two == '') { $segment_two = ($this->CI->uri->segment(2) == FALSE) ? 'index' : $this->CI->uri->segment(2); } $dir_path = $this->db->cachedir.$segment_one.'+'.$segment_two.'/'; delete_files($dir_path, TRUE); } // -------------------------------------------------------------------- /** * Delete all existing cache files * * @access public * @return bool */ function delete_all() { delete_files($this->db->cachedir, TRUE); } } /* End of file DB_cache.php */ /* Location: ./system/database/DB_cache.php */
101-code
system/database/DB_cache.php
PHP
gpl3
4,378
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // ------------------------------------------------------------------------ /** * MySQL Forge Class * * @category Database * @author ExpressionEngine Dev Team * @link http://codeigniter.com/user_guide/database/ */ class CI_DB_mysql_forge extends CI_DB_forge { /** * Create database * * @access private * @param string the database name * @return bool */ function _create_database($name) { return "CREATE DATABASE ".$name; } // -------------------------------------------------------------------- /** * Drop database * * @access private * @param string the database name * @return bool */ function _drop_database($name) { return "DROP DATABASE ".$name; } // -------------------------------------------------------------------- /** * Process Fields * * @access private * @param mixed the fields * @return string */ function _process_fields($fields) { $current_field_count = 0; $sql = ''; foreach ($fields as $field=>$attributes) { // Numeric field names aren't allowed in databases, so if the key is // numeric, we know it was assigned by PHP and the developer manually // entered the field information, so we'll simply add it to the list if (is_numeric($field)) { $sql .= "\n\t$attributes"; } else { $attributes = array_change_key_case($attributes, CASE_UPPER); $sql .= "\n\t".$this->db->_protect_identifiers($field); if (array_key_exists('NAME', $attributes)) { $sql .= ' '.$this->db->_protect_identifiers($attributes['NAME']).' '; } if (array_key_exists('TYPE', $attributes)) { $sql .= ' '.$attributes['TYPE']; if (array_key_exists('CONSTRAINT', $attributes)) { switch ($attributes['TYPE']) { case 'decimal': case 'float': case 'numeric': $sql .= '('.implode(',', $attributes['CONSTRAINT']).')'; break; case 'enum': case 'set': $sql .= '("'.implode('","', $attributes['CONSTRAINT']).'")'; break; default: $sql .= '('.$attributes['CONSTRAINT'].')'; } } } if (array_key_exists('UNSIGNED', $attributes) && $attributes['UNSIGNED'] === TRUE) { $sql .= ' UNSIGNED'; } if (array_key_exists('DEFAULT', $attributes)) { $sql .= ' DEFAULT \''.$attributes['DEFAULT'].'\''; } if (array_key_exists('NULL', $attributes) && $attributes['NULL'] === TRUE) { $sql .= ' NULL'; } else { $sql .= ' NOT NULL'; } if (array_key_exists('AUTO_INCREMENT', $attributes) && $attributes['AUTO_INCREMENT'] === TRUE) { $sql .= ' AUTO_INCREMENT'; } } // don't add a comma on the end of the last field if (++$current_field_count < count($fields)) { $sql .= ','; } } return $sql; } // -------------------------------------------------------------------- /** * Create Table * * @access private * @param string the table name * @param mixed the fields * @param mixed primary key(s) * @param mixed key(s) * @param boolean should 'IF NOT EXISTS' be added to the SQL * @return bool */ function _create_table($table, $fields, $primary_keys, $keys, $if_not_exists) { $sql = 'CREATE TABLE '; if ($if_not_exists === TRUE) { $sql .= 'IF NOT EXISTS '; } $sql .= $this->db->_escape_identifiers($table)." ("; $sql .= $this->_process_fields($fields); if (count($primary_keys) > 0) { $key_name = $this->db->_protect_identifiers(implode('_', $primary_keys)); $primary_keys = $this->db->_protect_identifiers($primary_keys); $sql .= ",\n\tPRIMARY KEY ".$key_name." (" . implode(', ', $primary_keys) . ")"; } if (is_array($keys) && count($keys) > 0) { foreach ($keys as $key) { if (is_array($key)) { $key_name = $this->db->_protect_identifiers(implode('_', $key)); $key = $this->db->_protect_identifiers($key); } else { $key_name = $this->db->_protect_identifiers($key); $key = array($key_name); } $sql .= ",\n\tKEY {$key_name} (" . implode(', ', $key) . ")"; } } $sql .= "\n) DEFAULT CHARACTER SET {$this->db->char_set} COLLATE {$this->db->dbcollat};"; return $sql; } // -------------------------------------------------------------------- /** * Drop Table * * @access private * @return string */ function _drop_table($table) { return "DROP TABLE IF EXISTS ".$this->db->_escape_identifiers($table); } // -------------------------------------------------------------------- /** * Alter table query * * Generates a platform-specific query so that a table can be altered * Called by add_column(), drop_column(), and column_alter(), * * @access private * @param string the ALTER type (ADD, DROP, CHANGE) * @param string the column name * @param array fields * @param string the field after which we should add the new field * @return object */ function _alter_table($alter_type, $table, $fields, $after_field = '') { $sql = 'ALTER TABLE '.$this->db->_protect_identifiers($table)." $alter_type "; // DROP has everything it needs now. if ($alter_type == 'DROP') { return $sql.$this->db->_protect_identifiers($fields); } $sql .= $this->_process_fields($fields); if ($after_field != '') { $sql .= ' AFTER ' . $this->db->_protect_identifiers($after_field); } return $sql; } // -------------------------------------------------------------------- /** * Rename a table * * Generates a platform-specific query so that a table can be renamed * * @access private * @param string the old table name * @param string the new table name * @return string */ function _rename_table($table_name, $new_table_name) { $sql = 'ALTER TABLE '.$this->db->_protect_identifiers($table_name)." RENAME TO ".$this->db->_protect_identifiers($new_table_name); return $sql; } } /* End of file mysql_forge.php */ /* Location: ./system/database/drivers/mysql/mysql_forge.php */
101-code
system/database/drivers/mysql/mysql_forge.php
PHP
gpl3
6,441
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // ------------------------------------------------------------------------ /** * MySQL Utility Class * * @category Database * @author ExpressionEngine Dev Team * @link http://codeigniter.com/user_guide/database/ */ class CI_DB_mysql_utility extends CI_DB_utility { /** * List databases * * @access private * @return bool */ function _list_databases() { return "SHOW DATABASES"; } // -------------------------------------------------------------------- /** * Optimize table query * * Generates a platform-specific query so that a table can be optimized * * @access private * @param string the table name * @return object */ function _optimize_table($table) { return "OPTIMIZE TABLE ".$this->db->_escape_identifiers($table); } // -------------------------------------------------------------------- /** * Repair table query * * Generates a platform-specific query so that a table can be repaired * * @access private * @param string the table name * @return object */ function _repair_table($table) { return "REPAIR TABLE ".$this->db->_escape_identifiers($table); } // -------------------------------------------------------------------- /** * MySQL Export * * @access private * @param array Preferences * @return mixed */ function _backup($params = array()) { if (count($params) == 0) { return FALSE; } // Extract the prefs for simplicity extract($params); // Build the output $output = ''; foreach ((array)$tables as $table) { // Is the table in the "ignore" list? if (in_array($table, (array)$ignore, TRUE)) { continue; } // Get the table schema $query = $this->db->query("SHOW CREATE TABLE `".$this->db->database.'`.`'.$table.'`'); // No result means the table name was invalid if ($query === FALSE) { continue; } // Write out the table schema $output .= '#'.$newline.'# TABLE STRUCTURE FOR: '.$table.$newline.'#'.$newline.$newline; if ($add_drop == TRUE) { $output .= 'DROP TABLE IF EXISTS '.$table.';'.$newline.$newline; } $i = 0; $result = $query->result_array(); foreach ($result[0] as $val) { if ($i++ % 2) { $output .= $val.';'.$newline.$newline; } } // If inserts are not needed we're done... if ($add_insert == FALSE) { continue; } // Grab all the data from the current table $query = $this->db->query("SELECT * FROM $table"); if ($query->num_rows() == 0) { continue; } // Fetch the field names and determine if the field is an // integer type. We use this info to decide whether to // surround the data with quotes or not $i = 0; $field_str = ''; $is_int = array(); while ($field = mysql_fetch_field($query->result_id)) { // Most versions of MySQL store timestamp as a string $is_int[$i] = (in_array( strtolower(mysql_field_type($query->result_id, $i)), array('tinyint', 'smallint', 'mediumint', 'int', 'bigint'), //, 'timestamp'), TRUE) ) ? TRUE : FALSE; // Create a string of field names $field_str .= '`'.$field->name.'`, '; $i++; } // Trim off the end comma $field_str = preg_replace( "/, $/" , "" , $field_str); // Build the insert string foreach ($query->result_array() as $row) { $val_str = ''; $i = 0; foreach ($row as $v) { // Is the value NULL? if ($v === NULL) { $val_str .= 'NULL'; } else { // Escape the data if it's not an integer if ($is_int[$i] == FALSE) { $val_str .= $this->db->escape($v); } else { $val_str .= $v; } } // Append a comma $val_str .= ', '; $i++; } // Remove the comma at the end of the string $val_str = preg_replace( "/, $/" , "" , $val_str); // Build the INSERT string $output .= 'INSERT INTO '.$table.' ('.$field_str.') VALUES ('.$val_str.');'.$newline; } $output .= $newline.$newline; } return $output; } } /* End of file mysql_utility.php */ /* Location: ./system/database/drivers/mysql/mysql_utility.php */
101-code
system/database/drivers/mysql/mysql_utility.php
PHP
gpl3
4,610
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // ------------------------------------------------------------------------ /** * MySQL Database Adapter Class * * Note: _DB is an extender class that the app controller * creates dynamically based on whether the active record * class is being used or not. * * @package CodeIgniter * @subpackage Drivers * @category Database * @author ExpressionEngine Dev Team * @link http://codeigniter.com/user_guide/database/ */ class CI_DB_mysql_driver extends CI_DB { var $dbdriver = 'mysql'; // The character used for escaping var $_escape_char = '`'; // clause and character used for LIKE escape sequences - not used in MySQL var $_like_escape_str = ''; var $_like_escape_chr = ''; /** * Whether to use the MySQL "delete hack" which allows the number * of affected rows to be shown. Uses a preg_replace when enabled, * adding a bit more processing to all queries. */ var $delete_hack = TRUE; /** * The syntax to count rows is slightly different across different * database engines, so this string appears in each driver and is * used for the count_all() and count_all_results() functions. */ var $_count_string = 'SELECT COUNT(*) AS '; var $_random_keyword = ' RAND()'; // database specific random keyword // whether SET NAMES must be used to set the character set var $use_set_names; /** * Non-persistent database connection * * @access private called by the base class * @return resource */ function db_connect() { if ($this->port != '') { $this->hostname .= ':'.$this->port; } return @mysql_connect($this->hostname, $this->username, $this->password, TRUE); } // -------------------------------------------------------------------- /** * Persistent database connection * * @access private called by the base class * @return resource */ function db_pconnect() { if ($this->port != '') { $this->hostname .= ':'.$this->port; } return @mysql_pconnect($this->hostname, $this->username, $this->password); } // -------------------------------------------------------------------- /** * Reconnect * * Keep / reestablish the db connection if no queries have been * sent for a length of time exceeding the server's idle timeout * * @access public * @return void */ function reconnect() { if (mysql_ping($this->conn_id) === FALSE) { $this->conn_id = FALSE; } } // -------------------------------------------------------------------- /** * Select the database * * @access private called by the base class * @return resource */ function db_select() { return @mysql_select_db($this->database, $this->conn_id); } // -------------------------------------------------------------------- /** * Set client character set * * @access public * @param string * @param string * @return resource */ function db_set_charset($charset, $collation) { if ( ! isset($this->use_set_names)) { // mysql_set_charset() requires PHP >= 5.2.3 and MySQL >= 5.0.7, use SET NAMES as fallback $this->use_set_names = (version_compare(PHP_VERSION, '5.2.3', '>=') && version_compare(mysql_get_server_info(), '5.0.7', '>=')) ? FALSE : TRUE; } if ($this->use_set_names === TRUE) { return @mysql_query("SET NAMES '".$this->escape_str($charset)."' COLLATE '".$this->escape_str($collation)."'", $this->conn_id); } else { return @mysql_set_charset($charset, $this->conn_id); } } // -------------------------------------------------------------------- /** * Version number query string * * @access public * @return string */ function _version() { return "SELECT version() AS ver"; } // -------------------------------------------------------------------- /** * Execute the query * * @access private called by the base class * @param string an SQL query * @return resource */ function _execute($sql) { $sql = $this->_prep_query($sql); return @mysql_query($sql, $this->conn_id); } // -------------------------------------------------------------------- /** * Prep the query * * If needed, each database adapter can prep the query string * * @access private called by execute() * @param string an SQL query * @return string */ function _prep_query($sql) { // "DELETE FROM TABLE" returns 0 affected rows This hack modifies // the query so that it returns the number of affected rows if ($this->delete_hack === TRUE) { if (preg_match('/^\s*DELETE\s+FROM\s+(\S+)\s*$/i', $sql)) { $sql = preg_replace("/^\s*DELETE\s+FROM\s+(\S+)\s*$/", "DELETE FROM \\1 WHERE 1=1", $sql); } } return $sql; } // -------------------------------------------------------------------- /** * Begin Transaction * * @access public * @return bool */ function trans_begin($test_mode = FALSE) { if ( ! $this->trans_enabled) { return TRUE; } // When transactions are nested we only begin/commit/rollback the outermost ones if ($this->_trans_depth > 0) { return TRUE; } // Reset the transaction failure flag. // If the $test_mode flag is set to TRUE transactions will be rolled back // even if the queries produce a successful result. $this->_trans_failure = ($test_mode === TRUE) ? TRUE : FALSE; $this->simple_query('SET AUTOCOMMIT=0'); $this->simple_query('START TRANSACTION'); // can also be BEGIN or BEGIN WORK return TRUE; } // -------------------------------------------------------------------- /** * Commit Transaction * * @access public * @return bool */ function trans_commit() { if ( ! $this->trans_enabled) { return TRUE; } // When transactions are nested we only begin/commit/rollback the outermost ones if ($this->_trans_depth > 0) { return TRUE; } $this->simple_query('COMMIT'); $this->simple_query('SET AUTOCOMMIT=1'); return TRUE; } // -------------------------------------------------------------------- /** * Rollback Transaction * * @access public * @return bool */ function trans_rollback() { if ( ! $this->trans_enabled) { return TRUE; } // When transactions are nested we only begin/commit/rollback the outermost ones if ($this->_trans_depth > 0) { return TRUE; } $this->simple_query('ROLLBACK'); $this->simple_query('SET AUTOCOMMIT=1'); return TRUE; } // -------------------------------------------------------------------- /** * Escape String * * @access public * @param string * @param bool whether or not the string will be used in a LIKE condition * @return string */ function escape_str($str, $like = FALSE) { if (is_array($str)) { foreach ($str as $key => $val) { $str[$key] = $this->escape_str($val, $like); } return $str; } if (function_exists('mysql_real_escape_string') AND is_resource($this->conn_id)) { $str = mysql_real_escape_string($str, $this->conn_id); } elseif (function_exists('mysql_escape_string')) { $str = mysql_escape_string($str); } else { $str = addslashes($str); } // escape LIKE condition wildcards if ($like === TRUE) { $str = str_replace(array('%', '_'), array('\\%', '\\_'), $str); } return $str; } // -------------------------------------------------------------------- /** * Affected Rows * * @access public * @return integer */ function affected_rows() { return @mysql_affected_rows($this->conn_id); } // -------------------------------------------------------------------- /** * Insert ID * * @access public * @return integer */ function insert_id() { return @mysql_insert_id($this->conn_id); } // -------------------------------------------------------------------- /** * "Count All" query * * Generates a platform-specific query string that counts all records in * the specified database * * @access public * @param string * @return string */ function count_all($table = '') { if ($table == '') { return 0; } $query = $this->query($this->_count_string . $this->_protect_identifiers('numrows') . " FROM " . $this->_protect_identifiers($table, TRUE, NULL, FALSE)); if ($query->num_rows() == 0) { return 0; } $row = $query->row(); $this->_reset_select(); return (int) $row->numrows; } // -------------------------------------------------------------------- /** * List table query * * Generates a platform-specific query string so that the table names can be fetched * * @access private * @param boolean * @return string */ function _list_tables($prefix_limit = FALSE) { $sql = "SHOW TABLES FROM ".$this->_escape_char.$this->database.$this->_escape_char; if ($prefix_limit !== FALSE AND $this->dbprefix != '') { $sql .= " LIKE '".$this->escape_like_str($this->dbprefix)."%'"; } return $sql; } // -------------------------------------------------------------------- /** * Show column query * * Generates a platform-specific query string so that the column names can be fetched * * @access public * @param string the table name * @return string */ function _list_columns($table = '') { return "SHOW COLUMNS FROM ".$this->_protect_identifiers($table, TRUE, NULL, FALSE); } // -------------------------------------------------------------------- /** * Field data query * * Generates a platform-specific query so that the column data can be retrieved * * @access public * @param string the table name * @return object */ function _field_data($table) { return "DESCRIBE ".$table; } // -------------------------------------------------------------------- /** * The error message string * * @access private * @return string */ function _error_message() { return mysql_error($this->conn_id); } // -------------------------------------------------------------------- /** * The error message number * * @access private * @return integer */ function _error_number() { return mysql_errno($this->conn_id); } // -------------------------------------------------------------------- /** * Escape the SQL Identifiers * * This function escapes column and table names * * @access private * @param string * @return string */ function _escape_identifiers($item) { if ($this->_escape_char == '') { return $item; } foreach ($this->_reserved_identifiers as $id) { if (strpos($item, '.'.$id) !== FALSE) { $str = $this->_escape_char. str_replace('.', $this->_escape_char.'.', $item); // remove duplicates if the user already included the escape return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $str); } } if (strpos($item, '.') !== FALSE) { $str = $this->_escape_char.str_replace('.', $this->_escape_char.'.'.$this->_escape_char, $item).$this->_escape_char; } else { $str = $this->_escape_char.$item.$this->_escape_char; } // remove duplicates if the user already included the escape return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $str); } // -------------------------------------------------------------------- /** * From Tables * * This function implicitly groups FROM tables so there is no confusion * about operator precedence in harmony with SQL standards * * @access public * @param type * @return type */ function _from_tables($tables) { if ( ! is_array($tables)) { $tables = array($tables); } return '('.implode(', ', $tables).')'; } // -------------------------------------------------------------------- /** * Insert statement * * Generates a platform-specific insert string from the supplied data * * @access public * @param string the table name * @param array the insert keys * @param array the insert values * @return string */ function _insert($table, $keys, $values) { return "INSERT INTO ".$table." (".implode(', ', $keys).") VALUES (".implode(', ', $values).")"; } // -------------------------------------------------------------------- /** * Replace statement * * Generates a platform-specific replace string from the supplied data * * @access public * @param string the table name * @param array the insert keys * @param array the insert values * @return string */ function _replace($table, $keys, $values) { return "REPLACE INTO ".$table." (".implode(', ', $keys).") VALUES (".implode(', ', $values).")"; } // -------------------------------------------------------------------- /** * Insert_batch statement * * Generates a platform-specific insert string from the supplied data * * @access public * @param string the table name * @param array the insert keys * @param array the insert values * @return string */ function _insert_batch($table, $keys, $values) { return "INSERT INTO ".$table." (".implode(', ', $keys).") VALUES ".implode(', ', $values); } // -------------------------------------------------------------------- /** * Update statement * * Generates a platform-specific update string from the supplied data * * @access public * @param string the table name * @param array the update data * @param array the where clause * @param array the orderby clause * @param array the limit clause * @return string */ function _update($table, $values, $where, $orderby = array(), $limit = FALSE) { foreach ($values as $key => $val) { $valstr[] = $key . ' = ' . $val; } $limit = ( ! $limit) ? '' : ' LIMIT '.$limit; $orderby = (count($orderby) >= 1)?' ORDER BY '.implode(", ", $orderby):''; $sql = "UPDATE ".$table." SET ".implode(', ', $valstr); $sql .= ($where != '' AND count($where) >=1) ? " WHERE ".implode(" ", $where) : ''; $sql .= $orderby.$limit; return $sql; } // -------------------------------------------------------------------- /** * Update_Batch statement * * Generates a platform-specific batch update string from the supplied data * * @access public * @param string the table name * @param array the update data * @param array the where clause * @return string */ function _update_batch($table, $values, $index, $where = NULL) { $ids = array(); $where = ($where != '' AND count($where) >=1) ? implode(" ", $where).' AND ' : ''; foreach ($values as $key => $val) { $ids[] = $val[$index]; foreach (array_keys($val) as $field) { if ($field != $index) { $final[$field][] = 'WHEN '.$index.' = '.$val[$index].' THEN '.$val[$field]; } } } $sql = "UPDATE ".$table." SET "; $cases = ''; foreach ($final as $k => $v) { $cases .= $k.' = CASE '."\n"; foreach ($v as $row) { $cases .= $row."\n"; } $cases .= 'ELSE '.$k.' END, '; } $sql .= substr($cases, 0, -2); $sql .= ' WHERE '.$where.$index.' IN ('.implode(',', $ids).')'; return $sql; } // -------------------------------------------------------------------- /** * Truncate statement * * Generates a platform-specific truncate string from the supplied data * If the database does not support the truncate() command * This function maps to "DELETE FROM table" * * @access public * @param string the table name * @return string */ function _truncate($table) { return "TRUNCATE ".$table; } // -------------------------------------------------------------------- /** * Delete statement * * Generates a platform-specific delete string from the supplied data * * @access public * @param string the table name * @param array the where clause * @param string the limit clause * @return string */ function _delete($table, $where = array(), $like = array(), $limit = FALSE) { $conditions = ''; if (count($where) > 0 OR count($like) > 0) { $conditions = "\nWHERE "; $conditions .= implode("\n", $this->ar_where); if (count($where) > 0 && count($like) > 0) { $conditions .= " AND "; } $conditions .= implode("\n", $like); } $limit = ( ! $limit) ? '' : ' LIMIT '.$limit; return "DELETE FROM ".$table.$conditions.$limit; } // -------------------------------------------------------------------- /** * Limit string * * Generates a platform-specific LIMIT clause * * @access public * @param string the sql query string * @param integer the number of rows to limit the query to * @param integer the offset value * @return string */ function _limit($sql, $limit, $offset) { if ($offset == 0) { $offset = ''; } else { $offset .= ", "; } return $sql."LIMIT ".$offset.$limit; } // -------------------------------------------------------------------- /** * Close DB Connection * * @access public * @param resource * @return void */ function _close($conn_id) { @mysql_close($conn_id); } } /* End of file mysql_driver.php */ /* Location: ./system/database/drivers/mysql/mysql_driver.php */
101-code
system/database/drivers/mysql/mysql_driver.php
PHP
gpl3
17,371
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // -------------------------------------------------------------------- /** * MySQL Result Class * * This class extends the parent result class: CI_DB_result * * @category Database * @author ExpressionEngine Dev Team * @link http://codeigniter.com/user_guide/database/ */ class CI_DB_mysql_result extends CI_DB_result { /** * Number of rows in the result set * * @access public * @return integer */ function num_rows() { return @mysql_num_rows($this->result_id); } // -------------------------------------------------------------------- /** * Number of fields in the result set * * @access public * @return integer */ function num_fields() { return @mysql_num_fields($this->result_id); } // -------------------------------------------------------------------- /** * Fetch Field Names * * Generates an array of column names * * @access public * @return array */ function list_fields() { $field_names = array(); while ($field = mysql_fetch_field($this->result_id)) { $field_names[] = $field->name; } return $field_names; } // -------------------------------------------------------------------- /** * Field data * * Generates an array of objects containing field meta-data * * @access public * @return array */ function field_data() { $retval = array(); while ($field = mysql_fetch_object($this->result_id)) { preg_match('/([a-zA-Z]+)(\(\d+\))?/', $field->Type, $matches); $type = (array_key_exists(1, $matches)) ? $matches[1] : NULL; $length = (array_key_exists(2, $matches)) ? preg_replace('/[^\d]/', '', $matches[2]) : NULL; $F = new stdClass(); $F->name = $field->Field; $F->type = $type; $F->default = $field->Default; $F->max_length = $length; $F->primary_key = ( $field->Key == 'PRI' ? 1 : 0 ); $retval[] = $F; } return $retval; } // -------------------------------------------------------------------- /** * Free the result * * @return null */ function free_result() { if (is_resource($this->result_id)) { mysql_free_result($this->result_id); $this->result_id = FALSE; } } // -------------------------------------------------------------------- /** * Data Seek * * Moves the internal pointer to the desired offset. We call * this internally before fetching results to make sure the * result set starts at zero * * @access private * @return array */ function _data_seek($n = 0) { return mysql_data_seek($this->result_id, $n); } // -------------------------------------------------------------------- /** * Result - associative array * * Returns the result set as an array * * @access private * @return array */ function _fetch_assoc() { return mysql_fetch_assoc($this->result_id); } // -------------------------------------------------------------------- /** * Result - object * * Returns the result set as an object * * @access private * @return object */ function _fetch_object() { return mysql_fetch_object($this->result_id); } } /* End of file mysql_result.php */ /* Location: ./system/database/drivers/mysql/mysql_result.php */
101-code
system/database/drivers/mysql/mysql_result.php
PHP
gpl3
3,625
<html> <head> <title>403 Forbidden</title> </head> <body> <p>Directory access is forbidden.</p> </body> </html>
101-code
system/database/drivers/mysql/index.html
HTML
gpl3
114
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // ------------------------------------------------------------------------ /** * MySQLi Forge Class * * @category Database * @author ExpressionEngine Dev Team * @link http://codeigniter.com/user_guide/database/ */ class CI_DB_mysqli_forge extends CI_DB_forge { /** * Create database * * @access private * @param string the database name * @return bool */ function _create_database($name) { return "CREATE DATABASE ".$name; } // -------------------------------------------------------------------- /** * Drop database * * @access private * @param string the database name * @return bool */ function _drop_database($name) { return "DROP DATABASE ".$name; } // -------------------------------------------------------------------- /** * Process Fields * * @access private * @param mixed the fields * @return string */ function _process_fields($fields) { $current_field_count = 0; $sql = ''; foreach ($fields as $field=>$attributes) { // Numeric field names aren't allowed in databases, so if the key is // numeric, we know it was assigned by PHP and the developer manually // entered the field information, so we'll simply add it to the list if (is_numeric($field)) { $sql .= "\n\t$attributes"; } else { $attributes = array_change_key_case($attributes, CASE_UPPER); $sql .= "\n\t".$this->db->_protect_identifiers($field); if (array_key_exists('NAME', $attributes)) { $sql .= ' '.$this->db->_protect_identifiers($attributes['NAME']).' '; } if (array_key_exists('TYPE', $attributes)) { $sql .= ' '.$attributes['TYPE']; } if (array_key_exists('CONSTRAINT', $attributes)) { $sql .= '('.$attributes['CONSTRAINT'].')'; } if (array_key_exists('UNSIGNED', $attributes) && $attributes['UNSIGNED'] === TRUE) { $sql .= ' UNSIGNED'; } if (array_key_exists('DEFAULT', $attributes)) { $sql .= ' DEFAULT \''.$attributes['DEFAULT'].'\''; } if (array_key_exists('NULL', $attributes) && $attributes['NULL'] === TRUE) { $sql .= ' NULL'; } else { $sql .= ' NOT NULL'; } if (array_key_exists('AUTO_INCREMENT', $attributes) && $attributes['AUTO_INCREMENT'] === TRUE) { $sql .= ' AUTO_INCREMENT'; } } // don't add a comma on the end of the last field if (++$current_field_count < count($fields)) { $sql .= ','; } } return $sql; } // -------------------------------------------------------------------- /** * Create Table * * @access private * @param string the table name * @param mixed the fields * @param mixed primary key(s) * @param mixed key(s) * @param boolean should 'IF NOT EXISTS' be added to the SQL * @return bool */ function _create_table($table, $fields, $primary_keys, $keys, $if_not_exists) { $sql = 'CREATE TABLE '; if ($if_not_exists === TRUE) { $sql .= 'IF NOT EXISTS '; } $sql .= $this->db->_escape_identifiers($table)." ("; $sql .= $this->_process_fields($fields); if (count($primary_keys) > 0) { $key_name = $this->db->_protect_identifiers(implode('_', $primary_keys)); $primary_keys = $this->db->_protect_identifiers($primary_keys); $sql .= ",\n\tPRIMARY KEY ".$key_name." (" . implode(', ', $primary_keys) . ")"; } if (is_array($keys) && count($keys) > 0) { foreach ($keys as $key) { if (is_array($key)) { $key_name = $this->db->_protect_identifiers(implode('_', $key)); $key = $this->db->_protect_identifiers($key); } else { $key_name = $this->db->_protect_identifiers($key); $key = array($key_name); } $sql .= ",\n\tKEY {$key_name} (" . implode(', ', $key) . ")"; } } $sql .= "\n) DEFAULT CHARACTER SET {$this->db->char_set} COLLATE {$this->db->dbcollat};"; return $sql; } // -------------------------------------------------------------------- /** * Drop Table * * @access private * @return string */ function _drop_table($table) { return "DROP TABLE IF EXISTS ".$this->db->_escape_identifiers($table); } // -------------------------------------------------------------------- /** * Alter table query * * Generates a platform-specific query so that a table can be altered * Called by add_column(), drop_column(), and column_alter(), * * @access private * @param string the ALTER type (ADD, DROP, CHANGE) * @param string the column name * @param array fields * @param string the field after which we should add the new field * @return object */ function _alter_table($alter_type, $table, $fields, $after_field = '') { $sql = 'ALTER TABLE '.$this->db->_protect_identifiers($table)." $alter_type "; // DROP has everything it needs now. if ($alter_type == 'DROP') { return $sql.$this->db->_protect_identifiers($fields); } $sql .= $this->_process_fields($fields); if ($after_field != '') { $sql .= ' AFTER ' . $this->db->_protect_identifiers($after_field); } return $sql; } // -------------------------------------------------------------------- /** * Rename a table * * Generates a platform-specific query so that a table can be renamed * * @access private * @param string the old table name * @param string the new table name * @return string */ function _rename_table($table_name, $new_table_name) { $sql = 'ALTER TABLE '.$this->db->_protect_identifiers($table_name)." RENAME TO ".$this->db->_protect_identifiers($new_table_name); return $sql; } } /* End of file mysqli_forge.php */ /* Location: ./system/database/drivers/mysqli/mysqli_forge.php */
101-code
system/database/drivers/mysqli/mysqli_forge.php
PHP
gpl3
6,103
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // ------------------------------------------------------------------------ /** * MySQLi Utility Class * * @category Database * @author ExpressionEngine Dev Team * @link http://codeigniter.com/user_guide/database/ */ class CI_DB_mysqli_utility extends CI_DB_utility { /** * List databases * * @access private * @return bool */ function _list_databases() { return "SHOW DATABASES"; } // -------------------------------------------------------------------- /** * Optimize table query * * Generates a platform-specific query so that a table can be optimized * * @access private * @param string the table name * @return object */ function _optimize_table($table) { return "OPTIMIZE TABLE ".$this->db->_escape_identifiers($table); } // -------------------------------------------------------------------- /** * Repair table query * * Generates a platform-specific query so that a table can be repaired * * @access private * @param string the table name * @return object */ function _repair_table($table) { return "REPAIR TABLE ".$this->db->_escape_identifiers($table); } // -------------------------------------------------------------------- /** * MySQLi Export * * @access private * @param array Preferences * @return mixed */ function _backup($params = array()) { // Currently unsupported return $this->db->display_error('db_unsuported_feature'); } } /* End of file mysqli_utility.php */ /* Location: ./system/database/drivers/mysqli/mysqli_utility.php */
101-code
system/database/drivers/mysqli/mysqli_utility.php
PHP
gpl3
1,984
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // ------------------------------------------------------------------------ /** * MySQLi Database Adapter Class - MySQLi only works with PHP 5 * * Note: _DB is an extender class that the app controller * creates dynamically based on whether the active record * class is being used or not. * * @package CodeIgniter * @subpackage Drivers * @category Database * @author ExpressionEngine Dev Team * @link http://codeigniter.com/user_guide/database/ */ class CI_DB_mysqli_driver extends CI_DB { var $dbdriver = 'mysqli'; // The character used for escaping var $_escape_char = '`'; // clause and character used for LIKE escape sequences - not used in MySQL var $_like_escape_str = ''; var $_like_escape_chr = ''; /** * The syntax to count rows is slightly different across different * database engines, so this string appears in each driver and is * used for the count_all() and count_all_results() functions. */ var $_count_string = "SELECT COUNT(*) AS "; var $_random_keyword = ' RAND()'; // database specific random keyword /** * Whether to use the MySQL "delete hack" which allows the number * of affected rows to be shown. Uses a preg_replace when enabled, * adding a bit more processing to all queries. */ var $delete_hack = TRUE; // whether SET NAMES must be used to set the character set var $use_set_names; // -------------------------------------------------------------------- /** * Non-persistent database connection * * @access private called by the base class * @return resource */ function db_connect() { if ($this->port != '') { return @mysqli_connect($this->hostname, $this->username, $this->password, $this->database, $this->port); } else { return @mysqli_connect($this->hostname, $this->username, $this->password, $this->database); } } // -------------------------------------------------------------------- /** * Persistent database connection * * @access private called by the base class * @return resource */ function db_pconnect() { return $this->db_connect(); } // -------------------------------------------------------------------- /** * Reconnect * * Keep / reestablish the db connection if no queries have been * sent for a length of time exceeding the server's idle timeout * * @access public * @return void */ function reconnect() { if (mysqli_ping($this->conn_id) === FALSE) { $this->conn_id = FALSE; } } // -------------------------------------------------------------------- /** * Select the database * * @access private called by the base class * @return resource */ function db_select() { return @mysqli_select_db($this->conn_id, $this->database); } // -------------------------------------------------------------------- /** * Set client character set * * @access private * @param string * @param string * @return resource */ function _db_set_charset($charset, $collation) { if ( ! isset($this->use_set_names)) { // mysqli_set_charset() requires MySQL >= 5.0.7, use SET NAMES as fallback $this->use_set_names = (version_compare(mysqli_get_server_info($this->conn_id), '5.0.7', '>=')) ? FALSE : TRUE; } if ($this->use_set_names === TRUE) { return @mysqli_query($this->conn_id, "SET NAMES '".$this->escape_str($charset)."' COLLATE '".$this->escape_str($collation)."'"); } else { return @mysqli_set_charset($this->conn_id, $charset); } } // -------------------------------------------------------------------- /** * Version number query string * * @access public * @return string */ function _version() { return "SELECT version() AS ver"; } // -------------------------------------------------------------------- /** * Execute the query * * @access private called by the base class * @param string an SQL query * @return resource */ function _execute($sql) { $sql = $this->_prep_query($sql); $result = @mysqli_query($this->conn_id, $sql); return $result; } // -------------------------------------------------------------------- /** * Prep the query * * If needed, each database adapter can prep the query string * * @access private called by execute() * @param string an SQL query * @return string */ function _prep_query($sql) { // "DELETE FROM TABLE" returns 0 affected rows This hack modifies // the query so that it returns the number of affected rows if ($this->delete_hack === TRUE) { if (preg_match('/^\s*DELETE\s+FROM\s+(\S+)\s*$/i', $sql)) { $sql = preg_replace("/^\s*DELETE\s+FROM\s+(\S+)\s*$/", "DELETE FROM \\1 WHERE 1=1", $sql); } } return $sql; } // -------------------------------------------------------------------- /** * Begin Transaction * * @access public * @return bool */ function trans_begin($test_mode = FALSE) { if ( ! $this->trans_enabled) { return TRUE; } // When transactions are nested we only begin/commit/rollback the outermost ones if ($this->_trans_depth > 0) { return TRUE; } // Reset the transaction failure flag. // If the $test_mode flag is set to TRUE transactions will be rolled back // even if the queries produce a successful result. $this->_trans_failure = ($test_mode === TRUE) ? TRUE : FALSE; $this->simple_query('SET AUTOCOMMIT=0'); $this->simple_query('START TRANSACTION'); // can also be BEGIN or BEGIN WORK return TRUE; } // -------------------------------------------------------------------- /** * Commit Transaction * * @access public * @return bool */ function trans_commit() { if ( ! $this->trans_enabled) { return TRUE; } // When transactions are nested we only begin/commit/rollback the outermost ones if ($this->_trans_depth > 0) { return TRUE; } $this->simple_query('COMMIT'); $this->simple_query('SET AUTOCOMMIT=1'); return TRUE; } // -------------------------------------------------------------------- /** * Rollback Transaction * * @access public * @return bool */ function trans_rollback() { if ( ! $this->trans_enabled) { return TRUE; } // When transactions are nested we only begin/commit/rollback the outermost ones if ($this->_trans_depth > 0) { return TRUE; } $this->simple_query('ROLLBACK'); $this->simple_query('SET AUTOCOMMIT=1'); return TRUE; } // -------------------------------------------------------------------- /** * Escape String * * @access public * @param string * @param bool whether or not the string will be used in a LIKE condition * @return string */ function escape_str($str, $like = FALSE) { if (is_array($str)) { foreach ($str as $key => $val) { $str[$key] = $this->escape_str($val, $like); } return $str; } if (function_exists('mysqli_real_escape_string') AND is_object($this->conn_id)) { $str = mysqli_real_escape_string($this->conn_id, $str); } elseif (function_exists('mysql_escape_string')) { $str = mysql_escape_string($str); } else { $str = addslashes($str); } // escape LIKE condition wildcards if ($like === TRUE) { $str = str_replace(array('%', '_'), array('\\%', '\\_'), $str); } return $str; } // -------------------------------------------------------------------- /** * Affected Rows * * @access public * @return integer */ function affected_rows() { return @mysqli_affected_rows($this->conn_id); } // -------------------------------------------------------------------- /** * Insert ID * * @access public * @return integer */ function insert_id() { return @mysqli_insert_id($this->conn_id); } // -------------------------------------------------------------------- /** * "Count All" query * * Generates a platform-specific query string that counts all records in * the specified database * * @access public * @param string * @return string */ function count_all($table = '') { if ($table == '') { return 0; } $query = $this->query($this->_count_string . $this->_protect_identifiers('numrows') . " FROM " . $this->_protect_identifiers($table, TRUE, NULL, FALSE)); if ($query->num_rows() == 0) { return 0; } $row = $query->row(); $this->_reset_select(); return (int) $row->numrows; } // -------------------------------------------------------------------- /** * List table query * * Generates a platform-specific query string so that the table names can be fetched * * @access private * @param boolean * @return string */ function _list_tables($prefix_limit = FALSE) { $sql = "SHOW TABLES FROM ".$this->_escape_char.$this->database.$this->_escape_char; if ($prefix_limit !== FALSE AND $this->dbprefix != '') { $sql .= " LIKE '".$this->escape_like_str($this->dbprefix)."%'"; } return $sql; } // -------------------------------------------------------------------- /** * Show column query * * Generates a platform-specific query string so that the column names can be fetched * * @access public * @param string the table name * @return string */ function _list_columns($table = '') { return "SHOW COLUMNS FROM ".$this->_protect_identifiers($table, TRUE, NULL, FALSE); } // -------------------------------------------------------------------- /** * Field data query * * Generates a platform-specific query so that the column data can be retrieved * * @access public * @param string the table name * @return object */ function _field_data($table) { return "DESCRIBE ".$table; } // -------------------------------------------------------------------- /** * The error message string * * @access private * @return string */ function _error_message() { return mysqli_error($this->conn_id); } // -------------------------------------------------------------------- /** * The error message number * * @access private * @return integer */ function _error_number() { return mysqli_errno($this->conn_id); } // -------------------------------------------------------------------- /** * Escape the SQL Identifiers * * This function escapes column and table names * * @access private * @param string * @return string */ function _escape_identifiers($item) { if ($this->_escape_char == '') { return $item; } foreach ($this->_reserved_identifiers as $id) { if (strpos($item, '.'.$id) !== FALSE) { $str = $this->_escape_char. str_replace('.', $this->_escape_char.'.', $item); // remove duplicates if the user already included the escape return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $str); } } if (strpos($item, '.') !== FALSE) { $str = $this->_escape_char.str_replace('.', $this->_escape_char.'.'.$this->_escape_char, $item).$this->_escape_char; } else { $str = $this->_escape_char.$item.$this->_escape_char; } // remove duplicates if the user already included the escape return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $str); } // -------------------------------------------------------------------- /** * From Tables * * This function implicitly groups FROM tables so there is no confusion * about operator precedence in harmony with SQL standards * * @access public * @param type * @return type */ function _from_tables($tables) { if ( ! is_array($tables)) { $tables = array($tables); } return '('.implode(', ', $tables).')'; } // -------------------------------------------------------------------- /** * Insert statement * * Generates a platform-specific insert string from the supplied data * * @access public * @param string the table name * @param array the insert keys * @param array the insert values * @return string */ function _insert($table, $keys, $values) { return "INSERT INTO ".$table." (".implode(', ', $keys).") VALUES (".implode(', ', $values).")"; } // -------------------------------------------------------------------- /** * Insert_batch statement * * Generates a platform-specific insert string from the supplied data * * @access public * @param string the table name * @param array the insert keys * @param array the insert values * @return string */ function _insert_batch($table, $keys, $values) { return "INSERT INTO ".$table." (".implode(', ', $keys).") VALUES ".implode(', ', $values); } // -------------------------------------------------------------------- /** * Replace statement * * Generates a platform-specific replace string from the supplied data * * @access public * @param string the table name * @param array the insert keys * @param array the insert values * @return string */ function _replace($table, $keys, $values) { return "REPLACE INTO ".$table." (".implode(', ', $keys).") VALUES (".implode(', ', $values).")"; } // -------------------------------------------------------------------- /** * Update statement * * Generates a platform-specific update string from the supplied data * * @access public * @param string the table name * @param array the update data * @param array the where clause * @param array the orderby clause * @param array the limit clause * @return string */ function _update($table, $values, $where, $orderby = array(), $limit = FALSE) { foreach ($values as $key => $val) { $valstr[] = $key." = ".$val; } $limit = ( ! $limit) ? '' : ' LIMIT '.$limit; $orderby = (count($orderby) >= 1)?' ORDER BY '.implode(", ", $orderby):''; $sql = "UPDATE ".$table." SET ".implode(', ', $valstr); $sql .= ($where != '' AND count($where) >=1) ? " WHERE ".implode(" ", $where) : ''; $sql .= $orderby.$limit; return $sql; } // -------------------------------------------------------------------- /** * Update_Batch statement * * Generates a platform-specific batch update string from the supplied data * * @access public * @param string the table name * @param array the update data * @param array the where clause * @return string */ function _update_batch($table, $values, $index, $where = NULL) { $ids = array(); $where = ($where != '' AND count($where) >=1) ? implode(" ", $where).' AND ' : ''; foreach ($values as $key => $val) { $ids[] = $val[$index]; foreach (array_keys($val) as $field) { if ($field != $index) { $final[$field][] = 'WHEN '.$index.' = '.$val[$index].' THEN '.$val[$field]; } } } $sql = "UPDATE ".$table." SET "; $cases = ''; foreach ($final as $k => $v) { $cases .= $k.' = CASE '."\n"; foreach ($v as $row) { $cases .= $row."\n"; } $cases .= 'ELSE '.$k.' END, '; } $sql .= substr($cases, 0, -2); $sql .= ' WHERE '.$where.$index.' IN ('.implode(',', $ids).')'; return $sql; } // -------------------------------------------------------------------- /** * Truncate statement * * Generates a platform-specific truncate string from the supplied data * If the database does not support the truncate() command * This function maps to "DELETE FROM table" * * @access public * @param string the table name * @return string */ function _truncate($table) { return "TRUNCATE ".$table; } // -------------------------------------------------------------------- /** * Delete statement * * Generates a platform-specific delete string from the supplied data * * @access public * @param string the table name * @param array the where clause * @param string the limit clause * @return string */ function _delete($table, $where = array(), $like = array(), $limit = FALSE) { $conditions = ''; if (count($where) > 0 OR count($like) > 0) { $conditions = "\nWHERE "; $conditions .= implode("\n", $this->ar_where); if (count($where) > 0 && count($like) > 0) { $conditions .= " AND "; } $conditions .= implode("\n", $like); } $limit = ( ! $limit) ? '' : ' LIMIT '.$limit; return "DELETE FROM ".$table.$conditions.$limit; } // -------------------------------------------------------------------- /** * Limit string * * Generates a platform-specific LIMIT clause * * @access public * @param string the sql query string * @param integer the number of rows to limit the query to * @param integer the offset value * @return string */ function _limit($sql, $limit, $offset) { $sql .= "LIMIT ".$limit; if ($offset > 0) { $sql .= " OFFSET ".$offset; } return $sql; } // -------------------------------------------------------------------- /** * Close DB Connection * * @access public * @param resource * @return void */ function _close($conn_id) { @mysqli_close($conn_id); } } /* End of file mysqli_driver.php */ /* Location: ./system/database/drivers/mysqli/mysqli_driver.php */
101-code
system/database/drivers/mysqli/mysqli_driver.php
PHP
gpl3
17,409
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // ------------------------------------------------------------------------ /** * MySQLi Result Class * * This class extends the parent result class: CI_DB_result * * @category Database * @author ExpressionEngine Dev Team * @link http://codeigniter.com/user_guide/database/ */ class CI_DB_mysqli_result extends CI_DB_result { /** * Number of rows in the result set * * @access public * @return integer */ function num_rows() { return @mysqli_num_rows($this->result_id); } // -------------------------------------------------------------------- /** * Number of fields in the result set * * @access public * @return integer */ function num_fields() { return @mysqli_num_fields($this->result_id); } // -------------------------------------------------------------------- /** * Fetch Field Names * * Generates an array of column names * * @access public * @return array */ function list_fields() { $field_names = array(); while ($field = mysqli_fetch_field($this->result_id)) { $field_names[] = $field->name; } return $field_names; } // -------------------------------------------------------------------- /** * Field data * * Generates an array of objects containing field meta-data * * @access public * @return array */ function field_data() { $retval = array(); while ($field = mysqli_fetch_object($this->result_id)) { preg_match('/([a-zA-Z]+)(\(\d+\))?/', $field->Type, $matches); $type = (array_key_exists(1, $matches)) ? $matches[1] : NULL; $length = (array_key_exists(2, $matches)) ? preg_replace('/[^\d]/', '', $matches[2]) : NULL; $F = new stdClass(); $F->name = $field->Field; $F->type = $type; $F->default = $field->Default; $F->max_length = $length; $F->primary_key = ( $field->Key == 'PRI' ? 1 : 0 ); $retval[] = $F; } return $retval; } // -------------------------------------------------------------------- /** * Free the result * * @return null */ function free_result() { if (is_object($this->result_id)) { mysqli_free_result($this->result_id); $this->result_id = FALSE; } } // -------------------------------------------------------------------- /** * Data Seek * * Moves the internal pointer to the desired offset. We call * this internally before fetching results to make sure the * result set starts at zero * * @access private * @return array */ function _data_seek($n = 0) { return mysqli_data_seek($this->result_id, $n); } // -------------------------------------------------------------------- /** * Result - associative array * * Returns the result set as an array * * @access private * @return array */ function _fetch_assoc() { return mysqli_fetch_assoc($this->result_id); } // -------------------------------------------------------------------- /** * Result - object * * Returns the result set as an object * * @access private * @return object */ function _fetch_object() { return mysqli_fetch_object($this->result_id); } } /* End of file mysqli_result.php */ /* Location: ./system/database/drivers/mysqli/mysqli_result.php */
101-code
system/database/drivers/mysqli/mysqli_result.php
PHP
gpl3
3,641
<html> <head> <title>403 Forbidden</title> </head> <body> <p>Directory access is forbidden.</p> </body> </html>
101-code
system/database/drivers/mysqli/index.html
HTML
gpl3
114
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // ------------------------------------------------------------------------ /** * SQLite Database Adapter Class * * Note: _DB is an extender class that the app controller * creates dynamically based on whether the active record * class is being used or not. * * @package CodeIgniter * @subpackage Drivers * @category Database * @author ExpressionEngine Dev Team * @link http://codeigniter.com/user_guide/database/ */ class CI_DB_sqlite_driver extends CI_DB { var $dbdriver = 'sqlite'; // The character used to escape with - not needed for SQLite var $_escape_char = ''; // clause and character used for LIKE escape sequences var $_like_escape_str = " ESCAPE '%s' "; var $_like_escape_chr = '!'; /** * The syntax to count rows is slightly different across different * database engines, so this string appears in each driver and is * used for the count_all() and count_all_results() functions. */ var $_count_string = "SELECT COUNT(*) AS "; var $_random_keyword = ' Random()'; // database specific random keyword /** * Non-persistent database connection * * @access private called by the base class * @return resource */ function db_connect() { if ( ! $conn_id = @sqlite_open($this->database, FILE_WRITE_MODE, $error)) { log_message('error', $error); if ($this->db_debug) { $this->display_error($error, '', TRUE); } return FALSE; } return $conn_id; } // -------------------------------------------------------------------- /** * Persistent database connection * * @access private called by the base class * @return resource */ function db_pconnect() { if ( ! $conn_id = @sqlite_popen($this->database, FILE_WRITE_MODE, $error)) { log_message('error', $error); if ($this->db_debug) { $this->display_error($error, '', TRUE); } return FALSE; } return $conn_id; } // -------------------------------------------------------------------- /** * Reconnect * * Keep / reestablish the db connection if no queries have been * sent for a length of time exceeding the server's idle timeout * * @access public * @return void */ function reconnect() { // not implemented in SQLite } // -------------------------------------------------------------------- /** * Select the database * * @access private called by the base class * @return resource */ function db_select() { return TRUE; } // -------------------------------------------------------------------- /** * Set client character set * * @access public * @param string * @param string * @return resource */ function db_set_charset($charset, $collation) { // @todo - add support if needed return TRUE; } // -------------------------------------------------------------------- /** * Version number query string * * @access public * @return string */ function _version() { return sqlite_libversion(); } // -------------------------------------------------------------------- /** * Execute the query * * @access private called by the base class * @param string an SQL query * @return resource */ function _execute($sql) { $sql = $this->_prep_query($sql); return @sqlite_query($this->conn_id, $sql); } // -------------------------------------------------------------------- /** * Prep the query * * If needed, each database adapter can prep the query string * * @access private called by execute() * @param string an SQL query * @return string */ function _prep_query($sql) { return $sql; } // -------------------------------------------------------------------- /** * Begin Transaction * * @access public * @return bool */ function trans_begin($test_mode = FALSE) { if ( ! $this->trans_enabled) { return TRUE; } // When transactions are nested we only begin/commit/rollback the outermost ones if ($this->_trans_depth > 0) { return TRUE; } // Reset the transaction failure flag. // If the $test_mode flag is set to TRUE transactions will be rolled back // even if the queries produce a successful result. $this->_trans_failure = ($test_mode === TRUE) ? TRUE : FALSE; $this->simple_query('BEGIN TRANSACTION'); return TRUE; } // -------------------------------------------------------------------- /** * Commit Transaction * * @access public * @return bool */ function trans_commit() { if ( ! $this->trans_enabled) { return TRUE; } // When transactions are nested we only begin/commit/rollback the outermost ones if ($this->_trans_depth > 0) { return TRUE; } $this->simple_query('COMMIT'); return TRUE; } // -------------------------------------------------------------------- /** * Rollback Transaction * * @access public * @return bool */ function trans_rollback() { if ( ! $this->trans_enabled) { return TRUE; } // When transactions are nested we only begin/commit/rollback the outermost ones if ($this->_trans_depth > 0) { return TRUE; } $this->simple_query('ROLLBACK'); return TRUE; } // -------------------------------------------------------------------- /** * Escape String * * @access public * @param string * @param bool whether or not the string will be used in a LIKE condition * @return string */ function escape_str($str, $like = FALSE) { if (is_array($str)) { foreach ($str as $key => $val) { $str[$key] = $this->escape_str($val, $like); } return $str; } $str = sqlite_escape_string($str); // escape LIKE condition wildcards if ($like === TRUE) { $str = str_replace( array('%', '_', $this->_like_escape_chr), array($this->_like_escape_chr.'%', $this->_like_escape_chr.'_', $this->_like_escape_chr.$this->_like_escape_chr), $str); } return $str; } // -------------------------------------------------------------------- /** * Affected Rows * * @access public * @return integer */ function affected_rows() { return sqlite_changes($this->conn_id); } // -------------------------------------------------------------------- /** * Insert ID * * @access public * @return integer */ function insert_id() { return @sqlite_last_insert_rowid($this->conn_id); } // -------------------------------------------------------------------- /** * "Count All" query * * Generates a platform-specific query string that counts all records in * the specified database * * @access public * @param string * @return string */ function count_all($table = '') { if ($table == '') { return 0; } $query = $this->query($this->_count_string . $this->_protect_identifiers('numrows') . " FROM " . $this->_protect_identifiers($table, TRUE, NULL, FALSE)); if ($query->num_rows() == 0) { return 0; } $row = $query->row(); $this->_reset_select(); return (int) $row->numrows; } // -------------------------------------------------------------------- /** * List table query * * Generates a platform-specific query string so that the table names can be fetched * * @access private * @param boolean * @return string */ function _list_tables($prefix_limit = FALSE) { $sql = "SELECT name from sqlite_master WHERE type='table'"; if ($prefix_limit !== FALSE AND $this->dbprefix != '') { $sql .= " AND 'name' LIKE '".$this->escape_like_str($this->dbprefix)."%' ".sprintf($this->_like_escape_str, $this->_like_escape_chr); } return $sql; } // -------------------------------------------------------------------- /** * Show column query * * Generates a platform-specific query string so that the column names can be fetched * * @access public * @param string the table name * @return string */ function _list_columns($table = '') { // Not supported return FALSE; } // -------------------------------------------------------------------- /** * Field data query * * Generates a platform-specific query so that the column data can be retrieved * * @access public * @param string the table name * @return object */ function _field_data($table) { return "SELECT * FROM ".$table." LIMIT 1"; } // -------------------------------------------------------------------- /** * The error message string * * @access private * @return string */ function _error_message() { return sqlite_error_string(sqlite_last_error($this->conn_id)); } // -------------------------------------------------------------------- /** * The error message number * * @access private * @return integer */ function _error_number() { return sqlite_last_error($this->conn_id); } // -------------------------------------------------------------------- /** * Escape the SQL Identifiers * * This function escapes column and table names * * @access private * @param string * @return string */ function _escape_identifiers($item) { if ($this->_escape_char == '') { return $item; } foreach ($this->_reserved_identifiers as $id) { if (strpos($item, '.'.$id) !== FALSE) { $str = $this->_escape_char. str_replace('.', $this->_escape_char.'.', $item); // remove duplicates if the user already included the escape return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $str); } } if (strpos($item, '.') !== FALSE) { $str = $this->_escape_char.str_replace('.', $this->_escape_char.'.'.$this->_escape_char, $item).$this->_escape_char; } else { $str = $this->_escape_char.$item.$this->_escape_char; } // remove duplicates if the user already included the escape return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $str); } // -------------------------------------------------------------------- /** * From Tables * * This function implicitly groups FROM tables so there is no confusion * about operator precedence in harmony with SQL standards * * @access public * @param type * @return type */ function _from_tables($tables) { if ( ! is_array($tables)) { $tables = array($tables); } return '('.implode(', ', $tables).')'; } // -------------------------------------------------------------------- /** * Insert statement * * Generates a platform-specific insert string from the supplied data * * @access public * @param string the table name * @param array the insert keys * @param array the insert values * @return string */ function _insert($table, $keys, $values) { return "INSERT INTO ".$table." (".implode(', ', $keys).") VALUES (".implode(', ', $values).")"; } // -------------------------------------------------------------------- /** * Update statement * * Generates a platform-specific update string from the supplied data * * @access public * @param string the table name * @param array the update data * @param array the where clause * @param array the orderby clause * @param array the limit clause * @return string */ function _update($table, $values, $where, $orderby = array(), $limit = FALSE) { foreach ($values as $key => $val) { $valstr[] = $key." = ".$val; } $limit = ( ! $limit) ? '' : ' LIMIT '.$limit; $orderby = (count($orderby) >= 1)?' ORDER BY '.implode(", ", $orderby):''; $sql = "UPDATE ".$table." SET ".implode(', ', $valstr); $sql .= ($where != '' AND count($where) >=1) ? " WHERE ".implode(" ", $where) : ''; $sql .= $orderby.$limit; return $sql; } // -------------------------------------------------------------------- /** * Truncate statement * * Generates a platform-specific truncate string from the supplied data * If the database does not support the truncate() command * This function maps to "DELETE FROM table" * * @access public * @param string the table name * @return string */ function _truncate($table) { return $this->_delete($table); } // -------------------------------------------------------------------- /** * Delete statement * * Generates a platform-specific delete string from the supplied data * * @access public * @param string the table name * @param array the where clause * @param string the limit clause * @return string */ function _delete($table, $where = array(), $like = array(), $limit = FALSE) { $conditions = ''; if (count($where) > 0 OR count($like) > 0) { $conditions = "\nWHERE "; $conditions .= implode("\n", $this->ar_where); if (count($where) > 0 && count($like) > 0) { $conditions .= " AND "; } $conditions .= implode("\n", $like); } $limit = ( ! $limit) ? '' : ' LIMIT '.$limit; return "DELETE FROM ".$table.$conditions.$limit; } // -------------------------------------------------------------------- /** * Limit string * * Generates a platform-specific LIMIT clause * * @access public * @param string the sql query string * @param integer the number of rows to limit the query to * @param integer the offset value * @return string */ function _limit($sql, $limit, $offset) { if ($offset == 0) { $offset = ''; } else { $offset .= ", "; } return $sql."LIMIT ".$offset.$limit; } // -------------------------------------------------------------------- /** * Close DB Connection * * @access public * @param resource * @return void */ function _close($conn_id) { @sqlite_close($conn_id); } } /* End of file sqlite_driver.php */ /* Location: ./system/database/drivers/sqlite/sqlite_driver.php */
101-code
system/database/drivers/sqlite/sqlite_driver.php
PHP
gpl3
14,055
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // ------------------------------------------------------------------------ /** * SQLite Forge Class * * @category Database * @author ExpressionEngine Dev Team * @link http://codeigniter.com/user_guide/database/ */ class CI_DB_sqlite_forge extends CI_DB_forge { /** * Create database * * @access public * @param string the database name * @return bool */ function _create_database() { // In SQLite, a database is created when you connect to the database. // We'll return TRUE so that an error isn't generated return TRUE; } // -------------------------------------------------------------------- /** * Drop database * * @access private * @param string the database name * @return bool */ function _drop_database($name) { if ( ! @file_exists($this->db->database) OR ! @unlink($this->db->database)) { if ($this->db->db_debug) { return $this->db->display_error('db_unable_to_drop'); } return FALSE; } return TRUE; } // -------------------------------------------------------------------- /** * Create Table * * @access private * @param string the table name * @param array the fields * @param mixed primary key(s) * @param mixed key(s) * @param boolean should 'IF NOT EXISTS' be added to the SQL * @return bool */ function _create_table($table, $fields, $primary_keys, $keys, $if_not_exists) { $sql = 'CREATE TABLE '; // IF NOT EXISTS added to SQLite in 3.3.0 if ($if_not_exists === TRUE && version_compare($this->db->_version(), '3.3.0', '>=') === TRUE) { $sql .= 'IF NOT EXISTS '; } $sql .= $this->db->_escape_identifiers($table)."("; $current_field_count = 0; foreach ($fields as $field=>$attributes) { // Numeric field names aren't allowed in databases, so if the key is // numeric, we know it was assigned by PHP and the developer manually // entered the field information, so we'll simply add it to the list if (is_numeric($field)) { $sql .= "\n\t$attributes"; } else { $attributes = array_change_key_case($attributes, CASE_UPPER); $sql .= "\n\t".$this->db->_protect_identifiers($field); $sql .= ' '.$attributes['TYPE']; if (array_key_exists('CONSTRAINT', $attributes)) { $sql .= '('.$attributes['CONSTRAINT'].')'; } if (array_key_exists('UNSIGNED', $attributes) && $attributes['UNSIGNED'] === TRUE) { $sql .= ' UNSIGNED'; } if (array_key_exists('DEFAULT', $attributes)) { $sql .= ' DEFAULT \''.$attributes['DEFAULT'].'\''; } if (array_key_exists('NULL', $attributes) && $attributes['NULL'] === TRUE) { $sql .= ' NULL'; } else { $sql .= ' NOT NULL'; } if (array_key_exists('AUTO_INCREMENT', $attributes) && $attributes['AUTO_INCREMENT'] === TRUE) { $sql .= ' AUTO_INCREMENT'; } } // don't add a comma on the end of the last field if (++$current_field_count < count($fields)) { $sql .= ','; } } if (count($primary_keys) > 0) { $primary_keys = $this->db->_protect_identifiers($primary_keys); $sql .= ",\n\tPRIMARY KEY (" . implode(', ', $primary_keys) . ")"; } if (is_array($keys) && count($keys) > 0) { foreach ($keys as $key) { if (is_array($key)) { $key = $this->db->_protect_identifiers($key); } else { $key = array($this->db->_protect_identifiers($key)); } $sql .= ",\n\tUNIQUE (" . implode(', ', $key) . ")"; } } $sql .= "\n)"; return $sql; } // -------------------------------------------------------------------- /** * Drop Table * * Unsupported feature in SQLite * * @access private * @return bool */ function _drop_table($table) { if ($this->db->db_debug) { return $this->db->display_error('db_unsuported_feature'); } return array(); } // -------------------------------------------------------------------- /** * Alter table query * * Generates a platform-specific query so that a table can be altered * Called by add_column(), drop_column(), and column_alter(), * * @access private * @param string the ALTER type (ADD, DROP, CHANGE) * @param string the column name * @param string the table name * @param string the column definition * @param string the default value * @param boolean should 'NOT NULL' be added * @param string the field after which we should add the new field * @return object */ function _alter_table($alter_type, $table, $column_name, $column_definition = '', $default_value = '', $null = '', $after_field = '') { $sql = 'ALTER TABLE '.$this->db->_protect_identifiers($table)." $alter_type ".$this->db->_protect_identifiers($column_name); // DROP has everything it needs now. if ($alter_type == 'DROP') { // SQLite does not support dropping columns // http://www.sqlite.org/omitted.html // http://www.sqlite.org/faq.html#q11 return FALSE; } $sql .= " $column_definition"; if ($default_value != '') { $sql .= " DEFAULT \"$default_value\""; } if ($null === NULL) { $sql .= ' NULL'; } else { $sql .= ' NOT NULL'; } if ($after_field != '') { $sql .= ' AFTER ' . $this->db->_protect_identifiers($after_field); } return $sql; } // -------------------------------------------------------------------- /** * Rename a table * * Generates a platform-specific query so that a table can be renamed * * @access private * @param string the old table name * @param string the new table name * @return string */ function _rename_table($table_name, $new_table_name) { $sql = 'ALTER TABLE '.$this->db->_protect_identifiers($table_name)." RENAME TO ".$this->db->_protect_identifiers($new_table_name); return $sql; } } /* End of file sqlite_forge.php */ /* Location: ./system/database/drivers/sqlite/sqlite_forge.php */
101-code
system/database/drivers/sqlite/sqlite_forge.php
PHP
gpl3
6,303