From 60d2dc93e7093fb27084153e1aea3aeb768d83ec Mon Sep 17 00:00:00 2001 From: rvieras Date: Wed, 27 Nov 2013 12:43:55 -0500 Subject: [PATCH 01/12] Big Changes. Changed the CameraView class to better support tablets. Began combining the ARMarker Lib. with the default DroidAR Lib. Fixed project properties to only support API 9 or greater. Fixed issue were some devices would not display anything due to missing the ROTATION_VECTOR sensor or that data received had a accuracy of "Unreliable" for everything. Misc. syntax changes. --- droidar/.classpath | 4 +- droidar/AndroidManifest.xml | 2 +- droidar/project.properties | 4 +- .../actions/ActionRotateCameraBuffered.java | 49 ++++- droidar/src/actions/algos/SmoothingAlgo.java | 125 +++++++++++ .../de/rwth/setups/GraphCreationSetup.java | 4 +- droidar/src/gl/CustomGLSurfaceView.java | 3 +- droidar/src/gl/GLCamera.java | 40 ++-- droidar/src/gl/ObjectPicker.java | 2 +- .../src/listeners/FrameReceivedListener.java | 11 + droidar/src/logger/ARLogger.java | 84 ++++++++ droidar/src/preview/CameraPreview.java | 7 + droidar/src/preview/CameraView.java | 197 ++++++++++++++++++ droidar/src/system/CameraView.java | 159 -------------- .../src/system/CameraViewForOldDevices.java | 26 --- .../system/ConcreteSimpleLocationManager.java | 11 +- droidar/src/system/ErrorHandler.java | 12 +- droidar/src/system/EventManager.java | 57 +++-- droidar/src/system/FrameChangeThread.java | 185 ++++++++++++++++ droidar/src/system/Setup.java | 88 ++------ droidar/src/system/SimpleLocationManager.java | 34 ++- droidar/src/util/LimitedQueue.java | 7 + .../src/v2/simpleUi/util/ErrorHandler.java | 4 +- 23 files changed, 786 insertions(+), 329 deletions(-) create mode 100644 droidar/src/actions/algos/SmoothingAlgo.java create mode 100644 droidar/src/listeners/FrameReceivedListener.java create mode 100644 droidar/src/logger/ARLogger.java create mode 100644 droidar/src/preview/CameraPreview.java create mode 100644 droidar/src/preview/CameraView.java delete mode 100644 droidar/src/system/CameraView.java delete mode 100644 droidar/src/system/CameraViewForOldDevices.java create mode 100644 droidar/src/system/FrameChangeThread.java diff --git a/droidar/.classpath b/droidar/.classpath index 7bc01d9..5176974 100644 --- a/droidar/.classpath +++ b/droidar/.classpath @@ -1,9 +1,9 @@ - - + + diff --git a/droidar/AndroidManifest.xml b/droidar/AndroidManifest.xml index c8f3c4e..f145f14 100644 --- a/droidar/AndroidManifest.xml +++ b/droidar/AndroidManifest.xml @@ -64,7 +64,7 @@ work for devices with android 1.5 as well. The development version is set to 1.6 to get access to stuff like high res. screens (eg samsung galaxy tab) --> - + - + diff --git a/droidar/src/actions/ActionUseCameraAngles2.java b/droidar/src/actions/ActionUseCameraAngles2.java index c20a47b..7cdd570 100644 --- a/droidar/src/actions/ActionUseCameraAngles2.java +++ b/droidar/src/actions/ActionUseCameraAngles2.java @@ -1,8 +1,8 @@ package actions; import listeners.eventManagerListeners.OrientationChangedListener; +import setup.ArSetup; import system.EventManager; -import system.Setup; import android.hardware.SensorManager; import android.view.Surface; @@ -26,7 +26,7 @@ public abstract class ActionUseCameraAngles2 implements private int screenRotation; public ActionUseCameraAngles2() { - screenRotation = Setup.getScreenOrientation(); + screenRotation = ArSetup.getScreenOrientation(); } @Override diff --git a/droidar/src/actions/ActionWithSensorProcessing.java b/droidar/src/actions/ActionWithSensorProcessing.java index 2887593..c3b0ab2 100644 --- a/droidar/src/actions/ActionWithSensorProcessing.java +++ b/droidar/src/actions/ActionWithSensorProcessing.java @@ -2,8 +2,8 @@ import gl.GLCamRotationController; import gl.GLUtilityClass; +import setup.ArSetup; import system.EventManager; -import system.Setup; import util.Calculus; import worldData.Updateable; import actions.algos.Algo; @@ -43,7 +43,7 @@ public abstract class ActionWithSensorProcessing extends Action { public ActionWithSensorProcessing(GLCamRotationController targetCamera) { myTargetCamera = targetCamera; initAlgos(); - screenRotation = Setup.getScreenOrientation(); + screenRotation = ArSetup.getScreenOrientation(); } protected abstract void initAlgos(); diff --git a/droidar/src/commands/system/CommandShowCameraPreview.java b/droidar/src/commands/system/CommandShowCameraPreview.java index d570bb9..5a367e6 100644 --- a/droidar/src/commands/system/CommandShowCameraPreview.java +++ b/droidar/src/commands/system/CommandShowCameraPreview.java @@ -1,12 +1,12 @@ package commands.system; -import system.Setup; +import setup.ArSetup; import commands.undoable.UndoableCommand; public class CommandShowCameraPreview extends UndoableCommand { - private Setup mySetup; + private ArSetup mySetup; private boolean showCameraPreview; /** @@ -14,26 +14,28 @@ public class CommandShowCameraPreview extends UndoableCommand { * @param show * false=camera is switched off */ - public CommandShowCameraPreview(Setup setup, boolean show) { + public CommandShowCameraPreview(ArSetup setup, boolean show) { mySetup = setup; showCameraPreview = show; } @Override public boolean override_do() { - if (showCameraPreview) - mySetup.resumeCameraPreview(); - else - mySetup.pauseCameraPreview(); +//TODO: Fix +// if (showCameraPreview) +// mySetup.resumeCameraPreview(); +// else +// mySetup.pauseCameraPreview(); return true; } @Override public boolean override_undo() { - if (showCameraPreview) - mySetup.pauseCameraPreview(); - else - mySetup.resumeCameraPreview(); +//TODO: Fix +// if (showCameraPreview) +// mySetup.pauseCameraPreview(); +// else +// mySetup.resumeCameraPreview(); return true; } diff --git a/droidar/src/de/rwth/TechDemoLauncher.java b/droidar/src/de/rwth/TechDemoLauncher.java index de0cac5..f26e147 100644 --- a/droidar/src/de/rwth/TechDemoLauncher.java +++ b/droidar/src/de/rwth/TechDemoLauncher.java @@ -1,12 +1,10 @@ package de.rwth; -import system.ArActivity; +import setup.ArSetup; import system.ErrorHandler; import system.EventManager; -import system.Setup; import tests.AndroidDeviceOnlyTests; import tests.EfficientListTests; -import tests.GameLogicTests; import tests.GeoTests; import tests.GlTests; import tests.IOTests; @@ -25,7 +23,6 @@ import de.rwth.setups.DebugSetup; import de.rwth.setups.FarAwayPOIScenarioSetup; import de.rwth.setups.FastChangingTextSetup; -import de.rwth.setups.GameDemoSetup; import de.rwth.setups.GeoPosTestSetup; import de.rwth.setups.GraphCreationSetup; import de.rwth.setups.GraphMovementTestSetup; @@ -36,6 +33,7 @@ import de.rwth.setups.PositionTestsSetup; import de.rwth.setups.SensorTestSetup; import de.rwth.setups.StaticDemoSetup; +import entry.ArActivity; public class TechDemoLauncher extends Activity { @Override @@ -55,9 +53,8 @@ protected void onResume() { l.removeAllViews(); showSetup("GeoPosTestSetup", new GeoPosTestSetup()); - //showSetup("Demo Setup", new StaticDemoSetup(null)); + showSetup("Demo Setup", new StaticDemoSetup()); showSetup("Animation Demo", new DebugSetup()); - showSetup("Game Demo", new GameDemoSetup()); showSetup("'Too far away' scenario", new FarAwayPOIScenarioSetup()); showSetup("Large worlds", new LargeWorldsSetup()); showSetup("Changing text Demo", new FastChangingTextSetup()); @@ -96,7 +93,7 @@ public void onButtonPressed() { } - private void showSetup(String string, final Setup aSetupInstance) { + private void showSetup(String string, final ArSetup aSetupInstance) { ((LinearLayout) findViewById(R.id.demoScreenLinView)) .addView(new SimpleButton(string) { @Override @@ -139,7 +136,6 @@ private void runTests() { new IOTests(this).run(); new WorldTests().run(); new AndroidDeviceOnlyTests(this).run(); - new GameLogicTests().run(); new GlTests().run(); new CommandShowToast(this, "All tests succeded on this device :)") diff --git a/droidar/src/de/rwth/setups/CollectItemsSetup.java b/droidar/src/de/rwth/setups/CollectItemsSetup.java index 38a044c..875301d 100644 --- a/droidar/src/de/rwth/setups/CollectItemsSetup.java +++ b/droidar/src/de/rwth/setups/CollectItemsSetup.java @@ -10,9 +10,9 @@ import gl.scenegraph.Shape; import gui.GuiSetup; import gui.InfoScreenSettings; +import setup.ArSetup; import system.ErrorHandler; import system.EventManager; -import system.Setup; import util.Vec; import worldData.Obj; import worldData.SystemUpdater; @@ -22,20 +22,19 @@ import actions.ActionMoveCameraBuffered; import actions.ActionRotateCameraBuffered; import android.app.Activity; - import commands.ui.CommandShowToast; import components.ProximitySensor; - import de.rwth.R; +import entry.ISetupEntry; -public class CollectItemsSetup extends Setup { +public class CollectItemsSetup extends ArSetup { private GLCamera camera; private World world; private int catchedNumber; @Override - public void _a_initFieldsIfNecessary() { + public void initFieldsIfNecessary() { // allow the user to send error reports to the developer: ErrorHandler.enableEmailReports("droidar.rwth@gmail.com", "Error in CollectItemsSetup"); @@ -43,7 +42,7 @@ public void _a_initFieldsIfNecessary() { } @Override - public void _b_addWorldsToRenderer(GL1Renderer renderer, + public void addWorldsToRenderer(GL1Renderer renderer, GLFactory objectFactory, GeoObj currentPosition) { camera = new GLCamera(new Vec(0, 0, 1)); @@ -70,7 +69,7 @@ public void _b_addWorldsToRenderer(GL1Renderer renderer, public void onObjectIsCloseToCamera(GLCamera myCamera2, Obj obj, MeshComponent m, float currentDistance) { catchedNumber++; - new CommandShowToast(myTargetActivity, "You got me " + new CommandShowToast(getActivity(), "You got me " + catchedNumber + " times").execute(); itemMesh.setPosition(Vec.getNewRandomPosInXYPlane( camera.getPosition(), 5, 20)); @@ -83,7 +82,7 @@ public void onObjectIsCloseToCamera(GLCamera myCamera2, Obj obj, } @Override - public void _c_addActionsToEvents(EventManager eventManager, + public void addActionsToEvents(EventManager eventManager, CustomGLSurfaceView arView, SystemUpdater updater) { ActionMoveCameraBuffered move = new ActionMoveCameraBuffered(camera, 5, 25); @@ -97,18 +96,18 @@ public void _c_addActionsToEvents(EventManager eventManager, } @Override - public void _d_addElementsToUpdateThread(SystemUpdater worldUpdater) { + public void addElementsToUpdateThread(SystemUpdater worldUpdater) { worldUpdater.addObjectToUpdateCycle(world); } @Override - public void _e2_addElementsToGuiSetup(GuiSetup guiSetup, Activity context) { + public void addElementsToGuiSetup(GuiSetup guiSetup, Activity context) { } @Override - public void _f_addInfoScreen(InfoScreenSettings infoScreenData) { + public void addInfoScreen(InfoScreenSettings infoScreenData) { infoScreenData .addText("There will an object spawned close to you which you have to collect!"); infoScreenData diff --git a/droidar/src/de/rwth/setups/DebugSetup.java b/droidar/src/de/rwth/setups/DebugSetup.java index 12fd7aa..aeda132 100644 --- a/droidar/src/de/rwth/setups/DebugSetup.java +++ b/droidar/src/de/rwth/setups/DebugSetup.java @@ -17,9 +17,9 @@ import gl.scenegraph.RenderList; import gl.scenegraph.Shape; import gui.GuiSetup; +import setup.ArSetup; import system.ErrorHandler; import system.EventManager; -import system.Setup; import util.IO; import util.Log; import util.Vec; @@ -34,7 +34,6 @@ import android.app.Activity; import android.widget.Button; import android.widget.TextView; - import commands.Command; import commands.CommandGroup; import commands.DebugCommandPositionEvent; @@ -43,8 +42,8 @@ import commands.system.CameraSetARInputCommand; import commands.system.CommandPlaySound; import commands.ui.CommandShowToast; - import de.rwth.R; +import entry.ISetupEntry; /** * This setup demonstrates the possible animations, camera movement, textured @@ -53,7 +52,7 @@ * @author Spobo * */ -public class DebugSetup extends Setup { +public class DebugSetup extends ArSetup { protected static final String LOG_TAG = "DebugSetup"; // World radar; @@ -66,7 +65,7 @@ public class DebugSetup extends Setup { private TimeModifier timeModifier; @Override - public void _a_initFieldsIfNecessary() { + public void initFieldsIfNecessary() { // allow the user to send error reports to the developer: ErrorHandler.enableEmailReports("droidar.rwth@gmail.com", @@ -77,7 +76,7 @@ public void _a_initFieldsIfNecessary() { } @Override - public void _b_addWorldsToRenderer(GL1Renderer renderer, + public void addWorldsToRenderer(GL1Renderer renderer, GLFactory objectFactory, GeoObj currentPosition) { camera = new GLCamera(new Vec(0, 0, 1)); @@ -93,7 +92,7 @@ public void _b_addWorldsToRenderer(GL1Renderer renderer, initNTest(world); world.add(objectFactory.newTextObject("text Input", new Vec(10, 1, 1), - myTargetActivity, camera)); + getActivity(), camera)); addTestGeoObj(world, camera); @@ -119,7 +118,7 @@ private void initNTest(World w) { MeshComponent triangleMesh = GLFactory.getInstance() .newTexturedSquare( "elefantId", - IO.loadBitmapFromId(myTargetActivity, + IO.loadBitmapFromId(getActivity(), R.drawable.elephant64)); triangleMesh.setScale(new Vec(10, 10, 10)); triangleMesh.addChild(new AnimationFaceToCamera(camera, 0.5f)); @@ -131,7 +130,7 @@ private void initNTest(World w) { MeshComponent triangleMesh = GLFactory.getInstance() .newTexturedSquare( "hippoId", - IO.loadBitmapFromId(myTargetActivity, + IO.loadBitmapFromId(getActivity(), R.drawable.hippopotamus64)); triangleMesh.addChild(new AnimationFaceToCamera(camera, 0.5f)); triangleMesh.setScale(new Vec(10, 10, 10)); @@ -148,7 +147,7 @@ private void initNTest(World w) { MeshComponent triangleMesh = GLFactory.getInstance() .newTexturedSquare( "pandaId", - IO.loadBitmapFromId(myTargetActivity, + IO.loadBitmapFromId(getActivity(), R.drawable.panda64)); triangleMesh.addChild(new AnimationFaceToCamera(camera, 0.5f)); triangleMesh.setScale(new Vec(10, 10, 10)); @@ -164,7 +163,7 @@ private void initI9Tests(World w) { MeshComponent triangleMesh = GLFactory.getInstance() .newTexturedSquare( "elefantId", - IO.loadBitmapFromId(myTargetActivity, + IO.loadBitmapFromId(getActivity(), R.drawable.elephant64)); triangleMesh.setScale(new Vec(10, 10, 10)); triangleMesh.addChild(new AnimationFaceToCamera(camera, 0.5f)); @@ -177,7 +176,7 @@ private void initI9Tests(World w) { MeshComponent triangleMesh = GLFactory.getInstance() .newTexturedSquare( "hippoId", - IO.loadBitmapFromId(myTargetActivity, + IO.loadBitmapFromId(getActivity(), R.drawable.hippopotamus64)); triangleMesh.addChild(new AnimationFaceToCamera(camera, 0.5f)); triangleMesh.setScale(new Vec(10, 10, 10)); @@ -194,7 +193,7 @@ private void initI9Tests(World w) { MeshComponent triangleMesh = GLFactory.getInstance() .newTexturedSquare( "pandaId", - IO.loadBitmapFromId(myTargetActivity, + IO.loadBitmapFromId(getActivity(), R.drawable.panda64)); triangleMesh.addChild(new AnimationFaceToCamera(camera, 0.5f)); triangleMesh.setScale(new Vec(10, 10, 10)); @@ -205,16 +204,16 @@ private void initI9Tests(World w) { { // transform android ui elements into opengl models: - TextView tv = new TextView(myTargetActivity); + TextView tv = new TextView(getActivity()); tv.setTextColor(Color.white().toIntARGB()); tv.setTextSize(20); tv.setText("! Hallo !"); - Button b = new Button(myTargetActivity); + Button b = new Button(getActivity()); b.setText("Click Me"); MeshComponent button = GLFactory.getInstance().newTexturedSquare( "buttonId", IO.loadBitmapFromView(b)); - button.setOnClickCommand(new CommandShowToast(myTargetActivity, + button.setOnClickCommand(new CommandShowToast(getActivity(), "Thanks alot")); button.addChild(new AnimationFaceToCamera(camera, 0.5f)); @@ -271,7 +270,7 @@ private synchronized void initWorld(RenderList l) { Obj treangle = new Obj(); MeshComponent treangleMesh = GLFactory.getInstance().newTexturedSquare( "worldIconId", - IO.loadBitmapFromId(myTargetActivity, R.drawable.icon)); + IO.loadBitmapFromId(getActivity(), R.drawable.icon)); treangleMesh.setPosition(new Vec(0, -2, 1)); treangleMesh.setRotation(new Vec(0, 0, 0)); treangleMesh.addChild(new AnimationFaceToCamera(camera, 0.5f)); @@ -317,7 +316,7 @@ private synchronized void initWorld(RenderList l) { } @Override - public void _c_addActionsToEvents(EventManager eventManager, + public void addActionsToEvents(EventManager eventManager, CustomGLSurfaceView arView, SystemUpdater updater) { ActionWASDMovement wasdAction = new ActionWASDMovement(camera, 25f, @@ -339,14 +338,14 @@ public void _c_addActionsToEvents(EventManager eventManager, } @Override - public void _d_addElementsToUpdateThread(SystemUpdater worldUpdater) { + public void addElementsToUpdateThread(SystemUpdater worldUpdater) { // add the created world to be updated: worldUpdater.addObjectToUpdateCycle(world); } @Override - public void _e2_addElementsToGuiSetup(GuiSetup guiSetup, Activity activity) { + public void addElementsToGuiSetup(GuiSetup guiSetup, Activity activity) { guiSetup.setBottomBackroundColor(new Color(0.5f, 0.5f, 0.5f, 0.4f) .toIntARGB()); diff --git a/droidar/src/de/rwth/setups/FarAwayPOIScenarioSetup.java b/droidar/src/de/rwth/setups/FarAwayPOIScenarioSetup.java index 7e7a35e..4925637 100644 --- a/droidar/src/de/rwth/setups/FarAwayPOIScenarioSetup.java +++ b/droidar/src/de/rwth/setups/FarAwayPOIScenarioSetup.java @@ -5,25 +5,25 @@ import gl.GLFactory; import gui.GuiSetup; import gui.RadarView; -import system.DefaultARSetup; +import setup.DefaultArSetup; import util.Vec; import worldData.SystemUpdater; import worldData.World; import android.app.Activity; import android.util.Log; - import commands.Command; import commands.ui.CommandShowToast; import components.SimpleTooFarAwayComp; +import entry.ISetupEntry; -public class FarAwayPOIScenarioSetup extends DefaultARSetup { +public class FarAwayPOIScenarioSetup extends DefaultArSetup { private String LOG_TAG = "FarAwayPOIScenarioSetup"; private RadarView radar; - + @Override - public void _a_initFieldsIfNecessary() { - super._a_initFieldsIfNecessary(); + public void initFieldsIfNecessary() { + super.initFieldsIfNecessary(); radar = new RadarView(getActivity(), (int) (getScreenWidth() / 3), getCamera(), getWorld().getAllItems()); } @@ -40,14 +40,14 @@ public void addObjectsTo(GL1Renderer renderer, World world, } @Override - public void _d_addElementsToUpdateThread(SystemUpdater updater) { - super._d_addElementsToUpdateThread(updater); + public void addElementsToUpdateThread(SystemUpdater updater) { + super.addElementsToUpdateThread(updater); updater.addObjectToUpdateCycle(radar); } @Override - public void _e2_addElementsToGuiSetup(GuiSetup guiSetup, Activity activity) { - super._e2_addElementsToGuiSetup(guiSetup, activity); + public void addElementsToGuiSetup(GuiSetup guiSetup, Activity activity) { + super.addElementsToGuiSetup(guiSetup, activity); guiSetup.addViewToTop(radar); guiSetup.addButtonToBottomView(new Command() { diff --git a/droidar/src/de/rwth/setups/FastChangingTextSetup.java b/droidar/src/de/rwth/setups/FastChangingTextSetup.java index 9a8cd32..a9c755d 100644 --- a/droidar/src/de/rwth/setups/FastChangingTextSetup.java +++ b/droidar/src/de/rwth/setups/FastChangingTextSetup.java @@ -1,5 +1,6 @@ package de.rwth.setups; +import entry.ISetupEntry; import gl.GL1Renderer; import gl.GLFactory; import gl.GLText; @@ -8,14 +9,13 @@ import java.util.HashMap; -import system.DefaultARSetup; +import setup.DefaultArSetup; import worldData.Obj; import worldData.World; import android.app.Activity; - import commands.Command; -public class FastChangingTextSetup extends DefaultARSetup { +public class FastChangingTextSetup extends DefaultArSetup { HashMap textMap = new HashMap(); private GLText text; @@ -24,7 +24,7 @@ public class FastChangingTextSetup extends DefaultARSetup { public void addObjectsTo(GL1Renderer renderer, World world, GLFactory objectFactory) { - text = new GLText("11223344swrvgweln@@@@", myTargetActivity, textMap, + text = new GLText("11223344swrvgweln@@@@", getActivity(), textMap, getCamera()); Obj o = new Obj(); @@ -33,8 +33,8 @@ public void addObjectsTo(GL1Renderer renderer, World world, } @Override - public void _e2_addElementsToGuiSetup(GuiSetup guiSetup, Activity activity) { - super._e2_addElementsToGuiSetup(guiSetup, activity); + public void addElementsToGuiSetup(GuiSetup guiSetup, Activity activity) { + super.addElementsToGuiSetup(guiSetup, activity); guiSetup.addSearchbarToView(guiSetup.getBottomView(), new Command() { @Override diff --git a/droidar/src/de/rwth/setups/GameDemoSetup.java b/droidar/src/de/rwth/setups/GameDemoSetup.java deleted file mode 100644 index c413f10..0000000 --- a/droidar/src/de/rwth/setups/GameDemoSetup.java +++ /dev/null @@ -1,43 +0,0 @@ -package de.rwth.setups; - -import gamelogic.ActionThrowFireball; -import gamelogic.GameParticipant; -import gamelogic.Stat; -import gl.GL1Renderer; -import gl.GLFactory; -import gui.GuiSetup; -import system.DefaultARSetup; -import worldData.SystemUpdater; -import worldData.World; -import android.app.Activity; -import de.rwth.R; - -public class GameDemoSetup extends DefaultARSetup { - private GameParticipant p; - private ActionThrowFireball e; - - public GameDemoSetup() { - p = new GameParticipant("Player", "Karlo", R.drawable.hippopotamus64); - p.addStat(new Stat(Stat.INTELLIGENCE, R.drawable.icon, 2)); - e = new ActionThrowFireball("Fireball"); - p.addAction(e); - } - - @Override - public void _d_addElementsToUpdateThread(SystemUpdater updater) { - super._d_addElementsToUpdateThread(updater); - updater.addObjectToUpdateCycle(p); - } - - @Override - public void addObjectsTo(GL1Renderer renderer, World world, - GLFactory objectFactory) { - - } - - @Override - public void _e2_addElementsToGuiSetup(GuiSetup guiSetup, Activity activity) { - super._e2_addElementsToGuiSetup(guiSetup, activity); - guiSetup.addViewToTop(e.getNewDefaultView(getActivity())); - } -} diff --git a/droidar/src/de/rwth/setups/GeoPosTestSetup.java b/droidar/src/de/rwth/setups/GeoPosTestSetup.java index 1d01c26..9d2232f 100644 --- a/droidar/src/de/rwth/setups/GeoPosTestSetup.java +++ b/droidar/src/de/rwth/setups/GeoPosTestSetup.java @@ -1,14 +1,14 @@ package de.rwth.setups; +import entry.ISetupEntry; import geo.GeoObj; import gl.GL1Renderer; import gl.GLFactory; -import system.DefaultARSetup; +import setup.DefaultArSetup; import util.Vec; import worldData.World; -public class GeoPosTestSetup extends DefaultARSetup { - +public class GeoPosTestSetup extends DefaultArSetup { @Override public void addObjectsTo(GL1Renderer renderer, World world, GLFactory objectFactory) { diff --git a/droidar/src/de/rwth/setups/GraphCreationSetup.java b/droidar/src/de/rwth/setups/GraphCreationSetup.java index 141a8ad..045ab9b 100644 --- a/droidar/src/de/rwth/setups/GraphCreationSetup.java +++ b/droidar/src/de/rwth/setups/GraphCreationSetup.java @@ -13,9 +13,9 @@ import gl.scenegraph.MeshComponent; import gui.GuiSetup; import gui.MetaInfos; +import setup.ArSetup; import system.ErrorHandler; import system.EventManager; -import system.Setup; import util.EfficientList; import util.EfficientListQualified; import util.Vec; @@ -29,11 +29,11 @@ import android.app.Activity; import android.util.Log; import android.widget.EditText; - import commands.Command; import commands.ui.CommandShowEditScreen; +import entry.ISetupEntry; -public class GraphCreationSetup extends Setup { +public class GraphCreationSetup extends ArSetup { private static final String LOG_TAG = "GraphCreationSetup"; private GeoGraph myGraph; @@ -45,7 +45,7 @@ public class GraphCreationSetup extends Setup { private MetaInfos i; @Override - public void _a_initFieldsIfNecessary() { + public void initFieldsIfNecessary() { // allow the user to send error reports to the developer: ErrorHandler.enableEmailReports("droidar.rwth@gmail.com", "Error in GraphCreationSetup"); @@ -63,13 +63,13 @@ public void _a_initFieldsIfNecessary() { } @Override - public void _b_addWorldsToRenderer(GL1Renderer renderer, + public void addWorldsToRenderer(GL1Renderer renderer, GLFactory objectFactory, GeoObj currentPosition) { renderer.addRenderElement(world); } @Override - public void _c_addActionsToEvents(EventManager eventManager, + public void addActionsToEvents(EventManager eventManager, CustomGLSurfaceView arView, SystemUpdater updater) { arView.addOnTouchMoveAction(new ActionBufferedCameraAR(camera)); Action rot = new ActionRotateCameraBuffered(camera); @@ -83,12 +83,12 @@ public void _c_addActionsToEvents(EventManager eventManager, } @Override - public void _d_addElementsToUpdateThread(SystemUpdater worldUpdater) { + public void addElementsToUpdateThread(SystemUpdater worldUpdater) { worldUpdater.addObjectToUpdateCycle(world); } @Override - public void _e2_addElementsToGuiSetup(GuiSetup guiSetup, Activity activity) { + public void addElementsToGuiSetup(GuiSetup guiSetup, Activity activity) { final EditText editText = guiSetup.addSearchbarToView( guiSetup.getTopView(), findWayToWaypoint(), "Waypoint name.."); @@ -149,7 +149,7 @@ public boolean execute() { }); myShape.setOnLongClickCommand(new CommandShowEditScreen( - myTargetActivity, p)); + getActivity(), p)); return p; } diff --git a/droidar/src/de/rwth/setups/GraphMovementTestSetup.java b/droidar/src/de/rwth/setups/GraphMovementTestSetup.java index f6c87d5..e2a9b62 100644 --- a/droidar/src/de/rwth/setups/GraphMovementTestSetup.java +++ b/droidar/src/de/rwth/setups/GraphMovementTestSetup.java @@ -1,20 +1,20 @@ package de.rwth.setups; +import entry.ISetupEntry; import geo.DefaultNodeEdgeListener; import geo.GeoGraph; import geo.GeoObj; import gl.CustomGLSurfaceView; import gl.GL1Renderer; import gl.GLFactory; -import system.DefaultARSetup; +import setup.DefaultArSetup; import system.EventManager; import util.EfficientList; import util.Vec; import worldData.SystemUpdater; import worldData.World; -public class GraphMovementTestSetup extends DefaultARSetup { - +public class GraphMovementTestSetup extends DefaultArSetup { @Override public void addObjectsTo(GL1Renderer renderer, World world, GLFactory objectFactory) { @@ -46,10 +46,10 @@ private GeoObj newOb(float x, float y) { } @Override - public void _c_addActionsToEvents(EventManager eventManager, + public void addActionsToEvents(EventManager eventManager, CustomGLSurfaceView arView, SystemUpdater updater) { - super._c_addActionsToEvents(eventManager, arView, updater); + super.addActionsToEvents(eventManager, arView, updater); eventManager.getOnLocationChangedAction().clear(); } diff --git a/droidar/src/de/rwth/setups/LargeWorldsSetup.java b/droidar/src/de/rwth/setups/LargeWorldsSetup.java index d99faa5..cdb4052 100644 --- a/droidar/src/de/rwth/setups/LargeWorldsSetup.java +++ b/droidar/src/de/rwth/setups/LargeWorldsSetup.java @@ -1,29 +1,29 @@ package de.rwth.setups; +import entry.ISetupEntry; import gl.GL1Renderer; import gl.GLFactory; import gui.InfoScreenSettings; -import system.DefaultARSetup; +import setup.DefaultArSetup; import system.ErrorHandler; import util.Vec; import worldData.AbstractObj; import worldData.RenderQuadList; import worldData.World; -public class LargeWorldsSetup extends DefaultARSetup { - +public class LargeWorldsSetup extends DefaultArSetup { private static final int NUMBER_OF_OBJECTS = 1000; @Override - public void _a_initFieldsIfNecessary() { - super._a_initFieldsIfNecessary(); + public void initFieldsIfNecessary() { + super.initFieldsIfNecessary(); // allow the user to send error reports to the developer: ErrorHandler.enableEmailReports("droidar.rwth@gmail.com", "Error in LargeWorldsSetup"); } @Override - public void _f_addInfoScreen(InfoScreenSettings infoScreenData) { + public void addInfoScreen(InfoScreenSettings infoScreenData) { infoScreenData .addText("This setup will demonstrate a possible culling-strategy for very large virtual worlds."); infoScreenData @@ -47,7 +47,7 @@ public void addObjectsTo(GL1Renderer renderer, World world, private AbstractObj newObj(int x, int y) { String name = "x=" + x + ",y=" + y; return GLFactory.getInstance().newTextObject(name, new Vec(x, y, 0), - getActivity(), camera); + getActivity(), getCamera()); } } diff --git a/droidar/src/de/rwth/setups/LightningSetup.java b/droidar/src/de/rwth/setups/LightningSetup.java index 5ae1560..220fa4c 100644 --- a/droidar/src/de/rwth/setups/LightningSetup.java +++ b/droidar/src/de/rwth/setups/LightningSetup.java @@ -1,5 +1,6 @@ package de.rwth.setups; +import entry.ISetupEntry; import gl.Color; import gl.CustomGLSurfaceView; import gl.GL1Renderer; @@ -14,7 +15,7 @@ import javax.microedition.khronos.opengles.GL10; -import system.DefaultARSetup; +import setup.DefaultArSetup; import system.EventManager; import util.Vec; import util.Wrapper; @@ -29,7 +30,7 @@ import commands.Command; -public class LightningSetup extends DefaultARSetup { +public class LightningSetup extends DefaultArSetup { protected static final String LOG_TAG = "LightningSetup"; @@ -42,13 +43,12 @@ public class LightningSetup extends DefaultARSetup { private final Obj lightObject; public LightningSetup() { - super(); lightObject = new Obj(); targetMoveWrapper = new Wrapper(lightObject); } @Override - public boolean _a2_initLightning(ArrayList lights) { + public boolean initLightning(ArrayList lights) { lights.add(LightSource.newDefaultAmbientLight(GL10.GL_LIGHT0)); spotLight = LightSource.newDefaultDefuseLight(GL10.GL_LIGHT1, new Vec( 0, 0, 0)); @@ -124,9 +124,9 @@ private Entity newCube() { } @Override - public void _c_addActionsToEvents(EventManager eventManager, + public void addActionsToEvents(EventManager eventManager, CustomGLSurfaceView arView, SystemUpdater updater) { - super._c_addActionsToEvents(eventManager, arView, updater); + super.addActionsToEvents(eventManager, arView, updater); // clear some inputs set in default methods eventManager.getOnLocationChangedAction().clear(); @@ -137,8 +137,8 @@ public void _c_addActionsToEvents(EventManager eventManager, } @Override - public void _e2_addElementsToGuiSetup(GuiSetup guiSetup, Activity activity) { - super._e2_addElementsToGuiSetup(guiSetup, activity); + public void addElementsToGuiSetup(GuiSetup guiSetup, Activity activity) { + super.addElementsToGuiSetup(guiSetup, activity); guiSetup.addButtonToBottomView(new Command() { @Override diff --git a/droidar/src/de/rwth/setups/PlaceObjectsSetup.java b/droidar/src/de/rwth/setups/PlaceObjectsSetup.java index b2eff00..b4a2f6a 100644 --- a/droidar/src/de/rwth/setups/PlaceObjectsSetup.java +++ b/droidar/src/de/rwth/setups/PlaceObjectsSetup.java @@ -8,9 +8,9 @@ import gl.GLFactory; import gl.scenegraph.MeshComponent; import gui.GuiSetup; +import setup.ArSetup; import system.ErrorHandler; import system.EventManager; -import system.Setup; import util.Vec; import util.Wrapper; import worldData.Obj; @@ -23,18 +23,17 @@ import actions.ActionPlaceObject; import actions.ActionRotateCameraBuffered; import android.app.Activity; - import commands.Command; +import entry.ISetupEntry; -public class PlaceObjectsSetup extends Setup { - +public class PlaceObjectsSetup extends ArSetup { private GLCamera camera; private World world; private Wrapper placeObjectWrapper; @Override - public void _a_initFieldsIfNecessary() { + public void initFieldsIfNecessary() { // allow the user to send error reports to the developer: ErrorHandler.enableEmailReports("droidar.rwth@gmail.com", @@ -45,7 +44,7 @@ public void _a_initFieldsIfNecessary() { } @Override - public void _b_addWorldsToRenderer(GL1Renderer renderer, + public void addWorldsToRenderer(GL1Renderer renderer, GLFactory objectFactory, GeoObj currentPosition) { camera = new GLCamera(new Vec(0, 0, 10)); world = new World(camera); @@ -60,7 +59,7 @@ public void _b_addWorldsToRenderer(GL1Renderer renderer, } @Override - public void _c_addActionsToEvents(EventManager eventManager, + public void addActionsToEvents(EventManager eventManager, CustomGLSurfaceView arView, SystemUpdater updater) { arView.addOnTouchMoveAction(new ActionBufferedCameraAR(camera)); Action rot1 = new ActionRotateCameraBuffered(camera); @@ -78,12 +77,12 @@ public void _c_addActionsToEvents(EventManager eventManager, } @Override - public void _d_addElementsToUpdateThread(SystemUpdater worldUpdater) { + public void addElementsToUpdateThread(SystemUpdater worldUpdater) { worldUpdater.addObjectToUpdateCycle(world); } @Override - public void _e2_addElementsToGuiSetup(GuiSetup guiSetup, Activity context) { + public void addElementsToGuiSetup(GuiSetup guiSetup, Activity context) { guiSetup.addButtonToTopView(new Command() { @Override diff --git a/droidar/src/de/rwth/setups/PlaceObjectsSetupTwo.java b/droidar/src/de/rwth/setups/PlaceObjectsSetupTwo.java index 2a16f9c..b5cce19 100644 --- a/droidar/src/de/rwth/setups/PlaceObjectsSetupTwo.java +++ b/droidar/src/de/rwth/setups/PlaceObjectsSetupTwo.java @@ -8,9 +8,9 @@ import gl.GLFactory; import gl.scenegraph.MeshComponent; import gui.GuiSetup; +import setup.ArSetup; import system.ErrorHandler; import system.EventManager; -import system.Setup; import util.Vec; import worldData.MoveComp; import worldData.Obj; @@ -22,12 +22,11 @@ import actions.ActionMoveCameraBuffered; import actions.ActionRotateCameraBuffered; import android.app.Activity; - import commands.Command; import components.ViewPosCalcerComp; +import entry.ISetupEntry; -public class PlaceObjectsSetupTwo extends Setup { - +public class PlaceObjectsSetupTwo extends ArSetup { private GLCamera camera; private World world; private ViewPosCalcerComp viewPosCalcer; @@ -35,7 +34,7 @@ public class PlaceObjectsSetupTwo extends Setup { private MoveComp moveComp; @Override - public void _a_initFieldsIfNecessary() { + public void initFieldsIfNecessary() { // allow the user to send error reports to the developer: ErrorHandler.enableEmailReports("droidar.rwth@gmail.com", @@ -59,14 +58,14 @@ public void onPositionUpdate(worldData.Updateable parent, } @Override - public void _b_addWorldsToRenderer(GL1Renderer renderer, + public void addWorldsToRenderer(GL1Renderer renderer, GLFactory objectFactory, GeoObj currentPosition) { world.add(newObject()); renderer.addRenderElement(world); } @Override - public void _c_addActionsToEvents(EventManager eventManager, + public void addActionsToEvents(EventManager eventManager, CustomGLSurfaceView arView, SystemUpdater updater) { arView.addOnTouchMoveAction(new ActionBufferedCameraAR(camera)); Action rot = new ActionRotateCameraBuffered(camera); @@ -80,12 +79,12 @@ public void _c_addActionsToEvents(EventManager eventManager, } @Override - public void _d_addElementsToUpdateThread(SystemUpdater worldUpdater) { + public void addElementsToUpdateThread(SystemUpdater worldUpdater) { worldUpdater.addObjectToUpdateCycle(world); } @Override - public void _e2_addElementsToGuiSetup(GuiSetup guiSetup, Activity context) { + public void addElementsToGuiSetup(GuiSetup guiSetup, Activity context) { guiSetup.addButtonToTopView(new Command() { @Override diff --git a/droidar/src/de/rwth/setups/PositionTestsSetup.java b/droidar/src/de/rwth/setups/PositionTestsSetup.java index 68ee528..d3a5f92 100644 --- a/droidar/src/de/rwth/setups/PositionTestsSetup.java +++ b/droidar/src/de/rwth/setups/PositionTestsSetup.java @@ -1,5 +1,6 @@ package de.rwth.setups; +import entry.ISetupEntry; import geo.GeoObj; import gl.Color; import gl.CustomGLSurfaceView; @@ -8,8 +9,8 @@ import gl.GLFactory; import gl.scenegraph.MeshComponent; import gui.GuiSetup; +import setup.ArSetup; import system.EventManager; -import system.Setup; import util.Vec; import worldData.SystemUpdater; import worldData.World; @@ -24,7 +25,7 @@ import commands.ui.CommandInUiThread; import commands.ui.CommandShowToast; -public class PositionTestsSetup extends Setup { +public class PositionTestsSetup extends ArSetup { protected static final int ZDELTA = 5; private final GLCamera camera; @@ -49,12 +50,12 @@ public PositionTestsSetup() { } @Override - public void _a_initFieldsIfNecessary() { + public void initFieldsIfNecessary() { } @Override - public void _b_addWorldsToRenderer(GL1Renderer renderer, + public void addWorldsToRenderer(GL1Renderer renderer, GLFactory objectFactory, GeoObj currentPosition) { spawnObj(posA, GLFactory.getInstance().newCircle(Color.green())); @@ -67,7 +68,7 @@ public void _b_addWorldsToRenderer(GL1Renderer renderer, } @Override - public void _c_addActionsToEvents(EventManager eventManager, + public void addActionsToEvents(EventManager eventManager, CustomGLSurfaceView arView, SystemUpdater updater) { arView.addOnTouchMoveListener(new ActionMoveCameraBuffered(camera, 5, 25)); @@ -82,12 +83,12 @@ public void _c_addActionsToEvents(EventManager eventManager, } @Override - public void _d_addElementsToUpdateThread(SystemUpdater updater) { + public void addElementsToUpdateThread(SystemUpdater updater) { updater.addObjectToUpdateCycle(world); } @Override - public void _e2_addElementsToGuiSetup(GuiSetup guiSetup, Activity activity) { + public void addElementsToGuiSetup(GuiSetup guiSetup, Activity activity) { guiSetup.setRightViewAllignBottom(); guiSetup.addImangeButtonToRightView(R.drawable.arrow_up_float, @@ -144,7 +145,7 @@ private void addGpsPosOutputButtons(GuiSetup guiSetup) { public void executeInUiThread() { Vec pos = camera.getGPSPositionVec(); String text = "latitude=" + pos.y + ", longitude=" + pos.x; - CommandShowToast.show(myTargetActivity, text); + CommandShowToast.show(getActivity(), text); } }, "Show Camera GPS pos"); @@ -156,7 +157,7 @@ public void executeInUiThread() { .getCurrentLocationObject(); String text = "latitude=" + pos.getLatitude() + ", longitude=" + pos.getLongitude(); - CommandShowToast.show(myTargetActivity, text); + CommandShowToast.show(getActivity(), text); } }, "Show real GPS pos"); @@ -168,7 +169,7 @@ public void executeInUiThread() { .getZeroPositionLocationObject(); String text = "latitude=" + pos.getLatitude() + ", longitude=" + pos.getLongitude(); - CommandShowToast.show(myTargetActivity, text); + CommandShowToast.show(getActivity(), text); } }, "Show zero GPS pos"); } @@ -192,7 +193,7 @@ private void spawnObj(final GeoObj pos, MeshComponent mesh) { mesh.setPosition(Vec.getNewRandomPosInXYPlane(new Vec(), 0.1f, 1f)); x.setComp(mesh); - CommandShowToast.show(myTargetActivity, "Object spawned at " + CommandShowToast.show(getActivity(), "Object spawned at " + x.getMySurroundGroup().getPosition()); world.add(x); } diff --git a/droidar/src/de/rwth/setups/SensorTestSetup.java b/droidar/src/de/rwth/setups/SensorTestSetup.java index e852edf..eba215c 100644 --- a/droidar/src/de/rwth/setups/SensorTestSetup.java +++ b/droidar/src/de/rwth/setups/SensorTestSetup.java @@ -10,9 +10,9 @@ import gl.scenegraph.MeshComponent; import gl.scenegraph.Shape; import gui.GuiSetup; +import setup.ArSetup; import system.ErrorHandler; import system.EventManager; -import system.Setup; import util.Vec; import worldData.SystemUpdater; import worldData.World; @@ -28,11 +28,10 @@ import actions.ActionRotateCameraUnbuffered2; import actions.ActionUseCameraAngles2; import android.app.Activity; - import commands.Command; +import entry.ISetupEntry; -public class SensorTestSetup extends Setup { - +public class SensorTestSetup extends ArSetup { private GLCamera camera; private World world; private Action rotActionB1; @@ -44,7 +43,7 @@ public class SensorTestSetup extends Setup { private Action rotActionB2; @Override - public void _a_initFieldsIfNecessary() { + public void initFieldsIfNecessary() { // allow the user to send error reports to the developer: ErrorHandler.enableEmailReports("droidar.rwth@gmail.com", "Error in DroidAR App"); @@ -66,7 +65,7 @@ public void _a_initFieldsIfNecessary() { } @Override - public void _b_addWorldsToRenderer(GL1Renderer renderer, + public void addWorldsToRenderer(GL1Renderer renderer, GLFactory objectFactory, GeoObj currentPosition) { world = new World(camera); @@ -122,7 +121,7 @@ public void _b_addWorldsToRenderer(GL1Renderer renderer, } @Override - public void _c_addActionsToEvents(EventManager eventManager, + public void addActionsToEvents(EventManager eventManager, CustomGLSurfaceView arView, SystemUpdater updater) { arView.addOnTouchMoveAction(new ActionBufferedCameraAR(camera)); eventManager.addOnOrientationChangedAction(rotActionB1); @@ -144,7 +143,7 @@ public void onAnglesUpdated(float pitch, float roll, } @Override - public void _d_addElementsToUpdateThread(SystemUpdater worldUpdater) { + public void addElementsToUpdateThread(SystemUpdater worldUpdater) { worldUpdater.addObjectToUpdateCycle(world); worldUpdater.addObjectToUpdateCycle(rotActionB1); worldUpdater.addObjectToUpdateCycle(rotActionB3); @@ -155,7 +154,7 @@ public void _d_addElementsToUpdateThread(SystemUpdater worldUpdater) { } @Override - public void _e2_addElementsToGuiSetup(GuiSetup guiSetup, Activity activity) { + public void addElementsToGuiSetup(GuiSetup guiSetup, Activity activity) { guiSetup.addButtonToBottomView(new myRotateAction(rotActionB1), "Camera Buffered 1"); guiSetup.addButtonToBottomView(new myRotateAction(rotActionB2), diff --git a/droidar/src/de/rwth/setups/StaticDemoSetup.java b/droidar/src/de/rwth/setups/StaticDemoSetup.java index 520673e..da30402 100644 --- a/droidar/src/de/rwth/setups/StaticDemoSetup.java +++ b/droidar/src/de/rwth/setups/StaticDemoSetup.java @@ -49,14 +49,16 @@ public class StaticDemoSetup extends ArSetup { private TimeModifier timeModifier; - public StaticDemoSetup(ISetupEntry pEntry) { + public StaticDemoSetup(){ + super(); + } + + public StaticDemoSetup(ISetupEntry pEntry){ super(pEntry); - // TODO Auto-generated constructor stub } - @Override - public void _a_initFieldsIfNecessary() { + public void initFieldsIfNecessary() { // allow the user to send error reports to the developer: ErrorHandler.enableEmailReports("droidar.rwth@gmail.com", @@ -65,7 +67,7 @@ public void _a_initFieldsIfNecessary() { } @Override - public void _b_addWorldsToRenderer(GL1Renderer renderer, + public void addWorldsToRenderer(GL1Renderer renderer, GLFactory objectFactory, GeoObj currentPosition) { camera = new GLCamera(new Vec(0, 0, 1)); @@ -229,7 +231,7 @@ private synchronized void initWorld(RenderList l) { } @Override - public void _c_addActionsToEvents(EventManager eventManager, + public void addActionsToEvents(EventManager eventManager, CustomGLSurfaceView arView, SystemUpdater updater) { ActionWASDMovement wasdAction = new ActionWASDMovement(camera, 25f, @@ -249,14 +251,14 @@ public void _c_addActionsToEvents(EventManager eventManager, } @Override - public void _d_addElementsToUpdateThread(SystemUpdater worldUpdater) { + public void addElementsToUpdateThread(SystemUpdater worldUpdater) { // add the created world to be updated: worldUpdater.addObjectToUpdateCycle(world); } @Override - public void _e2_addElementsToGuiSetup(GuiSetup guiSetup, Activity activity) { + public void addElementsToGuiSetup(GuiSetup guiSetup, Activity activity) { guiSetup.setBottomMinimumHeight(50); guiSetup.setBottomViewCentered(); @@ -281,5 +283,4 @@ public boolean execute() { }, "T-1"); } - } diff --git a/droidar/src/de/rwth/setups/TestSetup.java b/droidar/src/de/rwth/setups/TestSetup.java index 04b713e..06d309c 100644 --- a/droidar/src/de/rwth/setups/TestSetup.java +++ b/droidar/src/de/rwth/setups/TestSetup.java @@ -1,15 +1,15 @@ package de.rwth.setups; +import entry.ISetupEntry; import geo.GeoObj; import gl.GL1Renderer; import gl.GLFactory; import gl.scenegraph.Shape; -import system.DefaultARSetup; +import setup.DefaultArSetup; import util.Vec; import worldData.World; -public class TestSetup extends DefaultARSetup { - +public class TestSetup extends DefaultArSetup { @Override public void addObjectsTo(GL1Renderer renderer, World world, GLFactory objectFactory) { diff --git a/droidar/src/entry/ArActivity.java b/droidar/src/entry/ArActivity.java index d360f9f..0dd3492 100644 --- a/droidar/src/entry/ArActivity.java +++ b/droidar/src/entry/ArActivity.java @@ -1,22 +1,35 @@ package entry; +import logger.ARLogger; import preview.AugmentedView; import setup.ArSetup; import android.app.Activity; +import android.content.Intent; import android.os.Bundle; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import de.rwth.setups.StaticDemoSetup; +/** + * Container that acts as the glue between the {@link setup.ArSetup} and the {@link preview.AugmentedView}. + * Manages the life cycle and acts the entry point to the android application. + * To implement your own {@link setup.ArSetup} extend this class and override {@link entry.ArActivity#createSetup()}. + * To implement your own {@link preview.AugmentedView} extend this class and + * override {@link entry.ArActivity#createAugmentedView(Activity)}. + * + */ public class ArActivity extends Activity implements ISetupEntry { private static final String LOG_TAG = "ArActivity"; + private static boolean USE_STATIC_SETUP = false; + private static ArSetup STATIC_SETUP; private ArSetup mSetup; private AugmentedView mOverlayView; private ArType mType = ArType.ACTIVITY; + @Override public Activity getActivity() { return this; @@ -32,49 +45,70 @@ public AugmentedView getAugmentedView() { return mOverlayView; } + private void determainSetupToUse() { + if (USE_STATIC_SETUP) { + mSetup = STATIC_SETUP; + } else { + mSetup = createSetup(); + } + } + + private void setEntryIfNeeded() { + if (mSetup.getActivity() == null) { + mSetup.setEntry(this); + } + } + @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); - mSetup = createSetup(); + determainSetupToUse(); + setEntryIfNeeded(); mOverlayView = createAugmentedView(this); - mOverlayView.getRenderer().setUseLightning(mSetup._a2_initLightning(mOverlayView.getRenderer().getMyLights())); - mSetup.onCreate(); + mOverlayView.getRenderer().setUseLightning(mSetup.initLightning(mOverlayView.getRenderer().getMyLights())); + mSetup.onCreate(); + mSetup.onStart(); + mSetup.run(this); setContentView(mOverlayView); } - @Override protected void onRestart() { + ARLogger.debug(LOG_TAG, "onRestart"); super.onRestart(); mSetup.onResume(); } @Override protected void onResume() { + ARLogger.debug(LOG_TAG, "onResume"); super.onResume(); mSetup.onResume(); } @Override protected void onStart() { + ARLogger.debug(LOG_TAG, "onStart"); super.onStart(); - mSetup.onStart(); } @Override protected void onStop() { + ARLogger.debug(LOG_TAG, "onStop"); super.onStop(); mSetup.onPause(); } @Override protected void onDestroy() { + ARLogger.debug(LOG_TAG, "onDestory"); super.onDestroy(); mSetup.onStop(); } @Override protected void onPause() { + ARLogger.debug(LOG_TAG, "onPause"); super.onPause(); mSetup.onPause(); } @@ -82,30 +116,45 @@ protected void onPause() { @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if ((mSetup != null) - && (mSetup.onKeyDown(this, keyCode, event))) + && (mSetup.onKeyDown(this, keyCode, event))) { return true; + } return super.onKeyDown(keyCode, event); } @Override public boolean onCreateOptionsMenu(Menu menu) { - if (((mSetup != null) && mSetup.onCreateOptionsMenu(menu))) + if (((mSetup != null) && mSetup.onCreateOptionsMenu(menu))) { return true; + } return super.onCreateOptionsMenu(menu); } @Override public boolean onMenuItemSelected(int featureId, MenuItem item) { - if (mSetup != null) + if (mSetup != null) { return mSetup.onMenuItemSelected(featureId, item); + } return super.onMenuItemSelected(featureId, item); } - protected ArSetup createSetup(){ - return new StaticDemoSetup(this); + /** + * Simple way to kick off the ArActivity. + * @param currentActivity - {@link android.app.Activity} base + * @param setupToUse - {@link setup.ArSetup} + */ + public static void startWithSetup(Activity currentActivity, ArSetup setupToUse) { + USE_STATIC_SETUP = true; + STATIC_SETUP = setupToUse; + currentActivity.startActivity(new Intent(currentActivity, + ArActivity.class)); + } + + protected ArSetup createSetup() { + return new StaticDemoSetup(); } - protected AugmentedView createAugmentedView(Activity activity){ + protected AugmentedView createAugmentedView(Activity activity) { return new AugmentedView(activity); } } diff --git a/droidar/src/entry/ArFragment.java b/droidar/src/entry/ArFragment.java index 06ef990..3393d72 100644 --- a/droidar/src/entry/ArFragment.java +++ b/droidar/src/entry/ArFragment.java @@ -10,19 +10,20 @@ import android.view.ViewGroup; import de.rwth.setups.StaticDemoSetup; -public class ArFragment extends Fragment implements ISetupEntry { - - +/** + * Container that acts as the glue between the {@link setup.ArSetup} and the {@link preview.AugmentedView}. + * Manages the life cycle and acts the entry point to the android application. + * To implement your own {@link setup.ArSetup} extend this class and override {@link entry.ArFragment#createSetup()}. + * To implement your own {@link preview.AugmentedView} extend this class and + * override {@link entry.ArFragment#createAugmentedView(Activity)}. + */ +public class ArFragment extends Fragment implements ISetupEntry { private ArSetup mSetup; private AugmentedView mOverlayView; private ArType mType = ArType.FRAGMENT; - public ArFragment(){ - - } - @Override - public ArType getType(){ + public ArType getType() { return mType; } @@ -31,13 +32,6 @@ public AugmentedView getAugmentedView() { return mOverlayView; } - //////////////////////////////////////////////// - // Android Life Cycle For Fragments - // Notes: onCreateView is called every time - // the fragment is made visible - // onDestoryView is called every time - // the fragment is put into the backstack - ///////////////////////////////////////////////// @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); @@ -49,14 +43,15 @@ public View onCreateView(LayoutInflater inflater, ViewGroup container, return mOverlayView; } - - @Override public void onAttach(Activity activity) { super.onAttach(activity); mSetup = createSetup(); + if (mSetup.getActivity() == null) { + mSetup.setEntry(this); + } mOverlayView = createAugmentedView(getActivity()); - mOverlayView.getRenderer().setUseLightning(mSetup._a2_initLightning(mOverlayView.getRenderer().getMyLights())); + mOverlayView.getRenderer().setUseLightning(mSetup.initLightning(mOverlayView.getRenderer().getMyLights())); mSetup.onCreate(); mSetup.onStart(); mSetup.run(this); @@ -85,7 +80,6 @@ public void onPause() { mSetup.onPause(); } - @Override public void onStop() { super.onStop(); @@ -102,11 +96,11 @@ public void onDestroy() { super.onDestroy(); } - protected ArSetup createSetup(){ + protected ArSetup createSetup() { return new StaticDemoSetup(this); } - protected AugmentedView createAugmentedView(Activity activity){ + protected AugmentedView createAugmentedView(Activity activity) { return new AugmentedView(activity); } } diff --git a/droidar/src/entry/ISetupEntry.java b/droidar/src/entry/ISetupEntry.java index a57c022..09c1183 100644 --- a/droidar/src/entry/ISetupEntry.java +++ b/droidar/src/entry/ISetupEntry.java @@ -3,24 +3,28 @@ import preview.AugmentedView; import android.app.Activity; +/** + * The required methods for and entry to communicate to a {@link setup.ArSetup}. + * + */ public interface ISetupEntry { /** * Retrieve the contain/parent activity. Depending on the ISetupEntry.getType() this * may be either the containing activity or the main displayed activity. - * @return + * @return - {@link android.app.Activity} */ - public Activity getActivity(); + Activity getActivity(); /** - * Retrieve the type of the current class - * @return + * Retrieve the type of the current class. + * @return - {@link entry.ArType} */ - public ArType getType(); + ArType getType(); /** * Retrieve the augmented view this is displayed to the user. - * @return + * @return - {@link preview.AugmentedView} */ - public AugmentedView getAugmentedView(); + AugmentedView getAugmentedView(); } diff --git a/droidar/src/entry/entry.uxf b/droidar/src/entry/entry.uxf index a1b93b6..9bea703 100644 --- a/droidar/src/entry/entry.uxf +++ b/droidar/src/entry/entry.uxf @@ -4,7 +4,7 @@ com.umlet.element.Interface - 190 + 280 30 280 130 @@ -20,7 +20,7 @@ getAugmentedView():AugmentedView com.umlet.element.Class - 130 + 220 230 210 60 @@ -34,7 +34,7 @@ mSetup: ArSetup com.umlet.element.Class - 350 + 440 230 210 60 @@ -48,7 +48,7 @@ mSetup: ArSetup com.umlet.element.Relation - 350 + 440 120 110 130 @@ -59,7 +59,7 @@ mSetup: ArSetup com.umlet.element.Relation - 200 + 290 120 110 130 @@ -67,4 +67,30 @@ mSetup: ArSetup lt=<<- 90;30;40;70;30;110 + + com.umlet.element.Package + + 0 + 70 + 140 + 70 + + setup +-- +ArSetup +bg=gray +fg=red + + + + com.umlet.element.Relation + + 30 + 10 + 410 + 90 + + lt=<<<<- + 30;70;390;30 + diff --git a/droidar/src/gamelogic/ActionFeedback.java b/droidar/src/gamelogic/ActionFeedback.java deleted file mode 100644 index 75520d1..0000000 --- a/droidar/src/gamelogic/ActionFeedback.java +++ /dev/null @@ -1,41 +0,0 @@ -package gamelogic; - -import util.Log; - -public class ActionFeedback { - - private static final String SPACES = " "; - private static final String A = "+ "; - private String myLog; - private boolean actionCorrectExecuted; - - public ActionFeedback(String name) { - myLog = A + name + "\n"; - Log.v("Feedback", name); - } - - public void addInfo(String name, float value) { - Log.v("Feedback", name + "=" + value); - myLog += SPACES + name + "=" + value + "\n"; - // TODO store in list - } - - public void addInfo(String infoText) { - Log.v("Feedback", infoText); - myLog += SPACES + infoText + "\n"; - } - - public void setActionCorrectExecuted(boolean actionCorrectExecuted) { - this.actionCorrectExecuted = actionCorrectExecuted; - } - - public boolean actionCorrectlyExecuted() { - return actionCorrectExecuted; - } - - @Override - public String toString() { - return myLog; - } - -} diff --git a/droidar/src/gamelogic/ActionList.java b/droidar/src/gamelogic/ActionList.java deleted file mode 100644 index 32e23a7..0000000 --- a/droidar/src/gamelogic/ActionList.java +++ /dev/null @@ -1,5 +0,0 @@ -package gamelogic; - -public class ActionList extends GameElementList { - -} diff --git a/droidar/src/gamelogic/ActionThrowFireball.java b/droidar/src/gamelogic/ActionThrowFireball.java deleted file mode 100644 index 8d2b2e9..0000000 --- a/droidar/src/gamelogic/ActionThrowFireball.java +++ /dev/null @@ -1,104 +0,0 @@ -package gamelogic; - -import gui.simpleUI.ModifierGroup; -import gui.simpleUI.modifiers.InfoText; -import gui.simpleUI.modifiers.PlusMinusModifier; -import de.rwth.R; - -public class ActionThrowFireball extends GameAction { - - private static int myIconId = R.drawable.spaceship; - - public static final String FIREBALL_ACTION = "Throw fireball"; - - public static final String LEVEL = "Level"; - - public ActionThrowFireball() { - this(FIREBALL_ACTION); - } - - public ActionThrowFireball(String uniqueName) { - super(uniqueName, 1, myIconId); - addStat(new Stat(LEVEL, R.id.button1, 1)); - } - - @Override - public ActionFeedback onActionStart(GameParticipant initiator, - GameParticipant target) { - ActionFeedback feedback = new ActionFeedback("Fireball"); - if (target == null) { - feedback.addInfo("Can't attack, no enemy selected!"); - return feedback; - } - - Stat i = initiator.getStatList().get(Stat.INTELLIGENCE); - float damage = 0; - if (i != null) - damage = getStatValue(LEVEL) * i.getValue(); - feedback.addInfo("damage", damage); - - float defence = 0; - Stat f = target.getStatList().get(Stat.FIRE_RESISTANCE); - if (f != null) - defence = f.getValue(); - feedback.addInfo("fire resistance of target", defence); - - damage -= defence; - if (damage < 0) - damage = 0; - feedback.addInfo("final damage", damage); - Stat hp = target.getStatList().get(Stat.HP); - if (hp != null) { - float newHp = hp.getValue(); - feedback.addInfo("Target HP before damage", newHp); - newHp -= damage; - feedback.addInfo("Target HP after damage", newHp); - hp.setValue(newHp); - feedback.setActionCorrectExecuted(true); - } - - return feedback; - } - - @Override - public void generateViewGUI(ModifierGroup s) { - s.addModifier(new InfoText("Fireball Level", "" + getStatValue(LEVEL))); - } - - @Override - public void generateEditGUI(ModifierGroup s) { - s.addModifier(new PlusMinusModifier(R.drawable.minuscirclegray, - R.drawable.pluscirclegray) { - - @Override - public boolean save(double currentValue) { - getStatList().get(LEVEL).setValue((int) currentValue); - return true; - } - - @Override - public double plusEvent(double currentValue) { - return currentValue + 1; - } - - @Override - public double minusEvent(double currentValue) { - float level = getStatValue(LEVEL); - if (currentValue - 1 < level) - return level; - return currentValue - 1; - } - - @Override - public double load() { - return getStatValue(LEVEL); - } - - @Override - public String getVarName() { - return myName; - } - }); - } - -} diff --git a/droidar/src/gamelogic/Booster.java b/droidar/src/gamelogic/Booster.java deleted file mode 100644 index b6e675e..0000000 --- a/droidar/src/gamelogic/Booster.java +++ /dev/null @@ -1,87 +0,0 @@ -package gamelogic; - -import gui.simpleUI.ModifierGroup; -import gui.simpleUI.modifiers.InfoText; -import gui.simpleUI.modifiers.PlusMinusModifier; -import android.view.Gravity; -import de.rwth.R; - -public class Booster extends GameElement { - - // some examples: - public static final String MAX_HP_PLUS_15 = "Maximum HP + 15"; - public static final String MAX_HP_MINUS_10 = "Maximum HP - 10"; - public float myValue; - private String myTargetStat; - - /** - * @param uniqueName - * @param iconId - * @param value - * will be added on the stats value (e.g. +20 or -50) - */ - public Booster(String uniqueName, int iconId, float value) { - super(uniqueName, iconId); - myValue = value; - } - - public Booster(String uniqueName, String targetStatName, int iconId, - float value) { - this(uniqueName, iconId, value); - myTargetStat = targetStatName; - } - - public float getValue(float finalValue, float originalValue) { - return finalValue + myValue; - } - - public String getTargetStatName() { - return myTargetStat; - } - - @Override - public void generateEditGUI(ModifierGroup s) { - s.addModifier(new PlusMinusModifier(R.drawable.minuscirclegray, - R.drawable.pluscirclegray) { - - @Override - public boolean save(double currentValue) { - myValue = (float) currentValue; - return true; - } - - @Override - public double plusEvent(double currentValue) { - return currentValue + 1; - } - - @Override - public double minusEvent(double currentValue) { - if (currentValue - 1 <= myValue) - return myValue; - return currentValue - 1; - } - - @Override - public double load() { - return myValue; - } - - @Override - public String getVarName() { - return myName; - } - }); - } - - @Override - public void generateViewGUI(ModifierGroup s) { - if (myValue >= 0) - s.addModifier(new InfoText(" +" + myValue + " by " + myName, - Gravity.RIGHT)); - else - s.addModifier(new InfoText(" " + myValue + " by " + myName, - Gravity.RIGHT)); - } - -} diff --git a/droidar/src/gamelogic/BoosterList.java b/droidar/src/gamelogic/BoosterList.java deleted file mode 100644 index c695ad5..0000000 --- a/droidar/src/gamelogic/BoosterList.java +++ /dev/null @@ -1,15 +0,0 @@ -package gamelogic; - -public class BoosterList extends GameElementList { - - public float getValue(float originalValue) { - int length = length(); - float finalValue = originalValue; - for (int i = 0; i < length; i++) { - finalValue = getAllItems().get(i).getValue(finalValue, - originalValue); - } - return finalValue; - } - -} diff --git a/droidar/src/gamelogic/FactorBooster.java b/droidar/src/gamelogic/FactorBooster.java deleted file mode 100644 index 5df8045..0000000 --- a/droidar/src/gamelogic/FactorBooster.java +++ /dev/null @@ -1,93 +0,0 @@ -package gamelogic; - -import gui.simpleUI.ModifierGroup; -import gui.simpleUI.modifiers.InfoText; -import gui.simpleUI.modifiers.PlusMinusModifier; -import android.view.Gravity; -import de.rwth.R; - -public class FactorBooster extends Booster { - - /** - * this allows bonus values like -10% (90%) or originalValue*3 (300%) for - * any stat - * - * @param uniqueName - * @param iconId - * @param percentValue - * will change the stats value to a specific percentlevel. - * Example: statValue=50 percentValue=80 -> resultValue=40 - */ - public FactorBooster(String uniqueName, int iconId, float percentValue) { - super(uniqueName, iconId, percentValue); - } - - @Override - public float getValue(float finalValue, float originalValue) { - /* - * the original manipulations of the originalValue have to be permanent. - * - * finalValue=110 - * - * originalValue=100 - * - * percentValue=10% - * - * so normaly return 10 but final value is 110 so return - * (110-100)+10%*100=20 correct - * - * 200% -> return (110-100)+200%*100=210 also correct - * - * - * finalValue=50 originalValue=50 50% 50-100 + 50 = 0 - */ - - return (finalValue - originalValue) + originalValue * myValue / 100; - } - - @Override - public void generateEditGUI(ModifierGroup s) { - s.addModifier(new PlusMinusModifier(R.drawable.minuscirclegray, - R.drawable.pluscirclegray) { - - @Override - public boolean save(double currentValue) { - myValue = (float) currentValue; - return true; - } - - @Override - public double plusEvent(double currentValue) { - return currentValue + 10; - } - - @Override - public double minusEvent(double currentValue) { - if (currentValue - 1 <= myValue) - return myValue; - return currentValue - 10; - } - - @Override - public double load() { - return myValue; - } - - @Override - public String getVarName() { - return myName + " (in %)"; - } - }); - } - - @Override - public void generateViewGUI(ModifierGroup s) { - if (myValue >= 0) - s.addModifier(new InfoText(" +" + myValue + "% by " + myName, - Gravity.RIGHT)); - else - s.addModifier(new InfoText(" " + myValue + "% by " + myName, - Gravity.RIGHT)); - } - -} diff --git a/droidar/src/gamelogic/FeedbackReports.java b/droidar/src/gamelogic/FeedbackReports.java deleted file mode 100644 index e6bd914..0000000 --- a/droidar/src/gamelogic/FeedbackReports.java +++ /dev/null @@ -1,24 +0,0 @@ -package gamelogic; - -import util.EfficientList; - -public class FeedbackReports { - - private static FeedbackReports myInstance = new FeedbackReports(); - - public static FeedbackReports getInstance() { - return myInstance; - } - - private EfficientList myFeedbacks = new EfficientList(); - - public void addFeedback(ActionFeedback feedback) { - if (feedback != null) - myFeedbacks.add(feedback); - } - - public static void resetInstance() { - myInstance = new FeedbackReports(); - } - -} diff --git a/droidar/src/gamelogic/GameAction.java b/droidar/src/gamelogic/GameAction.java deleted file mode 100644 index 1b66f20..0000000 --- a/droidar/src/gamelogic/GameAction.java +++ /dev/null @@ -1,124 +0,0 @@ -package gamelogic; - -import util.Log; -import worldData.Updateable; - -public abstract class GameAction extends GameElement { - - private static final String LOG_TAG = "GameAction"; - private StatList myStatList; - private float myCooldownProgress; - private float myCooldownTime; - private boolean updateListeners; - - public GameAction(String uniqueName, float cooldownTime, int iconId) { - super(uniqueName, iconId); - setCooldownTime(cooldownTime); - setCooldownProgress(cooldownTime); - } - - /** - * @param initiator - * @param target - * might be null so always consider that! - * - * @return an ActionFeedback object with all information for fine-tuning and - * balancing should be returned. if the method is manually called - * the ActionFeedback should be registered in the FeedBackReports - * singleton - */ - public abstract ActionFeedback onActionStart(GameParticipant initiator, - GameParticipant target); - - @Override - public boolean updateListeners() { - return updateListeners; - } - - @Override - public boolean update(float timeDelta, Updateable parent) { - if (myCooldownProgress < myCooldownTime) { - // update cooldown time: - myCooldownProgress = myCooldownProgress + timeDelta; - if (myCooldownProgress > myCooldownTime) { - myCooldownProgress = myCooldownTime; - super.update(timeDelta, parent); - updateListeners = false; - } else { - super.update(timeDelta, parent); - } - } else { - super.update(timeDelta, parent); - } - myStatList.update(timeDelta, this); - return true; - } - - @Override - public boolean isAllowedToExecuteOnClickAction() { - return myCooldownTime == myCooldownProgress; - } - - public StatList getStatList() { - if (myStatList == null) - myStatList = new StatList(); - return myStatList; - } - - /** - * @param statName - * @return {@link Float#NaN} if the stat could not be found! - */ - public float getStatValue(String statName) { - if (myStatList == null) { - Log.e(LOG_TAG, "Tryed to get " + statName - + " from emplty statList (was null)"); - return Float.NaN; - } - Stat s = myStatList.get(statName); - if (s == null) { - Log.e(LOG_TAG, "Stat " + statName - + " could not be found! Returning Float.NaN"); - return Float.NaN; - } - return s.getValue(); - } - - public boolean setStatValue(String statName, float newStatValue) { - if (myStatList == null) - return false; - Stat s = getStatList().get(statName); - if (s == null) - return false; - s.setValue(newStatValue); - return true; - } - - public boolean addStat(Stat stat) { - return getStatList().add(stat); - } - - public float getCooldownProgress() { - return myCooldownProgress; - } - - public float getCooldownTime() { - return myCooldownTime; - } - - public void setCooldownProgress(float cooldownProgress) { - myCooldownProgress = cooldownProgress; - } - - public void setCooldownTime(float myCooldownTime) { - this.myCooldownTime = myCooldownTime; - } - - public ActionFeedback doAction(GameParticipant initiator, - GameParticipant target) { - setCooldownProgress(0); - updateListeners = true; - return onActionStart(initiator, target); - } - -} diff --git a/droidar/src/gamelogic/GameElement.java b/droidar/src/gamelogic/GameElement.java deleted file mode 100644 index 307eaef..0000000 --- a/droidar/src/gamelogic/GameElement.java +++ /dev/null @@ -1,175 +0,0 @@ -package gamelogic; - -import gui.ListItem; -import gui.simpleUI.ModifierGroup; -import util.IO; -import worldData.Entity; -import worldData.EntityList; -import worldData.Updateable; -import android.content.Context; -import android.view.View; -import android.view.View.OnClickListener; -import android.view.ViewGroup; -import android.widget.LinearLayout; -import android.widget.TextView; - -import commands.Command; - -public abstract class GameElement implements ListItem, Updateable { - - /** - * if this boolean in true a {@link GameElementList#removeEmptyItems()} call - * will remove it from the {@link GameElementList}. It is set via - * {@link GameElement#setShouldBeRemoved(boolean)} - */ - private boolean shouldBeRemoved; - public String myName; - public int myIconid; - private Command myOnClickCommand; - private Command myListLongClickCommand; - private EntityList myListeners; - - public GameElement(String uniqueName, int iconId) { - myName = uniqueName; - myIconid = iconId; - } - - /** - * Will do the same as {@link GameElement#setOnListClickCommand(Command)} on - * default - * - * @param myOnClickCommand - */ - public void setOnClickCommand(Command myOnClickCommand) { - this.myOnClickCommand = myOnClickCommand; - } - - /** - * Will do the same as {@link GameElement#setOnClickCommand(Command)} on - * default - * - * @param myOnClickCommand - */ - public void setOnListClickCommand(Command myOnClickCommand) { - this.myOnClickCommand = myOnClickCommand; - } - - public Command getOnClickCommand() { - return myOnClickCommand; - } - - @Override - public Command getListClickCommand() { - return myOnClickCommand; - } - - @Override - public Command getListLongClickCommand() { - return myListLongClickCommand; - } - - @Override - public View getMyListItemView(View viewToUseIfNotNull, ViewGroup parentView) { - if (viewToUseIfNotNull instanceof GameElementListItemView) { - ((GameElementListItemView) viewToUseIfNotNull) - .updateContent(parentView.getContext()); - return viewToUseIfNotNull; - } - return new GameElementListItemView(parentView.getContext()); - } - - public boolean shouldBeRemoved() { - return shouldBeRemoved; - } - - /** - * @param b - * set this to true to remove it from a {@link GameElementList} - * when {@link GameElementList#removeEmptyItems()} is called - */ - public void setShouldBeRemoved(boolean b) { - shouldBeRemoved = b; - } - - private class GameElementListItemView extends LinearLayout { - - private GameElementView myIconView; - private TextView myDescriptionView; - - public GameElementListItemView(Context context) { - super(context); - myIconView = new GameElementView(context, myIconid); - myDescriptionView = new TextView(context); - addView(myIconView); - addView(myDescriptionView); - updateContent(context); - } - - public void updateContent(Context context) { - myDescriptionView.setText(myName); - if (myIconid != 0) - myIconView.setIcon(IO.loadBitmapFromId(context, myIconid)); - } - - } - - public abstract void generateViewGUI(ModifierGroup s); - - public abstract void generateEditGUI(ModifierGroup s); - - @Override - public boolean update(float timeDelta, Updateable parent) { - if (myListeners != null && updateListeners()) { - myListeners.update(timeDelta, this); - } - return true; - } - - /** - * Override this method and return false when the listeners of this subclass - * of {@link GameElement} do not have to be updated - */ - public boolean updateListeners() { - return true; - } - - /** - * This will return a {@link View} (on default it is a - * {@link GameElementView}) which will be automatically updated - * - * Call {@link GameElement#registerNewListener(Entity)} if you are - * overriding this message and want to inform the view (is then has to be an - * {@link Entity}) on updates of this {@link GameElement} - * - * @param context - * - * @return - */ - public View getNewDefaultView(Context context) { - GameElementView v = new GameElementView(context, myIconid); - v.setOnClickListener(new OnClickListener() { - - @Override - public void onClick(View v) { - if (myOnClickCommand != null - && isAllowedToExecuteOnClickAction()) - myOnClickCommand.execute(GameElement.this); - } - }); - registerNewListener(v); - return v; - } - - /** - * @return - */ - public boolean isAllowedToExecuteOnClickAction() { - return true; - } - - public void registerNewListener(Entity v) { - if (myListeners == null) - myListeners = new EntityList(); - myListeners.add(v); - } -} diff --git a/droidar/src/gamelogic/GameElementList.java b/droidar/src/gamelogic/GameElementList.java deleted file mode 100644 index 94a4433..0000000 --- a/droidar/src/gamelogic/GameElementList.java +++ /dev/null @@ -1,109 +0,0 @@ -package gamelogic; - -import gui.simpleUI.ModifierGroup; - -import java.util.HashMap; - -import system.Container; -import util.EfficientList; -import worldData.Updateable; -import android.util.Log; - -public abstract class GameElementList implements - Updateable, Container { - - private static final String LOG_TAG = "GameElementList"; - private EfficientList myList = new EfficientList(); - /** - * an additional structure for fast searching for special GameElements - */ - private HashMap mySearchIndex = new HashMap(); - - @Override - public void clear() { - myList.clear(); - mySearchIndex.clear(); - } - - @Override - public boolean update(float timeDelta, Updateable parent) { - for (int i = 0; i < myList.myLength; i++) { - if (!myList.get(i).update(timeDelta, this)) { - Log.w(LOG_TAG, "Removing " + myList.get(i) - + " from list because it returned" - + " false on update()"); - myList.remove(myList.get(i)); - } - } - return true; - } - - @Override - public int length() { - return myList.myLength; - } - - @Override - public EfficientList getAllItems() { - return myList; - } - - @Override - public boolean isCleared() { - return myList.myLength == 0; - } - - @Override - public void removeEmptyItems() { - for (int i = 0; i < myList.myLength; i++) { - GameElement e = myList.get(i); - if (e.shouldBeRemoved()) - myList.remove(e); - - } - } - - @Override - public boolean add(T item) { - mySearchIndex.put(item.myName, item); - return myList.add(item); - } - - /** - * @param uniqueName - * @return null if the elemtent can't be found - */ - public T get(String uniqueName) { - return mySearchIndex.get(uniqueName); - } - - public boolean remove(String uniqueName) { - GameElement itemToDelete = mySearchIndex.get(uniqueName); - mySearchIndex.remove(uniqueName); - return myList.remove(itemToDelete); - } - - @Override - public boolean remove(T item) { - mySearchIndex.remove(item.myName); - return myList.remove(item); - } - - public void generateViewGUI(ModifierGroup s) { - for (int i = 0; i < myList.myLength; i++) { - myList.get(i).generateViewGUI(s); - } - } - - @Override - public boolean insert(int pos, T item) { - return myList.insert(pos, item); - }; - - public void generateEditGUI(ModifierGroup s) { - for (int i = 0; i < myList.myLength; i++) { - myList.get(i).generateEditGUI(s); - } - } - -} diff --git a/droidar/src/gamelogic/GameElementView.java b/droidar/src/gamelogic/GameElementView.java deleted file mode 100644 index e58c575..0000000 --- a/droidar/src/gamelogic/GameElementView.java +++ /dev/null @@ -1,243 +0,0 @@ -package gamelogic; - -import gui.SimpleCustomView; -import util.ImageTransform; -import worldData.Entity; -import worldData.Updateable; -import worldData.Visitor; -import android.content.Context; -import android.graphics.Bitmap; -import android.graphics.Canvas; -import android.graphics.Color; -import android.graphics.Paint; -import android.graphics.PorterDuff; -import android.graphics.PorterDuffXfermode; -import android.graphics.RectF; -import android.graphics.Xfermode; -import android.util.AttributeSet; -import android.util.Log; -import de.rwth.R; - -public class GameElementView extends SimpleCustomView implements Entity { - - private static final int DEFAULT_MAX_WIDTH_IN_DIP = 80; - private static final float DEFAULT_EDITOR_MAX_WIDTH_IN_DIP = 180; - - private static final String LOG_TAG = "GameElementView"; - - private Paint paint; - private Paint loadingPaint; - private Paint loadingLinePaint; - - float myLoadingAngle = 0; - - private Bitmap myIcon; - private Bitmap mutable; - private Canvas stampCanvas; - - private int myWidth; - private int myHeight; - - private Xfermode myXfermode; - private RectF arcRect; - private int myMaxWidth; - - // private String debug; - - public GameElementView(Context context, int iconid) { - super(context); - init((int) dipToPixels(DEFAULT_MAX_WIDTH_IN_DIP), - loadBitmapFromId(context, iconid)); - } - - @Deprecated - public GameElementView(Context context, AttributeSet attrs) { - super(context, attrs); - init((int) dipToPixels(DEFAULT_EDITOR_MAX_WIDTH_IN_DIP), - loadBitmapFromId(context, R.drawable.hippopotamus64)); - } - - public void setIcon(Bitmap icon) { - myIcon = icon; - resizeIconToViewSize(); - } - - private void resizeIconToViewSize() { - if (myIcon != null) { - myIcon = ImageTransform.resizeBitmap(myIcon, myHeight, myWidth); - myIcon = ImageTransform.createBitmapWithRoundCorners(myIcon, 8f); - } - } - - private void drawLoadingCircle(Canvas canvas, Paint paint) { - if (myLoadingAngle != 0 && myLoadingAngle != 360) { - - // Draw the Minutes-Arc into that rectangle - canvas.drawArc(arcRect, -90, myLoadingAngle, true, paint); - } - } - - private void init(int maxWidth, Bitmap icon) { - - paint = new Paint(); - myXfermode = new PorterDuffXfermode(PorterDuff.Mode.DST_IN); - loadingPaint = new Paint(Paint.ANTI_ALIAS_FLAG); - loadingPaint.setColor(Color.RED); - loadingPaint.setAlpha(100); - - loadingLinePaint = new Paint(); - loadingLinePaint = new Paint(Paint.ANTI_ALIAS_FLAG); - loadingLinePaint.setColor(Color.BLACK); - loadingLinePaint.setStyle(Paint.Style.STROKE); - loadingLinePaint.setStrokeWidth(3); - - myMaxWidth = maxWidth; - setSize(maxWidth, icon); - - if (isInEditMode()) - loadDemoValues(); - setIcon(icon); - } - - public void setSize(int newWidth, Bitmap icon) { - myWidth = newWidth; - if (myWidth > myMaxWidth) - myWidth = myMaxWidth; - if (icon != null) { - myHeight = (int) ((float) (icon.getHeight()) - / (float) (icon.getWidth()) * (float) (myWidth)); - } else { - myHeight = myWidth; - } - Log.w(LOG_TAG, "New height=" + myHeight); - Log.w(LOG_TAG, "New width=" + myWidth); - - if (myHeight <= 0 || myWidth <= 0) { - Log.e(LOG_TAG, "height or width were 0!"); - Log.w(LOG_TAG, " > icon=" + icon); - Log.w(LOG_TAG, " > icon.getHeight()=" + icon.getHeight()); - Log.w(LOG_TAG, " > icon.getWidth()=" + icon.getWidth()); - Log.w(LOG_TAG, " > recommendedWidth=" + newWidth); - showDebugInfos(); - } - - float x = myWidth * 0.5f; - arcRect = new RectF(-x, -x, myWidth + x, myHeight + x); - - mutable = Bitmap.createBitmap(myWidth, myHeight, - Bitmap.Config.ARGB_8888); - stampCanvas = new Canvas(mutable); - resizeIconToViewSize(); - } - - public void showDebugInfos() { - Log.w(LOG_TAG, " > myHeight=" + myHeight); - Log.w(LOG_TAG, " > myWidth=" + myWidth); - Log.w(LOG_TAG, " > myIcon=" + myIcon); - Log.w(LOG_TAG, " > myLoadingAngle=" + myLoadingAngle); - } - - /** - * This method will only be called when the view is displayed in the eclipse - * xml layout editor - */ - private void loadDemoValues() { - setLoadingAngle(160); - } - - public void setLoadingAngle(float myLoadingAngle) { - this.myLoadingAngle = myLoadingAngle; - this.postInvalidate(); - } - - @Override - public void onResizeEvent(int recommendedHeight, int recommendedWidth) { - int min = Math.min(recommendedHeight, recommendedHeight); - Log.i(LOG_TAG, "New recommended width=" + recommendedWidth); - Log.i(LOG_TAG, "New recommended heigth=" + recommendedHeight); - Log.d(LOG_TAG, "Choosen minimum=" + min); - setSize(min, myIcon); - setMeasuredDimension(myWidth, myHeight); - } - - @Override - protected void onDraw(Canvas onDrawCanvas) { - - // stampCanvas.drawARGB(0, 0, 0, 0); - stampCanvas.drawBitmap(myIcon, 0, 0, paint); - // Bitmap i2 = generateDebugImage2(getContext()); - // canvas.drawBitmap(i2, 0, 0, paint); - drawLoadingCircle(stampCanvas, loadingPaint); - drawLoadingCircle(stampCanvas, loadingLinePaint); - paint.setXfermode(myXfermode); - stampCanvas.drawBitmap(myIcon, 0, 0, paint); - paint.setXfermode(null); - - onDrawCanvas.drawBitmap(mutable, 0, 0, paint); - - // if (debug != null) { // TODO remove this - // paint.setColor(Color.RED); - // canvas.drawText(debug, 0, myHalfSize, paint); - // } - } - - // @Override - // public boolean onTouchEvent(MotionEvent event) { - // return onTouch(event.getX() - myHalfWidth, event.getY() - myHalfHeight); - // } - // - // private boolean onTouch(float x, float y) { - // double distFromCenter = Math.sqrt(x * x + y * y); - // distFromCenter *= myTouchScaleFactor; - // setLoadingAngle((float) (Math.random() * 359)); - // postInvalidate(); - // return true; - // } - - @Override - public boolean update(float timeDelta, Updateable parent) { - - if (parent instanceof GameAction) { - GameAction a = (GameAction) parent; - float prog = a.getCooldownProgress(); - float max = a.getCooldownTime(); - if (prog != Float.NaN && max != Float.NaN) { - if (prog + timeDelta < max) { - a.setCooldownProgress(prog + timeDelta); - this.setLoadingAngle((prog + timeDelta) / max * 360); - } else { - a.setCooldownProgress(max); - this.setLoadingAngle(360); - } - } else { - Log.e(LOG_TAG, "The parent action has not the required values"); - this.setLoadingAngle(360); - } - - } - /* - * TODO if view was removed from parent it can return false here! - */ - return true; - } - - @Override - public Updateable getMyParent() { - Log.e(LOG_TAG, "Get parent called which is not " - + "implemented for this component!"); - return null; - } - - @Override - public void setMyParent(Updateable parent) { - // can't have children so the parent does not have to be stored - Log.e(LOG_TAG, "Set parent called which is not " - + "implemented for this component!"); - } - - @Override - public boolean accept(Visitor visitor) { - return false; - } - -} diff --git a/droidar/src/gamelogic/GameItem.java b/droidar/src/gamelogic/GameItem.java deleted file mode 100644 index d0404d6..0000000 --- a/droidar/src/gamelogic/GameItem.java +++ /dev/null @@ -1,9 +0,0 @@ -package gamelogic; - -public abstract class GameItem extends GameElement { - - public GameItem(String uniqueName, int iconId) { - super(uniqueName, iconId); - } - -} diff --git a/droidar/src/gamelogic/GameItemList.java b/droidar/src/gamelogic/GameItemList.java deleted file mode 100644 index 672f311..0000000 --- a/droidar/src/gamelogic/GameItemList.java +++ /dev/null @@ -1,5 +0,0 @@ -package gamelogic; - -public class GameItemList extends GameElementList { - -} diff --git a/droidar/src/gamelogic/GameParticipant.java b/droidar/src/gamelogic/GameParticipant.java deleted file mode 100644 index aa5b2d3..0000000 --- a/droidar/src/gamelogic/GameParticipant.java +++ /dev/null @@ -1,186 +0,0 @@ -package gamelogic; - -import gui.simpleUI.EditItem; -import gui.simpleUI.ModifierGroup; - -import java.util.Arrays; - -import util.Log; -import worldData.Entity; -import worldData.Updateable; -import worldData.Visitor; - -import commands.Command; - -public class GameParticipant implements Entity, EditItem { - - private static final String LOG_TAG = "GameParticipant"; - private StatList myStatList; - private ActionList myActionList; - private GameItemList myGameItemList; - private String myType; - private String myName; - private int myIconId; - private Updateable myParent; - - public GameParticipant(String type, String participantName, int iconId) { - myType = type; - myName = participantName; - myIconId = iconId; - } - - public String getName() { - return myName; - } - - public String getType() { - return myType; - } - - public int getIconId() { - return myIconId; - } - - public StatList getStatList() { - if (myStatList == null) - myStatList = new StatList(); - return myStatList; - } - - /** - * @param statName - * @return {@link Float#NaN} if the stat could not be found! - */ - public float getStatValue(String statName) { - if (myStatList == null) { - Log.e(LOG_TAG, "Tryed to get " + statName - + " from emplty statList (was null)"); - return Float.NaN; - } - Stat s = myStatList.get(statName); - if (s == null) { - Log.e(LOG_TAG, "Stat " + statName - + " could not be found! Returning Float.NaN"); - return Float.NaN; - } - return s.getValue(); - } - - public boolean setStatValue(String statName, float newStatValue) { - if (myStatList == null) - return false; - Stat s = getStatList().get(statName); - if (s == null) - return false; - s.setValue(newStatValue); - return true; - } - - public ActionList getActionList() { - if (myActionList == null) - myActionList = new ActionList(); - return myActionList; - } - - public GameItemList getGameItemList() { - if (myGameItemList == null) - myGameItemList = new GameItemList(); - return myGameItemList; - } - - public ActionFeedback doAction(String actionName, GameParticipant target) { - if (actionName == null) - return null; - GameAction a = getActionList().get(actionName); - if (a != null) { - ActionFeedback feedback = a.doAction(this, target); - FeedbackReports.getInstance().addFeedback(feedback); - return feedback; - } - return null; - } - - public void generateEditGUI(ModifierGroup s) { - if (myStatList != null) { - myStatList.generateEditGUI(s); - } - if (myActionList != null) - myActionList.generateEditGUI(s); - - if (myGameItemList != null) - myGameItemList.generateEditGUI(s); - } - - public void generateViewGUI(ModifierGroup s) { - if (myStatList != null) - myStatList.generateViewGUI(s); - if (myActionList != null) - myActionList.generateViewGUI(s); - if (myGameItemList != null) - myGameItemList.generateViewGUI(s); - } - - @Override - public Updateable getMyParent() { - return myParent; - } - - @Override - public void setMyParent(Updateable parent) { - myParent = parent; - } - - @Override - public boolean update(float timeDelta, Updateable parent) { - setMyParent(parent); - if (myActionList != null) - myActionList.update(timeDelta, parent); - if (myStatList != null) - myStatList.update(timeDelta, parent); - if (myGameItemList != null) - myGameItemList.update(timeDelta, parent); - return true; - } - - @Override - public boolean accept(Visitor visitor) { - return visitor.default_visit(this); - } - - public boolean addStat(Stat stat) { - return getStatList().add(stat); - } - - public boolean addAction(GameAction action) { - if (action.getOnClickCommand() == null) - setDefaultExecuteAction(action); - return getActionList().add(action); - } - - private void setDefaultExecuteAction(final GameAction action) { - action.setOnClickCommand(new Command() { - @Override - public boolean execute() { - return action.doAction(GameParticipant.this, null) - .actionCorrectlyExecuted(); - } - }); - } - - @Override - public void customizeScreen(ModifierGroup group, Object message) { - - if (message instanceof String) { - String m = (String) message; - String[] keywords = { "Edit", "edit", "editscreen", "Edit screen", - "edit mode", "editmode", "Editmode" }; // TODO - if (Arrays.asList(keywords).contains(m)) { - generateEditGUI(group); - } - } else { - generateViewGUI(group); - } - - } - -} diff --git a/droidar/src/gamelogic/NameGenerator.java b/droidar/src/gamelogic/NameGenerator.java deleted file mode 100644 index 1144da6..0000000 --- a/droidar/src/gamelogic/NameGenerator.java +++ /dev/null @@ -1,109 +0,0 @@ -package gamelogic; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -public class NameGenerator { - - private List vocals = new ArrayList(); - private List startConsonants = new ArrayList(); - private List endConsonants = new ArrayList(); - private List nameInstructions = new ArrayList(); - - public NameGenerator() { - String demoVocals[] = { "a", "e", "i", "o", "u", "ei", "ai", "ou", "j", - "ji", "y", "oi", "au", "oo" }; - - String demoStartConsonants[] = { "b", "c", "d", "f", "g", "h", "k", - "l", "m", "n", "p", "q", "r", "s", "t", "v", "w", "x", "z", - "ch", "bl", "br", "fl", "gl", "gr", "kl", "pr", "pl", "st", - "sh", "th", "tw" }; - - String demoEndConsonants[] = { "b", "d", "f", "g", "h", "k", "l", "m", - "n", "p", "r", "s", "t", "v", "w", "z", "ch", "gh", "nn", "st", - "sh", "th", "tt", "ss", "pf", "nt" }; - - String nameInstructions[] = { "vd", "cvdvd", "cvd", "vdvd", "vdvdvd" }; - - this.vocals.addAll(Arrays.asList(demoVocals)); - this.startConsonants.addAll(Arrays.asList(demoStartConsonants)); - this.endConsonants.addAll(Arrays.asList(demoEndConsonants)); - this.nameInstructions.addAll(Arrays.asList(nameInstructions)); - } - - /** - * - * The names will look like this - * (v=vocal,c=startConsonsonant,d=endConsonants): vd, cvdvd, cvd, vdvd - * - * @param vocals - * pass something like {"a","e","ou",..} - * @param startConsonants - * pass something like {"s","f","kl",..} - * @param endConsonants - * pass something like {"th","sh","f",..} - */ - public NameGenerator(String[] vocals, String[] startConsonants, - String[] endConsonants) { - this.vocals.addAll(Arrays.asList(vocals)); - this.startConsonants.addAll(Arrays.asList(startConsonants)); - this.endConsonants.addAll(Arrays.asList(endConsonants)); - } - - /** - * see {@link NameGenerator#NameGenerator(String[], String[], String[])} - * - * @param vocals - * @param startConsonants - * @param endConsonants - * @param nameInstructions - * Use only the following letters: - * (v=vocal,c=startConsonsonant,d=endConsonants)! Pass something - * like {"vd", "cvdvd", "cvd", "vdvd"} - */ - public NameGenerator(String[] vocals, String[] startConsonants, - String[] endConsonants, String[] nameInstructions) { - this(vocals, startConsonants, endConsonants); - this.nameInstructions.addAll(Arrays.asList(nameInstructions)); - } - - public String getName() { - return firstCharUppercase(getNameByInstructions(getRandomElementFrom(nameInstructions))); - } - - private int randomInt(int min, int max) { - return (int) (min + (Math.random() * (max + 1 - min))); - } - - private String getNameByInstructions(String nameInstructions) { - String name = ""; - int l = nameInstructions.length(); - - for (int i = 0; i < l; i++) { - char x = nameInstructions.charAt(0); - switch (x) { - case 'v': - name += getRandomElementFrom(vocals); - break; - case 'c': - name += getRandomElementFrom(startConsonants); - break; - case 'd': - name += getRandomElementFrom(endConsonants); - break; - } - nameInstructions = nameInstructions.substring(1); - } - return name; - } - - private String firstCharUppercase(String name) { - return Character.toString(name.charAt(0)).toUpperCase() - + name.substring(1); - } - - private String getRandomElementFrom(List v) { - return v.get(randomInt(0, v.size() - 1)); - } -} diff --git a/droidar/src/gamelogic/Stat.java b/droidar/src/gamelogic/Stat.java deleted file mode 100644 index 022ecbc..0000000 --- a/droidar/src/gamelogic/Stat.java +++ /dev/null @@ -1,160 +0,0 @@ -package gamelogic; - -import gui.simpleUI.ModifierGroup; -import gui.simpleUI.modifiers.InfoText; -import gui.simpleUI.modifiers.PlusMinusModifier; -import worldData.Updateable; -import android.content.Context; -import android.view.View; -import android.view.ViewGroup; -import android.widget.ImageView; -import android.widget.LinearLayout; -import android.widget.TextView; -import de.rwth.R; - -public class Stat extends GameElement { - - // just some examples: - public static final String MAX_HP = "Max. HP"; - public static final String HP = "HP"; - public static final String MAX_MANA = "Max. Mana"; - public static final String MANA = "Mana"; - public static final String GOLD = "Gold"; - public static final String STRENGTH = "Strength"; - public static final String AGILITY = "Agility"; - public static final String INTELLIGENCE = "Intelligence"; - public static final String MIN_DAMAGE = "Min. Damage"; - public static final String MAX_DAMAGE = "Max. Damage"; - public static final String FIRE_RESISTANCE = "Fire resistance"; - - private float myValue; - private BoosterList myBoosterList; - - public Stat(String uniqueName, int iconId, float value) { - super(uniqueName, iconId); - myValue = value; - } - - public BoosterList getMyBoosterList() { - return myBoosterList; - } - - @Override - public View getMyListItemView(View viewToUseIfNotNull, ViewGroup parentView) { - if (viewToUseIfNotNull instanceof StatListItemView) { - ((StatListItemView) viewToUseIfNotNull).updateContent(); - return viewToUseIfNotNull; - } - return new StatListItemView(parentView.getContext()); - } - - public float getValue() { - if (myBoosterList != null) - return myBoosterList.getValue(myValue); - return myValue; - } - - private class StatListItemView extends LinearLayout { - - private ImageView myIconView; - private TextView myDescriptionView; - private TextView myValueView; - - public StatListItemView(Context context) { - super(context); - myIconView = new ImageView(context); - myDescriptionView = new TextView(context); - addView(myIconView); - LinearLayout l2 = new LinearLayout(context); - l2.setOrientation(LinearLayout.VERTICAL); - l2.addView(myDescriptionView); - l2.addView(myValueView); - addView(l2); - updateContent(); - } - - public void updateContent() { - myDescriptionView.setText(myName); - myValueView.setText("" + myValue); - if (myIconid != 0) - myIconView.setBackgroundResource(myIconid); - } - - } - - public boolean addBooster(Booster booster) { - if (myBoosterList == null) - myBoosterList = new BoosterList(); - return myBoosterList.add(booster); - } - - public void setValue(float newValue) { - if (myBoosterList != null) { - float boostValue = myBoosterList.getValue(0); - myValue = newValue - boostValue; - // TODO redesign this, too risky this way - } else { - myValue = newValue; - } - } - - @Override - public void generateEditGUI(ModifierGroup s) { - s.addModifier(new PlusMinusModifier(R.drawable.minuscirclegray, - R.drawable.pluscirclegray) { - - @Override - public boolean save(double currentValue) { - myValue = (float) currentValue; - return true; - } - - @Override - public double plusEvent(double currentValue) { - return currentValue + 1; - } - - @Override - public double minusEvent(double currentValue) { - if (currentValue - 1 <= myValue) - return myValue; - return currentValue - 1; - } - - @Override - public double load() { - return myValue; - } - - @Override - public String getVarName() { - return myName; - } - }); - } - - @Override - public void generateViewGUI(ModifierGroup s) { - if (myValue >= 0) - s.addModifier(new InfoText(myName + ":", "+" + myValue)); - else - s.addModifier(new InfoText(myName + ":", "" + myValue)); - } - - /** - * if you want to decrease the stat by -10.5 just pass -10.5f here - * - * @param incrValue - */ - public void incValue(float incrValue) { - setValue(getValue() + incrValue); - } - - @Override - public boolean update(float timeDelta, Updateable parent) { - super.update(timeDelta, parent); - if (myBoosterList != null) - myBoosterList.update(timeDelta, parent); - return true; - } -} diff --git a/droidar/src/gamelogic/StatList.java b/droidar/src/gamelogic/StatList.java deleted file mode 100644 index 96fa69b..0000000 --- a/droidar/src/gamelogic/StatList.java +++ /dev/null @@ -1,43 +0,0 @@ -package gamelogic; - -import gui.simpleUI.ModifierGroup; -import util.EfficientList; - -public class StatList extends GameElementList { - - public boolean applyBooster(Booster booster) { - String targetname = booster.getTargetStatName(); - Stat target = get(targetname); - if (target != null) { - return target.addBooster(booster); - } - return false; - } - - /** - * @param boosterList - * @return true if all booster were applied correctly - */ - public boolean applyBoosterList(BoosterList boosterList) { - int size = boosterList.length(); - EfficientList items = boosterList.getAllItems(); - boolean result = true; - for (int i = 0; i < size; i++) { - result &= applyBooster(items.get(i)); - } - return result; - } - - @Override - public void generateEditGUI(ModifierGroup s) { - EfficientList statList = getAllItems(); - int l = getAllItems().myLength; - for (int i = 0; i < l; i++) { - Stat o = statList.get(i); - o.generateEditGUI(s); - if (o.getMyBoosterList() != null) - o.getMyBoosterList().generateViewGUI(s); - } - } - -} diff --git a/droidar/src/gamelogic/concept.uxf b/droidar/src/gamelogic/concept.uxf deleted file mode 100644 index 917b328..0000000 --- a/droidar/src/gamelogic/concept.uxf +++ /dev/null @@ -1,142 +0,0 @@ -// Uncomment the following line to change the fontsize: -// fontsize=14 - - -////////////////////////////////////////////////////////////////////////////////////////////// -// Welcome to UMLet! -// -// Double-click on UML elements to add them to the diagram, or to copy them -// Edit elements by modifying the text in this panel -// Hold Ctrl to select multiple elements -// Use Ctrl+mouse to select via lasso -// -// Use ± or Ctrl+mouse wheel to zoom -// Drag a whole relation at its central square icon -// -// Press Ctrl+C to copy the whole diagram to the system clipboard (then just paste it to, eg, Word) -// Edit the files in the "palettes" directory to create your own element palettes -// -// Select "Custom Elements > New..." to create new element types -////////////////////////////////////////////////////////////////////////////////////////////// - - -// This text will be stored with each diagram; use it for notes.7com.umlet.element.base.Class141430818249*PlayerComp* --- -- String playerId -com.umlet.element.base.Class114838514749*TowerComp* --- -com.umlet.element.base.Class126746214749*EnemyComp* --- -com.umlet.element.base.Class15195614749*ExampleSetup* --- -fg=redcom.umlet.element.base.Relation149184112231lt=<- -myPlayer21;224;105;21com.umlet.element.base.Class69319614749*GameElementList* --- -com.umlet.element.base.Class40637116849/*GameElement*/ --- -- String uniqueName -- boolean shouldBeRemovedcom.umlet.element.base.Relation819203174132lt=<<-21;21;161;21;161;119com.umlet.element.base.Class86152514770*ExpansionSet* --- -String name --- -showStatList() -showBoosterList() -showActionList()com.umlet.element.base.Relation95937883160lt=<- -70;21;21;147com.umlet.element.base.Class95232217577*StatList* --- - - -com.umlet.element.base.Class49054616877*Stat* --- -- float value --- -getValue() -com.umlet.element.base.Class23144816877*Booster* --- - -- float value -- String target --- -getValue(Stat originalValue) -com.umlet.element.base.Class37864430177/*Action*/ --- - -+ do(GameParticipant initiator, GameParticipant target):ActionFeedbackcom.umlet.element.base.Class30884016877*AttackWithFireball* --- -/ / level= fireBallLevel - --- -com.umlet.element.base.Relation42770034153lt=<<-21;21;21;140com.umlet.element.base.Note0707350105+ do(StatHolder initiator, StatHolder target){ -float damage=calcDamagePoints(initiator); -Wrapper DefencePoints=initiator.doAction(GetDefencePoints.class, target); -Wrapper fireResistance=initiator.doAction(GetFireResistance.class, target); -if defencePoints!=null - damage-=defencePoints.getFloatValue() -if fireResistance!=null - damage-=fireResistance.getFloatValue() - -}com.umlet.element.base.Class120414717577 -*GameParticipant* --- - -update all game-elementscom.umlet.element.base.Relation1092203139132lt=-> -myStatList126;21;21;119com.umlet.element.base.Relation1344203111118lt=<<-21;21;98;105com.umlet.element.base.Relation128820355272lt=<<-21;21;42;259com.umlet.element.base.Relation120420362195lt=<<-49;21;21;182com.umlet.element.base.Class34395916877*GetDefencePoints* --- - --- -com.umlet.element.base.Relation46970041272lt=<<-28;21;21;259com.umlet.element.base.Class136539214749*ItemComp* --- -com.umlet.element.base.Relation132320369202lt=<<-21;21;56;189com.umlet.element.base.Class63791016877*Heal* --- - --- -com.umlet.element.base.Relation49039955160lt=<<-42;21;21;147com.umlet.element.base.Relation44139934258lt=<<-21;21;21;245com.umlet.element.base.Relation532700195223lt=<<-21;21;182;210com.umlet.element.base.Relation14779120262lt=.21;21;189;49com.umlet.element.base.Relation68622434160lt=<<-21;21;21;147com.umlet.element.base.Relation560413125146lt=<- - -112;21;21;133com.umlet.element.base.Class525100816877*Buy FireTower* --- - --- -com.umlet.element.base.Relation490700132321lt=<<-21;21;119;308com.umlet.element.base.Note3295538477+10 -+10% --30 -...com.umlet.element.base.Relation3365044862lt=.21;21;35;49com.umlet.element.base.Relation525217181167lt=<- -m1= * - 21;154;168;21com.umlet.element.base.Relation30839913962lt=<<-126;21;21;49com.umlet.element.base.Relation2455043476lt=<<-21;21;21;63com.umlet.element.base.Class21056710542*%Booster* - -com.umlet.element.base.Relation861364111174lt=<- -21;21;98;161com.umlet.element.base.Class79830811977*ActiontList* --- - -com.umlet.element.base.Relation7982243497lt=<<-21;21;21;84com.umlet.element.base.Relation868168349153lt=-> -myActionList336;21;21;140com.umlet.element.base.Class61637111263*BoosterList* --- - - -com.umlet.element.base.Relation707399216139lt=<- - - 21;21;203;126com.umlet.element.base.Class76381913377*IncreaseStat* --- -String target --- -com.umlet.element.base.Relation602700230132lt=<<-21;21;217;119com.umlet.element.base.Relation483224468314lt=<<.21;21;266;133;455;301com.umlet.element.base.Relation12745641104lt=<<.21;21;28;91com.umlet.element.base.Class1211018277 -*Component* --- - -com.umlet.element.base.Class742357749<<interface>> -*Collection* --- -com.umlet.element.base.Relation7566341146lt=<<.28;21;21;133com.umlet.element.base.Class33619616849<<interface>> -*ListItem* --- -com.umlet.element.base.Relation385224118160lt=<<.21;21;105;147com.umlet.element.base.Class69352510549*GameItem* --- -com.umlet.element.base.Relation532399209139lt=<<-21;21;196;126com.umlet.element.base.Class91010517577*GameItemList* --- -com.umlet.element.base.Relation106411915362lt=-> -myItemList140;49;21;21com.umlet.element.base.Relation81956132160lt=<<-21;147;49;147;49;21;119;21;119;49com.umlet.element.base.Relation7775259749lt=<- - - 84;35;21;35com.umlet.element.base.Class72864413377*ActionFeedback* -com.umlet.element.base.Class5183516849*Updatable* --- -com.umlet.element.base.Relation5116383321lt=<<-70;21;21;308com.umlet.element.base.Relation6376383146lt=<<-21;21;70;133com.umlet.element.base.Relation637378475279lt=<- -myStatList462;21;378;238;56;238;21;266 \ No newline at end of file diff --git a/droidar/src/gl/CustomGLSurfaceView.java b/droidar/src/gl/CustomGLSurfaceView.java index c952935..79a6537 100644 --- a/droidar/src/gl/CustomGLSurfaceView.java +++ b/droidar/src/gl/CustomGLSurfaceView.java @@ -6,8 +6,8 @@ import java.util.List; import listeners.eventManagerListeners.TouchMoveListener; +import setup.ArSetup; import system.EventManager; -import system.Setup; import system.TouchEventInterface; import util.Log; import android.content.Context; @@ -68,7 +68,7 @@ private void initGLSurfaceView(Context context) { setDebugFlags(DEBUG_CHECK_GL_ERROR | DEBUG_LOG_GL_CALLS); } - int screenOrientation = Setup.getScreenOrientation(); + int screenOrientation = ArSetup.getScreenOrientation(); if (screenOrientation == Surface.ROTATION_90 || screenOrientation == Surface.ROTATION_270) { LANDSCAPE_MODE = true; diff --git a/droidar/src/gl/ObjectPicker.java b/droidar/src/gl/ObjectPicker.java index 05c9351..da893a3 100644 --- a/droidar/src/gl/ObjectPicker.java +++ b/droidar/src/gl/ObjectPicker.java @@ -9,7 +9,6 @@ import javax.microedition.khronos.opengles.GL10; import listeners.SelectionListener; -import system.Setup; import util.Log; import util.Wrapper; diff --git a/droidar/src/gl2/GL2SurfaceView.java b/droidar/src/gl2/GL2SurfaceView.java deleted file mode 100644 index ae6faf2..0000000 --- a/droidar/src/gl2/GL2SurfaceView.java +++ /dev/null @@ -1,22 +0,0 @@ -package gl2; - -import gl.CustomGLSurfaceView; -import android.content.Context; - -public class GL2SurfaceView extends CustomGLSurfaceView { - - public GL2SurfaceView(Context context) { - super(context); - /* - * Create an OpenGL ES 2.0 context. - * - * IMPORTANT: - * - * If the following line causes COMPILE ERRORS set the Android version - * to 2.2 or higher (or update the droidar project to the latest version - * ;) - */ - setEGLContextClientVersion(2); - } - -} diff --git a/droidar/src/gui/GuiSetup.java b/droidar/src/gui/GuiSetup.java index b6c8a39..6c5fb63 100644 --- a/droidar/src/gui/GuiSetup.java +++ b/droidar/src/gui/GuiSetup.java @@ -1,7 +1,6 @@ package gui; import setup.ArSetup; -import system.Setup; import system.TaskManager; import util.Log; import util.Wrapper; diff --git a/droidar/src/listeners/SelectionListener.java b/droidar/src/listeners/SelectionListener.java index a3c966d..60091b5 100644 --- a/droidar/src/listeners/SelectionListener.java +++ b/droidar/src/listeners/SelectionListener.java @@ -6,38 +6,38 @@ public interface SelectionListener { - public Command getOnClickCommand(); + Command getOnClickCommand(); - public Command getOnLongClickCommand(); + Command getOnLongClickCommand(); - public Command getOnMapClickCommand(); + Command getOnMapClickCommand(); - public Command getOnDoubleClickCommand(); + Command getOnDoubleClickCommand(); /** * This will enable the selection mechanism (like color-picking in the - * {@link MeshComponent}) if possible + * {@link MeshComponent}) if possible. * - * @param c + * @param cmd - {@link commands.Command} */ - public void setOnClickCommand(Command c); + void setOnClickCommand(Command cmd); /** * This will enable the selection mechanism (like color-picking in the - * {@link MeshComponent}) if possible + * {@link MeshComponent}) if possible. * - * @param c + * @param cmd - {@link commands.Command} */ - public void setOnDoubleClickCommand(Command c); + void setOnDoubleClickCommand(Command cmd); /** * This will enable the selection mechanism (like color-picking in the * {@link MeshComponent}) if possible * - * @param c + * @param cmd - - {@link commands.Command} */ - public void setOnLongClickCommand(Command c); + public void setOnLongClickCommand(Command cmd); - public void setOnMapClickCommand(Command c); + public void setOnMapClickCommand(Command cmd); } diff --git a/droidar/src/listeners/SetupListener.java b/droidar/src/listeners/SetupListener.java index 7e81002..b815526 100644 --- a/droidar/src/listeners/SetupListener.java +++ b/droidar/src/listeners/SetupListener.java @@ -1,17 +1,13 @@ package listeners; -import system.Setup; - /** * this listener interface can be used to enable feedback for the user and for * debugging purpose. To get an overview over the different steps take a look at - * the constants in the {@link Setup}-class + * the constants in the {@link setup.ArSetup}-class * * Any custom setup can add additional steps by using the doSetupStep()-method * provided by the Setup-class. * - * @author Spobo - * */ public interface SetupListener { diff --git a/droidar/src/network/TCP.java b/droidar/src/network/TCP.java deleted file mode 100644 index 555a606..0000000 --- a/droidar/src/network/TCP.java +++ /dev/null @@ -1,162 +0,0 @@ -package network; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.PrintWriter; -import java.net.InetAddress; -import java.net.NetworkInterface; -import java.net.ServerSocket; -import java.net.Socket; -import java.net.SocketException; -import java.net.UnknownHostException; -import java.util.Enumeration; - -public class TCP { - - public static interface ResponseListener { - public void onResponse(String responseMessage); - } - - public static class Client { - - private Socket mySocket; - private PrintWriter myWriter; - private BufferedReader myReader; - - public Client(String serverIp, int serverPort) { - try { - mySocket = new Socket(serverIp, serverPort); - myWriter = new PrintWriter(mySocket.getOutputStream()); - myReader = new BufferedReader(new InputStreamReader( - mySocket.getInputStream())); - } catch (UnknownHostException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } - - } - - public void killConnection() { - try { - mySocket.close(); - System.out.println("TCP Client killed by user"); - } catch (IOException e) { - e.printStackTrace(); - } - } - - public void send(final String message, final ResponseListener listener) { - new Thread(new Runnable() { - @Override - public void run() { - try { - myWriter.println(message); - System.out - .println("TCP Client send message, waiting for response"); - listener.onResponse(myReader.readLine()); - } catch (Exception e) { - e.printStackTrace(); - } - } - }).start(); - } - - } - - public static interface MessageListener { - public void onMessage(String message, Responder response); - } - - public static class Responder { - - private PrintWriter myWriter; - - public Responder(PrintWriter printWriter) { - myWriter = printWriter; - } - - public void send(String response) { - myWriter.println(response); - System.out.println("TCP Server send response=" + response); - } - - } - - public static class Server { - // private ServerSocket myServerSocket; - // private MessageListener myListener; - private boolean running = true; - - public void waitForMessage(int port, MessageListener listener) { - try { - final ServerSocket myServerSocket = new ServerSocket(port); - final MessageListener myListener = listener; - new Thread(new Runnable() { - @Override - public void run() { - try { - System.out - .println("TCP Server waiting for connection"); - Socket socket = myServerSocket.accept(); - BufferedReader inputStream = new BufferedReader( - new InputStreamReader(socket - .getInputStream())); - Responder response = new Responder(new PrintWriter( - socket.getOutputStream(), true)); - System.out - .println("TCP Server has connection, waiting for message"); - while (running) { - System.out - .println("TCP Server is waiting for a new Line"); - myListener.onMessage(inputStream.readLine(), - response); - } - System.out - .println("TCP Server stoped, closing connection"); - socket.close(); - myServerSocket.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - }).start(); - } catch (IOException e) { - e.printStackTrace(); - } - } - - public void killServer() { - System.out.println("TCP Server killed by user"); - running = false; - } - - } - - /** - * iterates over all network interfaces (3G, WiFi,..) to find the ip - * - * @return null if there is no connection available - */ - public static String getDeviceIp() { - try { - for (Enumeration interfaces = NetworkInterface - .getNetworkInterfaces(); interfaces.hasMoreElements();) { - NetworkInterface netInterface = interfaces.nextElement(); - for (Enumeration ipAddresses = netInterface - .getInetAddresses(); ipAddresses.hasMoreElements();) { - InetAddress inetAddress = ipAddresses.nextElement(); - if (!inetAddress.isLoopbackAddress()) { - return inetAddress.getHostAddress().toString(); - } - } - } - } catch (SocketException e) { - e.printStackTrace(); - } - return null; - - } - -} diff --git a/droidar/src/network/UDP.java b/droidar/src/network/UDP.java deleted file mode 100644 index db3bb0d..0000000 --- a/droidar/src/network/UDP.java +++ /dev/null @@ -1,153 +0,0 @@ -package network; - -import java.io.IOException; -import java.net.DatagramPacket; -import java.net.DatagramSocket; -import java.net.InetAddress; -import java.net.NetworkInterface; -import java.net.SocketException; -import java.net.UnknownHostException; -import java.util.Enumeration; - -import util.Log; - -public class UDP { - - public static interface ReceiveListener { - public void onReceive(String message); - } - - public static class Server implements Runnable { - - private static final long SLEEP_TIME = 100; - private static final int MAX_LENGTH = 2000; - private DatagramSocket mySocket; - private boolean running = true; - private ReceiveListener myReceiveListener; - private boolean listenToTheMusic; - - public Server(int serverPort) { - try { - mySocket = new DatagramSocket(serverPort); - } catch (SocketException e) { - e.printStackTrace(); - } - Thread t = new Thread(this); - t.start(); - } - - public void closeConnection() { - mySocket.close(); - running = false; - } - - @Override - public void run() { - while (running) { - if (listenToTheMusic) { - byte[] message = new byte[MAX_LENGTH]; - DatagramPacket p = new DatagramPacket(message, - message.length); - try { - mySocket.receive(p); - } catch (IOException e) { - e.printStackTrace(); - } - if (listenToTheMusic) - myReceiveListener.onReceive(new String(message, 0, p - .getLength())); - } - try { - Thread.sleep(SLEEP_TIME); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - } - - public void receivePackage(ReceiveListener receiveListener) { - myReceiveListener = receiveListener; - listenToTheMusic = true; - } - - public void pauseListening() { - listenToTheMusic = false; - } - - public void resumeListening() { - listenToTheMusic = true; - } - - } - - public static class Client { - - private static final String MY_TAG = "Network"; - private String myIp; - private int myServerPort; - private DatagramSocket mySocket; - - public Client(String serverIp, int serverPort) { - myIp = serverIp; - myServerPort = serverPort; - try { - mySocket = new DatagramSocket(); - } catch (SocketException e) { - e.printStackTrace(); - } - } - - /** - * @param message - * @return true if the message could be send - */ - public boolean sendPackage(String message) { - try { - if (myIp == null) { - Log.e(MY_TAG, "No ip set!");// , maybe no internet - // connection?"); - return false; - } - InetAddress local = InetAddress.getByName(myIp); - mySocket.send(new DatagramPacket(message.getBytes(), message - .length(), local, myServerPort)); - return true; - } catch (UnknownHostException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } - return false; - } - - public void closeConnection() { - mySocket.close(); - } - - } - - /** - * iterates over all network interfaces (3G, WiFi,..) to find the ip - * - * @return null if there is no connection available - */ - public static String getDeviceIp() { - try { - for (Enumeration interfaces = NetworkInterface - .getNetworkInterfaces(); interfaces.hasMoreElements();) { - NetworkInterface netInterface = interfaces.nextElement(); - for (Enumeration ipAddresses = netInterface - .getInetAddresses(); ipAddresses.hasMoreElements();) { - InetAddress inetAddress = ipAddresses.nextElement(); - if (!inetAddress.isLoopbackAddress()) { - return inetAddress.getHostAddress().toString(); - } - } - } - } catch (SocketException e) { - e.printStackTrace(); - } - return null; - } - -} diff --git a/droidar/src/preview/AugmentedView.java b/droidar/src/preview/AugmentedView.java index a78ef50..390587e 100644 --- a/droidar/src/preview/AugmentedView.java +++ b/droidar/src/preview/AugmentedView.java @@ -1,14 +1,21 @@ package preview; -import de.rwth.R; import gl.CustomGLSurfaceView; import gl.GL1Renderer; -import gl.GLRenderer; import android.content.Context; -import android.opengl.GLSurfaceView; import android.view.View; import android.widget.FrameLayout; +import de.rwth.R; +/** + * A view that contains the GLSurfaceView, CameraView and Gui overlay for augmented reality + * applications. + * This class can be extended to customize the following components: + * {@link preview.AugmentedView#createGLSurface(Context)} + * {@link preview.AugmentedView#createCameraView(Context)} + * {@link preview.AugmentedView#createGuiView(Context)} + * {@link preview.AugmentedView#createRenderer(Context)} + */ public class AugmentedView extends FrameLayout { private CustomGLSurfaceView mGLSurfaceView; @@ -16,14 +23,17 @@ public class AugmentedView extends FrameLayout { private GL1Renderer mRenderer; private View mGuiView; - + /** + * Constructor - needed by superclass {@link FrameLayou}. + * @param context - {@link Context} + */ public AugmentedView(Context context) { super(context); initialize(context); addOverlays(); } - private void initialize(Context context){ + private void initialize(Context context) { mGLSurfaceView = createGLSurface(context); mCameraView = createCameraView(context); mGuiView = createGuiView(context); @@ -31,81 +41,80 @@ private void initialize(Context context){ mGLSurfaceView.setRenderer(mRenderer); } - private void addOverlays(){ + private void addOverlays() { mGLSurfaceView.setZOrderMediaOverlay(true); addView(mGuiView); addView(mCameraView, new LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); addView(mGLSurfaceView, new LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); - mGLSurfaceView.setZOrderMediaOverlay(true); } /** * Get the current gl surface view. - * @return + * @return - {@link gl.CustomGLSurfaceView} */ - public CustomGLSurfaceView getGLSurfaceView(){ + public CustomGLSurfaceView getGLSurfaceView() { return mGLSurfaceView; } /** * Get the current camera view. - * @return + * @return - {@link preview.CameraView} */ - public CameraView getCameraView(){ + public CameraView getCameraView() { return mCameraView; } /** - * - * @return + * Get the current gui view. + * @return - {@link View} */ - public View getGuiView(){ + public View getGuiView() { return mGuiView; } /** - * - * @return + * Get the current renderer. + * @return - {@link gl.GL1Renderer} */ - public GL1Renderer getRenderer(){ + public GL1Renderer getRenderer() { return mRenderer; } /** - * Override this method if you want to implement custom GLSurfaceView - * @param context - * @return + * Override this method if you want to implement custom GLSurfaceView. + * @param context - {@link android.app.Context} + * @return - {@link gl.CustomGLSurfaceView} */ - protected CustomGLSurfaceView createGLSurface(Context context){ + protected CustomGLSurfaceView createGLSurface(Context context) { return new CustomGLSurfaceView(context); } /** - * Override this method if you want to implement custom CameraView - * @param context - * @return + * Override this method if you want to implement custom CameraView. + * @param context - {@link android.app.Context} + * @return - {@link preview.CameraView} */ - protected CameraView createCameraView(Context context){ + protected CameraView createCameraView(Context context) { return new CameraView(context); } /** - * Override this method if you want to implement custom GLRenderer - * @param context - * @return + * Override this method if you want to implement custom GLRenderer. + * @param context - {@link android.app.Context} + * @return - {@link gl.GL1Renderer} */ - protected GL1Renderer createRenderer(Context context){ + protected GL1Renderer createRenderer(Context context) { return new GL1Renderer(); } /** - * Override this method if you want to implement custom gui view - * @param context - * @return + * Override this method if you want to implement custom gui view. + * @param context - {@link android.app.Context} + * @return - {@link View} */ - protected View createGuiView(Context context){ + protected View createGuiView(Context context) { return View.inflate(context, R.layout.defaultlayout, null); } diff --git a/droidar/src/preview/CameraPreview.java b/droidar/src/preview/CameraPreview.java index 9e983f7..cba0a99 100644 --- a/droidar/src/preview/CameraPreview.java +++ b/droidar/src/preview/CameraPreview.java @@ -1,7 +1,14 @@ package preview; +/** + * Callback interface for communicating frame information. + */ public interface CameraPreview { - public void reAddCallbackBuffer(byte[] frame); + /** + * Used as a callback method to re-add a frame with modified data. + * @param frame - byte array the contains frame information + */ + void reAddCallbackBuffer(byte[] frame); } diff --git a/droidar/src/preview/CameraView.java b/droidar/src/preview/CameraView.java index 1b68926..f07f0d4 100644 --- a/droidar/src/preview/CameraView.java +++ b/droidar/src/preview/CameraView.java @@ -16,6 +16,9 @@ import android.view.SurfaceHolder; import android.view.SurfaceView; +/** + * CameraView. Can be extended for custom functionality. + */ public class CameraView extends SurfaceView implements SurfaceHolder.Callback, Camera.PreviewCallback, @@ -28,13 +31,27 @@ public class CameraView extends SurfaceView implements private FrameChangeThread mOnFrameChange; private boolean mPause = false; + //magic numbers + private static final int ROTATE_90_DEG = 90; + private static final int BITSIZE = 8; + + /** + * Constructor needed by {@link SurfaceView}. + * @param context - {@link Context} + */ public CameraView(Context context) { super(context); mOnFrameChange = new FrameChangeThread(this); intiCameraView(context); } - public CameraView(Context context,FrameChangeThread thread, AttributeSet attrs) { + /** + * Constructor needed by {@link SurfaceView}. + * @param context - {@link Context} + * @param thread - {@link system.FrameChangeThread} + * @param attrs - {@link AttributeSet} + */ + public CameraView(Context context, FrameChangeThread thread, AttributeSet attrs) { super(context, attrs); mOnFrameChange = new FrameChangeThread(this); intiCameraView(context); @@ -43,7 +60,7 @@ public CameraView(Context context,FrameChangeThread thread, AttributeSet attrs) private void intiCameraView(Context context) { mSurfaceHolder = getHolder(); mSurfaceHolder.addCallback(this); - ARLogger.debug(LOG_TAG,"Camera surface holder created."); + ARLogger.debug(LOG_TAG, "Camera surface holder created."); } @Override @@ -58,8 +75,8 @@ public void surfaceCreated(SurfaceHolder holder) { releaseCamera(); ARLogger.exception(LOG_TAG, "Unable to set camear preview display", e); } - if(showInPortrait()){ - mCamera.setDisplayOrientation(90); + if (showInPortrait()) { + mCamera.setDisplayOrientation(ROTATE_90_DEG); } } @@ -80,9 +97,9 @@ public void surfaceDestroyed(SurfaceHolder holder) { @Override public void onPreviewFrame(byte[] data, Camera camera) { - if(mOnFrameChange.isAvailable()){ + if (mOnFrameChange.isAvailable()) { mOnFrameChange.nextFrame(data); - }else if(!mPause){ + } else if (!mPause) { mCamera.addCallbackBuffer(data); } @@ -93,7 +110,7 @@ public void onPreviewFrame(byte[] data, Camera camera) { * Sets the camera's parameters. Sets the optimal preview size * based on the width and height given. */ - public void setCameraParameters(int width, int height) { + private void setCameraParameters(int width, int height) { Parameters parameters = mCamera.getParameters(); List sizes = parameters.getSupportedPreviewSizes(); @@ -110,26 +127,27 @@ public void setCameraParameters(int width, int height) { } } - private void addPreviewCallback(){ - mCamera.setPreviewCallbackWithBuffer(this); + private void addPreviewCallback() { + mCamera.setPreviewCallbackWithBuffer(this); } - private void setCallBackBuffer(int width, int height){ + private void setCallBackBuffer(int width, int height) { Camera.Parameters parameters = mCamera.getParameters(); PixelFormat pixelFormat = new PixelFormat(); PixelFormat.getPixelFormatInfo( parameters.getPreviewFormat(), pixelFormat); - - int bufSize = ((width*height)*pixelFormat.bitsPerPixel)/8; + int bufSize = ((width * height) * pixelFormat.bitsPerPixel) / BITSIZE; byte[] buffer = new byte[bufSize]; mCamera.addCallbackBuffer(buffer); - ARLogger.debug(LOG_TAG,"Camera parameters: Size: "+bufSize+", Height: "+height+", Width: "+width+", pixelformat: "+pixelFormat.toString() ); + ARLogger.debug(LOG_TAG, "Camera parameters: Size: " + + bufSize + ", Height: " + height + ", Width: " + width + + ", pixelformat: " + pixelFormat.toString()); } /** - * Properly resume the Camera + * Properly resume the Camera. */ public void resumeCamera() { mPause = false; @@ -141,7 +159,9 @@ public void resumeCamera() { } } - + /** + * Pause the camera. + */ public void onPause() { mPause = true; if (mCamera != null) { @@ -151,7 +171,7 @@ public void onPause() { } /** - * Properly stop and release the camera + * Properly stop and release the camera. */ public void releaseCamera() { mPause = true; @@ -159,13 +179,13 @@ public void releaseCamera() { mCamera.stopPreview(); mCamera.release(); mCamera = null; - ARLogger.debug(LOG_TAG,"Camera released."); + ARLogger.debug(LOG_TAG, "Camera released."); } } /** - * Returns the optimal preview size given the width and height + * Returns the optimal preview size given the width and height. * @param sizes * @param width * @param height @@ -190,18 +210,18 @@ private Size getOptimalPreviewSize(List sizes, int width, int height) { return result; } - private boolean showInPortrait(){ + private boolean showInPortrait() { boolean ret = false; - if(getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT && - !EventManager.isTabletDevice){ + if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT + && !EventManager.isTabletDevice) { ret = true; } return ret; } - private void adjustOrientation(Parameters params){ - if(showInPortrait()){ + private void adjustOrientation(Parameters params) { + if (showInPortrait()) { params.set("orientation", "portrait"); params.set("rotation", "90"); } @@ -209,12 +229,16 @@ private void adjustOrientation(Parameters params){ @Override public void reAddCallbackBuffer(byte[] frame) { - if(!mPause){ + if (!mPause) { mCamera.addCallbackBuffer(frame); } } - public FrameChangeThread getFrameUpdater(){ + /** + * Get the frame updater. + * @return - {@link system.FrameChangeThread} + */ + public FrameChangeThread getFrameUpdater() { return mOnFrameChange; } diff --git a/droidar/src/setup/ArSetup.java b/droidar/src/setup/ArSetup.java index 15fe9d2..4e1898a 100644 --- a/droidar/src/setup/ArSetup.java +++ b/droidar/src/setup/ArSetup.java @@ -5,13 +5,10 @@ import javax.microedition.khronos.opengles.GL10; import logger.ARLogger; -import system.DefaultARSetup; import system.EventManager; -import system.Setup; import system.SimpleLocationManager; import system.TaskManager; import util.EfficientList; -import util.Log; import util.Vec; import worldData.SystemUpdater; import android.app.Activity; @@ -23,13 +20,14 @@ import android.view.Window; import android.view.WindowManager; import android.widget.FrameLayout; + import commands.Command; import commands.CommandGroup; import commands.system.CommandDeviceVibrate; import commands.undoable.CommandProcessor; + import entry.ArType; import entry.ISetupEntry; -import gamelogic.FeedbackReports; import gl.GLFactory; import gl.LightSource; import gl.ObjectPicker; @@ -40,11 +38,10 @@ /** * Extend this class and implement all abstract methods to initialize your AR * application. More information can be found in the JavaDoc of the specific - * methods and for a simple default AR setup use the {@link DefaultARSetup} + * methods and for a simple default AR setup use the {@link setup.DefaultARSetup} * */ public abstract class ArSetup implements ISetupSteps, ISetupLifeCycle { - private static final String LOG_TAG = "ArSetup"; private CommandGroup mOptionsMenuCommands; private ISetupEntry mEntry; @@ -52,6 +49,12 @@ public abstract class ArSetup implements ISetupSteps, ISetupLifeCycle { private SystemUpdater mWorldUpdater; private Thread mWorldThread; private static Integer mScreenOrientation = Surface.ROTATION_90; + + //magic numbers + private static final int VIBRATEDURATION = 30; + private static final int XLIGHTPOS = 5; + private static final int YLIGHTPOS = 5; + private static final int ZLIGHTPOS = 5; /** * Constructor. @@ -60,6 +63,21 @@ public abstract class ArSetup implements ISetupSteps, ISetupLifeCycle { public ArSetup(ISetupEntry pEntry) { mEntry = pEntry; } + + /** + * Constructor. + */ + public ArSetup() { + this(null); + } + + /** + * Set the entry for this setup. + * @param pEntry - {@link entry.ISetupEntry} + */ + public void setEntry(ISetupEntry pEntry) { + mEntry = pEntry; + } /** * Default initialization is {@link Surface#ROTATION_90}, use landscape on @@ -69,7 +87,7 @@ public ArSetup(ISetupEntry pEntry) { * mean portrait mode and 90 and 270 would mean landscape mode * (should be the same on tablets and mobile devices */ - public int getScreenOrientation() { + public static int getScreenOrientation() { if (mScreenOrientation == null) { ARLogger.error(LOG_TAG, "screenOrientation was not set! Will " + "asume default 90 degree rotation for screen"); @@ -79,11 +97,15 @@ public int getScreenOrientation() { } /** - * @return This will just return {@link Setup#myTargetActivity}. Direct + * @return This will just return {@link ArSetup#getActivity()}. Direct * access to this field is also possible */ public Activity getActivity() { - return mEntry.getActivity(); + if (mEntry == null) { + return null; + } else { + return mEntry.getActivity(); + } } /** @@ -93,7 +115,9 @@ public Activity getActivity() { * @param pEntry - {@link entry.ArFragment} or {@link entry.ArActivity} */ public void run(ISetupEntry pEntry) { - mEntry = pEntry; + if (pEntry != null) { + mEntry = pEntry; + } setFullScreen(); @@ -103,23 +127,32 @@ public void run(ISetupEntry pEntry) { EventManager.getInstance().registerListeners(getActivity(), true); - _a_initFieldsIfNecessary(); + initFieldsIfNecessary(); - _b_addWorldsToRenderer(mEntry.getAugmentedView().getRenderer(), + addWorldsToRenderer(mEntry.getAugmentedView().getRenderer(), GLFactory.getInstance(), EventManager.getInstance() .getCurrentLocationObject()); - _c_addActionsToEvents(EventManager.getInstance(), mEntry + addActionsToEvents(EventManager.getInstance(), mEntry .getAugmentedView().getGLSurfaceView(), mWorldUpdater); - _d_addElementsToUpdateThread(mWorldUpdater); + addElementsToUpdateThread(mWorldUpdater); - _e1_addElementsToOverlay(mEntry.getAugmentedView(), getActivity()); + addElementsToOverlay(mEntry.getAugmentedView(), getActivity()); mWorldThread = new Thread(mWorldUpdater); mWorldThread.start(); } + + /** + * This method has to be executed in the activity which want to display the + * AR content. + * + */ + public void run() { + run(null); + } private void setFullScreen() { if (mEntry.getType() == ArType.ACTIVITY) { @@ -153,10 +186,10 @@ public SystemUpdater getSystemUpdater() { } @Override - public boolean _a2_initLightning(ArrayList lights) { + public boolean initLightning(ArrayList lights) { lights.add(LightSource.newDefaultAmbientLight(GL10.GL_LIGHT0)); - lights.add(LightSource.newDefaultSpotLight(GL10.GL_LIGHT1, new Vec(5, - 5, 5), new Vec(0, 0, 0))); + lights.add(LightSource.newDefaultSpotLight(GL10.GL_LIGHT1, new Vec(XLIGHTPOS, + YLIGHTPOS, ZLIGHTPOS), new Vec(0, 0, 0))); return true; } @@ -165,9 +198,8 @@ private void initAllSingletons() { SimpleLocationManager.resetInstance(); TextureManager.resetInstance(); TaskManager.resetInstance(); - ObjectPicker.resetInstance(new CommandDeviceVibrate(getActivity(), 30)); + ObjectPicker.resetInstance(new CommandDeviceVibrate(getActivity(), VIBRATEDURATION)); CommandProcessor.resetInstance(); - FeedbackReports.resetInstance(); // TODO really reset it? } /** @@ -189,7 +221,7 @@ public void initEventManagerInstance(Activity activity) { * @param infoScreenData * See {@link InfoScreenSettings} */ - public void _f_addInfoScreen(InfoScreenSettings infoScreenData) { + public void addInfoScreen(InfoScreenSettings infoScreenData) { infoScreenData.setCloseInstantly(); } @@ -206,10 +238,10 @@ private static void loadDeviceDependentSettings(Activity activity) { } @Override - public void _e1_addElementsToOverlay(FrameLayout overlayView, + public void addElementsToOverlay(FrameLayout overlayView, Activity activity) { mGuiSetup = new GuiSetup(this, mEntry.getAugmentedView().getGuiView()); - _e2_addElementsToGuiSetup(getGuiSetup(), activity); + addElementsToGuiSetup(getGuiSetup(), activity); } /** diff --git a/droidar/src/setup/DefaultArSetup.java b/droidar/src/setup/DefaultArSetup.java index b0e63b8..4e790a8 100644 --- a/droidar/src/setup/DefaultArSetup.java +++ b/droidar/src/setup/DefaultArSetup.java @@ -7,8 +7,8 @@ import gl.GLCamera; import gl.GLFactory; import gui.GuiSetup; +import logger.ARLogger; import system.EventManager; -import util.Log; import util.Vec; import worldData.SystemUpdater; import worldData.World; @@ -40,6 +40,16 @@ public abstract class DefaultArSetup extends ArSetup { private ActionRotateCameraBuffered mRotateGLCameraAction; private ActionWaitForAccuracy mMinAccuracyAction; + //magic numbers + private static final int XREDUCTION = 25; + private static final int YREDUCTION = 50; + private static final int MAXWASDSPEED = 20; + private static final int TRACKBALLFACTOR = 5; + private static final int TOUCHSCREENFACTOR = 25; + private static final float MINGPSACCURACY = 24.0f; + private static final int MAXGPSPOSUPDATECOUNT = 10; + + /** * Constructor. * @param pEntry - {@link ISetupEntry} @@ -49,9 +59,26 @@ public DefaultArSetup(ISetupEntry pEntry, boolean pWaitForValidGps) { super(pEntry); mWaitForValidGps = pWaitForValidGps; } + + /** + * Constructor. By default the {@link setup.DefaultArSetup#mWaitForValidGps} if set to false. + */ + public DefaultArSetup() { + super(); + mWaitForValidGps = false; + } + + /** + * Constructor. + * @param pWaitForValidGps - {@link boolean} true if you want to wait for gps before drawing + */ + public DefaultArSetup(boolean pWaitForValidGps) { + super(); + mWaitForValidGps = pWaitForValidGps; + } @Override - public void _a_initFieldsIfNecessary() { + public void initFieldsIfNecessary() { mCamera = new GLCamera(new Vec(0, 0, 2)); mWorld = new World(mCamera); } @@ -73,7 +100,7 @@ public GLCamera getCamera() { } @Override - public void _b_addWorldsToRenderer(GL1Renderer glRenderer, + public void addWorldsToRenderer(GL1Renderer glRenderer, GLFactory objectFactory, GeoObj currentPosition) { mRenderer = glRenderer; if (!mWaitForValidGps) { @@ -82,26 +109,33 @@ public void _b_addWorldsToRenderer(GL1Renderer glRenderer, } glRenderer.addRenderElement(mWorld); } - + @Override - public void _c_addActionsToEvents(final EventManager eventManager, + public void addActionsToEvents(final EventManager eventManager, CustomGLSurfaceView arView, SystemUpdater updater) { - mWasdAction = new ActionWASDMovement(mCamera, 25, 50, 20); + mWasdAction = new ActionWASDMovement(mCamera, + XREDUCTION, + YREDUCTION, + MAXWASDSPEED); mRotateGLCameraAction = new ActionRotateCameraBuffered(mCamera); eventManager.addOnOrientationChangedAction(mRotateGLCameraAction); arView.addOnTouchMoveListener(mWasdAction); - eventManager.addOnTrackballAction(new ActionMoveCameraBuffered(mCamera,5, 25)); + eventManager.addOnTrackballAction(new ActionMoveCameraBuffered(mCamera, + TRACKBALLFACTOR, + TOUCHSCREENFACTOR)); eventManager.addOnLocationChangedAction(new ActionCalcRelativePos(mWorld, mCamera)); if (mWaitForValidGps) { - mMinAccuracyAction = new ActionWaitForAccuracy(getActivity(), 24.0f, 10) { + mMinAccuracyAction = new ActionWaitForAccuracy(getActivity(), + MINGPSACCURACY, + MAXGPSPOSUPDATECOUNT) { @Override public void minAccuracyReachedFirstTime(Location l, ActionWaitForAccuracy a) { callAddObjectsToWorldIfNotCalledAlready(); if (!eventManager.getOnLocationChangedAction().remove(a)) { - Log.e(LOG_TAG, + ARLogger.debug(LOG_TAG, "Could not remove minAccuracyAction from the onLocationChangedAction list"); } } @@ -118,14 +152,14 @@ private void callAddObjectsToWorldIfNotCalledAlready() { } @Override - public void _d_addElementsToUpdateThread(SystemUpdater updater) { + public void addElementsToUpdateThread(SystemUpdater updater) { updater.addObjectToUpdateCycle(mWorld); updater.addObjectToUpdateCycle(mWasdAction); updater.addObjectToUpdateCycle(mRotateGLCameraAction); } @Override - public void _e2_addElementsToGuiSetup(GuiSetup guiSetup, Activity activity) { + public void addElementsToGuiSetup(GuiSetup guiSetup, Activity activity) { } diff --git a/droidar/src/setup/ISetupLifeCycle.java b/droidar/src/setup/ISetupLifeCycle.java index 35b8430..e595bb7 100644 --- a/droidar/src/setup/ISetupLifeCycle.java +++ b/droidar/src/setup/ISetupLifeCycle.java @@ -1,5 +1,9 @@ package setup; +/** + * Life cycle events for {@link setup.ArSetup}. + * + */ public interface ISetupLifeCycle { /** @@ -7,29 +11,29 @@ public interface ISetupLifeCycle { * at this time. * Also note when this method is called is not mean that that it is currently in use. */ - public void onCreate(); + void onCreate(); /** * This method is called when the entry is ready to begin. This is when * all needed resources needed to be started */ - public void onStart(); + void onStart(); /** * This method is called when the entry is currently in the background. This is when * all needed resources should be halted but not destroyed. */ - public void onPause(); + void onPause(); /** * This method is called when the entry is being resumed from an ISetupLifeCycle.onPause() * state. All resources should resume at this time. View is active to the user. */ - public void onResume(); + void onResume(); /** * This method is called when the entry is done. All resources should be released or destroyed. */ - public void onStop(); + void onStop(); } diff --git a/droidar/src/setup/ISetupSteps.java b/droidar/src/setup/ISetupSteps.java index 77382df..6550090 100644 --- a/droidar/src/setup/ISetupSteps.java +++ b/droidar/src/setup/ISetupSteps.java @@ -3,7 +3,6 @@ import geo.GeoObj; import gl.CustomGLSurfaceView; import gl.GL1Renderer; -import gl.GLCamera; import gl.GLFactory; import gl.LightSource; import gui.GuiSetup; @@ -11,15 +10,15 @@ import java.util.ArrayList; import system.EventManager; -import system.Setup; -import actions.Action; -import actions.ActionCalcRelativePos; -import actions.ActionRotateCameraBuffered; +import worldData.SystemUpdater; import android.app.Activity; import android.widget.FrameLayout; -import worldData.SystemUpdater; -import worldData.World; +/** + * These are the necessary steps required for a {@link ArSetup} and to allow + * flexibility in the library. + * + */ public interface ISetupSteps { /** @@ -29,24 +28,24 @@ public interface ISetupSteps { * field initialization here is a difference to doing it right in the * constructor, because normally a Setup object is created not directly * before it is used to start the AR view. So placing your field - * initialization here normaly means to reduce the amount of created objects + * initialization here normally means to reduce the amount of created objects * if you are using more then one Setup. * */ - public void _a_initFieldsIfNecessary(); + void initFieldsIfNecessary(); /** - * If you don't override this method it will create 2 default + * If you don't override this method it will create 2 default. * {@link LightSource}s * * @param lights * add all the {@link LightSource}s you want to use to this list * @return true if lightning should be enabled */ - public boolean _a2_initLightning(ArrayList lights); + boolean initLightning(ArrayList lights); /** - * first you should create a new {@link GLCamera} and a new {@link World} + * first you should create a new {@link gl.GLCamera} and a new {@link World} * and then you can use the {@link GLFactory} object to add objects to the * created world. When your world is build, add it to the * {@link GL1Renderer} object by calling @@ -60,12 +59,12 @@ public interface ISetupSteps { * @param currentPosition * might be null if no position information is available! */ - public void _b_addWorldsToRenderer(GL1Renderer glRenderer, + void addWorldsToRenderer(GL1Renderer glRenderer, GLFactory objectFactory, GeoObj currentPosition); /** - * This method should be used to add {@link Action}s to the - * {@link EventManager} and the {@link CustomGLSurfaceView} to specify the + * This method should be used to add {@link actions.Action}s to the + * {@link system.EventManager} and the {@link gl.CustomGLSurfaceView} to specify the * input-mechanisms.
*
* @@ -80,28 +79,28 @@ public void _b_addWorldsToRenderer(GL1Renderer glRenderer, * camera));
*
* - * The {@link ActionRotateCameraBuffered} rotates the virtualCamera and the - * {@link ActionCalcRelativePos} calculates the virtual position of the + * The {@link actions.ActionRotateCameraBuffered} rotates the virtualCamera and the + * {@link actions.ActionCalcRelativePos} calculates the virtual position of the * camera and all the items in the virtual world. There are more - * {@link Action}s which can be defined in the {@link EventManager}, for + * {@link actions.Action}s which can be defined in the {@link system.EventManager}, for * example for keystrokes or other input types.
*
* * For more examples take a look at the different Setup examples. * - * @param eventManager + * @param eventManager - {@link system.EventManager} * * @param arView * The {@link CustomGLSurfaceView#addOnTouchMoveAction(Action)} * -method can be used to react on touch-screen input - * @param worldUpdater + * @param updater - {@link SystemUpdater} */ - public void _c_addActionsToEvents(EventManager eventManager, + void addActionsToEvents(EventManager eventManager, CustomGLSurfaceView arView, SystemUpdater updater); /** - * All elements (normally that should only be {@link World}s) which should - * be updated have to be added to the {@link SystemUpdater}. This update + * All elements (normally that should only be {@link worldData.World}s) which should + * be updated have to be added to the {@link system.SystemUpdater}. This update * process is independent to the rendering process and can be used for all * system-logic which has to be done periodically * @@ -109,35 +108,33 @@ public void _c_addActionsToEvents(EventManager eventManager, * add anything you want to update to this updater via * {@link SystemUpdater#addObjectToUpdateCycle(worldData.Updateable)} */ - public abstract void _d_addElementsToUpdateThread(SystemUpdater updater); + void addElementsToUpdateThread(SystemUpdater updater); /** * here you can define or load any view you want and add it to the overlay * View. If this method is implemented, the - * _e2_addElementsToGuiSetup()-method wont be called automatically + * addElementsToGuiSetup()-method wont be called automatically * * @param overlayView * here you have to add your created view * @param activity * use this as the context for new views */ - public void _e1_addElementsToOverlay(FrameLayout overlayView, - Activity activity); + void addElementsToOverlay(FrameLayout overlayView, Activity activity); /** * Here you can add UI-elements like buttons to the predefined design * (main.xml). If you want to overlay your own design, just override the - * {@link Setup}._e1_addElementsToOverlay() method and leave this one here + * {@link ArSetup}.addElementsToOverlay() method and leave this one here * empty. * - * @param guiSetup + * @param guiSetup - {@link GuiSetup} * @param activity * this is the same activity you can get with - * {@link Setup#myTargetActivity} but its easier to access this + * {@link ArSetup#getActivity()} but its easier to access this * way */ - public abstract void _e2_addElementsToGuiSetup(GuiSetup guiSetup, - Activity activity); + void addElementsToGuiSetup(GuiSetup guiSetup, Activity activity); } diff --git a/droidar/src/system/ArActivity.java b/droidar/src/system/ArActivity.java deleted file mode 100644 index 3adb23e..0000000 --- a/droidar/src/system/ArActivity.java +++ /dev/null @@ -1,138 +0,0 @@ -package system; - -import util.Log; -import android.app.Activity; -import android.content.Intent; -import android.content.res.Configuration; -import android.os.Bundle; -import android.view.KeyEvent; -import android.view.Menu; -import android.view.MenuItem; - -/** - * This is an example activity which demonstrates how to use a Setup object. It - * wraps the Setup object and forwards all needed events to it. - * - * @author Simon Heinen - * - */ -public class ArActivity extends Activity { - - private static final String LOG_TAG = "ArActivity"; - - private static Setup staticSetupHolder; - - private Setup mySetupToUse; - - /** - * Called when the activity is first created. - * - */ - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - Log.d(LOG_TAG, "main onCreate"); - if (staticSetupHolder != null) { - mySetupToUse = staticSetupHolder; - staticSetupHolder = null; - runSetup(); - } else { - Log.e(LOG_TAG, "There was no Setup specified to use. " - + "Please use ArActivity.show(..) when you " - + "want to use this way of starting the AR-view!"); - this.finish(); - } - } - - public static void startWithSetup(Activity currentActivity, Setup setupToUse) { - ArActivity.staticSetupHolder = setupToUse; - currentActivity.startActivity(new Intent(currentActivity, - ArActivity.class)); - } - - public static void startWithSetupForResult(Activity currentActivity, - Setup setupToUse, int requestCode) { - ArActivity.staticSetupHolder = setupToUse; - currentActivity.startActivityForResult(new Intent(currentActivity, - ArActivity.class), requestCode); - } - - private void runSetup() { - mySetupToUse.run(this); - } - - @Override - protected void onRestart() { - if (mySetupToUse != null) - mySetupToUse.onRestart(this); - super.onRestart(); - } - - @Override - protected void onResume() { - if (mySetupToUse != null) - mySetupToUse.onResume(this); - super.onResume(); - } - - @Override - protected void onStart() { - if (mySetupToUse != null) - mySetupToUse.onStart(this); - super.onStart(); - } - - @Override - protected void onStop() { - if (mySetupToUse != null) - mySetupToUse.onStop(this); - super.onStop(); - } - - @Override - protected void onDestroy() { - if (mySetupToUse != null) - mySetupToUse.onDestroy(this); - super.onDestroy(); - } - - @Override - protected void onPause() { - if (mySetupToUse != null) - mySetupToUse.onPause(this); - super.onPause(); - } - - @Override - public boolean onKeyDown(int keyCode, KeyEvent event) { - if ((mySetupToUse != null) - && (mySetupToUse.onKeyDown(this, keyCode, event))) - return true; - return super.onKeyDown(keyCode, event); - } - - @Override - public boolean onCreateOptionsMenu(Menu menu) { - if (((mySetupToUse != null) && mySetupToUse.onCreateOptionsMenu(menu))) - return true; - return super.onCreateOptionsMenu(menu); - } - - @Override - public boolean onMenuItemSelected(int featureId, MenuItem item) { - if (mySetupToUse != null) - return mySetupToUse.onMenuItemSelected(featureId, item); - return super.onMenuItemSelected(featureId, item); - } - - @Override - public void onConfigurationChanged(Configuration newConfig) { - Log.d(LOG_TAG, "main onConfigChanged"); - if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) - Log.d(LOG_TAG, "orientation changed to landscape"); - if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) - Log.d(LOG_TAG, "orientation changed to portrait"); - super.onConfigurationChanged(newConfig); - } - -} \ No newline at end of file diff --git a/droidar/src/system/DefaultARSetup.java b/droidar/src/system/DefaultARSetup.java deleted file mode 100644 index 23e4847..0000000 --- a/droidar/src/system/DefaultARSetup.java +++ /dev/null @@ -1,157 +0,0 @@ -package system; - -import geo.GeoObj; -import gl.CustomGLSurfaceView; -import gl.GL1Renderer; -import gl.GLCamera; -import gl.GLFactory; -import gui.GuiSetup; -import util.Log; -import util.Vec; -import worldData.SystemUpdater; -import worldData.World; -import actions.Action; -import actions.ActionCalcRelativePos; -import actions.ActionMoveCameraBuffered; -import actions.ActionRotateCameraBuffered; -import actions.ActionWASDMovement; -import actions.ActionWaitForAccuracy; -import android.R; -import android.app.Activity; -import android.location.Location; - -import commands.Command; - -/** - * This is an example how you can use the default setup:
- * - * ArActivity.startWithSetup(currentActicity, new DefaultARSetup() {
- * public void addObjectsTo(World world, GLFactory factory) {
- * GeoObj obj = new GeoObj();
- * obj.setComp(factory.newCube()); world.add(obj);
- * obj.setVirtualPosition(new Vec());
- * }
- * }); - * - * - * @author Spobo - * - */ -public abstract class DefaultARSetup extends Setup { - - protected static final int ZDELTA = 5; - private static final String LOG_TAG = "DefaultARSetup"; - - public GLCamera camera; - public World world; - private ActionWASDMovement wasdAction; - private GL1Renderer myRenderer; - private boolean addObjCalledOneTieme; - private ActionWaitForAccuracy minAccuracyAction; - private Action rotateGLCameraAction; - - public DefaultARSetup() { - - } - - @Override - public void _a_initFieldsIfNecessary() { - camera = new GLCamera(new Vec(0, 0, 2)); - world = new World(camera); - } - - public World getWorld() { - return world; - } - - public GLCamera getCamera() { - return camera; - } - - /** - * This will be called when the GPS accuracy is high enough - * - * @param renderer - * @param world - * @param objectFactory - */ - public abstract void addObjectsTo(GL1Renderer renderer, World world, - GLFactory objectFactory); - - @Override - public void _b_addWorldsToRenderer(GL1Renderer renderer, - GLFactory objectFactory, GeoObj currentPosition) { - myRenderer = renderer; - renderer.addRenderElement(world); - } - - @Override - public void _c_addActionsToEvents(final EventManager eventManager, - CustomGLSurfaceView arView, SystemUpdater updater) { - wasdAction = new ActionWASDMovement(camera, 25, 50, 20); - rotateGLCameraAction = new ActionRotateCameraBuffered(camera); - eventManager.addOnOrientationChangedAction(rotateGLCameraAction); - - arView.addOnTouchMoveListener(wasdAction); - // eventManager.addOnOrientationChangedAction(rotateGLCameraAction); - eventManager.addOnTrackballAction(new ActionMoveCameraBuffered(camera, - 5, 25)); - eventManager.addOnLocationChangedAction(new ActionCalcRelativePos( - world, camera)); - minAccuracyAction = new ActionWaitForAccuracy(getActivity(), 24.0f, 10) { - @Override - public void minAccuracyReachedFirstTime(Location l, - ActionWaitForAccuracy a) { - callAddObjectsToWorldIfNotCalledAlready(); - if (!eventManager.getOnLocationChangedAction().remove(a)) { - Log.e(LOG_TAG, - "Could not remove minAccuracyAction from the onLocationChangedAction list"); - } - } - }; - eventManager.addOnLocationChangedAction(minAccuracyAction); - } - - protected void callAddObjectsToWorldIfNotCalledAlready() { - if (!addObjCalledOneTieme) { - addObjectsTo(myRenderer, world, GLFactory.getInstance()); - } else { - Log.w(LOG_TAG, "callAddObjectsToWorldIfNotCalledAlready() " - + "called more then one time!"); - } - addObjCalledOneTieme = true; - } - - @Override - public void _d_addElementsToUpdateThread(SystemUpdater updater) { - updater.addObjectToUpdateCycle(world); - updater.addObjectToUpdateCycle(wasdAction); - updater.addObjectToUpdateCycle(rotateGLCameraAction); - } - - @Override - public void _e2_addElementsToGuiSetup(GuiSetup guiSetup, Activity activity) { - guiSetup.setRightViewAllignBottom(); - - guiSetup.addViewToTop(minAccuracyAction.getView()); - - guiSetup.addImangeButtonToRightView(R.drawable.arrow_up_float, - new Command() { - @Override - public boolean execute() { - camera.changeZPositionBuffered(+ZDELTA); - return false; - } - }); - guiSetup.addImangeButtonToRightView(R.drawable.arrow_down_float, - new Command() { - @Override - public boolean execute() { - camera.changeZPositionBuffered(-ZDELTA); - return false; - } - }); - - } - -} diff --git a/droidar/src/system/EventManager.java b/droidar/src/system/EventManager.java index d191600..93aacee 100644 --- a/droidar/src/system/EventManager.java +++ b/droidar/src/system/EventManager.java @@ -11,6 +11,7 @@ import listeners.eventManagerListeners.LocationEventListener; import listeners.eventManagerListeners.OrientationChangedListener; import listeners.eventManagerListeners.TrackBallEventListener; +import logger.ARLogger; import util.Log; import android.app.Activity; import android.content.Context; @@ -24,7 +25,6 @@ import android.os.Bundle; import android.view.KeyEvent; import android.view.MotionEvent; - import commands.Command; /** @@ -109,10 +109,12 @@ protected void registerSensorUpdates(Activity myTargetActivity, Sensor accelSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); Sensor sensorFusion = sensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR); Sensor magnetSensor = sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD); - - sensorManager.registerListener(this, accelSensor,SensorManager.SENSOR_DELAY_NORMAL); - sensorManager.registerListener(this, magnetSensor,SensorManager.SENSOR_DELAY_NORMAL); - sensorManager.registerListener(this,sensorFusion,SensorManager.SENSOR_DELAY_NORMAL); + ARLogger.debug(LOG_TAG, "Registering Sensors: \nAccel>: " + accelSensor + + "\nRotatationVector>: " + sensorFusion + + "\nMagnet>: " + magnetSensor); + sensorManager.registerListener(this, accelSensor,SensorManager.SENSOR_DELAY_GAME); + sensorManager.registerListener(this, magnetSensor,SensorManager.SENSOR_DELAY_GAME); + sensorManager.registerListener(this,sensorFusion,SensorManager.SENSOR_DELAY_GAME); } diff --git a/droidar/src/system/Setup.java b/droidar/src/system/Setup.java deleted file mode 100644 index f3a046e..0000000 --- a/droidar/src/system/Setup.java +++ /dev/null @@ -1,856 +0,0 @@ -package system; - -import gamelogic.FeedbackReports; -import geo.GeoObj; -import gl.CustomGLSurfaceView; -import gl.GL1Renderer; -import gl.GLCamera; -import gl.GLFactory; -import gl.GLRenderer; -import gl.LightSource; -import gl.ObjectPicker; -import gl.textures.TextureManager; -import gui.GuiSetup; -import gui.InfoScreen; -import gui.InfoScreenSettings; -import gui.simpleUI.EditItem; -import gui.simpleUI.ModifierGroup; -import gui.simpleUI.SimpleUIv1; - -import java.util.ArrayList; - -import javax.microedition.khronos.opengles.GL10; - -import preview.CameraView; -import listeners.SetupListener; -import util.EfficientList; -import util.Log; -import util.Vec; -import worldData.SystemUpdater; -import worldData.World; -import actions.Action; -import actions.ActionCalcRelativePos; -import actions.ActionRotateCameraBuffered; -import android.app.Activity; -import android.content.res.Configuration; -import android.os.Build; -import android.os.SystemClock; -import android.view.Display; -import android.view.Gravity; -import android.view.KeyEvent; -import android.view.Menu; -import android.view.MenuItem; -import android.view.Surface; -import android.view.View; -import android.view.ViewGroup.LayoutParams; -import android.view.Window; -import android.view.WindowManager; -import android.widget.FrameLayout; -import commands.Command; -import commands.CommandGroup; -import commands.system.CommandDeviceVibrate; -import commands.undoable.CommandProcessor; -import de.rwth.R; - -/** - * Extend this class and implement all abstract methods to initialize your AR - * application. More information can be found in the JavaDoc of the specific - * methods and for a simple default AR setup use the {@link DefaultARSetup} - * - *
- * To launch another activity from a setup do something like this:
- *
- * getActivity().startActivity(new Intent(getActivity(), - * MyOtherActivity.class)); - * - * @author Spobo - * - */ -@SuppressWarnings("deprecation") -public abstract class Setup { - - public static int defaultArLayoutId = R.layout.defaultlayout; - - private static final String LOG_TAG = "Setup"; - - public static boolean displaySetupStepLogging = true; - private static final String STEP0 = "Resetting all static stuff, singletons, etc.."; - private static final String STEP1 = "Registering exeption handler"; - private static final String STEP2 = "Loading device dependent settings"; - private static final String STEP3 = "Creating OpenGL overlay"; - private static final String STEP4 = "Initializing EventManager"; - private static final String STEP5 = "Initializing system values"; - private static final String STEP6 = "Creating OpenGL content"; - private static final String STEP7 = "Creating camera overlay"; - private static final String STEP8 = "Enabling user input"; - private static final String STEP9 = "Creating world updater"; - private static final String STEP10 = "Creating gui overlay"; - private static final String STEP11 = "Adding all overlays"; - private static final String STEP12 = "Show info screen"; - private static final String STEP13 = "Entering fullscreen mode"; - private static final String STEP_DONE = "All Setup-steps done!"; - - /** - * use {@link Setup#getActivity()} instead - * - * This is the activity which is created to display the AR content (camera - * preview, opengl-layer and UI-layer) - */ - @Deprecated - public Activity myTargetActivity; - private CommandGroup myOptionsMenuCommands; - public CustomGLSurfaceView myGLSurfaceView; - public CameraView myCameraView; - private FrameLayout myOverlayView; - private SetupListener mySetupListener; - private double lastTime; - /** - * TODO make this accessible - */ - private final boolean gotoFullScreenMode = true; - private final boolean useAccelAndMagnetoSensors; - - private GuiSetup guiSetup; - - private GLRenderer glRenderer; - - private SystemUpdater worldUpdater; - - private static Integer screenOrientation = Surface.ROTATION_90; - - public Setup() { - this(true); - } - - public Setup(Activity target, SetupListener listener, - boolean useAccelAndMagnetoSensors) { - this(useAccelAndMagnetoSensors); - mySetupListener = listener; - } - - // TODO remove boolean here and add to EventManager.setListeners..! - public Setup(boolean useAccelAndMagnetoSensors) { - this.useAccelAndMagnetoSensors = useAccelAndMagnetoSensors; - } - - /** - * Default initialization is {@link Surface#ROTATION_90}, use landscape on - * default mode if the initialization does not work - * - * @return {@link Surface#ROTATION_0} or {@link Surface#ROTATION_180} would - * mean portrait mode and 90 and 270 would meen landscape mode - * (should be the same on tablets and mobile devices - */ - public static int getScreenOrientation() { - if (screenOrientation == null) { - Log.e(LOG_TAG, "screenOrientation was not set! Will asume" - + " default 90 degree rotation for screen"); - return Surface.ROTATION_90; - } - return screenOrientation; - } - - /** - * @return This will just return {@link Setup#myTargetActivity}. Direct - * access to this field is also possible - */ - public Activity getActivity() { - return myTargetActivity; - } - - /** - * This method has to be executed in the activity which want to display the - * AR content. In your activity do something like this: - * - *
-	 * public void onCreate(Bundle savedInstanceState) {
-	 * 	super.onCreate(savedInstanceState);
-	 * 	new MySetup(this).run();
-	 * }
-	 * 
- * - * @param target - * - */ - public void run(Activity target) { - myTargetActivity = target; - Log.i(LOG_TAG, "Setup process is executed now.."); - - debugLogDoSetupStep(STEP0); - initAllSingletons(); - - initializeErrorHandler(); - - /* - * TODO move this to the end of the initialization method and use - * myTargetActivity.setProgress to display the progress of the loading - * before. maybe also change the text in the activity title to the - * current setup step in combination to the setProgress() - */ - - // Fullscreen: - if (getActivity().requestWindowFeature(Window.FEATURE_NO_TITLE)) { - if (gotoFullScreenMode) { - debugLogDoSetupStep(STEP13); - getActivity().getWindow().setFlags( - WindowManager.LayoutParams.FLAG_FULLSCREEN, - WindowManager.LayoutParams.FLAG_FULLSCREEN); - } - } else { - - /* - * The title bar is changed to a progress bar to visualize the setup - * progress - * - * displaying the following stuff does not work until the UI-update - * process is initialized by Activity.setContentView(..); so wrong - * place here: - */ - getActivity().requestWindowFeature(Window.PROGRESS_VISIBILITY_ON); - getActivity().getWindow().requestFeature(Window.FEATURE_PROGRESS); - getActivity().setProgressBarVisibility(true); - /* - * TODO do not expect the opengl view to start at the top of the - * screen! - */ - } - - getActivity().getWindow().setFlags( - WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, - WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); - - // load device dependent settings: - debugLogDoSetupStep(STEP2); - loadDeviceDependentSettings(getActivity()); - - /* - * set the orientation to always stay in landscape mode. this is - * necessary to use the camera correctly - * - * targetActivity - * .setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); - * - * no more needed, landscape mode is forced by the AndroidManifest - */ - - debugLogDoSetupStep(STEP3); - glRenderer = initOpenGLRenderer(); - myGLSurfaceView = initOpenGLView(glRenderer); - - debugLogDoSetupStep(STEP4); - // setting up the sensor Listeners: - EventManager.getInstance().registerListeners(getActivity(), - this.useAccelAndMagnetoSensors); - - debugLogDoSetupStep(STEP5); - _a_initFieldsIfNecessary(); - - debugLogDoSetupStep(STEP6); - - if (glRenderer instanceof GL1Renderer) { - _b_addWorldsToRenderer((GL1Renderer) glRenderer, - GLFactory.getInstance(), EventManager.getInstance() - .getCurrentLocationObject()); - } - initializeCamera(); - - debugLogDoSetupStep(STEP8); - - // set sensorinput actions: - worldUpdater = new SystemUpdater(); - _c_addActionsToEvents(EventManager.getInstance(), myGLSurfaceView, - worldUpdater); - - debugLogDoSetupStep(STEP9); - // and then init the worldupdater to be able to animate the world: - _d_addElementsToUpdateThread(worldUpdater); - - // World Update Thread: - Thread worldThread = new Thread(worldUpdater); - - worldThread.start(); - - debugLogDoSetupStep(STEP10); - - // create the thierd view on top of cameraPreview and OpenGL view and - // init it: - myOverlayView = new FrameLayout(getActivity()); - /* - * after everything is initialized add the guiElements to the screen. - * this should be done last because the gui might need a initialized - * renderer object or worldUpdater etc - */ - _e1_addElementsToOverlay(myOverlayView, getActivity()); - // myTargetActivity.addContentView(myOverlayView, new LayoutParams( - // LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); - - addOverlaysAndShowInfoScreen(); - - debugLogDoSetupStep(STEP_DONE); - } - - public SystemUpdater getSystemUpdater() { - return worldUpdater; - } - - /** - * By overriding this (and not calling the super metzhod) the - * {@link ErrorHandler} system provided by DroidAR will be deactivated (e.g. - * while debugging) - */ - public void initializeErrorHandler() { - debugLogDoSetupStep(STEP1); - ErrorHandler.registerNewErrorHandler(getActivity()); - } - - /** - * If you don't override this method it will create 2 default - * {@link LightSource}s - * - * @param lights - * add all the {@link LightSource}s you want to use to this list - * @return true if lightning should be enabled - */ - public boolean _a2_initLightning(ArrayList lights) { - lights.add(LightSource.newDefaultAmbientLight(GL10.GL_LIGHT0)); - lights.add(LightSource.newDefaultSpotLight(GL10.GL_LIGHT1, new Vec(5, - 5, 5), new Vec(0, 0, 0))); - // TODO lights.add(LightSource.newDefaultDayLight(GL10.GL_LIGHT1, new - // Date())); - return true; - } - - public void initializeCamera() { - - debugLogDoSetupStep(STEP7); - myCameraView = initCameraView(getActivity()); - - } - - private void addOverlaysAndShowInfoScreen() { - debugLogDoSetupStep(STEP11); - InfoScreenSettings infoScreenData = new InfoScreenSettings(getActivity()); - addOverlays(); - debugLogDoSetupStep(STEP12); - _f_addInfoScreen(infoScreenData); - showInfoDialog(infoScreenData); - } - - private void initAllSingletons() { - /* - * a good examples why you should not use singletons if you can avoid - * it.. TODO change all the singletons here to injection singletons. - * more flexible then. this can be done here, so just insert instance - * instead of resetInstance - */ - - initEventManagerInstance(getActivity()); - SimpleLocationManager.resetInstance(); - TextureManager.resetInstance(); - TaskManager.resetInstance(); - //GLFactory.resetInstance(); - ObjectPicker.resetInstance(new CommandDeviceVibrate(getActivity(),30)); - CommandProcessor.resetInstance(); - FeedbackReports.resetInstance(); // TODO really reset it? - - } - - /** - * You can create and set a subclass of {@link EventManager} here. To set - * the instance use - * {@link EventManager#initInstance(android.content.Context, EventManager)} - */ - public void initEventManagerInstance(Activity a) { - EventManager.initInstance(a, new EventManager()); - } - - protected CameraView initCameraView(Activity a) { - - return new CameraView(a); - } - - /** - * Don't call the super method if you want do display an info screen on - * startup. Just use the {@link InfoScreenSettings} to add information and - * the rest will be done automatically - * - * @param infoScreenData - * See {@link InfoScreenSettings} - */ - public void _f_addInfoScreen(InfoScreenSettings infoScreenData) { - Log.d(LOG_TAG, "Info screen will be closed instantly"); - infoScreenData.setCloseInstantly(); - } - - private void showInfoDialog(InfoScreenSettings infoScreenData) { - ActivityConnector.getInstance().startActivity(myTargetActivity, - InfoScreen.class, infoScreenData); - - } - - private void addOverlays() { - addCameraOverlay(); - addGLSurfaceOverlay(); - addGUIOverlay(); - } - - private void addGUIOverlay() { - // add overlay view as an content view to the activity: - myTargetActivity.addContentView(myOverlayView, new LayoutParams( - LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); - } - - public void addGLSurfaceOverlay() { - if (Integer.parseInt(android.os.Build.VERSION.SDK) >= Build.VERSION_CODES.ECLAIR) { - myGLSurfaceView.setZOrderMediaOverlay(true); - } - myTargetActivity.addContentView(myGLSurfaceView, new LayoutParams( - LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); - } - - public void addCameraOverlay() { - if (myCameraView != null) { - Log.d(LOG_TAG, "Camera preview added as view"); - myTargetActivity.addContentView(myCameraView, new LayoutParams( - LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); - } else { - Log.e(LOG_TAG, - "Camera preview not added to view because it wasnt initialized !"); - } - } - - private static void loadDeviceDependentSettings(Activity activity) { - try { - Display display = ((WindowManager) activity - .getSystemService(Activity.WINDOW_SERVICE)) - .getDefaultDisplay(); - screenOrientation = (Integer) display.getClass() - .getMethod("getRotation", null).invoke(display, null); - } catch (Exception e) { - e.printStackTrace(); - } - } - - /** - * This method can be called to visualize additional setup steps in the - * initialize-procedure of custom Setup subclass. One example would be to - * call this method every time a model is composed in the - * initFieldsIfNecessary() or the addWOrldsToRenderer() method. This could - * be useful to give feedback while creating complex models. - * - * Do not forget to set the {@link Setup}.addToStepsCount(int - * additionalSteps) to the correct value, depending on how often call this - * method here! - * - * @param statusText - */ - public void debugLogDoSetupStep(String statusText) { - - double msTheLastStepTook = 0; - double currentTime = SystemClock.uptimeMillis(); - if (lastTime != 0) { - msTheLastStepTook = currentTime - lastTime; - } - lastTime = currentTime; - if (msTheLastStepTook != 0) { - if (displaySetupStepLogging) { - Log.d(LOG_TAG, " -> Done (It took " + msTheLastStepTook - + "ms)"); - } - } - if (displaySetupStepLogging) { - Log.d(LOG_TAG, "Next step: " + statusText); - } - - /* - * displaying the following stuff does not work until the ui update - * process is initialized by Activity.setContentView(..); so wrong place - * here: - */ - // if (displaySetupStepInTitlebar) { - // setupProgress += Window.PROGRESS_END / setupStepsCount; - // myTargetActivity.setProgress(setupProgress); - // myTargetActivity.setTitle(statusText); - // } - - if (mySetupListener != null) { - mySetupListener.onNextStep(msTheLastStepTook, statusText); - } - } - - /** - * - * - * this is called after the initialization of the AR view started. Doing - * field initialization here is a difference to doing it right in the - * constructor, because normally a Setup object is created not directly - * before it is used to start the AR view. So placing your field - * initialization here normaly means to reduce the amount of created objects - * if you are using more then one Setup. - * - */ - public abstract void _a_initFieldsIfNecessary(); - - /** - * first you should create a new {@link GLCamera} and a new {@link World} - * and then you can use the {@link GLFactory} object to add objects to the - * created world. When your world is build, add it to the - * {@link GL1Renderer} object by calling - * {@link GL1Renderer#addRenderElement(worldData.Renderable)} - * - * @param glRenderer - * here you should add your world(s) - * @param objectFactory - * you could get this object your self wherever you want by - * getting the singleton-instance of {@link GLFactory} - * @param currentPosition - * might be null if no position information is available! - */ - public abstract void _b_addWorldsToRenderer(GL1Renderer glRenderer, - GLFactory objectFactory, GeoObj currentPosition); - - /** - * This method should be used to add {@link Action}s to the - * {@link EventManager} and the {@link CustomGLSurfaceView} to specify the - * input-mechanisms.
- *
- * - * Here is the typical AR example: The virtual camera should rotate when the - * device is rotated and it should move when the device moves to simulate - * the AR rotation and translation in a correct way. Therefore two actions - * have to be defined like this:
- *
- * eventManager.addOnOrientationChangedAction(new - * ActionRotateCameraBuffered(camera));
- * eventManager.addOnLocationChangedAction(new ActionCalcRelativePos(world, - * camera));

- *
- * - * The {@link ActionRotateCameraBuffered} rotates the virtualCamera and the - * {@link ActionCalcRelativePos} calculates the virtual position of the - * camera and all the items in the virtual world. There are more - * {@link Action}s which can be defined in the {@link EventManager}, for - * example for keystrokes or other input types.
- *
- * - * For more examples take a look at the different Setup examples. - * - * @param eventManager - * - * @param arView - * The {@link CustomGLSurfaceView#addOnTouchMoveAction(Action)} - * -method can be used to react on touch-screen input - * @param worldUpdater - */ - public abstract void _c_addActionsToEvents(EventManager eventManager, - CustomGLSurfaceView arView, SystemUpdater updater); - - /** - * All elements (normally that should only be {@link World}s) which should - * be updated have to be added to the {@link SystemUpdater}. This update - * process is independent to the rendering process and can be used for all - * system-logic which has to be done periodically - * - * @param updater - * add anything you want to update to this updater via - * {@link SystemUpdater#addObjectToUpdateCycle(worldData.Updateable)} - */ - public abstract void _d_addElementsToUpdateThread(SystemUpdater updater); - - /** - * here you can define or load any view you want and add it to the overlay - * View. If this method is implemented, the - * _e2_addElementsToGuiSetup()-method wont be called automatically - * - * @param overlayView - * here you have to add your created view - * @param activity - * use this as the context for new views - */ - public void _e1_addElementsToOverlay(FrameLayout overlayView, - Activity activity) { - // the main.xml layout is loaded and the guiSetup is created for - // customization. then the customized view is added to overlayView - View sourceView = View.inflate(activity, defaultArLayoutId, null); - //guiSetup = new GuiSetup(this, sourceView); - - _e2_addElementsToGuiSetup(getGuiSetup(), activity); - addDroidARInfoBox(activity); - overlayView.addView(sourceView); - } - - private void addDroidARInfoBox(final Activity currentActivity) { - addItemToOptionsMenu(new Command() { - - @Override - public boolean execute() { - SimpleUIv1.showInfoScreen(currentActivity, new EditItem() { - @Override - public void customizeScreen(ModifierGroup group, - Object message) { - group.addModifier(new gui.simpleUI.modifiers.Headline( - R.drawable.logo, "DroidAR")); - group.addModifier(new gui.simpleUI.modifiers.InfoText( - "This was creat" + "ed with the Droid" - + "AR fram" + "ework", Gravity.CENTER)); - group.addModifier(new gui.simpleUI.modifiers.InfoText( - "droidar.goog" + "lecode.com", Gravity.CENTER)); - } - }, null); - return true; - } - }, "About"); - } - - public GuiSetup getGuiSetup() { - return guiSetup; - } - - /** - * Here you can add UI-elements like buttons to the predefined design - * (main.xml). If you want to overlay your own design, just override the - * {@link Setup}._e1_addElementsToOverlay() method and leave this one here - * empty. - * - * @param guiSetup - * @param activity - * this is the same activity you can get with - * {@link Setup#myTargetActivity} but its easier to access this - * way - */ - public abstract void _e2_addElementsToGuiSetup(GuiSetup guiSetup, - Activity activity); - - public GLRenderer initOpenGLRenderer() { - GL1Renderer r = new GL1Renderer(); - r.setUseLightning(_a2_initLightning(r.getMyLights())); - return r; - } - - public CustomGLSurfaceView initOpenGLView(GLRenderer glRenderer2) { - CustomGLSurfaceView arView = new CustomGLSurfaceView(getActivity()); - arView.setRenderer(glRenderer2); - return arView; - } - - /** - * This will kill the camera - */ - public void releaseCamera() { - if (myCameraView != null) { - Log.d(LOG_TAG, "Releasing camera preview " + myCameraView); - myCameraView.releaseCamera(); - } - } - - private boolean fillMenuWithCommandsFromCommandgroup(Menu menu, - CommandGroup g) { - EfficientList cList = g.myList; - final int l = g.myList.myLength; - for (int i = 0; i < l; i++) { - menu.add(Menu.NONE, i, Menu.NONE, cList.get(i).getInfoObject() - .getShortDescr()); - } - return true; - } - - public boolean onCreateOptionsMenu(Menu menu) { - if (myOptionsMenuCommands != null) { - return fillMenuWithCommandsFromCommandgroup(menu, - myOptionsMenuCommands); - } - return false; - } - - /* - * is used by the GuiSetup class to add elements to the options menu - */ - public void addItemToOptionsMenu(Command menuItem, String menuItemText) { - if (myOptionsMenuCommands == null) { - myOptionsMenuCommands = new CommandGroup(); - } - menuItem.getInfoObject().setShortDescr(menuItemText); - myOptionsMenuCommands.add(menuItem); - } - - public boolean onMenuItemSelected(int featureId, MenuItem item) { - if (featureId == Window.FEATURE_OPTIONS_PANEL) { - if (myOptionsMenuCommands != null) { - return myOptionsMenuCommands.myList.get(item.getItemId()) - .execute(); - } - } - return false; - } - - /** - * see {@link Activity#onDestroy} - * - * @param a - */ - public void onDestroy(Activity a) { - Log.d(LOG_TAG, "Default onDestroy behavior"); - pauseRenderer(); - pauseUpdater(); - worldUpdater.killUpdaterThread(); - releaseCamera(); - // killCompleteApplicationProcess(); - } - - /** - * This will kill the complete process and thereby also any other activity - * which uses this process. Only use this method if you want to implement a - * final "Exit application" button. - */ - public static void killCompleteApplicationProcess() { - Log.w(LOG_TAG, "Killing complete process"); - System.gc(); - android.os.Process.killProcess(android.os.Process.myPid()); - System.exit(1); - } - - /** - * see {@link Activity#onStart} - * - * @param a - */ - public void onStart(Activity a) { - Log.d(LOG_TAG, "main onStart (setup=" + this + ")"); - } - - /** - * When this is called the activity is still visible! - * - * see {@link Activity#onPause} - * - * @param a - */ - public void onPause(Activity a) { - Log.d(LOG_TAG, "main onPause (setup=" + this + ")"); - } - - /** - * see {@link Activity#onResume} - * - * @param a - */ - public void onResume(Activity a) { - Log.d(LOG_TAG, "main onResume (setup=" + this + ")"); - } - - /** - * When this is called the activity is no longer visible. Camera see - * {@link Activity#onStop} - * - * @param a - */ - public void onStop(Activity a) { - Log.d(LOG_TAG, "main onStop (setup=" + this + ")"); - pauseRenderer(); - pauseUpdater(); - pauseCameraPreview(); - pauseEventManager(); - } - - /** - * see {@link Activity#onRestart} - * - * @param a - */ - public void onRestart(Activity a) { - Log.d(LOG_TAG, "main onRestart (setup=" + this + ")"); - resumeRenderer(); - resumeUpdater(); - resumeCameraPreview(); - resumeEventManager(); - reloadTextures(); - } - - private void reloadTextures() { - TextureManager.reloadTexturesIfNeeded(); - } - - public void pauseEventManager() { - EventManager.getInstance().pauseEventListeners(); - } - - public void resumeEventManager() { - EventManager.getInstance().resumeEventListeners(myTargetActivity, - useAccelAndMagnetoSensors); - } - - public void pauseUpdater() { - if (worldUpdater != null) { - Log.d(LOG_TAG, "Pausing world updater now"); - worldUpdater.pauseUpdater(); - } - } - - public void resumeUpdater() { - if (worldUpdater != null) { - worldUpdater.resumeUpdater(); - } - } - - public final void pauseCameraPreview() { - if (myCameraView != null) { - Log.d(LOG_TAG, "Pausing camera preview " + myCameraView); - myCameraView.onPause(); - } - } - - public final void resumeCameraPreview() { - if (myCameraView != null) { - Log.d(LOG_TAG, "Resuming camera preview " + myCameraView); - myCameraView.resumeCamera(); - } - } - - public void pauseRenderer() { - if (glRenderer != null) { - Log.d(LOG_TAG, "Pausing renderer and GLSurfaceView now"); - glRenderer.pause(); - if (myGLSurfaceView != null) { - myGLSurfaceView.onPause(); - } - } - } - - public void resumeRenderer() { - if (glRenderer != null) { - Log.d(LOG_TAG, "Resuming renderer and GLSurfaceView now"); - } - glRenderer.resume(); - if (myGLSurfaceView != null) { - myGLSurfaceView.onResume(); - } - } - - public boolean onKeyDown(Activity a, int keyCode, KeyEvent event) { - // if the keyAction isnt defined return false: - return EventManager.getInstance().onKeyDown(keyCode, event); - } - - public float getScreenWidth() { - if (getScreenOrientation() == Surface.ROTATION_90 - || getScreenOrientation() == Surface.ROTATION_270) { - return getActivity().getWindowManager().getDefaultDisplay() - .getHeight(); - } else { - return getActivity().getWindowManager().getDefaultDisplay() - .getWidth(); - } - } - - public float getScreenHeigth() { - if (getScreenOrientation() == Surface.ROTATION_90 - || getScreenOrientation() == Surface.ROTATION_270) { - return getActivity().getWindowManager().getDefaultDisplay() - .getWidth(); - } else { - return getActivity().getWindowManager().getDefaultDisplay() - .getHeight(); - } - } - -} diff --git a/droidar/src/tests/GameLogicTests.java b/droidar/src/tests/GameLogicTests.java deleted file mode 100644 index 18ec431..0000000 --- a/droidar/src/tests/GameLogicTests.java +++ /dev/null @@ -1,53 +0,0 @@ -package tests; - -import gamelogic.ActionList; -import gamelogic.ActionThrowFireball; -import gamelogic.Booster; -import gamelogic.BoosterList; -import gamelogic.GameParticipant; -import gamelogic.Stat; -import gamelogic.StatList; -import de.rwth.R; - -public class GameLogicTests extends SimpleTesting { - - @Override - public void run() throws Exception { - newPlayerTest(); - } - - private void newPlayerTest() throws Exception { - GameParticipant p = new GameParticipant("Player", "P A", 0); - GameParticipant enemy = new GameParticipant("Player", "P Enemy", 0); - - StatList stats = p.getStatList(); - assertNotNull(stats); - assertTrue(stats.add(new Stat(Stat.MAX_HP, R.drawable.icon, 20))); - stats.add(new Stat(Stat.INTELLIGENCE, R.drawable.icon, 20)); - assertTrue(stats.get(Stat.MAX_HP).addBooster( - new Booster(Booster.MAX_HP_PLUS_15, R.drawable.elephant64, 15))); - - BoosterList boosterList = new BoosterList(); - boosterList.add(new Booster(Booster.MAX_HP_MINUS_10, Stat.MAX_HP, - R.drawable.hippopotamus64, -10)); - assertTrue(stats.applyBoosterList(boosterList)); - - assertTrue(stats.get(Stat.MAX_HP).getValue() == 25); - - ActionList actions = p.getActionList(); - actions.add(new ActionThrowFireball(ActionThrowFireball.FIREBALL_ACTION)); - - enemy.getStatList().add(new Stat(Stat.HP, R.drawable.elephant64, 100)); - enemy.getStatList().add( - new Stat(Stat.FIRE_RESISTANCE, R.drawable.elephant64, 5)); - - assertTrue(p.doAction(ActionThrowFireball.FIREBALL_ACTION, enemy) - .actionCorrectlyExecuted()); - - // when target null it should not crash! - assertFalse(p.doAction(ActionThrowFireball.FIREBALL_ACTION, null) - .actionCorrectlyExecuted()); - - } - -} diff --git a/droidar/src/tests/NetworkTests.java b/droidar/src/tests/NetworkTests.java deleted file mode 100644 index 7f73076..0000000 --- a/droidar/src/tests/NetworkTests.java +++ /dev/null @@ -1,163 +0,0 @@ -package tests; - -import network.TCP; -import network.TCP.Responder; -import network.TCP.ResponseListener; -import network.UDP; -import network.UDP.Client; -import network.UDP.Server; -import util.Log; - -public class NetworkTests extends SimpleTesting { - - @Override - public void run() throws Exception { - udpTest(); - // tcpTest(); - // tcpThreadTest(); - } - - private void tcpTest() { - int port = 5221; - String targetIp = TCP.getDeviceIp(); - final String testInput1 = "aaa"; - final String testInput2 = "bbb"; - final String testResponse1 = "raaa"; - final String testResponse2 = "rbbb"; - - final TCP.Server server = new TCP.Server(); - server.waitForMessage(port, new TCP.MessageListener() { - @Override - public void onMessage(String message, Responder response) { - System.out.println("TCP Server got message=" + message); - if (message.equals(testInput1)) { - response.send(testResponse1); - } - if (message.equals(testInput2)) { - response.send(testResponse2); - } - server.killServer(); - } - }); - - final TCP.Client client = new TCP.Client(targetIp, port); - client.send(testInput1, new ResponseListener() { - @SuppressWarnings("null") - @Override - public void onResponse(String responseMessage) { - System.out - .println("TCP Client got response=" + responseMessage); - try { - assertEquals(responseMessage, testResponse1); - } catch (Exception e) { - Log.e("", "TCP test failed: " + e); - Object x = null; - x.toString(); - } - } - }); - - client.send(testInput2, new ResponseListener() { - @SuppressWarnings("null") - @Override - public void onResponse(String responseMessage) { - System.out - .println("TCP Client got response=" + responseMessage); - try { - assertEquals(responseMessage, testResponse2); - client.killConnection(); - } catch (Exception e) { - Log.e("", "TCP test failed: " + e); - Object x = null; - x.toString(); - } - } - }); - - } - - private void tcpThreadTest() { - int port = 5221; - String targetIp = TCP.getDeviceIp(); - final String testInput1 = "aaa"; - final String testInput2 = "bbb"; - final String testResponse1 = "raaa"; - final String testResponse2 = "rbbb"; - - final TCP.Server server = new TCP.Server(); - server.waitForMessage(port, new TCP.MessageListener() { - @Override - public void onMessage(String message, Responder response) { - System.out.println("TCP Server got message=" + message); - if (message.equals(testInput1)) { - response.send(testResponse1); - } - if (message.equals(testInput2)) { - response.send(testResponse2); - } - server.killServer(); - } - }); - - final TCP.Client client = new TCP.Client(targetIp, port); - - for (int i = 0; i < 10; i++) { - new Thread(new Runnable() { - @Override - public void run() { - client.send(testInput1, new ResponseListener() { - @SuppressWarnings("null") - @Override - public void onResponse(String responseMessage) { - System.out.println("TCP Client got response=" - + responseMessage); - try { - assertEquals(responseMessage, testResponse1); - } catch (Exception e) { - Log.e("", "TCP test failed: " + e); - Object x = null; - x.toString(); - } - } - }); - } - }).start(); - } - } - - /** - * This will send some text from the device ip to the device ip (but could - * be any other ip as well) - * - * @throws Exception - */ - private void udpTest() throws Exception { - - int targetPort = 5221; - final String text = "some text"; - final Server server = new UDP.Server(targetPort); - server.receivePackage(new UDP.ReceiveListener() { - @SuppressWarnings("null") - @Override - public void onReceive(String message) { - System.out.println("UDP: recieved " + message); - try { - assertTrue(message.equals(text)); - } catch (Exception e) { - Log.e("", "UDP test failed: " + e); - Object x = null; - x.toString(); - } - server.closeConnection(); - } - }); - - String targetIp = UDP.getDeviceIp(); - System.out.println("UDP ip: " + targetIp); - Client x = new UDP.Client(targetIp, targetPort); - x.sendPackage(text); - x.closeConnection(); - - } - -} From 2f9e4751ea0973caa16a4b83a56aaeb11cd6a0a6 Mon Sep 17 00:00:00 2001 From: rvieras Date: Thu, 5 Dec 2013 14:50:10 -0500 Subject: [PATCH 05/12] Code clean up in actions package. --- droidar/project.properties | 2 +- droidar/src/actions/Action.java | 50 ++--- .../src/actions/ActionBufferedCameraAR.java | 32 +-- .../src/actions/ActionCalcRelativePos.java | 80 ++++--- droidar/src/actions/ActionDoAlongAxis.java | 53 +++-- .../src/actions/ActionMoveCameraBuffered.java | 7 +- .../actions/ActionMoveCameraUnbuffered.java | 18 +- droidar/src/actions/ActionMoveObject.java | 18 +- droidar/src/actions/ActionPlaceObject.java | 108 --------- .../actions/ActionRotateCameraBuffered.java | 87 ++++---- .../actions/ActionRotateCameraBuffered2.java | 23 -- .../actions/ActionRotateCameraBuffered3.java | 25 --- .../actions/ActionRotateCameraBuffered4.java | 24 -- .../ActionRotateCameraBufferedDebug.java | 52 ----- .../ActionRotateCameraBufferedDirect.java | 152 ------------- .../actions/ActionRotateCameraUnbuffered.java | 18 -- .../ActionRotateCameraUnbuffered2.java | 19 -- .../src/actions/ActionUseCameraAngles.java | 123 ---------- .../src/actions/ActionUseCameraAngles2.java | 73 +++--- droidar/src/actions/ActionWASDMovement.java | 67 +++--- .../src/actions/ActionWaitForAccuracy2.java | 158 ------------- .../actions/ActionWithSensorProcessing.java | 210 +++++++++--------- .../src/de/rwth/setups/PlaceObjectsSetup.java | 9 +- .../src/de/rwth/setups/SensorTestSetup.java | 20 +- droidar/src/gui/RadarView.java | 12 +- droidar/src/logger/ARLogger.java | 15 +- droidar/src/preview/AugmentedView.java | 3 +- droidar/src/setup/ArSetup.java | 7 +- 28 files changed, 420 insertions(+), 1045 deletions(-) delete mode 100644 droidar/src/actions/ActionPlaceObject.java delete mode 100644 droidar/src/actions/ActionRotateCameraBuffered2.java delete mode 100644 droidar/src/actions/ActionRotateCameraBuffered3.java delete mode 100644 droidar/src/actions/ActionRotateCameraBuffered4.java delete mode 100644 droidar/src/actions/ActionRotateCameraBufferedDebug.java delete mode 100644 droidar/src/actions/ActionRotateCameraBufferedDirect.java delete mode 100644 droidar/src/actions/ActionRotateCameraUnbuffered.java delete mode 100644 droidar/src/actions/ActionRotateCameraUnbuffered2.java delete mode 100644 droidar/src/actions/ActionUseCameraAngles.java delete mode 100644 droidar/src/actions/ActionWaitForAccuracy2.java diff --git a/droidar/project.properties b/droidar/project.properties index e21e210..4fc43f3 100644 --- a/droidar/project.properties +++ b/droidar/project.properties @@ -7,7 +7,7 @@ # "ant.properties", and override values to adapt the script to your # project structure. -android.library=true +android.library=false # Indicates whether an apk should be generated for each density. split.density=false # Project target. diff --git a/droidar/src/actions/Action.java b/droidar/src/actions/Action.java index 77af7da..799d418 100644 --- a/droidar/src/actions/Action.java +++ b/droidar/src/actions/Action.java @@ -1,44 +1,43 @@ package actions; import listeners.EventListener; +import logger.ARLogger; import util.Log; import util.Vec; import worldData.Updateable; import android.location.Location; import android.view.MotionEvent; +/** + * Base implementation to provide actions to various augmented elements. + */ public abstract class Action implements EventListener, Updateable { - // protected static final float BUFFER_SPEED_ACCEL_SENSOR = 500; - // protected static final float BUFFER_SPEED_MAGNET_SENSOR = 1500; - - protected static final float SMOOTH_ROTATION_SPEED = 2; - protected static final float SMOOTH_MOTION_SPEED = 3; + private static final float SMOOTH_ROTATION_SPEED = 2; + //private static final float SMOOTH_MOTION_SPEED = 3; private static final String LOG_TAG = "action event"; - private boolean accelNotCatchedOutputFlag; - private boolean magnetNotCatchedOutputFlag; + private boolean mAccelNotCatchedOutputFlag; + private boolean mMagnetNotCatchedOutputFlag; @Override public boolean onOrientationChanged(float[] values) { - Log.e("action event", - "onOrientationChanged not catched by defined action: " + ARLogger.error(LOG_TAG, + "onOrientationChanged not catched by defined action: " + this.getClass()); return false; } @Override public boolean onLocationChanged(Location location) { - String s = ""; s += "Time: " + location.getTime() + "\n"; s += "\t Latitude: " + location.getLatitude() + "\n"; s += "\t Longitude: " + location.getLongitude() + "\n"; s += "\t Altitude: " + location.getAltitude() + "\n"; s += "\t Accuracy: " + location.getAccuracy() + "\n"; - Log.d("Location Info", s); - - Log.e("action event", "changeLocation not catched by defined action: " + ARLogger.debug(LOG_TAG, s); + ARLogger.error(LOG_TAG, "changeLocation not catched by defined action: " + this.getClass()); return false; } @@ -53,9 +52,9 @@ public boolean onTouchMove(MotionEvent e1, MotionEvent e2, @Override public boolean onAccelChanged(float[] values) { - if (!accelNotCatchedOutputFlag) { - accelNotCatchedOutputFlag = true; - Log.e("action event", + if (!mAccelNotCatchedOutputFlag) { + mAccelNotCatchedOutputFlag = true; + ARLogger.error(LOG_TAG, "AccelerationValuesChanged not catched by defined action: " + this.getClass()); } @@ -64,10 +63,10 @@ public boolean onAccelChanged(float[] values) { @Override public boolean onMagnetChanged(float[] values) { - if (!magnetNotCatchedOutputFlag) { - magnetNotCatchedOutputFlag = true; - Log.e("action event", - "MegnetometerValuesChanged not catched by defined action: " + if (!mMagnetNotCatchedOutputFlag) { + mMagnetNotCatchedOutputFlag = true; + ARLogger.error(LOG_TAG, + "MagnetValuesChanged not catched by defined action: " + this.getClass()); } return false; @@ -75,7 +74,7 @@ public boolean onMagnetChanged(float[] values) { @Override public boolean onReleaseTouchMove() { - Log.e("action event", + ARLogger.error(LOG_TAG, "onReleaseTouchMove not catched by defined action: " + this.getClass()); return false; @@ -83,26 +82,23 @@ public boolean onReleaseTouchMove() { @Override public boolean onTrackballEvent(float x, float y, MotionEvent event) { - Log.e(LOG_TAG, "onTrackballEvent not catched by defined action: " + ARLogger.error(LOG_TAG, "onTrackballEvent not catched by defined action: " + this.getClass()); return false; } @Override public boolean update(float timeDelta, Updateable parent) { - Log.e(LOG_TAG, + ARLogger.error(LOG_TAG, "update event was not handeld correctly by this action type:" + this.getClass().toString()); - Log.e(LOG_TAG, + ARLogger.error(LOG_TAG, " > As a reaction to this, the action will now be removed from " + "the update cycle! Impelemnt the update method in the specified " + "action and return true to fix this error!"); return false; } - /** - * default implementation done here (Vec.morphToNewAngleVec()) - */ @Override public void onCamRotationVecUpdate(Vec target, Vec values, float timeDelta) { Vec.morphToNewAngleVec(target, values.x, values.y, values.z, timeDelta diff --git a/droidar/src/actions/ActionBufferedCameraAR.java b/droidar/src/actions/ActionBufferedCameraAR.java index 74d04f1..31fe4e5 100644 --- a/droidar/src/actions/ActionBufferedCameraAR.java +++ b/droidar/src/actions/ActionBufferedCameraAR.java @@ -13,11 +13,11 @@ */ public class ActionBufferedCameraAR extends Action { - // x is the short side of the screen (in landscape mode) - private final float TOUCH_SENSITY_X; - // y is the long side of the screen - private final float TOUCH_SENSITY_Y; - private GLCamera myTargetCamera; + private static final float DEFAULT_X_TOUCH_SENSITY = 2; + private static final float DEFAULT_Y_TOUCH_SENSITY = 36; + private final float mXTouchSensity; + private final float mYTouchSensity; + private GLCamera mTargetCamera; /** * @param glCamera @@ -29,33 +29,33 @@ public class ActionBufferedCameraAR extends Action { */ public ActionBufferedCameraAR(GLCamera glCamera, float sensityX, float sensityY) { - myTargetCamera = glCamera; - TOUCH_SENSITY_X = sensityX; - TOUCH_SENSITY_Y = sensityY; + mTargetCamera = glCamera; + mXTouchSensity = sensityX; + mYTouchSensity = sensityY; } /** - * uses default accuracy + * uses default accuracy. * - * @param camera + * @param camera - {@link gl.GLCamera} */ public ActionBufferedCameraAR(GLCamera camera) { - this(camera, 2, 36); + this(camera, DEFAULT_X_TOUCH_SENSITY, DEFAULT_Y_TOUCH_SENSITY); } @Override public boolean onTouchMove(MotionEvent e1, MotionEvent e2, float screenDeltaX, float screenDeltaY) { - screenDeltaX = screenDeltaX / TOUCH_SENSITY_X; - screenDeltaY = -screenDeltaY / TOUCH_SENSITY_Y; - myTargetCamera.changeZAngleBuffered(screenDeltaX); - myTargetCamera.changeZPositionBuffered(screenDeltaY); + screenDeltaX = screenDeltaX / mXTouchSensity; + screenDeltaY = -screenDeltaY / mYTouchSensity; + mTargetCamera.changeZAngleBuffered(screenDeltaX); + mTargetCamera.changeZPositionBuffered(screenDeltaY); return true; } @Override public boolean onReleaseTouchMove() { - myTargetCamera.resetBufferedAngle(); + mTargetCamera.resetBufferedAngle(); return true; } diff --git a/droidar/src/actions/ActionCalcRelativePos.java b/droidar/src/actions/ActionCalcRelativePos.java index dcf3147..f509245 100644 --- a/droidar/src/actions/ActionCalcRelativePos.java +++ b/droidar/src/actions/ActionCalcRelativePos.java @@ -2,8 +2,8 @@ import geo.GeoCalcer; import gl.GLCamera; +import logger.ARLogger; import system.EventManager; -import util.Log; import worldData.World; import android.location.Location; @@ -26,16 +26,17 @@ public class ActionCalcRelativePos extends Action { /** * On default this is false, because the altitude values received via GPS - * are very inaccurate + * are very inaccurate. * * set this to true if your scenario need to take altitude values into * account */ public static boolean USE_ALTITUDE_VALUES = false; + /** * set this to false if you want to position objects at the real 0 altitude, * because otherwise if you set altitude to 0 the current device altitude - * will be used + * will be used. */ public static final boolean USE_DEVICE_ALTI_FOR_ZERO = true; @@ -49,24 +50,29 @@ public class ActionCalcRelativePos extends Action { * {@link EventManager#getZeroPositionLocationObject()} values. Should store * the same information. where is the better place to store the data TODO */ - private double nullLongitude; - private double nullLatitude; - private double nullAltitude; + private double mNullLongitude; + private double mNullLatitude; + private double mNullAltitude; - private World myWorld; - private GLCamera myCamera; - private GeoCalcer myGeoCalcer; + private World mWorld; + private GLCamera mCamera; + private GeoCalcer mGeoCalcer; + /** + * Constructor. + * @param world - {@link worldData.World} + * @param camera - {@link gl.GLCamera} + */ public ActionCalcRelativePos(World world, GLCamera camera) { - myWorld = world; - myCamera = camera; + mWorld = world; + mCamera = camera; } @Override public boolean onLocationChanged(Location location) { - if (nullLatitude == 0 || nullLongitude == 0) { + if (mNullLatitude == 0 || mNullLongitude == 0) { /* - * if the nullLat or nullLong are 0 this method was probably never + * if the mNullLat or mNullLong are 0 this method was probably never * called before (TODO problem when living in greenwhich e.g.?) */ resetWorldZeroPositions(location); @@ -78,14 +84,14 @@ public boolean onLocationChanged(Location location) { * to increase performance because this method will be called every * time a new GPS-position arrives */ - final double latitudeDistInMeters = (location.getLatitude() - nullLatitude) * 111133.3333; - final double longitudeDistInMeters = (location.getLongitude() - nullLongitude) - * 111319.4917 * Math.cos(nullLatitude * 0.0174532925); + final double latitudeDistInMeters = (location.getLatitude() - mNullLatitude) * 111133.3333; + final double longitudeDistInMeters = (location.getLongitude() - mNullLongitude) + * 111319.4917 * Math.cos(mNullLatitude * 0.0174532925); if (LOG_SHOW_POSITION) { - Log.v(LOG_TAG, "latutude dist (north(+)/south(-))=" + ARLogger.verbose(LOG_TAG, "latutude dist (north(+)/south(-))=" + latitudeDistInMeters); - Log.v(LOG_TAG, "longitude dist (east(+)/west(-))=" + ARLogger.verbose(LOG_TAG, "longitude dist (east(+)/west(-))=" + longitudeDistInMeters); } @@ -99,13 +105,13 @@ public boolean onLocationChanged(Location location) { * correct height */ final double relativeHeight = location.getAltitude() - - nullAltitude; - myCamera.setNewPosition((float) longitudeDistInMeters, + - mNullAltitude; + mCamera.setNewPosition((float) longitudeDistInMeters, (float) latitudeDistInMeters, (float) relativeHeight); } else { // else dont change the z value - myCamera.setNewPosition((float) longitudeDistInMeters, + mCamera.setNewPosition((float) longitudeDistInMeters, (float) latitudeDistInMeters); } @@ -115,37 +121,43 @@ public boolean onLocationChanged(Location location) { return true; } - private void resetCameraToNullPosition() { - myCamera.resetPosition(false); + private void resetCameraTomNullPosition() { + mCamera.resetPosition(false); } private boolean worldShouldBeRecalced(double latDistMet, double longDistMet) { - if (Math.abs(latDistMet) > MAX_METER_DISTANCE) + if (Math.abs(latDistMet) > MAX_METER_DISTANCE) { return true; - if (Math.abs(longDistMet) > MAX_METER_DISTANCE) + } else if (Math.abs(longDistMet) > MAX_METER_DISTANCE) { return true; + } return false; } + /** + * Reset the world to (0,0,0) position. + * @param location {@link Location} + */ public void resetWorldZeroPositions(Location location) { - Log.d(LOG_TAG, "Reseting virtual world positions"); + ARLogger.debug(LOG_TAG, "Reseting virtual world positions"); setNewNullValues(location); - resetCameraToNullPosition(); + resetCameraTomNullPosition(); calcNewWorldPositions(); } private void setNewNullValues(Location location) { - nullLatitude = location.getLatitude(); - nullLongitude = location.getLongitude(); - nullAltitude = location.getAltitude(); + mNullLatitude = location.getLatitude(); + mNullLongitude = location.getLongitude(); + mNullAltitude = location.getAltitude(); EventManager.getInstance().setZeroLocation(location); } private void calcNewWorldPositions() { - if (myGeoCalcer == null) - myGeoCalcer = new GeoCalcer(); - myGeoCalcer.setNullPos(nullLatitude, nullLongitude, nullAltitude); - myWorld.accept(myGeoCalcer); + if (mGeoCalcer == null) { + mGeoCalcer = new GeoCalcer(); + } + mGeoCalcer.setNullPos(mNullLatitude, mNullLongitude, mNullAltitude); + mWorld.accept(mGeoCalcer); } } diff --git a/droidar/src/actions/ActionDoAlongAxis.java b/droidar/src/actions/ActionDoAlongAxis.java index 359e716..775193f 100644 --- a/droidar/src/actions/ActionDoAlongAxis.java +++ b/droidar/src/actions/ActionDoAlongAxis.java @@ -16,13 +16,16 @@ */ public abstract class ActionDoAlongAxis extends Action { - protected GLCamera myTargetCamera; - private float myTrackballFactor; - private final float myTouchscreenReductionFactor; - private Vec movementVec = new Vec(); + private GLCamera mTargetCamera; + private float mTrackballFactor; + private final float mTouchscreenReductionFactor; + private Vec mMovementVec = new Vec(); + + private static final int CIRCLE = 360; /** - * @param camera + * Constructor. + * @param camera - {@link gl.GLCamera} * @param trackballFactor * should be around 2-15 * @param touchscreenFactor @@ -31,14 +34,14 @@ public abstract class ActionDoAlongAxis extends Action { */ public ActionDoAlongAxis(GLCamera camera, float trackballFactor, float touchscreenFactor) { - myTargetCamera = camera; - myTrackballFactor = trackballFactor; - myTouchscreenReductionFactor = touchscreenFactor; + mTargetCamera = camera; + mTrackballFactor = trackballFactor; + mTouchscreenReductionFactor = touchscreenFactor; } @Override public boolean onTrackballEvent(float x, float y, MotionEvent event) { - AlignAcordingToViewAxes(x * myTrackballFactor, -y * myTrackballFactor); + alignAcordingToViewAxes(x * mTrackballFactor, -y * mTrackballFactor); return true; } @@ -47,8 +50,8 @@ public boolean onTrackballEvent(float x, float y, MotionEvent event) { public boolean onTouchMove(MotionEvent e1, MotionEvent e2, float screenDeltaX, float screenDeltaY) { - AlignAcordingToViewAxes(screenDeltaX / myTouchscreenReductionFactor, - -screenDeltaY / myTouchscreenReductionFactor); + alignAcordingToViewAxes(screenDeltaX / mTouchscreenReductionFactor, + -screenDeltaY / mTouchscreenReductionFactor); return true; } @@ -56,19 +59,29 @@ public boolean onTouchMove(MotionEvent e1, MotionEvent e2, * This is where the magic happens. The input movement is mapped according * to the virtual camera rotation around the z axis to do the movement * "along the axes" - * - * @param x - * @param y */ - private void AlignAcordingToViewAxes(float x, float y) { - movementVec.x = x; - movementVec.y = y; - movementVec.rotateAroundZAxis(360 - (myTargetCamera + private void alignAcordingToViewAxes(float x, float y) { + mMovementVec.x = x; + mMovementVec.y = y; + mMovementVec.rotateAroundZAxis(CIRCLE - (mTargetCamera .getCameraAnglesInDegree()[0])); - doAlongViewAxis(movementVec.x, movementVec.y); + doAlongViewAxis(mMovementVec.x, mMovementVec.y); } + + /** + * Get the target camera. + * @return - {@link gl.GLCamera} + */ + public GLCamera getTargetCamera() { + return mTargetCamera; + } - public abstract void doAlongViewAxis(float x, float y); + /** + * Perform some action along the view axis. + * @param x - axis + * @param y - axis + */ + abstract void doAlongViewAxis(float x, float y); } diff --git a/droidar/src/actions/ActionMoveCameraBuffered.java b/droidar/src/actions/ActionMoveCameraBuffered.java index ba39949..c06bbe9 100644 --- a/droidar/src/actions/ActionMoveCameraBuffered.java +++ b/droidar/src/actions/ActionMoveCameraBuffered.java @@ -4,7 +4,7 @@ /** * can be used to move the virtual camera when touching the screen or using the - * trackball etc + * trackball etc. * * @author Spobo * @@ -12,7 +12,8 @@ public class ActionMoveCameraBuffered extends ActionDoAlongAxis { /** - * @param camera + * Constructor. + * @param camera - {@link gl.GLCamera} * @param trackballFactor * something like 5 * @param touchscreenFactor @@ -27,7 +28,7 @@ public ActionMoveCameraBuffered(GLCamera camera, float trackballFactor, @Override public void doAlongViewAxis(float x, float y) { - myTargetCamera.changeXYPositionBuffered(x, y); + getTargetCamera().changeXYPositionBuffered(x, y); } } diff --git a/droidar/src/actions/ActionMoveCameraUnbuffered.java b/droidar/src/actions/ActionMoveCameraUnbuffered.java index 01fe32c..64f7e81 100644 --- a/droidar/src/actions/ActionMoveCameraUnbuffered.java +++ b/droidar/src/actions/ActionMoveCameraUnbuffered.java @@ -3,25 +3,31 @@ import gl.GLCamera; import android.view.MotionEvent; +/** + * Perform unbuffered processing when moving the camera. + * //TODO: Determine if this class is needed. + * + */ @Deprecated public class ActionMoveCameraUnbuffered extends Action { - private GLCamera myCamera; - private float myFactor; + private GLCamera mCamera; + private float mFactor; /** - * @param camera + * Constructor. + * @param camera - {@link gl.GLCamera} * @param factor * should be around 2-15 */ public ActionMoveCameraUnbuffered(GLCamera camera, float factor) { - myCamera = camera; - myFactor = factor; + mCamera = camera; + mFactor = factor; } @Override public boolean onTrackballEvent(float x, float y, MotionEvent event) { - myCamera.changePositionUnbuffered(y * myFactor, x * myFactor); + mCamera.changePositionUnbuffered(y * mFactor, x * mFactor); return true; } diff --git a/droidar/src/actions/ActionMoveObject.java b/droidar/src/actions/ActionMoveObject.java index 83d8e96..c176ba9 100644 --- a/droidar/src/actions/ActionMoveObject.java +++ b/droidar/src/actions/ActionMoveObject.java @@ -6,13 +6,18 @@ import worldData.MoveComp; import worldData.Obj; +/** + * An action to move an object along the axis. + * + */ public class ActionMoveObject extends ActionDoAlongAxis { - private Wrapper target; + private Wrapper mTarget; /** - * @param wrapper - * @param camera + * Constructor. + * @param wrapper - {@link util.Wrapper} + * @param camera - {@link gl.GLCamera} * @param trackballFactor * should be around 2-15 * @param touchscreenFactor @@ -22,13 +27,14 @@ public class ActionMoveObject extends ActionDoAlongAxis { public ActionMoveObject(Wrapper wrapper, GLCamera camera, float trackballFactor, float touchscreenFactor) { super(camera, trackballFactor, touchscreenFactor); - target = wrapper; + mTarget = wrapper; } @Override public void doAlongViewAxis(float x, float y) { - if (target != null && target.getObject() instanceof Obj) - foundObj((Obj) target.getObject(), x, y); + if (mTarget != null && mTarget.getObject() instanceof Obj) { + foundObj((Obj) mTarget.getObject(), x, y); + } } private void foundObj(Obj obj, float x, float y) { diff --git a/droidar/src/actions/ActionPlaceObject.java b/droidar/src/actions/ActionPlaceObject.java deleted file mode 100644 index 23aa19d..0000000 --- a/droidar/src/actions/ActionPlaceObject.java +++ /dev/null @@ -1,108 +0,0 @@ -package actions; - -import gl.GLCamera; -import util.Vec; -import util.Wrapper; -import worldData.MoveComp; -import worldData.Obj; - -import components.ViewPosCalcerComp; - -import de.rwth.setups.PlaceObjectsSetupTwo; - -/** - * Don't use this {@link Action} anymore, instead use a - * {@link ViewPosCalcerComp} like in the {@link PlaceObjectsSetupTwo} ! - * - * @author Spobo - * - */ -@Deprecated -public class ActionPlaceObject extends ActionUseCameraAngles { - - private GLCamera myCamera; - private Wrapper myObjWrapper; - private float maxDistance; - private float myAzimuth; - private MoveComp myMoveObjComp; - private Obj compareObj; - - /** - * @param targetCamera - * @param objToPlace - * the Wrapper should contain a {@link Obj} - * @param maxDistance - * maximum distance in meters how far away from the camera the - * elements can be places - */ - @Deprecated - public ActionPlaceObject(GLCamera targetCamera, Wrapper objToPlace, - float maxDistance) { - super(targetCamera); - myCamera = targetCamera; - myObjWrapper = objToPlace; - this.maxDistance = maxDistance; - myMoveObjComp = new MoveComp(4); - } - - @Override - public void updateCompassAzimuth(float azimuth) { - myAzimuth = azimuth; - } - - @Override - public void updatePitch(float pitch) { - // not needed for movement, maybe for rotation? - } - - @Override - public void updateRoll(float rollAngle) { - /* - * if the element in the wrapper changes, flip the component to the new - * element if its an Obj: - */ - final Object o = myObjWrapper.getObject(); - if (compareObj != o) { - System.out.println(o.getClass().toString()); - if (o instanceof Obj) { - if (compareObj != null) - compareObj.remove(myMoveObjComp); - ((Obj) o).setComp(myMoveObjComp); - System.out.println("myMoveCom was set"); - compareObj = (Obj) o; - calcPosOnFloor(rollAngle); - } - } else { - calcPosOnFloor(rollAngle); - } - } - - private void calcPosOnFloor(float rollAngle) { - final Vec camPos = myCamera.getPosition(); - if (camPos != null) { - Vec targetPos = myMoveObjComp.myTargetPos; - /* - * the following formula calculates the opposite side of the - * right-angled triangle where the adjacent side is the height of - * the camera and the alpha angle the roll angle of the device - * - * this way the distance can be calculated by the angle - */ - float distance = (float) (Math.tan(Math.toRadians(rollAngle)) * camPos.z); - if (distance > maxDistance) - distance = maxDistance; - targetPos.x = 0; - targetPos.y = distance; - targetPos.z = 0; - if (myAzimuth != 0) { - // now calc the real position according to the cam rotation: - targetPos.rotateAroundZAxis(360 - myAzimuth); - } - - // dont forget to mention that the camera doesnt have to be a - // the zero point: - targetPos.x += camPos.x; - targetPos.y += camPos.y; - } - } -} diff --git a/droidar/src/actions/ActionRotateCameraBuffered.java b/droidar/src/actions/ActionRotateCameraBuffered.java index b460b4e..d8d540e 100644 --- a/droidar/src/actions/ActionRotateCameraBuffered.java +++ b/droidar/src/actions/ActionRotateCameraBuffered.java @@ -1,57 +1,60 @@ package actions; import gl.GLCamRotationController; -import actions.algos.BufferAlgo1; +import actions.algos.Algo; import actions.algos.BufferAlgo2; import actions.algos.SensorAlgo1; -import actions.algos.SmoothingAlgo; +/** + * Perform buffered camera rotation. + * + */ public class ActionRotateCameraBuffered extends ActionWithSensorProcessing { - + + //magic numbers + private static final float ACCEL_ALGO_BARRIER = 0.5f; + private static final float ACCEL_BUFFER_BARRIER = 0.2f; + private static final float MAGNET_ALGO_BARRIER = 0.8f; + private static final float MAGNET_BUFFER_BARRIER = 0.2f; + private static final float ORIENT_ALGO_BARRIER = 0.8f; + private static final float ORIENT_BUFFER_BARRIER = 0.8f; + + /** + * Constructor. + * @param targetCamera - {@link gl.GLCamRotationController} + */ public ActionRotateCameraBuffered(GLCamRotationController targetCamera) { super(targetCamera); } @Override - public void initAlgos() { - //accelAlgo = new SensorAlgo1(0.1f); - //accelAlgo = new SmoothingAlgo(true); - //accelAlgo = new SmoothingAlgo(SmoothingAlgo.FilterType.BAND); - //accelBufferAlgo = new BufferAlgo1(0.01f, 2f); - - //magnetAlgo = new SensorAlgo1(1.4f); - //magnetAlgo = new SmoothingAlgo(SmoothingAlgo.FilterType.BAND); - //magnetBufferAlgo = new BufferAlgo1(0.01f, 2f); - - //orientAlgo = new SmoothingAlgo(true);//new SensorAlgo1(0.35f);// TODO - //orientAlgo = new SmoothingAlgo(SmoothingAlgo.FilterType.BAND); - //orientationBufferAlgo = new BufferAlgo2(0.1f); // TODO - - //accelAlgo = new SmoothingAlgo(SmoothingAlgo.FilterType.BAND); - //magnetAlgo = new SmoothingAlgo(SmoothingAlgo.FilterType.BAND); - accelAlgo = new SensorAlgo1(0.5f); - magnetAlgo = new SensorAlgo1(0.8f); - accelBufferAlgo = new BufferAlgo2(0.2f); - magnetBufferAlgo = new BufferAlgo2(0.2f); - - orientAlgo = new SensorAlgo1(0.8f);// TODO - orientationBufferAlgo = new BufferAlgo2(0.2f); // TODO + protected Algo createMagnetAlgo() { + return new SensorAlgo1(MAGNET_ALGO_BARRIER); } -// @Override -// public synchronized boolean onOrientationChanged(float[] values) { -// return false; -// } - -// @Override -// public synchronized boolean onAccelChanged(float[] values) { -// return false; -// } -// -// @Override -// public synchronized boolean onMagnetChanged(float[] values) { -// return false; -// } - - + @Override + protected Algo createAccelAlgo() { + return new SensorAlgo1(ACCEL_ALGO_BARRIER); + } + + @Override + protected Algo createOrientAlgo() { + return new SensorAlgo1(ORIENT_ALGO_BARRIER); + } + + @Override + protected Algo createMagnetBufferAlgo() { + return new BufferAlgo2(MAGNET_BUFFER_BARRIER); + } + + @Override + protected Algo createAccelBufferAlgo() { + return new BufferAlgo2(ACCEL_BUFFER_BARRIER); + } + + @Override + protected Algo createOrientBufferAlgo() { + return new BufferAlgo2(ORIENT_BUFFER_BARRIER); + } + } diff --git a/droidar/src/actions/ActionRotateCameraBuffered2.java b/droidar/src/actions/ActionRotateCameraBuffered2.java deleted file mode 100644 index 18e3c05..0000000 --- a/droidar/src/actions/ActionRotateCameraBuffered2.java +++ /dev/null @@ -1,23 +0,0 @@ -package actions; - -import gl.GLCamRotationController; -import actions.algos.BufferAlgo1; -import actions.algos.SensorAlgo1; - -public class ActionRotateCameraBuffered2 extends ActionWithSensorProcessing { - - public ActionRotateCameraBuffered2(GLCamRotationController targetCamera) { - super(targetCamera); - } - - @Override - public void initAlgos() { - accelAlgo = new SensorAlgo1(0.1f); - magnetAlgo = new SensorAlgo1(1.4f); - orientAlgo = new SensorAlgo1(0.005f);// TODO find correct values - - accelBufferAlgo = new BufferAlgo1(0.1f, 4f); - magnetBufferAlgo = new BufferAlgo1(0.1f, 4f); - } - -} diff --git a/droidar/src/actions/ActionRotateCameraBuffered3.java b/droidar/src/actions/ActionRotateCameraBuffered3.java deleted file mode 100644 index 0e0d514..0000000 --- a/droidar/src/actions/ActionRotateCameraBuffered3.java +++ /dev/null @@ -1,25 +0,0 @@ -package actions; - -import gl.GLCamRotationController; -import actions.algos.BufferAlgo3; -import actions.algos.SensorAlgo1; - -public class ActionRotateCameraBuffered3 extends ActionWithSensorProcessing { - - public ActionRotateCameraBuffered3(GLCamRotationController targetCamera) { - super(targetCamera); - } - - @Override - protected void initAlgos() { - accelAlgo = new SensorAlgo1(0.5f); - magnetAlgo = new SensorAlgo1(0.8f); - - orientAlgo = new SensorAlgo1(0.5f);// TODO - orientationBufferAlgo = new BufferAlgo3(0.2f, 0.1f, 4); // TODO - - accelBufferAlgo = new BufferAlgo3(0.2f, 0.1f, 4); - magnetBufferAlgo = new BufferAlgo3(0.2f, 0.1f, 4); - } - -} diff --git a/droidar/src/actions/ActionRotateCameraBuffered4.java b/droidar/src/actions/ActionRotateCameraBuffered4.java deleted file mode 100644 index 2ad6482..0000000 --- a/droidar/src/actions/ActionRotateCameraBuffered4.java +++ /dev/null @@ -1,24 +0,0 @@ -package actions; - -import gl.GLCamRotationController; -import actions.algos.BufferAlgo2; -import actions.algos.SensorAlgo1; - -public class ActionRotateCameraBuffered4 extends ActionWithSensorProcessing { - - public ActionRotateCameraBuffered4(GLCamRotationController targetCamera) { - super(targetCamera); - } - - @Override - protected void initAlgos() { - accelAlgo = new SensorAlgo1(0.5f); - magnetAlgo = new SensorAlgo1(0.8f); - accelBufferAlgo = new BufferAlgo2(0.2f); - magnetBufferAlgo = new BufferAlgo2(0.2f); - - orientAlgo = new SensorAlgo1(0.5f);// TODO - orientationBufferAlgo = new BufferAlgo2(0.2f); // TODO - } - -} diff --git a/droidar/src/actions/ActionRotateCameraBufferedDebug.java b/droidar/src/actions/ActionRotateCameraBufferedDebug.java deleted file mode 100644 index 92c79b5..0000000 --- a/droidar/src/actions/ActionRotateCameraBufferedDebug.java +++ /dev/null @@ -1,52 +0,0 @@ -package actions; - -import gl.GLCamera; -import worldData.Updateable; - -/** - * this class is for debugging purpose only at the moment and has to be modified - * to work. it extracts the the yaw, pitch and roll from the sensor data arrays - * - * @author Spobo - * - */ -@Deprecated -public class ActionRotateCameraBufferedDebug extends Action { - - private Updateable myCamera; - - public ActionRotateCameraBufferedDebug(GLCamera camera) { - myCamera = camera; - } - - @Override - public boolean onAccelChanged(float[] values) { - - float pitch = (float) +Math.toDegrees(Math.atan2(-values[1], - Math.sqrt(values[2] * values[2] + values[0] * values[0]))); - float roll = (float) -Math.toDegrees(Math.atan2(values[0], -values[2])); - - return true; - } - - @Override - public boolean onMagnetChanged(float[] values) { - - float yaw = (float) -Math.toDegrees(Math.atan2(-values[0], - Math.sqrt(values[1] * values[1] + values[2] * values[2]))); - float pitch = (float) -Math - .toDegrees(Math.atan2(-values[2], values[1])); - - return true; - } - - @Override - public boolean onOrientationChanged(float[] values) { - // TODO find right order: - float yaw = values[0]; - float pitch = values[1]; - float roll = values[2]; - return true; - } - -} diff --git a/droidar/src/actions/ActionRotateCameraBufferedDirect.java b/droidar/src/actions/ActionRotateCameraBufferedDirect.java deleted file mode 100644 index f496052..0000000 --- a/droidar/src/actions/ActionRotateCameraBufferedDirect.java +++ /dev/null @@ -1,152 +0,0 @@ -package actions; - -import gl.GLCamRotationController; -import gl.GLUtilityClass; -import util.Calculus; -import actions.algos.Algo; -import actions.algos.BufferAlgo1; -import actions.algos.SensorAlgo1; -import android.hardware.SensorManager; -import android.view.MotionEvent; - -/** - * This is nearly the same like {@link ActionRotateCameraBuffered} (same values) - * but without buffering in the update thread. This class is just for testing so - * it is depricated and might be removed soon. - * - * @author Spobo - * - */ -@Deprecated -public class ActionRotateCameraBufferedDirect extends Action { - - private GLCamRotationController myTargetCamera; - - public Algo magnetAlgo; - public Algo accelAlgo; - public Algo orientAlgo; - public Algo accelBufferAlgo; - public Algo magnetBufferAlgo; - public Algo orientationBufferAlgo; - - private float[] myAccelValues = new float[3]; - private float[] myMagnetValues = new float[3]; - private float[] myOrientValues = new float[3]; - - private boolean accelChanged; - private float[] myNewAccelValues; - private boolean magnetoChanged; - private float[] myNewMagnetValues; - private boolean orientationDataChanged; - private float[] myNewOrientValues; - - private float[] unrotatedMatrix = Calculus.createIdentityMatrix(); - private float[] rotationMatrix = Calculus.createIdentityMatrix(); - - private float timeDelta; - - public ActionRotateCameraBufferedDirect(GLCamRotationController targetCamera) { - myTargetCamera = targetCamera; - accelAlgo = new SensorAlgo1(0.1f); - magnetAlgo = new SensorAlgo1(1.4f); - orientAlgo = new SensorAlgo1(0.005f);// TODO find correct values - - accelBufferAlgo = new BufferAlgo1(0.1f, 4f); - magnetBufferAlgo = new BufferAlgo1(0.1f, 4f); - timeDelta = 0.02f; - } - - @Override - public boolean onTouchMove(MotionEvent e1, MotionEvent e2, - float screenDeltaX, float screenDeltaY) { - myTargetCamera.changeZAngleBuffered(screenDeltaY); - return true; - } - - @Override - public synchronized boolean onAccelChanged(float[] values) { - - if (accelAlgo != null) - myNewAccelValues = accelAlgo.execute(values); - else - myNewAccelValues = values; - accelChanged = true; - calc(); - return true; - - } - - @Override - public synchronized boolean onMagnetChanged(float[] values) { - if (magnetAlgo != null) - myNewMagnetValues = magnetAlgo.execute(values); - else - myNewMagnetValues = values; - magnetoChanged = true; - calc(); - return true; - - } - - @Override - public synchronized boolean onOrientationChanged(float[] values) { - if (orientAlgo != null) - myNewOrientValues = orientAlgo.execute(values); - else - myNewOrientValues = values; - orientationDataChanged = true; - calc(); - return true; - - } - - private void calc() { - if (magnetoChanged || accelChanged || orientationDataChanged) { - if (magnetoChanged || accelChanged) { - // if accel or magnet changed: - if (accelChanged) { - accelChanged = false; - if (accelBufferAlgo != null) - accelBufferAlgo.execute(myAccelValues, - myNewAccelValues, timeDelta); - else - myAccelValues = myNewAccelValues; - } - if (magnetoChanged) { - magnetoChanged = false; - if (magnetBufferAlgo != null) - magnetBufferAlgo.execute(myMagnetValues, - myNewMagnetValues, timeDelta); - else - myMagnetValues = myNewMagnetValues; - } - // first calc the unrotated matrix: - SensorManager.getRotationMatrix(unrotatedMatrix, null, - myAccelValues, myMagnetValues); - } else if (orientationDataChanged) { - orientationDataChanged = false; - if (orientationBufferAlgo != null) - orientationBufferAlgo.execute(myOrientValues, - myNewOrientValues, timeDelta); - else - myOrientValues = myNewOrientValues; - GLUtilityClass.getRotationMatrixFromVector(unrotatedMatrix, - myOrientValues); - } - - // then rotate it according to the screen rotation: - SensorManager.remapCoordinateSystem(unrotatedMatrix, - SensorManager.AXIS_Y, SensorManager.AXIS_MINUS_X, - rotationMatrix); - - myTargetCamera.setRotationMatrix(rotationMatrix, 0); - } - } - - @Override - public boolean onReleaseTouchMove() { - myTargetCamera.resetBufferedAngle(); - return true; - } - -} diff --git a/droidar/src/actions/ActionRotateCameraUnbuffered.java b/droidar/src/actions/ActionRotateCameraUnbuffered.java deleted file mode 100644 index e571c9a..0000000 --- a/droidar/src/actions/ActionRotateCameraUnbuffered.java +++ /dev/null @@ -1,18 +0,0 @@ -package actions; - -import gl.GLCamRotationController; - -public class ActionRotateCameraUnbuffered extends ActionWithSensorProcessing { - - private static final String LOG_TAG = "ActionRotateCameraUnbuffered"; - - public ActionRotateCameraUnbuffered(GLCamRotationController targetCamera) { - super(targetCamera); - } - - @Override - protected void initAlgos() { - // no buffering at all so dont init any algos - } - -} diff --git a/droidar/src/actions/ActionRotateCameraUnbuffered2.java b/droidar/src/actions/ActionRotateCameraUnbuffered2.java deleted file mode 100644 index fe0dcf6..0000000 --- a/droidar/src/actions/ActionRotateCameraUnbuffered2.java +++ /dev/null @@ -1,19 +0,0 @@ -package actions; - -import gl.GLCamRotationController; -import actions.algos.SensorAlgo1; - -public class ActionRotateCameraUnbuffered2 extends ActionWithSensorProcessing { - - public ActionRotateCameraUnbuffered2(GLCamRotationController targetCamera) { - super(targetCamera); - } - - @Override - protected void initAlgos() { - accelAlgo = new SensorAlgo1(0.5f); - magnetAlgo = new SensorAlgo1(0.8f); - orientAlgo = new SensorAlgo1(0.5f);// TODO - } - -} diff --git a/droidar/src/actions/ActionUseCameraAngles.java b/droidar/src/actions/ActionUseCameraAngles.java deleted file mode 100644 index 1f87136..0000000 --- a/droidar/src/actions/ActionUseCameraAngles.java +++ /dev/null @@ -1,123 +0,0 @@ -package actions; - -import gl.GLCamera; -import worldData.Updateable; -import android.hardware.SensorManager; - -/** - * Use - * - * Children of this class can access the angles of the specified camera - * - * - * - * @author Spobo - * - */ -@Deprecated -public abstract class ActionUseCameraAngles extends Action { - - @Deprecated - private int accelCounter; - @Deprecated - private int accelThreshold = 10; - /** - * sould represent {@link SensorManager#getOrientation(float[], float[])} - */ - @Deprecated - private float[] myAngles = new float[3]; - private GLCamera myCamera; - - public ActionUseCameraAngles(GLCamera camera) { - myCamera = camera; - } - - /** - * this affects how often the updatePitch() and updateRoll() methods are - * called. - * - * @param threshold - * 1 means update on every event 10 means update every 10 events. - * default is 10 - */ - public void setUpdateThreshold(int threshold) { - this.accelThreshold = threshold; - } - - @Override - public boolean onAccelChanged(float[] values) { - accelCounter++; - if (accelCounter > accelThreshold) { - accelCounter = 0; - /* - * missing documentation for the following calculations.. TODO - */ - float pitch = (float) Math.toDegrees(Math.atan2(-values[1], - Math.sqrt(values[2] * values[2] + values[0] * values[0]))); - myAngles[1] = pitch; - updatePitch(pitch); - float roll = 180 + (float) -Math.toDegrees(Math.atan2(values[0], - -values[2])); - myAngles[2] = pitch; - updateRoll(roll); - } - return true; - } - - /** - * pitch is the rotation around the x axis. when the device would be a - * steering wheel, this method would indicate how much it is rotated - * - * @param pitchAngle - * 0 means the car drives straight forward, positive values (0 to - * 90) mean that the car turns left, negative values mean that - * the car turns right - */ - public abstract void updatePitch(float pitchAngle); - - /** - * the roll is the rotation around the y axis. if the device would be your - * head 0 would mean you are looking on the ground, 90 would mean you look - * in front of you and 180 would mean you look in the sky - * - * @param rollAngle - * from 0 to 360. 0 means the camera targets the ground, 180 the - * camera looks into the sky - */ - public abstract void updateRoll(float rollAngle); - - /** - * @param azimuth - * 0=north 90=east 180=south 270=west - */ - public abstract void updateCompassAzimuth(float azimuth); - - @Override - public boolean onOrientationChanged(float[] values) { - /* - * the use of the orientation sensor results in other values then the - * normal magnetometer and accelerometer values. Therefore it was - * disabled for the moment. - */ - // float pitch = -xAngle; - // float roll = -yAngle; - // updateCompassDirection(-zAngle); - return true; - } - - @Override - public boolean update(float timeDelta, Updateable parent) { - float[] v = myCamera.getCameraAnglesInDegree(); - - float azimuth = v[0]; - if (myCamera.getRotation() != null) - azimuth += myCamera.getRotation().z; - if (azimuth >= 360) - azimuth -= 360; - myAngles[0] = azimuth; - updateCompassAzimuth(azimuth); - - return true; - } - -} diff --git a/droidar/src/actions/ActionUseCameraAngles2.java b/droidar/src/actions/ActionUseCameraAngles2.java index 7cdd570..05cdeb1 100644 --- a/droidar/src/actions/ActionUseCameraAngles2.java +++ b/droidar/src/actions/ActionUseCameraAngles2.java @@ -9,7 +9,7 @@ /** * Register it in the * {@link EventManager#addOnOrientationChangedAction(OrientationChangedListener)} - * and you will get updates whenever the angles change + * and you will get updates whenever the angles change. * * @author Simon Heinen * @@ -17,29 +17,39 @@ public abstract class ActionUseCameraAngles2 implements OrientationChangedListener { - private float[] mag; - private float[] accel; - private boolean sensorRead; - float[] R = new float[16]; - float[] outR = new float[16]; - float[] I = new float[16]; - private int screenRotation; + private static final int MATRIX_SIZE = 16; + private static final int CIRCLE = 360; + private static final int HALF_CIRCLE = CIRCLE / 2; + private static final int MIN_MATRIX_SIZE = 3; + private static final int FOURTH_OF_CIRCLE_DEG = 90; + + private float[] mMag; + private float[] mAccel; + private boolean mSensorRead; + private float[] mR = new float[MATRIX_SIZE]; + private float[] mOutR = new float[MATRIX_SIZE]; + private float[] mI = new float[MATRIX_SIZE]; + private int mScreenRotation; + /** + * Constructor. + * + */ public ActionUseCameraAngles2() { - screenRotation = ArSetup.getScreenOrientation(); + mScreenRotation = ArSetup.getScreenOrientation(); } @Override public boolean onMagnetChanged(float[] values) { - mag = values; - sensorRead = true; + mMag = values; + mSensorRead = true; calcMatrix(); return true; } @Override public boolean onAccelChanged(float[] values) { - accel = values; + mAccel = values; calcMatrix(); return true; } @@ -51,10 +61,10 @@ public boolean onOrientationChanged(float[] values) { } private void calcMatrix() { - if (mag != null && accel != null && sensorRead) { - sensorRead = false; - SensorManager.getRotationMatrix(R, I, accel, mag); - onRotationMatrixUpdated(R); + if (mMag != null && mAccel != null && mSensorRead) { + mSensorRead = false; + SensorManager.getRotationMatrix(mR, mI, mAccel, mMag); + onRotationMatrixUpdated(mR); } } @@ -69,25 +79,25 @@ public float[] getRotateMatrixAccordingToDeviceOrientation() { * /libgdx/source/browse/trunk/backends/gdx -backend-android/src/com * /badlogic/gdx/backends/android/AndroidInput.java */ - SensorManager.remapCoordinateSystem(R, SensorManager.AXIS_X, - SensorManager.AXIS_Y, outR); + SensorManager.remapCoordinateSystem(mR, SensorManager.AXIS_X, + SensorManager.AXIS_Y, mOutR); } else { /* * TODO do this for all 4 rotation possibilities! */ - if (screenRotation == Surface.ROTATION_90) { + if (mScreenRotation == Surface.ROTATION_90) { // then rotate it according to the screen rotation: - SensorManager.remapCoordinateSystem(R, SensorManager.AXIS_Y, - SensorManager.AXIS_MINUS_X, outR); + SensorManager.remapCoordinateSystem(mR, SensorManager.AXIS_Y, + SensorManager.AXIS_MINUS_X, mOutR); } else { - outR = R; + mOutR = mR; } } - return outR; + return mOutR; } - private final float rad2deg = 180 / (float) Math.PI; - private float[] o = new float[3]; + private final float mRad2deg = HALF_CIRCLE / (float) Math.PI; + private float[] mO = new float[MIN_MATRIX_SIZE]; /** * you can also use @@ -98,14 +108,15 @@ public float[] getRotateMatrixAccordingToDeviceOrientation() { * glCamera.setRotationMatrix(getRotateMatrixAccordingToDeviceOrientation(), * 0); * - * @param updatedRotationMatrix + * @param updatedRotationMatrix - float[] contains the updated matrix */ public void onRotationMatrixUpdated(float[] updatedRotationMatrix) { - SensorManager.getOrientation(updatedRotationMatrix, o); - float magnet = o[0] * rad2deg + 90; - if (magnet < 0) - magnet += 360; - onAnglesUpdated(o[1] * rad2deg, -o[2] * rad2deg, magnet); + SensorManager.getOrientation(updatedRotationMatrix, mO); + float magnet = mO[0] * mRad2deg + FOURTH_OF_CIRCLE_DEG; + if (magnet < 0) { + magnet += CIRCLE; + } + onAnglesUpdated(mO[1] * mRad2deg, -mO[2] * mRad2deg, magnet); } /** diff --git a/droidar/src/actions/ActionWASDMovement.java b/droidar/src/actions/ActionWASDMovement.java index 35301c3..cdec3ed 100644 --- a/droidar/src/actions/ActionWASDMovement.java +++ b/droidar/src/actions/ActionWASDMovement.java @@ -18,18 +18,22 @@ * */ public class ActionWASDMovement extends Action { + + private static final int HALF_CIRCLE_DEG = 180; + private static final int RAY_DIRECTION_SIZE = 4; - protected GLCamera myTargetCamera; - private final float xReduction; - private final float yReduction; - private Vec accelerationVec = new Vec(); - private float myMaxSpeed; + private GLCamera mTargetCamera; + private final float mXReduction; + private final float mYReduction; + private Vec mAccelerationVec = new Vec(); + private float mMaxSpeed; - private float yFactor; - private float xFactor; + private float mYFactor; + private float mXFactor; /** - * @param camera + * Constructor. + * @param camera - {@link gl.GLCamera} * @param xReduction * redutcion in x (W or S key) direction. Higher means slower. * Try 25f @@ -41,42 +45,42 @@ public class ActionWASDMovement extends Action { */ public ActionWASDMovement(GLCamera camera, float xReduction, float yReduction, float maxSpeed) { - myTargetCamera = camera; - this.xReduction = xReduction; - this.yReduction = yReduction; - myMaxSpeed = maxSpeed; + mTargetCamera = camera; + mXReduction = xReduction; + mYReduction = yReduction; + mMaxSpeed = maxSpeed; } @Override public boolean onTouchMove(MotionEvent e1, MotionEvent e2, float screenDeltaX, float screenDeltaY) { - yFactor = (-e2.getX() + e1.getX()) / yReduction; - xFactor = (e1.getY() - e2.getY()) / xReduction; + mYFactor = (-e2.getX() + e1.getX()) / mYReduction; + mXFactor = (e1.getY() - e2.getY()) / mXReduction; return true; } @Override public boolean onReleaseTouchMove() { - xFactor = 0; - yFactor = 0; + mXFactor = 0; + mYFactor = 0; return true; } @Override public boolean update(float timeDelta, Updateable parent) { - if (xFactor != 0 || yFactor != 0) { + if (mXFactor != 0 || mYFactor != 0) { - float[] rayDir = new float[4]; - myTargetCamera.getCameraViewDirectionRay(null, rayDir); + float[] rayDir = new float[RAY_DIRECTION_SIZE]; + mTargetCamera.getCameraViewDirectionRay(null, rayDir); - accelerationVec.x = rayDir[0]; - accelerationVec.y = rayDir[1]; - accelerationVec.z = rayDir[2]; + mAccelerationVec.x = rayDir[0]; + mAccelerationVec.y = rayDir[1]; + mAccelerationVec.z = rayDir[2]; - accelerationVec.normalize(); - accelerationVec.mult(xFactor); + mAccelerationVec.normalize(); + mAccelerationVec.mult(mXFactor); /* * now the yFactor which has to be added orthogonal to the x * direction (with z value 0) @@ -84,19 +88,20 @@ public boolean update(float timeDelta, Updateable parent) { // Vec normalizedOrtoh = // Vec.getOrthogonalHorizontal(accelerationVec); - Vec yDir = new Vec(yFactor, 0, 0); - yDir.rotateAroundZAxis(180 - myTargetCamera + Vec yDir = new Vec(mYFactor, 0, 0); + yDir.rotateAroundZAxis(HALF_CIRCLE_DEG - mTargetCamera .getCameraAnglesInDegree()[0]); // System.out.println("yDir="+yDir); - accelerationVec.add(yDir); + mAccelerationVec.add(yDir); - if (accelerationVec.getLength() > myMaxSpeed) - accelerationVec.setLength(myMaxSpeed); + if (mAccelerationVec.getLength() > mMaxSpeed) { + mAccelerationVec.setLength(mMaxSpeed); + } - myTargetCamera.changeNewPosition(accelerationVec.x * timeDelta, - accelerationVec.y * timeDelta, accelerationVec.z + mTargetCamera.changeNewPosition(mAccelerationVec.x * timeDelta, + mAccelerationVec.y * timeDelta, mAccelerationVec.z * timeDelta); } diff --git a/droidar/src/actions/ActionWaitForAccuracy2.java b/droidar/src/actions/ActionWaitForAccuracy2.java deleted file mode 100644 index 7cc924f..0000000 --- a/droidar/src/actions/ActionWaitForAccuracy2.java +++ /dev/null @@ -1,158 +0,0 @@ -package actions; - -import geo.GeoUtils; -import system.EventManager; -import android.app.Activity; -import android.app.Dialog; -import android.location.Location; -import android.util.Log; -import android.view.View; -import android.view.View.OnClickListener; -import android.widget.Button; - -public abstract class ActionWaitForAccuracy2 extends Action { - private static final String TEXT_DIALOG_TITLE = "Do you want to cancel the accuracy detection?"; - private static final String TEXT_SKIP_ACCURACY_DETECTION = "Skip accuracy detection (not recomended!)"; - - // 1 minutes in ms: - private static final long MAX_TIME_SINCE_LAST_UPDATE_IN_MS = 1000 * 60 * 1; - - private static final String LOG_TAG = "ActionWaitForAccuracy"; - - private float myCurrentAccuracy; - private float myMinAccuracy; - private boolean firstTimeReached = false; - - private int myMaxPosUpdateCount; - - private int stepCounter = 0; - - private Activity myActivity; - - /** - * @param context - * @param minAccuracy - * should be >= 25m - * @param maxPosUpdateCount - * The max number of update events before the position should be - * accurate enough (something around 6) - */ - public ActionWaitForAccuracy2(Activity context, float minAccuracy, - int maxPosUpdateCount) { - myActivity = context; - myMinAccuracy = minAccuracy; - myMaxPosUpdateCount = maxPosUpdateCount; - analyseInitLocation(GeoUtils.getCurrentLocation(context)); - } - - private void analyseInitLocation(Location l) { - if (l != null) { - myCurrentAccuracy = l.getAccuracy(); - long passedTime = System.currentTimeMillis() - l.getTime(); - Log.d(LOG_TAG, "Passed time since last location event=" - + (passedTime / 1000f / 10f) + " minutes"); - if (passedTime <= MAX_TIME_SINCE_LAST_UPDATE_IN_MS) - onLocationChanged(l); - } else { - GeoUtils.enableLocationProvidersIfNeeded(myActivity); - } - } - - @Override - public boolean onLocationChanged(Location l) { - Log.d(LOG_TAG, "Current signal accuracy=" + l.getAccuracy()); - Log.d(LOG_TAG, "Minimum needed accuracy=" + myMinAccuracy); - Log.d(LOG_TAG, "Current pos update count=" + stepCounter); - Log.d(LOG_TAG, "Max pos updates=" + myMaxPosUpdateCount); - stepCounter++; - myCurrentAccuracy = l.getAccuracy(); - updateUI(myActivity, (int) (myMinAccuracy / myCurrentAccuracy * 100), - stepCounter); - if ((myCurrentAccuracy != 0 && myCurrentAccuracy <= myMinAccuracy) - || (stepCounter >= myMaxPosUpdateCount)) { - callFirstTimeAccReachedIfNotYetCalled(l); - } - return true; - } - - /** - * This method is for display purpose only. If the UI does not have to react - * on updates do not do anything here - * - * @param activity - * @param neededAccuracyInPercent - * @param numberOfMeasurments - */ - public abstract void updateUI(Activity activity, - int neededAccuracyInPercent, int numberOfMeasurments); - - private void callFirstTimeAccReachedIfNotYetCalled(Location location) { - if (!firstTimeReached) { - firstTimeReached = true; - Log.d(LOG_TAG, "Required accuracy was reached!"); - minAccuracyReachedFirstTime(location, this); - } else - Log.w(LOG_TAG, "callFirstTimeAccReachedIfNotYetCalled was " - + "called more then one time! This action should " - + "be removed once the accuracy was reached!"); - } - - /** - * @param location - * The {@link Location} object that was accurate enough - * @param a - * the {@link ActionWaitForAccuracy2} object which can be used to - * remove it from the {@link EventListenerGroup} it was contained - * in (e.g. the {@link EventManager#onLocationChangedList}) - */ - public abstract void minAccuracyReachedFirstTime(Location location, - ActionWaitForAccuracy2 a); - - private void waitSomeSecondsAndThenRegisterForGPSEvents() { - - new Thread(new Runnable() { - - @Override - public void run() { - try { - Thread.sleep(5000); - } catch (InterruptedException e) { - } - EventManager.getInstance().registerLocationUpdates(); - onGPSActivatedEvent(); - } - }).start(); - - } - - /** - * Override this if you need additional custom behavior as soon as the user - * activates GPS - */ - public void onGPSActivatedEvent() { - // on default do nothing - } - - /** - * call this if the user should be able to skip this procedure - */ - public void showSkipPositionDetectionDialog() { - final Dialog dialog = new Dialog(myActivity); - Button b = new Button(myActivity); - b.setText(TEXT_SKIP_ACCURACY_DETECTION); - b.setOnClickListener(new OnClickListener() { - - @Override - public void onClick(View v) { - callFirstTimeAccReachedIfNotYetCalled(GeoUtils - .getCurrentLocation(myActivity)); - dialog.dismiss(); - } - }); - dialog.setContentView(b); - dialog.setTitle(TEXT_DIALOG_TITLE); - dialog.setCanceledOnTouchOutside(true); - dialog.show(); - } - -} diff --git a/droidar/src/actions/ActionWithSensorProcessing.java b/droidar/src/actions/ActionWithSensorProcessing.java index c3b0ab2..19cf5b2 100644 --- a/droidar/src/actions/ActionWithSensorProcessing.java +++ b/droidar/src/actions/ActionWithSensorProcessing.java @@ -10,167 +10,175 @@ import android.hardware.SensorManager; import android.view.MotionEvent; import android.view.Surface; - +/** + * Base action for those that need sensor data to perform specific tasks. + * TODO: Refactor this class. + */ public abstract class ActionWithSensorProcessing extends Action { private static final String LOG_TAG = "ActionWithSensorProcessing"; - - private final GLCamRotationController myTargetCamera; - - public Algo magnetAlgo; - public Algo accelAlgo; - public Algo orientAlgo; - public Algo accelBufferAlgo; - public Algo magnetBufferAlgo; - public Algo orientationBufferAlgo; - - private float[] myAccelValues = new float[3]; - private float[] myMagnetValues = new float[3]; - private float[] myOrientValues = new float[3]; - - private boolean accelChanged; - private float[] myNewAccelValues; - private boolean magnetoChanged; - private float[] myNewMagnetValues; - private boolean orientationDataChanged; - private float[] myNewOrientValues; - - private final float[] unrotatedMatrix = Calculus.createIdentityMatrix(); - private float[] rotationMatrix = Calculus.createIdentityMatrix(); - - private final int screenRotation; - + private static final int SENSOR_ARRAY_SIZE = 3; + private final GLCamRotationController mTargetCamera; + + private Algo mMagnetAlgo; + private Algo mAccelAlgo; + private Algo mOrientAlgo; + private Algo mAccelBufferAlgo; + private Algo mMagnetBufferAlgo; + private Algo mOrientationBufferAlgo; + + private float[] mAccelValues = new float[SENSOR_ARRAY_SIZE]; + private float[] mMagnetValues = new float[SENSOR_ARRAY_SIZE]; + private float[] mOrientValues = new float[SENSOR_ARRAY_SIZE]; + + private boolean mAccelChanged; + private float[] mNewAccelValues; + private boolean mMagnetoChanged; + private float[] mNewMagnetValues; + private boolean mOrientationDataChanged; + private float[] mNewOrientValues; + + private final float[] mUnrotatedMatrix = Calculus.createIdentityMatrix(); + private float[] mRotationMatrix = Calculus.createIdentityMatrix(); + + private final int mScreenRotation; + + /** + * Constructor. + * @param targetCamera - {@link gl.GLCamRotationController} + */ public ActionWithSensorProcessing(GLCamRotationController targetCamera) { - myTargetCamera = targetCamera; + mTargetCamera = targetCamera; initAlgos(); - screenRotation = ArSetup.getScreenOrientation(); + mScreenRotation = ArSetup.getScreenOrientation(); } - protected abstract void initAlgos(); - @Override public boolean onTouchMove(MotionEvent e1, MotionEvent e2, float screenDeltaX, float screenDeltaY) { - myTargetCamera.changeZAngleBuffered(screenDeltaY); + mTargetCamera.changeZAngleBuffered(screenDeltaY); return true; } @Override public synchronized boolean onAccelChanged(float[] values) { - - if (accelAlgo != null) { - myNewAccelValues = accelAlgo.execute(values); + if (mAccelAlgo != null) { + mNewAccelValues = mAccelAlgo.execute(values); } else { - myNewAccelValues = values; + mNewAccelValues = values; } - accelChanged = true; + mAccelChanged = true; return true; - } @Override public synchronized boolean onMagnetChanged(float[] values) { - if (magnetAlgo != null) { - myNewMagnetValues = magnetAlgo.execute(values); + if (mMagnetAlgo != null) { + mNewMagnetValues = mMagnetAlgo.execute(values); } else { - myNewMagnetValues = values; + mNewMagnetValues = values; } - magnetoChanged = true; + mMagnetoChanged = true; return true; - } @Override public synchronized boolean onOrientationChanged(float[] values) { - if (orientAlgo != null) { - myNewOrientValues = orientAlgo.execute(values); + if (mOrientAlgo != null) { + mNewOrientValues = mOrientAlgo.execute(values); } else { - myNewOrientValues = values; + mNewOrientValues = values; } - orientationDataChanged = true; + mOrientationDataChanged = true; return true; - } @Override public synchronized boolean update(float timeDelta, Updateable parent) { - if (magnetoChanged || accelChanged || orientationDataChanged) { - if (magnetoChanged || accelChanged) { - // if accel or magnet changed: - if (accelChanged) { - accelChanged = false; - if (accelBufferAlgo != null) { - accelBufferAlgo.execute(myAccelValues, - myNewAccelValues, timeDelta); + if (mMagnetoChanged || mAccelChanged || mOrientationDataChanged) { + if (mMagnetoChanged || mAccelChanged) { + if (mAccelChanged) { + mAccelChanged = false; + if (mAccelBufferAlgo != null) { + mAccelBufferAlgo.execute(mAccelValues, + mNewAccelValues, timeDelta); } else { - myAccelValues = myNewAccelValues; + mAccelValues = mNewAccelValues; } } - if (magnetoChanged) { - magnetoChanged = false; - if (magnetBufferAlgo != null) { - magnetBufferAlgo.execute(myMagnetValues, - myNewMagnetValues, timeDelta); + if (mMagnetoChanged) { + mMagnetoChanged = false; + if (mMagnetBufferAlgo != null) { + mMagnetBufferAlgo.execute(mMagnetValues, + mNewMagnetValues, timeDelta); } else { - myMagnetValues = myNewMagnetValues; + mMagnetValues = mNewMagnetValues; } } - // first calc the unrotated matrix: - SensorManager.getRotationMatrix(unrotatedMatrix, null, - myAccelValues, myMagnetValues); - } else if (orientationDataChanged) { - orientationDataChanged = false; - if (orientationBufferAlgo != null) { - orientationBufferAlgo.execute(myOrientValues, - myNewOrientValues, timeDelta); + SensorManager.getRotationMatrix(mUnrotatedMatrix, null, + mAccelValues, mMagnetValues); + } else if (mOrientationDataChanged) { + mOrientationDataChanged = false; + if (mOrientationBufferAlgo != null) { + mOrientationBufferAlgo.execute(mOrientValues, + mNewOrientValues, timeDelta); } else { - myOrientValues = myNewOrientValues; + mOrientValues = mNewOrientValues; } - GLUtilityClass.getRotationMatrixFromVector(unrotatedMatrix, - myOrientValues); + GLUtilityClass.getRotationMatrixFromVector(mUnrotatedMatrix, + mOrientValues); } - /* - * Then in addition the values have to be remapped of the device is - * used in landscape mode or if it is a tablet etc - */ - if (EventManager.isTabletDevice) { - /* - * change accel sensor data according to - * http://code.google.com/p - * /libgdx/source/browse/trunk/backends/gdx - * -backend-android/src/com - * /badlogic/gdx/backends/android/AndroidInput.java - */ - SensorManager.remapCoordinateSystem(unrotatedMatrix, + SensorManager.remapCoordinateSystem(mUnrotatedMatrix, SensorManager.AXIS_X, SensorManager.AXIS_Y, - rotationMatrix); + mRotationMatrix); } else { - /* - * TODO do this for all 4 rotation possibilities! - */ - if (screenRotation == Surface.ROTATION_90) { - // then rotate it according to the screen rotation: - SensorManager.remapCoordinateSystem(unrotatedMatrix, + if (mScreenRotation == Surface.ROTATION_90) { + SensorManager.remapCoordinateSystem(mUnrotatedMatrix, SensorManager.AXIS_Y, SensorManager.AXIS_MINUS_X, - rotationMatrix); + mRotationMatrix); } else { - /* - * else its in portrait mode so no remapping needed - */ - rotationMatrix = unrotatedMatrix; + mRotationMatrix = mUnrotatedMatrix; } } - myTargetCamera.setRotationMatrix(rotationMatrix, 0); + mTargetCamera.setRotationMatrix(mRotationMatrix, 0); } return true; } @Override public boolean onReleaseTouchMove() { - myTargetCamera.resetBufferedAngle(); + mTargetCamera.resetBufferedAngle(); return true; } + + + private void initAlgos() { + mMagnetAlgo = createMagnetAlgo(); + mAccelAlgo = createAccelAlgo(); + mOrientAlgo = createOrientAlgo(); + mAccelBufferAlgo = createAccelBufferAlgo(); + mMagnetBufferAlgo = createMagnetBufferAlgo(); + mOrientationBufferAlgo = createOrientBufferAlgo(); + }; + + + protected abstract Algo createMagnetAlgo(); + + protected abstract Algo createAccelAlgo(); + + protected abstract Algo createOrientAlgo(); + + protected abstract Algo createMagnetBufferAlgo(); + + protected abstract Algo createAccelBufferAlgo(); + + protected abstract Algo createOrientBufferAlgo(); + + + + + } \ No newline at end of file diff --git a/droidar/src/de/rwth/setups/PlaceObjectsSetup.java b/droidar/src/de/rwth/setups/PlaceObjectsSetup.java index b4a2f6a..8a53e49 100644 --- a/droidar/src/de/rwth/setups/PlaceObjectsSetup.java +++ b/droidar/src/de/rwth/setups/PlaceObjectsSetup.java @@ -20,11 +20,10 @@ import actions.ActionBufferedCameraAR; import actions.ActionCalcRelativePos; import actions.ActionMoveCameraBuffered; -import actions.ActionPlaceObject; import actions.ActionRotateCameraBuffered; import android.app.Activity; + import commands.Command; -import entry.ISetupEntry; public class PlaceObjectsSetup extends ArSetup { private GLCamera camera; @@ -63,13 +62,13 @@ public void addActionsToEvents(EventManager eventManager, CustomGLSurfaceView arView, SystemUpdater updater) { arView.addOnTouchMoveAction(new ActionBufferedCameraAR(camera)); Action rot1 = new ActionRotateCameraBuffered(camera); - Action rot2 = new ActionPlaceObject(camera, placeObjectWrapper, 50); + //Action rot2 = new ActionPlaceObject(camera, placeObjectWrapper, 50); updater.addObjectToUpdateCycle(rot1); - updater.addObjectToUpdateCycle(rot2); + //updater.addObjectToUpdateCycle(rot2); eventManager.addOnOrientationChangedAction(rot1); - eventManager.addOnOrientationChangedAction(rot2); + //eventManager.addOnOrientationChangedAction(rot2); eventManager.addOnTrackballAction(new ActionMoveCameraBuffered(camera, 5, 25)); eventManager.addOnLocationChangedAction(new ActionCalcRelativePos( diff --git a/droidar/src/de/rwth/setups/SensorTestSetup.java b/droidar/src/de/rwth/setups/SensorTestSetup.java index eba215c..a6e7c5d 100644 --- a/droidar/src/de/rwth/setups/SensorTestSetup.java +++ b/droidar/src/de/rwth/setups/SensorTestSetup.java @@ -20,16 +20,10 @@ import actions.ActionBufferedCameraAR; import actions.ActionMoveCameraBuffered; import actions.ActionRotateCameraBuffered; -import actions.ActionRotateCameraBuffered3; -import actions.ActionRotateCameraBuffered4; -import actions.ActionRotateCameraBufferedDebug; -import actions.ActionRotateCameraBufferedDirect; -import actions.ActionRotateCameraUnbuffered; -import actions.ActionRotateCameraUnbuffered2; import actions.ActionUseCameraAngles2; import android.app.Activity; + import commands.Command; -import entry.ISetupEntry; public class SensorTestSetup extends ArSetup { private GLCamera camera; @@ -55,12 +49,12 @@ public void initFieldsIfNecessary() { camera = new GLCamera(); rotActionB1 = new ActionRotateCameraBuffered(camera); - rotActionB2 = new ActionRotateCameraBufferedDirect(camera); - rotActionB3 = new ActionRotateCameraBuffered3(camera); - rotActionB4 = new ActionRotateCameraBuffered4(camera); - new ActionRotateCameraBufferedDebug(camera); - rotActionUnB = new ActionRotateCameraUnbuffered(camera); - rotActionUnB2 = new ActionRotateCameraUnbuffered2(camera); +// rotActionB2 = new ActionRotateCameraBufferedDirect(camera); +// rotActionB3 = new ActionRotateCameraBuffered3(camera); +// rotActionB4 = new ActionRotateCameraBuffered4(camera); +// new ActionRotateCameraBufferedDebug(camera); +// rotActionUnB = new ActionRotateCameraUnbuffered(camera); +// rotActionUnB2 = new ActionRotateCameraUnbuffered2(camera); } diff --git a/droidar/src/gui/RadarView.java b/droidar/src/gui/RadarView.java index abeb3d5..9fb962b 100644 --- a/droidar/src/gui/RadarView.java +++ b/droidar/src/gui/RadarView.java @@ -45,6 +45,7 @@ public class RadarView extends SimpleCustomView implements Updateable { private UpdateTimer myTimer; private float myUpdateSpeed = DEFAULT_UPDATE_SPEED; private double myTouchScaleFactor = 5; + private volatile float mCameraAngleInDeg = -1; private String debug; @@ -186,8 +187,9 @@ protected void onDraw(Canvas canvas) { */ drawBackGround(canvas); - if (items != null) + if (items != null) { drawItems(canvas); + } paint.setColor(Color.BLACK); drawCircle(canvas, myHalfSize, myHalfSize, myHalfSize / 30, paint); @@ -202,6 +204,10 @@ protected void onDraw(Canvas canvas) { paint.setColor(Color.RED); canvas.drawText(debug, 0, myHalfSize, paint); } + + if (mCameraAngleInDeg > 0) { + setRotation(mCameraAngleInDeg); + } } @Override @@ -331,7 +337,9 @@ private Bitmap createBackground(int size, int halfSize) { @Override public boolean update(float timeDelta, Updateable parent) { if (myTimer.update(timeDelta, parent)) { - setRotation(myCamera.getCameraAnglesInDegree()[0]); + //setRotation(myCamera.getCameraAnglesInDegree()[0]); + mCameraAngleInDeg = myCamera.getCameraAnglesInDegree()[0]; + postInvalidate(); } /* * TODO if view was removed from parent it can return false here! diff --git a/droidar/src/logger/ARLogger.java b/droidar/src/logger/ARLogger.java index 1aeb144..f3915d7 100644 --- a/droidar/src/logger/ARLogger.java +++ b/droidar/src/logger/ARLogger.java @@ -14,6 +14,7 @@ public final class ARLogger { * Used to determine message what type of message is begin received. */ private static enum MessageType { + VERBOSE, INFO, DEBUG, WARNING, @@ -110,6 +111,16 @@ public static void warn(String id, String message) { logMessage(MessageType.WARNING, affixId(id, message), null); } + /** + * Create a verbose message with an internal location. + * @param id - location or class name + * @param message - message displayed + */ + public static void verbose(String id, String message) { + logMessage(MessageType.WARNING, affixId(id, message), null); + } + + private static String affixId(String id, String message) { if (id.equals("")) { return message; @@ -120,6 +131,9 @@ private static String affixId(String id, String message) { private static void logMessage(MessageType type, String message, Exception exception) { switch(type) { + case VERBOSE: + Log.v(LOG_TAG, message); + break; case INFO: Log.i(LOG_TAG, message); break; @@ -138,5 +152,4 @@ private static void logMessage(MessageType type, String message, Exception excep break; } } - } diff --git a/droidar/src/preview/AugmentedView.java b/droidar/src/preview/AugmentedView.java index 390587e..07ae397 100644 --- a/droidar/src/preview/AugmentedView.java +++ b/droidar/src/preview/AugmentedView.java @@ -3,6 +3,7 @@ import gl.CustomGLSurfaceView; import gl.GL1Renderer; import android.content.Context; +import android.view.SurfaceView; import android.view.View; import android.widget.FrameLayout; import de.rwth.R; @@ -43,11 +44,11 @@ private void initialize(Context context) { private void addOverlays() { mGLSurfaceView.setZOrderMediaOverlay(true); - addView(mGuiView); addView(mCameraView, new LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); addView(mGLSurfaceView, new LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); + addView(mGuiView); } /** diff --git a/droidar/src/setup/ArSetup.java b/droidar/src/setup/ArSetup.java index 4e1898a..c359bdf 100644 --- a/droidar/src/setup/ArSetup.java +++ b/droidar/src/setup/ArSetup.java @@ -20,12 +20,10 @@ import android.view.Window; import android.view.WindowManager; import android.widget.FrameLayout; - import commands.Command; import commands.CommandGroup; import commands.system.CommandDeviceVibrate; import commands.undoable.CommandProcessor; - import entry.ArType; import entry.ISetupEntry; import gl.GLFactory; @@ -231,7 +229,7 @@ private static void loadDeviceDependentSettings(Activity activity) { .getSystemService(Activity.WINDOW_SERVICE)) .getDefaultDisplay(); mScreenOrientation = (Integer) display.getClass() - .getMethod("getRotation", null).invoke(display, null); + .getMethod("getRotation", new Class[]{}).invoke(display, new Object[]{}); } catch (Exception e) { e.printStackTrace(); } @@ -356,6 +354,7 @@ public boolean onKeyDown(Activity activity, int keyCode, KeyEvent event) { * Retrieve the screen width based on orientation. * @return - float */ + @SuppressWarnings("deprecation") public float getScreenWidth() { if (getScreenOrientation() == Surface.ROTATION_90 || getScreenOrientation() == Surface.ROTATION_270) { @@ -371,6 +370,7 @@ public float getScreenWidth() { * Retrieve the screen height based on orientation. * @return - float */ + @SuppressWarnings("deprecation") public float getScreenHeigth() { if (getScreenOrientation() == Surface.ROTATION_90 || getScreenOrientation() == Surface.ROTATION_270) { @@ -384,6 +384,7 @@ public float getScreenHeigth() { @Override public void onCreate() { + ARLogger.debug(LOG_TAG, "onCreate"); initAllSingletons(); mWorldUpdater = new SystemUpdater(); } From e1bb9b33af15c03df79cc0be7430336d44606dc3 Mon Sep 17 00:00:00 2001 From: rvieras Date: Thu, 5 Dec 2013 15:22:13 -0500 Subject: [PATCH 06/12] Changes to the package actions.algos. --- droidar/src/actions/algos/Algo.java | 13 ++++ .../actions/algos/AlgoCubicRootBuffer.java | 27 ------- droidar/src/actions/algos/BufferAlgo1.java | 38 ++++++---- droidar/src/actions/algos/BufferAlgo2.java | 11 ++- droidar/src/actions/algos/BufferAlgo3.java | 38 ---------- .../algos/DoubleMeanSquareRootBuffer.java | 63 ---------------- droidar/src/actions/algos/SensorAlgo1.java | 24 +++--- droidar/src/actions/algos/SmoothingAlgo.java | 73 ++++++++----------- .../src/actions/algos/SquareRootBuffer.java | 47 ------------ 9 files changed, 86 insertions(+), 248 deletions(-) delete mode 100644 droidar/src/actions/algos/AlgoCubicRootBuffer.java delete mode 100644 droidar/src/actions/algos/BufferAlgo3.java delete mode 100644 droidar/src/actions/algos/DoubleMeanSquareRootBuffer.java delete mode 100644 droidar/src/actions/algos/SquareRootBuffer.java diff --git a/droidar/src/actions/algos/Algo.java b/droidar/src/actions/algos/Algo.java index 3c93e6b..cba5102 100644 --- a/droidar/src/actions/algos/Algo.java +++ b/droidar/src/actions/algos/Algo.java @@ -2,13 +2,26 @@ import util.Log; +/** + * Sensor filter/buffer algo base class. + */ public abstract class Algo { + /** + * @param values - new float[] that contains the new values from the sensors + * @return - new float[] that contains the buffered/filtered values + */ public float[] execute(float[] values) { Log.e("algo class error", "execute(one param) not catched"); return null; } + /** + * @param targetValues - new values will be placed in this array + * @param newValues - new float[] data + * @param bufferSize - buffer/filter constant + * @return - true if boo + */ public boolean execute(float[] targetValues, float[] newValues, float bufferSize) { Log.e("algo class error", "execute(3 params) not catched"); diff --git a/droidar/src/actions/algos/AlgoCubicRootBuffer.java b/droidar/src/actions/algos/AlgoCubicRootBuffer.java deleted file mode 100644 index a3bd3fc..0000000 --- a/droidar/src/actions/algos/AlgoCubicRootBuffer.java +++ /dev/null @@ -1,27 +0,0 @@ -package actions.algos; - -public class AlgoCubicRootBuffer extends Algo { - - /** - * uses cubic root but doesnt work fine.. - * - * @param target - * @param values - * @param bufferSize - */ - @Override - public boolean execute(float[] target, float[] values, float bufferSize) { - - target[0] = (float) (Math.cbrt((target[0] * target[0] * target[0] - * bufferSize + values[0] * values[0] * values[0]) - / (bufferSize + 1))); - target[1] = (float) (Math.cbrt((target[1] * target[1] * target[1] - * bufferSize + values[1] * values[1] * values[1]) - / (bufferSize + 1))); - target[2] = (float) (Math.cbrt((target[2] * target[2] * target[2] - * bufferSize + values[2] * values[2] * values[2]) - / (bufferSize + 1))); - return true; - } - -} diff --git a/droidar/src/actions/algos/BufferAlgo1.java b/droidar/src/actions/algos/BufferAlgo1.java index ab1d4ae..1d56dfe 100644 --- a/droidar/src/actions/algos/BufferAlgo1.java +++ b/droidar/src/actions/algos/BufferAlgo1.java @@ -1,7 +1,7 @@ package actions.algos; /** - * implementation of the function
+ * implementation of the function.
* *
  *       /              0  		for       |x| < a   
@@ -25,16 +25,20 @@
  */
 public class BufferAlgo1 extends Algo {
 
-	private final float a;
-	private final float b;
-	private final float m;
-	private final float n;
+	private final float mA;
+	private final float mB;
+	private final float mM;
+	private final float mN;
 
+	/**
+	 * @param a - upper bound buffer
+	 * @param b - lower bound buffer
+	 */
 	public BufferAlgo1(float a, float b) {
-		this.a = a;
-		this.b = b;
-		m = 1f / (b - a);
-		n = a / (a - b);
+		this.mA = a;
+		this.mB = b;
+		mM = 1f / (b - a);
+		mN = a / (a - b);
 	}
 
 	@Override
@@ -53,17 +57,21 @@ public boolean execute(float[] target, float[] values, float bufferSize) {
 	private float morph(float v, float newV) {
 		float x = newV - v;
 		if (x >= 0) {
-			if (x < a)
+			if (x < mA) {
 				return v; // v+0*x
-			if (b <= x)
+			}
+			if (mB <= x) {
 				return newV; // v+1*x
-			return v + x * m + n;
+			}
+			return v + x * mM + mN;
 		} else {
-			if (-x < a)
+			if (-x < mA) {
 				return v;
-			if (b <= -x)
+			}
+			if (mB <= -x) {
 				return newV;
-			return v + x * m + n;
+			}
+			return v + x * mM + mN;
 		}
 	}
 
diff --git a/droidar/src/actions/algos/BufferAlgo2.java b/droidar/src/actions/algos/BufferAlgo2.java
index 49a277e..f343f7a 100644
--- a/droidar/src/actions/algos/BufferAlgo2.java
+++ b/droidar/src/actions/algos/BufferAlgo2.java
@@ -1,15 +1,18 @@
 package actions.algos;
-
+/**
+ * Another form of the {@link actions.algos.BufferAlgo1} class.
+ *
+ */
 public class BufferAlgo2 extends Algo {
 
-	private float myBuffer;
+	private float mBuffer;
 
 	/**
 	 * @param buffer
 	 *            has to be between 0 and 1 (try 0.2)
 	 */
 	public BufferAlgo2(float buffer) {
-		myBuffer = buffer;
+		mBuffer = buffer;
 	}
 
 	@Override
@@ -21,7 +24,7 @@ public boolean execute(float[] target, float[] values, float bufferSize) {
 	}
 
 	private float morph(float t, float v) {
-		return t + (v - t) * myBuffer;
+		return t + (v - t) * mBuffer;
 	}
 
 }
diff --git a/droidar/src/actions/algos/BufferAlgo3.java b/droidar/src/actions/algos/BufferAlgo3.java
deleted file mode 100644
index bc2ea8f..0000000
--- a/droidar/src/actions/algos/BufferAlgo3.java
+++ /dev/null
@@ -1,38 +0,0 @@
-package actions.algos;
-
-public class BufferAlgo3 extends Algo {
-
-	private float myBuffer;
-	private float a;
-	private float b;
-
-	/**
-	 * @param buffer
-	 *            has to be between 0 and 1 (try 0.2)
-	 */
-	public BufferAlgo3(float buffer, float a, float b) {
-		myBuffer = buffer;
-		this.a = a;
-		this.b = b;
-	}
-
-	@Override
-	public boolean execute(float[] target, float[] values, float bufferSize) {
-		target[0] = morph(target[0], values[0]);
-		target[1] = morph(target[1], values[1]);
-		target[2] = morph(target[2], values[2]);
-		return true;
-	}
-
-	private float morph(float t, float v) {
-		float dist = v - t;
-		if (-a < dist && dist < a) {
-			return t;
-		}
-		if (dist < -b || b < dist) {
-			return v;
-		}
-		return t + (dist) * myBuffer;
-	}
-
-}
diff --git a/droidar/src/actions/algos/DoubleMeanSquareRootBuffer.java b/droidar/src/actions/algos/DoubleMeanSquareRootBuffer.java
deleted file mode 100644
index fcbde0e..0000000
--- a/droidar/src/actions/algos/DoubleMeanSquareRootBuffer.java
+++ /dev/null
@@ -1,63 +0,0 @@
-package actions.algos;
-
-import util.Log;
-
-public class DoubleMeanSquareRootBuffer {
-
-	private static final boolean DEBUG_SHOW_VALUES = false;
-	private float mybufferValue;
-	private int bufferCount;
-	private float minimumBufferValue;
-
-	/**
-	 * uses double mean square root method and sets lower and upper bounds to
-	 * buffer values
-	 * 
-	 * @param target
-	 * @param values
-	 * @param buffer
-	 */
-	private synchronized void rootMeanSquareBuffer4(float[] target,
-			float[] values, float buffer) {
-
-		/*
-		 * dont set amplification under 150
-		 */
-		final float amplification = 200;
-		mybufferValue = (bufferCount * mybufferValue + buffer)
-				/ (1 + bufferCount);
-		if (mybufferValue < minimumBufferValue) {
-			mybufferValue = minimumBufferValue;
-		}
-		if (DEBUG_SHOW_VALUES)
-			Log.d("Eventmanager", "buffer values: " + mybufferValue);
-
-		target[0] += amplification;
-		target[1] += amplification;
-		target[2] += amplification;
-		values[0] += amplification;
-		values[1] += amplification;
-		values[2] += amplification;
-
-		target[0] = (float) (Math.sqrt(Math.sqrt((target[0] * target[0]
-				* target[0] * target[0] * mybufferValue + values[0] * values[0]
-				* values[0] * values[0])
-				/ (1 + mybufferValue))));
-		target[1] = (float) (Math.sqrt(Math.sqrt((target[1] * target[1]
-				* target[1] * target[1] * mybufferValue + values[1] * values[1]
-				* values[1] * values[1])
-				/ (1 + mybufferValue))));
-		target[2] = (float) (Math.sqrt(Math.sqrt((target[2] * target[2]
-				* target[2] * target[2] * mybufferValue + values[2] * values[2]
-				* values[2] * values[2])
-				/ (1 + mybufferValue))));
-
-		target[0] -= amplification;
-		target[1] -= amplification;
-		target[2] -= amplification;
-		values[0] -= amplification;
-		values[1] -= amplification;
-		values[2] -= amplification;
-	}
-
-}
diff --git a/droidar/src/actions/algos/SensorAlgo1.java b/droidar/src/actions/algos/SensorAlgo1.java
index ad7d7b3..4da2f12 100644
--- a/droidar/src/actions/algos/SensorAlgo1.java
+++ b/droidar/src/actions/algos/SensorAlgo1.java
@@ -3,7 +3,7 @@
 /**
  * 
  * accel-sensor: has normal values from -11 to +11 and shake values from -19 to
- * 19
+ * 19.
  * 
  * magnet-sensor: has normal values from -60 to +60 and metal/magnet values from
  * -120 to 120
@@ -14,20 +14,24 @@
  * 
  */
 public class SensorAlgo1 extends Algo {
+	
+	private static final int ARRAY_SIZE = 3;
+	private float[] mOldV = new float[ARRAY_SIZE];
+	private float mBarrier;
 
-	private float[] oldV = new float[3];
-	private float myBarrier;
-
+	/**
+	 * @param barrier - barrier value.
+	 */
 	public SensorAlgo1(float barrier) {
-		myBarrier = barrier;
+		mBarrier = barrier;
 	}
 
 	@Override
 	public float[] execute(float[] v) {
-		oldV[0] = checkAndCalc(oldV[0], v[0]);
-		oldV[1] = checkAndCalc(oldV[1], v[1]);
-		oldV[2] = checkAndCalc(oldV[2], v[2]);
-		return oldV;
+		mOldV[0] = checkAndCalc(mOldV[0], v[0]);
+		mOldV[1] = checkAndCalc(mOldV[1], v[1]);
+		mOldV[2] = checkAndCalc(mOldV[2], v[2]);
+		return mOldV;
 	}
 
 	private float checkAndCalc(float oldV, float newV) {
@@ -36,7 +40,7 @@ private float checkAndCalc(float oldV, float newV) {
 		 * if the new value is very different from the old one, morph to the new
 		 * one
 		 */
-		if (delta < -myBarrier || myBarrier < delta) {
+		if (delta < -mBarrier || mBarrier < delta) {
 			return (oldV + newV) / 2;
 		}
 		/*
diff --git a/droidar/src/actions/algos/SmoothingAlgo.java b/droidar/src/actions/algos/SmoothingAlgo.java
index 4ba209a..0dbf17f 100644
--- a/droidar/src/actions/algos/SmoothingAlgo.java
+++ b/droidar/src/actions/algos/SmoothingAlgo.java
@@ -1,8 +1,11 @@
 package actions.algos;
 
-
+/**
+ * Perform different kinds of filtering based on the {@link actions.algos.SmoothingAlgo.FilterType}. 
+ */
 public class SmoothingAlgo extends Algo {
 	
+	private static final int SENSOR_ARRAY_SIZE = 3;
 	private static final float ALPHA = 0.04f;
 	private static final float BETA = 0.03f;
 	private FilterType mFilter = FilterType.NONE;
@@ -11,10 +14,13 @@ public class SmoothingAlgo extends Algo {
 	private float[] mPrevValues;
 	
 	//variables needed for highpass filter
-	private float[] mCurrentValues   = new float[3];
-	private float[] mLastValues      = new float[3];
-	private float[] mHighPassValues  = new float[3];
+	private float[] mCurrentValues   = new float[SENSOR_ARRAY_SIZE];
+	private float[] mLastValues      = new float[SENSOR_ARRAY_SIZE];
+	private float[] mHighPassValues  = new float[SENSOR_ARRAY_SIZE];
 	
+	/**
+	 * Different filters that can be used they {@link actions.algos.SmoothingAlgo}. 
+	 */
 	public enum FilterType {
 		NONE,
 		LOWPASS,
@@ -25,35 +31,39 @@ public enum FilterType {
 		KORMAN,
 	}
 	
-	public SmoothingAlgo(FilterType pFilter){
+	/**
+	 * Constructor.
+	 * @param pFilter - {@link actions.algos.SmoothingAlgo.FilterType}
+	 */
+	public SmoothingAlgo(FilterType pFilter) {
 		mFilter = pFilter;
 	}
 	
 	@Override
 	public float[] execute(float[] pNewData) {
 		float[] retValue = pNewData.clone();
-		switch(mFilter){
+		switch(mFilter) {
 		case NONE:
 			break;
 		case LOWPASS:
-			mPrevValues = lowPass(pNewData,mPrevValues);
+			mPrevValues = lowPass(pNewData, mPrevValues);
 			retValue = mPrevValues.clone();
 			break;
 		case LOWPASSV2:
-			mPrevValues = lowPass(pNewData,mPrevValues);
+			mPrevValues = lowPass(pNewData, mPrevValues);
 			retValue = mPrevValues.clone();
 			break;
 		case HIGHPASS:
 			mCurrentValues = pNewData.clone();
-			mHighPassValues = highPass(mCurrentValues,mLastValues,mHighPassValues);
+			mHighPassValues = highPass(mCurrentValues, mLastValues, mHighPassValues);
 			mLastValues = mCurrentValues.clone();
 			retValue = mHighPassValues;
 			break;
 		case BAND:
 			mCurrentValues = pNewData.clone();
-			mHighPassValues = highPass(mCurrentValues,mLastValues,mHighPassValues);
+			mHighPassValues = highPass(mCurrentValues, mLastValues, mHighPassValues);
 			mLastValues = mCurrentValues.clone();
-			mPrevValues = lowPass(mHighPassValues,mPrevValues);
+			mPrevValues = lowPass(mHighPassValues, mPrevValues);
 			retValue = mPrevValues.clone();
 			break;
 		case BANDV2:
@@ -68,15 +78,15 @@ public float[] execute(float[] pNewData) {
 	}
 	
 	
-	private float[] lowPass(float[] current, float[] last){
-		if(last == null){
+	private float[] lowPass(float[] current, float[] last) {
+		if (last == null) {
 			last = new float[current.length];
 		}
 		
-		for(int i = 0; i < current.length; i++){
-			if(mFilter == FilterType.LOWPASS|| mFilter == FilterType.BAND){
+		for (int i = 0; i < current.length; i++) {
+			if (mFilter == FilterType.LOWPASS || mFilter == FilterType.BAND) {
 				last[i] = last[i] * (1.0f - ALPHA) + current[i] * ALPHA;
-			}else{
+			} else {
 				//Assume LOWPASSV2
 				last[i] = current[i] * (1.0f - ALPHA) + last[i] * ALPHA;
 			}
@@ -85,41 +95,16 @@ private float[] lowPass(float[] current, float[] last){
 		return last;
 	}
 	
-	private float[] highPass(float[] current, float[] last, float[] filtered){
-		if(last == null || filtered == null ){
+	private float[] highPass(float[] current, float[] last, float[] filtered) {
+		if (last == null || filtered == null) {
 			last = new float[current.length];
 			filtered = new float[current.length];
 		}
 		
-		for(int i = 0; i < current.length; i++){
+		for (int i = 0; i < current.length; i++) {
 			filtered[i] = BETA * (filtered[i] + current[i] + last[i]);
 			last[i] = current[i];
 		}
 		return filtered;
 	}
-	
-//	public static float[] filterLowPass(float[] input, float[] prev, float alpha) {
-//		if (input == null || prev == null)
-//			throw new NullPointerException("input/prev needs to be inititialzied");
-//		if (input.length != prev.length)
-//			throw new IllegalArgumentException("Input arguemtments have different lengths");
-//
-//		for (int i = 0; i < input.length; i++) {
-//			prev[i] = prev[i] + alpha * (input[i] - prev[i]);
-//		}
-//		return prev;
-//	}
-//	
-//	public static float[] filterHighPass(float[] input, float[] prev, float alpha) {
-//		if (input == null || prev == null)
-//			throw new NullPointerException("input/prev needs to be inititialzied");
-//		if (input.length != prev.length)
-//			throw new IllegalArgumentException("Input arguemtments have different lengths");
-//
-//		for (int i = 0; i < input.length; i++) {
-//			prev[i] = (input[i] * ALPHA) + (prev[i] * (1.0f - ALPHA));
-//		}
-//
-//		return prev;
-//	}
 }
diff --git a/droidar/src/actions/algos/SquareRootBuffer.java b/droidar/src/actions/algos/SquareRootBuffer.java
deleted file mode 100644
index 4f0e9c0..0000000
--- a/droidar/src/actions/algos/SquareRootBuffer.java
+++ /dev/null
@@ -1,47 +0,0 @@
-package actions.algos;
-
-public class SquareRootBuffer extends Algo {
-
-	/*
-	 * dont set amplification under 150
-	 */
-	final float AMPLIFIC = 150;
-
-	@Override
-	public boolean execute(float[] target, float[] values, float bufferSize) {
-		return rootMeanSquareBuffer2(target, values, bufferSize);
-	}
-
-	private synchronized boolean rootMeanSquareBuffer2(float[] target,
-			float[] values, float mybufferValue) {
-
-		target[0] += AMPLIFIC;
-		target[1] += AMPLIFIC;
-		target[2] += AMPLIFIC;
-		values[0] += AMPLIFIC;
-		values[1] += AMPLIFIC;
-		values[2] += AMPLIFIC;
-
-		target[0] = (float) (Math
-				.sqrt((target[0] * target[0] * mybufferValue + values[0]
-						* values[0])
-						/ (1 + mybufferValue)));
-		target[1] = (float) (Math
-				.sqrt((target[1] * target[1] * mybufferValue + values[1]
-						* values[1])
-						/ (1 + mybufferValue)));
-		target[2] = (float) (Math
-				.sqrt((target[2] * target[2] * mybufferValue + values[2]
-						* values[2])
-						/ (1 + mybufferValue)));
-
-		target[0] -= AMPLIFIC;
-		target[1] -= AMPLIFIC;
-		target[2] -= AMPLIFIC;
-		values[0] -= AMPLIFIC;
-		values[1] -= AMPLIFIC;
-		values[2] -= AMPLIFIC;
-		return true;
-	}
-
-}

From 24d51912e92f4ea421d463b486f752f796249a10 Mon Sep 17 00:00:00 2001
From: rvieras 
Date: Fri, 6 Dec 2013 11:26:36 -0500
Subject: [PATCH 07/12] checkstyle updates for listeners package.

---
 droidar/src/listeners/EventListener.java      |  4 +-
 .../src/listeners/FrameReceivedListener.java  | 27 ++++++++++---
 droidar/src/listeners/ItemGuiListener.java    |  8 +++-
 .../src/listeners/ItemSelectedListener.java   |  9 ++++-
 .../src/listeners/ObjectCreateListener.java   | 10 -----
 droidar/src/listeners/ProcessListener.java    | 10 ++++-
 droidar/src/listeners/SelectionListener.java  | 38 +++++++++++++++----
 .../CamRotationVecUpdateListener.java         | 11 +++++-
 .../LocationEventListener.java                | 10 ++++-
 .../OrientationChangedListener.java           | 29 +++++++-------
 .../TouchMoveListener.java                    | 18 +++++++--
 .../TrackBallEventListener.java               | 12 +++++-
 12 files changed, 134 insertions(+), 52 deletions(-)
 delete mode 100644 droidar/src/listeners/ObjectCreateListener.java

diff --git a/droidar/src/listeners/EventListener.java b/droidar/src/listeners/EventListener.java
index e9b4efb..398c35e 100644
--- a/droidar/src/listeners/EventListener.java
+++ b/droidar/src/listeners/EventListener.java
@@ -6,7 +6,9 @@
 import listeners.eventManagerListeners.TouchMoveListener;
 import listeners.eventManagerListeners.TrackBallEventListener;
 
-@Deprecated
+/**
+ * Listener to will listen for events from multiple sources. 
+ */
 public interface EventListener extends LocationEventListener,
 		OrientationChangedListener, TouchMoveListener, TrackBallEventListener,
 		CamRotationVecUpdateListener {
diff --git a/droidar/src/listeners/FrameReceivedListener.java b/droidar/src/listeners/FrameReceivedListener.java
index 193a949..d17ecf9 100644
--- a/droidar/src/listeners/FrameReceivedListener.java
+++ b/droidar/src/listeners/FrameReceivedListener.java
@@ -1,11 +1,28 @@
 package listeners;
-
+/**
+ * Interface for listening for new frames. 
+ * Subject to change. 
+ */
 public interface FrameReceivedListener {
+	/**
+	 * This is called when a new frame has been received. 
+	 * @param frame - byte[] that contains the frame being viewed
+	 * @param mat - byte[] that contains data ??TODO: ??
+	 * @param frameWidth - current frame width
+	 * @param frameHeight - current frame height
+	 */
+	void onFrameReceived(byte[] frame, float[] mat, int frameWidth, int frameHeight);
 	
-	public void onFrameReceived(byte[] frame, float[] mat, int frameWidth, int frameHeight);
+	/**
+	 * This is called when a new frame has been parsed.
+	 * @param mat - byte[] array that contains the information that has been parsed.
+	 */
+	void onFrameParsed(float[] mat);
 	
-	public void onFrameParsed(float[] mat);
-	
-	public void onForceRefresh();
+	/**
+	 * Force the renderer to redraw.
+	 * TODO: This may be removed. 
+	 */
+	void onForceRefresh();
 	
 }
diff --git a/droidar/src/listeners/ItemGuiListener.java b/droidar/src/listeners/ItemGuiListener.java
index 88211ec..232521c 100644
--- a/droidar/src/listeners/ItemGuiListener.java
+++ b/droidar/src/listeners/ItemGuiListener.java
@@ -5,13 +5,17 @@
 
 /**
  * This listener is used to define a custom gui view for an object and it is
- * called everytime a gui view is needed
+ * called everytime a gui view is needed.
  * 
  * @author Spobo
  * 
  */
 public interface ItemGuiListener {
-
+	/**
+	 * @param viewToUseIfNotNull - {@link android.view.View}
+	 * @param parentView - {@link android.view.ViewGroup}
+	 * @return - {@link android.view.View} of the requested item. 
+	 */
 	View requestItemView(View viewToUseIfNotNull, ViewGroup parentView);
 
 }
diff --git a/droidar/src/listeners/ItemSelectedListener.java b/droidar/src/listeners/ItemSelectedListener.java
index 1a8e539..3225362 100644
--- a/droidar/src/listeners/ItemSelectedListener.java
+++ b/droidar/src/listeners/ItemSelectedListener.java
@@ -1,9 +1,14 @@
 package listeners;
 
 import gui.MetaInfos;
-
+/**
+ * Item selected listener. 
+ */
 public interface ItemSelectedListener {
-
+	/**
+	 * @param metaInfos - {@link gui.MetaInfos}
+	 * @return - true is everything processes correctly. 
+	 */
 	boolean onItemSelected(MetaInfos metaInfos);
 
 }
\ No newline at end of file
diff --git a/droidar/src/listeners/ObjectCreateListener.java b/droidar/src/listeners/ObjectCreateListener.java
deleted file mode 100644
index 70530f0..0000000
--- a/droidar/src/listeners/ObjectCreateListener.java
+++ /dev/null
@@ -1,10 +0,0 @@
-package listeners;
-
-import util.Wrapper;
-
-@Deprecated
-public interface ObjectCreateListener {
-
-	boolean setWrapperToObject(Wrapper targetWrapper);
-
-}
diff --git a/droidar/src/listeners/ProcessListener.java b/droidar/src/listeners/ProcessListener.java
index 1e2737e..7dd8021 100644
--- a/droidar/src/listeners/ProcessListener.java
+++ b/droidar/src/listeners/ProcessListener.java
@@ -1,7 +1,15 @@
 package listeners;
-
+/**
+ * TODO: Not sure what this interface if for yet.
+ */
 public interface ProcessListener {
 
+	/**
+	 * Process an object. 
+	 * @param pos - current
+	 * @param max - max
+	 * @param objectToProcessNow - object to process
+	 */
 	void onProcessStep(int pos, int max, Object objectToProcessNow);
 
 }
diff --git a/droidar/src/listeners/SelectionListener.java b/droidar/src/listeners/SelectionListener.java
index 60091b5..2487f59 100644
--- a/droidar/src/listeners/SelectionListener.java
+++ b/droidar/src/listeners/SelectionListener.java
@@ -1,22 +1,38 @@
 package listeners;
 
-import gl.scenegraph.MeshComponent;
-
 import commands.Command;
-
+/**
+ * Interface for handling UI interaction.  
+ */
 public interface SelectionListener {
 
+	/**
+	 * Get the on click command. 
+	 * @return - {@link commands.Command}
+	 */
 	Command getOnClickCommand();
 
+	/**
+	 * Get the on long click command. 
+	 * @return - {@link commands.Command}
+	 */
 	Command getOnLongClickCommand();
 
+	/**
+	 * Get the on map click command. 
+	 * @return - {@link commands.Command}
+	 */
 	Command getOnMapClickCommand();
 
+	/**
+	 * Get the on double click command. 
+	 * @return - {@link commands.Command}
+	 */
 	Command getOnDoubleClickCommand();
 
 	/**
 	 * This will enable the selection mechanism (like color-picking in the
-	 * {@link MeshComponent}) if possible.
+	 * {@link gl.scenegraph.MeshComponent}) if possible.
 	 * 
 	 * @param cmd - {@link commands.Command}
 	 */
@@ -24,7 +40,7 @@ public interface SelectionListener {
 
 	/**
 	 * This will enable the selection mechanism (like color-picking in the
-	 * {@link MeshComponent}) if possible.
+	 * {@link gl.scenegraph.MeshComponent}) if possible.
 	 * 
 	 * @param cmd - {@link commands.Command}
 	 */
@@ -32,12 +48,18 @@ public interface SelectionListener {
 
 	/**
 	 * This will enable the selection mechanism (like color-picking in the
-	 * {@link MeshComponent}) if possible
+	 * {@link gl.scenegraph.MeshComponent}) if possible.
 	 * 
 	 * @param cmd - - {@link commands.Command}
 	 */
-	public void setOnLongClickCommand(Command cmd);
+	void setOnLongClickCommand(Command cmd);
 
-	public void setOnMapClickCommand(Command cmd);
+	/**
+	 * This will enable the selection mechanism (like color-picking in the
+	 * {@link gl.scenegraph.MeshComponent}) if possible.
+	 * 
+	 * @param cmd - - {@link commands.Command}
+	 */
+	void setOnMapClickCommand(Command cmd);
 
 }
diff --git a/droidar/src/listeners/eventManagerListeners/CamRotationVecUpdateListener.java b/droidar/src/listeners/eventManagerListeners/CamRotationVecUpdateListener.java
index c75c8ae..ade5591 100644
--- a/droidar/src/listeners/eventManagerListeners/CamRotationVecUpdateListener.java
+++ b/droidar/src/listeners/eventManagerListeners/CamRotationVecUpdateListener.java
@@ -1,7 +1,14 @@
 package listeners.eventManagerListeners;
 
 import util.Vec;
-
+/**
+ *  Listener for camera rotation updates. 
+ */
 public interface CamRotationVecUpdateListener {
-	public void onCamRotationVecUpdate(Vec target, Vec values, float timeDelta);
+	/**
+	 * @param target - target location in {@link util.Vec} 
+	 * @param values - current location in {@link util.Vec}
+	 * @param timeDelta - time between last update. 
+	 */
+	void onCamRotationVecUpdate(Vec target, Vec values, float timeDelta);
 }
diff --git a/droidar/src/listeners/eventManagerListeners/LocationEventListener.java b/droidar/src/listeners/eventManagerListeners/LocationEventListener.java
index 538900c..ec5278e 100644
--- a/droidar/src/listeners/eventManagerListeners/LocationEventListener.java
+++ b/droidar/src/listeners/eventManagerListeners/LocationEventListener.java
@@ -1,7 +1,13 @@
 package listeners.eventManagerListeners;
 
 import android.location.Location;
-
+/**
+ * Listener for when the location has been changed. 
+ */
 public interface LocationEventListener {
-	public abstract boolean onLocationChanged(Location location);
+	/**
+	 * @param location - new/current {@link android.location.Location}
+	 * @return - process successful
+	 */
+	boolean onLocationChanged(Location location);
 }
diff --git a/droidar/src/listeners/eventManagerListeners/OrientationChangedListener.java b/droidar/src/listeners/eventManagerListeners/OrientationChangedListener.java
index 8e760e3..553d391 100644
--- a/droidar/src/listeners/eventManagerListeners/OrientationChangedListener.java
+++ b/droidar/src/listeners/eventManagerListeners/OrientationChangedListener.java
@@ -1,32 +1,33 @@
 package listeners.eventManagerListeners;
 
-import android.hardware.SensorEventListener;
-
+/**
+ * Listener for sensors. 
+ */
 public interface OrientationChangedListener {
 	/**
 	 * see
-	 * {@link SensorEventListener#onSensorChanged(android.hardware.SensorEvent)}
+	 * {@link android.hardware.SensorEventListener#onSensorChanged(android.hardware.SensorEvent)}.
 	 * 
-	 * @param values
-	 * @return
+	 * @param values - values returned from sensor.
+	 * @return - process successful
 	 */
-	public abstract boolean onOrientationChanged(float[] values);
+	boolean onOrientationChanged(float[] values);
 
 	/**
 	 * see
-	 * {@link SensorEventListener#onSensorChanged(android.hardware.SensorEvent)}
+	 * {@link android.hardware.SensorEventListener#onSensorChanged(android.hardware.SensorEvent)}.
 	 * 
-	 * @param values
-	 * @return
+	 * @param values - values returned from sensor
+	 * @return - process successful
 	 */
-	public boolean onMagnetChanged(float[] values);
+	boolean onMagnetChanged(float[] values);
 
 	/**
 	 * see
-	 * {@link SensorEventListener#onSensorChanged(android.hardware.SensorEvent)}
+	 * {@link android.hardware.SensorEventListener#onSensorChanged(android.hardware.SensorEvent)}.
 	 * 
-	 * @param values
-	 * @return
+	 * @param values - values returned from sensor
+	 * @return - process successful
 	 */
-	public abstract boolean onAccelChanged(float[] values);
+	boolean onAccelChanged(float[] values);
 }
diff --git a/droidar/src/listeners/eventManagerListeners/TouchMoveListener.java b/droidar/src/listeners/eventManagerListeners/TouchMoveListener.java
index 6cee33c..ddb5714 100644
--- a/droidar/src/listeners/eventManagerListeners/TouchMoveListener.java
+++ b/droidar/src/listeners/eventManagerListeners/TouchMoveListener.java
@@ -1,11 +1,23 @@
 package listeners.eventManagerListeners;
 
 import android.view.MotionEvent;
-
+/**
+ * Listen for touch move events.
+ */
 public interface TouchMoveListener {
 
-	public boolean onTouchMove(MotionEvent e1, MotionEvent e2,
+	/**
+	 * @param e1 - {@link android.view.MotionEvent} first motion
+	 * @param e2 - {@link android.view.MotionEvent} second motion
+	 * @param screenDeltaX - change in x
+	 * @param screenDeltaY - change in y 
+	 * @return - process successful
+	 */
+	boolean onTouchMove(MotionEvent e1, MotionEvent e2,
 			float screenDeltaX, float screenDeltaY);
 
-	public boolean onReleaseTouchMove();
+	/**
+	 * @return process successful
+	 */
+	boolean onReleaseTouchMove();
 }
diff --git a/droidar/src/listeners/eventManagerListeners/TrackBallEventListener.java b/droidar/src/listeners/eventManagerListeners/TrackBallEventListener.java
index 5a866ee..f3c0e87 100644
--- a/droidar/src/listeners/eventManagerListeners/TrackBallEventListener.java
+++ b/droidar/src/listeners/eventManagerListeners/TrackBallEventListener.java
@@ -1,7 +1,15 @@
 package listeners.eventManagerListeners;
 
 import android.view.MotionEvent;
-
+/**
+ * Listen for events from the track ball.  
+ */
 public interface TrackBallEventListener {
-	public boolean onTrackballEvent(float x, float y, MotionEvent event);
+	/**
+	 * @param x -  x axis
+	 * @param y - y axis
+	 * @param event - {@link android.view.MotionEvent}
+	 * @return - process successful
+	 */
+	boolean onTrackballEvent(float x, float y, MotionEvent event);
 }

From ca25dc747c4c21c0d324fd77aadcf9206d8bda34 Mon Sep 17 00:00:00 2001
From: rvieras 
Date: Fri, 6 Dec 2013 13:06:57 -0500
Subject: [PATCH 08/12] checkstyle updates.

---
 droidar/src/actions/Action.java               |   2 +-
 .../src/actions/ActionCalcRelativePos.java    |   4 +-
 droidar/src/actions/ActionMoveObject.java     |  10 +-
 droidar/src/actions/ActionWASDMovement.java   |   2 +-
 .../actions/ActionWithSensorProcessing.java   |   2 +-
 droidar/src/commands/Command.java             |   4 +-
 droidar/src/commands/CommandGroup.java        |   2 +-
 .../logic/CommandSetWrapperToValue.java       |   3 +-
 .../logic/CommandSetWrapperToValue2.java      |   3 +-
 .../system/CommandShowWorldAnimation.java     |   3 +-
 droidar/src/components/PhysicsComponent.java  |   8 +-
 droidar/src/components/ProximitySensor.java   |  10 +-
 .../ProximitySensorForOtherObjects.java       |  17 ++-
 .../src/components/SimpleTooFarAwayComp.java  |   9 +-
 droidar/src/components/TimerComp.java         |   9 +-
 droidar/src/components/TooFarAwayComp.java    |  10 +-
 droidar/src/components/ViewPosCalcerComp.java |   8 +-
 droidar/src/components/Visitable.java         |   2 +-
 .../src/de/rwth/setups/CollectItemsSetup.java |   6 +-
 droidar/src/de/rwth/setups/DebugSetup.java    |   6 +-
 .../rwth/setups/FarAwayPOIScenarioSetup.java  |   4 +-
 .../de/rwth/setups/FastChangingTextSetup.java |   4 +-
 .../src/de/rwth/setups/GeoPosTestSetup.java   |   2 +-
 .../de/rwth/setups/GraphCreationSetup.java    |   4 +-
 .../rwth/setups/GraphMovementTestSetup.java   |   4 +-
 .../src/de/rwth/setups/LargeWorldsSetup.java  |   6 +-
 .../src/de/rwth/setups/LightningSetup.java    |  15 ++-
 .../src/de/rwth/setups/PlaceObjectsSetup.java |   7 +-
 .../de/rwth/setups/PlaceObjectsSetupTwo.java  |  12 +-
 .../de/rwth/setups/PositionTestsSetup.java    |   5 +-
 .../src/de/rwth/setups/SensorTestSetup.java   |   5 +-
 .../src/de/rwth/setups/StaticDemoSetup.java   |   6 +-
 droidar/src/de/rwth/setups/TestSetup.java     |   2 +-
 droidar/src/de/rwth/setups/TimeModifier.java  |   6 +-
 droidar/src/geo/GeoCalcer.java                |   4 +-
 droidar/src/geo/GeoGraph.java                 |  12 +-
 droidar/src/geo/GeoObj.java                   |   8 +-
 droidar/src/geo/SimpleNodeEdgeListener.java   |   5 +-
 droidar/src/gl/GLCamera.java                  |  26 ++--
 droidar/src/gl/GLFactory.java                 |   6 +-
 droidar/src/gl/GLText.java                    |   2 +-
 droidar/src/gl/LightSource.java               |   2 +-
 .../gl/animations/AnimationAlphaBlend.java    |   4 +-
 .../src/gl/animations/AnimationBounce.java    |   4 +-
 .../gl/animations/AnimationColorBounce.java   |   4 +-
 .../gl/animations/AnimationColorMorph.java    |   4 +-
 .../gl/animations/AnimationFaceToCamera.java  |   4 +-
 droidar/src/gl/animations/AnimationGrow.java  |   6 +-
 droidar/src/gl/animations/AnimationMove.java  |   4 +-
 droidar/src/gl/animations/AnimationPulse.java |   4 +-
 .../src/gl/animations/AnimationRotate.java    |   4 +-
 .../src/gl/animations/AnimationShrink.java    |   4 +-
 .../gl/animations/AnimationSwingRotate.java   |   4 +-
 droidar/src/gl/animations/GLAnimation.java    |   4 +-
 droidar/src/gl/scenegraph/MeshComponent.java  |   7 +-
 droidar/src/gl/scenegraph/RenderList.java     |   6 +-
 droidar/src/gl/scenegraph/Shape.java          |   2 +-
 droidar/src/gui/RadarView.java                |  10 +-
 droidar/src/setup/ArSetup.java                |   4 +-
 droidar/src/setup/DefaultArSetup.java         |   4 +-
 droidar/src/setup/ISetupSteps.java            |   8 +-
 droidar/src/tests/GeoTests.java               |   3 +-
 droidar/src/tests/SystemTests.java            |   5 +-
 droidar/src/tests/WorldTests.java             |   4 +-
 droidar/src/worldData/Entity.java             |  31 -----
 droidar/src/worldData/RenderableEntity.java   |  26 ----
 .../{worldData => worlddata}/AbstractObj.java |  22 +++-
 droidar/src/worlddata/Entity.java             |  33 +++++
 .../{worldData => worlddata}/EntityList.java  |  50 ++++----
 .../HasInfosInterface.java                    |   6 +-
 .../{worldData => worlddata}/LargeWorld.java  |  24 ++--
 .../{worldData => worlddata}/MoveComp.java    |  26 ++--
 droidar/src/{worldData => worlddata}/Obj.java | 118 +++++++++---------
 .../RenderQuadList.java                       |   2 +-
 droidar/src/worlddata/RenderableEntity.java   |  22 ++++
 .../SystemUpdater.java                        |   2 +-
 .../UpdatableWithInit.java                    |   2 +-
 .../{worldData => worlddata}/UpdateTimer.java |   2 +-
 .../{worldData => worlddata}/Updateable.java  |   2 +-
 .../src/{worldData => worlddata}/Visitor.java |   6 +-
 .../src/{worldData => worlddata}/World.java   |   2 +-
 .../src/{worldData => worlddata}/visitor.uxf  |   0
 .../src/{worldData => worlddata}/world.uxf    |   0
 83 files changed, 371 insertions(+), 375 deletions(-)
 delete mode 100644 droidar/src/worldData/Entity.java
 delete mode 100644 droidar/src/worldData/RenderableEntity.java
 rename droidar/src/{worldData => worlddata}/AbstractObj.java (86%)
 create mode 100644 droidar/src/worlddata/Entity.java
 rename droidar/src/{worldData => worlddata}/EntityList.java (59%)
 rename droidar/src/{worldData => worlddata}/HasInfosInterface.java (83%)
 rename droidar/src/{worldData => worlddata}/LargeWorld.java (87%)
 rename droidar/src/{worldData => worlddata}/MoveComp.java (66%)
 rename droidar/src/{worldData => worlddata}/Obj.java (67%)
 rename droidar/src/{worldData => worlddata}/RenderQuadList.java (99%)
 create mode 100644 droidar/src/worlddata/RenderableEntity.java
 rename droidar/src/{worldData => worlddata}/SystemUpdater.java (99%)
 rename droidar/src/{worldData => worlddata}/UpdatableWithInit.java (90%)
 rename droidar/src/{worldData => worlddata}/UpdateTimer.java (99%)
 rename droidar/src/{worldData => worlddata}/Updateable.java (97%)
 rename droidar/src/{worldData => worlddata}/Visitor.java (97%)
 rename droidar/src/{worldData => worlddata}/World.java (99%)
 rename droidar/src/{worldData => worlddata}/visitor.uxf (100%)
 rename droidar/src/{worldData => worlddata}/world.uxf (100%)

diff --git a/droidar/src/actions/Action.java b/droidar/src/actions/Action.java
index 799d418..ab9d64b 100644
--- a/droidar/src/actions/Action.java
+++ b/droidar/src/actions/Action.java
@@ -4,7 +4,7 @@
 import logger.ARLogger;
 import util.Log;
 import util.Vec;
-import worldData.Updateable;
+import worlddata.Updateable;
 import android.location.Location;
 import android.view.MotionEvent;
 
diff --git a/droidar/src/actions/ActionCalcRelativePos.java b/droidar/src/actions/ActionCalcRelativePos.java
index f509245..5dfc44a 100644
--- a/droidar/src/actions/ActionCalcRelativePos.java
+++ b/droidar/src/actions/ActionCalcRelativePos.java
@@ -4,7 +4,7 @@
 import gl.GLCamera;
 import logger.ARLogger;
 import system.EventManager;
-import worldData.World;
+import worlddata.World;
 import android.location.Location;
 
 /**
@@ -60,7 +60,7 @@ public class ActionCalcRelativePos extends Action {
 
 	/**
 	 * Constructor.
-	 * @param world - {@link worldData.World}
+	 * @param world - {@link worlddata.World}
 	 * @param camera - {@link gl.GLCamera}
 	 */
 	public ActionCalcRelativePos(World world, GLCamera camera) {
diff --git a/droidar/src/actions/ActionMoveObject.java b/droidar/src/actions/ActionMoveObject.java
index c176ba9..6646a27 100644
--- a/droidar/src/actions/ActionMoveObject.java
+++ b/droidar/src/actions/ActionMoveObject.java
@@ -3,8 +3,8 @@
 import gl.GLCamera;
 import util.Vec;
 import util.Wrapper;
-import worldData.MoveComp;
-import worldData.Obj;
+import worlddata.MoveComp;
+import worlddata.Obj;
 
 /**
  * An action to move an object along the axis.
@@ -41,10 +41,10 @@ private void foundObj(Obj obj, float x, float y) {
 		MoveComp mc = obj.getComp(MoveComp.class);
 		Vec pos = obj.getPosition();
 		if (mc != null) {
-			if (mc.myTargetPos == null && pos != null) {
-				mc.myTargetPos = pos.copy();
+			if (mc.mTargetPos == null && pos != null) {
+				mc.mTargetPos = pos.copy();
 			}
-			mc.myTargetPos.add(x, y, 0.0f);
+			mc.mTargetPos.add(x, y, 0.0f);
 		} else if (pos != null) {
 			/*
 			 * if no move comp was found in the target object, the mesh itself
diff --git a/droidar/src/actions/ActionWASDMovement.java b/droidar/src/actions/ActionWASDMovement.java
index cdec3ed..e39a749 100644
--- a/droidar/src/actions/ActionWASDMovement.java
+++ b/droidar/src/actions/ActionWASDMovement.java
@@ -2,7 +2,7 @@
 
 import gl.GLCamera;
 import util.Vec;
-import worldData.Updateable;
+import worlddata.Updateable;
 import android.view.MotionEvent;
 
 /**
diff --git a/droidar/src/actions/ActionWithSensorProcessing.java b/droidar/src/actions/ActionWithSensorProcessing.java
index 19cf5b2..82dc5d2 100644
--- a/droidar/src/actions/ActionWithSensorProcessing.java
+++ b/droidar/src/actions/ActionWithSensorProcessing.java
@@ -5,7 +5,7 @@
 import setup.ArSetup;
 import system.EventManager;
 import util.Calculus;
-import worldData.Updateable;
+import worlddata.Updateable;
 import actions.algos.Algo;
 import android.hardware.SensorManager;
 import android.view.MotionEvent;
diff --git a/droidar/src/commands/Command.java b/droidar/src/commands/Command.java
index 8708339..2b35e5f 100644
--- a/droidar/src/commands/Command.java
+++ b/droidar/src/commands/Command.java
@@ -4,7 +4,7 @@
 import gui.MetaInfos;
 import listeners.ItemGuiListener;
 import util.Log;
-import worldData.HasInfosInterface;
+import worlddata.HasInfosInterface;
 import android.view.View;
 import android.view.ViewGroup;
 
@@ -71,7 +71,7 @@ public MetaInfos getInfoObject() {
 	}
 
 	@Override
-	public boolean HasInfoObject() {
+	public boolean hasInfoObject() {
 		if (myInfoObj != null)
 			return true;
 		return false;
diff --git a/droidar/src/commands/CommandGroup.java b/droidar/src/commands/CommandGroup.java
index 0a9d330..ac5a466 100644
--- a/droidar/src/commands/CommandGroup.java
+++ b/droidar/src/commands/CommandGroup.java
@@ -123,7 +123,7 @@ public void removeEmptyItems() {
 
 	@Override
 	public String toString() {
-		if (this.HasInfoObject())
+		if (this.hasInfoObject())
 			return "CG " + getInfoObject().getShortDescr();
 		return super.toString();
 	}
diff --git a/droidar/src/commands/logic/CommandSetWrapperToValue.java b/droidar/src/commands/logic/CommandSetWrapperToValue.java
index cfbf955..f2ea8b2 100644
--- a/droidar/src/commands/logic/CommandSetWrapperToValue.java
+++ b/droidar/src/commands/logic/CommandSetWrapperToValue.java
@@ -3,8 +3,7 @@
 import util.Log;
 import util.Wrapper;
 import util.Wrapper.Type;
-import worldData.Obj;
-
+import worlddata.Obj;
 import commands.undoable.UndoableCommand;
 
 public class CommandSetWrapperToValue extends UndoableCommand {
diff --git a/droidar/src/commands/logic/CommandSetWrapperToValue2.java b/droidar/src/commands/logic/CommandSetWrapperToValue2.java
index f4ea953..37ac219 100644
--- a/droidar/src/commands/logic/CommandSetWrapperToValue2.java
+++ b/droidar/src/commands/logic/CommandSetWrapperToValue2.java
@@ -3,8 +3,7 @@
 import listeners.SelectionListener;
 import util.Log;
 import util.Wrapper;
-import worldData.AbstractObj;
-
+import worlddata.AbstractObj;
 import commands.undoable.UndoableCommand;
 
 /**
diff --git a/droidar/src/commands/system/CommandShowWorldAnimation.java b/droidar/src/commands/system/CommandShowWorldAnimation.java
index 1d43974..cce88d5 100644
--- a/droidar/src/commands/system/CommandShowWorldAnimation.java
+++ b/droidar/src/commands/system/CommandShowWorldAnimation.java
@@ -1,7 +1,6 @@
 package commands.system;
 
-import worldData.SystemUpdater;
-
+import worlddata.SystemUpdater;
 import commands.undoable.UndoableCommand;
 
 public class CommandShowWorldAnimation extends UndoableCommand {
diff --git a/droidar/src/components/PhysicsComponent.java b/droidar/src/components/PhysicsComponent.java
index 3977fef..3562497 100644
--- a/droidar/src/components/PhysicsComponent.java
+++ b/droidar/src/components/PhysicsComponent.java
@@ -3,10 +3,10 @@
 import gl.scenegraph.MeshComponent;
 import util.Log;
 import util.Vec;
-import worldData.Entity;
-import worldData.Obj;
-import worldData.Updateable;
-import worldData.Visitor;
+import worlddata.Entity;
+import worlddata.Obj;
+import worlddata.Updateable;
+import worlddata.Visitor;
 
 /**
  * currently only for testing! not functional jet
diff --git a/droidar/src/components/ProximitySensor.java b/droidar/src/components/ProximitySensor.java
index 0b06e57..efa64aa 100644
--- a/droidar/src/components/ProximitySensor.java
+++ b/droidar/src/components/ProximitySensor.java
@@ -5,11 +5,11 @@
 import gl.scenegraph.MeshComponent;
 import util.Log;
 import util.Vec;
-import worldData.Entity;
-import worldData.Obj;
-import worldData.UpdateTimer;
-import worldData.Updateable;
-import worldData.Visitor;
+import worlddata.Entity;
+import worlddata.Obj;
+import worlddata.UpdateTimer;
+import worlddata.Updateable;
+import worlddata.Visitor;
 
 public abstract class ProximitySensor implements Entity {
 
diff --git a/droidar/src/components/ProximitySensorForOtherObjects.java b/droidar/src/components/ProximitySensorForOtherObjects.java
index 2998a3e..c3c6278 100644
--- a/droidar/src/components/ProximitySensorForOtherObjects.java
+++ b/droidar/src/components/ProximitySensorForOtherObjects.java
@@ -5,15 +5,14 @@
 import util.Log;
 import util.QuadTree;
 import util.Vec;
-import worldData.Entity;
-import worldData.LargeWorld;
-import worldData.Obj;
-import worldData.RenderableEntity;
-import worldData.UpdateTimer;
-import worldData.Updateable;
-import worldData.Visitor;
-import worldData.World;
-
+import worlddata.Entity;
+import worlddata.LargeWorld;
+import worlddata.Obj;
+import worlddata.RenderableEntity;
+import worlddata.UpdateTimer;
+import worlddata.Updateable;
+import worlddata.Visitor;
+import worlddata.World;
 import commands.Command;
 
 public class ProximitySensorForOtherObjects implements Entity {
diff --git a/droidar/src/components/SimpleTooFarAwayComp.java b/droidar/src/components/SimpleTooFarAwayComp.java
index b1c3949..917451e 100644
--- a/droidar/src/components/SimpleTooFarAwayComp.java
+++ b/droidar/src/components/SimpleTooFarAwayComp.java
@@ -7,11 +7,10 @@
 import gl.scenegraph.Shape;
 import util.Log;
 import util.Vec;
-import worldData.MoveComp;
-import worldData.Obj;
-import worldData.Updateable;
+import worlddata.MoveComp;
+import worlddata.Obj;
+import worlddata.Updateable;
 import android.app.Activity;
-
 import commands.Command;
 import commands.ui.CommandShowToast;
 
@@ -87,7 +86,7 @@ public void onFarAwayEvent(Updateable parent, MeshComponent parentsMesh,
 				.newDirectedPath(lineEndPos, null).getMyRenderData());
 		Vec pos = direction.setLength(direction.getLength() - 10);
 		pos.z -= 5;
-		mover.myTargetPos = pos;
+		mover.mTargetPos = pos;
 	}
 
 }
diff --git a/droidar/src/components/TimerComp.java b/droidar/src/components/TimerComp.java
index ab3ecf1..d2c1e7f 100644
--- a/droidar/src/components/TimerComp.java
+++ b/droidar/src/components/TimerComp.java
@@ -1,11 +1,10 @@
 package components;
 
 import commands.Command;
-
-import worldData.Entity;
-import worldData.UpdateTimer;
-import worldData.Updateable;
-import worldData.Visitor;
+import worlddata.Entity;
+import worlddata.UpdateTimer;
+import worlddata.Updateable;
+import worlddata.Visitor;
 
 public class TimerComp implements Entity {
 
diff --git a/droidar/src/components/TooFarAwayComp.java b/droidar/src/components/TooFarAwayComp.java
index 1e08a26..b505f50 100644
--- a/droidar/src/components/TooFarAwayComp.java
+++ b/droidar/src/components/TooFarAwayComp.java
@@ -4,11 +4,11 @@
 import gl.HasPosition;
 import gl.scenegraph.MeshComponent;
 import util.Vec;
-import worldData.Entity;
-import worldData.Obj;
-import worldData.UpdateTimer;
-import worldData.Updateable;
-import worldData.Visitor;
+import worlddata.Entity;
+import worlddata.Obj;
+import worlddata.UpdateTimer;
+import worlddata.Updateable;
+import worlddata.Visitor;
 import android.util.Log;
 
 public abstract class TooFarAwayComp implements Entity {
diff --git a/droidar/src/components/ViewPosCalcerComp.java b/droidar/src/components/ViewPosCalcerComp.java
index 1a48b8c..e93b779 100644
--- a/droidar/src/components/ViewPosCalcerComp.java
+++ b/droidar/src/components/ViewPosCalcerComp.java
@@ -2,10 +2,10 @@
 
 import gl.GLCamera;
 import util.Vec;
-import worldData.Entity;
-import worldData.UpdateTimer;
-import worldData.Updateable;
-import worldData.Visitor;
+import worlddata.Entity;
+import worlddata.UpdateTimer;
+import worlddata.Updateable;
+import worlddata.Visitor;
 import android.util.Log;
 
 public abstract class ViewPosCalcerComp implements Entity {
diff --git a/droidar/src/components/Visitable.java b/droidar/src/components/Visitable.java
index 9afccb5..10815b1 100644
--- a/droidar/src/components/Visitable.java
+++ b/droidar/src/components/Visitable.java
@@ -1,6 +1,6 @@
 package components;
 
-import worldData.Visitor;
+import worlddata.Visitor;
 
 public interface Visitable {
 	/**
diff --git a/droidar/src/de/rwth/setups/CollectItemsSetup.java b/droidar/src/de/rwth/setups/CollectItemsSetup.java
index 875301d..8b0b2c0 100644
--- a/droidar/src/de/rwth/setups/CollectItemsSetup.java
+++ b/droidar/src/de/rwth/setups/CollectItemsSetup.java
@@ -14,9 +14,9 @@
 import system.ErrorHandler;
 import system.EventManager;
 import util.Vec;
-import worldData.Obj;
-import worldData.SystemUpdater;
-import worldData.World;
+import worlddata.Obj;
+import worlddata.SystemUpdater;
+import worlddata.World;
 import actions.Action;
 import actions.ActionCalcRelativePos;
 import actions.ActionMoveCameraBuffered;
diff --git a/droidar/src/de/rwth/setups/DebugSetup.java b/droidar/src/de/rwth/setups/DebugSetup.java
index aeda132..a83e4d1 100644
--- a/droidar/src/de/rwth/setups/DebugSetup.java
+++ b/droidar/src/de/rwth/setups/DebugSetup.java
@@ -24,9 +24,9 @@
 import util.Log;
 import util.Vec;
 import util.Wrapper;
-import worldData.Obj;
-import worldData.SystemUpdater;
-import worldData.World;
+import worlddata.Obj;
+import worlddata.SystemUpdater;
+import worlddata.World;
 import actions.ActionCalcRelativePos;
 import actions.ActionMoveCameraBuffered;
 import actions.ActionRotateCameraBuffered;
diff --git a/droidar/src/de/rwth/setups/FarAwayPOIScenarioSetup.java b/droidar/src/de/rwth/setups/FarAwayPOIScenarioSetup.java
index 4925637..e0d45b2 100644
--- a/droidar/src/de/rwth/setups/FarAwayPOIScenarioSetup.java
+++ b/droidar/src/de/rwth/setups/FarAwayPOIScenarioSetup.java
@@ -7,8 +7,8 @@
 import gui.RadarView;
 import setup.DefaultArSetup;
 import util.Vec;
-import worldData.SystemUpdater;
-import worldData.World;
+import worlddata.SystemUpdater;
+import worlddata.World;
 import android.app.Activity;
 import android.util.Log;
 import commands.Command;
diff --git a/droidar/src/de/rwth/setups/FastChangingTextSetup.java b/droidar/src/de/rwth/setups/FastChangingTextSetup.java
index a9c755d..52f8ba7 100644
--- a/droidar/src/de/rwth/setups/FastChangingTextSetup.java
+++ b/droidar/src/de/rwth/setups/FastChangingTextSetup.java
@@ -10,8 +10,8 @@
 import java.util.HashMap;
 
 import setup.DefaultArSetup;
-import worldData.Obj;
-import worldData.World;
+import worlddata.Obj;
+import worlddata.World;
 import android.app.Activity;
 import commands.Command;
 
diff --git a/droidar/src/de/rwth/setups/GeoPosTestSetup.java b/droidar/src/de/rwth/setups/GeoPosTestSetup.java
index 9d2232f..22a664c 100644
--- a/droidar/src/de/rwth/setups/GeoPosTestSetup.java
+++ b/droidar/src/de/rwth/setups/GeoPosTestSetup.java
@@ -6,7 +6,7 @@
 import gl.GLFactory;
 import setup.DefaultArSetup;
 import util.Vec;
-import worldData.World;
+import worlddata.World;
 
 public class GeoPosTestSetup extends DefaultArSetup {
 	@Override
diff --git a/droidar/src/de/rwth/setups/GraphCreationSetup.java b/droidar/src/de/rwth/setups/GraphCreationSetup.java
index 045ab9b..f18152a 100644
--- a/droidar/src/de/rwth/setups/GraphCreationSetup.java
+++ b/droidar/src/de/rwth/setups/GraphCreationSetup.java
@@ -19,8 +19,8 @@
 import util.EfficientList;
 import util.EfficientListQualified;
 import util.Vec;
-import worldData.SystemUpdater;
-import worldData.World;
+import worlddata.SystemUpdater;
+import worlddata.World;
 import actions.Action;
 import actions.ActionBufferedCameraAR;
 import actions.ActionCalcRelativePos;
diff --git a/droidar/src/de/rwth/setups/GraphMovementTestSetup.java b/droidar/src/de/rwth/setups/GraphMovementTestSetup.java
index e2a9b62..38562cd 100644
--- a/droidar/src/de/rwth/setups/GraphMovementTestSetup.java
+++ b/droidar/src/de/rwth/setups/GraphMovementTestSetup.java
@@ -11,8 +11,8 @@
 import system.EventManager;
 import util.EfficientList;
 import util.Vec;
-import worldData.SystemUpdater;
-import worldData.World;
+import worlddata.SystemUpdater;
+import worlddata.World;
 
 public class GraphMovementTestSetup extends DefaultArSetup {
 	@Override
diff --git a/droidar/src/de/rwth/setups/LargeWorldsSetup.java b/droidar/src/de/rwth/setups/LargeWorldsSetup.java
index cdb4052..d564e81 100644
--- a/droidar/src/de/rwth/setups/LargeWorldsSetup.java
+++ b/droidar/src/de/rwth/setups/LargeWorldsSetup.java
@@ -7,9 +7,9 @@
 import setup.DefaultArSetup;
 import system.ErrorHandler;
 import util.Vec;
-import worldData.AbstractObj;
-import worldData.RenderQuadList;
-import worldData.World;
+import worlddata.AbstractObj;
+import worlddata.RenderQuadList;
+import worlddata.World;
 
 public class LargeWorldsSetup extends DefaultArSetup {
 	private static final int NUMBER_OF_OBJECTS = 1000;
diff --git a/droidar/src/de/rwth/setups/LightningSetup.java b/droidar/src/de/rwth/setups/LightningSetup.java
index 220fa4c..d3425b0 100644
--- a/droidar/src/de/rwth/setups/LightningSetup.java
+++ b/droidar/src/de/rwth/setups/LightningSetup.java
@@ -19,15 +19,14 @@
 import system.EventManager;
 import util.Vec;
 import util.Wrapper;
-import worldData.Entity;
-import worldData.MoveComp;
-import worldData.Obj;
-import worldData.SystemUpdater;
-import worldData.World;
+import worlddata.Entity;
+import worlddata.MoveComp;
+import worlddata.Obj;
+import worlddata.SystemUpdater;
+import worlddata.World;
 import actions.ActionMoveObject;
 import android.app.Activity;
 import android.util.Log;
-
 import commands.Command;
 
 public class LightningSetup extends DefaultArSetup {
@@ -147,7 +146,7 @@ public boolean execute() {
 					MoveComp mover = ((Obj) targetMoveWrapper.getObject())
 							.getComp(MoveComp.class);
 					if (mover != null) {
-						mover.myTargetPos.z -= zMoveFactor;
+						mover.mTargetPos.z -= zMoveFactor;
 					} else {
 						Vec pos = ((Obj) targetMoveWrapper.getObject())
 								.getPosition();
@@ -170,7 +169,7 @@ public boolean execute() {
 					MoveComp mover = ((Obj) targetMoveWrapper.getObject())
 							.getComp(MoveComp.class);
 					if (mover != null) {
-						mover.myTargetPos.z += zMoveFactor;
+						mover.mTargetPos.z += zMoveFactor;
 					} else {
 						Vec pos = ((Obj) targetMoveWrapper.getObject())
 								.getPosition();
diff --git a/droidar/src/de/rwth/setups/PlaceObjectsSetup.java b/droidar/src/de/rwth/setups/PlaceObjectsSetup.java
index 8a53e49..12d1d00 100644
--- a/droidar/src/de/rwth/setups/PlaceObjectsSetup.java
+++ b/droidar/src/de/rwth/setups/PlaceObjectsSetup.java
@@ -13,16 +13,15 @@
 import system.EventManager;
 import util.Vec;
 import util.Wrapper;
-import worldData.Obj;
-import worldData.SystemUpdater;
-import worldData.World;
+import worlddata.Obj;
+import worlddata.SystemUpdater;
+import worlddata.World;
 import actions.Action;
 import actions.ActionBufferedCameraAR;
 import actions.ActionCalcRelativePos;
 import actions.ActionMoveCameraBuffered;
 import actions.ActionRotateCameraBuffered;
 import android.app.Activity;
-
 import commands.Command;
 
 public class PlaceObjectsSetup extends ArSetup {
diff --git a/droidar/src/de/rwth/setups/PlaceObjectsSetupTwo.java b/droidar/src/de/rwth/setups/PlaceObjectsSetupTwo.java
index b5cce19..b5610ce 100644
--- a/droidar/src/de/rwth/setups/PlaceObjectsSetupTwo.java
+++ b/droidar/src/de/rwth/setups/PlaceObjectsSetupTwo.java
@@ -12,10 +12,10 @@
 import system.ErrorHandler;
 import system.EventManager;
 import util.Vec;
-import worldData.MoveComp;
-import worldData.Obj;
-import worldData.SystemUpdater;
-import worldData.World;
+import worlddata.MoveComp;
+import worlddata.Obj;
+import worlddata.SystemUpdater;
+import worlddata.World;
 import actions.Action;
 import actions.ActionBufferedCameraAR;
 import actions.ActionCalcRelativePos;
@@ -43,13 +43,13 @@ public void initFieldsIfNecessary() {
 		world = new World(camera);
 		viewPosCalcer = new ViewPosCalcerComp(camera, 150, 0.1f) {
 			@Override
-			public void onPositionUpdate(worldData.Updateable parent,
+			public void onPositionUpdate(worlddata.Updateable parent,
 					Vec targetVec) {
 				if (parent instanceof Obj) {
 					Obj obj = (Obj) parent;
 					MoveComp m = obj.getComp(MoveComp.class);
 					if (m != null) {
-						m.myTargetPos = targetVec;
+						m.mTargetPos = targetVec;
 					}
 				}
 			}
diff --git a/droidar/src/de/rwth/setups/PositionTestsSetup.java b/droidar/src/de/rwth/setups/PositionTestsSetup.java
index d3a5f92..77d3665 100644
--- a/droidar/src/de/rwth/setups/PositionTestsSetup.java
+++ b/droidar/src/de/rwth/setups/PositionTestsSetup.java
@@ -12,14 +12,13 @@
 import setup.ArSetup;
 import system.EventManager;
 import util.Vec;
-import worldData.SystemUpdater;
-import worldData.World;
+import worlddata.SystemUpdater;
+import worlddata.World;
 import actions.ActionCalcRelativePos;
 import actions.ActionMoveCameraBuffered;
 import actions.ActionRotateCameraBuffered;
 import android.R;
 import android.app.Activity;
-
 import commands.Command;
 import commands.DebugCommandPositionEvent;
 import commands.ui.CommandInUiThread;
diff --git a/droidar/src/de/rwth/setups/SensorTestSetup.java b/droidar/src/de/rwth/setups/SensorTestSetup.java
index a6e7c5d..e9adbba 100644
--- a/droidar/src/de/rwth/setups/SensorTestSetup.java
+++ b/droidar/src/de/rwth/setups/SensorTestSetup.java
@@ -14,15 +14,14 @@
 import system.ErrorHandler;
 import system.EventManager;
 import util.Vec;
-import worldData.SystemUpdater;
-import worldData.World;
+import worlddata.SystemUpdater;
+import worlddata.World;
 import actions.Action;
 import actions.ActionBufferedCameraAR;
 import actions.ActionMoveCameraBuffered;
 import actions.ActionRotateCameraBuffered;
 import actions.ActionUseCameraAngles2;
 import android.app.Activity;
-
 import commands.Command;
 
 public class SensorTestSetup extends ArSetup {
diff --git a/droidar/src/de/rwth/setups/StaticDemoSetup.java b/droidar/src/de/rwth/setups/StaticDemoSetup.java
index da30402..9867457 100644
--- a/droidar/src/de/rwth/setups/StaticDemoSetup.java
+++ b/droidar/src/de/rwth/setups/StaticDemoSetup.java
@@ -20,9 +20,9 @@
 import system.EventManager;
 import util.IO;
 import util.Vec;
-import worldData.Obj;
-import worldData.SystemUpdater;
-import worldData.World;
+import worlddata.Obj;
+import worlddata.SystemUpdater;
+import worlddata.World;
 import actions.ActionMoveCameraBuffered;
 import actions.ActionRotateCameraBuffered;
 import actions.ActionWASDMovement;
diff --git a/droidar/src/de/rwth/setups/TestSetup.java b/droidar/src/de/rwth/setups/TestSetup.java
index 06d309c..318d543 100644
--- a/droidar/src/de/rwth/setups/TestSetup.java
+++ b/droidar/src/de/rwth/setups/TestSetup.java
@@ -7,7 +7,7 @@
 import gl.scenegraph.Shape;
 import setup.DefaultArSetup;
 import util.Vec;
-import worldData.World;
+import worlddata.World;
 
 public class TestSetup extends DefaultArSetup {
 	@Override
diff --git a/droidar/src/de/rwth/setups/TimeModifier.java b/droidar/src/de/rwth/setups/TimeModifier.java
index ca25f74..d447851 100644
--- a/droidar/src/de/rwth/setups/TimeModifier.java
+++ b/droidar/src/de/rwth/setups/TimeModifier.java
@@ -5,9 +5,9 @@
 import javax.microedition.khronos.opengles.GL10;
 
 import util.Calculus;
-import worldData.RenderableEntity;
-import worldData.Updateable;
-import worldData.Visitor;
+import worlddata.RenderableEntity;
+import worlddata.Updateable;
+import worlddata.Visitor;
 import android.util.Log;
 
 public class TimeModifier implements RenderableEntity {
diff --git a/droidar/src/geo/GeoCalcer.java b/droidar/src/geo/GeoCalcer.java
index 3cc3940..c5034f9 100644
--- a/droidar/src/geo/GeoCalcer.java
+++ b/droidar/src/geo/GeoCalcer.java
@@ -2,8 +2,8 @@
 
 import system.Container;
 import util.Log;
-import worldData.LargeWorld;
-import worldData.Visitor;
+import worlddata.LargeWorld;
+import worlddata.Visitor;
 
 public class GeoCalcer extends Visitor {
 
diff --git a/droidar/src/geo/GeoGraph.java b/droidar/src/geo/GeoGraph.java
index aed7d96..bdee925 100644
--- a/droidar/src/geo/GeoGraph.java
+++ b/droidar/src/geo/GeoGraph.java
@@ -12,10 +12,10 @@
 import util.EfficientList;
 import util.EfficientListQualified;
 import util.Log;
-import worldData.AbstractObj;
-import worldData.Updateable;
-import worldData.Visitor;
-import worldData.World;
+import worlddata.AbstractObj;
+import worlddata.Updateable;
+import worlddata.Visitor;
+import worlddata.World;
 
 /**
  * A {@link GeoGraph} is a simple graph which holds {@link GeoObj}s and supports
@@ -498,12 +498,12 @@ public void setNonDirectional(boolean nonDirectional) {
 	@Override
 	public String toString() {
 		if (myNodes != null) {
-			if (HasInfoObject())
+			if (hasInfoObject())
 				return "GeoGraph '" + getInfoObject().getShortDescr()
 						+ "' (size=" + myNodes.myLength + ")";
 			return "GeoGraph (size=" + myNodes.myLength + ")";
 		} else {
-			if (HasInfoObject())
+			if (hasInfoObject())
 				return "GeoGraph '" + getInfoObject().getShortDescr()
 						+ "' (size=no objects in graph)";
 			return "GeoGraph (size=no objects in graph)";
diff --git a/droidar/src/geo/GeoObj.java b/droidar/src/geo/GeoObj.java
index e91f802..236d138 100644
--- a/droidar/src/geo/GeoObj.java
+++ b/droidar/src/geo/GeoObj.java
@@ -9,9 +9,9 @@
 import util.HasDebugInformation;
 import util.Log;
 import util.Vec;
-import worldData.Entity;
-import worldData.Obj;
-import worldData.Visitor;
+import worlddata.Entity;
+import worlddata.Obj;
+import worlddata.Visitor;
 import actions.ActionCalcRelativePos;
 import android.location.Address;
 import android.location.Location;
@@ -206,7 +206,7 @@ public void setComp(Entity comp) {
 	/*
 	 * (non-Javadoc)
 	 * 
-	 * @see worldData.Obj#getPosition()
+	 * @see worlddata.Obj#getPosition()
 	 */
 	@Override
 	public Vec getPosition() {
diff --git a/droidar/src/geo/SimpleNodeEdgeListener.java b/droidar/src/geo/SimpleNodeEdgeListener.java
index ef4f2ae..239cc0e 100644
--- a/droidar/src/geo/SimpleNodeEdgeListener.java
+++ b/droidar/src/geo/SimpleNodeEdgeListener.java
@@ -9,9 +9,8 @@
 import util.EfficientList;
 import util.Log;
 import util.Vec;
-import worldData.Entity;
-import worldData.Obj;
-
+import worlddata.Entity;
+import worlddata.Obj;
 import components.ProximitySensor;
 
 public abstract class SimpleNodeEdgeListener implements NodeListener,
diff --git a/droidar/src/gl/GLCamera.java b/droidar/src/gl/GLCamera.java
index 9ff5e4b..2a1a205 100644
--- a/droidar/src/gl/GLCamera.java
+++ b/droidar/src/gl/GLCamera.java
@@ -10,8 +10,8 @@
 import util.HasDebugInformation;
 import util.Log;
 import util.Vec;
-import worldData.MoveComp;
-import worldData.Updateable;
+import worlddata.MoveComp;
+import worlddata.Updateable;
 import actions.ActionUseCameraAngles2;
 import android.location.Location;
 import android.opengl.Matrix;
@@ -136,7 +136,7 @@ public void setNewPosition(Vec cameraPosition) {
 		if (myPosition == null) {
 			myPosition = new Vec();
 		}
-		myMover.myTargetPos = cameraPosition;
+		myMover.mTargetPos = cameraPosition;
 	}
 
 	/**
@@ -147,7 +147,7 @@ public void setNewPosition(Vec cameraPosition) {
 	 * @return the {@link Vec} (x,y,z)
 	 */
 	public Vec getMyNewPosition() {
-		return myMover.myTargetPos;
+		return myMover.mTargetPos;
 	}
 
 	public void setNewCameraOffset(Vec newCameraOffset) {
@@ -463,7 +463,7 @@ public void setNewRotation(float xAngle, float yAngle, float zAngle) {
 	 * @param deltaY
 	 */
 	public synchronized void changeXYPositionBuffered(float deltaX, float deltaY) {
-		myMover.myTargetPos.add(deltaX, deltaY, 0);
+		myMover.mTargetPos.add(deltaX, deltaY, 0);
 	}
 
 	/**
@@ -533,7 +533,7 @@ public void changeZAngleBuffered(float deltaZ) {
 	 *            eg. -10 to move the camera 10 meters down
 	 */
 	public void changeZPositionBuffered(float deltaZ) {
-		myMover.myTargetPos.add(0, 0, deltaZ);
+		myMover.mTargetPos.add(0, 0, deltaZ);
 	}
 
 	/**
@@ -542,12 +542,12 @@ public void changeZPositionBuffered(float deltaZ) {
 	 */
 	public void resetPosition(boolean resetZValueToo) {
 		float pz = myPosition.z;
-		float npz = myMover.myTargetPos.z;
+		float npz = myMover.mTargetPos.z;
 		myPosition.setToZero();
-		myMover.myTargetPos.setToZero();
+		myMover.mTargetPos.setToZero();
 		if (!resetZValueToo) {
 			myPosition.z = pz;
-			myMover.myTargetPos.z = npz;
+			myMover.mTargetPos.z = npz;
 		}
 	}
 
@@ -559,7 +559,7 @@ public void resetPosition() {
 	}
 
 	public void changeNewPosition(float deltaX, float deltaY, float deltaZ) {
-		myMover.myTargetPos.add(deltaX, deltaY, deltaZ);
+		myMover.mTargetPos.add(deltaX, deltaY, deltaZ);
 	}
 
 	/**
@@ -571,7 +571,7 @@ public void changeNewPosition(float deltaX, float deltaY, float deltaZ) {
 	 *            the height of the camera
 	 */
 	public void setNewPosition(float x, float y, float z) {
-		myMover.myTargetPos.setTo(x, y, z);
+		myMover.mTargetPos.setTo(x, y, z);
 
 	}
 
@@ -582,7 +582,7 @@ public void setNewPosition(float x, float y, float z) {
 	 *            positive means north of zero pos (latitude direction)
 	 */
 	public void setNewPosition(float x, float y) {
-		myMover.myTargetPos.setTo(x, y);
+		myMover.mTargetPos.setTo(x, y);
 	}
 
 	public Vec getNewCameraOffset() {
@@ -681,7 +681,7 @@ public float[] getRotationMatrix() {
 	public void showDebugInformation() {
 		Log.w(LOG_TAG, "Infos about GLCamera:");
 		Log.w(LOG_TAG, "   > myPosition=" + myPosition);
-		Log.w(LOG_TAG, "   > myMover.myTargetPos=" + myMover.myTargetPos);
+		Log.w(LOG_TAG, "   > myMover.myTargetPos=" + myMover.mTargetPos);
 		Log.w(LOG_TAG, "   > myOffset=" + myOffset);
 		Log.w(LOG_TAG, "   > myNewOffset=" + myNewOffset);
 		Log.w(LOG_TAG, "   > myRotationVec=" + myRotationVec);
diff --git a/droidar/src/gl/GLFactory.java b/droidar/src/gl/GLFactory.java
index 5631ad7..e95b26b 100644
--- a/droidar/src/gl/GLFactory.java
+++ b/droidar/src/gl/GLFactory.java
@@ -16,9 +16,9 @@
 import util.IO;
 import util.Log;
 import util.Vec;
-import worldData.Obj;
-import worldData.Visitor;
-import worldData.World;
+import worlddata.Obj;
+import worlddata.Visitor;
+import worlddata.World;
 import android.content.Context;
 import android.graphics.Bitmap;
 import android.graphics.Typeface;
diff --git a/droidar/src/gl/GLText.java b/droidar/src/gl/GLText.java
index bb1dd5f..4183955 100644
--- a/droidar/src/gl/GLText.java
+++ b/droidar/src/gl/GLText.java
@@ -10,7 +10,7 @@
 
 import util.Log;
 import util.Vec;
-import worldData.Visitor;
+import worlddata.Visitor;
 import android.content.Context;
 import android.graphics.Bitmap;
 import android.graphics.Typeface;
diff --git a/droidar/src/gl/LightSource.java b/droidar/src/gl/LightSource.java
index 23742c4..1cb0c08 100644
--- a/droidar/src/gl/LightSource.java
+++ b/droidar/src/gl/LightSource.java
@@ -8,7 +8,7 @@
 
 import util.Log;
 import util.Vec;
-import worldData.Visitor;
+import worlddata.Visitor;
 
 /**
  * Great tutorials:
diff --git a/droidar/src/gl/animations/AnimationAlphaBlend.java b/droidar/src/gl/animations/AnimationAlphaBlend.java
index 9eddde0..2d44a0f 100644
--- a/droidar/src/gl/animations/AnimationAlphaBlend.java
+++ b/droidar/src/gl/animations/AnimationAlphaBlend.java
@@ -7,8 +7,8 @@
 import javax.microedition.khronos.opengles.GL10;
 
 import util.Vec;
-import worldData.Updateable;
-import worldData.Visitor;
+import worlddata.Updateable;
+import worlddata.Visitor;
 
 /**
  * TODO what is the difference between this and ColorMorph? what was the intend?
diff --git a/droidar/src/gl/animations/AnimationBounce.java b/droidar/src/gl/animations/AnimationBounce.java
index 66cc345..f34edc1 100644
--- a/droidar/src/gl/animations/AnimationBounce.java
+++ b/droidar/src/gl/animations/AnimationBounce.java
@@ -5,8 +5,8 @@
 import javax.microedition.khronos.opengles.GL10;
 
 import util.Vec;
-import worldData.Updateable;
-import worldData.Visitor;
+import worlddata.Updateable;
+import worlddata.Visitor;
 
 public class AnimationBounce extends GLAnimation {
 
diff --git a/droidar/src/gl/animations/AnimationColorBounce.java b/droidar/src/gl/animations/AnimationColorBounce.java
index f0bc2d7..e582ce2 100644
--- a/droidar/src/gl/animations/AnimationColorBounce.java
+++ b/droidar/src/gl/animations/AnimationColorBounce.java
@@ -7,8 +7,8 @@
 import javax.microedition.khronos.opengles.GL10;
 
 import util.Vec;
-import worldData.Updateable;
-import worldData.Visitor;
+import worlddata.Updateable;
+import worlddata.Visitor;
 
 public class AnimationColorBounce extends GLAnimation {
 
diff --git a/droidar/src/gl/animations/AnimationColorMorph.java b/droidar/src/gl/animations/AnimationColorMorph.java
index 6785792..d79fa70 100644
--- a/droidar/src/gl/animations/AnimationColorMorph.java
+++ b/droidar/src/gl/animations/AnimationColorMorph.java
@@ -8,8 +8,8 @@
 
 import util.Log;
 import util.Vec;
-import worldData.Updateable;
-import worldData.Visitor;
+import worlddata.Updateable;
+import worlddata.Visitor;
 
 public class AnimationColorMorph extends GLAnimation {
 
diff --git a/droidar/src/gl/animations/AnimationFaceToCamera.java b/droidar/src/gl/animations/AnimationFaceToCamera.java
index 6cab5d9..92b65d1 100644
--- a/droidar/src/gl/animations/AnimationFaceToCamera.java
+++ b/droidar/src/gl/animations/AnimationFaceToCamera.java
@@ -7,8 +7,8 @@
 import javax.microedition.khronos.opengles.GL10;
 
 import util.Vec;
-import worldData.Updateable;
-import worldData.Visitor;
+import worlddata.Updateable;
+import worlddata.Visitor;
 
 public class AnimationFaceToCamera extends GLAnimation {
 
diff --git a/droidar/src/gl/animations/AnimationGrow.java b/droidar/src/gl/animations/AnimationGrow.java
index 5401e1c..8c50359 100644
--- a/droidar/src/gl/animations/AnimationGrow.java
+++ b/droidar/src/gl/animations/AnimationGrow.java
@@ -5,9 +5,9 @@
 import javax.microedition.khronos.opengles.GL10;
 
 import util.Log;
-import worldData.UpdateTimer;
-import worldData.Updateable;
-import worldData.Visitor;
+import worlddata.UpdateTimer;
+import worlddata.Updateable;
+import worlddata.Visitor;
 
 public class AnimationGrow extends GLAnimation {
 
diff --git a/droidar/src/gl/animations/AnimationMove.java b/droidar/src/gl/animations/AnimationMove.java
index eb92c24..5672954 100644
--- a/droidar/src/gl/animations/AnimationMove.java
+++ b/droidar/src/gl/animations/AnimationMove.java
@@ -5,8 +5,8 @@
 import javax.microedition.khronos.opengles.GL10;
 
 import util.Vec;
-import worldData.Updateable;
-import worldData.Visitor;
+import worlddata.Updateable;
+import worlddata.Visitor;
 
 public class AnimationMove extends GLAnimation {
 
diff --git a/droidar/src/gl/animations/AnimationPulse.java b/droidar/src/gl/animations/AnimationPulse.java
index 7ef3faf..95fbc1a 100644
--- a/droidar/src/gl/animations/AnimationPulse.java
+++ b/droidar/src/gl/animations/AnimationPulse.java
@@ -5,8 +5,8 @@
 import javax.microedition.khronos.opengles.GL10;
 
 import util.Vec;
-import worldData.Updateable;
-import worldData.Visitor;
+import worlddata.Updateable;
+import worlddata.Visitor;
 
 public class AnimationPulse extends GLAnimation {
 
diff --git a/droidar/src/gl/animations/AnimationRotate.java b/droidar/src/gl/animations/AnimationRotate.java
index b027601..2cf535f 100644
--- a/droidar/src/gl/animations/AnimationRotate.java
+++ b/droidar/src/gl/animations/AnimationRotate.java
@@ -6,8 +6,8 @@
 import javax.microedition.khronos.opengles.GL10;
 
 import util.Vec;
-import worldData.Updateable;
-import worldData.Visitor;
+import worlddata.Updateable;
+import worlddata.Visitor;
 
 /**
  * This animation rotates a {@link MeshComponent}
diff --git a/droidar/src/gl/animations/AnimationShrink.java b/droidar/src/gl/animations/AnimationShrink.java
index d89327d..8e1f090 100644
--- a/droidar/src/gl/animations/AnimationShrink.java
+++ b/droidar/src/gl/animations/AnimationShrink.java
@@ -5,8 +5,8 @@
 import javax.microedition.khronos.opengles.GL10;
 
 import util.Log;
-import worldData.Updateable;
-import worldData.Visitor;
+import worlddata.Updateable;
+import worlddata.Visitor;
 
 public class AnimationShrink extends GLAnimation {
 
diff --git a/droidar/src/gl/animations/AnimationSwingRotate.java b/droidar/src/gl/animations/AnimationSwingRotate.java
index b228432..e8f9ad8 100644
--- a/droidar/src/gl/animations/AnimationSwingRotate.java
+++ b/droidar/src/gl/animations/AnimationSwingRotate.java
@@ -5,8 +5,8 @@
 import javax.microedition.khronos.opengles.GL10;
 
 import util.Vec;
-import worldData.Updateable;
-import worldData.Visitor;
+import worlddata.Updateable;
+import worlddata.Visitor;
 
 /**
  * This animation simulated the movement of a metronome. For more details see
diff --git a/droidar/src/gl/animations/GLAnimation.java b/droidar/src/gl/animations/GLAnimation.java
index 5e3d183..5ad16f7 100644
--- a/droidar/src/gl/animations/GLAnimation.java
+++ b/droidar/src/gl/animations/GLAnimation.java
@@ -1,8 +1,8 @@
 package gl.animations;
 
 import util.Log;
-import worldData.RenderableEntity;
-import worldData.Updateable;
+import worlddata.RenderableEntity;
+import worlddata.Updateable;
 
 /**
  * An animation can be used to do predefined movements (which might be continous
diff --git a/droidar/src/gl/scenegraph/MeshComponent.java b/droidar/src/gl/scenegraph/MeshComponent.java
index d715ba0..2a82e4a 100644
--- a/droidar/src/gl/scenegraph/MeshComponent.java
+++ b/droidar/src/gl/scenegraph/MeshComponent.java
@@ -19,11 +19,10 @@
 import util.Log;
 import util.Vec;
 import util.Wrapper;
-import worldData.Obj;
-import worldData.RenderableEntity;
-import worldData.Updateable;
+import worlddata.Obj;
+import worlddata.RenderableEntity;
+import worlddata.Updateable;
 import android.opengl.Matrix;
-
 import commands.Command;
 import commands.undoable.UndoableCommand;
 
diff --git a/droidar/src/gl/scenegraph/RenderList.java b/droidar/src/gl/scenegraph/RenderList.java
index 5a7149a..d590c94 100644
--- a/droidar/src/gl/scenegraph/RenderList.java
+++ b/droidar/src/gl/scenegraph/RenderList.java
@@ -7,9 +7,9 @@
 import system.Container;
 import util.EfficientList;
 import util.Log;
-import worldData.RenderableEntity;
-import worldData.Updateable;
-import worldData.Visitor;
+import worlddata.RenderableEntity;
+import worlddata.Updateable;
+import worlddata.Visitor;
 
 public class RenderList implements RenderableEntity,
 		Container {
diff --git a/droidar/src/gl/scenegraph/Shape.java b/droidar/src/gl/scenegraph/Shape.java
index dbb0265..67fd6ae 100644
--- a/droidar/src/gl/scenegraph/Shape.java
+++ b/droidar/src/gl/scenegraph/Shape.java
@@ -8,7 +8,7 @@
 import javax.microedition.khronos.opengles.GL10;
 
 import util.Vec;
-import worldData.Visitor;
+import worlddata.Visitor;
 
 public class Shape extends MeshComponent {
 
diff --git a/droidar/src/gui/RadarView.java b/droidar/src/gui/RadarView.java
index 9fb962b..5e755ff 100644
--- a/droidar/src/gui/RadarView.java
+++ b/droidar/src/gui/RadarView.java
@@ -6,11 +6,11 @@
 import gl.scenegraph.Shape;
 import util.EfficientList;
 import util.Vec;
-import worldData.Obj;
-import worldData.RenderableEntity;
-import worldData.UpdateTimer;
-import worldData.Updateable;
-import worldData.World;
+import worlddata.Obj;
+import worlddata.RenderableEntity;
+import worlddata.UpdateTimer;
+import worlddata.Updateable;
+import worlddata.World;
 import android.app.Activity;
 import android.content.Context;
 import android.graphics.Bitmap;
diff --git a/droidar/src/setup/ArSetup.java b/droidar/src/setup/ArSetup.java
index c359bdf..5ffe4f1 100644
--- a/droidar/src/setup/ArSetup.java
+++ b/droidar/src/setup/ArSetup.java
@@ -10,7 +10,7 @@
 import system.TaskManager;
 import util.EfficientList;
 import util.Vec;
-import worldData.SystemUpdater;
+import worlddata.SystemUpdater;
 import android.app.Activity;
 import android.view.Display;
 import android.view.KeyEvent;
@@ -177,7 +177,7 @@ private void keepScreenOn() {
 
 	/**
 	 * Retrieve the system updater.
-	 * @return - {@link worldData.SystemUpdater}
+	 * @return - {@link worlddata.SystemUpdater}
 	 */
 	public SystemUpdater getSystemUpdater() {
 		return mWorldUpdater;
diff --git a/droidar/src/setup/DefaultArSetup.java b/droidar/src/setup/DefaultArSetup.java
index 4e790a8..f1e022b 100644
--- a/droidar/src/setup/DefaultArSetup.java
+++ b/droidar/src/setup/DefaultArSetup.java
@@ -10,8 +10,8 @@
 import logger.ARLogger;
 import system.EventManager;
 import util.Vec;
-import worldData.SystemUpdater;
-import worldData.World;
+import worlddata.SystemUpdater;
+import worlddata.World;
 import actions.ActionCalcRelativePos;
 import actions.ActionMoveCameraBuffered;
 import actions.ActionRotateCameraBuffered;
diff --git a/droidar/src/setup/ISetupSteps.java b/droidar/src/setup/ISetupSteps.java
index 6550090..eaa6789 100644
--- a/droidar/src/setup/ISetupSteps.java
+++ b/droidar/src/setup/ISetupSteps.java
@@ -10,7 +10,7 @@
 import java.util.ArrayList;
 
 import system.EventManager;
-import worldData.SystemUpdater;
+import worlddata.SystemUpdater;
 import android.app.Activity;
 import android.widget.FrameLayout;
 
@@ -49,7 +49,7 @@ public interface ISetupSteps {
 	 * and then you can use the {@link GLFactory} object to add objects to the
 	 * created world. When your world is build, add it to the
 	 * {@link GL1Renderer} object by calling
-	 * {@link GL1Renderer#addRenderElement(worldData.Renderable)}
+	 * {@link GL1Renderer#addRenderElement(worlddata.Renderable)}
 	 * 
 	 * @param glRenderer
 	 *            here you should add your world(s)
@@ -99,14 +99,14 @@ void addActionsToEvents(EventManager eventManager,
 			CustomGLSurfaceView arView, SystemUpdater updater);
 	
 	/**
-	 * All elements (normally that should only be {@link worldData.World}s) which should
+	 * All elements (normally that should only be {@link worlddata.World}s) which should
 	 * be updated have to be added to the {@link system.SystemUpdater}. This update
 	 * process is independent to the rendering process and can be used for all
 	 * system-logic which has to be done periodically
 	 * 
 	 * @param updater
 	 *            add anything you want to update to this updater via
-	 *            {@link SystemUpdater#addObjectToUpdateCycle(worldData.Updateable)}
+	 *            {@link SystemUpdater#addObjectToUpdateCycle(worlddata.Updateable)}
 	 */
 	void addElementsToUpdateThread(SystemUpdater updater);
 	
diff --git a/droidar/src/tests/GeoTests.java b/droidar/src/tests/GeoTests.java
index 7583c57..48eb11c 100644
--- a/droidar/src/tests/GeoTests.java
+++ b/droidar/src/tests/GeoTests.java
@@ -5,10 +5,9 @@
 import gl.GLCamera;
 import gl.GLFactory;
 import util.Vec;
-import worldData.World;
+import worlddata.World;
 import actions.ActionCalcRelativePos;
 import android.util.Log;
-
 import commands.DebugCommandPositionEvent;
 
 public class GeoTests extends SimpleTesting {
diff --git a/droidar/src/tests/SystemTests.java b/droidar/src/tests/SystemTests.java
index fef728a..9aeb2e2 100644
--- a/droidar/src/tests/SystemTests.java
+++ b/droidar/src/tests/SystemTests.java
@@ -9,9 +9,8 @@
 import util.Log;
 import util.Vec;
 import util.Wrapper;
-import worldData.Entity;
-import worldData.Obj;
-
+import worlddata.Entity;
+import worlddata.Obj;
 import components.ProximitySensor;
 
 public class SystemTests extends SimpleTesting {
diff --git a/droidar/src/tests/WorldTests.java b/droidar/src/tests/WorldTests.java
index d9e625c..4a37006 100644
--- a/droidar/src/tests/WorldTests.java
+++ b/droidar/src/tests/WorldTests.java
@@ -7,8 +7,8 @@
 import gl.scenegraph.Shape;
 import system.Container;
 import util.Vec;
-import worldData.Obj;
-import worldData.World;
+import worlddata.Obj;
+import worlddata.World;
 
 public class WorldTests extends SimpleTesting {
 
diff --git a/droidar/src/worldData/Entity.java b/droidar/src/worldData/Entity.java
deleted file mode 100644
index 6c9ce7f..0000000
--- a/droidar/src/worldData/Entity.java
+++ /dev/null
@@ -1,31 +0,0 @@
-package worldData;
-
-import components.Visitable;
-
-public interface Entity extends Updateable, Visitable {
-
-	/**
-	 * This method can be called to move through the scene graph. Every subclass
-	 * of {@link Entity} will have to take care that it refreshes its parent as
-	 * soon as {@link Updateable#update(float, Updateable)} is called. 
- *
- * See also {@link Entity#setMyParent(Updateable)} - * - * @return - */ - public Updateable getMyParent(); - - /** - * This should be called as the first thing in - * {@link Updateable#update(float, Updateable)} if the component ha s - * children because these children might call {@link Entity#getMyParent()} - * to navigate through the Scene Graph - * - * If the component does not have any children this method can return null - * because no child will ever call it - * - * @param parent - */ - public void setMyParent(Updateable parent); - -} diff --git a/droidar/src/worldData/RenderableEntity.java b/droidar/src/worldData/RenderableEntity.java deleted file mode 100644 index 4511d6f..0000000 --- a/droidar/src/worldData/RenderableEntity.java +++ /dev/null @@ -1,26 +0,0 @@ -package worldData; - -import gl.LightSource; -import gl.Renderable; -import gl.scenegraph.MeshComponent; -import gl.scenegraph.RenderList; -import gl.scenegraph.Shape; - -/** - * This is the basic interface for any object which hat to do with Rendering and - * which also needs to be updated from time to time.
- *
- * - * The existing important subclasses are:
- * - * - {@link RenderList}: It is a group of {@link RenderableEntity}s
- * - * - {@link MeshComponent}: A basic {@link Shape} e.g. to draw OpenGL objects or - * {@link LightSource} to add lighning effects to a scene
- * - * @author Spobo - * - */ -public interface RenderableEntity extends Entity, Renderable { - -} diff --git a/droidar/src/worldData/AbstractObj.java b/droidar/src/worlddata/AbstractObj.java similarity index 86% rename from droidar/src/worldData/AbstractObj.java rename to droidar/src/worlddata/AbstractObj.java index 3916333..41c04d4 100644 --- a/droidar/src/worldData/AbstractObj.java +++ b/droidar/src/worlddata/AbstractObj.java @@ -1,4 +1,4 @@ -package worldData; +package worlddata; import gui.ListItem; import gui.MetaInfos; @@ -12,6 +12,9 @@ import commands.Command; +/** + * Default implementation for Objs. + */ public abstract class AbstractObj implements HasInfosInterface, ListItem, SelectionListener, EditItem, RenderableEntity { @@ -34,7 +37,7 @@ public MetaInfos getInfoObject() { } @Override - public boolean HasInfoObject() { + public boolean hasInfoObject() { if (mInfoObj != null) { return true; } @@ -101,10 +104,16 @@ public void setOnMapClickCommand(Command c) { mOnMapClickCommand = c; } + /** + * @param clickCommand - {@link commands.Command} + */ public void setListClickCommand(Command clickCommand) { mListClickCommand = clickCommand; } + /** + * @param longClickCommand - {@link commands.Command} + */ public void setListLongClickCommand(Command longClickCommand) { mListLongClickCommand = longClickCommand; } @@ -120,8 +129,11 @@ public View getMyListItemView(View viewToUseIfNotNull, ViewGroup parentView) { parentView); } - public void setmItemGuiListener(ItemGuiListener mItemGuiListener) { - this.mItemGuiListener = mItemGuiListener; + /** + * @param pItemGuiListener - {@link listeners.ItemGuiListener} + */ + public void setmItemGuiListener(ItemGuiListener pItemGuiListener) { + mItemGuiListener = pItemGuiListener; } @Override @@ -131,7 +143,7 @@ public void customizeScreen(ModifierGroup g, Object message) { @Override public String toString() { - if (HasInfoObject()) { + if (hasInfoObject()) { return getInfoObject().getShortDescr(); } return super.toString(); diff --git a/droidar/src/worlddata/Entity.java b/droidar/src/worlddata/Entity.java new file mode 100644 index 0000000..80f0a31 --- /dev/null +++ b/droidar/src/worlddata/Entity.java @@ -0,0 +1,33 @@ +package worlddata; + +import components.Visitable; +/** + * Used for relationships between Objs. + */ +public interface Entity extends Updateable, Visitable { + + /** + * This method can be called to move through the scene graph. Every subclass + * of {@link Entity} will have to take care that it refreshes its parent as + * soon as {@link worlddata.Updateable#update(float, worlddata.Updateable)} is called.
+ *
. + * See also {@link Entity#setMyParent(worlddata.Updateable)} + * + * @return - {@link worlddata.Updateable} + */ + Updateable getMyParent(); + + /** + * This should be called as the first thing in + * {@link worlddata.Updateable#update(float, worlddata.Updateable)} if the component ha s + * children because these children might call {@link Entity#getMyParent()} + * to navigate through the Scene Graph. + * + * If the component does not have any children this method can return null + * because no child will ever call it + * + * @param parent - {@link worlddata.Updateable} + */ + void setMyParent(Updateable parent); + +} diff --git a/droidar/src/worldData/EntityList.java b/droidar/src/worlddata/EntityList.java similarity index 59% rename from droidar/src/worldData/EntityList.java rename to droidar/src/worlddata/EntityList.java index abc8fd4..abf1915 100644 --- a/droidar/src/worldData/EntityList.java +++ b/droidar/src/worlddata/EntityList.java @@ -1,39 +1,42 @@ -package worldData; +package worlddata; import system.Container; import util.EfficientList; import util.Log; - +/** + * Essentially a list class that contains multiple entities. + */ public class EntityList implements Entity, Container { private static final String LOG_TAG = "RenderList"; - EfficientList myItems = new EfficientList(); - private boolean isClearedAtLeastOnce; - private Updateable myParent; + private EfficientList mItems = new EfficientList(); + private boolean mIsClearedAtLeastOnce; + private Updateable mParent; @Override public Updateable getMyParent() { - return myParent; + return mParent; } @Override public void setMyParent(Updateable parent) { - myParent = parent; + mParent = parent; } @Override public boolean update(float timeDelta, Updateable parent) { setMyParent(parent); - for (int i = 0; i < myItems.myLength; i++) { - if (!myItems.get(i).update(timeDelta, parent)) { - Log.d(LOG_TAG, "Item " + myItems.get(i) + for (int i = 0; i < mItems.myLength; i++) { + if (!mItems.get(i).update(timeDelta, parent)) { + Log.d(LOG_TAG, "Item " + mItems.get(i) + " will now be removed from RenderList because it " + "is finished (returned false on update())"); - myItems.remove(myItems.get(i)); + mItems.remove(mItems.get(i)); } } - if (myItems.myLength == 0) + if (mItems.myLength == 0) { return false; + } return true; } @@ -43,42 +46,43 @@ public boolean add(Entity child) { Log.e(LOG_TAG, "Not allowed to add object to itself!"); return false; } - return myItems.add(child); + return mItems.add(child); } @Override public boolean remove(Entity child) { - return myItems.remove(child); + return mItems.remove(child); } @Override public void clear() { - myItems.clear(); - isClearedAtLeastOnce = true; + mItems.clear(); + mIsClearedAtLeastOnce = true; } @Override public boolean isCleared() { - return isClearedAtLeastOnce; + return mIsClearedAtLeastOnce; } @SuppressWarnings("rawtypes") @Override public void removeEmptyItems() { - for (int i = 0; i < myItems.myLength; i++) { - if (((Container) myItems.get(i)).isCleared()) - myItems.remove(myItems.get(i)); + for (int i = 0; i < mItems.myLength; i++) { + if (((Container) mItems.get(i)).isCleared()) { + mItems.remove(mItems.get(i)); + } } } @Override public int length() { - return myItems.myLength; + return mItems.myLength; } @Override public EfficientList getAllItems() { - return myItems; + return mItems; } @Override @@ -88,6 +92,6 @@ public boolean accept(Visitor visitor) { @Override public boolean insert(int pos, Entity item) { - return myItems.insert(pos, item); + return mItems.insert(pos, item); } } diff --git a/droidar/src/worldData/HasInfosInterface.java b/droidar/src/worlddata/HasInfosInterface.java similarity index 83% rename from droidar/src/worldData/HasInfosInterface.java rename to droidar/src/worlddata/HasInfosInterface.java index 7d8be18..30ba08f 100644 --- a/droidar/src/worldData/HasInfosInterface.java +++ b/droidar/src/worlddata/HasInfosInterface.java @@ -1,4 +1,4 @@ -package worldData; +package worlddata; import gui.MetaInfos; @@ -15,11 +15,11 @@ public interface HasInfosInterface { * @return normally not null, on default a infoObject is initialized of * there was none before this request */ - public MetaInfos getInfoObject(); + MetaInfos getInfoObject(); /** * @return true if the object currently has a info object */ - public boolean HasInfoObject(); + boolean hasInfoObject(); } diff --git a/droidar/src/worldData/LargeWorld.java b/droidar/src/worlddata/LargeWorld.java similarity index 87% rename from droidar/src/worldData/LargeWorld.java rename to droidar/src/worlddata/LargeWorld.java index bfae69d..f6c2caf 100644 --- a/droidar/src/worldData/LargeWorld.java +++ b/droidar/src/worlddata/LargeWorld.java @@ -1,4 +1,4 @@ -package worldData; +package worlddata; import gl.GLCamera; import gl.HasPosition; @@ -19,9 +19,9 @@ @Deprecated public class LargeWorld extends World { - private float myRenderDistance; - private float myRecalcDistanceMin; - private float myRecalcDistanceMax; + private float mRenderDistance; + private float mRecalcDistanceMin; + private float mRecalcDistanceMax; private QuadTree tree; @SuppressWarnings("rawtypes") @@ -33,9 +33,9 @@ public class LargeWorld extends World { public LargeWorld(GLCamera glCamera, float renderDistance, float recalcDistance) { super(glCamera); - myRenderDistance = renderDistance; - myRecalcDistanceMin = -recalcDistance; - myRecalcDistanceMax = recalcDistance; + mRenderDistance = renderDistance; + mRecalcDistanceMin = -recalcDistance; + mRecalcDistanceMax = recalcDistance; tree = new QuadTree(); itemsListener = tree.new ResultListener() { @@ -135,10 +135,10 @@ public boolean update(float timeDelta, Updateable parent) { private synchronized EfficientList getList(float x, float y) { if (itemsInRange != null - && needsNoRecalculation(x - oldX, myRecalcDistanceMin, - myRecalcDistanceMax) - && needsNoRecalculation(y - oldY, myRecalcDistanceMin, - myRecalcDistanceMax)) { + && needsNoRecalculation(x - oldX, mRecalcDistanceMin, + mRecalcDistanceMax) + && needsNoRecalculation(y - oldY, mRecalcDistanceMin, + mRecalcDistanceMax)) { return itemsInRange; } else { if (itemsInRange == null) @@ -147,7 +147,7 @@ && needsNoRecalculation(y - oldY, myRecalcDistanceMin, itemsInRange.clear(); oldX = x; oldY = y; - tree.findInArea(itemsListener, x, y, myRenderDistance); + tree.findInArea(itemsListener, x, y, mRenderDistance); return itemsInRange; } } diff --git a/droidar/src/worldData/MoveComp.java b/droidar/src/worlddata/MoveComp.java similarity index 66% rename from droidar/src/worldData/MoveComp.java rename to droidar/src/worlddata/MoveComp.java index 834ca27..7e1da0f 100644 --- a/droidar/src/worldData/MoveComp.java +++ b/droidar/src/worlddata/MoveComp.java @@ -1,8 +1,7 @@ -package worldData; +package worlddata; import gl.HasPosition; import gl.Renderable; -import gl.scenegraph.MeshComponent; import javax.microedition.khronos.opengles.GL10; @@ -10,7 +9,7 @@ /** * This class can be used to move any {@link Entity} which implements the - * {@link HasPosition} interface (like {@link Obj} or {@link MeshComponent}) + * {@link HasPosition} interface (like {@link Obj} or {@link gl.scenegraph.MeshComponent}). * * @author Spobo * @@ -18,12 +17,12 @@ public class MoveComp implements RenderableEntity { /** - * this vector is the new position, where to send the {@link MeshComponent} - * of the parent {@link HasPosition} to + * this vector is the new position, where to send the {@link gl.scenegraph.MeshComponent} + * of the parent {@link HasPosition} to. */ - public Vec myTargetPos = new Vec(); - private float mySpeedFactor; - private Updateable myParent; + public Vec mTargetPos = new Vec(); + private float mSpeedFactor; + private Updateable mParent; /** * @param speedFactor @@ -31,7 +30,7 @@ public class MoveComp implements RenderableEntity { * nearly like instant placing so values should be < 20! */ public MoveComp(float speedFactor) { - this.mySpeedFactor = speedFactor; + this.mSpeedFactor = speedFactor; } @Override @@ -42,12 +41,12 @@ public boolean accept(Visitor visitor) { @Override public Updateable getMyParent() { - return myParent; + return mParent; } @Override public void setMyParent(Updateable parent) { - myParent = parent; + mParent = parent; } @Override @@ -55,11 +54,12 @@ public boolean update(float timeDelta, Updateable parent) { setMyParent(parent); Vec pos = null; // TODO remove these 2 lines later: - if (parent instanceof HasPosition) + if (parent instanceof HasPosition) { pos = ((HasPosition) parent).getPosition(); + } if (pos != null) { - Vec.morphToNewVec(pos, myTargetPos, timeDelta * mySpeedFactor); + Vec.morphToNewVec(pos, mTargetPos, timeDelta * mSpeedFactor); } return true; diff --git a/droidar/src/worldData/Obj.java b/droidar/src/worlddata/Obj.java similarity index 67% rename from droidar/src/worldData/Obj.java rename to droidar/src/worlddata/Obj.java index 6b0f22c..291fe40 100644 --- a/droidar/src/worldData/Obj.java +++ b/droidar/src/worlddata/Obj.java @@ -1,4 +1,4 @@ -package worldData; +package worlddata; import gl.Color; import gl.HasColor; @@ -13,16 +13,18 @@ import util.Vec; import commands.Command; - +/** + * Base class for storing {@link worlddata.MeshComponent}. + */ public class Obj extends AbstractObj implements HasPosition, HasColor { - EfficientList myComponents = new EfficientList(); + EfficientList mComponents = new EfficientList(); public void setMyComponents(EfficientList myComponents) { - this.myComponents = myComponents; + this.mComponents = myComponents; } - private MeshComponent myGraphicsComponent; + private MeshComponent mGraphicsComponent; /** * @return the same object as {@link Obj#getGraphicsComponent()} @@ -39,37 +41,36 @@ public MeshComponent getMeshComp() { return getGraphicsComponent(); } + /** + * @return - {@link gl.scenegraph.MeshComponent} + */ public MeshComponent getGraphicsComponent() { - return myGraphicsComponent; + return mGraphicsComponent; } - // public void updateComponents(Component component) { - // Log.e("Obj.update()", "update not catched from: " + component); - // } - /** - * is called from time to time by the {@link World} Thread + * is called from time to time by the {@link World} Thread. * * @param timeDelta * how many ms have passed since last update + * @param parent - {@link worlddata.Updateable} + * @return - true if process successful */ @Override public boolean update(float timeDelta, Updateable parent) { - final int lenght = myComponents.myLength; + final int lenght = mComponents.myLength; for (int i = 0; i < lenght; i++) { - if (myComponents.get(i) != null) - if (!myComponents.get(i).update(timeDelta, this)) { - remove(myComponents.get(i)); + if (mComponents.get(i) != null) { + if (!mComponents.get(i).update(timeDelta, this)) { + remove(mComponents.get(i)); } + } } return true; } /** - * @param uniqueCompName - * look into {@link Consts} and there the COMP_.. strings for - * component types - * @param comp + * @param comp - set the component */ public void setComp(Entity comp) { // TODO rename to add.. and return boolean if could be added @@ -77,8 +78,9 @@ public void setComp(Entity comp) { if (comp instanceof MeshComponent) { setMyGraphicsComponent((MeshComponent) comp); } - if (comp != null && myComponents.contains(comp) == -1) - myComponents.add(comp); + if (comp != null && mComponents.contains(comp) == -1) { + mComponents.add(comp); + } } /** @@ -87,22 +89,26 @@ public void setComp(Entity comp) { * use {@link Obj#setComp(Entity)} and pass the {@link MeshComponent} there * as a parameter! * - * @param newGraphicsComponent + * @param newGraphicsComponent - {@link gl.scenegraph.MeshComponent} */ @Deprecated public void setMyGraphicsComponent(MeshComponent newGraphicsComponent) { - this.myGraphicsComponent = newGraphicsComponent; + this.mGraphicsComponent = newGraphicsComponent; } + /** + * @return - return list of Entity + */ public EfficientList getMyComponents() { - return myComponents; + return mComponents; } @Override public void render(GL10 gl, Renderable parent) { - if (myGraphicsComponent == null) + if (mGraphicsComponent == null) { return; + } /* * nessecary for objects with picking disabled (wich cant be clicked). @@ -123,7 +129,7 @@ public void render(GL10 gl, Renderable parent) { gl.glColor4f(1, 1, 1, 1); } - myGraphicsComponent.render(gl, this); + mGraphicsComponent.render(gl, this); } @Override @@ -134,42 +140,49 @@ public void setOnClickCommand(Command c) { m.enableMeshPicking(this); } } - + + /** + * @param compToRemove - {@link worlddata.Entity} to remove + * @return - true if successful + */ public boolean remove(Entity compToRemove) { - if (compToRemove instanceof MeshComponent) - myGraphicsComponent = null; - return myComponents.remove(compToRemove); + if (compToRemove instanceof MeshComponent) { + mGraphicsComponent = null; + } + return mComponents.remove(compToRemove); } - // public boolean accept(Visitor visitor) { - // return visitor.default_visit(this); - // } - /** - * @param componentSubclass + * @param componentSubclass - not sure * @return true if any of the {@link Obj} {@link Entity}s is a of the * specified class */ @SuppressWarnings({ "unchecked", "rawtypes" }) public boolean hasComponent(Class componentSubclass) { - if (getComp(componentSubclass) != null) + if (getComp(componentSubclass) != null) { return true; + } return false; } + /** + * @param componentSubclass - class + * @return - T + */ @SuppressWarnings("unchecked") public T getComp(Class componentSubclass) { if (componentSubclass.isAssignableFrom(MeshComponent.class)) { // Log.e(LOG_TAG, "Fast access to obj.meshcomp=" + - // myGraphicsComponent); + // mGraphicsComponent); return (T) getGraphicsComponent(); } - for (int i = 0; i < myComponents.myLength; i++) { - Entity a = myComponents.get(i); - if (componentSubclass.isAssignableFrom(a.getClass())) + for (int i = 0; i < mComponents.myLength; i++) { + Entity a = mComponents.get(i); + if (componentSubclass.isAssignableFrom(a.getClass())) { return (T) a; + } } return null; } @@ -177,16 +190,18 @@ public T getComp(Class componentSubclass) { @Override public Vec getPosition() { MeshComponent g = getGraphicsComponent(); - if (g != null) + if (g != null) { return g.getPosition(); + } return null; } @Override public void setPosition(Vec position) { MeshComponent g = getGraphicsComponent(); - if (g != null) + if (g != null) { g.setPosition(position); + } } @Override @@ -210,23 +225,4 @@ public void setColor(Color c) { g.setColor(c); } } - - // public String getDebugInfos() { - // return myGraphicsComponent.toString(); - // } - - // public Component getComponent(String compName) { - // return myComponents.get(compName); - // } - - // @Override - // public void setLongDescr(String info) { - // getMyInfoObject().setLongDescr(info); - // } - - // @Override - // public void setShortDescr(String name) { - // myInfoObj.setShortDescr(name); - // } - } diff --git a/droidar/src/worldData/RenderQuadList.java b/droidar/src/worlddata/RenderQuadList.java similarity index 99% rename from droidar/src/worldData/RenderQuadList.java rename to droidar/src/worlddata/RenderQuadList.java index 7320066..34f227a 100644 --- a/droidar/src/worldData/RenderQuadList.java +++ b/droidar/src/worlddata/RenderQuadList.java @@ -1,4 +1,4 @@ -package worldData; +package worlddata; import gl.GLCamera; import gl.HasPosition; diff --git a/droidar/src/worlddata/RenderableEntity.java b/droidar/src/worlddata/RenderableEntity.java new file mode 100644 index 0000000..efc5c93 --- /dev/null +++ b/droidar/src/worlddata/RenderableEntity.java @@ -0,0 +1,22 @@ +package worlddata; + +import gl.Renderable; + +/** + * This is the basic interface for any object which hat to do with Rendering and + * which also needs to be updated from time to time.
+ *
+ * + * The existing important subclasses are:
+ * + * - {@link gl.senegraph.RenderList}: It is a group of {@link worlddata.RenderableEntity}s
+ * + * - {@link gl.scenegraph.MeshComponent}: A basic {@link gl.scenegraph.Shape} e.g. to draw OpenGL objects or + * {@link gl.LightSource} to add lighning effects to a scene
+ * + * @author Spobo + * + */ +public interface RenderableEntity extends Entity, Renderable { + +} diff --git a/droidar/src/worldData/SystemUpdater.java b/droidar/src/worlddata/SystemUpdater.java similarity index 99% rename from droidar/src/worldData/SystemUpdater.java rename to droidar/src/worlddata/SystemUpdater.java index c17a456..99d2f88 100644 --- a/droidar/src/worldData/SystemUpdater.java +++ b/droidar/src/worlddata/SystemUpdater.java @@ -1,4 +1,4 @@ -package worldData; +package worlddata; import util.EfficientList; import android.os.SystemClock; diff --git a/droidar/src/worldData/UpdatableWithInit.java b/droidar/src/worlddata/UpdatableWithInit.java similarity index 90% rename from droidar/src/worldData/UpdatableWithInit.java rename to droidar/src/worlddata/UpdatableWithInit.java index 5d807a9..c337c2f 100644 --- a/droidar/src/worldData/UpdatableWithInit.java +++ b/droidar/src/worlddata/UpdatableWithInit.java @@ -1,4 +1,4 @@ -package worldData; +package worlddata; public interface UpdatableWithInit extends Updateable { diff --git a/droidar/src/worldData/UpdateTimer.java b/droidar/src/worlddata/UpdateTimer.java similarity index 99% rename from droidar/src/worldData/UpdateTimer.java rename to droidar/src/worlddata/UpdateTimer.java index d757aaf..35a7912 100644 --- a/droidar/src/worldData/UpdateTimer.java +++ b/droidar/src/worlddata/UpdateTimer.java @@ -1,4 +1,4 @@ -package worldData; +package worlddata; import commands.Command; diff --git a/droidar/src/worldData/Updateable.java b/droidar/src/worlddata/Updateable.java similarity index 97% rename from droidar/src/worldData/Updateable.java rename to droidar/src/worlddata/Updateable.java index 4b9eefb..800aad0 100644 --- a/droidar/src/worldData/Updateable.java +++ b/droidar/src/worlddata/Updateable.java @@ -1,4 +1,4 @@ -package worldData; +package worlddata; public interface Updateable { diff --git a/droidar/src/worldData/Visitor.java b/droidar/src/worlddata/Visitor.java similarity index 97% rename from droidar/src/worldData/Visitor.java rename to droidar/src/worlddata/Visitor.java index 1def290..cdeacd9 100644 --- a/droidar/src/worldData/Visitor.java +++ b/droidar/src/worlddata/Visitor.java @@ -1,4 +1,4 @@ -package worldData; +package worlddata; import geo.Edge; import geo.GeoGraph; @@ -51,8 +51,8 @@ public boolean visit(Container x) { } public boolean default_visit(Obj obj) { - EfficientList x = obj.myComponents; - final int lenght = obj.myComponents.myLength; + EfficientList x = obj.mComponents; + final int lenght = obj.mComponents.myLength; for (int i = 0; i < lenght; i++) { x.get(i).accept(this); } diff --git a/droidar/src/worldData/World.java b/droidar/src/worlddata/World.java similarity index 99% rename from droidar/src/worldData/World.java rename to droidar/src/worlddata/World.java index 5844516..8dd6f4a 100644 --- a/droidar/src/worldData/World.java +++ b/droidar/src/worlddata/World.java @@ -1,4 +1,4 @@ -package worldData; +package worlddata; import gl.CordinateAxis; import gl.GLCamera; diff --git a/droidar/src/worldData/visitor.uxf b/droidar/src/worlddata/visitor.uxf similarity index 100% rename from droidar/src/worldData/visitor.uxf rename to droidar/src/worlddata/visitor.uxf diff --git a/droidar/src/worldData/world.uxf b/droidar/src/worlddata/world.uxf similarity index 100% rename from droidar/src/worldData/world.uxf rename to droidar/src/worlddata/world.uxf From d5d7b7ebf413206cf15fa1803f3277de0b3d8fc9 Mon Sep 17 00:00:00 2001 From: rvieras Date: Fri, 27 Dec 2013 14:37:30 -0500 Subject: [PATCH 09/12] Cleaned up some files. Made changes to reduce the flickering when touched. --- .../src/actions/ActionBufferedCameraAR.java | 1 + .../src/actions/ActionCalcRelativePos.java | 6 +- .../src/actions/ActionWaitForAccuracy.java | 122 +- droidar/src/commands/CommandGroup.java | 14 +- .../logic/CommandWrapperEqualsCondition.java | 126 -- .../system/CommandAddHighPrioTask.java | 21 - .../commands/system/CommandShowRendering.java | 41 - .../system/CommandShowWorldAnimation.java | 40 - droidar/src/commands/system/RedoCommand.java | 13 - droidar/src/commands/system/TestCommand.java | 25 - droidar/src/commands/system/UndoCommand.java | 13 - droidar/src/gl/CustomGLSurfaceView.java | 49 +- droidar/src/gl/ReplicaGLSurfaceView.java | 1701 ----------------- droidar/src/gui/InfoScreen.java | 124 -- droidar/src/preview/AugmentedView.java | 1 - droidar/src/system/EventManager.java | 12 +- .../system/StepSettingsControllerView.java | 133 -- droidar/src/util/MagicNumbers.java | 14 + 18 files changed, 132 insertions(+), 2324 deletions(-) delete mode 100644 droidar/src/commands/logic/CommandWrapperEqualsCondition.java delete mode 100644 droidar/src/commands/system/CommandAddHighPrioTask.java delete mode 100644 droidar/src/commands/system/CommandShowRendering.java delete mode 100644 droidar/src/commands/system/CommandShowWorldAnimation.java delete mode 100644 droidar/src/commands/system/RedoCommand.java delete mode 100644 droidar/src/commands/system/TestCommand.java delete mode 100644 droidar/src/commands/system/UndoCommand.java delete mode 100644 droidar/src/gl/ReplicaGLSurfaceView.java delete mode 100644 droidar/src/gui/InfoScreen.java delete mode 100644 droidar/src/system/StepSettingsControllerView.java create mode 100644 droidar/src/util/MagicNumbers.java diff --git a/droidar/src/actions/ActionBufferedCameraAR.java b/droidar/src/actions/ActionBufferedCameraAR.java index 31fe4e5..e924eb8 100644 --- a/droidar/src/actions/ActionBufferedCameraAR.java +++ b/droidar/src/actions/ActionBufferedCameraAR.java @@ -21,6 +21,7 @@ public class ActionBufferedCameraAR extends Action { /** * @param glCamera + * {@link GLCamera} * @param sensityX * is the vertical value (should be around 2, smaller is faster) * @param sensityY diff --git a/droidar/src/actions/ActionCalcRelativePos.java b/droidar/src/actions/ActionCalcRelativePos.java index 5dfc44a..3619ea0 100644 --- a/droidar/src/actions/ActionCalcRelativePos.java +++ b/droidar/src/actions/ActionCalcRelativePos.java @@ -31,7 +31,7 @@ public class ActionCalcRelativePos extends Action { * set this to true if your scenario need to take altitude values into * account */ - public static boolean USE_ALTITUDE_VALUES = false; + public static final boolean USE_ALTITUDE_VALUES = false; /** * set this to false if you want to position objects at the real 0 altitude, @@ -70,7 +70,7 @@ public ActionCalcRelativePos(World world, GLCamera camera) { @Override public boolean onLocationChanged(Location location) { - if (mNullLatitude == 0 || mNullLongitude == 0) { + if ((mNullLatitude == 0) || (mNullLongitude == 0)) { /* * if the mNullLat or mNullLong are 0 this method was probably never * called before (TODO problem when living in greenwhich e.g.?) @@ -135,7 +135,7 @@ private boolean worldShouldBeRecalced(double latDistMet, double longDistMet) { } /** - * Reset the world to (0,0,0) position. + * Reset the world to (0,0,0) position. * @param location {@link Location} */ public void resetWorldZeroPositions(Location location) { diff --git a/droidar/src/actions/ActionWaitForAccuracy.java b/droidar/src/actions/ActionWaitForAccuracy.java index 0a05c22..2d82ca9 100644 --- a/droidar/src/actions/ActionWaitForAccuracy.java +++ b/droidar/src/actions/ActionWaitForAccuracy.java @@ -4,6 +4,7 @@ import system.EventManager; import android.app.Activity; import android.app.Dialog; +import android.content.Context; import android.location.Location; import android.util.Log; import android.view.View; @@ -14,6 +15,9 @@ import android.widget.TextView; import de.rwth.R; +/** + * Action to wait for a valid GPS with good accuracy before drawing. + */ public abstract class ActionWaitForAccuracy extends Action { private static final String TEXT_DIALOG_TITLE = "Do you want to cancel the accuracy detection?"; @@ -27,26 +31,27 @@ public abstract class ActionWaitForAccuracy extends Action { private static final String LOG_TAG = "ActionWaitForAccuracy"; - private float myCurrentAccuracy; - private float myMinAccuracy; - private boolean firstTimeReached = false; + private float mCurrentAccuracy; + private float mMinAccuracy; + private boolean mFirstTimeReached = false; - private int myMaxPosUpdateCount; + private int mMaxPosUpdateCount; - private int stepCounter = 0; + private int mStepCounter = 0; - private Activity myActivity; + private Activity mActivity; - private TextView accText; + private TextView mAccText; - private ProgressBar steps; + private ProgressBar mSteps; - private View viewContainer; + private View mViewContainer; - private Button warningText; + private Button mWarningText; /** * @param context + * {@link Context} * @param minAccuracy * should be >= 25m * @param maxPosUpdateCount @@ -55,17 +60,17 @@ public abstract class ActionWaitForAccuracy extends Action { */ public ActionWaitForAccuracy(Activity context, float minAccuracy, int maxPosUpdateCount) { - myActivity = context; - myMinAccuracy = minAccuracy; - myMaxPosUpdateCount = maxPosUpdateCount; + mActivity = context; + mMinAccuracy = minAccuracy; + mMaxPosUpdateCount = maxPosUpdateCount; analyseInitLocation(GeoUtils.getCurrentLocation(context)); } private void analyseInitLocation(Location l) { if (l != null) { - myCurrentAccuracy = l.getAccuracy(); + mCurrentAccuracy = l.getAccuracy(); long passedTime = System.currentTimeMillis() - l.getTime(); - Log.i(LOG_TAG, "Last known pos accuracy=" + myCurrentAccuracy); + Log.i(LOG_TAG, "Last known pos accuracy=" + mCurrentAccuracy); Log.i(LOG_TAG, "Last known pos age=" + (passedTime / 1000f / 10f) + " minutes"); if (passedTime <= MAX_TIME_SINCE_LAST_UPDATE_IN_MS) { @@ -74,24 +79,24 @@ private void analyseInitLocation(Location l) { Log.i(LOG_TAG, "Last known pos age was to old to use it " + "as a current position, will now wait " + "for position signal"); - myCurrentAccuracy = 1000; // 1000m + mCurrentAccuracy = 1000; // 1000m } } else { - GeoUtils.enableLocationProvidersIfNeeded(myActivity); + GeoUtils.enableLocationProvidersIfNeeded(mActivity); } } @Override public boolean onLocationChanged(Location l) { Log.d(LOG_TAG, "Current signal accuracy=" + l.getAccuracy()); - Log.d(LOG_TAG, "Minimum needed accuracy=" + myMinAccuracy); - Log.d(LOG_TAG, "Current pos update count=" + stepCounter); - Log.d(LOG_TAG, "Max pos updates=" + myMaxPosUpdateCount); - stepCounter++; - myCurrentAccuracy = l.getAccuracy(); + Log.d(LOG_TAG, "Minimum needed accuracy=" + mMinAccuracy); + Log.d(LOG_TAG, "Current pos update count=" + mStepCounter); + Log.d(LOG_TAG, "Max pos updates=" + mMaxPosUpdateCount); + mStepCounter++; + mCurrentAccuracy = l.getAccuracy(); updateUI(); - if ((myCurrentAccuracy != 0 && myCurrentAccuracy <= myMinAccuracy) - || (stepCounter >= myMaxPosUpdateCount)) { + if (((mCurrentAccuracy != 0) && (mCurrentAccuracy <= mMinAccuracy)) + || (mStepCounter >= mMaxPosUpdateCount)) { callFirstTimeAccReachedIfNotYetCalled(l); hideUI(); return false; @@ -100,14 +105,15 @@ public boolean onLocationChanged(Location l) { } private void callFirstTimeAccReachedIfNotYetCalled(Location location) { - if (!firstTimeReached) { - firstTimeReached = true; + if (!mFirstTimeReached) { + mFirstTimeReached = true; Log.d(LOG_TAG, "Required accuracy was reached!"); minAccuracyReachedFirstTime(location, this); - } else + } else { Log.w(LOG_TAG, "callFirstTimeAccReachedIfNotYetCalled was " + "called more then one time! This action should " + "be removed once the accuracy was reached!"); + } } /** @@ -122,23 +128,23 @@ public abstract void minAccuracyReachedFirstTime(Location location, ActionWaitForAccuracy a); public View getView() { - viewContainer = View.inflate(myActivity, + mViewContainer = View.inflate(mActivity, R.layout.action_wait_for_accuracy_view, null); - accText = (TextView) viewContainer.findViewById(R.id.awfa_accText); - warningText = (Button) viewContainer.findViewById(R.id.awfa_warning); - warningText.setOnClickListener(new OnClickListener() { + mAccText = (TextView) mViewContainer.findViewById(R.id.awfa_accText); + mWarningText = (Button) mViewContainer.findViewById(R.id.awfa_warning); + mWarningText.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { - if (GeoUtils.enableGPS(myActivity)) { - warningText.setVisibility(View.GONE); + if (GeoUtils.enableGPS(mActivity)) { + mWarningText.setVisibility(View.GONE); waitSomeSecondsAndThenRegisterForGPSEvents(); } } }); - ImageView i = (ImageView) viewContainer.findViewById(R.id.awfa_image); + ImageView i = (ImageView) mViewContainer.findViewById(R.id.awfa_image); i.setOnClickListener(new OnClickListener() { @Override @@ -148,11 +154,11 @@ public void onClick(View v) { }); - steps = (ProgressBar) viewContainer.findViewById(R.id.awfa_steps); + mSteps = (ProgressBar) mViewContainer.findViewById(R.id.awfa_steps); showDebugInfosAboutTheUiElements(); updateUI(); - return viewContainer; + return mViewContainer; } private void waitSomeSecondsAndThenRegisterForGPSEvents() { @@ -181,16 +187,16 @@ public void onGPSActivatedEvent() { } private void showDebugInfosAboutTheUiElements() { - Log.d(LOG_TAG, "viewContainer=" + viewContainer); - Log.d(LOG_TAG, " > accText=" + accText); - Log.d(LOG_TAG, " > warningText=" + warningText); - Log.d(LOG_TAG, " > steps=" + steps); - Log.d(LOG_TAG, " > stepCounter=" + stepCounter); + Log.d(LOG_TAG, "mViewContainer=" + mViewContainer); + Log.d(LOG_TAG, " > mAccText=" + mAccText); + Log.d(LOG_TAG, " > mWarningText=" + mWarningText); + Log.d(LOG_TAG, " > mSteps=" + mSteps); + Log.d(LOG_TAG, " > mStepCounter=" + mStepCounter); } private void showSkipPositionDetectionDialog() { - final Dialog dialog = new Dialog(myActivity); - Button b = new Button(myActivity); + final Dialog dialog = new Dialog(mActivity); + Button b = new Button(mActivity); b.setText(TEXT_SKIP_ACCURACY_DETECTION); b.setOnClickListener(new OnClickListener() { @@ -198,7 +204,7 @@ private void showSkipPositionDetectionDialog() { public void onClick(View v) { Log.d(LOG_TAG, "Trying to skip accuracy detection"); callFirstTimeAccReachedIfNotYetCalled(GeoUtils - .getCurrentLocation(myActivity)); + .getCurrentLocation(mActivity)); hideUI(); dialog.dismiss(); } @@ -210,41 +216,43 @@ public void onClick(View v) { } private void updateUI() { - if (accText != null && steps != null && warningText != null) - myActivity.runOnUiThread(new Runnable() { + if ((mAccText != null) && (mSteps != null) && (mWarningText != null)) { + mActivity.runOnUiThread(new Runnable() { @Override public void run() { - accText.setText(TEXT_POSITION_ACCURACY - + (int) (myMinAccuracy / myCurrentAccuracy * 100) + mAccText.setText(TEXT_POSITION_ACCURACY + + (int) ((mMinAccuracy / mCurrentAccuracy) * 100) + "%"); - steps.setMax(myMaxPosUpdateCount); - steps.setProgress(stepCounter); + mSteps.setMax(mMaxPosUpdateCount); + mSteps.setProgress(mStepCounter); showWarningIfGPSOff(); } }); + } } private void hideUI() { - if (viewContainer != null) - myActivity.runOnUiThread(new Runnable() { + if (mViewContainer != null) { + mActivity.runOnUiThread(new Runnable() { @Override public void run() { Log.i(LOG_TAG, "Setting view container to invisible"); - viewContainer.setVisibility(View.GONE); + mViewContainer.setVisibility(View.GONE); } }); + } } private void showWarningIfGPSOff() { - if (GeoUtils.isGPSDisabled(myActivity)) { + if (GeoUtils.isGPSDisabled(mActivity)) { Log.d(LOG_TAG, "GPS disabled!"); - warningText.setVisibility(View.VISIBLE); - warningText.setText("Enable GPS"); + mWarningText.setVisibility(View.VISIBLE); + mWarningText.setText("Enable GPS"); } else { Log.d(LOG_TAG, "GPS enabled!"); - warningText.setVisibility(View.GONE); + mWarningText.setVisibility(View.GONE); } } } diff --git a/droidar/src/commands/CommandGroup.java b/droidar/src/commands/CommandGroup.java index ac5a466..cb432a0 100644 --- a/droidar/src/commands/CommandGroup.java +++ b/droidar/src/commands/CommandGroup.java @@ -9,10 +9,7 @@ /** * The CommandGroup can hold several {@link UndoableCommand}s and is a Command - * itself (Composite pattern) - * - * @author Spobo - * + * itself (Composite pattern). */ public class CommandGroup extends UndoableCommand implements Container { @@ -38,9 +35,10 @@ public boolean override_do() { + ") NO parameter"); boolean result = true; for (int i = 0; i < myList.myLength; i++) { - if (myProcessListener != null) + if (myProcessListener != null) { myProcessListener.onProcessStep(i, myList.myLength, myList.get(i)); + } Log.d("Commands", " + CG " + this + " EXECUTING " + myList.get(i) + " (NO parameter)"); @@ -96,8 +94,9 @@ public boolean add(Command c) { @Override public EfficientList getAllItems() { - if (myList == null) + if (myList == null) { myList = new EfficientList(); + } return myList; } @@ -123,8 +122,9 @@ public void removeEmptyItems() { @Override public String toString() { - if (this.hasInfoObject()) + if (this.hasInfoObject()) { return "CG " + getInfoObject().getShortDescr(); + } return super.toString(); } diff --git a/droidar/src/commands/logic/CommandWrapperEqualsCondition.java b/droidar/src/commands/logic/CommandWrapperEqualsCondition.java deleted file mode 100644 index c29eeb5..0000000 --- a/droidar/src/commands/logic/CommandWrapperEqualsCondition.java +++ /dev/null @@ -1,126 +0,0 @@ -package commands.logic; - -import util.Log; -import util.Wrapper; - -import commands.Command; - -public class CommandWrapperEqualsCondition extends Command { - - private Wrapper.Type mode; - - private Wrapper myW; - private String mySValue; - private boolean myBValue; - private int myIValue; - - private Command myCommand; - - private Command myElseCommand; - - public CommandWrapperEqualsCondition(Wrapper w, String valueToCompareWith, - Command commandToExecute) { - mode = Wrapper.Type.String; - myW = w; - mySValue = valueToCompareWith; - myCommand = commandToExecute; - } - - public CommandWrapperEqualsCondition(Wrapper w, boolean valueToCompareWith, - Command ifTrueCommand) { - mode = Wrapper.Type.Bool; - myW = w; - myBValue = valueToCompareWith; - myCommand = ifTrueCommand; - } - - public CommandWrapperEqualsCondition(Wrapper w, boolean valueToCompareWith, - Command ifTrueCommand, Command elseCommand) { - this(w, valueToCompareWith, ifTrueCommand); - myElseCommand = elseCommand; - } - - @Override - public boolean execute() { - - if (myW == null) { - Log.e("Command Error", - "CommandEqualsCondition.doMethod: wrapper object is null!"); - return false; - } - - Log.d("Commands", "running equals command in mode=" + mode); - - switch (mode) { - case String: - if (myW.equals(mySValue)) { - return myCommand.execute(); - } else if (myElseCommand != null) { - return myElseCommand.execute(); - } - return false; - case Bool: - Log.d("Commands", - "myBool=" + myBValue + " wrapperBool=" - + myW.getBooleanValue()); - if (myW.equals(myBValue)) { - return myCommand.execute(); - } else if (myElseCommand != null) { - return myElseCommand.execute(); - } - return false; - case Int: - if (myW.equals(myIValue)) { - return myCommand.execute(); - } else if (myElseCommand != null) { - return myElseCommand.execute(); - } - return false; - } - // TODO all cases checked? verify by writing a test - return false; - } - - @Override - public boolean execute(Object transfairObject) { - - if (myW == null) { - Log.e("Command Error", - "CommandEqualsCondition.doMethod: wrapper object is null!"); - return false; - } - - Log.d("Commands", "running equals command in mode=" + mode); - - switch (mode) { - case String: - if (myW.equals(mySValue)) { - return myCommand.execute(transfairObject); - } else if (myElseCommand != null) { - return myElseCommand.execute(transfairObject); - } - return false; - case Bool: - Log.d("Commands", - "myBool=" + myBValue + " wrapperBool=" - + myW.getBooleanValue()); - if (myW.equals(myBValue)) { - return myCommand.execute(transfairObject); - } else if (myElseCommand != null) { - return myElseCommand.execute(transfairObject); - } - return false; - case Int: - if (myW.equals(myIValue)) { - return myCommand.execute(transfairObject); - } else if (myElseCommand != null) { - return myElseCommand.execute(transfairObject); - } - return false; - } - // TODO all cases checked? verify by writing a test - return false; - - } - -} diff --git a/droidar/src/commands/system/CommandAddHighPrioTask.java b/droidar/src/commands/system/CommandAddHighPrioTask.java deleted file mode 100644 index 19b3be8..0000000 --- a/droidar/src/commands/system/CommandAddHighPrioTask.java +++ /dev/null @@ -1,21 +0,0 @@ -package commands.system; - -import system.TaskManager; - -import commands.Command; - -public class CommandAddHighPrioTask extends Command { - - private Command myCommandToAdd; - - public CommandAddHighPrioTask(Command commandToAdd) { - myCommandToAdd = commandToAdd; - } - - @Override - public boolean execute() { - TaskManager.getInstance().addHighPrioTask(myCommandToAdd); - return true; - } - -} diff --git a/droidar/src/commands/system/CommandShowRendering.java b/droidar/src/commands/system/CommandShowRendering.java deleted file mode 100644 index 8ec483c..0000000 --- a/droidar/src/commands/system/CommandShowRendering.java +++ /dev/null @@ -1,41 +0,0 @@ -package commands.system; - -import gl.GLRenderer; - -import commands.undoable.UndoableCommand; - -public class CommandShowRendering extends UndoableCommand { - - private GLRenderer myR; - private boolean b; - - public CommandShowRendering(GLRenderer r, boolean show) { - myR = r; - b = show; - } - - @Override - public boolean override_do() { - if (myR != null) { - if (b) - myR.resume(); - else - myR.pause(); - return true; - } - return false; - } - - @Override - public boolean override_undo() { - if (myR != null) { - if (b) - myR.pause(); - else - myR.resume(); - return true; - } - return false; - } - -} diff --git a/droidar/src/commands/system/CommandShowWorldAnimation.java b/droidar/src/commands/system/CommandShowWorldAnimation.java deleted file mode 100644 index cce88d5..0000000 --- a/droidar/src/commands/system/CommandShowWorldAnimation.java +++ /dev/null @@ -1,40 +0,0 @@ -package commands.system; - -import worlddata.SystemUpdater; -import commands.undoable.UndoableCommand; - -public class CommandShowWorldAnimation extends UndoableCommand { - - private SystemUpdater myW; - private boolean startWorldThread; - - /** - * @param updater - * @param show - * false=animation is paused - */ - public CommandShowWorldAnimation(SystemUpdater updater, boolean show) { - myW = updater; - startWorldThread = show; - } - - @Override - public boolean override_do() { - if (startWorldThread && myW != null) - myW.resumeUpdater(); - else - myW.pauseUpdater(); - return true; - } - - @Override - public boolean override_undo() { - if (startWorldThread && myW != null) - myW.pauseUpdater(); - else - myW.resumeUpdater(); - - return true; - } - -} diff --git a/droidar/src/commands/system/RedoCommand.java b/droidar/src/commands/system/RedoCommand.java deleted file mode 100644 index 01ecf06..0000000 --- a/droidar/src/commands/system/RedoCommand.java +++ /dev/null @@ -1,13 +0,0 @@ -package commands.system; - -import commands.Command; -import commands.undoable.CommandProcessor; - -public class RedoCommand extends Command { - - @Override - public boolean execute() { - return CommandProcessor.getInstance().redo(); - } - -} diff --git a/droidar/src/commands/system/TestCommand.java b/droidar/src/commands/system/TestCommand.java deleted file mode 100644 index 68ec228..0000000 --- a/droidar/src/commands/system/TestCommand.java +++ /dev/null @@ -1,25 +0,0 @@ -package commands.system; - -import util.Log; - -import commands.undoable.UndoableCommand; - -public class TestCommand extends UndoableCommand { - - private int x = 0; - - @Override - public boolean override_do() { - x++; - Log.out("Test Command do. Count: " + x); - return true; - } - - @Override - public boolean override_undo() { - x--; - Log.out("Test Command undo. Count: " + x); - return true; - } - -} diff --git a/droidar/src/commands/system/UndoCommand.java b/droidar/src/commands/system/UndoCommand.java deleted file mode 100644 index 3b42181..0000000 --- a/droidar/src/commands/system/UndoCommand.java +++ /dev/null @@ -1,13 +0,0 @@ -package commands.system; - -import commands.Command; -import commands.undoable.CommandProcessor; - -public class UndoCommand extends Command { - - @Override - public boolean execute() { - return CommandProcessor.getInstance().undo(); - } - -} diff --git a/droidar/src/gl/CustomGLSurfaceView.java b/droidar/src/gl/CustomGLSurfaceView.java index 79a6537..6678632 100644 --- a/droidar/src/gl/CustomGLSurfaceView.java +++ b/droidar/src/gl/CustomGLSurfaceView.java @@ -13,6 +13,7 @@ import android.content.Context; import android.graphics.PixelFormat; import android.opengl.GLSurfaceView; +import android.os.AsyncTask; import android.util.AttributeSet; import android.view.GestureDetector; import android.view.MotionEvent; @@ -69,8 +70,8 @@ private void initGLSurfaceView(Context context) { } int screenOrientation = ArSetup.getScreenOrientation(); - if (screenOrientation == Surface.ROTATION_90 - || screenOrientation == Surface.ROTATION_270) { + if ((screenOrientation == Surface.ROTATION_90) + || (screenOrientation == Surface.ROTATION_270)) { LANDSCAPE_MODE = true; } else { LANDSCAPE_MODE = false; @@ -132,22 +133,17 @@ public boolean onTouchEvent(MotionEvent event) { myGestureDetector.onTouchEvent(event); - requestFocus(); - - try { - // Sleep 20ms to not flood the thread - Thread.sleep(TOUCH_INPUT_SLEEP_TIME); - } catch (InterruptedException e) { - e.printStackTrace(); - } + // requestFocus(); + // + // try { + // // Sleep 20ms to not flood the thread + // Thread.sleep(TOUCH_INPUT_SLEEP_TIME); + // } catch (InterruptedException e) { + // e.printStackTrace(); + // } if (event.getAction() == MotionEvent.ACTION_UP) { - if (onTouchListeners != null) { - for (int i = 0; i < onTouchListeners.size(); i++) { - onTouchListeners.get(i).onReleaseTouchMove(); - } - - } + (new NotifyListenersTask(onTouchListeners)).execute(new Object()); } return true; } @@ -230,5 +226,26 @@ public void onScroll(MotionEvent e1, MotionEvent e2, float distanceX, } } } + + /** + * Background task to notify listeners. + */ + private class NotifyListenersTask extends AsyncTask { + private List mListeners; + + public NotifyListenersTask(List listeners) { + mListeners = listeners; + } + + @Override + protected Object doInBackground(Object... arg0) { + if (onTouchListeners != null) { + for (int i = 0; i < onTouchListeners.size(); i++) { + onTouchListeners.get(i).onReleaseTouchMove(); + } + } + return null; + } + } } diff --git a/droidar/src/gl/ReplicaGLSurfaceView.java b/droidar/src/gl/ReplicaGLSurfaceView.java deleted file mode 100644 index a102f66..0000000 --- a/droidar/src/gl/ReplicaGLSurfaceView.java +++ /dev/null @@ -1,1701 +0,0 @@ -package gl; - -import java.io.Writer; -import java.util.ArrayList; - -import javax.microedition.khronos.egl.EGL10; -import javax.microedition.khronos.egl.EGL11; -import javax.microedition.khronos.egl.EGLConfig; -import javax.microedition.khronos.egl.EGLContext; -import javax.microedition.khronos.egl.EGLDisplay; -import javax.microedition.khronos.egl.EGLSurface; -import javax.microedition.khronos.opengles.GL; -import javax.microedition.khronos.opengles.GL10; - -import util.Log; -import android.content.Context; -import android.content.pm.ConfigurationInfo; -import android.opengl.GLDebugHelper; -import android.util.AttributeSet; -import android.view.SurfaceHolder; -import android.view.SurfaceView; - -/** - * A modified version of - * http://code.google.com/p/replicaisland/source/browse/trunk - * /src/com/replica/replicaisland/GLSurfaceView.java - * - *
- * Auto reloading of opengl context didn't work (textures were gone eg) so this - * wont be used but would work (if you change the parent of - * {@link CustomGLSurfaceView} to {@link ReplicaGLSurfaceView} and the parent of - * {@link GL1Renderer} to {@link ReplicaRenderer}) - * - * - *
- * Also see http://groups.google.com/group/replica-island-coding-community/ - * browse_thread/thread/45bf454a3ee25136 - * - *
- *
- * - * An implementation of SurfaceView that uses the dedicated surface for - * displaying OpenGL rendering. - *

- * A GLSurfaceView provides the following features: - *

- *

    - *
  • Manages a surface, which is a special piece of memory that can be - * composited into the Android view system. - *
  • Manages an EGL display, which enables OpenGL to render into a surface. - *
  • Accepts a user-provided Renderer object that does the actual rendering. - *
  • Renders on a dedicated thread to decouple rendering performance from the - * UI thread. - *
  • Supports both on-demand and continuous rendering. - *
  • Optionally wraps, traces, and/or error-checks the renderer's OpenGL - * calls. - *
- * - *

Using GLSurfaceView

- *

- * Typically you use GLSurfaceView by subclassing it and overriding one or more - * of the View system input event methods. If your application does not need to - * override event methods then GLSurfaceView can be used as-is. For the most - * part GLSurfaceView behavior is customized by calling "set" methods rather - * than by subclassing. For example, unlike a regular View, drawing is delegated - * to a separate Renderer object which is registered with the GLSurfaceView - * using the {@link #setRenderer(ReplicaRenderer)} call. - *

- *

Initializing GLSurfaceView

- * All you have to do to initialize a GLSurfaceView is call - * {@link #setRenderer(ReplicaRenderer)}. However, if desired, you can modify - * the default behavior of GLSurfaceView by calling one or more of these methods - * before calling setRenderer: - *
    - *
  • {@link #setDebugFlags(int)} - *
  • {@link #setEGLConfigChooser(boolean)} - *
  • {@link #setEGLConfigChooser(EGLConfigChooser)} - *
  • {@link #setEGLConfigChooser(int, int, int, int, int, int)} - *
  • {@link #setGLWrapper(GLWrapper)} - *
- *

- *

Choosing an EGL Configuration

- * A given Android device may support multiple possible types of drawing - * surfaces. The available surfaces may differ in how may channels of data are - * present, as well as how many bits are allocated to each channel. Therefore, - * the first thing GLSurfaceView has to do when starting to render is choose - * what type of surface to use. - *

- * By default GLSurfaceView chooses an available surface that's closest to a - * 16-bit R5G6B5 surface with a 16-bit depth buffer and no stencil. If you would - * prefer a different surface (for example, if you do not need a depth buffer) - * you can override the default behavior by calling one of the - * setEGLConfigChooser methods. - *

- *

Debug Behavior

- * You can optionally modify the behavior of GLSurfaceView by calling one or - * more of the debugging methods {@link #setDebugFlags(int)}, and - * {@link #setGLWrapper}. These methods may be called before and/or after - * setRenderer, but typically they are called before setRenderer so that they - * take effect immediately. - *

- *

Setting a Renderer

- * Finally, you must call {@link #setRenderer} to register a - * {@link ReplicaRenderer}. The renderer is responsible for doing the actual - * OpenGL rendering. - *

- *

Rendering Mode

- * Once the renderer is set, you can control whether the renderer draws - * continuously or on-demand by calling {@link #setRenderMode}. The default is - * continuous rendering. - *

- *

Activity Life-cycle

- * A GLSurfaceView must be notified when the activity is paused and resumed. - * GLSurfaceView clients are required to call {@link #onPause()} when the - * activity pauses and {@link #onResume()} when the activity resumes. These - * calls allow GLSurfaceView to pause and resume the rendering thread, and also - * allow GLSurfaceView to release and recreate the OpenGL display. - *

- *

Handling events

- *

- * To handle an event you will typically subclass GLSurfaceView and override the - * appropriate method, just as you would with any other View. However, when - * handling the event, you may need to communicate with the Renderer object - * that's running in the rendering thread. You can do this using any standard - * Java cross-thread communication mechanism. In addition, one relatively easy - * way to communicate with your renderer is to call - * {@link #queueEvent(Runnable)}. For example: - * - *

- * class MyGLSurfaceView extends GLSurfaceView {
- * 
- * 	private MyRenderer mMyRenderer;
- * 
- * 	public void start() {
- *         mMyRenderer = ...;
- *         setRenderer(mMyRenderer);
- *     }
- * 
- * 	public boolean onKeyDown(int keyCode, KeyEvent event) {
- * 		if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
- * 			queueEvent(new Runnable() {
- * 				// This method will be called on the rendering
- * 				// thread:
- * 				public void run() {
- * 					mMyRenderer.handleDpadCenter();
- * 				}
- * 			});
- * 			return true;
- * 		}
- * 		return super.onKeyDown(keyCode, event);
- * 	}
- * }
- * 
- * - */ -@Deprecated -public class ReplicaGLSurfaceView extends SurfaceView implements - SurfaceHolder.Callback { - private final static boolean LOG_THREADS = false; - private final static boolean LOG_SURFACE = true; - private final static boolean LOG_RENDERER = false; - // Work-around for bug 2263168 - private final static boolean DRAW_TWICE_AFTER_SIZE_CHANGED = true; - /** - * The renderer only renders when the surface is created, or when - * {@link #requestRender} is called. - * - * @see #getRenderMode() - * @see #setRenderMode(int) - */ - public final static int RENDERMODE_WHEN_DIRTY = 0; - /** - * The renderer is called continuously to re-render the scene. - * - * @see #getRenderMode() - * @see #setRenderMode(int) - * @see #requestRender() - */ - public final static int RENDERMODE_CONTINUOUSLY = 1; - - /** - * Check glError() after every GL call and throw an exception if glError - * indicates that an error has occurred. This can be used to help track down - * which OpenGL ES call is causing an error. - * - * @see #getDebugFlags - * @see #setDebugFlags - */ - public final static int DEBUG_CHECK_GL_ERROR = 1; - - /** - * Log GL calls to the system log at "verbose" level with tag - * "GLSurfaceView". - * - * @see #getDebugFlags - * @see #setDebugFlags - */ - public final static int DEBUG_LOG_GL_CALLS = 2; - - /** - * Standard View constructor. In order to render something, you must call - * {@link #setRenderer} to register a renderer. - */ - public ReplicaGLSurfaceView(Context context) { - super(context); - init(); - } - - /** - * Standard View constructor. In order to render something, you must call - * {@link #setRenderer} to register a renderer. - */ - public ReplicaGLSurfaceView(Context context, AttributeSet attrs) { - super(context, attrs); - init(); - } - - private void init() { - // Install a SurfaceHolder.Callback so we get notified when the - // underlying surface is created and destroyed - SurfaceHolder holder = getHolder(); - holder.addCallback(this); - holder.setType(SurfaceHolder.SURFACE_TYPE_GPU); - - } - - /** - * Set the glWrapper. If the glWrapper is not null, its - * {@link GLWrapper#wrap(GL)} method is called whenever a surface is - * created. A GLWrapper can be used to wrap the GL object that's passed to - * the renderer. Wrapping a GL object enables examining and modifying the - * behavior of the GL calls made by the renderer. - *

- * Wrapping is typically used for debugging purposes. - *

- * The default value is null. - * - * @param glWrapper - * the new GLWrapper - */ - public void setGLWrapper(GLWrapper glWrapper) { - mGLWrapper = glWrapper; - } - - /** - * Set the debug flags to a new value. The value is constructed by - * OR-together zero or more of the DEBUG_CHECK_* constants. The debug flags - * take effect whenever a surface is created. The default value is zero. - * - * @param debugFlags - * the new debug flags - * @see #DEBUG_CHECK_GL_ERROR - * @see #DEBUG_LOG_GL_CALLS - */ - public void setDebugFlags(int debugFlags) { - mDebugFlags = debugFlags; - } - - /** - * Get the current value of the debug flags. - * - * @return the current value of the debug flags. - */ - public int getDebugFlags() { - return mDebugFlags; - } - - /** - * Set the renderer associated with this view. Also starts the thread that - * will call the renderer, which in turn causes the rendering to start. - *

- * This method should be called once and only once in the life-cycle of a - * GLSurfaceView. - *

- * The following GLSurfaceView methods can only be called before - * setRenderer is called: - *

    - *
  • {@link #setEGLConfigChooser(boolean)} - *
  • {@link #setEGLConfigChooser(EGLConfigChooser)} - *
  • {@link #setEGLConfigChooser(int, int, int, int, int, int)} - *
- *

- * The following GLSurfaceView methods can only be called after - * setRenderer is called: - *

    - *
  • {@link #getRenderMode()} - *
  • {@link #onPause()} - *
  • {@link #onResume()} - *
  • {@link #queueEvent(Runnable)} - *
  • {@link #requestRender()} - *
  • {@link #setRenderMode(int)} - *
- * - * @param renderer - * the renderer to use to perform OpenGL drawing. - */ - public void setRenderer(ReplicaRenderer renderer) { - checkRenderThreadState(); - if (mEGLConfigChooser == null) { - mEGLConfigChooser = new SimpleEGLConfigChooser(true); - } - if (mEGLContextFactory == null) { - mEGLContextFactory = new DefaultContextFactory(); - } - if (mEGLWindowSurfaceFactory == null) { - mEGLWindowSurfaceFactory = new DefaultWindowSurfaceFactory(); - } - mGLThread = new GLThread(renderer); - mGLThread.start(); - } - - /** - * Install a custom EGLContextFactory. - *

- * If this method is called, it must be called before - * {@link #setRenderer(ReplicaRenderer)} is called. - *

- * If this method is not called, then by default a context will be created - * with no shared context and with a null attribute list. - */ - public void setEGLContextFactory(EGLContextFactory factory) { - checkRenderThreadState(); - mEGLContextFactory = factory; - } - - /** - * Install a custom EGLWindowSurfaceFactory. - *

- * If this method is called, it must be called before - * {@link #setRenderer(ReplicaRenderer)} is called. - *

- * If this method is not called, then by default a window surface will be - * created with a null attribute list. - */ - public void setEGLWindowSurfaceFactory(EGLWindowSurfaceFactory factory) { - checkRenderThreadState(); - mEGLWindowSurfaceFactory = factory; - } - - /** - * Install a custom EGLConfigChooser. - *

- * If this method is called, it must be called before - * {@link #setRenderer(ReplicaRenderer)} is called. - *

- * If no setEGLConfigChooser method is called, then by default the view will - * choose a config as close to 16-bit RGB as possible, with a depth buffer - * as close to 16 bits as possible. - * - * @param configChooser - */ - public void setEGLConfigChooser(EGLConfigChooser configChooser) { - checkRenderThreadState(); - mEGLConfigChooser = configChooser; - } - - /** - * Install a config chooser which will choose a config as close to 16-bit - * RGB as possible, with or without an optional depth buffer as close to - * 16-bits as possible. - *

- * If this method is called, it must be called before - * {@link #setRenderer(ReplicaRenderer)} is called. - *

- * If no setEGLConfigChooser method is called, then by default the view will - * choose a config as close to 16-bit RGB as possible, with a depth buffer - * as close to 16 bits as possible. - * - * @param needDepth - */ - public void setEGLConfigChooser(boolean needDepth) { - setEGLConfigChooser(new SimpleEGLConfigChooser(needDepth)); - } - - /** - * Install a config chooser which will choose a config with at least the - * specified component sizes, and as close to the specified component sizes - * as possible. - *

- * If this method is called, it must be called before - * {@link #setRenderer(ReplicaRenderer)} is called. - *

- * If no setEGLConfigChooser method is called, then by default the view will - * choose a config as close to 16-bit RGB as possible, with a depth buffer - * as close to 16 bits as possible. - * - */ - public void setEGLConfigChooser(int redSize, int greenSize, int blueSize, - int alphaSize, int depthSize, int stencilSize) { - setEGLConfigChooser(new ComponentSizeChooser(redSize, greenSize, - blueSize, alphaSize, depthSize, stencilSize)); - } - - /** - * Inform the default EGLContextFactory and default EGLConfigChooser which - * EGLContext client version to pick. - *

- * Use this method to create an OpenGL ES 2.0-compatible context. Example: - * - *

-	 * public MyView(Context context) {
-	 * 	super(context);
-	 * 	setEGLContextClientVersion(2); // Pick an OpenGL ES 2.0 context.
-	 * 	setRenderer(new MyRenderer());
-	 * }
-	 * 
- *

- * Note: Activities which require OpenGL ES 2.0 should indicate this by - * setting @lt;uses-feature android:glEsVersion="0x00020000" /> in the - * activity's AndroidManifest.xml file. - *

- * If this method is called, it must be called before - * {@link #setRenderer(ReplicaRenderer)} is called. - *

- * This method only affects the behavior of the default EGLContexFactory and - * the default EGLConfigChooser. If - * {@link #setEGLContextFactory(EGLContextFactory)} has been called, then - * the supplied EGLContextFactory is responsible for creating an OpenGL ES - * 2.0-compatible context. If {@link #setEGLConfigChooser(EGLConfigChooser)} - * has been called, then the supplied EGLConfigChooser is responsible for - * choosing an OpenGL ES 2.0-compatible config. - * - * @param version - * The EGLContext client version to choose. Use 2 for OpenGL ES - * 2.0 - */ - public void setEGLContextClientVersion(int version) { - checkRenderThreadState(); - mEGLContextClientVersion = version; - } - - /** - * Set the rendering mode. When renderMode is RENDERMODE_CONTINUOUSLY, the - * renderer is called repeatedly to re-render the scene. When renderMode is - * RENDERMODE_WHEN_DIRTY, the renderer only rendered when the surface is - * created, or when {@link #requestRender} is called. Defaults to - * RENDERMODE_CONTINUOUSLY. - *

- * Using RENDERMODE_WHEN_DIRTY can improve battery life and overall system - * performance by allowing the GPU and CPU to idle when the view does not - * need to be updated. - *

- * This method can only be called after - * {@link #setRenderer(ReplicaRenderer)} - * - * @param renderMode - * one of the RENDERMODE_X constants - * @see #RENDERMODE_CONTINUOUSLY - * @see #RENDERMODE_WHEN_DIRTY - */ - public void setRenderMode(int renderMode) { - mGLThread.setRenderMode(renderMode); - } - - /** - * Get the current rendering mode. May be called from any thread. Must not - * be called before a renderer has been set. - * - * @return the current rendering mode. - * @see #RENDERMODE_CONTINUOUSLY - * @see #RENDERMODE_WHEN_DIRTY - */ - public int getRenderMode() { - return mGLThread.getRenderMode(); - } - - /** - * Request that the renderer render a frame. This method is typically used - * when the render mode has been set to {@link #RENDERMODE_WHEN_DIRTY}, so - * that frames are only rendered on demand. May be called from any thread. - * Must not be called before a renderer has been set. - */ - public void requestRender() { - mGLThread.requestRender(); - } - - /** - * This method is part of the SurfaceHolder.Callback interface, and is not - * normally called or subclassed by clients of GLSurfaceView. - */ - @Override - public void surfaceCreated(SurfaceHolder holder) { - mGLThread.surfaceCreated(); - } - - /** - * This method is part of the SurfaceHolder.Callback interface, and is not - * normally called or subclassed by clients of GLSurfaceView. - */ - @Override - public void surfaceDestroyed(SurfaceHolder holder) { - // Surface will be destroyed when we return - mGLThread.surfaceDestroyed(); - } - - /** - * This method is part of the SurfaceHolder.Callback interface, and is not - * normally called or subclassed by clients of GLSurfaceView. - */ - @Override - public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) { - mGLThread.onWindowResize(w, h); - } - - /** - * Inform the view that the activity is paused. The owner of this view must - * call this method when the activity is paused. Calling this method will - * pause the rendering thread. Must not be called before a renderer has been - * set. - */ - public void onPause() { - mGLThread.onPause(); - } - - /** - * Inform the view that the activity is resumed. The owner of this view must - * call this method when the activity is resumed. Calling this method will - * recreate the OpenGL display and resume the rendering thread. Must not be - * called before a renderer has been set. - */ - public void onResume() { - mGLThread.onResume(); - } - - public void setSafeMode(boolean safeMode) { - mGLThread.setSafeMode(safeMode); - } - - /** - * Queue a runnable to be run on the GL rendering thread. This can be used - * to communicate with the Renderer on the rendering thread. Must not be - * called before a renderer has been set. - * - * @param r - * the runnable to be run on the GL rendering thread. - */ - public void queueEvent(Runnable r) { - mGLThread.queueEvent(r); - } - - /** - * Inform the view that the window focus has changed. - */ - @Override - public void onWindowFocusChanged(boolean hasFocus) { - super.onWindowFocusChanged(hasFocus); - mGLThread.onWindowFocusChanged(hasFocus); - } - - /** - * This method is used as part of the View class and is not normally called - * or subclassed by clients of GLSurfaceView. Must not be called before a - * renderer has been set. - */ - @Override - protected void onDetachedFromWindow() { - super.onDetachedFromWindow(); - mGLThread.requestExitAndWait(); - } - - // ---------------------------------------------------------------------- - - /** - * An interface used to wrap a GL interface. - *

- * Typically used for implementing debugging and tracing on top of the - * default GL interface. You would typically use this by creating your own - * class that implemented all the GL methods by delegating to another GL - * instance. Then you could add your own behavior before or after calling - * the delegate. All the GLWrapper would do was instantiate and return the - * wrapper GL instance: - * - *

-	 * class MyGLWrapper implements GLWrapper {
-	 *     GL wrap(GL gl) {
-	 *         return new MyGLImplementation(gl);
-	 *     }
-	 *     static class MyGLImplementation implements GL,GL10,GL11,... {
-	 *         ...
-	 *     }
-	 * }
-	 * 
- * - * @see #setGLWrapper(GLWrapper) - */ - public interface GLWrapper { - /** - * Wraps a gl interface in another gl interface. - * - * @param gl - * a GL interface that is to be wrapped. - * @return either the input argument or another GL object that wraps the - * input argument. - */ - GL wrap(GL gl); - } - - /** - * A generic renderer interface. - *

- * The renderer is responsible for making OpenGL calls to render a frame. - *

- * GLSurfaceView clients typically create their own classes that implement - * this interface, and then call {@link ReplicaGLSurfaceView#setRenderer} to - * register the renderer with the GLSurfaceView. - *

- *

Threading

- * The renderer will be called on a separate thread, so that rendering - * performance is decoupled from the UI thread. Clients typically need to - * communicate with the renderer from the UI thread, because that's where - * input events are received. Clients can communicate using any of the - * standard Java techniques for cross-thread communication, or they can use - * the {@link ReplicaGLSurfaceView#queueEvent(Runnable)} convenience method. - *

- *

EGL Context Lost

- * There are situations where the EGL rendering context will be lost. This - * typically happens when device wakes up after going to sleep. When the EGL - * context is lost, all OpenGL resources (such as textures) that are - * associated with that context will be automatically deleted. In order to - * keep rendering correctly, a renderer must recreate any lost resources - * that it still needs. The {@link #onSurfaceCreated(GL10, EGLConfig)} - * method is a convenient place to do this. - * - * - * @see #setRenderer(ReplicaRenderer) - */ - public interface ReplicaRenderer { - /** - * Called when the surface is created or recreated. - *

- * Called when the rendering thread starts and whenever the EGL context - * is lost. The context will typically be lost when the Android device - * awakes after going to sleep. - *

- * Since this method is called at the beginning of rendering, as well as - * every time the EGL context is lost, this method is a convenient place - * to put code to create resources that need to be created when the - * rendering starts, and that need to be recreated when the EGL context - * is lost. Textures are an example of a resource that you might want to - * create here. - *

- * Note that when the EGL context is lost, all OpenGL resources - * associated with that context will be automatically deleted. You do - * not need to call the corresponding "glDelete" methods such as - * glDeleteTextures to manually delete these lost resources. - *

- * - * @param gl - * the GL interface. Use instanceof to test if - * the interface supports GL11 or higher interfaces. - * @param config - * the EGLConfig of the created surface. Can be used to - * create matching pbuffers. - */ - void onSurfaceCreated(GL10 gl, EGLConfig config); - - /** - * Called when the surface changed size. - *

- * Called after the surface is created and whenever the OpenGL ES - * surface size changes. - *

- * Typically you will set your viewport here. If your camera is fixed - * then you could also set your projection matrix here: - * - *

-		 * void onSurfaceChanged(GL10 gl, int width, int height) {
-		 * 	gl.glViewport(0, 0, width, height);
-		 * 	// for a fixed camera, set the projection too
-		 * 	float ratio = (float) width / height;
-		 * 	gl.glMatrixMode(GL10.GL_PROJECTION);
-		 * 	gl.glLoadIdentity();
-		 * 	gl.glFrustumf(-ratio, ratio, -1, 1, 1, 10);
-		 * }
-		 * 
- * - * @param gl - * the GL interface. Use instanceof to test if - * the interface supports GL11 or higher interfaces. - * @param width - * @param height - */ - void onSurfaceChanged(GL10 gl, int width, int height); - - /** - * Called to draw the current frame. - *

- * This method is responsible for drawing the current frame. - *

- * The implementation of this method typically looks like this: - * - *

-		 * void onDrawFrame(GL10 gl) {
-		 * 	gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
-		 * 	// ... other gl calls to render the scene ...
-		 * }
-		 * 
- * - * @param gl - * the GL interface. Use instanceof to test if - * the interface supports GL11 or higher interfaces. - */ - void onDrawFrame(GL10 gl); - - } - - /** - * An interface for customizing the eglCreateContext and eglDestroyContext - * calls. - *

- * This interface must be implemented by clients wishing to call - * {@link ReplicaGLSurfaceView#setEGLContextFactory(EGLContextFactory)} - */ - public interface EGLContextFactory { - EGLContext createContext(EGL10 egl, EGLDisplay display, - EGLConfig eglConfig); - - void destroyContext(EGL10 egl, EGLDisplay display, EGLContext context); - } - - private class DefaultContextFactory implements EGLContextFactory { - private int EGL_CONTEXT_CLIENT_VERSION = 0x3098; - - @Override - public EGLContext createContext(EGL10 egl, EGLDisplay display, - EGLConfig config) { - int[] attrib_list = { EGL_CONTEXT_CLIENT_VERSION, - mEGLContextClientVersion, EGL10.EGL_NONE }; - - return egl.eglCreateContext(display, config, EGL10.EGL_NO_CONTEXT, - mEGLContextClientVersion != 0 ? attrib_list : null); - } - - @Override - public void destroyContext(EGL10 egl, EGLDisplay display, - EGLContext context) { - egl.eglDestroyContext(display, context); - } - } - - /** - * An interface for customizing the eglCreateWindowSurface and - * eglDestroySurface calls. - *

- * This interface must be implemented by clients wishing to call - * {@link ReplicaGLSurfaceView#setEGLWindowSurfaceFactory(EGLWindowSurfaceFactory)} - */ - public interface EGLWindowSurfaceFactory { - EGLSurface createWindowSurface(EGL10 egl, EGLDisplay display, - EGLConfig config, Object nativeWindow); - - void destroySurface(EGL10 egl, EGLDisplay display, EGLSurface surface); - } - - private static class DefaultWindowSurfaceFactory implements - EGLWindowSurfaceFactory { - - @Override - public EGLSurface createWindowSurface(EGL10 egl, EGLDisplay display, - EGLConfig config, Object nativeWindow) { - return egl.eglCreateWindowSurface(display, config, nativeWindow, - null); - } - - @Override - public void destroySurface(EGL10 egl, EGLDisplay display, - EGLSurface surface) { - egl.eglDestroySurface(display, surface); - } - } - - /** - * An interface for choosing an EGLConfig configuration from a list of - * potential configurations. - *

- * This interface must be implemented by clients wishing to call - * {@link ReplicaGLSurfaceView#setEGLConfigChooser(EGLConfigChooser)} - */ - public interface EGLConfigChooser { - /** - * Choose a configuration from the list. Implementors typically - * implement this method by calling {@link EGL10#eglChooseConfig} and - * iterating through the results. Please consult the EGL specification - * available from The Khronos Group to learn how to call - * eglChooseConfig. - * - * @param egl - * the EGL10 for the current display. - * @param display - * the current display. - * @return the chosen configuration. - */ - EGLConfig chooseConfig(EGL10 egl, EGLDisplay display); - } - - private abstract class BaseConfigChooser implements EGLConfigChooser { - public BaseConfigChooser(int[] configSpec) { - mConfigSpec = filterConfigSpec(configSpec); - } - - @Override - public EGLConfig chooseConfig(EGL10 egl, EGLDisplay display) { - int[] num_config = new int[1]; - if (!egl.eglChooseConfig(display, mConfigSpec, null, 0, num_config)) { - throw new IllegalArgumentException("eglChooseConfig failed"); - } - - int numConfigs = num_config[0]; - - if (numConfigs <= 0) { - throw new IllegalArgumentException( - "No configs match configSpec"); - } - - EGLConfig[] configs = new EGLConfig[numConfigs]; - if (!egl.eglChooseConfig(display, mConfigSpec, configs, numConfigs, - num_config)) { - throw new IllegalArgumentException("eglChooseConfig#2 failed"); - } - EGLConfig config = chooseConfig(egl, display, configs); - if (config == null) { - throw new IllegalArgumentException("No config chosen"); - } - return config; - } - - abstract EGLConfig chooseConfig(EGL10 egl, EGLDisplay display, - EGLConfig[] configs); - - protected int[] mConfigSpec; - - private int[] filterConfigSpec(int[] configSpec) { - if (mEGLContextClientVersion != 2) { - return configSpec; - } - /* - * We know none of the subclasses define EGL_RENDERABLE_TYPE. And we - * know the configSpec is well formed. - */ - int len = configSpec.length; - int[] newConfigSpec = new int[len + 2]; - System.arraycopy(configSpec, 0, newConfigSpec, 0, len - 1); - newConfigSpec[len - 1] = EGL10.EGL_RENDERABLE_TYPE; - newConfigSpec[len] = 4; /* EGL_OPENGL_ES2_BIT */ - newConfigSpec[len + 1] = EGL10.EGL_NONE; - return newConfigSpec; - } - } - - private class ComponentSizeChooser extends BaseConfigChooser { - public ComponentSizeChooser(int redSize, int greenSize, int blueSize, - int alphaSize, int depthSize, int stencilSize) { - super(new int[] { EGL10.EGL_RED_SIZE, redSize, - EGL10.EGL_GREEN_SIZE, greenSize, EGL10.EGL_BLUE_SIZE, - blueSize, EGL10.EGL_ALPHA_SIZE, alphaSize, - EGL10.EGL_DEPTH_SIZE, depthSize, EGL10.EGL_STENCIL_SIZE, - stencilSize, EGL10.EGL_NONE }); - mValue = new int[1]; - mRedSize = redSize; - mGreenSize = greenSize; - mBlueSize = blueSize; - mAlphaSize = alphaSize; - mDepthSize = depthSize; - mStencilSize = stencilSize; - } - - @Override - public EGLConfig chooseConfig(EGL10 egl, EGLDisplay display, - EGLConfig[] configs) { - EGLConfig closestConfig = null; - int closestDistance = 1000; - for (EGLConfig config : configs) { - int d = findConfigAttrib(egl, display, config, - EGL10.EGL_DEPTH_SIZE, 0); - int s = findConfigAttrib(egl, display, config, - EGL10.EGL_STENCIL_SIZE, 0); - if (d >= mDepthSize && s >= mStencilSize) { - int r = findConfigAttrib(egl, display, config, - EGL10.EGL_RED_SIZE, 0); - int g = findConfigAttrib(egl, display, config, - EGL10.EGL_GREEN_SIZE, 0); - int b = findConfigAttrib(egl, display, config, - EGL10.EGL_BLUE_SIZE, 0); - int a = findConfigAttrib(egl, display, config, - EGL10.EGL_ALPHA_SIZE, 0); - int distance = Math.abs(r - mRedSize) - + Math.abs(g - mGreenSize) - + Math.abs(b - mBlueSize) - + Math.abs(a - mAlphaSize); - if (distance < closestDistance) { - closestDistance = distance; - closestConfig = config; - } - } - } - return closestConfig; - } - - private int findConfigAttrib(EGL10 egl, EGLDisplay display, - EGLConfig config, int attribute, int defaultValue) { - - if (egl.eglGetConfigAttrib(display, config, attribute, mValue)) { - return mValue[0]; - } - return defaultValue; - } - - private int[] mValue; - // Subclasses can adjust these values: - protected int mRedSize; - protected int mGreenSize; - protected int mBlueSize; - protected int mAlphaSize; - protected int mDepthSize; - protected int mStencilSize; - } - - /** - * This class will choose a supported surface as close to RGB565 as - * possible, with or without a depth buffer. - * - */ - private class SimpleEGLConfigChooser extends ComponentSizeChooser { - public SimpleEGLConfigChooser(boolean withDepthBuffer) { - super(4, 4, 4, 0, withDepthBuffer ? 16 : 0, 0); - // Adjust target values. This way we'll accept a 4444 or - // 555 buffer if there's no 565 buffer available. - mRedSize = 5; - mGreenSize = 6; - mBlueSize = 5; - } - } - - /** - * An EGL helper class. - */ - - private class EglHelper { - public EglHelper() { - - } - - /** - * Initialize EGL for a given configuration spec. - * - * @param configSpec - */ - public void start() { - /* - * Get an EGL instance - */ - mEgl = (EGL10) EGLContext.getEGL(); - - /* - * Get to the default display. - */ - mEglDisplay = mEgl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY); - - if (mEglDisplay == EGL10.EGL_NO_DISPLAY) { - throw new RuntimeException("eglGetDisplay failed"); - } - - /* - * We can now initialize EGL for that display - */ - int[] version = new int[2]; - if (!mEgl.eglInitialize(mEglDisplay, version)) { - throw new RuntimeException("eglInitialize failed"); - } - mEglConfig = mEGLConfigChooser.chooseConfig(mEgl, mEglDisplay); - - /* - * Create an OpenGL ES context. This must be done only once, an - * OpenGL context is a somewhat heavy object. - */ - mEglContext = mEGLContextFactory.createContext(mEgl, mEglDisplay, - mEglConfig); - if (mEglContext == null || mEglContext == EGL10.EGL_NO_CONTEXT) { - throwEglException("createContext"); - } - - mEglSurface = null; - } - - /* - * React to the creation of a new surface by creating and returning an - * OpenGL interface that renders to that surface. - */ - public GL createSurface(SurfaceHolder holder) { - /* - * The window size has changed, so we need to create a new surface. - */ - if (mEglSurface != null && mEglSurface != EGL10.EGL_NO_SURFACE) { - - /* - * Unbind and destroy the old EGL surface, if there is one. - */ - mEgl.eglMakeCurrent(mEglDisplay, EGL10.EGL_NO_SURFACE, - EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_CONTEXT); - mEGLWindowSurfaceFactory.destroySurface(mEgl, mEglDisplay, - mEglSurface); - } - - /* - * Create an EGL surface we can render into. - */ - mEglSurface = mEGLWindowSurfaceFactory.createWindowSurface(mEgl, - mEglDisplay, mEglConfig, holder); - - if (mEglSurface == null || mEglSurface == EGL10.EGL_NO_SURFACE) { - throwEglException("createWindowSurface"); - } - - /* - * Before we can issue GL commands, we need to make sure the context - * is current and bound to a surface. - */ - if (!mEgl.eglMakeCurrent(mEglDisplay, mEglSurface, mEglSurface, - mEglContext)) { - throwEglException("eglMakeCurrent"); - } - - GL gl = mEglContext.getGL(); - if (mGLWrapper != null) { - gl = mGLWrapper.wrap(gl); - } - - if ((mDebugFlags & (DEBUG_CHECK_GL_ERROR | DEBUG_LOG_GL_CALLS)) != 0) { - int configFlags = 0; - Writer log = null; - if ((mDebugFlags & DEBUG_CHECK_GL_ERROR) != 0) { - configFlags |= GLDebugHelper.CONFIG_CHECK_GL_ERROR; - } - if ((mDebugFlags & DEBUG_LOG_GL_CALLS) != 0) { - log = new LogWriter(); - } - gl = GLDebugHelper.wrap(gl, configFlags, log); - } - return gl; - } - - /** - * Display the current render surface. - * - * @return false if the context has been lost. - */ - public boolean swap() { - mEgl.eglSwapBuffers(mEglDisplay, mEglSurface); - - /* - * Always check for EGL_CONTEXT_LOST, which means the context and - * all associated data were lost (For instance because the device - * went to sleep). We need to sleep until we get a new surface. - */ - return mEgl.eglGetError() != EGL11.EGL_CONTEXT_LOST; - } - - public void destroySurface() { - if (mEglSurface != null && mEglSurface != EGL10.EGL_NO_SURFACE) { - mEgl.eglMakeCurrent(mEglDisplay, EGL10.EGL_NO_SURFACE, - EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_CONTEXT); - mEGLWindowSurfaceFactory.destroySurface(mEgl, mEglDisplay, - mEglSurface); - mEglSurface = null; - } - } - - public void finish() { - if (mEglContext != null) { - mEGLContextFactory.destroyContext(mEgl, mEglDisplay, - mEglContext); - mEglContext = null; - } - if (mEglDisplay != null) { - mEgl.eglTerminate(mEglDisplay); - mEglDisplay = null; - } - } - - private void throwEglException(String function) { - throw new RuntimeException(function + " failed: " - + mEgl.eglGetError()); - } - - /** Checks to see if the current context is valid. **/ - public boolean verifyContext() { - EGLContext currentContext = mEgl.eglGetCurrentContext(); - return currentContext != EGL10.EGL_NO_CONTEXT - && mEgl.eglGetError() != EGL11.EGL_CONTEXT_LOST; - } - - EGL10 mEgl; - EGLDisplay mEglDisplay; - EGLSurface mEglSurface; - EGLConfig mEglConfig; - EGLContext mEglContext; - - } - - /** - * A generic GL Thread. Takes care of initializing EGL and GL. Delegates to - * a Renderer instance to do the actual drawing. Can be configured to render - * continuously or on request. - * - * All potentially blocking synchronization is done through the - * sGLThreadManager object. This avoids multiple-lock ordering issues. - * - */ - private class GLThread extends Thread { - public GLThread(ReplicaRenderer renderer) { - super(); - mWidth = 0; - mHeight = 0; - mRequestRender = true; - mRenderMode = RENDERMODE_CONTINUOUSLY; - mRenderer = renderer; - } - - @Override - public void run() { - setName("GLThread " + getId()); - if (LOG_THREADS) { - Log.i("GLThread", "starting tid=" + getId()); - } - - try { - guardedRun(); - } catch (InterruptedException e) { - // fall thru and exit normally - } finally { - sGLThreadManager.threadExiting(this); - } - } - - /* - * This private method should only be called inside a - * synchronized(sGLThreadManager) block. - */ - private void stopEglLocked() { - if (mHaveEglSurface) { - mHaveEglSurface = false; - mEglHelper.destroySurface(); - sGLThreadManager.releaseEglSurfaceLocked(this); - } - } - - private void guardedRun() throws InterruptedException { - mEglHelper = new EglHelper(); - mHaveEglContext = false; - mHaveEglSurface = false; - try { - GL10 gl = null; - boolean createEglSurface = false; - boolean sizeChanged = false; - boolean wantRenderNotification = false; - boolean doRenderNotification = false; - int w = 0; - int h = 0; - Runnable event = null; - int framesSinceResetHack = 0; - while (true) { - synchronized (sGLThreadManager) { - while (true) { - if (mShouldExit) { - return; - } - - if (!mEventQueue.isEmpty()) { - event = mEventQueue.remove(0); - break; - } - - // Do we need to release the EGL surface? - if (mHaveEglSurface && mPaused) { - if (LOG_SURFACE) { - Log.i("GLThread", - "releasing EGL surface because paused tid=" - + getId()); - } - stopEglLocked(); - } - - // Have we lost the surface view surface? - if ((!mHasSurface) && (!mWaitingForSurface)) { - if (LOG_SURFACE) { - Log.i("GLThread", - "noticed surfaceView surface lost tid=" - + getId()); - } - if (mHaveEglSurface) { - stopEglLocked(); - } - mWaitingForSurface = true; - sGLThreadManager.notifyAll(); - } - - // Have we acquired the surface view surface? - if (mHasSurface && mWaitingForSurface) { - if (LOG_SURFACE) { - Log.i("GLThread", - "noticed surfaceView surface acquired tid=" - + getId()); - } - mWaitingForSurface = false; - sGLThreadManager.notifyAll(); - } - - if (doRenderNotification) { - wantRenderNotification = false; - doRenderNotification = false; - mRenderComplete = true; - sGLThreadManager.notifyAll(); - } - - // Ready to draw? - if ((!mPaused) - && mHasSurface - && (mWidth > 0) - && (mHeight > 0) - && (mRequestRender || (mRenderMode == RENDERMODE_CONTINUOUSLY))) { - - if (mHaveEglContext && !mHaveEglSurface) { - // Let's make sure the context hasn't been - // lost. - if (!mEglHelper.verifyContext()) { - mEglHelper.finish(); - mHaveEglContext = false; - } - } - // If we don't have an egl surface, try to - // acquire one. - if ((!mHaveEglContext) - && sGLThreadManager - .tryAcquireEglSurfaceLocked(this)) { - mHaveEglContext = true; - mEglHelper.start(); - - sGLThreadManager.notifyAll(); - } - - if (mHaveEglContext && !mHaveEglSurface) { - mHaveEglSurface = true; - createEglSurface = true; - sizeChanged = true; - } - - if (mHaveEglSurface) { - if (mSizeChanged) { - sizeChanged = true; - w = mWidth; - h = mHeight; - wantRenderNotification = true; - - if (DRAW_TWICE_AFTER_SIZE_CHANGED) { - // We keep mRequestRender true so - // that we draw twice after the size - // changes. - // (Once because of mSizeChanged, - // the second time because of - // mRequestRender.) - // This forces the updated graphics - // onto the screen. - } else { - mRequestRender = false; - } - mSizeChanged = false; - } else { - mRequestRender = false; - } - sGLThreadManager.notifyAll(); - break; - } - } - - // By design, this is the only place in a GLThread - // thread where we wait(). - if (LOG_THREADS) { - Log.i("GLThread", "waiting tid=" + getId()); - } - sGLThreadManager.wait(); - } - } // end of synchronized(sGLThreadManager) - - if (event != null) { - event.run(); - event = null; - continue; - } - - if (mHasFocus) { - if (createEglSurface) { - gl = (GL10) mEglHelper.createSurface(getHolder()); - sGLThreadManager.checkGLDriver(gl); - if (LOG_RENDERER) { - Log.w("GLThread", "onSurfaceCreated"); - } - mGL = gl; - mRenderer.onSurfaceCreated(gl, - mEglHelper.mEglConfig); - createEglSurface = false; - framesSinceResetHack = 0; - } - - if (sizeChanged) { - if (LOG_RENDERER) { - Log.w("GLThread", "onSurfaceChanged(" + w - + ", " + h + ")"); - } - mRenderer.onSurfaceChanged(gl, w, h); - sizeChanged = false; - } - - if (LOG_RENDERER) { - Log.w("GLThread", "onDrawFrame"); - } - - // Some phones (Motorola Cliq, Backflip; also the - // Huawei Pulse, and maybe the Samsung Behold II), use a - // broken graphics driver from Qualcomm. It fails in a - // very specific case: when the EGL context is lost due - // to - // resource constraints, and then recreated, if GL - // commands - // are sent within two frames of the surface being - // created - // then eglSwapBuffers() will hang. Normally, - // applications using - // the stock GLSurfaceView never run into this problem - // because it - // discards the EGL context explicitly on every pause. - // But - // I've modified this class to not do that--I only want - // to reload - // textures when the context is actually lost--so this - // bug - // revealed itself as black screens on devices like the - // Cliq. - // Thus, in "safe mode," I force two swaps to occur - // before - // issuing any GL commands. Don't ask me how long it - // took - // to figure this out. - if (framesSinceResetHack > 1 || !mSafeMode) { - mRenderer.onDrawFrame(gl); - } else { - Log.w("GLThread", "Safe Mode Wait..."); - } - - framesSinceResetHack++; - - if (!mEglHelper.swap()) { - if (LOG_SURFACE) { - Log.i("GLThread", "egl surface lost tid=" - + getId()); - } - - stopEglLocked(); - } - - } - if (wantRenderNotification) { - doRenderNotification = true; - } - } - - } finally { - mGL = null; - /* - * clean-up everything... - */ - synchronized (sGLThreadManager) { - stopEglLocked(); - mEglHelper.finish(); - } - } - } - - public void setRenderMode(int renderMode) { - if (!((RENDERMODE_WHEN_DIRTY <= renderMode) && (renderMode <= RENDERMODE_CONTINUOUSLY))) { - throw new IllegalArgumentException("renderMode"); - } - synchronized (sGLThreadManager) { - mRenderMode = renderMode; - sGLThreadManager.notifyAll(); - } - } - - public int getRenderMode() { - synchronized (sGLThreadManager) { - return mRenderMode; - } - } - - public void requestRender() { - synchronized (sGLThreadManager) { - mRequestRender = true; - sGLThreadManager.notifyAll(); - } - } - - public void surfaceCreated() { - synchronized (sGLThreadManager) { - if (LOG_THREADS) { - Log.i("GLThread", "surfaceCreated tid=" + getId()); - } - mHasSurface = true; - sGLThreadManager.notifyAll(); - } - } - - public void surfaceDestroyed() { - synchronized (sGLThreadManager) { - if (LOG_THREADS) { - Log.i("GLThread", "surfaceDestroyed tid=" + getId()); - } - mHasSurface = false; - sGLThreadManager.notifyAll(); - while ((!mWaitingForSurface) && (!mExited)) { - try { - sGLThreadManager.wait(); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - } - } - } - } - - public void onPause() { - synchronized (sGLThreadManager) { - mPaused = true; - sGLThreadManager.notifyAll(); - } - } - - public void onResume() { - synchronized (sGLThreadManager) { - mPaused = false; - mRequestRender = true; - sGLThreadManager.notifyAll(); - } - } - - public void onWindowResize(int w, int h) { - synchronized (sGLThreadManager) { - mWidth = w; - mHeight = h; - mSizeChanged = true; - mRequestRender = true; - mRenderComplete = false; - sGLThreadManager.notifyAll(); - - // Wait for thread to react to resize and render a frame - while (!mExited && !mPaused && !mRenderComplete) { - if (LOG_SURFACE) { - Log.i("Main thread", - "onWindowResize waiting for render complete."); - } - try { - sGLThreadManager.wait(); - } catch (InterruptedException ex) { - Thread.currentThread().interrupt(); - } - } - } - } - - // On some Qualcomm devices (such as the HTC Magic running Android 1.6), - // there's a bug in the graphics driver that will cause glViewport() to - // do the wrong thing in a very specific situation. When the screen is - // rotated, if a surface is created in one layout (say, portrait view) - // and then rotated to another, subsequent calls to glViewport are - // clipped. - // So, if the window is, say, 320x480 when the surface is created, and - // then the rotation occurs and glViewport() is called with the new - // size of 480x320, devices with the buggy driver will clip the viewport - // to the old width (which means 320x320...ugh!). This is fixed in - // Android 2.1 Qualcomm devices (like Nexus One) and doesn't affect - // non-Qualcomm devices (like the Motorola DROID). - // - // Unfortunately, under Android 1.6 this exact case occurs when the - // screen is put to sleep and then wakes up again. The lock screen - // comes up in portrait mode, but at the same time the window surface - // is also created in the backgrounded game. When the lock screen is - // closed - // and the game comes forward, the window is fixed to the correct size - // which causes the bug to occur. - - // The solution used here is to simply never render when the window - // surface - // does not have the focus. When the lock screen (or menu) is up, - // rendering - // will stop. This resolves the driver bug (as the egl surface won't be - // created - // until after the screen size has been fixed), and is generally good - // practice - // since you don't want to be doing a lot of CPU intensive work when the - // lock - // screen is up (to preserve battery life). - - public void onWindowFocusChanged(boolean hasFocus) { - synchronized (sGLThreadManager) { - mHasFocus = hasFocus; - sGLThreadManager.notifyAll(); - } - if (LOG_SURFACE) { - Log.i("Main thread", "Focus " + (mHasFocus ? "gained" : "lost")); - } - - } - - public void requestExitAndWait() { - // don't call this from GLThread thread or it is a guaranteed - // deadlock! - synchronized (sGLThreadManager) { - mShouldExit = true; - sGLThreadManager.notifyAll(); - while (!mExited) { - try { - sGLThreadManager.wait(); - } catch (InterruptedException ex) { - Thread.currentThread().interrupt(); - } - } - } - } - - /** - * Queue an "event" to be run on the GL rendering thread. - * - * @param r - * the runnable to be run on the GL rendering thread. - */ - public void queueEvent(Runnable r) { - if (r == null) { - throw new IllegalArgumentException("r must not be null"); - } - synchronized (sGLThreadManager) { - mEventQueue.add(r); - sGLThreadManager.notifyAll(); - } - } - - public void setSafeMode(boolean on) { - mSafeMode = on; - } - - // Once the thread is started, all accesses to the following member - // variables are protected by the sGLThreadManager monitor - private boolean mShouldExit; - private boolean mExited; - private boolean mPaused; - private boolean mHasSurface; - private boolean mWaitingForSurface; - private boolean mHaveEglContext; - private boolean mHaveEglSurface; - private int mWidth; - private int mHeight; - private int mRenderMode; - private boolean mRequestRender; - private boolean mRenderComplete; - private ArrayList mEventQueue = new ArrayList(); - private GL10 mGL; - private boolean mHasFocus; - private boolean mSafeMode = false; - - // End of member variables protected by the sGLThreadManager monitor. - - private ReplicaRenderer mRenderer; - private EglHelper mEglHelper; - } - - static class LogWriter extends Writer { - - @Override - public void close() { - flushBuilder(); - } - - @Override - public void flush() { - flushBuilder(); - } - - @Override - public void write(char[] buf, int offset, int count) { - for (int i = 0; i < count; i++) { - char c = buf[offset + i]; - if (c == '\n') { - flushBuilder(); - } else { - mBuilder.append(c); - } - } - } - - private void flushBuilder() { - if (mBuilder.length() > 0) { - Log.v("GLSurfaceView", mBuilder.toString()); - mBuilder.delete(0, mBuilder.length()); - } - } - - private StringBuilder mBuilder = new StringBuilder(); - } - - private void checkRenderThreadState() { - if (mGLThread != null) { - throw new IllegalStateException( - "setRenderer has already been called for this instance."); - } - } - - private static class GLThreadManager { - - public synchronized void threadExiting(GLThread thread) { - if (LOG_THREADS) { - Log.i("GLThread", "exiting tid=" + thread.getId()); - } - thread.mExited = true; - if (mEglOwner == thread) { - mEglOwner = null; - } - notifyAll(); - } - - /* - * Tries once to acquire the right to use an EGL surface. Does not - * block. Requires that we are already in the sGLThreadManager monitor - * when this is called. - * - * @return true if the right to use an EGL surface was acquired. - */ - public boolean tryAcquireEglSurfaceLocked(GLThread thread) { - if (mEglOwner == thread || mEglOwner == null) { - mEglOwner = thread; - notifyAll(); - return true; - } - checkGLESVersion(); - if (mMultipleGLESContextsAllowed) { - return true; - } - return false; - } - - /* - * Releases the EGL surface. Requires that we are already in the - * sGLThreadManager monitor when this is called. - */ - public void releaseEglSurfaceLocked(GLThread thread) { - if (mEglOwner == thread) { - mEglOwner = null; - } - notifyAll(); - } - - public synchronized void checkGLDriver(GL10 gl) { - if (!mGLESDriverCheckComplete) { - checkGLESVersion(); - if (mGLESVersion < kGLES_20) { - String renderer = gl.glGetString(GL10.GL_RENDERER); - mMultipleGLESContextsAllowed = false; - notifyAll(); - } - mGLESDriverCheckComplete = true; - } - } - - private void checkGLESVersion() { - if (!mGLESVersionCheckComplete) { - mGLESVersion = ConfigurationInfo.GL_ES_VERSION_UNDEFINED; - if (mGLESVersion >= kGLES_20) { - mMultipleGLESContextsAllowed = true; - } - mGLESVersionCheckComplete = true; - } - - } - - private boolean mGLESVersionCheckComplete; - private int mGLESVersion; - private boolean mGLESDriverCheckComplete; - private boolean mMultipleGLESContextsAllowed; - private int mGLContextCount; - private static final int kGLES_20 = 0x20000; - private GLThread mEglOwner; - - } - - private static final GLThreadManager sGLThreadManager = new GLThreadManager(); - private boolean mSizeChanged = true; - - private GLThread mGLThread; - private EGLConfigChooser mEGLConfigChooser; - private EGLContextFactory mEGLContextFactory; - private EGLWindowSurfaceFactory mEGLWindowSurfaceFactory; - private GLWrapper mGLWrapper; - private int mDebugFlags; - private int mEGLContextClientVersion; - -} diff --git a/droidar/src/gui/InfoScreen.java b/droidar/src/gui/InfoScreen.java deleted file mode 100644 index 84623dd..0000000 --- a/droidar/src/gui/InfoScreen.java +++ /dev/null @@ -1,124 +0,0 @@ -package gui; - -import system.ActivityConnector; -import android.app.Activity; -import android.os.Bundle; -import android.util.Log; -import android.view.View; -import android.view.View.OnClickListener; -import android.view.Window; -import android.widget.Button; -import android.widget.LinearLayout; -import android.widget.ScrollView; -import android.widget.TextView; -import de.rwth.R; - -/** - * This screen can be used to display an introduction to the user when the AR - * view is displayed. - * - * TODO improve and integrate into smartui - * - * @author Spobo - * - */ -public class InfoScreen extends Activity { - - protected static final long AUTO_CLOSE_TIME = 3000; - private static final String LOG_TAG = "InfoScreen"; - private InfoScreenSettings myInfoSettings; - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - requestWindowFeature(Window.FEATURE_NO_TITLE); - setContentView(R.layout.infoscreen); - - Object infos = ActivityConnector.getInstance() - .loadObjFromNewlyCreatedActivity(this); - - if (infos instanceof InfoScreenSettings) { - myInfoSettings = (InfoScreenSettings) infos; - addContent((ScrollView) findViewById(R.id.infoScreenScrollview)); - } - - } - - private void addContent(ScrollView s) { - try { - InfoScreenSettings infos = getInfoScreenSettings(); - if (infos.backgroundColor != null) - s.setBackgroundColor(infos.backgroundColor.toIntARGB()); - LinearLayout linLayBox = infos.getLinLayout(); - fixPossibleParentProblem(linLayBox); - s.addView(linLayBox); - if (!infos.closeInstantly()) { - infos.getLinLayout().addView(newCloseButton(infos)); - } else { - infos.getLinLayout().addView(newLoadingInfo(infos)); - } - } catch (Exception e) { - e.printStackTrace(); - } - - } - - private void fixPossibleParentProblem(LinearLayout linLayBox) { - if (linLayBox.getParent() != null) { - Log.e(LOG_TAG, - "The lin.layout of the info screen already had a parent!"); - if (linLayBox.getParent() instanceof LinearLayout) { - ((LinearLayout) linLayBox.getParent()).removeView(linLayBox); - } - } - } - - private InfoScreenSettings getInfoScreenSettings() { - if (myInfoSettings == null) { - Log.e(LOG_TAG, - "The info settings where null, created dummy info settings"); - myInfoSettings = new InfoScreenSettings(getApplicationContext()); - myInfoSettings.setCloseInstantly(); - } - return myInfoSettings; - } - - private View newLoadingInfo(InfoScreenSettings infos) { - TextView t = new TextView(this); - t.setText(infos.getLoadingText()); - return t; - } - - private View newCloseButton(InfoScreenSettings infos) { - Button b = new Button(this); - b.setText(infos.getCloseButtonText()); - b.setOnClickListener(new OnClickListener() { - - @Override - public void onClick(View v) { - InfoScreen.this.finish(); - } - }); - return b; - } - - @Override - protected void onPostResume() { - super.onPostResume(); - - new Thread(new Runnable() { - - @Override - public void run() { - try { - Thread.sleep(AUTO_CLOSE_TIME); - } catch (InterruptedException e) { - e.printStackTrace(); - } - if (getInfoScreenSettings().closeInstantly()) - InfoScreen.this.finish(); - } - }).start(); - } - -} diff --git a/droidar/src/preview/AugmentedView.java b/droidar/src/preview/AugmentedView.java index 07ae397..d5c9f07 100644 --- a/droidar/src/preview/AugmentedView.java +++ b/droidar/src/preview/AugmentedView.java @@ -3,7 +3,6 @@ import gl.CustomGLSurfaceView; import gl.GL1Renderer; import android.content.Context; -import android.view.SurfaceView; import android.view.View; import android.widget.FrameLayout; import de.rwth.R; diff --git a/droidar/src/system/EventManager.java b/droidar/src/system/EventManager.java index 93aacee..68a4549 100644 --- a/droidar/src/system/EventManager.java +++ b/droidar/src/system/EventManager.java @@ -25,6 +25,7 @@ import android.os.Bundle; import android.view.KeyEvent; import android.view.MotionEvent; + import commands.Command; /** @@ -109,8 +110,8 @@ protected void registerSensorUpdates(Activity myTargetActivity, Sensor accelSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); Sensor sensorFusion = sensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR); Sensor magnetSensor = sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD); - ARLogger.debug(LOG_TAG, "Registering Sensors: \nAccel>: " + accelSensor - + "\nRotatationVector>: " + sensorFusion + ARLogger.debug(LOG_TAG, "Registering Sensors: \nAccel>: " + accelSensor + + "\nRotatationVector>: " + sensorFusion + "\nMagnet>: " + magnetSensor); sensorManager.registerListener(this, accelSensor,SensorManager.SENSOR_DELAY_GAME); sensorManager.registerListener(this, magnetSensor,SensorManager.SENSOR_DELAY_GAME); @@ -155,8 +156,13 @@ public void onSensorChanged(SensorEvent event) { // event.sensor.getType() != Sensor.TYPE_ACCELEROMETER) { // return; //} + float[] values = event.values.clone(); + if ((values[0] == 0) && (values[1] == 0) && (values[2] == 0)) { + return; + } + if (onOrientationChangedList != null) { for (int i = 0; i < onOrientationChangedList.size(); i++) { @@ -251,7 +257,7 @@ public void addOnKeyPressedCommand(int keycode, Command c) { public boolean onKeyDown(int keyCode, KeyEvent event) { - if (keyCode >= 19 && keyCode <= 22) { + if ((keyCode >= 19) && (keyCode <= 22)) { /* * if the keycode is on of the numbers from 19 to 22 it is a pseudo * trackball event (eg the motorola milestone has pseudo trackball). diff --git a/droidar/src/system/StepSettingsControllerView.java b/droidar/src/system/StepSettingsControllerView.java deleted file mode 100644 index c031a95..0000000 --- a/droidar/src/system/StepSettingsControllerView.java +++ /dev/null @@ -1,133 +0,0 @@ -package system; - -import v2.simpleUi.M_Checkbox; -import v2.simpleUi.M_Container; -import v2.simpleUi.M_Double; -import v2.simpleUi.M_Integer; -import android.content.Context; - -public class StepSettingsControllerView extends M_Container { - - public StepSettingsControllerView(Context context) { - - this.add(new M_Checkbox() { - - @Override - public boolean save(boolean newValue) { - SimpleLocationManager.setStepDetectionEnabled(newValue); - return true; - } - - @Override - public boolean loadVar() { - return SimpleLocationManager.isStepDetectionEnabled(); - } - - @Override - public CharSequence getVarName() { - return "StepDetectionEnabled"; - } - }); - - this.add(new M_Double() { - - @Override - public boolean save(double newValue) { - SimpleLocationManager - .setMinimumAverageAccuracy((float) newValue); - return true; - } - - @Override - public double load() { - return SimpleLocationManager.getMinimumAverageAccuracy(); - } - - @Override - public String getVarName() { - return "MinimumAverageAccuracy"; - } - }); - this.add(new M_Integer() { - - @Override - public boolean save(int newValue) { - SimpleLocationManager - .setNumberOfSimulatedStepsInSameDirection(newValue); - return true; - } - - @Override - public int load() { - return SimpleLocationManager - .getNumberOfSimulatedStepsInSameDirection(); - } - - @Override - public String getVarName() { - return "NumberOfSimulatedStepsInSameDirection"; - } - }); - final StepManager sm = SimpleLocationManager.getInstance(context) - .getStepManager(); - if (sm != null) { - - this.add(new M_Double() { - - @Override - public boolean save(double newValue) { - sm.setMinStepPeakSize(newValue); - return true; - } - - @Override - public double load() { - return sm.getMinStepPeakSize(); - } - - @Override - public String getVarName() { - return "MinStepPeakSize"; - } - }); - - this.add(new M_Double() { - - @Override - public boolean save(double newValue) { - sm.setStepLengthInMeter(newValue); - return true; - } - - @Override - public double load() { - return sm.getStepLengthInMeter(); - } - - @Override - public String getVarName() { - return "StepLengthInMeter"; - } - }); - this.add(new M_Integer() { - - @Override - public boolean save(int newValue) { - sm.setMinTimeBetweenSteps(newValue); - return true; - } - - @Override - public int load() { - return sm.getMinTimeBetweenSteps(); - } - - @Override - public String getVarName() { - return "MinTimeBetweenSteps"; - } - }); - - } - } -} diff --git a/droidar/src/util/MagicNumbers.java b/droidar/src/util/MagicNumbers.java new file mode 100644 index 0000000..7eb2b66 --- /dev/null +++ b/droidar/src/util/MagicNumbers.java @@ -0,0 +1,14 @@ +package util; + +/** + * Utility class for storing magic numbers constants. + */ +public final class MagicNumbers { + + private MagicNumbers() { + } + + public static final int MAXTRIX_SIZE = 4; + + +} From 52acb3b766217967af624eec4c54a20b9e8eb68e Mon Sep 17 00:00:00 2001 From: rvieras Date: Fri, 27 Dec 2013 15:16:48 -0500 Subject: [PATCH 10/12] Checkstyle updates and cleanup. --- droidar/src/gl/GLFactory.java | 27 ++--- .../gl/animations/AnimationAlphaBlend.java | 81 ------------- .../src/gl/animations/AnimationBounce.java | 60 +++++----- .../gl/animations/AnimationColorBounce.java | 64 +++++----- .../gl/animations/AnimationColorMorph.java | 26 +++-- .../gl/animations/AnimationFaceToCamera.java | 110 ++++++++++-------- droidar/src/gl/animations/AnimationGrow.java | 41 ++++--- droidar/src/gl/animations/AnimationMove.java | 40 ++++--- droidar/src/gl/animations/AnimationPulse.java | 55 +++++---- .../src/gl/animations/AnimationRotate.java | 24 ++-- .../src/gl/animations/AnimationShrink.java | 27 +++-- .../gl/animations/AnimationSwingRotate.java | 56 +++++---- droidar/src/gl/animations/GLAnimation.java | 8 +- 13 files changed, 291 insertions(+), 328 deletions(-) delete mode 100644 droidar/src/gl/animations/AnimationAlphaBlend.java diff --git a/droidar/src/gl/GLFactory.java b/droidar/src/gl/GLFactory.java index e95b26b..2555169 100644 --- a/droidar/src/gl/GLFactory.java +++ b/droidar/src/gl/GLFactory.java @@ -38,7 +38,7 @@ * @author Spobo * */ -public class GLFactory { +public final class GLFactory { private static final String LOG_TAG = "GLFactory"; @@ -285,7 +285,7 @@ public MeshComponent newGrid(Color netColor, float spaceBetweenNetStrings, int lineCount) { Shape s = new Shape(netColor); s.setLineDrawing(); - float coord = (lineCount - 1) * spaceBetweenNetStrings / 2; + float coord = ((lineCount - 1) * spaceBetweenNetStrings) / 2; Vec start = new Vec(coord, coord, 0); Vec end = new Vec(coord, -coord, 0); for (int i = 0; i < lineCount; i++) { @@ -308,8 +308,9 @@ public MeshComponent newGrid(Color netColor, float spaceBetweenNetStrings, public Obj newSolarSystem(Vec position) { Obj solarSystem = new Obj(); MeshComponent sunBox = new Shape(); - if (position != null) + if (position != null) { sunBox.setPosition(position); + } solarSystem.setComp(sunBox); MeshComponent earthRing = new Shape(); @@ -382,10 +383,10 @@ public Shape newDiamond(Color canBeNull) { Vec e1 = new Vec(-width + c, 0, 0); Vec e4 = new Vec(width - c, 0, 0); - Vec e2 = new Vec(-width / 2 + c, width, 0); - Vec e6 = new Vec(-width / 2 + c, -width, 0); - Vec e3 = new Vec(width / 2 - c, width, 0); - Vec e5 = new Vec(width / 2 - c, -width, 0); + Vec e2 = new Vec((-width / 2) + c, width, 0); + Vec e6 = new Vec((-width / 2) + c, -width, 0); + Vec e3 = new Vec((width / 2) - c, width, 0); + Vec e5 = new Vec((width / 2) - c, -width, 0); s.add(top); s.add(e1); @@ -522,7 +523,7 @@ public Shape newNSidedPolygonWithGaps(int numberOfSides, Color c) { double factor = 360 / numberOfSides; // there have to be n triangles: - for (int i = 0; i < numberOfSides / 2; i++) { + for (int i = 0; i < (numberOfSides / 2); i++) { s.add(v.copy()); v.rotateAroundZAxis(factor); s.add(v.copy()); @@ -540,11 +541,11 @@ public Shape newPyramid(Vec center, float height, Color color) { // side length: float a = HEIGHT_TO_SIDE_FACTOR * Math.abs(height); - Vec p1 = new Vec(center.x - 1f / 2f * a, center.y - 1f / 3f - * Math.abs(height), 0f); - Vec p2 = new Vec(center.x + 1f / 2f * a, center.y - 1f / 3f - * Math.abs(height), 0f); - Vec p3 = new Vec(center.x, center.y + 2f / 3f * Math.abs(height), 0f); + Vec p1 = new Vec(center.x - ((1f / 2f) * a), center.y - ((1f / 3f) + * Math.abs(height)), 0f); + Vec p2 = new Vec(center.x + ((1f / 2f) * a), center.y - ((1f / 3f) + * Math.abs(height)), 0f); + Vec p3 = new Vec(center.x, center.y + ((2f / 3f) * Math.abs(height)), 0f); Vec p4 = new Vec(center.x, center.y, height); p.add(p1); diff --git a/droidar/src/gl/animations/AnimationAlphaBlend.java b/droidar/src/gl/animations/AnimationAlphaBlend.java deleted file mode 100644 index 2d44a0f..0000000 --- a/droidar/src/gl/animations/AnimationAlphaBlend.java +++ /dev/null @@ -1,81 +0,0 @@ -package gl.animations; - -import gl.Color; -import gl.ObjectPicker; -import gl.Renderable; - -import javax.microedition.khronos.opengles.GL10; - -import util.Vec; -import worlddata.Updateable; -import worlddata.Visitor; - -/** - * TODO what is the difference between this and ColorMorph? what was the intend? - * - * @author Spobo - * - */ -public class AnimationAlphaBlend extends GLAnimation { - - private float mySpeed; - private Color myLowerColor; - private Color myUpperColor; - private float myAccur; - private Color myCurrentColor; - private Color myTargetColor; - /** - * true = upperEnd, false = lowerEnd - */ - private boolean mode; - - /** - * @param speed - * should be 0.5 to - * @param startColor - * @param endColor - * @param accur - * 0.2f ood value to start - */ - public AnimationAlphaBlend(float speed, Color startColor, Color endColor, - float accur) { - mySpeed = speed; - myCurrentColor = startColor.copy(); - myTargetColor = endColor.copy(); - myLowerColor = startColor.copy(); - myUpperColor = endColor.copy(); - myAccur = accur; - mode = true; - } - - @Override - public boolean update(float timeDelta, Updateable parent) { - final Vec distance = Color.morphToNewColor(myCurrentColor, - myTargetColor, timeDelta * mySpeed); - - if ((Vec.abs(distance.x) < myAccur) && (Vec.abs(distance.y) < myAccur) - && (Vec.abs(distance.z) < myAccur)) { - if (mode) { - mode = false; - myTargetColor = myLowerColor; - } else { - mode = true; - myTargetColor = myUpperColor; - } - } - return true; - } - - @Override - public void render(GL10 gl, Renderable parent) { - if (!ObjectPicker.readyToDrawWithColor) - gl.glColor4f(myCurrentColor.red, myCurrentColor.green, - myCurrentColor.blue, myCurrentColor.alpha); - - } - - @Override - public boolean accept(Visitor visitor) { - return visitor.default_visit(this); - } -} diff --git a/droidar/src/gl/animations/AnimationBounce.java b/droidar/src/gl/animations/AnimationBounce.java index f34edc1..6688308 100644 --- a/droidar/src/gl/animations/AnimationBounce.java +++ b/droidar/src/gl/animations/AnimationBounce.java @@ -8,50 +8,53 @@ import worlddata.Updateable; import worlddata.Visitor; +/** + * Animation to bounce. + */ public class AnimationBounce extends GLAnimation { - private final int mySpeed; - private final Vec dEnd; - private final Vec uEnd; - private Vec currentPos; - private Vec targetPos; - private float accuracy; - private int mode; // 1=morph to uperEnd 0=morph to lowerEnd + private final int mSpeed; + private final Vec mDEnd; + private final Vec mUEnd; + private Vec mCurrentPos; + private Vec mTargetPos; + private float mAccuracy; + private int mMode; // 1=morph to uperEnd 0=morph to lowerEnd /** * @param speed + * The bounce speed * @param relativeLowerEnd + * lower bound to bounce too * @param relativeUperEnd + * upper bound to bounce too * @param accuracy * should be 0.2f (or something between 0.01f and 0.5f) */ public AnimationBounce(int speed, Vec relativeLowerEnd, Vec relativeUperEnd, float accuracy) { - this.mySpeed = speed; - this.accuracy = accuracy; - this.dEnd = relativeLowerEnd.copy(); - this.uEnd = relativeUperEnd.copy(); - this.currentPos = dEnd.copy(); - this.targetPos = uEnd.copy(); - this.mode = 1; + mSpeed = speed; + mAccuracy = accuracy; + mDEnd = relativeLowerEnd.copy(); + mUEnd = relativeUperEnd.copy(); + mCurrentPos = mDEnd.copy(); + mTargetPos = mUEnd.copy(); + mMode = 1; } @Override public boolean update(float timeDelta, Updateable parent) { - - // TODO this does not bounce nice, better use sort of gravity version - - Vec.morphToNewVec(currentPos, targetPos, timeDelta * mySpeed); - final Vec distance = Vec.sub(currentPos, targetPos); - if ((Vec.abs(distance.x) < accuracy) - && (Vec.abs(distance.y) < accuracy) - && (Vec.abs(distance.z) < accuracy)) { - if (mode == 0) { - mode = 1; - targetPos = uEnd; + Vec.morphToNewVec(mCurrentPos, mTargetPos, timeDelta * mSpeed); + final Vec distance = Vec.sub(mCurrentPos, mTargetPos); + if ((Vec.abs(distance.x) < mAccuracy) + && (Vec.abs(distance.y) < mAccuracy) + && (Vec.abs(distance.z) < mAccuracy)) { + if (mMode == 0) { + mMode = 1; + mTargetPos = mUEnd; } else { - mode = 0; - targetPos = dEnd; + mMode = 0; + mTargetPos = mDEnd; } } return true; @@ -59,12 +62,11 @@ public boolean update(float timeDelta, Updateable parent) { @Override public void render(GL10 gl, Renderable parent) { - gl.glTranslatef(currentPos.x, currentPos.y, currentPos.z); + gl.glTranslatef(mCurrentPos.x, mCurrentPos.y, mCurrentPos.z); } @Override public boolean accept(Visitor visitor) { return visitor.default_visit(this); } - } diff --git a/droidar/src/gl/animations/AnimationColorBounce.java b/droidar/src/gl/animations/AnimationColorBounce.java index e582ce2..a34cdf1 100644 --- a/droidar/src/gl/animations/AnimationColorBounce.java +++ b/droidar/src/gl/animations/AnimationColorBounce.java @@ -10,52 +10,57 @@ import worlddata.Updateable; import worlddata.Visitor; +/** + * Animation to bounce between colors. + * + * @author rvieras + * + */ public class AnimationColorBounce extends GLAnimation { - private float mySpeed; - private Color myLowerColor; - private Color myUpperColor; - private float myAccur; - private Color myCurrentColor; - private Color myTargetColor; - /** - * true = upperEnd, false = lowerEnd - */ - private boolean mode; + private float mSpeed; + private Color mLowerColor; + private Color mUpperColor; + private float mAccur; + private Color mCurrentColor; + private Color mTargetColor; + private boolean mMode; // true = upperEnd, false = lowerEnd /** * @param speed * should be 0.5 to * @param startColor + * The starting color * @param endColor + * The ending color * @param accur * 0.2f ood value to start */ public AnimationColorBounce(float speed, Color startColor, Color endColor, float accur) { - mySpeed = speed; - myCurrentColor = startColor.copy(); - myTargetColor = endColor.copy(); - myLowerColor = startColor.copy(); - myUpperColor = endColor.copy(); - myAccur = accur; - mode = true; + mSpeed = speed; + mCurrentColor = startColor.copy(); + mTargetColor = endColor.copy(); + mLowerColor = startColor.copy(); + mUpperColor = endColor.copy(); + mAccur = accur; + mMode = true; } @Override public boolean update(float timeDelta, Updateable parent) { - final Vec distance = Color.morphToNewColor(myCurrentColor, - myTargetColor, timeDelta * mySpeed); + final Vec distance = Color.morphToNewColor(mCurrentColor, + mTargetColor, timeDelta * mSpeed); - if ((Vec.abs(distance.x) < myAccur) && (Vec.abs(distance.y) < myAccur) - && (Vec.abs(distance.z) < myAccur)) { - if (mode) { - mode = false; - myTargetColor = myLowerColor; + if ((Vec.abs(distance.x) < mAccur) && (Vec.abs(distance.y) < mAccur) + && (Vec.abs(distance.z) < mAccur)) { + if (mMode) { + mMode = false; + mTargetColor = mLowerColor; } else { - mode = true; - myTargetColor = myUpperColor; + mMode = true; + mTargetColor = mUpperColor; } } return true; @@ -64,9 +69,10 @@ public boolean update(float timeDelta, Updateable parent) { @Override public void render(GL10 gl, Renderable parent) { - if (!ObjectPicker.readyToDrawWithColor) - gl.glColor4f(myCurrentColor.red, myCurrentColor.green, - myCurrentColor.blue, myCurrentColor.alpha); + if (!ObjectPicker.readyToDrawWithColor) { + gl.glColor4f(mCurrentColor.red, mCurrentColor.green, + mCurrentColor.blue, mCurrentColor.alpha); + } } diff --git a/droidar/src/gl/animations/AnimationColorMorph.java b/droidar/src/gl/animations/AnimationColorMorph.java index d79fa70..17fe78a 100644 --- a/droidar/src/gl/animations/AnimationColorMorph.java +++ b/droidar/src/gl/animations/AnimationColorMorph.java @@ -11,21 +11,30 @@ import worlddata.Updateable; import worlddata.Visitor; +/** + * Animation to change color. + */ public class AnimationColorMorph extends GLAnimation { private static final float MIN_DISTANCE = 0.001f; - private float myDurationInMS; - private Color myTargetColor; - + private float mDurationInMS; + private Color mTargetColor; + + /** + * Constructor. + * + * @param durationInMS + * The amount of time it takes to change the object color + * @param targetColor + * The target color that the object will turn too + */ public AnimationColorMorph(float durationInMS, Color targetColor) { - myDurationInMS = durationInMS; - myTargetColor = targetColor; + mDurationInMS = durationInMS; + mTargetColor = targetColor; } @Override public void render(GL10 gl, Renderable parent) { - // TODO Auto-generated method stub - } @Override @@ -33,8 +42,7 @@ public boolean update(float timeDelta, Updateable parent) { if (parent instanceof HasColor) { Vec colorDistance = Color.morphToNewColor( - ((HasColor) parent).getColor(), myTargetColor, timeDelta - / myDurationInMS); +((HasColor) parent).getColor(), mTargetColor, timeDelta / mDurationInMS); if (!(colorDistance.getLength() > MIN_DISTANCE)) { Log.d("NodeListener", "color morph finnished for " + parent); } diff --git a/droidar/src/gl/animations/AnimationFaceToCamera.java b/droidar/src/gl/animations/AnimationFaceToCamera.java index 92b65d1..f77341e8 100644 --- a/droidar/src/gl/animations/AnimationFaceToCamera.java +++ b/droidar/src/gl/animations/AnimationFaceToCamera.java @@ -10,21 +10,27 @@ import worlddata.Updateable; import worlddata.Visitor; +/** + * Animation to face the camera. + */ public class AnimationFaceToCamera extends GLAnimation { - - private GLCamera myTargetCamera; - private float lastUpdateAway = 0; - private float myUpdateDelay; - private Vec rotationVec = new Vec(); - private Vec newRotationVec = new Vec(); - - private Vec adjustmentVec; - private Vec myTargetCameraPosition; - private boolean dontChangeXRotation; + private static final float DEFAULT_UPDATE_DELAY = 0.5f; + private static final int ADJUST_OBJECT_ROTATION = 90; + private GLCamera mTargetCamera; + private float mLastUpdateAway = 0; + private float mUpdateDelay; + private Vec mRotationVec = new Vec(); + private Vec mNewRotationVec = new Vec(); + + private Vec mAdjustmentVec; + private Vec mTargetCameraPosition; + private boolean mDontChangeXRotation; /** + * Constructor. + * * @param targetCamera - * @param targetMesh + * {@link GLCamera} * @param updateDelay * around 0.5f s * @param dontChangeXRotation @@ -33,97 +39,100 @@ public class AnimationFaceToCamera extends GLAnimation { */ public AnimationFaceToCamera(GLCamera targetCamera, float updateDelay, boolean dontChangeXRotation) { - myTargetCamera = targetCamera; - - myUpdateDelay = updateDelay; - myTargetCameraPosition = myTargetCamera.getPosition(); - this.dontChangeXRotation = dontChangeXRotation; - // Log.d("face camera animation", "created. camera=" + myTargetCamera - // + " targetMesh class=" + myTargetMesh.getClass() - // + " update delay=" + myUpdateDelay); + mTargetCamera = targetCamera; + + mUpdateDelay = updateDelay; + mTargetCameraPosition = mTargetCamera.getPosition(); + mDontChangeXRotation = dontChangeXRotation; } + /** + * Constructor. + * + * @param targetCamera + * {@link GLCamera} + * @param updateDelay + * The amount of time to update. Normally should be .5fs + */ public AnimationFaceToCamera(GLCamera targetCamera, float updateDelay) { this(targetCamera, updateDelay, true); } + /** + * Constructor. + * + * @param targetCamera + * {@link GLCamera} + */ public AnimationFaceToCamera(GLCamera targetCamera) { - this(targetCamera, 0.5f, true); + this(targetCamera, DEFAULT_UPDATE_DELAY, true); } /** * @param targetCamera - * @param targetMesh + * {@link GLCamera} * @param updateDelay * 0.5f * @param adjustmentVec + * Adjustment vector */ public AnimationFaceToCamera(GLCamera targetCamera, float updateDelay, Vec adjustmentVec) { this(targetCamera, updateDelay); - this.adjustmentVec = adjustmentVec; + mAdjustmentVec = adjustmentVec; } @Override public boolean update(float timeDelta, Updateable parent) { - - /* - * TODO use mesh instead of assigning a mesh while creating this - * animation! - */ timeDelta = Math.abs(timeDelta); - lastUpdateAway += timeDelta; - if (lastUpdateAway > myUpdateDelay) { + mLastUpdateAway += timeDelta; + if (mLastUpdateAway > mUpdateDelay) { updateRotation(parent); - // Log.d("face camera animation", "new rotation vec calculated:"); - // Log.d("face camera animation", - // "x="+newRotationVec.x+" , z="+newRotationVec.z); - lastUpdateAway = 0; + mLastUpdateAway = 0; } - if (dontChangeXRotation) { - Vec.morphToNewAngleVec(rotationVec, 0, 0, newRotationVec.z, + if (mDontChangeXRotation) { + Vec.morphToNewAngleVec(mRotationVec, 0, 0, mNewRotationVec.z, timeDelta); } else { - Vec.morphToNewAngleVec(rotationVec, newRotationVec.x, - newRotationVec.y, newRotationVec.z, timeDelta); + Vec.morphToNewAngleVec(mRotationVec, mNewRotationVec.x, mNewRotationVec.y, mNewRotationVec.z, timeDelta); } return true; } - Vec absolutePosition = new Vec(); + private Vec mAbsolutePosition = new Vec(); private void updateRotation(Updateable parent) { if (parent instanceof MeshComponent) { - absolutePosition.setToZero(); - ((MeshComponent) parent).getAbsoluteMeshPosition(absolutePosition); + mAbsolutePosition.setToZero(); + ((MeshComponent) parent).getAbsoluteMeshPosition(mAbsolutePosition); // Log.d("face camera animation", "mesh position: "+pos); - newRotationVec.toAngleVec(absolutePosition, myTargetCameraPosition); + mNewRotationVec.toAngleVec(mAbsolutePosition, mTargetCameraPosition); /* * substract 90 from the x value becaute calcanglevec returns 90 if * the rotation should be the horizon (which would mean no object * rotation) */ - newRotationVec.x -= 90; - newRotationVec.z *= -1; + mNewRotationVec.x -= ADJUST_OBJECT_ROTATION; + mNewRotationVec.z *= -1; } } @Override public void render(GL10 gl, Renderable parent) { - gl.glRotatef(rotationVec.z, 0, 0, 1); - gl.glRotatef(rotationVec.x, 1, 0, 0); - gl.glRotatef(rotationVec.y, 0, 1, 0); + gl.glRotatef(mRotationVec.z, 0, 0, 1); + gl.glRotatef(mRotationVec.x, 1, 0, 0); + gl.glRotatef(mRotationVec.y, 0, 1, 0); - if (adjustmentVec != null) { + if (mAdjustmentVec != null) { /* * if an adjustment vector is set this adjustment has to be done * AFTER the rotation to be easy to use, see constructor for infos * about adjustment */ - gl.glRotatef(adjustmentVec.x, 1, 0, 0); // TODO find correct order - gl.glRotatef(adjustmentVec.z, 0, 0, 1); - gl.glRotatef(adjustmentVec.y, 0, 1, 0); + gl.glRotatef(mAdjustmentVec.x, 1, 0, 0); + gl.glRotatef(mAdjustmentVec.z, 0, 0, 1); + gl.glRotatef(mAdjustmentVec.y, 0, 1, 0); } } @@ -131,5 +140,4 @@ public void render(GL10 gl, Renderable parent) { public boolean accept(Visitor visitor) { return visitor.default_visit(this); } - } diff --git a/droidar/src/gl/animations/AnimationGrow.java b/droidar/src/gl/animations/AnimationGrow.java index 8c50359..7431545 100644 --- a/droidar/src/gl/animations/AnimationGrow.java +++ b/droidar/src/gl/animations/AnimationGrow.java @@ -4,42 +4,42 @@ import javax.microedition.khronos.opengles.GL10; -import util.Log; import worlddata.UpdateTimer; import worlddata.Updateable; import worlddata.Visitor; +/** + * Animation to show a growing animation. + */ public class AnimationGrow extends GLAnimation { - - private static final String LOG_TAG = "Grow Animation"; - private float myGrothSize; - final private float myGrothFactor; - private UpdateTimer myStopCondition; - + private float mGrothSize; + private float mGrothFactor; + private UpdateTimer mStopCondition; + + /** + * Constructor. + * + * @param timeTillFullGrothInSeconds + * The amount of time to fully grow the animation in seconds. + */ public AnimationGrow(float timeTillFullGrothInSeconds) { - /* - * TODO maybe better to pass the stop condition directly? more flexible? - */ - myStopCondition = new UpdateTimer(timeTillFullGrothInSeconds, null); - myGrothFactor = 1 / timeTillFullGrothInSeconds; - Log.d(LOG_TAG, "My grow factor is " + myGrothFactor); + mStopCondition = new UpdateTimer(timeTillFullGrothInSeconds, null); + mGrothFactor = 1 / timeTillFullGrothInSeconds; } @Override public void render(GL10 gl, Renderable parent) { - gl.glScalef(myGrothSize, myGrothSize, myGrothSize); + gl.glScalef(mGrothSize, mGrothSize, mGrothSize); } @Override public boolean update(float timeDelta, Updateable parent) { - if (myStopCondition.update(timeDelta, parent)) { + if (mStopCondition.update(timeDelta, parent)) { return false; } - myGrothSize += myGrothFactor * timeDelta; - if (myGrothSize > 1) { - myGrothSize = 1; - Log.e(LOG_TAG, - "Grouth was > 1, should not happen when grothFactor correct"); + mGrothSize += mGrothFactor * timeDelta; + if (mGrothSize > 1) { + mGrothSize = 1; } return true; } @@ -48,5 +48,4 @@ public boolean update(float timeDelta, Updateable parent) { public boolean accept(Visitor visitor) { return visitor.default_visit(this); } - } diff --git a/droidar/src/gl/animations/AnimationMove.java b/droidar/src/gl/animations/AnimationMove.java index 5672954..f37c48c 100644 --- a/droidar/src/gl/animations/AnimationMove.java +++ b/droidar/src/gl/animations/AnimationMove.java @@ -8,31 +8,43 @@ import worlddata.Updateable; import worlddata.Visitor; +/** + * Animation to show movement. + */ public class AnimationMove extends GLAnimation { - private final float MIN_DISTANCE = 0.01f; - private float timeToMove; - private Vec relativeTargetPos; - private Vec pos; - private boolean done; - + private static final float MIN_DISTANCE = 0.01f; + private float mTimeToMove; + private Vec mRelativeTargetPos; + private Vec mPos; + private boolean mDone; + + /** + * Constructor. + * + * @param timeToMove + * The amount of time it will take the object to move to + * @param relativeTargetPos} + * @param relativeTargetPos + * The position to move to + */ public AnimationMove(float timeToMove, Vec relativeTargetPos) { - this.timeToMove = timeToMove; - this.relativeTargetPos = relativeTargetPos; - pos = new Vec(); + this.mTimeToMove = timeToMove; + this.mRelativeTargetPos = relativeTargetPos; + mPos = new Vec(); } @Override public void render(GL10 gl, Renderable parent) { - gl.glTranslatef(pos.x, pos.y, pos.z); + gl.glTranslatef(mPos.x, mPos.y, mPos.z); } @Override public boolean update(float timeDelta, Updateable parent) { - if (!done) { - Vec.morphToNewVec(pos, relativeTargetPos, timeDelta / timeToMove); - if (Vec.distance(pos, relativeTargetPos) < MIN_DISTANCE) { - done = true; + if (!mDone) { + Vec.morphToNewVec(mPos, mRelativeTargetPos, timeDelta / mTimeToMove); + if (Vec.distance(mPos, mRelativeTargetPos) < MIN_DISTANCE) { + mDone = true; } } return true; diff --git a/droidar/src/gl/animations/AnimationPulse.java b/droidar/src/gl/animations/AnimationPulse.java index 95fbc1a..97ab43c 100644 --- a/droidar/src/gl/animations/AnimationPulse.java +++ b/droidar/src/gl/animations/AnimationPulse.java @@ -8,47 +8,52 @@ import worlddata.Updateable; import worlddata.Visitor; +/** + * Animation the will pulse the object. + */ public class AnimationPulse extends GLAnimation { - private final float speed; - private final Vec myLowerEnd; - private final Vec myUperEnd; - private Vec currentScale; - private Vec targetScale; - private float accuracy; - private boolean mode; // true=morph to uperEnd false=morph to lowerEnd + private final float mSpeed; + private final Vec mLowerEnd; + private final Vec mUperEnd; + private Vec mCurrentScale; + private Vec mTargetScale; + private float mAccuracy; + private boolean mMode; // true=morph to uperEnd false=morph to lowerEnd /** * @param speed * 1 to 10 * @param lowerEnd + * The lower end to pulse. * @param uperEnd + * The upper end to pulse. * @param accuracy * should be 0.2f (or something between 0.01f and 0.5f) */ public AnimationPulse(float speed, Vec lowerEnd, Vec uperEnd, float accuracy) { - this.speed = speed; - this.accuracy = accuracy; - this.myLowerEnd = lowerEnd.copy(); - this.myUperEnd = uperEnd.copy(); - this.currentScale = myLowerEnd.copy(); - this.targetScale = myUperEnd.copy(); - this.mode = true; + this.mSpeed = speed; + this.mAccuracy = accuracy; + this.mLowerEnd = lowerEnd.copy(); + this.mUperEnd = uperEnd.copy(); + this.mCurrentScale = mLowerEnd.copy(); + this.mTargetScale = mUperEnd.copy(); + this.mMode = true; } @Override public boolean update(float timeDelta, Updateable parent) { - Vec.morphToNewVec(currentScale, targetScale, timeDelta * speed); - final Vec distance = Vec.sub(currentScale, targetScale); - if ((Vec.abs(distance.x) < accuracy) - && (Vec.abs(distance.y) < accuracy) - && (Vec.abs(distance.z) < accuracy)) { - if (mode) { - mode = false; - targetScale = myUperEnd; + Vec.morphToNewVec(mCurrentScale, mTargetScale, timeDelta * mSpeed); + final Vec distance = Vec.sub(mCurrentScale, mTargetScale); + if ((Vec.abs(distance.x) < mAccuracy) + && (Vec.abs(distance.y) < mAccuracy) + && (Vec.abs(distance.z) < mAccuracy)) { + if (mMode) { + mMode = false; + mTargetScale = mUperEnd; } else { - mode = true; - targetScale = myLowerEnd; + mMode = true; + mTargetScale = mLowerEnd; } } return true; @@ -56,7 +61,7 @@ public boolean update(float timeDelta, Updateable parent) { @Override public void render(GL10 gl, Renderable parent) { - gl.glScalef(currentScale.x, currentScale.y, currentScale.z); + gl.glScalef(mCurrentScale.x, mCurrentScale.y, mCurrentScale.z); } @Override diff --git a/droidar/src/gl/animations/AnimationRotate.java b/droidar/src/gl/animations/AnimationRotate.java index 2cf535f..e2b7c78 100644 --- a/droidar/src/gl/animations/AnimationRotate.java +++ b/droidar/src/gl/animations/AnimationRotate.java @@ -1,7 +1,6 @@ package gl.animations; import gl.Renderable; -import gl.scenegraph.MeshComponent; import javax.microedition.khronos.opengles.GL10; @@ -10,44 +9,45 @@ import worlddata.Visitor; /** - * This animation rotates a {@link MeshComponent} + * This animation rotates a {@link gl.scenegraph.MeshComponent}. * * @author Spobo * */ public class AnimationRotate extends GLAnimation { - private float angle = 0; - private final float speed; - private final Vec rotVec; + private static final int FULL_CIRCLE_IN_DEG = 360; + private float mAngle = 0; + private float mSpeed; + private Vec mRotVec; /** * @param speed * something around 30 to 100 * @param rotationVector + * - The rotation vector for this animation. */ public AnimationRotate(float speed, Vec rotationVector) { - this.speed = speed; - rotVec = rotationVector; + this.mSpeed = speed; + mRotVec = rotationVector; } @Override public boolean update(float timeDelta, Updateable parent) { - if (angle > 360) { - angle = 0; + if (mAngle > FULL_CIRCLE_IN_DEG) { + mAngle = 0; } - angle = angle + timeDelta * speed; + mAngle = mAngle + (timeDelta * mSpeed); return true; } @Override public void render(GL10 gl, Renderable parent) { - gl.glRotatef(angle, rotVec.x, rotVec.y, rotVec.z); + gl.glRotatef(mAngle, mRotVec.x, mRotVec.y, mRotVec.z); } @Override public boolean accept(Visitor visitor) { return visitor.default_visit(this); } - } diff --git a/droidar/src/gl/animations/AnimationShrink.java b/droidar/src/gl/animations/AnimationShrink.java index 8e1f090..8cecee5 100644 --- a/droidar/src/gl/animations/AnimationShrink.java +++ b/droidar/src/gl/animations/AnimationShrink.java @@ -4,32 +4,38 @@ import javax.microedition.khronos.opengles.GL10; -import util.Log; import worlddata.Updateable; import worlddata.Visitor; +/** + * Animation to shrink. + */ public class AnimationShrink extends GLAnimation { - private static final String LOG_TAG = "Grow Animation"; - private float myGrothSize = 1; - final private float myShrinkFactor; + private float mGrothSize = 1; + private float mShrinkFactor; + /** + * Constructor. + * + * @param timeTillFullGrothInSeconds + * The time till full size in seconds + */ public AnimationShrink(float timeTillFullGrothInSeconds) { - myShrinkFactor = 1 / timeTillFullGrothInSeconds; - Log.d(LOG_TAG, "My shrink factor is " + myShrinkFactor); + mShrinkFactor = 1 / timeTillFullGrothInSeconds; } @Override public void render(GL10 gl, Renderable parent) { - gl.glScalef(myGrothSize, myGrothSize, myGrothSize); + gl.glScalef(mGrothSize, mGrothSize, mGrothSize); } @Override public boolean update(float timeDelta, Updateable parent) { - if (myGrothSize > 0) { - myGrothSize -= myShrinkFactor * timeDelta; + if (mGrothSize > 0) { + mGrothSize -= mShrinkFactor * timeDelta; } else { - myGrothSize = 0; + mGrothSize = 0; } return true; } @@ -38,5 +44,4 @@ public boolean update(float timeDelta, Updateable parent) { public boolean accept(Visitor visitor) { return visitor.default_visit(this); } - } diff --git a/droidar/src/gl/animations/AnimationSwingRotate.java b/droidar/src/gl/animations/AnimationSwingRotate.java index e8f9ad8..7cb0059 100644 --- a/droidar/src/gl/animations/AnimationSwingRotate.java +++ b/droidar/src/gl/animations/AnimationSwingRotate.java @@ -17,13 +17,13 @@ */ public class AnimationSwingRotate extends GLAnimation { - private final float speed; - private final Vec dEnd; - private final Vec uEnd; - private Vec currentPos; - private Vec targetPos; - private float accuracy; - private int mode; // 1=morph to uperEnd 0=morph to lowerEnd + private final float mSpeed; + private final Vec mDEnd; + private final Vec mUEnd; + private Vec mCurrentPos; + private Vec mTargetPos; + private float mAccuracy; + private int mMode; // 1=morph to uperEnd 0=morph to lowerEnd /** * this works as an metronome, it pendels from lowerEnd vector to upperEnd @@ -41,28 +41,28 @@ public class AnimationSwingRotate extends GLAnimation { */ public AnimationSwingRotate(float speed, Vec lowerEnd, Vec upperEnd, float accuracy) { - this.speed = speed; - this.accuracy = accuracy; - this.dEnd = lowerEnd.copy(); - this.uEnd = upperEnd.copy(); - this.currentPos = dEnd.copy(); - this.targetPos = uEnd.copy(); - this.mode = 1; + this.mSpeed = speed; + this.mAccuracy = accuracy; + this.mDEnd = lowerEnd.copy(); + this.mUEnd = upperEnd.copy(); + this.mCurrentPos = mDEnd.copy(); + this.mTargetPos = mUEnd.copy(); + this.mMode = 1; } @Override public boolean update(float timeDelta, Updateable parent) { - Vec.morphToNewVec(currentPos, targetPos, timeDelta * speed); - final Vec distance = Vec.sub(currentPos, targetPos); - if ((Vec.abs(distance.x) < accuracy) - && (Vec.abs(distance.y) < accuracy) - && (Vec.abs(distance.z) < accuracy)) { - if (mode == 0) { - mode = 1; - targetPos = uEnd; + Vec.morphToNewVec(mCurrentPos, mTargetPos, timeDelta * mSpeed); + final Vec distance = Vec.sub(mCurrentPos, mTargetPos); + if ((Vec.abs(distance.x) < mAccuracy) + && (Vec.abs(distance.y) < mAccuracy) + && (Vec.abs(distance.z) < mAccuracy)) { + if (mMode == 0) { + mMode = 1; + mTargetPos = mUEnd; } else { - mode = 0; - targetPos = dEnd; + mMode = 0; + mTargetPos = mDEnd; } } return true; @@ -70,15 +70,13 @@ public boolean update(float timeDelta, Updateable parent) { @Override public boolean accept(Visitor visitor) { - // TODO Auto-generated method stub return visitor.default_visit(this); } @Override public void render(GL10 gl, Renderable parent) { - gl.glRotatef(currentPos.z, 0, 0, 1); - gl.glRotatef(currentPos.x, 1, 0, 0); - gl.glRotatef(currentPos.y, 0, 1, 0); + gl.glRotatef(mCurrentPos.z, 0, 0, 1); + gl.glRotatef(mCurrentPos.x, 1, 0, 0); + gl.glRotatef(mCurrentPos.y, 0, 1, 0); } - } diff --git a/droidar/src/gl/animations/GLAnimation.java b/droidar/src/gl/animations/GLAnimation.java index 5ad16f7..9c676e3 100644 --- a/droidar/src/gl/animations/GLAnimation.java +++ b/droidar/src/gl/animations/GLAnimation.java @@ -1,6 +1,6 @@ package gl.animations; -import util.Log; +import logger.ARLogger; import worlddata.RenderableEntity; import worlddata.Updateable; @@ -14,11 +14,11 @@ */ public abstract class GLAnimation implements RenderableEntity { - private static final String LOG_TAG = "GLAnimation"; + private static final String LOG_TAG = GLAnimation.class.getSimpleName(); @Override public Updateable getMyParent() { - Log.e(LOG_TAG, "Get parent called which is not " + ARLogger.error(LOG_TAG, "Get parent called which is not " + "implemented for this component!"); return null; } @@ -26,7 +26,7 @@ public Updateable getMyParent() { @Override public void setMyParent(Updateable parent) { // can't have children so the parent does not have to be stored - Log.e(LOG_TAG, "Set parent called which is not " + ARLogger.error(LOG_TAG, "Set parent called which is not " + "implemented for this component!"); } From e01eeead011e8a3c007ce938d02c254b89df44a8 Mon Sep 17 00:00:00 2001 From: rvieras Date: Fri, 27 Dec 2013 16:18:07 -0500 Subject: [PATCH 11/12] Added new animation to face and object rather then the camera. --- .../src/de/rwth/setups/StaticDemoSetup.java | 11 +- .../src/gl/animations/AnimationFaceToObj.java | 142 ++++++++++++++++++ 2 files changed, 149 insertions(+), 4 deletions(-) create mode 100644 droidar/src/gl/animations/AnimationFaceToObj.java diff --git a/droidar/src/de/rwth/setups/StaticDemoSetup.java b/droidar/src/de/rwth/setups/StaticDemoSetup.java index 9867457..09d70c6 100644 --- a/droidar/src/de/rwth/setups/StaticDemoSetup.java +++ b/droidar/src/de/rwth/setups/StaticDemoSetup.java @@ -1,5 +1,7 @@ package de.rwth.setups; +import de.rwth.R; +import entry.ISetupEntry; import geo.GeoObj; import gl.Color; import gl.CustomGLSurfaceView; @@ -32,10 +34,9 @@ import android.view.View.MeasureSpec; import android.widget.Button; import android.widget.LinearLayout.LayoutParams; + import commands.Command; import commands.ui.CommandShowToast; -import de.rwth.R; -import entry.ISetupEntry; public class StaticDemoSetup extends ArSetup { @@ -104,7 +105,7 @@ private void addTestGeoObj(World w, GLCamera c) { } private void initI9Tests(World w) { - + GeoObj ref = null; { MeshComponent triangleMesh = GLFactory.getInstance() .newTexturedSquare( @@ -115,6 +116,7 @@ private void initI9Tests(World w) { triangleMesh.addChild(new AnimationFaceToCamera(camera, 0.5f)); GeoObj treangleGeo = new GeoObj(GeoObj.newRandomGeoObjAroundCamera( camera, MIN_DIST, MAX_DIST), triangleMesh); + ref = treangleGeo; w.add(treangleGeo); } @@ -126,7 +128,7 @@ private void initI9Tests(World w) { IO.loadBitmapFromId(getActivity(), R.drawable.hippopotamus64)); triangleMesh.addChild(new AnimationFaceToCamera(camera, 0.5f)); - triangleMesh.setScale(new Vec(10, 10, 10)); + // triangleMesh.addChild(new AnimationFaceToObj(ref, 0.5f)); GeoObj treangleGeo = new GeoObj(GeoObj.newRandomGeoObjAroundCamera( camera, MIN_DIST, MAX_DIST), triangleMesh); w.add(treangleGeo); @@ -168,6 +170,7 @@ private void initI9Tests(World w) { "Thanks alot")); button.addChild(new AnimationFaceToCamera(camera, 0.5f)); + // button.addChild(new AnimationFaceToObj(ref, 0.5f)); button.setScale(new Vec(10, 10, 10)); button.setColor(Color.red()); diff --git a/droidar/src/gl/animations/AnimationFaceToObj.java b/droidar/src/gl/animations/AnimationFaceToObj.java new file mode 100644 index 0000000..3946c0f --- /dev/null +++ b/droidar/src/gl/animations/AnimationFaceToObj.java @@ -0,0 +1,142 @@ +package gl.animations; + +import gl.Renderable; +import gl.scenegraph.MeshComponent; + +import javax.microedition.khronos.opengles.GL10; + +import util.Vec; +import worlddata.Obj; +import worlddata.Updateable; +import worlddata.Visitor; + +/** + * Animation to face another object. + */ +public class AnimationFaceToObj extends GLAnimation { + + private static final float DEFAULT_UPDATE_DELAY = 0.5f; + private static final int ADJUST_OBJECT_ROTATION = 90; + private Obj mTargetObject; + private float mLastUpdateAway = 0; + private float mUpdateDelay; + private Vec mRotationVec = new Vec(); + private Vec mNewRotationVec = new Vec(); + + private Vec mAdjustmentVec; + private Vec mTargetObjectPosition; + private boolean mDontChangeXRotation; + + /** + * Constructor. + * + * @param targetCamera + * {@link Obj} + * @param updateDelay + * around 0.5f s + * @param dontChangeXRotation + * if this is false, the mesh will also change the rotation x + * value, otherwise only the z value to face to the camera + */ + public AnimationFaceToObj(Obj targetCamera, float updateDelay, boolean dontChangeXRotation) { + mTargetObject = targetCamera; + + mUpdateDelay = updateDelay; + mTargetObjectPosition = mTargetObject.getPosition(); + mDontChangeXRotation = dontChangeXRotation; + } + + /** + * Constructor. + * + * @param targetObj + * {@link Obj} + * @param updateDelay + * The amount of time to update. Normally should be .5fs + */ + public AnimationFaceToObj(Obj targetObj, float updateDelay) { + this(targetObj, updateDelay, true); + } + + /** + * Constructor. + * + * @param targetObj + * {@link Obj} + */ + public AnimationFaceToObj(Obj targetObj) { + this(targetObj, DEFAULT_UPDATE_DELAY, true); + } + + /** + * @param targetObj + * {@link Obj} + * @param updateDelay + * 0.5f + * @param adjustmentVec + * Adjustment vector + */ + public AnimationFaceToObj(Obj targetObj, float updateDelay, Vec adjustmentVec) { + this(targetObj, updateDelay); + mAdjustmentVec = adjustmentVec; + } + + @Override + public boolean update(float timeDelta, Updateable parent) { + timeDelta = Math.abs(timeDelta); + mLastUpdateAway += timeDelta; + if (mLastUpdateAway > mUpdateDelay) { + updateRotation(parent); + mLastUpdateAway = 0; + } + if (mDontChangeXRotation) { + Vec.morphToNewAngleVec(mRotationVec, 0, 0, mNewRotationVec.z, timeDelta); + } else { + Vec.morphToNewAngleVec(mRotationVec, mNewRotationVec.x, mNewRotationVec.y, mNewRotationVec.z, timeDelta); + } + return true; + } + + private Vec mAbsolutePosition = new Vec(); + + private void updateRotation(Updateable parent) { + if (parent instanceof MeshComponent) { + mAbsolutePosition.setToZero(); + ((MeshComponent) parent).getAbsoluteMeshPosition(mAbsolutePosition); + // Log.d("face camera animation", "mesh position: "+pos); + mNewRotationVec.toAngleVec(mAbsolutePosition, mTargetObjectPosition); + /* + * substract 90 from the x value becaute calcanglevec returns 90 if + * the rotation should be the horizon (which would mean no object + * rotation) + */ + mNewRotationVec.x -= ADJUST_OBJECT_ROTATION; + mNewRotationVec.z *= -1; + } + } + + @Override + public void render(GL10 gl, Renderable parent) { + + gl.glRotatef(mRotationVec.z, 0, 0, 1); + gl.glRotatef(mRotationVec.x, 1, 0, 0); + gl.glRotatef(mRotationVec.y, 0, 1, 0); + + if (mAdjustmentVec != null) { + /* + * if an adjustment vector is set this adjustment has to be done + * AFTER the rotation to be easy to use, see constructor for infos + * about adjustment + */ + gl.glRotatef(mAdjustmentVec.x, 1, 0, 0); + gl.glRotatef(mAdjustmentVec.z, 0, 0, 1); + gl.glRotatef(mAdjustmentVec.y, 0, 1, 0); + } + } + + @Override + public boolean accept(Visitor visitor) { + return visitor.default_visit(this); + } + +} From cb29b9841957acccae2d9cd5ba231ebf51b20437 Mon Sep 17 00:00:00 2001 From: rvieras Date: Thu, 2 Jan 2014 13:30:52 -0500 Subject: [PATCH 12/12] Code clean up. Finishing some partial implmented code that has been hanging around. --- .../commands/ui/CommandShowListActivity.java | 91 ------ .../ExampleSpecialEventManager.java | 25 -- .../rwth/setups/FarAwayPOIScenarioSetup.java | 4 +- droidar/src/geo/GeoObj.java | 35 +- droidar/src/gl/GLCamera.java | 251 +++++++-------- droidar/src/gl/ObjectPicker.java | 17 +- droidar/src/gl/Renderable.java | 12 +- droidar/src/gui/CustomListActivity.java | 299 ------------------ droidar/src/gui/RadarView.java | 53 ++-- droidar/src/setup/ArSetup.java | 21 +- droidar/src/setup/DefaultArSetup.java | 51 ++- droidar/src/system/ActivityConnector.java | 99 ------ 12 files changed, 244 insertions(+), 714 deletions(-) delete mode 100644 droidar/src/commands/ui/CommandShowListActivity.java delete mode 100644 droidar/src/de/rwth/exampleClasses/ExampleSpecialEventManager.java delete mode 100644 droidar/src/gui/CustomListActivity.java delete mode 100644 droidar/src/system/ActivityConnector.java diff --git a/droidar/src/commands/ui/CommandShowListActivity.java b/droidar/src/commands/ui/CommandShowListActivity.java deleted file mode 100644 index 2a72117..0000000 --- a/droidar/src/commands/ui/CommandShowListActivity.java +++ /dev/null @@ -1,91 +0,0 @@ -package commands.ui; - -import gui.CustomBaseAdapter; -import gui.CustomListActivity; -import gui.ListSettings; -import system.ActivityConnector; -import system.Container; -import util.Log; -import util.Wrapper; -import android.app.Activity; -import android.widget.BaseAdapter; - -import commands.Command; -import commands.undoable.UndoableCommand; - -public class CommandShowListActivity extends Command { - - private Wrapper myListItemsWrapper; - private Activity myCurrentActivity; - private boolean closeOnCorrectClick; - private Command myDefaultClickCommand; - private UndoableCommand myDefaultLongClickCommand; - private Command myOnCorrectClickCommand; - private Command myOnCorrectLongClickCommand; - private UndoableCommand myMenuCommands; - private String myActivityName; - - public CommandShowListActivity(Wrapper listItemsWrapper, - Activity currentActivity) { - this(listItemsWrapper, currentActivity, true, null, null, null, null, - null, null); - } - - /** - * @param listItemsWrapper - * @param currentActivity - * @param closeOnCorrectClick - * @param defaultOnClickCommand - * @param defaultOnLongClickCommand - * @param onCorrectClickCommand - * @param onCorrectLongClickCommand - * @param menuCommands - * @param activityName - */ - public CommandShowListActivity(Wrapper listItemsWrapper, - Activity currentActivity, boolean closeOnCorrectClick, - Command defaultOnClickCommand, - UndoableCommand defaultOnLongClickCommand, - Command onCorrectClickCommand, Command onCorrectLongClickCommand, - UndoableCommand menuCommands, String activityName) { - myListItemsWrapper = listItemsWrapper; - this.closeOnCorrectClick = closeOnCorrectClick; - myCurrentActivity = currentActivity; - myDefaultClickCommand = defaultOnClickCommand; - myDefaultLongClickCommand = defaultOnLongClickCommand; - myOnCorrectClickCommand = onCorrectClickCommand; - myOnCorrectLongClickCommand = onCorrectLongClickCommand; - myMenuCommands = menuCommands; - myActivityName = activityName; - } - - @Override - public boolean execute() { - /* - * create an adapter and pass it to the listactivity by using the - * ActivityConnector - */ - - if (myListItemsWrapper.getObject() instanceof Container) { - - BaseAdapter adapter = new CustomBaseAdapter( - (Container) myListItemsWrapper.getObject()); - - ListSettings listSettings = new ListSettings(adapter, - closeOnCorrectClick, myOnCorrectClickCommand, - myOnCorrectLongClickCommand, myDefaultClickCommand, - myDefaultLongClickCommand, myMenuCommands, myActivityName); - - ActivityConnector.getInstance().startActivity(myCurrentActivity, - CustomListActivity.class, listSettings); - - return true; - } else { - Log.d("Commands", - "No activity will be created because you did not pass a CanBeShownInList-Class of ListItems in the Wrapper!"); - } - - return false; - } - -} diff --git a/droidar/src/de/rwth/exampleClasses/ExampleSpecialEventManager.java b/droidar/src/de/rwth/exampleClasses/ExampleSpecialEventManager.java deleted file mode 100644 index 18ee384..0000000 --- a/droidar/src/de/rwth/exampleClasses/ExampleSpecialEventManager.java +++ /dev/null @@ -1,25 +0,0 @@ -package de.rwth.exampleClasses; - -import system.EventManager; -import android.app.Activity; -import android.location.Location; - -public class ExampleSpecialEventManager extends EventManager { - - @Override - protected void registerSensorUpdates(Activity myTargetActivity, - boolean useAccelAndMagnetoSensors) { - // TODO Auto-generated method stub - super.registerSensorUpdates(myTargetActivity, useAccelAndMagnetoSensors); - } - - @Override - public void onLocationChanged(Location location) { - - // do something with the location here (e.g. buffering) - location.setLatitude(location.getLatitude() + 1); - - super.onLocationChanged(location); - } - -} diff --git a/droidar/src/de/rwth/setups/FarAwayPOIScenarioSetup.java b/droidar/src/de/rwth/setups/FarAwayPOIScenarioSetup.java index e0d45b2..31a7377 100644 --- a/droidar/src/de/rwth/setups/FarAwayPOIScenarioSetup.java +++ b/droidar/src/de/rwth/setups/FarAwayPOIScenarioSetup.java @@ -11,10 +11,10 @@ import worlddata.World; import android.app.Activity; import android.util.Log; + import commands.Command; import commands.ui.CommandShowToast; import components.SimpleTooFarAwayComp; -import entry.ISetupEntry; public class FarAwayPOIScenarioSetup extends DefaultArSetup { @@ -25,7 +25,7 @@ public class FarAwayPOIScenarioSetup extends DefaultArSetup { public void initFieldsIfNecessary() { super.initFieldsIfNecessary(); radar = new RadarView(getActivity(), (int) (getScreenWidth() / 3), - getCamera(), getWorld().getAllItems()); + getCamera(), getWorld().getAllItems(), this); } @Override diff --git a/droidar/src/geo/GeoObj.java b/droidar/src/geo/GeoObj.java index 236d138..80c7e65 100644 --- a/droidar/src/geo/GeoObj.java +++ b/droidar/src/geo/GeoObj.java @@ -166,12 +166,13 @@ public GeoObj(boolean autoCalcVirtualPos) { * virtual position of the {@link GeoObj} */ public MeshComponent getMySurroundGroup() { - if (mySurroundGroup == null) + if (mySurroundGroup == null) { if (autoCalcVirtualPos) { mySurroundGroup = new Shape(null, getVirtualPosition()); } else { mySurroundGroup = new Shape(); } + } return mySurroundGroup; } @@ -199,8 +200,9 @@ public void setComp(Entity comp) { if (getMyComponents().contains(g) == -1) { getMyComponents().add(g); } - } else + } else { super.setComp(comp); + } } /* @@ -373,9 +375,10 @@ public double getAltitude() { public void setMyLatitude(double latitude) { this.myLatitude = latitude; - if (myUpdateListener != null) + if (myUpdateListener != null) { myUpdateListener.updateToNewPosition((int) (getLatitude() * 1E6), (int) (getLongitude() * 1E6)); + } } /** @@ -387,9 +390,10 @@ public void setMyLatitude(double latitude) { public void setMyLongitude(double longitude) { this.myLongitude = longitude; - if (myUpdateListener != null) + if (myUpdateListener != null) { myUpdateListener.updateToNewPosition((int) (getLatitude() * 1E6), (int) (getLongitude() * 1E6)); + } } /** @@ -401,9 +405,10 @@ public void setMyLongitude(double longitude) { public void setMyAltitude(double altitude) { this.myAltitude = altitude; - if (myUpdateListener != null) + if (myUpdateListener != null) { myUpdateListener.updateToNewPosition((int) (getLatitude() * 1E6), (int) (getLongitude() * 1E6)); + } } /** @@ -447,7 +452,7 @@ public Vec getVirtualPosition(double zeroLatitude, double zeroLongitude, * default mean the current device altitude is used: */ if (ActionCalcRelativePos.USE_ALTITUDE_VALUES) { - if (myAltitude == 0 + if ((myAltitude == 0) && ActionCalcRelativePos.USE_DEVICE_ALTI_FOR_ZERO) { position.z = 0; } else { @@ -523,9 +528,9 @@ public static Vec calcGPSPosition(Vec virtualPosition, double zeroLatitude, * longitude: */ Vec result = new Vec(); - result.x = (float) (virtualPosition.x - / (111319.889f * Math.cos(zeroLatitude * 0.0174532925f)) + zeroLongitude); - result.y = (float) (virtualPosition.y / 111133.3333f + zeroLatitude); + result.x = (float) ((virtualPosition.x + / (111319.889f * Math.cos(zeroLatitude * 0.0174532925f))) + zeroLongitude); + result.y = (float) ((virtualPosition.y / 111133.3333f) + zeroLatitude); result.z = (float) (virtualPosition.z + zeroAltitude); return result; } @@ -577,10 +582,10 @@ private static double distFrom(double lat1, double lng1, double lat2, double lng2) { final double dLat = Math.toRadians(lat2 - lat1); final double dLng = Math.toRadians(lng2 - lng1); - final double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) - + Math.cos(Math.toRadians(lat1)) + final double a = (Math.sin(dLat / 2) * Math.sin(dLat / 2)) + + (Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) * Math.sin(dLng / 2) - * Math.sin(dLng / 2); + * Math.sin(dLng / 2)); return EARTH_RADIUS * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); } @@ -641,8 +646,7 @@ public Vec getVirtualPosition(GeoObj relativeNullPoint) { * axis)) */ public Vec getVirtualPosition() { - return getVirtualPosition(EventManager.getInstance() - .getZeroPositionLocationObject()); + return getVirtualPosition(EventManager.getInstance().getZeroPositionLocationObject().copy()); } /** @@ -721,8 +725,9 @@ public void showDebugInformation() { public static GeoObj newRandomGeoObjAroundCamera(GLCamera camera, float minDist, float maxDist) { GeoObj o = new GeoObj(); - if (maxDist < minDist) + if (maxDist < minDist) { maxDist = minDist; + } o.setVirtualPosition(Vec.getNewRandomPosInXYPlane(camera.getPosition(), minDist, maxDist)); return o; diff --git a/droidar/src/gl/GLCamera.java b/droidar/src/gl/GLCamera.java index 2a1a205..ebf2602 100644 --- a/droidar/src/gl/GLCamera.java +++ b/droidar/src/gl/GLCamera.java @@ -4,7 +4,6 @@ import javax.microedition.khronos.opengles.GL10; -import logger.ARLogger; import system.EventManager; import util.Calculus; import util.HasDebugInformation; @@ -22,6 +21,14 @@ * offset. Do this via {@link GLCamera#setNewPosition(Vec)}, * {@link GLCamera#setNewRotation(Vec)} and {@link GLCamera#setNewOffset(Vec)} * + * + * Notes: mRotationMatrix y is always the angle from floor to top (rotation + * around green achsis counterclockwise) and x always the clockwise rotation + * (like when you lean to the side on a motorcycle) angle of the camera. + * + * to move from the green to the red axis (clockwise) you would have to add 90 + * degree. + * * @author Spobo * */ @@ -30,48 +37,21 @@ public class GLCamera implements Updateable, HasDebugInformation, Renderable, private static final String LOG_TAG = "GLCamera"; - // private float mybufferValue = 1000; - // private float minimumBufferValue = 20; - // private float bufferCount = 20; - - private Vec myOffset = null; - private Vec myNewOffset = new Vec(0, 0, 0); - private Vec myPosition = new Vec(0, 0, 0); - // TODO would be dangerous to set any of those vecs to null because there - // might be references in commands to those objects so check where those are - // set to null! - // @Deprecated - // private Vec myNewPosition = new Vec(0, 0, 0); + private Vec mOffset = null; + private Vec mNewOffset = new Vec(0, 0, 0); + private Vec mPosition = new Vec(0, 0, 0); + private Vec mRotationVec = new Vec(0, 0, 0); - /** - * y is always the angle from floor to top (rotation around green achsis - * counterclockwise) and x always the clockwise rotation (like when you lean - * to the side on a motorcycle) angle of the camera. - * - * to move from the green to the red axis (clockwise) you would have to add - * 90 degree. - */ - private Vec myRotationVec = new Vec(0, 0, 0); - @Deprecated - public Vec myNewRotationVec; + private boolean mSensorInputEnabled = true; + private float[] mRotationMatrix = Calculus.createIdentityMatrix(); + private final Object mRotMatrLock = new Object(); + private int mMatrixOffset = 0; + private final float[] mInvRotMatrix = Calculus.createIdentityMatrix(); + private float[] mInitDir = new float[4]; + private final float[] mRotDirection = new float[4]; + private final MoveComp mMover = new MoveComp(3); - /** - * set to false if you want the camera not to react on sensor events - */ - private boolean sensorInputEnabled = true; - - /** - * http://www.songho.ca/opengl/gl_transform.html - */ - private float[] rotationMatrix = Calculus.createIdentityMatrix(); - /** - * This lock has to be used to not override the matrix while it is displayed - * by opengl - */ - private final Object rotMatrLock = new Object(); - private int matrixOffset = 0; - private final float[] invRotMatrix = Calculus.createIdentityMatrix(); /** * use a {@link ActionUseCameraAngles2} instead @@ -85,15 +65,22 @@ public class GLCamera implements Updateable, HasDebugInformation, Renderable, */ @Deprecated private final float[] cameraAnglesInDegree = new float[3]; - float[] initDir = new float[4]; - private final float[] rotDirection = new float[4]; - // public boolean forceAngleCalculation = false; + @Deprecated + public Vec myNewRotationVec; - private final MoveComp myMover = new MoveComp(3); + /** + * Default constructor. + */ public GLCamera() { } + /** + * Constructor. + * + * @param initialCameraPosition + * The {@link Vec} stating the starting position of the camera. + */ public GLCamera(Vec initialCameraPosition) { setNewPosition(initialCameraPosition); } @@ -101,42 +88,41 @@ public GLCamera(Vec initialCameraPosition) { @Override public boolean update(float timeDelta, Updateable parent) { - if ((myRotationVec != null) && (myNewRotationVec != null)) { - Vec.morphToNewAngleVec(myRotationVec, myNewRotationVec, timeDelta); + if ((mRotationVec != null) && (myNewRotationVec != null)) { + Vec.morphToNewAngleVec(mRotationVec, myNewRotationVec, timeDelta); } - if ((myOffset != null) && (myNewOffset != null)) { - Vec.morphToNewVec(myOffset, myNewOffset, timeDelta); + if ((mOffset != null) && (mNewOffset != null)) { + Vec.morphToNewVec(mOffset, mNewOffset, timeDelta); } - if (myPosition != null) { - myMover.update(timeDelta, this); + if (mPosition != null) { + mMover.update(timeDelta, this); } return true; - } @Override public Vec getRotation() { - return myRotationVec; + return mRotationVec; } @Override @Deprecated public void setRotation(Vec rotation) { - if (myRotationVec == null) { - myRotationVec = rotation; + if (mRotationVec == null) { + mRotationVec = rotation; } else { - myRotationVec.setToVec(rotation); + mRotationVec.setToVec(rotation); } } public void setNewPosition(Vec cameraPosition) { - if (myPosition == null) { - myPosition = new Vec(); + if (mPosition == null) { + mPosition = new Vec(); } - myMover.mTargetPos = cameraPosition; + mMover.mTargetPos = cameraPosition; } /** @@ -147,18 +133,18 @@ public void setNewPosition(Vec cameraPosition) { * @return the {@link Vec} (x,y,z) */ public Vec getMyNewPosition() { - return myMover.mTargetPos; + return mMover.mTargetPos; } public void setNewCameraOffset(Vec newCameraOffset) { if (newCameraOffset != null) { - if (myNewOffset == null) { - myNewOffset = new Vec(newCameraOffset); - if (myOffset == null) { - myOffset = new Vec(); + if (mNewOffset == null) { + mNewOffset = new Vec(newCameraOffset); + if (mOffset == null) { + mOffset = new Vec(); } } else { - myNewOffset.setToVec(newCameraOffset); + mNewOffset.setToVec(newCameraOffset); } } } @@ -178,7 +164,7 @@ public void setNewRotation(Vec cameraRotation) { * @param rayPosition * the vector where the ray pos will be stored in, so pass a * vector here that can be overwritten. Normally this value will - * be the same as {@link GLCamera#myPosition} but if a marker is + * be the same as {@link GLCamera#mPosition} but if a marker is * used to move the {@link GLCamera} the translation will be * contained in the matrix as well and therefore the rayPosition * will be this translation in relation to the marker @@ -204,23 +190,23 @@ public void getPickingRay(Vec rayPosition, Vec rayDirection, float x, y = (GLRenderer.height - y - GLRenderer.halfHeight) / GLRenderer.halfHeight; - Matrix.invertM(invRotMatrix, 0, rotationMatrix, matrixOffset); + Matrix.invertM(mInvRotMatrix, 0, mRotationMatrix, mMatrixOffset); if (rayPosition != null) { float[] rayPos = new float[4]; float[] initPos = { 0.0f, 0.0f, 0.0f, 1.0f }; - Matrix.multiplyMV(rayPos, 0, invRotMatrix, 0, initPos, 0); + Matrix.multiplyMV(rayPos, 0, mInvRotMatrix, 0, initPos, 0); rayPosition.x = rayPos[0]; rayPosition.y = rayPos[1]; rayPosition.z = rayPos[2]; - if (myPosition != null) { - rayPosition.add(myPosition); + if (mPosition != null) { + rayPosition.add(mPosition); } } float[] rayDir = new float[4]; float[] initDir = { x * GLRenderer.nearHeight * GLRenderer.aspectRatio, y * GLRenderer.nearHeight, -GLRenderer.minViewDistance, 0.0f }; - Matrix.multiplyMV(rayDir, 0, invRotMatrix, 0, initDir, 0); + Matrix.multiplyMV(rayDir, 0, mInvRotMatrix, 0, initDir, 0); rayDirection.x = rayDir[0]; rayDirection.y = rayDir[1]; rayDirection.z = rayDir[2]; @@ -237,13 +223,13 @@ public float[] getScreenCoordinatesFor(Vec virtualWorldPosition) { float[] rayPos = new float[4]; float[] initPos = { virtualWorldPosition.x, virtualWorldPosition.y, virtualWorldPosition.z, 1.0f }; - Matrix.multiplyMV(rayPos, 0, rotationMatrix, matrixOffset, initPos, 0); + Matrix.multiplyMV(rayPos, 0, mRotationMatrix, mMatrixOffset, initPos, 0); // TODO return rayPos; } public int getMatrixOffset() { - return matrixOffset; + return mMatrixOffset; } /** @@ -289,7 +275,7 @@ public Vec getPositionOnGroundWhereTheCameraIsLookingAt() { * then calc intersection with ground */ float f = -rayPos[2] / rayDir[2]; - return new Vec(f * rayDir[0] + rayPos[0], f * rayDir[1] + rayPos[1], 0); + return new Vec((f * rayDir[0]) + rayPos[0], (f * rayDir[1]) + rayPos[1], 0); } /** @@ -298,7 +284,7 @@ public Vec getPositionOnGroundWhereTheCameraIsLookingAt() { * * @param rayPos * here the rayPos will be stored, pass a new float[4]. The - * result will contain {@link GLCamera#myPosition} so you dont + * result will contain {@link GLCamera#mPosition} so you dont * need to add it manually! Can be NULL if you only need the * ray-direction * @param rayDir @@ -306,20 +292,20 @@ public Vec getPositionOnGroundWhereTheCameraIsLookingAt() { * @return */ public void getCameraViewDirectionRay(float[] rayPos, float[] rayDir) { - Matrix.invertM(invRotMatrix, 0, rotationMatrix, matrixOffset); + Matrix.invertM(mInvRotMatrix, 0, mRotationMatrix, mMatrixOffset); if (rayPos != null) { float[] initPos = { 0.0f, 0.0f, 0.0f, 1.0f }; - Matrix.multiplyMV(rayPos, 0, invRotMatrix, 0, initPos, 0); + Matrix.multiplyMV(rayPos, 0, mInvRotMatrix, 0, initPos, 0); /* * TODO is raypos != 0 if initPos ist the 0 vector?? is this calc. * redundant? */ - rayPos[0] += myPosition.x; - rayPos[1] += myPosition.y; - rayPos[2] += myPosition.z; + rayPos[0] += mPosition.x; + rayPos[1] += mPosition.y; + rayPos[2] += mPosition.z; } float[] initDir = { 0, 0, -GLRenderer.minViewDistance, 0.0f }; - Matrix.multiplyMV(rayDir, 0, invRotMatrix, 0, initDir, 0); + Matrix.multiplyMV(rayDir, 0, mInvRotMatrix, 0, initDir, 0); } /** @@ -335,19 +321,19 @@ public synchronized void render(GL10 gl, Renderable parent) { // if the camera sould not be in the center of the rotation it has to be // moved out before rotating: - glLoadPosition(gl, myOffset); + glLoadPosition(gl, mOffset); - synchronized (rotMatrLock) { + synchronized (mRotMatrLock) { // load rotation matrix: - gl.glMultMatrixf(rotationMatrix, matrixOffset); + gl.glMultMatrixf(mRotationMatrix, mMatrixOffset); } // rotate Camera TODO use for manual rotation: - glLoadRotation(gl, myRotationVec); + glLoadRotation(gl, mRotationVec); // set the point where to rotate around - //ARLogger.debug("GLCAMERA","Render Camera Position:\nx:" + myPosition.x+"\ny:"+myPosition.y+"\nz:"+myPosition.z); - glLoadPosition(gl, myPosition); + //ARLogger.debug("GLCAMERA","Render Camera Position:\nx:" + mPosition.x+"\ny:"+mPosition.y+"\nz:"+mPosition.z); + glLoadPosition(gl, mPosition); } /* @@ -357,9 +343,9 @@ public synchronized void render(GL10 gl, Renderable parent) { */ @Override public void setRotationMatrix(float[] rotMatrix, int offset) { - synchronized (rotMatrLock) { - rotationMatrix = rotMatrix; - matrixOffset = offset; + synchronized (mRotMatrLock) { + mRotationMatrix = rotMatrix; + mMatrixOffset = offset; } } @@ -378,16 +364,15 @@ public float[] getCameraAnglesInDegree() { @Deprecated private void updateCameraAngles() { - Calculus.invertM(invRotMatrix, 0, rotationMatrix, matrixOffset); - initDir[0] = 0; - initDir[1] = 0; - initDir[2] = -GLRenderer.minViewDistance; - initDir[3] = 0; + Calculus.invertM(mInvRotMatrix, 0, mRotationMatrix, mMatrixOffset); + mInitDir[0] = 0; + mInitDir[1] = 0; + mInitDir[2] = -GLRenderer.minViewDistance; + mInitDir[3] = 0; // TODO not a good idea to use myAnglesInRadians2 here, maybe additional // helper var?: - Matrix.multiplyMV(rotDirection, 0, invRotMatrix, 0, initDir, 0); - cameraAnglesInDegree[0] = Vec.getRotationAroundZAxis(rotDirection[1], - rotDirection[0]); + Matrix.multiplyMV(mRotDirection, 0, mInvRotMatrix, 0, mInitDir, 0); + cameraAnglesInDegree[0] = Vec.getRotationAroundZAxis(mRotDirection[1], mRotDirection[0]); } private void glLoadPosition(GL10 gl, Vec vec) { @@ -404,7 +389,7 @@ private void glLoadRotation(GL10 gl, Vec vec) { * when you change the rotation order to x y z ! the order y x z is * needed to use extract the angles from the rotation matrix with: * - * SensorManager.getOrientation(rotationMatrix, anglesInRadians); + * SensorManager.getOrientation(mRotationMatrix, anglesInRadians); * * so remember this oder when doing own rotations. * @@ -438,9 +423,9 @@ private void glLoadRotation(GL10 gl, Vec vec) { * like a compass (0=north, 90 east and so on */ public void setRotation(float xAngle, float yAngle, float zAngle) { - myRotationVec.x = xAngle; - myRotationVec.y = yAngle; - myRotationVec.z = zAngle; + mRotationVec.x = xAngle; + mRotationVec.y = yAngle; + mRotationVec.z = zAngle; } @Deprecated @@ -463,7 +448,7 @@ public void setNewRotation(float xAngle, float yAngle, float zAngle) { * @param deltaY */ public synchronized void changeXYPositionBuffered(float deltaX, float deltaY) { - myMover.mTargetPos.add(deltaX, deltaY, 0); + mMover.mTargetPos.add(deltaX, deltaY, 0); } /** @@ -480,8 +465,8 @@ public synchronized void changeXYPositionBuffered(float deltaX, float deltaY) { * see deltaX description */ public synchronized void changePositionUnbuffered(float deltaX, float deltaY) { - myPosition.x += deltaX; - myPosition.y += deltaY; + mPosition.x += deltaX; + mPosition.y += deltaY; } /* @@ -493,7 +478,7 @@ public synchronized void changePositionUnbuffered(float deltaX, float deltaY) { @Deprecated public void resetBufferedAngle() { Log.d(LOG_TAG, "Reseting camera rotation in resetBufferedAngle()!"); - if ((myNewRotationVec != null) && (sensorInputEnabled)) { + if ((myNewRotationVec != null) && (mSensorInputEnabled)) { myNewRotationVec.setToZero(); } } @@ -507,7 +492,7 @@ public void resetBufferedAngle() { * @param deltaZ */ public void changeZAngleUnbuffered(float deltaZ) { - myRotationVec.z += deltaZ; + mRotationVec.z += deltaZ; } /* @@ -533,7 +518,7 @@ public void changeZAngleBuffered(float deltaZ) { * eg. -10 to move the camera 10 meters down */ public void changeZPositionBuffered(float deltaZ) { - myMover.mTargetPos.add(0, 0, deltaZ); + mMover.mTargetPos.add(0, 0, deltaZ); } /** @@ -541,13 +526,13 @@ public void changeZPositionBuffered(float deltaZ) { * if you just want to reset x and y set this to false */ public void resetPosition(boolean resetZValueToo) { - float pz = myPosition.z; - float npz = myMover.mTargetPos.z; - myPosition.setToZero(); - myMover.mTargetPos.setToZero(); + float pz = mPosition.z; + float npz = mMover.mTargetPos.z; + mPosition.setToZero(); + mMover.mTargetPos.setToZero(); if (!resetZValueToo) { - myPosition.z = pz; - myMover.mTargetPos.z = npz; + mPosition.z = pz; + mMover.mTargetPos.z = npz; } } @@ -559,7 +544,7 @@ public void resetPosition() { } public void changeNewPosition(float deltaX, float deltaY, float deltaZ) { - myMover.mTargetPos.add(deltaX, deltaY, deltaZ); + mMover.mTargetPos.add(deltaX, deltaY, deltaZ); } /** @@ -571,7 +556,7 @@ public void changeNewPosition(float deltaX, float deltaY, float deltaZ) { * the height of the camera */ public void setNewPosition(float x, float y, float z) { - myMover.mTargetPos.setTo(x, y, z); + mMover.mTargetPos.setTo(x, y, z); } @@ -582,15 +567,15 @@ public void setNewPosition(float x, float y, float z) { * positive means north of zero pos (latitude direction) */ public void setNewPosition(float x, float y) { - myMover.mTargetPos.setTo(x, y); + mMover.mTargetPos.setTo(x, y); } public Vec getNewCameraOffset() { - return myNewOffset; + return mNewOffset; } public void setNewOffset(Vec myNewOffset) { - this.myNewOffset = myNewOffset; + this.mNewOffset = myNewOffset; } /** @@ -603,15 +588,15 @@ public void setNewOffset(Vec myNewOffset) { */ @Override public Vec getPosition() { - return myPosition; + return mPosition; } @Override public void setPosition(Vec position) { - if (myPosition == null) { - myPosition = position; + if (mPosition == null) { + mPosition = position; } else { - myPosition.setToVec(position); + mPosition.setToVec(position); } } @@ -674,27 +659,27 @@ public GeoObj getGPSPositionAsGeoObj() { } public float[] getRotationMatrix() { - return rotationMatrix; + return mRotationMatrix; } @Override public void showDebugInformation() { Log.w(LOG_TAG, "Infos about GLCamera:"); - Log.w(LOG_TAG, " > myPosition=" + myPosition); - Log.w(LOG_TAG, " > myMover.myTargetPos=" + myMover.mTargetPos); - Log.w(LOG_TAG, " > myOffset=" + myOffset); - Log.w(LOG_TAG, " > myNewOffset=" + myNewOffset); - Log.w(LOG_TAG, " > myRotationVec=" + myRotationVec); + Log.w(LOG_TAG, " > mPosition=" + mPosition); + Log.w(LOG_TAG, " > myMover.myTargetPos=" + mMover.mTargetPos); + Log.w(LOG_TAG, " > mOffset=" + mOffset); + Log.w(LOG_TAG, " > mNewOffset=" + mNewOffset); + Log.w(LOG_TAG, " > mRotationVec=" + mRotationVec); Log.w(LOG_TAG, " > myNewRotationVec=" + myNewRotationVec); - Log.w(LOG_TAG, " > rotationMatrix=" + rotationMatrix); + Log.w(LOG_TAG, " > mRotationMatrix=" + mRotationMatrix); } public boolean isSensorInputEnabled() { - return sensorInputEnabled; + return mSensorInputEnabled; } /** - * @param sensorInputEnabled + * @param mSensorInputEnabled * set false tell the camera to ignore sensor input. You can * still use the methods like * {@link GLCamera#setNewPosition(Vec)} @@ -703,10 +688,10 @@ public boolean isSensorInputEnabled() { * movement through a virtual world. */ public void setSensorInputEnabled(boolean sensorInputEnabled) { - this.sensorInputEnabled = sensorInputEnabled; + this.mSensorInputEnabled = sensorInputEnabled; if (!sensorInputEnabled) { // reset rotation matrix - rotationMatrix = Calculus.createIdentityMatrix(); + mRotationMatrix = Calculus.createIdentityMatrix(); } } diff --git a/droidar/src/gl/ObjectPicker.java b/droidar/src/gl/ObjectPicker.java index da893a3..7e9cbf2 100644 --- a/droidar/src/gl/ObjectPicker.java +++ b/droidar/src/gl/ObjectPicker.java @@ -64,13 +64,13 @@ private void findObjectForValue(byte[] b) { Log.v(LOG_TAG, " > Pixelvalues: " + key); Log.v(LOG_TAG, " > Picked object: " + wrapper); - if (wrapper == null && !key.equals("000")) { + if ((wrapper == null) && !key.equals("000")) { Log.d(LOG_TAG, " > Possible picking problem found! Trying to fix it"); wrapper = tryToFindCorrectObjectFor(b); } - if (wrapper != null && wrapper.getObject() instanceof SelectionListener) { + if ((wrapper != null) && (wrapper.getObject() instanceof SelectionListener)) { SelectionListener s = (SelectionListener) wrapper.getObject(); @@ -114,8 +114,9 @@ private void findObjectForValue(byte[] b) { } private void giveSelectFeedbackIfEnabled() { - if (myFeedbackCommand != null) + if (myFeedbackCommand != null) { myFeedbackCommand.execute(); + } } private Wrapper tryToFindCorrectObjectFor(byte[] b) { @@ -238,9 +239,9 @@ private Color getBestColor(Color x) { c = new Color(0, 0, 0.01f, 1); } while (isAlreadyTaken(c)) { - if (c.red < 1) + if (c.red < 1) { c.red += 0.01f; - else if (c.green < 1) { + } else if (c.green < 1) { c.green += 0.01f; c.red = 0; } else if (c.blue < 1) { @@ -264,8 +265,9 @@ else if (c.green < 1) { private boolean isAlreadyTaken(Color c) { byte[] b = getByteArrayFromColor(c); String key = "" + b[0] + b[1] + b[2]; - if (myObjectLookUpTable.get(key) != null) + if (myObjectLookUpTable.get(key) != null) { return true; + } return false; } @@ -305,8 +307,9 @@ public static byte floatToByteColorValue(float f, boolean oldDevice) { * older devices another part of this bugfix is the * tryToFindCorrectObjectFor method */ - if (f == 1) + if (f == 1) { return -1; + } return (byte) (f * 256f); } return (byte) (f * 255f); diff --git a/droidar/src/gl/Renderable.java b/droidar/src/gl/Renderable.java index d71f424..a9c45c8 100644 --- a/droidar/src/gl/Renderable.java +++ b/droidar/src/gl/Renderable.java @@ -3,11 +3,19 @@ import javax.microedition.khronos.opengles.GL10; /** - * Use this interface for custom rendering + * Use this interface for custom rendering. * * @author Spobo * */ public interface Renderable { - public void render(GL10 gl, Renderable parent); + /** + * Implement this method to render an GL object. + * + * @param gl + * {@link GL10} + * @param parent + * {@link Renderable}'s parent + */ + void render(GL10 gl, Renderable parent); } diff --git a/droidar/src/gui/CustomListActivity.java b/droidar/src/gui/CustomListActivity.java deleted file mode 100644 index 2cfe306..0000000 --- a/droidar/src/gui/CustomListActivity.java +++ /dev/null @@ -1,299 +0,0 @@ -package gui; - -import system.ActivityConnector; -import util.EfficientList; -import util.Log; -import android.app.ListActivity; -import android.os.Bundle; -import android.view.ContextMenu; -import android.view.ContextMenu.ContextMenuInfo; -import android.view.Menu; -import android.view.MenuItem; -import android.view.View; -import android.view.Window; -import android.widget.AdapterView.AdapterContextMenuInfo; -import android.widget.BaseAdapter; -import android.widget.ListView; - -import commands.Command; -import commands.CommandGroup; - -/** - * will probably be replaced by a smartui class - * - * @author Spobo - * - */ -@Deprecated -public class CustomListActivity extends ListActivity { - - ListSettings mySettings; - // TODO why is this id static??: - private String activityId = ""; - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - // TODO write this in onresume?? - activityId = getIntent().getExtras().getString( - ActivityConnector.KEY_IDENTIFIER); - Object x = ActivityConnector.getInstance() - .loadObjFromNewlyCreatedActivity(this); - if (x instanceof ListSettings) { - mySettings = (ListSettings) x; - Log.d("ListActivity", "Setting adapter=" + mySettings.adapter - + " to CommandListActivity"); - setListAdapter(mySettings.adapter); - this.setTitle(mySettings.getActivityTitle()); - } else { - Log.e("ListActivity", - "Passing CustomBasAdapter from Activity A to B failed!"); - } - - registerForContextMenu(getListView()); - - } - - @Override - public boolean onCreateOptionsMenu(Menu menu) { - Log.d("ListActivity", "Creating optionsmenu"); - if (createOptionsMenu(menu)) { - return true; - } - Log.d("ListActivity", "No Optionsmenu defined"); - return super.onCreateOptionsMenu(menu); - } - - /* - * every time you longpress an item in the list is done. so get the - * commandgroup or command of the item and show all possibilities - */ - @Override - public void onCreateContextMenu(ContextMenu menu, View v, - ContextMenuInfo menuInfo) { - AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo; - int position = info.position; - if (mySettings.adapter.getItem(position) instanceof ListItem) { - ListItem item = (ListItem) mySettings.adapter.getItem(position); - if (!createLongClickMenu(menu, item)) { - Log.e("ListActivity", - "Long click menu wasn't created correctly! :("); - menu.close(); - } - Log.e("ListActivity", "Long click menu created correctly! :)"); - } else { - Log.e("ListActivity", - "Long click menu wasn't created correctly! :("); - menu.close(); - } - } - - @Override - public boolean onContextItemSelected(MenuItem item) { - AdapterContextMenuInfo info = (AdapterContextMenuInfo) item - .getMenuInfo(); - Log.d("ListActivity", "info.position=" + info.position); - if (mySettings.adapter.getItem(info.position) instanceof ListItem) { - ListItem listitem = (ListItem) mySettings.adapter - .getItem(info.position); - if (clickLongOnListItem(listitem, item.getItemId())) { - executeCorrectLongClickCommand(listitem); - refreshList(); - return true; - } else { - Log.w("ListActivity", - "long click on item in menu wasn't executed correctly"); - } - } - Log.w("ListActivity", "LongCLick action wasn't executed correctly!"); - return false; - } - - @Override - protected void onListItemClick(ListView l, View v, int position, long id) { - Log.d("ListActivity", "Item in list was clicked: pos=" + position - + " id=" + id); - Log.d("ListActivity", - " -> Informing " + mySettings.adapter.getItem(position)); - if (mySettings.adapter.getItem(position) instanceof ListItem) { - ListItem item = (ListItem) mySettings.adapter.getItem(position); - if (clickOnListItem(item)) { - executeCorrectClickCommand(item); - refreshList(); - if (mySettings.closeOnCorrectClick) { - this.finish(); - } - } else { - Log.w("ListActivity", - "on click command wasnt executed correctly!"); - } - } else { - Log.w("ListActivity", - "Item " + mySettings.adapter.getItem(position) - + " was clicked in list, but wasn't ListItem " - + "so nothing is done!"); - } - } - - @Override - public boolean onMenuItemSelected(int featureId, MenuItem item) { - - Log.d("ListActivity", "Item in options menu clicked(featureId=" - + featureId + ", item=" + item + ")"); - - if (featureId == Window.FEATURE_CONTEXT_MENU) { - return onContextItemSelected(item); - } - if (featureId == Window.FEATURE_OPTIONS_PANEL) { - if (mySettings.myMenuCommands != null) { - if (mySettings.myMenuCommands instanceof CommandGroup) { - boolean b = ((CommandGroup) mySettings.myMenuCommands).myList - .get(item.getItemId()).execute(); - refreshList(); - return b; - } - boolean b = mySettings.myMenuCommands.execute(); - refreshList(); - return b; - } - } - return super.onMenuItemSelected(featureId, item); - } - - private void executeCorrectClickCommand(ListItem item) { - if (mySettings.myCommandOnCorrectClick != null) { - mySettings.myCommandOnCorrectClick.execute(item); - } - } - - private void executeCorrectLongClickCommand(ListItem item) { - if (mySettings.myCommandOnCorrectLongClick != null) { - mySettings.myCommandOnCorrectLongClick.execute(item); - } - } - - private void refreshList() { - Log.d("ListActivity", "Trying to refresh list"); - if (mySettings.adapter instanceof BaseAdapter) { - ((BaseAdapter) mySettings.adapter).notifyDataSetChanged(); - // ((BaseAdapter) mySettings.adapter).notifyDataSetInvalidated(); - Log.d("ListActivity", " -> List refreshed :)"); - } - } - - public boolean clickOnListItem(ListItem i) { - - if (mySettings.myDefaultClickCommand != null) { - return mySettings.myDefaultClickCommand.execute(i); - } - Command c = i.getListClickCommand(); - if (c != null) { - return c.execute(i); - } - Log.w("ListActivity", - "Item has no click command and defaultClickCommand was null too!"); - return false; - } - - public boolean createOptionsMenu(Menu menu) { - // check settings and load if necessary: - if (mySettings == null) { - Log.w("ListActivity", "mySetup was null, trying to reload it.."); - if (activityId != "") { - Object x = ActivityConnector.getInstance().getObj(activityId); - if (x instanceof ListSettings) { - mySettings = (ListSettings) x; - Log.d("ListActivity", "Setting adapter=" - + mySettings.adapter + " to CommandListActivity"); - setListAdapter(mySettings.adapter); - } - } - } - // recheck mySettings - if (mySettings == null) { - Log.e("ListActivity", "mySetup could not be loaded"); - // TODO exit app? - return false; - } - if (mySettings.myMenuCommands instanceof CommandGroup) { - Log.d("ListActivity", "Menu commands loaded"); - return fillMenuWithCommandsFromCommandgroup(menu, - (CommandGroup) mySettings.myMenuCommands); - } - if (mySettings.myMenuCommands != null) { - Log.d("ListActivity", "Menu command was loaded"); - menu.add(mySettings.myMenuCommands.getInfoObject().getShortDescr()); - return true; - } - Log.w("ListActivity", "No menu commands were set"); - return false; - - } - - public boolean createLongClickMenu(ContextMenu menu, ListItem item) { - - if (mySettings.myDefaultLongClickCommand instanceof CommandGroup) { - return fillMenuWithCommandsFromCommandgroup(menu, - (CommandGroup) mySettings.myDefaultLongClickCommand); - } - if (mySettings.myDefaultLongClickCommand != null) { - menu.add(mySettings.myDefaultLongClickCommand.getInfoObject() - .getShortDescr()); - return true; - } - if (item.getListLongClickCommand() instanceof CommandGroup) { - return fillMenuWithCommandsFromCommandgroup(menu, - (CommandGroup) item.getListLongClickCommand()); - } - if (item.getListLongClickCommand() instanceof Command) { - // TODO maybe let ListItem implement MetaInfoInterface ?? - menu.add((item.getListLongClickCommand()).getInfoObject() - .getShortDescr()); - return true; - } - return false; - - } - - private boolean fillMenuWithCommandsFromCommandgroup(Menu menu, - CommandGroup g) { - EfficientList a = g.myList; - final int l = g.myList.myLength; - for (int i = 0; i < l; i++) { - menu.add(Menu.NONE, i, Menu.NONE, a.get(i).getInfoObject() - .getShortDescr()); - } - return true; - } - - public boolean clickLongOnListItem(ListItem item, int menuId) { - final Command defaultC = mySettings.myDefaultLongClickCommand; - if (defaultC != null) { - Log.d("ListActivity", "Executing default long press command: " - + defaultC); - if (defaultC instanceof CommandGroup) { - return ((CommandGroup) defaultC).myList.get(menuId).execute( - item); - } - return defaultC.execute(item); - } - - Command c = item.getListLongClickCommand(); - Log.d("ListActivity", "Executing long press command: " + c); - if (c instanceof CommandGroup) { - return ((CommandGroup) c).myList.get(menuId).execute(item); - } - if (c instanceof Command) { - - return c.execute(item); - } - Log.d("ListActivity", - "Item has no long click command and defaultLongClickCommand was null too!"); - return false; - } - - public void setCloseOnCorrectClick(boolean closeOnCorrectClick) { - mySettings.closeOnCorrectClick = closeOnCorrectClick; - } - -} diff --git a/droidar/src/gui/RadarView.java b/droidar/src/gui/RadarView.java index 5e755ff..a19c46b 100644 --- a/droidar/src/gui/RadarView.java +++ b/droidar/src/gui/RadarView.java @@ -4,6 +4,8 @@ import gl.HasColor; import gl.HasPosition; import gl.scenegraph.Shape; +import logger.ARLogger; +import setup.DefaultArSetup; import util.EfficientList; import util.Vec; import worlddata.Obj; @@ -46,13 +48,14 @@ public class RadarView extends SimpleCustomView implements Updateable { private float myUpdateSpeed = DEFAULT_UPDATE_SPEED; private double myTouchScaleFactor = 5; private volatile float mCameraAngleInDeg = -1; + private DefaultArSetup mSetup; private String debug; public RadarView(Context context, GLCamera camera, int minimumRadarViewSize, int displRadiusInMeters, float updateSpeed, boolean rotateNeedle, - boolean displayOutOfRadarArea, EfficientList items) { + boolean displayOutOfRadarArea, EfficientList items, DefaultArSetup setup) { super(context); init(minimumRadarViewSize); myCamera = camera; @@ -61,6 +64,7 @@ public RadarView(Context context, GLCamera camera, setDisplayOutOfRadarArea(displayOutOfRadarArea); setItems(items); setUpdateSpeed(updateSpeed); + mSetup = setup; } public void setUpdateSpeed(float myUpdateSpeed) { @@ -101,10 +105,11 @@ public RadarView(Context context, AttributeSet attrs) { * {@link World#getAllItems()}) */ public RadarView(Activity myTargetActivity, int radarViewSize, - GLCamera camera, EfficientList items) { + GLCamera camera, EfficientList items, + DefaultArSetup setup) { this(myTargetActivity, camera, radarViewSize, DEFAULT_RADAR_MAX_DISTANCE, DEFAULT_UPDATE_SPEED, false, true, - items); + items, setup); } private void init(int minimumViewSize) { @@ -121,14 +126,16 @@ private void init(int minimumViewSize) { this.minimumSize = minimumViewSize; setSize(minimumViewSize); - if (isInEditMode()) + if (isInEditMode()) { loadDemoValues(); + } } public void setSize(int viewSize) { - if (viewSize < minimumSize) + if (viewSize < minimumSize) { viewSize = minimumSize; + } mySize = viewSize; myHalfSize = viewSize / 2; @@ -185,8 +192,13 @@ protected void onDraw(Canvas canvas) { * TODO store in bitmap object and only redraw if something changes to * increase performance! */ + drawBackGround(canvas); + if (mCameraAngleInDeg > 0) { + setRotation(mCameraAngleInDeg); + } + if (items != null) { drawItems(canvas); } @@ -216,13 +228,14 @@ public boolean onTouchEvent(MotionEvent event) { } private boolean onTouch(float x, float y) { - double distFromCenter = Math.sqrt(x * x + y * y); + double distFromCenter = Math.sqrt((x * x) + (y * y)); // TODO use the myHalfSize to calculate percent value. important to stay // size independent! distFromCenter *= myTouchScaleFactor; myDisplRadius = (int) distFromCenter; - if (myDisplRadius < MIN_DISP_RADIUS) + if (myDisplRadius < MIN_DISP_RADIUS) { myDisplRadius = MIN_DISP_RADIUS; + } return true; } @@ -233,7 +246,7 @@ private void drawCompassNeedle(Canvas canvas) { myHalfSize + myRotVec.y, linePaint); } else { canvas.drawLine(myHalfSize, myHalfSize, myHalfSize, myHalfSize - - myHalfSize / 2.5f, linePaint); + - (myHalfSize / 2.5f), linePaint); } } @@ -241,16 +254,17 @@ private void drawItems(Canvas canvas) { for (int i = 0; i < items.myLength; i++) { if (items.get(i) instanceof HasPosition) { RenderableEntity element = items.get(i); - Vec pos = ((HasPosition) element).getPosition().copy() - .sub(myCamera.getPosition()); - + // Vec pos = ((HasPosition) + // element).getPosition().copy().sub(myCamera.getPosition()); + Vec pos = ((HasPosition) element).getPosition().copy(); float length = pos.getLength(); if (length > myDisplRadius) { if (displayOutOfRadarArea) { pos.setLength(myDisplRadius); length = myDisplRadius; - } else + } else { continue; + } } if (!rotateNeedle) { @@ -260,17 +274,17 @@ private void drawItems(Canvas canvas) { /* * now convert the distance in meters into a distance in pixels: */ - pos.setLength(length / myDisplRadius * (myHalfSize - MARGIN)); + pos.setLength((length / myDisplRadius) * (myHalfSize - MARGIN)); /* * the canvas coords are not like the opengl coords! 10,10 means * down on the screen */ - // debug = "" + pos; + ARLogger.debug("debug = " + pos); float northPos = myHalfSize - pos.y; float eastPos = myHalfSize + pos.x; - // debug="n="+northPos+", e="+eastPos; + ARLogger.debug("debug= n=" + northPos + ", e=" + eastPos); drawElement(element, canvas, northPos, eastPos); } @@ -282,8 +296,9 @@ private void drawElement(RenderableEntity element, Canvas canvas, paint.setColor(Color.WHITE); if (element instanceof HasColor) { gl.Color c = ((HasColor) element).getColor(); - if (c != null) + if (c != null) { paint.setColor(c.toIntARGB()); + } } drawCircle(canvas, eastPos, northPos, 6, paint); } @@ -293,8 +308,9 @@ private void drawBackGround(Canvas canvas) { } private Bitmap getBackGround() { - if (background == null) + if (background == null) { background = createBackground(mySize, myHalfSize); + } return background; } @@ -338,7 +354,8 @@ private Bitmap createBackground(int size, int halfSize) { public boolean update(float timeDelta, Updateable parent) { if (myTimer.update(timeDelta, parent)) { //setRotation(myCamera.getCameraAnglesInDegree()[0]); - mCameraAngleInDeg = myCamera.getCameraAnglesInDegree()[0]; + // mCameraAngleInDeg = myCamera.getCameraAnglesInDegree()[0]; + mCameraAngleInDeg = mSetup.getCameraAngle().z; postInvalidate(); } /* diff --git a/droidar/src/setup/ArSetup.java b/droidar/src/setup/ArSetup.java index 5ffe4f1..89bc1b5 100644 --- a/droidar/src/setup/ArSetup.java +++ b/droidar/src/setup/ArSetup.java @@ -20,10 +20,12 @@ import android.view.Window; import android.view.WindowManager; import android.widget.FrameLayout; + import commands.Command; import commands.CommandGroup; import commands.system.CommandDeviceVibrate; import commands.undoable.CommandProcessor; + import entry.ArType; import entry.ISetupEntry; import gl.GLFactory; @@ -70,7 +72,7 @@ public ArSetup() { } /** - * Set the entry for this setup. + * Set the entry for this setup. * @param pEntry - {@link entry.ISetupEntry} */ public void setEntry(ISetupEntry pEntry) { @@ -275,7 +277,7 @@ public boolean onCreateOptionsMenu(Menu menu) { } /** - * Add items to the options menu. + * Add items to the options menu. * @param menuItem - {@link Command} * @param menuItemText - {@link String} text displayed */ @@ -308,21 +310,21 @@ private void reloadTextures() { } /** - * Pause the event manager thread. + * Pause the event manager thread. */ public void pauseEventManager() { EventManager.getInstance().pauseEventListeners(); } /** - * Resume the event manager thread. + * Resume the event manager thread. */ public void resumeEventManager() { EventManager.getInstance().resumeEventListeners(getActivity(), true); } /** - * Pause the updater thread. + * Pause the updater thread. */ public void pauseUpdater() { if (mWorldUpdater != null) { @@ -356,8 +358,8 @@ public boolean onKeyDown(Activity activity, int keyCode, KeyEvent event) { */ @SuppressWarnings("deprecation") public float getScreenWidth() { - if (getScreenOrientation() == Surface.ROTATION_90 - || getScreenOrientation() == Surface.ROTATION_270) { + if ((getScreenOrientation() == Surface.ROTATION_90) + || (getScreenOrientation() == Surface.ROTATION_270)) { return getActivity().getWindowManager().getDefaultDisplay() .getHeight(); } else { @@ -372,8 +374,8 @@ public float getScreenWidth() { */ @SuppressWarnings("deprecation") public float getScreenHeigth() { - if (getScreenOrientation() == Surface.ROTATION_90 - || getScreenOrientation() == Surface.ROTATION_270) { + if ((getScreenOrientation() == Surface.ROTATION_90) + || (getScreenOrientation() == Surface.ROTATION_270)) { return getActivity().getWindowManager().getDefaultDisplay() .getWidth(); } else { @@ -391,6 +393,7 @@ public void onCreate() { @Override public void onStart() { + ARLogger.debug(LOG_TAG, "onStart"); } @Override diff --git a/droidar/src/setup/DefaultArSetup.java b/droidar/src/setup/DefaultArSetup.java index f1e022b..854c5a0 100644 --- a/droidar/src/setup/DefaultArSetup.java +++ b/droidar/src/setup/DefaultArSetup.java @@ -15,14 +15,15 @@ import actions.ActionCalcRelativePos; import actions.ActionMoveCameraBuffered; import actions.ActionRotateCameraBuffered; +import actions.ActionUseCameraAngles2; import actions.ActionWASDMovement; import actions.ActionWaitForAccuracy; import android.app.Activity; import android.location.Location; /** - * Default AR setup that initializes all of the lighting and - * event management so that concrete classes only need to add the objects to the world. + * Default AR setup that initializes all of the lighting and + * event management so that concrete classes only need to add the objects to the world. * */ public abstract class DefaultArSetup extends ArSetup { @@ -33,6 +34,8 @@ public abstract class DefaultArSetup extends ArSetup { private World mWorld; private GL1Renderer mRenderer; + private Vec mCameraAngleData = new Vec(0, 0, 0); + private boolean mWaitForValidGps = false; private boolean mAddObjectsCalled = false; @@ -43,7 +46,7 @@ public abstract class DefaultArSetup extends ArSetup { //magic numbers private static final int XREDUCTION = 25; private static final int YREDUCTION = 50; - private static final int MAXWASDSPEED = 20; + private static final int MAXWASDSPEED = 20; private static final int TRACKBALLFACTOR = 5; private static final int TOUCHSCREENFACTOR = 25; private static final float MINGPSACCURACY = 24.0f; @@ -69,7 +72,7 @@ public DefaultArSetup() { } /** - * Constructor. + * Constructor. * @param pWaitForValidGps - {@link boolean} true if you want to wait for gps before drawing */ public DefaultArSetup(boolean pWaitForValidGps) { @@ -113,29 +116,38 @@ public void addWorldsToRenderer(GL1Renderer glRenderer, @Override public void addActionsToEvents(final EventManager eventManager, CustomGLSurfaceView arView, SystemUpdater updater) { - mWasdAction = new ActionWASDMovement(mCamera, - XREDUCTION, - YREDUCTION, + mWasdAction = new ActionWASDMovement(mCamera, + XREDUCTION, + YREDUCTION, MAXWASDSPEED); mRotateGLCameraAction = new ActionRotateCameraBuffered(mCamera); eventManager.addOnOrientationChangedAction(mRotateGLCameraAction); arView.addOnTouchMoveListener(mWasdAction); eventManager.addOnTrackballAction(new ActionMoveCameraBuffered(mCamera, - TRACKBALLFACTOR, + TRACKBALLFACTOR, TOUCHSCREENFACTOR)); eventManager.addOnLocationChangedAction(new ActionCalcRelativePos(mWorld, mCamera)); + eventManager.addOnOrientationChangedAction(new ActionUseCameraAngles2() { + @Override + public void onAnglesUpdated(float pitch, float roll, float compassAzimuth) { + mCameraAngleData.x = pitch; + mCameraAngleData.y = roll; + mCameraAngleData.z = compassAzimuth; + } + }); + if (mWaitForValidGps) { - mMinAccuracyAction = new ActionWaitForAccuracy(getActivity(), - MINGPSACCURACY, + mMinAccuracyAction = new ActionWaitForAccuracy(getActivity(), + MINGPSACCURACY, MAXGPSPOSUPDATECOUNT) { @Override public void minAccuracyReachedFirstTime(Location l, ActionWaitForAccuracy a) { callAddObjectsToWorldIfNotCalledAlready(); if (!eventManager.getOnLocationChangedAction().remove(a)) { - ARLogger.debug(LOG_TAG, + ARLogger.debug(LOG_TAG, "Could not remove minAccuracyAction from the onLocationChangedAction list"); } } @@ -163,12 +175,23 @@ public void addElementsToGuiSetup(GuiSetup guiSetup, Activity activity) { } + /** + * @return {@link Vec} containing the camera angle data. compassAngle=z, + * pitch=x, roll=y + */ + public Vec getCameraAngle() { + return mCameraAngleData; + } + /** * This will be called when the GPS accuracy is high enough. * - * @param renderer - {@link GL1Renderer} - * @param world - {@link World} - * @param objectFactory - {@link GLFactory} + * @param renderer + * - {@link GL1Renderer} + * @param world + * - {@link World} + * @param objectFactory + * - {@link GLFactory} */ public abstract void addObjectsTo(GL1Renderer renderer, World world, GLFactory objectFactory); diff --git a/droidar/src/system/ActivityConnector.java b/droidar/src/system/ActivityConnector.java deleted file mode 100644 index a6d4602..0000000 --- a/droidar/src/system/ActivityConnector.java +++ /dev/null @@ -1,99 +0,0 @@ -package system; - -import java.util.HashMap; - -import android.app.Activity; -import android.content.Intent; - -/** - * This is a Singleton to pass objects between activities. The two essential - * methods are: - * - * startActivity(Activity currentActivity, Class ActivityClassToShow, Object - * objectToPass): to start a new activity and pass an object to it. - * - * loadObjFromNewlyCreatedActivity(Activity theNewActivity): to load the passed - * object in the new Activity. - * - * @author Spobo - * - */ -public class ActivityConnector { - - private static ActivityConnector myInstance = new ActivityConnector(); - public static final String KEY_IDENTIFIER = "key"; - - private HashMap myHashMap = new HashMap(); - private int id; - - private ActivityConnector() { - } - - public Object getObj(String id) { - return myHashMap.get(id); - } - - public String getNextKey(Object o) { - id++; - return "key=" + o.getClass() + " " + id; - } - - public void addTransfairObject(String key, Object transfairObject) { - myHashMap.put(key, transfairObject); - } - - /** - * @param o - * The object which wants to pass some data - * @param transfairObject - * the object to send to the activity - * @return the key which can be used at .getObject(key) - */ - public String addTransfairObject(Object o, Object transfairObject) { - String key = getNextKey(o); - myHashMap.put(key, transfairObject); - return key; - } - - public static ActivityConnector getInstance() { - return myInstance; - } - - /** - * @param currentActivity - * The current activity - * @param ActivityClassToShow - * the .class object of the activity to start - * @param objectToPass - * the object to pass (null if nothing should be passed) - */ - @SuppressWarnings("unchecked") - public void startActivity(Activity currentActivity, - Class ActivityClassToShow, Object objectToPass) { - Intent intent = new Intent(currentActivity, ActivityClassToShow); - if (objectToPass != null) { - String key = addTransfairObject(currentActivity, objectToPass); - // The key to the object will be stored in the extras of the - // activity: - intent.putExtra(ActivityConnector.KEY_IDENTIFIER, key); - } - currentActivity.startActivity(intent); - } - - /** - * @param theNewActivity - * the newly created activity - * @return The object which was passed or null if nothing was passed - */ - public Object loadObjFromNewlyCreatedActivity(Activity theNewActivity) { - if (theNewActivity == null) - return null; - String key = theNewActivity.getIntent().getExtras() - .getString(KEY_IDENTIFIER); - Object o = getObj(key); - // TODO remove o from the hashmap now?: - // myHashMap.remove(key); - return o; - } - -}